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
108
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
67k
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
cf6f018ad42712605f9c5ca364adc02f0b6a2af3
28,546
cpp
C++
com/netfx/src/clr/fusion/tools/copy2gac/copy2gac.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/netfx/src/clr/fusion/tools/copy2gac/copy2gac.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/netfx/src/clr/fusion/tools/copy2gac/copy2gac.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== #include "common.h" #include <comdef.h> #include <tchar.h> //#include "initguid.h" #include <initguid.h> #include "copy2gac.h" #include "bindsink.h" TCHAR *CApp::c_szBakupDir = TEXT("bak\\"); CApp::CApp() : m_bDeleteAssemblies (FALSE), m_bAuto(FALSE), m_bRestore(FALSE), m_hFusionDll(NULL), m_pfnCreateAssemblyCache(NULL), m_bInstall(FALSE), m_bUninstall(FALSE), m_bQuiet(FALSE), m_bUseInstallRef(FALSE), m_hff(INVALID_HANDLE_VALUE) { *m_szAsmListFilename=0; *m_szCorPathOverride=0; *m_szInstallRefID=0; *m_szInstallRefDesc=0; m_bstrCorPath = ""; m_pCache = NULL; } CApp::~CApp() { if (m_pCache) SAFERELEASE(m_pCache); if (m_hFusionDll) FreeLibrary(m_hFusionDll); } void CApp::ErrorMessage( const TCHAR *format, ... ) { va_list arglist; TCHAR buf[1024]; va_start(arglist,format); wvnsprintf(buf,1024, format,arglist); va_end( arglist ); if (m_bQuiet) _tprintf( _T("Error: %s\n"), buf); else WszMessageBoxInternal( NULL, buf, TEXT("Copy2GAC Error:"), MB_OK); } BOOL CApp::ParseParameters( int argc, TCHAR* argv[]) { while ( --argc ) { if ( !lstrcmpi( argv[argc], TEXT("-d")) || !lstrcmpi( argv[argc], TEXT("/d")) ) { m_bDeleteAssemblies = TRUE; } else if ( !lstrcmpi( argv[argc], TEXT("/?")) || !lstrcmpi( argv[argc], TEXT("-?")) ) { return FALSE; } else if ( !lstrcmpi( argv[argc], TEXT("/r")) || !lstrcmpi( argv[argc], TEXT("-r")) ) { m_bRestore = TRUE; } else if ( !lstrcmpi( argv[argc], TEXT("/i")) || !lstrcmpi( argv[argc], TEXT("-i")) ) { m_bInstall = TRUE; } else if ( !lstrcmpi( argv[argc], TEXT("/q")) || !lstrcmpi( argv[argc], TEXT("-q")) ) { m_bQuiet = TRUE; } else if ( !lstrcmpi( argv[argc], TEXT("/u")) || !lstrcmpi( argv[argc], TEXT("-u")) ) { m_bUninstall = TRUE; } else if ( !_tcsncicmp( argv[argc], TEXT("/f:"), lstrlen(TEXT("/f:"))) || !_tcsncicmp( argv[argc], TEXT("-f:"),lstrlen(TEXT("-f:"))) ) { if ( lstrlen(argv[argc]) == lstrlen(TEXT("/f:")) ) { return FALSE; }else { lstrcpy(m_szAsmListFilename, argv[argc]+3); } } else if ( !_tcsncicmp( argv[argc], TEXT("/p:"), lstrlen(TEXT("/p:"))) || !_tcsncicmp( argv[argc], TEXT("-p:"),lstrlen(TEXT("-p:"))) ) { if ( lstrlen(argv[argc]) == lstrlen(TEXT("/p:")) ) { return FALSE; }else { lstrcpy(m_szCorPathOverride, argv[argc]+3); int len=lstrlen(m_szCorPathOverride); if (m_szCorPathOverride[len-1]!=_T('\\')) m_szCorPathOverride[len-1]=_T('\\'); } } else if ( !_tcsncicmp( argv[argc], TEXT("/ri:"), lstrlen(TEXT("/ri:"))) || !_tcsncicmp( argv[argc], TEXT("-ri:"),lstrlen(TEXT("-ri:"))) ) { if ( (lstrlen(argv[argc]) == lstrlen(TEXT("/ri:")) ) || (lstrlen(argv[argc]) >= MAX_PATH) ) { return FALSE; }else { lstrcpy(m_szInstallRefID, argv[argc]+4); } } else if ( !_tcsncicmp( argv[argc], TEXT("/rd:"), lstrlen(TEXT("/rd:"))) || !_tcsncicmp( argv[argc], TEXT("-rd:"),lstrlen(TEXT("-rd:"))) ) { if ( (lstrlen(argv[argc]) == lstrlen(TEXT("/rd:"))) || (lstrlen(argv[argc]) >= MAX_PATH) ) { return FALSE; }else { lstrcpy(m_szInstallRefDesc, argv[argc]+4); } } else if ( !lstrcmpi( argv[argc], TEXT("/a")) || !lstrcmpi( argv[argc], TEXT("-a")) ) { m_bAuto = TRUE; } } _tprintf(_T("\n")); if (!m_bInstall && !m_bUninstall) { _tprintf( _T("Must specify either /i or /u.\n")); return FALSE; } if (lstrlen(m_szInstallRefID) && !lstrlen(m_szInstallRefDesc) ) { _tprintf( _T("Missing /rd:InstallReferenceDescription.\n")); return FALSE; } if (!lstrlen(m_szInstallRefID) && lstrlen(m_szInstallRefDesc) ) { _tprintf( _T("Missing /ri:InstallReferenceID.\n")); return FALSE; } if (m_bAuto && *m_szAsmListFilename) { _tprintf( _T("Cannot use /a & /f together.\n")); return FALSE; } if (!m_bAuto && !*m_szAsmListFilename) { _tprintf( _T("Must specify either /a or /f.\n")); return FALSE; } if (m_bInstall && m_bUninstall) { _tprintf( _T("Cannot use /i & /u together.\n")); return FALSE; } if (m_bUninstall) { //ignore these during uninstall m_bRestore = FALSE; } if (m_bInstall) { //ignore these during install m_bDeleteAssemblies = FALSE; } return TRUE; } BOOL CApp::Initialize() { HMODULE hModEEShim = LoadLibrary(TEXT("mscoree.dll")); if (!hModEEShim) { _tprintf( _T("Error loading mscoree.dll\n") ); _tprintf( _T("Make sure you have COM+ installed\n") ); return FALSE; } typedef HRESULT (WINAPI *PFNGETCORSYSTEMDIRECTORY)(LPWSTR, DWORD, LPDWORD); PFNGETCORSYSTEMDIRECTORY pfnGetCorSystemDirectory = NULL; pfnGetCorSystemDirectory = (PFNGETCORSYSTEMDIRECTORY) GetProcAddress(hModEEShim, "GetCORSystemDirectory"); WCHAR wszCorPath[MAX_PATH]; *wszCorPath = 0; DWORD ccPath = MAX_PATH; if (!pfnGetCorSystemDirectory || FAILED(pfnGetCorSystemDirectory( wszCorPath, ccPath, &ccPath))) { _tprintf( _T("Error reading COM+ install location from mscoree.dll\n")); _tprintf( _T("Make sure COM+ is installed correctly\n")); } FreeLibrary(hModEEShim); if (!*wszCorPath) { return FALSE; } m_bstrCorPath = wszCorPath; TCHAR szFusionPath[MAX_PATH]; lstrcpy(szFusionPath, m_bstrCorPath); lstrcat(szFusionPath,TEXT("fusion.dll")); m_hFusionDll = LoadLibrary( szFusionPath ); if (!m_hFusionDll) { return FALSE; } m_pfnCreateAssemblyCache = (pfnCREATEASSEMBLYCACHE)GetProcAddress( m_hFusionDll, "CreateAssemblyCache"); if (!m_pfnCreateAssemblyCache) return FALSE; if ( FAILED(m_pfnCreateAssemblyCache(&m_pCache, 0))) return FALSE; m_pfnCreateAssemblyNameObject = (pfnCREATEASSEMBLYNAMEOBJECT)GetProcAddress( m_hFusionDll, "CreateAssemblyNameObject"); if (!m_pfnCreateAssemblyNameObject) return FALSE; m_pfnCreateApplicationContext = (pfnCREATEAPPLICATIONCONTEXT)GetProcAddress( m_hFusionDll, "CreateApplicationContext"); if (!m_pfnCreateAssemblyNameObject) return FALSE; m_pfnCopyPDBs = (pfnCOPYPDBS)GetProcAddress( m_hFusionDll, "CopyPDBs"); if (!m_pfnCopyPDBs) return FALSE; return TRUE; } HRESULT CApp::BindToObject( WCHAR *wszDisplayName, WCHAR *wszCodebase, IAssembly **ppAssembly ) { IAssemblyName *pAsmName = NULL; IAssemblyName *pAppName = NULL; IApplicationContext *pAppContext = NULL; IAssemblyName *pNameDef = NULL; CBindSink *pBindSink = NULL; DWORD dwFlags = 0; if (wszDisplayName) dwFlags = CANOF_PARSE_DISPLAY_NAME ; else dwFlags = 0; HRESULT hr = m_pfnCreateAssemblyNameObject( &pAppName, wszDisplayName, dwFlags , NULL); if (FAILED(hr) || !pAppName) { goto exitBind; } hr = m_pfnCreateApplicationContext( pAppName, &pAppContext ); if (FAILED(hr) || !pAppContext) { goto exitBind; } hr = m_pfnCreateAssemblyNameObject( &pAsmName, NULL, 0, NULL); if (FAILED(hr) || !pAsmName) { goto exitBind; } hr = pAppContext->Set(ACTAG_APP_BASE_URL, (WCHAR*)m_bstrCorPath, (lstrlenW(m_bstrCorPath)+1)*sizeof(WCHAR),0); if (FAILED(hr)) { goto exitBind; } hr = CreateBindSink(&pBindSink, (LPVOID*)ppAssembly); if (FAILED(hr)) goto exitBind; hr = pAsmName->BindToObject( __uuidof(IAssembly), pBindSink, pAppContext, wszCodebase, 0, NULL,0, (PVOID*)ppAssembly ); if (FAILED(hr) || !ppAssembly) { //_tprintf(_T("Failed to bind\n")); if (hr == E_PENDING) { WaitForSingleObject(pBindSink->_hEvent, INFINITE); hr = pBindSink->_hr; }else { goto exitBind; } } else { //_tprintf(_T("Succeeded binding\n")); } exitBind: SAFE_RELEASE(pBindSink); SAFE_RELEASE(pAsmName); SAFE_RELEASE(pAppName); SAFE_RELEASE(pAppContext); SAFE_RELEASE(pNameDef); return hr; } WCHAR* CApp::GetDisplayName( IAssembly *pAssembly ) { WCHAR *wszDisplayName = NULL; IAssemblyName *pNameDef = NULL; assert(pAssembly); HRESULT hr = pAssembly->GetAssemblyNameDef(&pNameDef); if (FAILED(hr)) { goto Exit; } DWORD dwChars = 0; hr = pNameDef->GetDisplayName( NULL, &dwChars,ASM_DISPLAYF_VERSION | ASM_DISPLAYF_CULTURE | ASM_DISPLAYF_PUBLIC_KEY_TOKEN | ASM_DISPLAYF_CUSTOM ); if (FAILED(hr)) { goto Exit; } wszDisplayName = new WCHAR[dwChars]; if (!wszDisplayName) { goto Exit; } hr = pNameDef->GetDisplayName( wszDisplayName, &dwChars, ASM_DISPLAYF_VERSION | ASM_DISPLAYF_CULTURE | ASM_DISPLAYF_PUBLIC_KEY_TOKEN | ASM_DISPLAYF_CUSTOM ); if (FAILED(hr)) { goto Exit; } Exit: if(FAILED(hr) && wszDisplayName) { delete [] wszDisplayName; wszDisplayName = NULL; } if (pNameDef) { pNameDef->Release(); } return wszDisplayName; } HRESULT CApp::UninstallAssembly( WCHAR *wszCodebase ) { IAssembly *pAssembly = NULL; HRESULT hr = BindToObject(NULL, wszCodebase, &pAssembly ); if (FAILED(hr)) { return hr; } if (!pAssembly) return E_FAIL; if (pAssembly) { WCHAR *wszDisplayName = GetDisplayName( pAssembly ); if (wszDisplayName) { _tprintf(_T("Uninstalling %s\n"), wszDisplayName); DWORD dwDisp; HRESULT hr = m_pCache->UninstallAssembly(0, wszDisplayName, m_bUseInstallRef?&m_installRef:NULL, &dwDisp); if (FAILED(hr)) { _tprintf(_T("UninstallAssembly failed with hr = %X\n"), hr ); } delete [] wszDisplayName; } pAssembly->Release(); } return S_OK; } /* BOOL CApp::RestoreAssembly( _bstr_t &bstrFile ) { _bstr_t bstrFilename = m_bstrCorPath; bstrFilename += "bak\\"; bstrFilename += bstrFile; //_tprintf(_T("Restoring %s\n"), (TCHAR*)bstrFilename); _bstr_t bstrDestFilename = m_bstrCorPath; bstrDestFilename += bstrFile; if (!CopyFile( bstrFilename, bstrDestFilename, FALSE)) { _tprintf( _T("Failed to copy %s to corpath.\n"), (TCHAR*)bstrFile ); return FALSE; } m_dwAssembliesMigrated++; if (!UninstallAssembly( bstrFilename )) { //nothing } if (!DeleteFile( bstrFilename )) { _tprintf( _T("Failed to delete %s\n"), (TCHAR*)bstrFilename); } return TRUE; } */ BOOL CApp::GetNextFilenameAuto( WCHAR *wszFilename) { //if we havent got a FF handle yet, do it now if (m_hff == INVALID_HANDLE_VALUE) { bstr_t bstrSearchPath = m_bstrCorPath; bstrSearchPath += "*.dll"; m_hff = FindFirstFile( bstrSearchPath, &m_ffData); if (m_hff == INVALID_HANDLE_VALUE) { return FALSE; } } else { if (!FindNextFile( m_hff, &m_ffData )) { FindClose(m_hff); m_hff=INVALID_HANDLE_VALUE; return FALSE; } } _bstr_t bstrFilename( m_ffData.cFileName ); //_tprintf(_T("Found %s\n"),(TCHAR*)bstrFilename); lstrcpyW( wszFilename, bstrFilename); return TRUE; } BOOL CApp::GetNextFilenameFromFilelist( WCHAR *wszFilename) { if (m_hff==INVALID_HANDLE_VALUE) { m_hff = CreateFile( m_szAsmListFilename,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL); if (m_hff == INVALID_HANDLE_VALUE) { _tprintf( _T("Could not open %s\n"), m_szAsmListFilename); return FALSE; } } char szFilename[MAX_PATH]; char *tmp = szFilename; DWORD dwBytesRead; *tmp=0; while (1) { if (tmp == szFilename + MAX_PATH) { _tprintf( _T("Invalid assembly filename in input file.\n") ); CloseHandle( m_hff ); m_hff = INVALID_HANDLE_VALUE; return FALSE; } BOOL bRes = ReadFile( m_hff, tmp, 1, &dwBytesRead, NULL); if (!bRes || !dwBytesRead) { *tmp=0; break; } if (*tmp == '\n') { *tmp = 0; break; }else if ( *tmp != '\r') { tmp++; } } if (*szFilename) { _bstr_t bstrFilename(szFilename); lstrcpyW(wszFilename, bstrFilename); return TRUE; } else { CloseHandle( m_hff ); m_hff = INVALID_HANDLE_VALUE; return FALSE; } } BOOL CApp::GetNextFilename( WCHAR *wszFilename ) { if (m_bAuto) return GetNextFilenameAuto(wszFilename); else return GetNextFilenameFromFilelist(wszFilename); } /* BOOL CApp::Restore() { HANDLE hff; WIN32_FIND_DATA ffData; bstr_t bstrSearchPath = m_bstrCorPath; bstrSearchPath += "bak\\*.dll"; hff = FindFirstFile( bstrSearchPath, &ffData); if (hff == INVALID_HANDLE_VALUE) { return FALSE; } do { _bstr_t bstrFilename(ffData.cFileName); _tprintf(_T("Restoring %s\n"),(TCHAR*)bstrFilename); RestoreAssembly( bstrFilename ); }while (FindNextFile( hff, &ffData )); FindClose(hff); return TRUE; } */ /* BOOL CApp::AutoMigrate() { HANDLE hff; WIN32_FIND_DATA ffData; TCHAR szSearchPath[MAX_PATH]; lstrcpy( szSearchPath, m_bstrCorPath); lstrcat( szSearchPath,TEXT("*.dll")); hff = FindFirstFile( szSearchPath, &ffData); if (hff == INVALID_HANDLE_VALUE) { return FALSE; } do { _bstr_t bstrFilename(ffData.cFileName); //_tprintf(_T("trying %s\n"),(TCHAR*)bstrFilename); int i=-1; while ( AsmExceptions[++i] ) { if (!lstrcmpi(AsmExceptions[i], bstrFilename)) break; } if (!AsmExceptions[i]) //that means we are at the end of the array (null) MigrateAssembly( bstrFilename ); }while (FindNextFile( hff, &ffData )); FindClose(hff); return TRUE; } */ HRESULT CApp::Install() { WCHAR wszFilename[MAX_PATH]; HRESULT hrRet = S_OK; int i=0; while (GetNextFilename(wszFilename)) { _bstr_t bstrFilename(wszFilename); //_tprintf( _T("Installing %s\n"), (TCHAR*)bstrFilename); HRESULT hr = MigrateAssembly( bstrFilename ); if (FAILED(hr)) { if (!m_bAuto) ErrorMessage( TEXT("Failed to Install %s.\n hr = 0x%8X"), (TCHAR*)bstrFilename, hr); hrRet = hr; } else { i++; } } _tprintf( TEXT("Installed %d Assemblies into GAC.\n"), i); // Call genpubcfg if available if (GetFileAttributesA("genpubcfg.exe") != -1) { CHAR szCmdLine[MAX_PATH]; CHAR szAsmListFilename[MAX_PATH]; BOOL bRet; STARTUPINFOA si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); si.cb = sizeof(si); bRet = WideCharToMultiByte(CP_ACP, 0, m_szAsmListFilename, -1, szAsmListFilename, sizeof(szAsmListFilename), NULL, NULL); if (bRet) { wnsprintfA(szCmdLine, MAX_PATH, "genpubcfg -f:%s -d:%s", szAsmListFilename, (CHAR*)m_bstrCorPath); if (!CreateProcessA(NULL, szCmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) { _tprintf(TEXT("Error spawning genpubcfg.exe\n")); } WaitForSingleObject(pi.hProcess, INFINITE); } else { _tprintf(TEXT("Fatal error calling WideCharToMultiByte\n")); } } return hrRet; } HRESULT CApp::Uninstall() { WCHAR wszFilename[MAX_PATH]; HRESULT hrRet = S_OK; int i=0; while (GetNextFilename(wszFilename)) { _bstr_t bstrFilename = m_bstrCorPath; bstrFilename += wszFilename; HRESULT hr = UninstallAssembly( bstrFilename ); if (FAILED(hr)) { if (!m_bAuto) ErrorMessage( TEXT("Failed to Uninstall %s.\n hr = 0x%8X"), (TCHAR*)bstrFilename, hr); hrRet = hr; } else { i++; } } _tprintf( TEXT("Uninstalled %d Assemblies from GAC.\n"), i); if (GetFileAttributesA("genpubcfg.exe") != -1) { CHAR szCmdLine[MAX_PATH]; STARTUPINFOA si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); si.cb = sizeof(si); wnsprintfA(szCmdLine, MAX_PATH, "genpubcfg -u"); if (!CreateProcessA(NULL, szCmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) { _tprintf(TEXT("Error spawning genpubcfg.exe\n")); } WaitForSingleObject(pi.hProcess, INFINITE); } return hrRet; } HRESULT CApp::MigrateAssembly( TCHAR *szFile) { _bstr_t bstrCommand; _bstr_t bstrDestPath; //set up source path/command bstrCommand = m_bstrCorPath; bstrCommand += szFile; //setup dest path bstrDestPath = m_bstrCorPath; bstrDestPath += c_szBakupDir; bstrDestPath += szFile ; TCHAR *pszSourcePath = ((TCHAR*)bstrCommand); if ( m_bDeleteAssemblies ) { BOOL bRes = CopyFile( pszSourcePath, bstrDestPath, FALSE); if (!bRes) { _tprintf( _T("Failed to backup %s. Skipping installation.\n"), pszSourcePath ); return HRESULT_FROM_WIN32(GetLastError()); } } HRESULT hr = m_pCache->InstallAssembly(IASSEMBLYCACHE_INSTALL_FLAG_REFRESH, (WCHAR*)bstrCommand, m_bUseInstallRef? &m_installRef : NULL); if (FAILED(hr)) { if ( hr != HRESULT_FROM_WIN32(ERROR_BAD_FORMAT) && hr != 0x80131042 && m_bAuto) _tprintf( _T(" Failed to install %s (hr = 0x%X)\n"), pszSourcePath,hr); //delete the backup file since we failed DeleteFile( bstrDestPath ); }else { _tprintf( _T("Installed %s\n"), szFile); if (m_bDeleteAssemblies) { BOOL bRes = DeleteFile( pszSourcePath ); if (!bRes) { _tprintf( _T(" Warning: Failed to delete %s\n"), pszSourcePath ); //hr = HRESULT_FROM_WIN32(GetLastError()); } } } return hr; } /* BOOL CApp::Migrate() { HANDLE hFile = CreateFile( m_szAsmListFilename,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL); if (hFile == INVALID_HANDLE_VALUE) { printf("Could not open %s\n", m_szAsmListFilename); return FALSE; } char szFilename[MAX_PATH]; char *tmp = szFilename; DWORD dwBytesRead; while (1) { BOOL bRes = ReadFile( hFile, tmp, 1, &dwBytesRead, NULL); if (!bRes || !dwBytesRead) { if (*tmp) *tmp = '\n'; else break; } if (*tmp=='\r') { } else if (*tmp=='\n') { *tmp = 0; //printf("Filename:%s\n",szFilename); tmp=szFilename; MigrateAssembly( szFilename ); *tmp = 0; }else { tmp++; } } CloseHandle( hFile); return TRUE; } */ int CApp::Main(int argc, TCHAR* argv[]) { if ((argc==1) || !ParseParameters( argc, argv )) { _tprintf( TEXT("\n")); _tprintf( TEXT("Use: copy2gac [action] [input] [options]\n") ); _tprintf( TEXT("Action:\n") ); _tprintf( TEXT(" /i : Install to GAC\n") ); _tprintf( TEXT(" /u : Uninstall from GAC\n") ); _tprintf( TEXT("Input:\n") ); _tprintf( TEXT(" /f:inputfile.txt : Reads a list of files from inputfile.txt\n") ); _tprintf( TEXT(" /a : All dlls in directory\n") ); _tprintf( TEXT("Options:\n") ); _tprintf( TEXT(" /ri:ReferenceID : Install reference ID\n") ); _tprintf( TEXT(" /rd:ReferenceDescription : Install reference description\n") ); _tprintf( TEXT(" /d : Deletes the assemblies after they are installed") ); _tprintf( TEXT("\n and backs them up in the \"bak\" subdir of your corpath.") ); _tprintf( TEXT("\n (Only valid for Install)\n") ); _tprintf( TEXT(" /p:NewPath : Use NewPath instead of Corpath\n") ); return E_INVALIDARG; } if ( !Initialize() ) return E_FAIL; //BUGBUG: return better error code if (*m_szCorPathOverride) m_bstrCorPath=m_szCorPathOverride; _tprintf( TEXT("%sPath: %s\n"),*m_szCorPathOverride? _T("Source"): _T("Cor"), (TCHAR*)m_bstrCorPath ); if (m_bDeleteAssemblies) { TCHAR szBackupDir[MAX_PATH]; lstrcpy(szBackupDir, m_bstrCorPath); lstrcat(szBackupDir, c_szBakupDir ); if (!CreateDirectory( szBackupDir, NULL)) { return HRESULT_FROM_WIN32(GetLastError()); } } //initialize the Fusion Install Reference m_installRef.cbSize = sizeof (FUSION_INSTALL_REFERENCE); m_installRef.dwFlags = 0; m_installRef.guidScheme = FUSION_REFCOUNT_OPAQUE_STRING_GUID; m_installRef.szIdentifier = m_szInstallRefID; m_installRef.szNonCannonicalData = m_szInstallRefDesc; if (lstrlen(m_szInstallRefID) && lstrlen(m_szInstallRefDesc)) m_bUseInstallRef = TRUE; if (m_bInstall) { return Install(); } else { return Uninstall(); } return S_OK; } int __cdecl _tmain(int argc, TCHAR* argv[]) { CApp copy2gac; #ifndef USE_FUSWRAPPERS OnUnicodeSystem(); #endif return copy2gac.Main(argc,argv); }
31.753059
146
0.452323
npocmaka
cf708df51fb5083c3c62162788598581a3e4ff18
3,336
cpp
C++
tools/client_session/client_session.cpp
smallsunsun1/async_lib
d1e88aa73a1084a9549f884241266c8bdf568411
[ "Apache-2.0", "MIT" ]
null
null
null
tools/client_session/client_session.cpp
smallsunsun1/async_lib
d1e88aa73a1084a9549f884241266c8bdf568411
[ "Apache-2.0", "MIT" ]
null
null
null
tools/client_session/client_session.cpp
smallsunsun1/async_lib
d1e88aa73a1084a9549f884241266c8bdf568411
[ "Apache-2.0", "MIT" ]
null
null
null
#include <glog/logging.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/text_format.h> #include <grpc++/grpc++.h> #include <grpc/grpc.h> #include <stdio.h> #include <stdlib.h> #include <fstream> #include <iostream> #include <string> #include <vector> #include "absl/flags/flag.h" #include "absl/flags/parse.h" #include "async/context/host_context.h" #include "tools/client_session/sample_client.h" #include "tools/proto/config.pb.h" ABSL_FLAG(std::string, config_file, "tools/data/config.pb.txt", "config filename for client session"); namespace sss { namespace async { class ClientSession { public: explicit ClientSession(const SessionConfig& config); void RunCalc(const Request& request); private: void RunStreamCalc(const Request& request); void RunUnaryCalc(const Request& request); SessionConfig config_; std::unique_ptr<HostContext> context_; std::vector<std::string> worker_addresses_; std::vector<AsyncUnaryClient> unary_clients_; std::vector<AsyncStreamClient> stream_clients_; std::atomic<uint32_t> index_; uint32_t total_clients_; }; void ClientSession::RunStreamCalc(const Request& request) { uint32_t index = index_.fetch_add(1) % total_clients_; stream_clients_[index].StreamRemoteCall(request); } void ClientSession::RunUnaryCalc(const Request& request) { uint32_t index = index_.fetch_add(1) % total_clients_; unary_clients_[index].AsyncRemoteCall(request); } void ClientSession::RunCalc(const Request& request) { if (config_.client_config().type() == ClientConfig::kUnary) { RunUnaryCalc(request); } else if (config_.client_config().type() == ClientConfig::kStream) { RunStreamCalc(request); } } ClientSession::ClientSession(const SessionConfig& config) : config_(config) { grpc::ChannelArguments arguments; arguments.SetLoadBalancingPolicyName("grpclb"); context_ = CreateCustomHostContext( config_.context_config().non_block_worker_threads(), config_.context_config().block_worker_threads()); for (const std::string& address : config_.worker_addresses()) { worker_addresses_.push_back(address); if (config_.client_config().type() == ClientConfig::kUnary) { LOG(INFO) << "Build Unary Clients"; unary_clients_.emplace_back(grpc::CreateCustomChannel( address, grpc::InsecureChannelCredentials(), arguments)); } else if (config_.client_config().type() == ClientConfig::kStream) { LOG(INFO) << "Build Stream Clients"; stream_clients_.emplace_back(grpc::CreateCustomChannel( address, grpc::InsecureChannelCredentials(), arguments)); } } total_clients_ = config_.worker_addresses().size(); } } // namespace async } // namespace sss int main(int argc, char* argv[]) { absl::ParseCommandLine(argc, argv); std::string config_file = absl::GetFlag(FLAGS_config_file); std::ifstream ifs(config_file); std::istreambuf_iterator<char> begin(ifs); std::istreambuf_iterator<char> end; std::string input(begin, end); sss::async::SessionConfig config; google::protobuf::TextFormat::ParseFromString(input, &config); auto session = std::make_unique<sss::async::ClientSession>(config); sss::async::Request request; request.set_type("hello world"); for (int i = 0; i < 2; ++i) { session->RunCalc(request); } return 0; }
32.38835
77
0.731715
smallsunsun1
cf71987536faba6b3dffd0ab446b58c52cd5bbd1
244
cpp
C++
contests/UnBalloon/2-maratona/c-complexo-demais/complexo_demais.cpp
XatubaPox/programming-competitive
f5fe512266de7109f45259a82a74035ed19d9474
[ "MIT" ]
1
2022-01-25T13:11:45.000Z
2022-01-25T13:11:45.000Z
contests/UnBalloon/2-maratona/c-complexo-demais/complexo_demais.cpp
XatubaPox/programming-competitive
f5fe512266de7109f45259a82a74035ed19d9474
[ "MIT" ]
null
null
null
contests/UnBalloon/2-maratona/c-complexo-demais/complexo_demais.cpp
XatubaPox/programming-competitive
f5fe512266de7109f45259a82a74035ed19d9474
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main (){ int a, b, c, d, com1, com2; cin >> a >> b >> c >> d; com1 = (a * c) - (b * d); com2 = (a * d) + (b * c); printf("(%i) + (%ii)\n", com1, com2); return 0; }
14.352941
41
0.422131
XatubaPox
cf719b54b3cde4c45c34365b7d2f54cf098d449e
13,322
cpp
C++
platform/javascript/export/export.cpp
xsellier/godot
0512868e0d6236c42ac3cd3efbf8604b979b2f62
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
2
2019-08-19T19:28:25.000Z
2020-12-08T08:21:14.000Z
platform/javascript/export/export.cpp
xsellier/godot
0512868e0d6236c42ac3cd3efbf8604b979b2f62
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
platform/javascript/export/export.cpp
xsellier/godot
0512868e0d6236c42ac3cd3efbf8604b979b2f62
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
/*************************************************************************/ /* export.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "export.h" #include "editor/editor_import_export.h" #include "editor/editor_node.h" #include "editor/editor_settings.h" #include "globals.h" #include "io/marshalls.h" #include "io/zip_io.h" #include "os/file_access.h" #include "os/os.h" #include "platform/javascript/logo.gen.h" #include "string.h" #include "version.h" class EditorExportPlatformJavaScript : public EditorExportPlatform { OBJ_TYPE(EditorExportPlatformJavaScript, EditorExportPlatform); String custom_release_package; String custom_debug_package; enum PackMode { PACK_SINGLE_FILE, PACK_MULTIPLE_FILES }; void _fix_html(Vector<uint8_t> &p_html, const String &p_name, bool p_debug); PackMode pack_mode; bool show_run; int max_memory; int version_code; String html_title; String html_head_include; String html_font_family; String html_style_include; bool html_controls_enabled; Ref<ImageTexture> logo; protected: bool _set(const StringName &p_name, const Variant &p_value); bool _get(const StringName &p_name, Variant &r_ret) const; void _get_property_list(List<PropertyInfo> *p_list) const; public: virtual String get_name() const { return "HTML5"; } virtual ImageCompression get_image_compression() const { return IMAGE_COMPRESSION_BC; } virtual Ref<Texture> get_logo() const { return logo; } virtual bool poll_devices() { return show_run ? true : false; } virtual int get_device_count() const { return show_run ? 1 : 0; }; virtual String get_device_name(int p_device) const { return "Run in Browser"; } virtual String get_device_info(int p_device) const { return "Run exported HTML in the system's default browser."; } virtual Error run(int p_device, int p_flags = 0); virtual bool requires_password(bool p_debug) const { return false; } virtual String get_binary_extension() const { return "html"; } virtual Error export_project(const String &p_path, bool p_debug, int p_flags = 0); virtual bool can_export(String *r_error = NULL) const; EditorExportPlatformJavaScript(); ~EditorExportPlatformJavaScript(); }; bool EditorExportPlatformJavaScript::_set(const StringName &p_name, const Variant &p_value) { String n = p_name; if (n == "custom_package/debug") custom_debug_package = p_value; else if (n == "custom_package/release") custom_release_package = p_value; else if (n == "browser/enable_run") show_run = p_value; else if (n == "options/memory_size") max_memory = p_value; else if (n == "html/title") html_title = p_value; else if (n == "html/head_include") html_head_include = p_value; else if (n == "html/font_family") html_font_family = p_value; else if (n == "html/style_include") html_style_include = p_value; else if (n == "html/controls_enabled") html_controls_enabled = p_value; else return false; return true; } bool EditorExportPlatformJavaScript::_get(const StringName &p_name, Variant &r_ret) const { String n = p_name; if (n == "custom_package/debug") r_ret = custom_debug_package; else if (n == "custom_package/release") r_ret = custom_release_package; else if (n == "browser/enable_run") r_ret = show_run; else if (n == "options/memory_size") r_ret = max_memory; else if (n == "html/title") r_ret = html_title; else if (n == "html/head_include") r_ret = html_head_include; else if (n == "html/font_family") r_ret = html_font_family; else if (n == "html/style_include") r_ret = html_style_include; else if (n == "html/controls_enabled") r_ret = html_controls_enabled; else return false; return true; } void EditorExportPlatformJavaScript::_get_property_list(List<PropertyInfo> *p_list) const { p_list->push_back(PropertyInfo(Variant::STRING, "custom_package/debug", PROPERTY_HINT_GLOBAL_FILE, "zip")); p_list->push_back(PropertyInfo(Variant::STRING, "custom_package/release", PROPERTY_HINT_GLOBAL_FILE, "zip")); p_list->push_back(PropertyInfo(Variant::INT, "options/memory_size", PROPERTY_HINT_ENUM, "32mb,64mb,128mb,256mb,512mb,1024mb")); p_list->push_back(PropertyInfo(Variant::BOOL, "browser/enable_run")); p_list->push_back(PropertyInfo(Variant::STRING, "html/title")); p_list->push_back(PropertyInfo(Variant::STRING, "html/head_include", PROPERTY_HINT_MULTILINE_TEXT)); p_list->push_back(PropertyInfo(Variant::STRING, "html/font_family")); p_list->push_back(PropertyInfo(Variant::STRING, "html/style_include", PROPERTY_HINT_MULTILINE_TEXT)); p_list->push_back(PropertyInfo(Variant::BOOL, "html/controls_enabled")); //p_list->push_back( PropertyInfo( Variant::INT, "resources/pack_mode", PROPERTY_HINT_ENUM,"Copy,Single Exec.,Pack (.pck),Bundles (Optical)")); } void EditorExportPlatformJavaScript::_fix_html(Vector<uint8_t> &p_html, const String &p_name, bool p_debug) { String str; String strnew; str.parse_utf8((const char *)p_html.ptr(), p_html.size()); Vector<String> lines = str.split("\n"); for (int i = 0; i < lines.size(); i++) { String current_line = lines[i]; current_line = current_line.replace("$GODOT_TMEM", itos((1 << (max_memory + 5)) * 1024 * 1024)); current_line = current_line.replace("$GODOT_FS", p_name + "fs.js"); current_line = current_line.replace("$GODOT_MEM", p_name + ".mem"); current_line = current_line.replace("$GODOT_JS", p_name + ".js"); current_line = current_line.replace("$GODOT_ASM", p_name + ".asm.js"); current_line = current_line.replace("$GODOT_CANVAS_WIDTH", Globals::get_singleton()->get("display/width")); current_line = current_line.replace("$GODOT_CANVAS_HEIGHT", Globals::get_singleton()->get("display/height")); current_line = current_line.replace("$GODOT_HEAD_TITLE", !html_title.empty() ? html_title : (String)Globals::get_singleton()->get("application/name")); current_line = current_line.replace("$GODOT_HEAD_INCLUDE", html_head_include); current_line = current_line.replace("$GODOT_STYLE_FONT_FAMILY", html_font_family); current_line = current_line.replace("$GODOT_STYLE_INCLUDE", html_style_include); current_line = current_line.replace("$GODOT_CONTROLS_ENABLED", html_controls_enabled ? "true" : "false"); current_line = current_line.replace("$GODOT_DEBUG_ENABLED", p_debug ? "true" : "false"); strnew += current_line + "\n"; } CharString cs = strnew.utf8(); p_html.resize(cs.length()); for (int i = 9; i < cs.length(); i++) { p_html[i] = cs[i]; } } static void _fix_files(Vector<uint8_t> &html, uint64_t p_data_size) { String str; String strnew; str.parse_utf8((const char *)html.ptr(), html.size()); Vector<String> lines = str.split("\n"); for (int i = 0; i < lines.size(); i++) { if (lines[i].find("$DPLEN") != -1) { strnew += lines[i].replace("$DPLEN", itos(p_data_size)); } else { strnew += lines[i] + "\n"; } } CharString cs = strnew.utf8(); html.resize(cs.length()); for (int i = 9; i < cs.length(); i++) { html[i] = cs[i]; } } struct JSExportData { EditorProgress *ep; FileAccess *f; }; Error EditorExportPlatformJavaScript::export_project(const String &p_path, bool p_debug, int p_flags) { String src_template; EditorProgress ep("export", "Exporting for javascript", 104); if (p_debug) src_template = custom_debug_package; else src_template = custom_release_package; if (src_template == "") { String err; if (p_debug) { src_template = find_export_template("javascript_debug.zip", &err); } else { src_template = find_export_template("javascript_release.zip", &err); } if (src_template == "") { EditorNode::add_io_error(err); return ERR_FILE_NOT_FOUND; } } FileAccess *src_f = NULL; zlib_filefunc_def io = zipio_create_io_from_file(&src_f); ep.step("Exporting to HTML5", 0); ep.step("Finding Files..", 1); FileAccess *f = FileAccess::open(p_path.get_base_dir() + "/data.pck", FileAccess::WRITE); if (!f) { EditorNode::add_io_error("Could not create file for writing:\n" + p_path.basename() + "_files.js"); return ERR_FILE_CANT_WRITE; } Error err = save_pack(f); size_t len = f->get_len(); memdelete(f); if (err) return err; unzFile pkg = unzOpen2(src_template.utf8().get_data(), &io); if (!pkg) { EditorNode::add_io_error("Could not find template HTML5 to export:\n" + src_template); return ERR_FILE_NOT_FOUND; } ERR_FAIL_COND_V(!pkg, ERR_CANT_OPEN); int ret = unzGoToFirstFile(pkg); while (ret == UNZ_OK) { //get filename unz_file_info info; char fname[16384]; ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0); String file = fname; Vector<uint8_t> data; data.resize(info.uncompressed_size); //read unzOpenCurrentFile(pkg); unzReadCurrentFile(pkg, data.ptr(), data.size()); unzCloseCurrentFile(pkg); //write if (file == "godot.html") { _fix_html(data, p_path.get_file().basename(), p_debug); file = p_path.get_file(); } if (file == "godotfs.js") { _fix_files(data, len); file = p_path.get_file().basename() + "fs.js"; } if (file == "godot.js") { //_fix_godot(data); file = p_path.get_file().basename() + ".js"; } if (file == "godot.asm.js") { file = p_path.get_file().basename() + ".asm.js"; } if (file == "godot.mem") { //_fix_godot(data); file = p_path.get_file().basename() + ".mem"; } String dst = p_path.get_base_dir().plus_file(file); FileAccess *f = FileAccess::open(dst, FileAccess::WRITE); if (!f) { EditorNode::add_io_error("Could not create file for writing:\n" + dst); unzClose(pkg); return ERR_FILE_CANT_WRITE; } f->store_buffer(data.ptr(), data.size()); memdelete(f); ret = unzGoToNextFile(pkg); } return OK; } Error EditorExportPlatformJavaScript::run(int p_device, int p_flags) { String path = EditorSettings::get_singleton()->get_settings_path() + "/tmp/tmp_export.html"; Error err = export_project(path, true, p_flags); if (err) return err; OS::get_singleton()->shell_open(path); return OK; } EditorExportPlatformJavaScript::EditorExportPlatformJavaScript() { show_run = false; Image img(_javascript_logo); logo = Ref<ImageTexture>(memnew(ImageTexture)); logo->create_from_image(img); max_memory = 3; html_title = ""; html_font_family = "arial,sans-serif"; html_controls_enabled = true; pack_mode = PACK_SINGLE_FILE; } bool EditorExportPlatformJavaScript::can_export(String *r_error) const { bool valid = true; String err; if (!exists_export_template("javascript_debug.zip") || !exists_export_template("javascript_release.zip")) { valid = false; err += "No export templates found.\nDownload and install export templates.\n"; } if (custom_debug_package != "" && !FileAccess::exists(custom_debug_package)) { valid = false; err += "Custom debug package not found.\n"; } if (custom_release_package != "" && !FileAccess::exists(custom_release_package)) { valid = false; err += "Custom release package not found.\n"; } if (r_error) *r_error = err; return valid; } EditorExportPlatformJavaScript::~EditorExportPlatformJavaScript() { } void register_javascript_exporter() { Ref<EditorExportPlatformJavaScript> exporter = Ref<EditorExportPlatformJavaScript>(memnew(EditorExportPlatformJavaScript)); EditorImportExport::get_singleton()->add_export_platform(exporter); }
33.305
153
0.673998
xsellier
cf779711db3d667c6089abce10543466f82a9d1a
943
cc
C++
solutions/leetcode/unique-paths-ii/dp.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
4
2020-11-07T14:38:02.000Z
2022-01-03T19:02:36.000Z
solutions/leetcode/unique-paths-ii/dp.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
1
2019-04-17T06:55:14.000Z
2019-04-17T06:55:14.000Z
solutions/leetcode/unique-paths-ii/dp.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
null
null
null
#include <vector> int uniquePathsWithObstacles(std::vector<std::vector<int>> &obstacleGrid) { if (obstacleGrid.at(0).at(0)) return 0; const int M = obstacleGrid.at(0).size(); const int N = obstacleGrid.size(); // Convert to a 2D vector of unsigned ints // to avoid signed integer overflows std::vector<std::vector<unsigned int>> num(N, std::vector<unsigned int>(M, -1)); num.at(0).at(0) = 1; for (int i = 1; i < M; i++) { num.at(0).at(i) = obstacleGrid.at(0).at(i) ? 0 : num.at(0).at(i - 1); } for (int i = 1; i < N; i++) { num.at(i).at(0) = obstacleGrid.at(i).at(0) ? 0 : num.at(i - 1).at(0); } for (int y = 1; y < N; y++) { for (int x = 1; x < M; x++) { num.at(y).at(x) = obstacleGrid.at(y).at(x) ? 0 : num.at(y).at(x - 1) + num.at(y - 1).at(x); } } return num.back().back(); }
26.942857
79
0.492047
zwliew
cf79c6deb54ab67715ce12a04a4e39c542afc31f
17,493
cc
C++
src/oxli/assembler.cc
sadeepdarshana/khmer
bee54c4f579611d970c59367323d31d3545cafa6
[ "CNRI-Python" ]
558
2015-05-22T15:03:21.000Z
2022-03-23T04:49:17.000Z
src/oxli/assembler.cc
sadeepdarshana/khmer
bee54c4f579611d970c59367323d31d3545cafa6
[ "CNRI-Python" ]
1,057
2015-05-14T20:27:04.000Z
2022-03-08T09:29:36.000Z
src/oxli/assembler.cc
sadeepdarshana/khmer
bee54c4f579611d970c59367323d31d3545cafa6
[ "CNRI-Python" ]
193
2015-05-18T10:13:34.000Z
2021-12-10T11:58:01.000Z
/* This file is part of khmer, https://github.com/dib-lab/khmer/, and is Copyright (C) 2015-2016, The Regents of the University of California. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Michigan State University 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. LICENSE (END) Contact: khmer-project@idyll.org */ #include "oxli/assembler.hh" #include <algorithm> #include <iostream> using namespace std; namespace oxli { /******************************** * Simple Linear Assembly ********************************/ LinearAssembler::LinearAssembler(const Hashgraph * ht) : graph(ht), _ksize(ht->ksize()) { } // Starting from the given seed k-mer, assemble the maximal linear path in // both directions. std::string LinearAssembler::assemble(const Kmer seed_kmer, const Hashgraph * stop_bf) const { if (graph->get_count(seed_kmer) == 0) { // If the seed k-mer is not in the de Bruijn graph, stop trying to make // something happen. It's not going to happen! return ""; } std::list<KmerFilter> node_filters; if (stop_bf) { node_filters.push_back(get_stop_bf_filter(stop_bf)); } std::shared_ptr<SeenSet> visited = std::make_shared<SeenSet>(); AssemblerTraverser<TRAVERSAL_RIGHT> rcursor(graph, seed_kmer, node_filters, visited); AssemblerTraverser<TRAVERSAL_LEFT> lcursor(graph, seed_kmer, node_filters, visited); std::string right_contig = _assemble_directed<TRAVERSAL_RIGHT>(rcursor); std::string left_contig = _assemble_directed<TRAVERSAL_LEFT>(lcursor); #if DEBUG_ASSEMBLY std::cout << "Left: " << left_contig << std::endl; std::cout << "Right: " << right_contig << std::endl; #endif right_contig = right_contig.substr(_ksize); return left_contig + right_contig; } std::string LinearAssembler::assemble_right(const Kmer seed_kmer, const Hashgraph * stop_bf) const { std::list<KmerFilter> node_filters; if (stop_bf) { node_filters.push_back(get_stop_bf_filter(stop_bf)); } AssemblerTraverser<TRAVERSAL_RIGHT> cursor(graph, seed_kmer, node_filters); return _assemble_directed<TRAVERSAL_RIGHT>(cursor); } std::string LinearAssembler::assemble_left(const Kmer seed_kmer, const Hashgraph * stop_bf) const { std::list<KmerFilter> node_filters; if (stop_bf) { node_filters.push_back(get_stop_bf_filter(stop_bf)); } AssemblerTraverser<TRAVERSAL_LEFT> cursor(graph, seed_kmer, node_filters); return _assemble_directed<TRAVERSAL_LEFT>(cursor); } template <> std::string LinearAssembler:: _assemble_directed<TRAVERSAL_LEFT>(AssemblerTraverser<TRAVERSAL_LEFT>& cursor) const { std::string contig = cursor.cursor.get_string_rep(_ksize); if (!cursor.cursor.is_forward()) { contig = _revcomp(contig); } #if DEBUG_ASSEMBLY std::cout << "## assemble_linear_left[start] at " << contig << std::endl; #endif reverse(contig.begin(), contig.end()); char next_base; unsigned int found = 0; while ((next_base = cursor.next_symbol()) != '\0') { contig += next_base; found++; } reverse(contig.begin(), contig.end()); #if DEBUG_ASSEMBLY std::cout << "## assemble_linear_left[end] found " << found << std::endl; #endif return contig; } template<> std::string LinearAssembler:: _assemble_directed<TRAVERSAL_RIGHT>(AssemblerTraverser<TRAVERSAL_RIGHT>& cursor) const { std::string contig = cursor.cursor.get_string_rep(_ksize); if (!cursor.cursor.is_forward()) { contig = _revcomp(contig); } char next_base; unsigned int found = 0; #if DEBUG_ASSEMBLY std::cout << "## assemble_linear_right[start] at " << contig << std::endl; #endif while ((next_base = cursor.next_symbol()) != '\0') { contig += next_base; found++; } #if DEBUG_ASSEMBLY std::cout << "## assemble_linear_right[end] found " << found << std::endl; #endif return contig; } /******************************** * Labeled Assembly ********************************/ SimpleLabeledAssembler::SimpleLabeledAssembler(const LabelHash * lh) : graph(lh->graph), lh(lh), _ksize(lh->graph->ksize()) { linear_asm = new LinearAssembler(graph); } SimpleLabeledAssembler::~SimpleLabeledAssembler() { delete this->linear_asm; } // Starting from the given seed k-mer, assemble all maximal linear paths in // both directions, using labels to skip over tricky bits. StringVector SimpleLabeledAssembler::assemble(const Kmer seed_kmer, const Hashgraph * stop_bf) const { #if DEBUG_ASSEMBLY std::cout << "Assemble Labeled: " << seed_kmer.repr(_ksize) << std::endl; #endif KmerFilterList node_filters; if (stop_bf) { node_filters.push_back(get_stop_bf_filter(stop_bf)); } std::shared_ptr<SeenSet> visited = std::make_shared<SeenSet>(); #if DEBUG_ASSEMBLY std::cout << "Assemble Labeled RIGHT: " << seed_kmer.repr(_ksize) << std::endl; #endif StringVector right_paths; AssemblerTraverser<TRAVERSAL_RIGHT> rcursor(graph, seed_kmer, node_filters, visited); _assemble_directed<TRAVERSAL_RIGHT>(rcursor, right_paths); #if DEBUG_ASSEMBLY std::cout << "Assemble Labeled LEFT: " << seed_kmer.repr(_ksize) << std::endl; #endif StringVector left_paths; AssemblerTraverser<TRAVERSAL_LEFT> lcursor(graph, seed_kmer, node_filters, visited); _assemble_directed<TRAVERSAL_LEFT>(lcursor, left_paths); StringVector paths; for (unsigned int i = 0; i < left_paths.size(); i++) { for (unsigned int j = 0; j < right_paths.size(); j++) { std::string right = right_paths[j]; right = right.substr(_ksize); std::string contig = left_paths[i] + right; paths.push_back(contig); } } visited->clear(); return paths; } template <bool direction> void SimpleLabeledAssembler:: _assemble_directed(AssemblerTraverser<direction>& start_cursor, StringVector& paths) const { #if DEBUG_ASSEMBLY std::cout << "## assemble_labeled_directed_" << direction << " [start] at " << start_cursor.cursor.repr(_ksize) << std::endl; #endif // prime the traversal with the first linear segment std::string root_contig = linear_asm->_assemble_directed<direction> (start_cursor); #if DEBUG_ASSEMBLY std::cout << "Primed: " << root_contig << std::endl; std::cout << "Cursor: " << start_cursor.cursor.repr(_ksize) << std::endl; #endif StringVector segments; std::vector< AssemblerTraverser<direction> > cursors; segments.push_back(root_contig); cursors.push_back(start_cursor); while(segments.size() != 0) { std::string segment = segments.back(); AssemblerTraverser<direction> cursor = cursors.back(); #if DEBUG_ASSEMBLY std::cout << "Pop: " << segments.size() << " segments on stack." << std::endl; std::cout << "Segment: " << segment << std::endl; std::cout << "Cursor: " << cursor.cursor.repr(_ksize) << std::endl; std::cout << "n_filters: " << cursor.n_filters() << std::endl; #endif segments.pop_back(); cursors.pop_back(); // check if the cursor has hit a HDN or reached a dead end if (cursor.cursor_degree() > 1) { LabelSet labels; lh->get_tag_labels(cursor.cursor, labels); if(labels.size() == 0) { // if no labels are found we can do nothing; gather this contig #if DEBUG_ASSEMBLY std::cout << "no-label dead-end" << std::endl; #endif paths.push_back(segment); continue; } else { // if there are labels, try to hop the HDN. // first, get a label filter cursor.push_filter(get_simple_label_intersect_filter(labels, lh)); KmerQueue branch_starts; // now get neighbors that pass the filter cursor.neighbors(branch_starts); // remove the filter cursor.pop_filter(); // no neighbors found; done with this path if (branch_starts.empty()) { #if DEBUG_ASSEMBLY std::cout << "no-neighbors dead-end" << std::endl; #endif paths.push_back(segment); continue; } // found some neighbors; extend them while(!branch_starts.empty()) { // spin off a cursor for the new branch AssemblerTraverser<direction> branch_cursor(cursor); branch_cursor.cursor = branch_starts.front(); branch_starts.pop(); #if DEBUG_ASSEMBLY std::cout << "Branch cursor: " << branch_cursor.cursor.repr( _ksize) << std::endl; #endif // assemble linearly as far as possible std::string branch = linear_asm->_assemble_directed<direction>(branch_cursor); // create a new segment with the branch std::string new_segment = branch_cursor.join_contigs(segment, branch, 1); #if DEBUG_ASSEMBLY std::cout << "Push segment: " << new_segment << std::endl; std::cout << "Push cursor: " << branch_cursor.cursor.repr(_ksize) << std::endl; #endif segments.push_back(new_segment); cursors.push_back(branch_cursor); } } } else { // this segment is a dead-end; keep the contig #if DEBUG_ASSEMBLY std::cout << "degree-1 dead-end" << std::endl; #endif paths.push_back(segment); continue; } } } /*************************************** * Junction-counting assembler ***************************************/ JunctionCountAssembler::JunctionCountAssembler(Hashgraph * ht) : graph(ht), _ksize(ht->ksize()), traverser(ht), linear_asm(ht) { std::vector<uint64_t> table_sizes = graph->get_tablesizes(); junctions = new Countgraph(_ksize, table_sizes); } JunctionCountAssembler::~JunctionCountAssembler() { delete this->junctions; } uint16_t JunctionCountAssembler::consume(std::string sequence) { // first we need to put the sequence in the graph graph->consume_string(sequence); // now we find its high degree nodes and count the // branch junctions KmerIterator kmers(sequence.c_str(), _ksize); Kmer kmer = kmers.next(); if (kmers.done()) { return 0; } Kmer next_kmer = kmers.next(); if (kmers.done()) { return 0; } uint16_t d = this->traverser.degree(kmer); uint16_t next_d = this->traverser.degree(next_kmer); uint16_t n_junctions = 0; while(!kmers.done()) { if (d > 2 || next_d > 2) { count_junction(kmer, next_kmer); n_junctions++; #if DEBUG_ASSEMBLY std::cout << "Junction: " << kmer.repr(_ksize) << ", " << next_kmer.repr( _ksize) << std::endl; std::cout << "Junction Count: " << get_junction_count(kmer, next_kmer) << std::endl; #endif } kmer = next_kmer; d = next_d; next_kmer = kmers.next(); next_d = this->traverser.degree(next_kmer); } return n_junctions / 2; } void JunctionCountAssembler::count_junction(Kmer kmer_a, Kmer kmer_b) { junctions->count(kmer_a.kmer_u ^ kmer_b.kmer_u); } BoundedCounterType JunctionCountAssembler::get_junction_count(Kmer kmer_a, Kmer kmer_b) const { return junctions->get_count(kmer_a.kmer_u ^ kmer_b.kmer_u); } // Starting from the given seed k-mer, assemble all maximal linear paths in // both directions, using junction counts to skip over tricky bits. StringVector JunctionCountAssembler::assemble(const Kmer seed_kmer, const Hashtable * stop_bf) const { #if DEBUG_ASSEMBLY std::cout << "Assemble Junctions: " << seed_kmer.repr(_ksize) << std::endl; #endif KmerFilterList node_filters; if (stop_bf) { node_filters.push_back(get_stop_bf_filter(stop_bf)); } std::shared_ptr<SeenSet> visited = std::make_shared<SeenSet>(); #if DEBUG_ASSEMBLY std::cout << "Assemble Junctions RIGHT: " << seed_kmer.repr( _ksize) << std::endl; #endif StringVector right_paths; AssemblerTraverser<TRAVERSAL_RIGHT> rcursor(graph, seed_kmer, node_filters, visited); _assemble_directed<TRAVERSAL_RIGHT>(rcursor, right_paths); #if DEBUG_ASSEMBLY std::cout << "Assemble Junctions LEFT: " << seed_kmer.repr(_ksize) << std::endl; #endif StringVector left_paths; AssemblerTraverser<TRAVERSAL_LEFT> lcursor(graph, seed_kmer, node_filters, visited); _assemble_directed<TRAVERSAL_LEFT>(lcursor, left_paths); StringVector paths; for (unsigned int i = 0; i < left_paths.size(); i++) { for (unsigned int j = 0; j < right_paths.size(); j++) { std::string right = right_paths[j]; right = right.substr(_ksize); std::string contig = left_paths[i] + right; paths.push_back(contig); } } visited->clear(); return paths; } template <bool direction> void JunctionCountAssembler:: _assemble_directed(AssemblerTraverser<direction>& start_cursor, StringVector& paths) const { #if DEBUG_ASSEMBLY std::cout << "## assemble_junctions_directed_" << direction << " [start] at " << start_cursor.cursor.repr(_ksize) << std::endl; #endif // prime the traversal with the first linear segment std::string root_contig = linear_asm._assemble_directed<direction> (start_cursor); #if DEBUG_ASSEMBLY std::cout << "Primed: " << root_contig << std::endl; std::cout << "Cursor: " << start_cursor.cursor.repr(_ksize) << std::endl; #endif StringVector segments; std::vector< AssemblerTraverser<direction> > cursors; segments.push_back(root_contig); cursors.push_back(start_cursor); while(segments.size() != 0) { std::string segment = segments.back(); AssemblerTraverser<direction> cursor = cursors.back(); #if DEBUG_ASSEMBLY std::cout << "Pop: " << segments.size() << " segments on stack." << std::endl; std::cout << "Segment: " << segment << std::endl; std::cout << "Cursor: " << cursor.cursor.repr(_ksize) << std::endl; std::cout << "n_filters: " << cursor.n_filters() << std::endl; #endif segments.pop_back(); cursors.pop_back(); // check if the cursor has hit a HDN or reached a dead end if (cursor.cursor_degree() > 1) { cursor.push_filter(get_junction_count_filter(cursor.cursor, this->junctions)); KmerQueue branch_starts; // now get neighbors that pass the filter cursor.neighbors(branch_starts); // remove the filter cursor.pop_filter(); // no neighbors found; done with this path if (branch_starts.empty()) { paths.push_back(segment); continue; } // found some neighbors; extend them while(!branch_starts.empty()) { // spin off a cursor for the new branch AssemblerTraverser<direction> branch_cursor(cursor); branch_cursor.cursor = branch_starts.front(); branch_starts.pop(); // assemble linearly as far as possible std::string branch = linear_asm._assemble_directed<direction>(branch_cursor); // create a new segment with the branch std::string new_segment = branch_cursor.join_contigs(segment, branch, 1); segments.push_back(new_segment); cursors.push_back(branch_cursor); } } else { // this segment is a dead-end; keep the contig paths.push_back(segment); continue; } } } }
32.758427
99
0.63231
sadeepdarshana
cf79d84525dbac544bc9cf6a6930997cbb1ab8a6
9,972
hpp
C++
src/imgui/imgui_impl_dx11_shaders.hpp
SleepKiller/shaderpatch
4bda848df0273993c96f1d20a2cf79161088a77d
[ "MIT" ]
13
2019-03-25T09:40:12.000Z
2022-03-13T16:12:39.000Z
src/imgui/imgui_impl_dx11_shaders.hpp
SleepKiller/shaderpatch
4bda848df0273993c96f1d20a2cf79161088a77d
[ "MIT" ]
110
2018-10-16T09:05:43.000Z
2022-03-16T23:32:28.000Z
src/imgui/imgui_impl_dx11_shaders.hpp
SleepKiller/swbfii-shaderpatch
b49ce3349d4dd09b19237ff4766652166ba1ffd4
[ "MIT" ]
1
2020-02-06T20:32:50.000Z
2020-02-06T20:32:50.000Z
constexpr inline static unsigned char imgui_impl_dx11_vs_shader[] = {68, 88, 66, 67, 193, 41, 206, 126, 110, 128, 143, 52, 233, 167, 187, 47, 111, 86, 223, 148, 1, 0, 0, 0, 80, 4, 0, 0, 6, 0, 0, 0, 56, 0, 0, 0, 24, 1, 0, 0, 32, 2, 0, 0, 156, 2, 0, 0, 108, 3, 0, 0, 220, 3, 0, 0, 65, 111, 110, 57, 216, 0, 0, 0, 216, 0, 0, 0, 0, 2, 254, 255, 152, 0, 0, 0, 64, 0, 0, 0, 2, 0, 36, 0, 0, 0, 60, 0, 0, 0, 60, 0, 0, 0, 36, 0, 1, 0, 60, 0, 0, 0, 0, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 3, 0, 1, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 254, 255, 31, 0, 0, 2, 5, 0, 0, 128, 0, 0, 15, 144, 31, 0, 0, 2, 5, 0, 1, 128, 1, 0, 15, 144, 31, 0, 0, 2, 5, 0, 2, 128, 2, 0, 15, 144, 5, 0, 0, 3, 0, 0, 15, 128, 0, 0, 85, 144, 2, 0, 228, 160, 4, 0, 0, 4, 0, 0, 15, 128, 1, 0, 228, 160, 0, 0, 0, 144, 0, 0, 228, 128, 2, 0, 0, 3, 0, 0, 15, 128, 0, 0, 228, 128, 3, 0, 228, 160, 4, 0, 0, 4, 0, 0, 3, 192, 0, 0, 255, 128, 0, 0, 228, 160, 0, 0, 228, 128, 1, 0, 0, 2, 0, 0, 12, 192, 0, 0, 228, 128, 1, 0, 0, 2, 0, 0, 15, 224, 1, 0, 228, 144, 1, 0, 0, 2, 1, 0, 3, 224, 2, 0, 228, 144, 255, 255, 0, 0, 83, 72, 68, 82, 0, 1, 0, 0, 64, 0, 1, 0, 64, 0, 0, 0, 89, 0, 0, 4, 70, 142, 32, 0, 0, 0, 0, 0, 4, 0, 0, 0, 95, 0, 0, 3, 50, 16, 16, 0, 0, 0, 0, 0, 95, 0, 0, 3, 242, 16, 16, 0, 1, 0, 0, 0, 95, 0, 0, 3, 50, 16, 16, 0, 2, 0, 0, 0, 103, 0, 0, 4, 242, 32, 16, 0, 0, 0, 0, 0, 1, 0, 0, 0, 101, 0, 0, 3, 242, 32, 16, 0, 1, 0, 0, 0, 101, 0, 0, 3, 50, 32, 16, 0, 2, 0, 0, 0, 104, 0, 0, 2, 1, 0, 0, 0, 56, 0, 0, 8, 242, 0, 16, 0, 0, 0, 0, 0, 86, 21, 16, 0, 0, 0, 0, 0, 70, 142, 32, 0, 0, 0, 0, 0, 1, 0, 0, 0, 50, 0, 0, 10, 242, 0, 16, 0, 0, 0, 0, 0, 70, 142, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 16, 16, 0, 0, 0, 0, 0, 70, 14, 16, 0, 0, 0, 0, 0, 0, 0, 0, 8, 242, 32, 16, 0, 0, 0, 0, 0, 70, 14, 16, 0, 0, 0, 0, 0, 70, 142, 32, 0, 0, 0, 0, 0, 3, 0, 0, 0, 54, 0, 0, 5, 242, 32, 16, 0, 1, 0, 0, 0, 70, 30, 16, 0, 1, 0, 0, 0, 54, 0, 0, 5, 50, 32, 16, 0, 2, 0, 0, 0, 70, 16, 16, 0, 2, 0, 0, 0, 62, 0, 0, 1, 83, 84, 65, 84, 116, 0, 0, 0, 6, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 82, 68, 69, 70, 200, 0, 0, 0, 1, 0, 0, 0, 76, 0, 0, 0, 1, 0, 0, 0, 28, 0, 0, 0, 0, 4, 254, 255, 0, 129, 0, 0, 160, 0, 0, 0, 60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 118, 101, 114, 116, 101, 120, 66, 117, 102, 102, 101, 114, 0, 171, 171, 171, 60, 0, 0, 0, 1, 0, 0, 0, 100, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 124, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 2, 0, 0, 0, 144, 0, 0, 0, 0, 0, 0, 0, 80, 114, 111, 106, 101, 99, 116, 105, 111, 110, 77, 97, 116, 114, 105, 120, 0, 171, 171, 171, 3, 0, 3, 0, 4, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 77, 105, 99, 114, 111, 115, 111, 102, 116, 32, 40, 82, 41, 32, 72, 76, 83, 76, 32, 83, 104, 97, 100, 101, 114, 32, 67, 111, 109, 112, 105, 108, 101, 114, 32, 49, 48, 46, 49, 0, 73, 83, 71, 78, 104, 0, 0, 0, 3, 0, 0, 0, 8, 0, 0, 0, 80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 89, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 15, 15, 0, 0, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0, 3, 3, 0, 0, 80, 79, 83, 73, 84, 73, 79, 78, 0, 67, 79, 76, 79, 82, 0, 84, 69, 88, 67, 79, 79, 82, 68, 0, 79, 83, 71, 78, 108, 0, 0, 0, 3, 0, 0, 0, 8, 0, 0, 0, 80, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 92, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 15, 0, 0, 0, 98, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0, 3, 12, 0, 0, 83, 86, 95, 80, 79, 83, 73, 84, 73, 79, 78, 0, 67, 79, 76, 79, 82, 0, 84, 69, 88, 67, 79, 79, 82, 68, 0, 171}; constexpr inline static unsigned char imgui_impl_dx11_ps_shader[] = {68, 88, 66, 67, 150, 64, 133, 239, 64, 93, 176, 41, 27, 158, 89, 90, 221, 169, 17, 109, 1, 0, 0, 0, 32, 3, 0, 0, 6, 0, 0, 0, 56, 0, 0, 0, 192, 0, 0, 0, 92, 1, 0, 0, 216, 1, 0, 0, 120, 2, 0, 0, 236, 2, 0, 0, 65, 111, 110, 57, 128, 0, 0, 0, 128, 0, 0, 0, 0, 2, 255, 255, 88, 0, 0, 0, 40, 0, 0, 0, 0, 0, 40, 0, 0, 0, 40, 0, 0, 0, 40, 0, 1, 0, 36, 0, 0, 0, 40, 0, 0, 0, 0, 0, 1, 2, 255, 255, 31, 0, 0, 2, 0, 0, 0, 128, 0, 0, 15, 176, 31, 0, 0, 2, 0, 0, 0, 128, 1, 0, 3, 176, 31, 0, 0, 2, 0, 0, 0, 144, 0, 8, 15, 160, 66, 0, 0, 3, 0, 0, 15, 128, 1, 0, 228, 176, 0, 8, 228, 160, 5, 0, 0, 3, 0, 0, 15, 128, 0, 0, 228, 128, 0, 0, 228, 176, 1, 0, 0, 2, 0, 8, 15, 128, 0, 0, 228, 128, 255, 255, 0, 0, 83, 72, 68, 82, 148, 0, 0, 0, 64, 0, 0, 0, 37, 0, 0, 0, 90, 0, 0, 3, 0, 96, 16, 0, 0, 0, 0, 0, 88, 24, 0, 4, 0, 112, 16, 0, 0, 0, 0, 0, 85, 85, 0, 0, 98, 16, 0, 3, 242, 16, 16, 0, 1, 0, 0, 0, 98, 16, 0, 3, 50, 16, 16, 0, 2, 0, 0, 0, 101, 0, 0, 3, 242, 32, 16, 0, 0, 0, 0, 0, 104, 0, 0, 2, 1, 0, 0, 0, 69, 0, 0, 9, 242, 0, 16, 0, 0, 0, 0, 0, 70, 16, 16, 0, 2, 0, 0, 0, 70, 126, 16, 0, 0, 0, 0, 0, 0, 96, 16, 0, 0, 0, 0, 0, 56, 0, 0, 7, 242, 32, 16, 0, 0, 0, 0, 0, 70, 14, 16, 0, 0, 0, 0, 0, 70, 30, 16, 0, 1, 0, 0, 0, 62, 0, 0, 1, 83, 84, 65, 84, 116, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 82, 68, 69, 70, 152, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 28, 0, 0, 0, 0, 4, 255, 255, 0, 129, 0, 0, 110, 0, 0, 0, 92, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 101, 0, 0, 0, 2, 0, 0, 0, 5, 0, 0, 0, 4, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 1, 0, 0, 0, 12, 0, 0, 0, 115, 97, 109, 112, 108, 101, 114, 48, 0, 116, 101, 120, 116, 117, 114, 101, 48, 0, 77, 105, 99, 114, 111, 115, 111, 102, 116, 32, 40, 82, 41, 32, 72, 76, 83, 76, 32, 83, 104, 97, 100, 101, 114, 32, 67, 111, 109, 112, 105, 108, 101, 114, 32, 49, 48, 46, 49, 0, 171, 171, 73, 83, 71, 78, 108, 0, 0, 0, 3, 0, 0, 0, 8, 0, 0, 0, 80, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 92, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 15, 15, 0, 0, 98, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0, 3, 3, 0, 0, 83, 86, 95, 80, 79, 83, 73, 84, 73, 79, 78, 0, 67, 79, 76, 79, 82, 0, 84, 69, 88, 67, 79, 79, 82, 68, 0, 171, 79, 83, 71, 78, 44, 0, 0, 0, 1, 0, 0, 0, 8, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 83, 86, 95, 84, 97, 114, 103, 101, 116, 0, 171, 171};
74.977444
78
0.286502
SleepKiller
cf7d1141ef88a7242dd538b4f82daa4596954eb6
607
cpp
C++
98.validate-binary-search-tree.159689697.ac.cpp
blossom2017/Leetcode
8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b
[ "Apache-2.0" ]
null
null
null
98.validate-binary-search-tree.159689697.ac.cpp
blossom2017/Leetcode
8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b
[ "Apache-2.0" ]
null
null
null
98.validate-binary-search-tree.159689697.ac.cpp
blossom2017/Leetcode
8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b
[ "Apache-2.0" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isValid(TreeNode * root, TreeNode * &prev) { if(!root)return true; if(!(isValid(root->left,prev)))return false; if(prev!=NULL&&prev->val>=root->val)return false; prev= root; return isValid(root->right,prev); } bool isValidBST(TreeNode* root) { TreeNode * prev = NULL; return isValid(root,prev); } };
23.346154
59
0.560132
blossom2017
cf7dc474ebd427220acf680c83be738994184d17
3,920
cpp
C++
hi_dsp_library/dywapitchtrack/PitchDetection.cpp
Matt-Dub/HISE
ae2dd1653e1c8d749a9088edcd573de6252b0b96
[ "Intel" ]
null
null
null
hi_dsp_library/dywapitchtrack/PitchDetection.cpp
Matt-Dub/HISE
ae2dd1653e1c8d749a9088edcd573de6252b0b96
[ "Intel" ]
null
null
null
hi_dsp_library/dywapitchtrack/PitchDetection.cpp
Matt-Dub/HISE
ae2dd1653e1c8d749a9088edcd573de6252b0b96
[ "Intel" ]
null
null
null
/* =========================================================================== * * This file is part of HISE. * Copyright 2016 Christoph Hart * * HISE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HISE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HISE. If not, see <http://www.gnu.org/licenses/>. * * Commercial licenses for using HISE in an closed source project are * available on request. Please visit the project's website to get more * information about commercial licensing: * * http://www.hise.audio/ * * HISE is based on the JUCE library, * which must be separately licensed for closed source applications: * * http://www.juce.com * * =========================================================================== */ namespace hise { using namespace juce; double PitchDetection::detectPitch(float* fullData, int numSamples, double sampleRate) { dywapitchtracker tracker; dywapitch_inittracking(&tracker); auto numPerCheck = dywapitch_neededsamplecount((int)(50.0 * (44100.0 / sampleRate))); Array<double> pitchResults; int startSample = 0; while ((startSample + numPerCheck) < numSamples) { const double pitchResult = dywapitch_computepitch(&tracker, fullData, startSample, numPerCheck); auto thisPitch = pitchResult * (sampleRate / 44100.0); pitchResults.add(thisPitch); startSample += numPerCheck / 2; } if (!pitchResults.isEmpty()) { pitchResults.sort(); return pitchResults[pitchResults.size() / 2]; } return 0.0; } double PitchDetection::detectPitch(const File &fileToScan, AudioSampleBuffer &workingBuffer, double sampleRate) { const int numSamplesPerDetection = workingBuffer.getNumSamples(); AudioFormatManager afm; afm.registerBasicFormats(); ScopedPointer<AudioFormatReader> afr = afm.createReaderFor(std::unique_ptr<InputStream>(new FileInputStream(File(fileToScan)))); int64 startSample = 0; Array<double> pitchResults; while (startSample + numSamplesPerDetection < afr->lengthInSamples) { afr->read(&workingBuffer, 0, workingBuffer.getNumSamples(), startSample, true, true); auto thisPitch = detectPitch(workingBuffer, 0, numSamplesPerDetection, sampleRate); pitchResults.add(thisPitch); startSample += numSamplesPerDetection / 2; } if (pitchResults.size() > 0) { return pitchResults[pitchResults.size() / 2]; } return 0.0; } double PitchDetection::detectPitch(const AudioSampleBuffer &buffer, int startSample, int numSamples, double sampleRate) { Array<DywaFloat> doubleSamples; doubleSamples.ensureStorageAllocated(numSamples); for (int i = 0; i < numSamples; i++) { if (buffer.getNumChannels() == 2) { const double value = (double)(buffer.getSample(0, startSample + i) + buffer.getSample(1, startSample + i)) / 2.0; doubleSamples.set(i, value); } else { const double value = (double)(buffer.getSample(0, startSample + i)); doubleSamples.set(i, value); } } dywapitchtracker tracker; dywapitch_inittracking(&tracker); const double pitchResult = dywapitch_computepitch(&tracker, doubleSamples.getRawDataPointer(), 0, numSamples); return pitchResult * (sampleRate / 44100.0); } int PitchDetection::getNumSamplesNeeded(double sampleRate) { return getNumSamplesNeeded(sampleRate, 50.0); } int PitchDetection::getNumSamplesNeeded(double sampleRate, double minFrequencyToAnalyse) { return dywapitch_neededsamplecount((int)(minFrequencyToAnalyse * (44100.0 / sampleRate))); } } // namespace hise
28.405797
129
0.713265
Matt-Dub
cf7f6c1997592fdbd0ad70e5196c9cedb8dc848b
852
cpp
C++
fi-tools/sw-faults/Regression/testsuite/CPP/54/54.origin.cpp
ucx-code/ucXception
6b1f4fe4aa53a28e87584d07f540095c20ee50e9
[ "BSD-3-Clause" ]
2
2020-08-11T10:54:56.000Z
2021-03-22T14:54:19.000Z
fi-tools/sw-faults/Regression/testsuite/CPP/54/54.origin.cpp
ucx-code/ucXception
6b1f4fe4aa53a28e87584d07f540095c20ee50e9
[ "BSD-3-Clause" ]
null
null
null
fi-tools/sw-faults/Regression/testsuite/CPP/54/54.origin.cpp
ucx-code/ucXception
6b1f4fe4aa53a28e87584d07f540095c20ee50e9
[ "BSD-3-Clause" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <algorithm> struct _slot { int begin; int end; }; struct _slot slot[150000]; bool operator<(const struct _slot& a, const struct _slot& b) { return a.end < b.end; } int main() { int n; scanf("%d\n", &n); int i; for (i = 0; i < n; i++) { scanf("%d %d", &slot[i].begin, &slot[i].end); } std::sort(slot, slot+n); // i = 0, se a nao interessta +1, i = a // while int a; int maximo = 0; int begin = 1; int linhas = n; maximo = 0; int master = 0; for (i = 1; i < n; i++) { if ((slot[master].end <= slot[i].begin)) { ++maximo; master = i; } } printf("%d\n", n-maximo); return 0; }
18.521739
62
0.428404
ucx-code
cf7fa47cfadeb082783b387895eac6395ed54bac
5,121
cpp
C++
tab/tools/tab_com.cpp
constcut/mtherapp
20b8e32361ef492d5b7cb4ff150f0956e952fdef
[ "MIT" ]
2
2022-03-04T17:54:48.000Z
2022-03-28T06:20:31.000Z
tab/tools/tab_com.cpp
constcut/aurals
bb00fac92a3a919867fe2e482c37fc0abe5e6984
[ "MIT" ]
null
null
null
tab/tools/tab_com.cpp
constcut/aurals
bb00fac92a3a919867fe2e482c37fc0abe5e6984
[ "MIT" ]
null
null
null
#include "tab/Tab.hpp" #include "midi/MidiFile.hpp" #include "GmyFile.hpp" #include "TabLoader.hpp" #include "GtpFiles.hpp" #include <fstream> #include <QDebug> using namespace aurals; //TODO prepare undo operations //They have to be for all possible commands void Tab::setSignsTillEnd(size_t num, size_t denom) { _macroCommands.push_back(TwoIntCommand<TabCommand>{TabCommand::SetSignTillEnd, num, denom}); for (size_t trackId = 0; trackId < this->size(); ++trackId) for (size_t i = _currentBar; i < this->at(trackId)->size(); ++i){ this->at(trackId)->at(i)->setSignDenum(denom); this->at(trackId)->at(i)->setSignNum(num); qDebug() << "Changing bar " << i << " on " << num << " " << denom; } } void Tab::moveCursorInTrackRight() { if (_displayBar < at(0)->size() - 1) ++_displayBar; } void Tab::moveCursorInTrackLeft() { if (_displayBar > 0) --_displayBar; } void Tab::changeTrackVolume(size_t newVol) { _macroCommands.push_back(IntCommand<TabCommand>{TabCommand::Volume, newVol}); at(_currentTrack)->setVolume(newVol); } void Tab::changeTrackName(std::string newName) { _macroCommands.push_back(StringCommand<TabCommand>{TabCommand::Name, newName}); at(_currentTrack)->setName(newName); } void Tab::changeTrackInstrument(size_t val) { _macroCommands.push_back(IntCommand<TabCommand>{TabCommand::Instument, val}); at(_currentTrack)->setInstrument(val); } void Tab::changeTrackPanoram(size_t val) { _macroCommands.push_back(IntCommand<TabCommand>{TabCommand::Panoram, val}); at(_currentTrack)->setPan(val); } void Tab::createNewTrack() { Tab* pTab = this; auto track = std::make_unique<Track>(); track->setParent(pTab); std::string iName("NewInstrument"); track->setName(iName); track->setInstrument(25); track->setVolume(15); track->setDrums(false); track->setPan(8); //center now auto& tuning = track->getTuningRef(); tuning.setStringsAmount(6); tuning.setTune(0, 64); tuning.setTune(1, 59); tuning.setTune(2, 55); tuning.setTune(3, 50); tuning.setTune(4, 45); tuning.setTune(5, 40); if (pTab->size()) { for (size_t barI=0; barI < pTab->at(0)->size(); ++barI) { auto bar = std::make_unique<Bar>(); bar->flush(); bar->setSignDenum(4); bar->setSignNum(4); //Подумать над механизмами, разные размеры только при полиритмии нужны bar->setRepeat(0); auto beat = std::make_unique<Beat>(); beat->setPause(true); beat->setDotted(0); beat->setDuration(3); beat->setDurationDetail(0); bar->push_back(std::move(beat)); track->push_back(std::move(bar)); } } else { auto bar = std::make_unique<Bar>(); bar->flush(); bar->setSignDenum(4); bar->setSignNum(4); bar->setRepeat(0); auto beat = std::make_unique<Beat>(); beat->setPause(true); beat->setDotted(0); beat->setDuration(3); beat->setDurationDetail(0); bar->push_back(std::move(beat)); track->push_back(std::move(bar)); } pTab->push_back(std::move(track)); pTab->connectTracks(); } void Tab::midiPause() { if (_isPlaying == false) { //STARTMIDI _isPlaying = true; } else { //MidiEngine::stopDefaultFile(); _isPlaying = false; } } void Tab::setMarker(std::string text) { auto& fromFirstTrack = at(0)->at(_currentBar); fromFirstTrack->setMarker(text,0); } void Tab::openReprise() { auto& firstTrackBar = this->at(0)->at(_currentBar); std::uint8_t repeat = firstTrackBar->getRepeat(); std::uint8_t repeatOpens = repeat & 1; std::uint8_t repeatCloses = repeat & 2; if (repeatOpens){ firstTrackBar->setRepeat(0); //flush firstTrackBar->setRepeat(repeatCloses); } else firstTrackBar->setRepeat(1); } void Tab::closeReprise(size_t count) { _macroCommands.push_back(IntCommand<TabCommand>{TabCommand::CloseReprise, count}); auto& firstTrackBar = this->at(0)->at(_currentBar); std::uint8_t repeat = firstTrackBar->getRepeat(); std::uint8_t repeatOpens = repeat & 1; std::uint8_t repeatCloses = repeat & 2; if (repeatCloses) { firstTrackBar->setRepeat(0); firstTrackBar->setRepeat(repeatOpens); } else { if (count) firstTrackBar->setRepeat(2, count); } } void Tab::gotoBar(size_t pos) { _macroCommands.push_back(IntCommand<TabCommand>{TabCommand::GotoBar, pos}); _currentBar = pos; _displayBar = pos; } void Tab::saveAs(std::string filename) { _macroCommands.push_back(StringCommand<TabCommand>{TabCommand::SaveAs, filename}); std::ofstream file(filename); GmyFile gmyFile; gmyFile.saveToFile(file, this); file.close(); } void Tab::onTabCommand(TabCommand command) { _macroCommands.push_back(command); if (_handlers.count(command)) (this->*_handlers.at(command))(); }
25.605
124
0.629369
constcut
cf8244e6fdf3164351551303e75ffb44b29c1b3d
7,487
cpp
C++
hw/src/SEST.cpp
bebosudo/sensors_station
c5db51d38f2ccd3d3671a42ab164e6357e0a6694
[ "MIT" ]
1
2018-01-01T18:25:26.000Z
2018-01-01T18:25:26.000Z
hw/src/SEST.cpp
bebosudo/sensors_station
c5db51d38f2ccd3d3671a42ab164e6357e0a6694
[ "MIT" ]
null
null
null
hw/src/SEST.cpp
bebosudo/sensors_station
c5db51d38f2ccd3d3671a42ab164e6357e0a6694
[ "MIT" ]
1
2018-01-01T22:55:28.000Z
2018-01-01T22:55:28.000Z
// SEST library. // Alberto Chiusole -- 2017. #include "SEST.h" #include "Arduino.h" // #include <algorithm> #include <cstdint> #include <math.h> #include <string> const unsigned int MS_WAIT_BEFORE_TIMEOUT = 5000; SEST::SEST(Client& client, const std::string& address, const std::string& write_key) : _client(client), _address(address), _write_key(write_key) { // Strip newlines from the URI. // Can't do it with algorithm due to a bug in the esp8266/arduino package: // https://github.com/platformio/platformio-core/issues/653 for (int p = _address.find("\n"); p != (int)std::string::npos; p = _address.find("\n")) { _address.erase(p, 1); } // Remove the possible heading http(s) the user could insert. std::string prot = "http://"; if (_address.substr(0, prot.length()) == prot) { _address = _address.substr(prot.length(), std::string::npos); } prot = "https://"; if (_address.substr(0, prot.length()) == prot) { _address = _address.substr(prot.length(), std::string::npos); } if (is_url_valid()) { extract_domain(); extract_path(); } else { _host = ""; _path = ""; } // The port can be changed with the set_port method. _port = 80; } SEST::~SEST() {} void SEST::set_port(unsigned int port) { _port = port; } bool SEST::is_url_valid() const { // I consider an host to be valid when there's at least a period that // separates the 1st to the 2nd level domain name. std::size_t pos = _address.find("."); return pos != std::string::npos; } void SEST::extract_domain() { // Given an url, extract the domain. std::size_t pos = _address.find("/"); if (pos != std::string::npos) { _host = _address.substr(0, pos); } // If a slash isn't found, the address saved is a domain. } void SEST::extract_path() { // Given an url, extract the path (the address following the domain), if // any. std::size_t pos = _address.find("/"); if (pos != std::string::npos) { _path = _address.substr(pos + 1, std::string::npos); } } std::string number_to_string(int number) { char buffer[64]; int status = snprintf(buffer, sizeof buffer, "%d", number); if (status < 0) return std::string(""); return std::string(buffer); } std::string number_to_string(double number) { /* Home-made version of dtostrf, because it doesn't seem to be supported on the esp8266: http://stackoverflow.com/a/27652012 */ int dec_precision = 4; int int_part = floor(number); int dec_part = floor((number - int_part) * pow(10, dec_precision)); std::string buffer = number_to_string(int_part); buffer += "."; buffer += number_to_string(dec_part); return std::string(buffer); } bool SEST::set_field(unsigned int field_no, int value) { if (field_no <= MAX_NUMBER_FIELDS and field_no != 0) { // The user creates field types counting from 1, and we remap the // position to a position one step lower in order to save it into // C-style arrays. _field_arr[field_no - 1] = number_to_string(value); return true; } return false; } bool SEST::set_field(unsigned int field_no, double value) { if (field_no <= MAX_NUMBER_FIELDS and field_no != 0) { // The user creates field types counting from 1, and we remap the // position to a position one step lower in order to save it into // C-style arrays. _field_arr[field_no - 1] = number_to_string(value); return true; } return false; } bool SEST::_connect_to_server() { if (_host == "") { return false; } return _client.connect(_host.c_str(), _port); } std::string SEST::_get_fields_encoded() const { std::string body = ""; for (int i = 0; i < MAX_NUMBER_FIELDS; i++) { if (_field_arr[i] != "") { if (body != "") { body += "&"; } body += "field"; // As we already did in the set_field method, we need to move the // position of the field by one step. body += number_to_string((int)i + 1); body += "="; // The array is already made of strings. body += _field_arr[i]; } } return body; } void SEST::_reset_fields() { for (int i = 0; i < MAX_NUMBER_FIELDS; i++) { _field_arr[i] = ""; } } bool SEST::push() { std::string to_be_discarded; push(to_be_discarded); } bool SEST::push(std::string& collect_response) { std::string body = _get_fields_encoded(); collect_response = collect_response + "Trying to connect to server '" + _host + "', port '" + number_to_string((int)_port) + "', pointing to path '/" + _path + "'.\n"; if (!_connect_to_server()) { _read_http_response(collect_response); return false; } else if (_write_key == "") { collect_response += "Missing writing key for the chosen channel.\n"; return false; } else if (body == "") { collect_response += "Missing body message (no fields to send).\n"; return false; } std::string header = "POST /"; header += _path; header += " HTTP/1.1\r\nHost: "; header += _host; header += "\r\nAccept: */*\r\n"; header += HTTP_WRITE_KEY; header += ": "; header += _write_key; header += "\r\nUser-Agent: "; header += USER_AGENT; header += "\r\n"; header += "Content-type: application/x-www-form-urlencoded\r\n"; header += "Connection: close\r\nContent-Length: "; header += number_to_string((int)body.length()); header += "\r\n\r\n"; if (!_client.print(header.c_str())) { collect_response += "ERROR when uploading.\n"; return false; } if (!_client.print(body.c_str())) { collect_response += "ERROR when uploading.\n"; return false; } collect_response += "Attempting to send:\n\n" + header + body + "\n\n"; _reset_fields(); if (_read_http_response(collect_response)) { collect_response += "Package reached destination.\n"; return true; } collect_response += "Some problems arose while sending.\n"; return false; } bool SEST::_read_http_response(std::string& response) const { long unsigned int start_time = millis(); // Wait until the client has something to say, or until enough time has // passed before receiving a response. Reason to use delay: // https://github.com/esp8266/Arduino/issues/34#issuecomment-102302835 while (_client.available() == 0 && millis() - start_time < MS_WAIT_BEFORE_TIMEOUT) { delay(100); } // If the client still has nothing to say, it means that timeout // arrived. if (_client.available() == 0) { response += " ERROR: timeout when waiting for the server to reply (address: "; response += _address; response += ", TCP port: "; response += number_to_string((int)_port); response += ").\n"; return false; } size_t s = 100; char buffer[s]; size_t size_read = 0; while (_client.available() != 0) { size_read += _client.read((uint8_t*)buffer, s); // Empty the buffer on the ESP wifi module. // _client.flush(); response += std::string(buffer); } return size_read == s; }
29.828685
78
0.594364
bebosudo
cf84b0016e76801f834cd3a0f8ed389708fda89e
939
hpp
C++
include/oogl/RenderBuffer.hpp
rharel/cpp-oogl
e8fd19649cc113aff43ddb8d805ca356e9a6b02c
[ "MIT" ]
1
2019-08-28T19:03:45.000Z
2019-08-28T19:03:45.000Z
include/oogl/RenderBuffer.hpp
rharel/cpp-oogl
e8fd19649cc113aff43ddb8d805ca356e9a6b02c
[ "MIT" ]
null
null
null
include/oogl/RenderBuffer.hpp
rharel/cpp-oogl
e8fd19649cc113aff43ddb8d805ca356e9a6b02c
[ "MIT" ]
1
2019-08-28T19:03:51.000Z
2019-08-28T19:03:51.000Z
/** * Render Buffer Object. * * @author Raoul Harel * @url github/rharel/cpp-oogl */ #pragma once #include <glew/glew.h> #include <oogl/GLObject.hpp> namespace oogl { /** * This class wraps around OpenGL render buffer objects. * Render buffers are used as render targets and are used together * with frame buffers. */ class RenderBuffer : public GLObject { public: /** * Defines the storage structure of the currently bound buffer. */ static void DefineStorage ( GLenum internal_format, GLsizei width, GLsizei height ); /** * Creates a new buffer. */ RenderBuffer(); /** * Deletes buffer. */ ~RenderBuffer() override; /** * Binds to context. */ void Bind() override; }; } #include <oogl/RenderBuffer.cpp>
18.057692
71
0.538871
rharel
cf85be95aed6719820898de9f92c83aa6ffdaac5
18,997
cpp
C++
src/utils/file.cpp
ramonbrugman/bubichain
433e2352d0c7cea591cd5c9229e9e2c5dbd7957a
[ "Apache-2.0" ]
99
2017-08-08T01:37:45.000Z
2021-05-15T14:39:43.000Z
src/utils/file.cpp
ramonbrugman/bubichain
433e2352d0c7cea591cd5c9229e9e2c5dbd7957a
[ "Apache-2.0" ]
3
2017-08-23T06:39:15.000Z
2019-09-06T18:18:17.000Z
src/utils/file.cpp
ramonbrugman/bubichain
433e2352d0c7cea591cd5c9229e9e2c5dbd7957a
[ "Apache-2.0" ]
41
2017-08-08T01:38:41.000Z
2022-02-15T12:12:21.000Z
/* Copyright © Bubi Technologies Co., Ltd. 2017 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 "utils.h" #include "strings.h" #include "file.h" #ifdef WIN32 #include <shlobj.h> #else #include <unistd.h> #include <pwd.h> #include <fnmatch.h> #endif #ifdef WIN32 const char *utils::File::PATH_SEPARATOR = "\\"; const char utils::File::PATH_CHAR = '\\'; #else const char *utils::File::PATH_SEPARATOR = "/"; const char utils::File::PATH_CHAR = '/'; #endif utils::File::File() { handle_ = NULL; } utils::File::~File() { if (IsOpened()) Close(); } std::string utils::File::RegularPath(const std::string &path) { std::string new_path = path; #ifdef WIN32 if (new_path.size() > 1 && new_path.at(0) == '/') { new_path.erase(0, 1); new_path.insert(1, ":"); } new_path = utils::String::Replace(new_path, "/", File::PATH_SEPARATOR); #else new_path = utils::String::Replace(new_path, "\\", File::PATH_SEPARATOR); #endif return new_path; } std::string utils::File::GetFileFromPath(const std::string &path) { std::string regular_path = path; regular_path = File::RegularPath(regular_path); size_t nPos = regular_path.rfind(File::PATH_CHAR); if (std::string::npos == nPos) { return regular_path; } else if (nPos + 1 >= regular_path.size()) { return std::string(""); } else { return regular_path.substr(nPos + 1, regular_path.size() - nPos - 1); } } bool utils::File::Open(const std::string &strFile0, int nMode) { CHECK_ERROR_RET(IsOpened(), ERROR_ALREADY_EXISTS, false); file_name_ = File::RegularPath(strFile0); // read or write char szMode[64] = { 0 }; if (nMode & FILE_M_READ) strcpy(szMode, (nMode & FILE_M_WRITE) ? "r+" : "r"); else if (nMode & FILE_M_WRITE) strcpy(szMode, "w"); else if (nMode & FILE_M_APPEND) strcpy(szMode, "a"); else strcpy(szMode, "r+"); // text or binary if (nMode & FILE_M_BINARY) strcat(szMode, "b"); else if (nMode & FILE_M_TEXT) strcat(szMode, "t"); else strcat(szMode, "b"); // default as binary handle_ = fopen(file_name_.c_str(), szMode); if (NULL == handle_) { return false; } open_mode_ = nMode; if (nMode & FILE_M_LOCK && !LockRange(0, utils::LOW32_BITS_MASK, true)) { uint32_t error_code = utils::error_code(); fclose(handle_); handle_ = NULL; utils::set_error_code(error_code); return false; } return NULL != handle_; } bool utils::File::Close() { CHECK_ERROR_RET(!IsOpened(), ERROR_NOT_READY, false); if (open_mode_ & FILE_M_LOCK) { UnlockRange(0, utils::LOW32_BITS_MASK); } fclose(handle_); handle_ = NULL; return true; } bool utils::File::Flush() { CHECK_ERROR_RET(!IsOpened(), ERROR_NOT_READY, false); return fflush(handle_) == 0; } bool utils::File::LockRange(uint64_t offset, uint64_t size, bool try_lock /* = false */) { CHECK_ERROR_RET(!IsOpened(), ERROR_NOT_READY, false); bool result = false; int file_no = fileno(handle_); #ifdef WIN32 OVERLAPPED nOverlapped; DWORD dwSizeLow = (DWORD)(size & utils::LOW32_BITS_MASK); DWORD dwSizeHigh = (DWORD)((size >> 32) & utils::LOW32_BITS_MASK); DWORD dwFlags = try_lock ? (LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY) : LOCKFILE_EXCLUSIVE_LOCK; memset(&nOverlapped, 0, sizeof(nOverlapped)); nOverlapped.Offset = (DWORD)(offset & utils::LOW32_BITS_MASK); nOverlapped.OffsetHigh = (DWORD)((offset >> 32) & utils::LOW32_BITS_MASK); result = (::LockFileEx((HANDLE)_get_osfhandle(file_no), dwFlags, 0, dwSizeLow, dwSizeHigh, &nOverlapped) == TRUE); #else uint64_t nOldPosition = GetPosition(); if (nOldPosition != offset && !Seek(offset, File::FILE_S_BEGIN)) { return false; } int nFlags = try_lock ? F_TLOCK : F_LOCK; off_t nUnlockSize = (utils::LOW32_BITS_MASK == size) ? 0 : (off_t)size; result = (lockf(file_no, nFlags, nUnlockSize) == 0); if (nOldPosition != offset && !Seek(nOldPosition, File::FILE_S_BEGIN)) { uint32_t nErrorCode = utils::error_code(); // unlock //result = false; result = (lockf(file_no, F_ULOCK, nUnlockSize) == 0); utils::set_error_code(nErrorCode); } #endif return result; } bool utils::File::UnlockRange(uint64_t offset, uint64_t size) { CHECK_ERROR_RET(!IsOpened(), ERROR_NOT_READY, false); bool result = false; int file_no = fileno(handle_); #ifdef WIN32 OVERLAPPED nOverlapped; DWORD dwSizeLow = (DWORD)(size & utils::LOW32_BITS_MASK); DWORD dwSizeHigh = (DWORD)((size >> 32) & utils::LOW32_BITS_MASK); memset(&nOverlapped, 0, sizeof(nOverlapped)); nOverlapped.Offset = (DWORD)(offset & utils::LOW32_BITS_MASK); nOverlapped.OffsetHigh = (DWORD)((offset >> 32) & utils::LOW32_BITS_MASK); result = (::UnlockFileEx((HANDLE)_get_osfhandle(file_no), 0, dwSizeLow, dwSizeHigh, &nOverlapped) == TRUE); #else #ifndef ANDROID uint64_t nOldPosition = GetPosition(); if (nOldPosition != offset && !Seek(offset, File::FILE_S_BEGIN)) { return false; } off_t nUnlockSize = (utils::LOW32_BITS_MASK == size) ? 0 : (off_t)size; bool bResult = (lockf(file_no, F_ULOCK, nUnlockSize) == 0); if (nOldPosition != offset && !Seek(nOldPosition, File::FILE_S_BEGIN)) { bResult = false; } #endif #endif return result; } size_t utils::File::ReadData(std::string &data, size_t max_count) { CHECK_ERROR_RET(!IsOpened(), ERROR_NOT_READY, 0); const size_t buffer_size = 1024 * 1024; size_t read_bytes_size = 0; static char nTmpBuffer[buffer_size]; while (read_bytes_size < max_count) { size_t nCount = MIN(max_count - read_bytes_size, buffer_size); size_t nRetBytes = fread(nTmpBuffer, 1, nCount, handle_); if (nRetBytes > 0) { read_bytes_size += nRetBytes; data.append(nTmpBuffer, nRetBytes); } else { break; } } return read_bytes_size; } size_t utils::File::Read(void *pBuffer, size_t nChunkSize, size_t nCount) { CHECK_ERROR_RET(!IsOpened(), ERROR_NOT_READY, 0); return fread(pBuffer, nChunkSize, nCount, handle_); } bool utils::File::ReadLine(std::string &strLine, size_t nMaxCount) { CHECK_ERROR_RET(!IsOpened(), ERROR_NOT_READY, 0); strLine.resize(nMaxCount + 1, 0); char *pszBuffer = (char *)strLine.c_str(); pszBuffer[nMaxCount] = 0; if (fgets(pszBuffer, nMaxCount, handle_) == NULL) { strLine.clear(); return false; } size_t nNewLen = strlen(pszBuffer); strLine.resize(nNewLen); return true; } size_t utils::File::Write(const void *pBuffer, size_t nChunkSize, size_t nCount) { CHECK_ERROR_RET(!IsOpened(), ERROR_NOT_READY, 0); return fwrite(pBuffer, nChunkSize, nCount, handle_); } uint64_t utils::File::GetPosition() { return 0; } bool utils::File::Seek(uint64_t offset, FILE_SEEK_MODE nMode) { return true; } bool utils::File::IsAbsolute(const std::string &path) { std::string regular_path = File::RegularPath(path); #ifdef WIN32 return regular_path.size() > 0 && regular_path.find(':') != std::string::npos; #else return regular_path.size() > 0 && '/' == regular_path[0]; #endif } std::string utils::File::GetBinPath() { std::string path; char szpath[File::MAX_PATH_LEN * 4] = { 0 }; #ifdef WIN32 DWORD path_len = ::GetModuleFileNameA(NULL, szpath, File::MAX_PATH_LEN * 4 - 1); if (path_len >= 0) { szpath[path_len] = '\0'; path = szpath; } #else ssize_t path_len = readlink("/proc/self/exe", szpath, File::MAX_PATH_LEN * 4 - 1); if (path_len >= 0) { szpath[path_len] = '\0'; path = szpath; } #endif return path; } utils::FileAttribute::FileAttribute() { is_directory_ = false; create_time_ = 0; modify_time_ = 0; access_time_ = 0; size_ = 0; } std::string utils::File::GetBinDirecotry() { std::string path = File::GetBinPath(); return GetUpLevelPath(path); } std::string utils::File::GetBinHome() { return GetUpLevelPath(GetBinDirecotry()); } std::string utils::File::GetUpLevelPath(const std::string &path) { std::string normal_path = File::RegularPath(path); size_t nPos = normal_path.rfind(File::PATH_CHAR); if (std::string::npos == nPos) { #ifdef WIN32 nPos = normal_path.rfind(':'); if (std::string::npos == nPos) { return std::string(""); } else { nPos++; } #else return std::string(""); #endif } if (0 == nPos && normal_path.size() > 0 && normal_path[0] == File::PATH_CHAR) { nPos++; } return normal_path.substr(0, nPos); } #ifdef WIN32 time_t __WinFileTime2UnixTime(const FILETIME &nTime) { LONGLONG nTimeTick = (((LONGLONG)nTime.dwHighDateTime) << 32) + (LONGLONG)(nTime.dwLowDateTime); return (time_t)((nTimeTick - 116444736000000000L) / 10000000); } #endif bool utils::File::GetAttribue(const std::string &strFile0, FileAttribute &nAttr) { std::string file1 = RegularPath(strFile0); #ifdef WIN32 WIN32_FILE_ATTRIBUTE_DATA nFileAttr; if (GetFileAttributesExA(file1.c_str(), GetFileExInfoStandard, &nFileAttr)) { nAttr.is_directory_ = (nFileAttr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; nAttr.create_time_ = __WinFileTime2UnixTime(nFileAttr.ftCreationTime); nAttr.modify_time_ = __WinFileTime2UnixTime(nFileAttr.ftLastWriteTime); nAttr.access_time_ = __WinFileTime2UnixTime(nFileAttr.ftLastAccessTime); nAttr.size_ = (((uint64_t)(nFileAttr.nFileSizeHigh)) << 32) + (uint64_t)(nFileAttr.nFileSizeLow); return true; } #else struct stat nFileStat; if (stat(file1.c_str(), &nFileStat) == 0) { nAttr.is_directory_ = (nFileStat.st_mode & S_IFDIR) != 0; nAttr.create_time_ = nFileStat.st_ctime; nAttr.modify_time_ = nFileStat.st_mtime; nAttr.access_time_ = nFileStat.st_atime; nAttr.size_ = nFileStat.st_size; return true; } #endif else { return false; } } #ifdef WIN32 size_t __WinGetDriveInfo(utils::FileAttributes &nFiles) { DWORD dwDrv = GetLogicalDrives(); for (int i = 0; dwDrv > 0; i++, dwDrv >>= 1) { if ((dwDrv & 0x00000001) == 0) continue; std::string strName = utils::String::Format("%c", 'A' + i); utils::FileAttribute &nAttr = nFiles[strName]; nAttr.is_directory_ = true; } return nFiles.size(); } #endif bool utils::File::GetFileList(const std::string &strDirectory0, const std::string &strPattern, utils::FileAttributes &nFiles, bool bFillAttr, size_t nMaxCount) { std::string strNormalPath = File::RegularPath(strDirectory0); #ifdef WIN32 if (strDirectory0 == "/") { __WinGetDriveInfo(nFiles); return true; } WIN32_FIND_DATAA nFindData; HANDLE hFindFile = INVALID_HANDLE_VALUE; std::string strFindName = utils::String::Format("%s\\%s", strNormalPath.c_str(), strPattern.empty() ? "*" : strPattern.c_str()); hFindFile = FindFirstFileA(strFindName.c_str(), &nFindData); if (INVALID_HANDLE_VALUE == hFindFile) { return false; } // clean old files nFiles.clear(); do { if (strcmp(nFindData.cFileName, ".") == 0 || strcmp(nFindData.cFileName, "..") == 0) { // self or parent continue; } std::string strName(nFindData.cFileName); utils::FileAttribute &nAttr = nFiles[strName]; nAttr.is_directory_ = (nFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; nAttr.create_time_ = __WinFileTime2UnixTime(nFindData.ftCreationTime); nAttr.modify_time_ = __WinFileTime2UnixTime(nFindData.ftLastWriteTime); nAttr.access_time_ = __WinFileTime2UnixTime(nFindData.ftLastAccessTime); nAttr.size_ = (((uint64_t)(nFindData.nFileSizeHigh)) << 32) + (uint64_t)(nFindData.nFileSizeLow); if (nMaxCount > 0 && nFiles.size() >= nMaxCount) { break; } } while (FindNextFileA(hFindFile, &nFindData)); FindClose(hFindFile); hFindFile = INVALID_HANDLE_VALUE; #else DIR *pDir = opendir(strNormalPath.c_str()); if (NULL == pDir) { return false; } // clean old files nFiles.clear(); struct dirent *pItem = NULL; while ((pItem = readdir(pDir)) != NULL) { if (strcmp(pItem->d_name, ".") == 0 || strcmp(pItem->d_name, "..") == 0) { // self or parent continue; } if (!strPattern.empty() && fnmatch(strPattern.c_str(), pItem->d_name, FNM_FILE_NAME | FNM_PERIOD) != 0) { // not match the pattern continue; } std::string strName(pItem->d_name); utils::FileAttribute &nAttr = nFiles[strName]; if (bFillAttr) { std::string strFilePath = utils::String::Format("%s/%s", strNormalPath.c_str(), strName.c_str()); File::GetAttribue(strFilePath, nAttr); } if (nMaxCount > 0 && nFiles.size() >= nMaxCount) { break; } } closedir(pDir); #endif return true; } bool utils::File::GetFileList(const std::string &strDirectory0, utils::FileAttributes &nFiles, bool bFillAttr, size_t nMaxCount) { return utils::File::GetFileList(strDirectory0, std::string(""), nFiles, bFillAttr, nMaxCount); } utils::FileAttribute utils::File::GetAttribue(const std::string &strFile0) { utils::FileAttribute nAttr; std::string strNormalFile = File::RegularPath(strFile0); File::GetAttribue(strNormalFile, nAttr); return nAttr; } bool utils::File::Move(const std::string &strSource, const std::string &strDest, bool bOverwrite) { std::string strNormalSource = File::RegularPath(strSource); std::string strNormalDest = File::RegularPath(strDest); if (bOverwrite && utils::File::IsExist(strDest)) { utils::File::Delete(strDest); } #ifdef WIN32 return ::MoveFileA(strNormalSource.c_str(), strNormalDest.c_str()) == TRUE; #else return rename(strNormalSource.c_str(), strNormalDest.c_str()) == 0; #endif } bool utils::File::Copy(const std::string &strSource, const std::string &strDest, bool bOverwrite) { std::string strNormalSource = File::RegularPath(strSource); std::string strNormalDest = File::RegularPath(strDest); #ifdef WIN32 return ::CopyFileA(strNormalSource.c_str(), strNormalDest.c_str(), !bOverwrite) == TRUE; #else if (strNormalSource == strNormalDest) { utils::set_error_code(ERROR_ALREADY_EXISTS); return false; } else if (!bOverwrite && utils::File::IsExist(strNormalDest)) { utils::set_error_code(ERROR_ALREADY_EXISTS); return false; } utils::File nSource, nDest; uint32_t nErrorCode = ERROR_SUCCESS; bool bSuccess = false; char *pDataBuffer = NULL; const size_t nBufferSize = 102400; do { pDataBuffer = (char *)malloc(nBufferSize); if (NULL == pDataBuffer) { nErrorCode = utils::error_code(); break; } if (!nSource.Open(strNormalSource, utils::File::FILE_M_READ | utils::File::FILE_M_BINARY) || !nDest.Open(strNormalDest, utils::File::FILE_M_WRITE | utils::File::FILE_M_BINARY)) { nErrorCode = utils::error_code(); break; } while (true) { size_t nSizeRead = nSource.Read(pDataBuffer, 1, nBufferSize); if (nSizeRead == 0) { bSuccess = true; break; } if (nDest.Write(pDataBuffer, 1, nSizeRead) != nSizeRead) { nErrorCode = utils::error_code(); break; } } } while (false); if (NULL != pDataBuffer) free(pDataBuffer); if (nSource.IsOpened()) nSource.Close(); if (nDest.IsOpened()) nDest.Close(); if (ERROR_SUCCESS != nErrorCode) { utils::set_error_code(nErrorCode); } return bSuccess; #endif } bool utils::File::IsExist(const std::string &strFile) { std::string strNormalFile = File::RegularPath(strFile); #ifdef WIN32 return ::PathFileExistsA(strNormalFile.c_str()) == TRUE; #else struct stat nFileStat; return stat(strNormalFile.c_str(), &nFileStat) == 0 || errno != ENOENT; #endif } bool utils::File::Delete(const std::string &strFile) { std::string strNormalFile = File::RegularPath(strFile); #ifdef WIN32 return ::DeleteFileA(strNormalFile.c_str()) == TRUE; #else return unlink(strNormalFile.c_str()) == 0; #endif } #ifdef WIN32 #else void dfs_remove_dir() { DIR* cur_dir = opendir("."); struct dirent *ent = NULL; struct stat st; if (!cur_dir) { // LOG_ERROR(""); return; } while ((ent = readdir(cur_dir)) != NULL) { stat(ent->d_name, &st); if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) { continue; } if (S_ISDIR(st.st_mode)) { chdir(ent->d_name); chdir(".."); } remove(ent->d_name); } closedir(cur_dir); } #endif // WIN32 bool utils::File::DeleteFolder(const std::string &path) { std::string strNormalFile = File::RegularPath(path); #ifdef WIN32 SHFILEOPSTRUCT FileOp; FileOp.fFlags = FOF_NOCONFIRMATION | FOF_SILENT; FileOp.hNameMappings = NULL; FileOp.hwnd = NULL; FileOp.lpszProgressTitle = NULL; strNormalFile += '\0'; //sxf add 20170302 meet the FileOp.pFrom input of double null FileOp.pFrom = strNormalFile.c_str(); FileOp.pTo = NULL; FileOp.wFunc = FO_DELETE; int n = SHFileOperation(&FileOp); return n == 0; #else char old_path[100]; if (!path.c_str()) { return false; } getcwd(old_path, 100); if (chdir(path.c_str()) == -1) { //LOG_ERROR("not a dir or access error\n"); return false; } //LOG_INFO("path_raw : %s\n", path_raw); dfs_remove_dir(); chdir(old_path); unlink(old_path); return rmdir(strNormalFile.c_str()) == 0; #endif } std::string utils::File::GetExtension(const std::string &path) { std::string normal_path = RegularPath(path); // check whether url is like "*****?url=*.*.*.*" size_t end_pos = normal_path.find('?'); if (end_pos != std::string::npos) { normal_path = normal_path.substr(0, end_pos); } size_t nPos = normal_path.rfind('.'); if (std::string::npos == nPos || (nPos + 1) == normal_path.size()) { return std::string(""); } return normal_path.substr(nPos + 1); } std::string utils::File::GetTempDirectory() { std::string strPath; #ifdef WIN32 const size_t nMaxPathSize = 10240; strPath.resize(nMaxPathSize, 0); DWORD dwRetVal = GetTempPathA((DWORD)nMaxPathSize - 1, (char *)strPath.c_str()); if (dwRetVal > 0) { strPath.resize(dwRetVal); } else { strPath.clear(); } #else strPath = std::string("/tmp"); #endif while (strPath.size() > 0 && File::PATH_CHAR == strPath[strPath.size() - 1]) { strPath.erase(strPath.size() - 1, 1); } return strPath; } bool utils::File::CreateDir(const std::string &path) { std::string strNormalFile = File::RegularPath(path); #ifdef WIN32 return CreateDirectoryA(strNormalFile.c_str(), NULL) != 0; #else return mkdir(strNormalFile.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0; #endif }
26.869873
162
0.669895
ramonbrugman
cf8675a041ff03cac9068f6c39293bd2adf55684
448
cc
C++
src/calc/errorhandler.cc
madeso/bbcalc
1f5e316ce007b1d1d9b4fc49f9afb03715e5674c
[ "MIT" ]
null
null
null
src/calc/errorhandler.cc
madeso/bbcalc
1f5e316ce007b1d1d9b4fc49f9afb03715e5674c
[ "MIT" ]
null
null
null
src/calc/errorhandler.cc
madeso/bbcalc
1f5e316ce007b1d1d9b4fc49f9afb03715e5674c
[ "MIT" ]
null
null
null
#include "calc/errorhandler.h" #include <fmt/core.h> #include "calc/output.h" void ErrorHandler::Err(const std::string& str) { errors.emplace_back(str); } [[nodiscard]] bool ErrorHandler::HasErr() const { return !errors.empty(); } void ErrorHandler::PrintErrors(Output* output) { output->PrintError("Error while parsing:"); for (const auto& err: errors) { output->PrintError(fmt::format(" - {}", err)); } }
14
54
0.642857
madeso
cf869f7a2b62a398c965eb211f3d2ccc82f9018e
1,012
cpp
C++
Week 4/Week 4 Sample Programs/Pr7-1.cpp
sugamkarki/NAMI-Year-II-Term-I-Software_Engineering
39182816b670dcb75ec322e24b346a4cfeb80be0
[ "Apache-2.0" ]
null
null
null
Week 4/Week 4 Sample Programs/Pr7-1.cpp
sugamkarki/NAMI-Year-II-Term-I-Software_Engineering
39182816b670dcb75ec322e24b346a4cfeb80be0
[ "Apache-2.0" ]
null
null
null
Week 4/Week 4 Sample Programs/Pr7-1.cpp
sugamkarki/NAMI-Year-II-Term-I-Software_Engineering
39182816b670dcb75ec322e24b346a4cfeb80be0
[ "Apache-2.0" ]
null
null
null
/** * @file Pr7-1.cpp * @author your name (you@domain.com) * @brief * @version 0.1 * @date 2020-12-14 * * @copyright Copyright (c) 2020 * */ #include <iostream> /** * @brief * */ using namespace std; int main() { /** * @brief * */ const int NUM_EMPLOYEES = 6; int hours[NUM_EMPLOYEES]; // Get the hours worked by each employee. /** * @brief * */ cout << "Enter the hours worked by " << NUM_EMPLOYEES << " employees: "; cin >> hours[0]; cin >> hours[1]; cin >> hours[2]; cin >> hours[3]; cin >> hours[4]; cin >> hours[5]; /** * @brief * */ // Display the values in the array. cout << "The hours you entered are:"; cout << " " << hours[0]; cout << " " << hours[1]; cout << " " << hours[2]; cout << " " << hours[3]; cout << " " << hours[4]; cout << " " << hours[5] << endl; /** * @brief * */ return 0; }
17.152542
45
0.4417
sugamkarki
cf89a29bc26a7caa9493f3cd67ef36d25d5eecd7
4,419
hh
C++
include/upnpdevice.hh
vbtdung/h-box
9d39aef2adee5384d556a4dcf991d6af262ca92e
[ "MIT" ]
1
2018-09-16T06:13:12.000Z
2018-09-16T06:13:12.000Z
include/upnpdevice.hh
vbtdung/h-box
9d39aef2adee5384d556a4dcf991d6af262ca92e
[ "MIT" ]
null
null
null
include/upnpdevice.hh
vbtdung/h-box
9d39aef2adee5384d556a4dcf991d6af262ca92e
[ "MIT" ]
null
null
null
/* Copyright (c) 2010-2012 Aalto University 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 UPNPDEVICE_HH #define UPNPDEVICE_HH #include <string> #include <list> #include "proxyserver.hh" using namespace std; /** * @class upnp_service * @brief A data structure to represent an UPnP service. * @author Vu Ba Tien Dung * */ class upnp_service { private: string serviceDescription; string serviceName; public: /** * Constructor of upnp_service class * @param serviceDescription this is the service's description XML string * */ upnp_service(const string& serviceDescription) : serviceDescription(serviceDescription) { serviceName = ""; } /** * Constructor of upnp_service class * @param serviceDescription this is the service's description XML string * */ upnp_service(const string& serviceName, const string& serviceDescription) : serviceName(serviceName), serviceDescription(serviceDescription) { } // getters and setters string getServiceName() const { return serviceName; } string getServiceDescription() const { return serviceDescription; } }; /** * @class upnp_device * @brief UPnP device data structure. * @author Dung * */ class upnp_device { private: string STATE; string deviceName; string deviceDescription; list<upnp_service> upnpServices; int remotePort; int localPort; int rewritePort; string ipAddress; bool isMediaServer; tcp_proxy_server* server; public: /** * Constructor of upnp_device class * @param deviceDescription this is the device's description XML string * */ upnp_device(const string& deviceDescription) : deviceDescription(deviceDescription) { deviceName = ""; isMediaServer = false; STATE = "INIT"; remotePort = 0; localPort = 0; server = NULL; } ~upnp_device() { if (server) delete server; } // getters and setters string getState() { return STATE; } void setState(const string& STATE) { this->STATE = STATE; } string getIpAddress() { return ipAddress; } void setIpAddress(string ipAddress) { this->ipAddress = ipAddress; } int getRemotePort() { return remotePort; } void setRemotePort(int remotePort) { this->remotePort = remotePort; } int getLocalPort() { return localPort; } void setLocalPort(int localPort) { this->localPort = localPort; } bool getMediaServer() { return isMediaServer; } void setMediaServer(bool isMediaServer) { this->isMediaServer = isMediaServer; } tcp_proxy_server* getServer() { return server; } void setServer(tcp_proxy_server* server) { this->server = server; } void setDeviceName(string name) { this->deviceName = name; } string getDeviceName() { return deviceName; } void setDeviceDescription(string description) { this->deviceDescription = description; } string getDeviceDescription() { return deviceDescription; } list<upnp_service> getServiceList() { return upnpServices; } void start() { STATE = "READY"; } void addUpnpService(const upnp_service& service) { for (list<upnp_service>::iterator it = upnpServices.begin(); it != upnpServices.end(); it++) if (it->getServiceName() == service.getServiceName()) return; upnpServices.insert(upnpServices.begin(), service); } void removeUpnpService(const string serviceName) { list<upnp_service>::iterator it; for (it = upnpServices.begin(); it != upnpServices.end(); it++) if ((*it).getServiceName() == serviceName) break; upnpServices.erase(it); } }; #endif
29.657718
143
0.742476
vbtdung
cf89b08d967eeaa4b97f2f80785b3611011af143
1,567
cpp
C++
module_05/ex03/ShrubberyCreationForm.cpp
paulahemsi/piscine_cpp
f98feefd8e70308f77442f9b4cb64758676349a7
[ "MIT" ]
4
2021-12-14T18:02:53.000Z
2022-03-24T01:12:38.000Z
module_05/ex02/ShrubberyCreationForm.cpp
paulahemsi/piscine_cpp
f98feefd8e70308f77442f9b4cb64758676349a7
[ "MIT" ]
null
null
null
module_05/ex02/ShrubberyCreationForm.cpp
paulahemsi/piscine_cpp
f98feefd8e70308f77442f9b4cb64758676349a7
[ "MIT" ]
3
2021-11-01T00:34:50.000Z
2022-01-29T19:57:30.000Z
#include "ShrubberyCreationForm.hpp" #include <iostream> #include <fstream> # define V_CYAN "\e[0;38;5;44m" # define RESET "\e[0m" ShrubberyCreationForm::ShrubberyCreationForm(std::string target) : AForm("ShrubberyCreationForm", 145, 137) { this->setTarget(target); std::cout << *this << std::endl; return ; } void ShrubberyCreationForm::_createFile(void)const { std::string line; std::string name = this->getTarget() + "_shrubbery"; std::ofstream outputFile(name.c_str()); std::ifstream inputFile("trees.txt"); if(inputFile && outputFile) { while(getline(inputFile, line)) outputFile << line << std::endl; std::cout << V_CYAN << name << " was sussefuly created and filled with beautifull ASCII trees, go take a look!" << RESET << std::endl; } else std::cout << V_CYAN << "Error creating file" << RESET << std::endl; outputFile.close(); inputFile.close(); } bool ShrubberyCreationForm::execute(Bureaucrat const &executor) const { if (AForm::execute(executor)) { this->_createFile(); return (true); } return (false); } std::ostream &operator<<(std::ostream &outputFile, ShrubberyCreationForm const &i) { outputFile << V_CYAN << i.getName() << std::endl << "Grade to sign: " << i.getGradeToSign() << std::endl << "Grade to execute: " << i.getGradeToExecute() << std::endl << "Target: " << i.getTarget() << std::endl << "Is signed: "; if (i.getIsSigned()) outputFile << "Yes." << RESET << std::endl; else outputFile << "No." << RESET << std::endl; return (outputFile); }
23.742424
136
0.64582
paulahemsi
cf9043d6181db83caf01cf8750abc169b60d67b9
1,983
cpp
C++
update-client-hub/modules/pal-blockdevice/source/arm_uc_pal_blockdevice_mbed.cpp
linlingao/mbed-cloud-client
13e0cef7f9508c10d50f3beb049eafea2af6f17b
[ "Apache-2.0" ]
null
null
null
update-client-hub/modules/pal-blockdevice/source/arm_uc_pal_blockdevice_mbed.cpp
linlingao/mbed-cloud-client
13e0cef7f9508c10d50f3beb049eafea2af6f17b
[ "Apache-2.0" ]
null
null
null
update-client-hub/modules/pal-blockdevice/source/arm_uc_pal_blockdevice_mbed.cpp
linlingao/mbed-cloud-client
13e0cef7f9508c10d50f3beb049eafea2af6f17b
[ "Apache-2.0" ]
null
null
null
//---------------------------------------------------------------------------- // The confidential and proprietary information contained in this file may // only be used by a person authorised under and to the extent permitted // by a subsisting licensing agreement from ARM Limited or its affiliates. // // (C) COPYRIGHT 2017 ARM Limited or its affiliates. // ALL RIGHTS RESERVED // // This entire notice must be reproduced on all copies of this file // and copies of this file may only be made by a person if such person is // permitted to do so under the terms of a subsisting license agreement // from ARM Limited or its affiliates. //---------------------------------------------------------------------------- #include "arm_uc_config.h" #if defined(ARM_UC_FEATURE_PAL_BLOCKDEVICE) && (ARM_UC_FEATURE_PAL_BLOCKDEVICE == 1) #if defined(TARGET_LIKE_MBED) #include "update-client-pal-blockdevice/arm_uc_pal_blockdevice_platform.h" #include "mbed.h" extern BlockDevice *arm_uc_blockdevice; int32_t arm_uc_blockdevice_init(void) { return arm_uc_blockdevice->init(); } uint32_t arm_uc_blockdevice_get_program_size(void) { return arm_uc_blockdevice->get_program_size(); } uint32_t arm_uc_blockdevice_get_erase_size(void) { return arm_uc_blockdevice->get_erase_size(); } int32_t arm_uc_blockdevice_erase(uint64_t address, uint64_t size) { return arm_uc_blockdevice->erase(address, size); } int32_t arm_uc_blockdevice_program(const uint8_t *buffer, uint64_t address, uint32_t size) { return arm_uc_blockdevice->program(buffer, address, size); } int32_t arm_uc_blockdevice_read(uint8_t *buffer, uint64_t address, uint32_t size) { return arm_uc_blockdevice->read(buffer, address, size); } #endif /* #if defined(TARGET_LIKE_MBED) */ #endif /* defined(ARM_UC_FEATURE_PAL_BLOCKDEVICE) */
33.05
84
0.655572
linlingao
cf9c90ec735a4cfa1930fc220d98f50ac5d81adb
1,062
cpp
C++
src/XML/XMLConfigMarkISection.cpp
dmalysiak/Lazarus
925d92843e311d2cd5afd437766563d0d5ab9052
[ "Apache-2.0" ]
1
2019-04-29T05:31:32.000Z
2019-04-29T05:31:32.000Z
src/XML/XMLConfigMarkISection.cpp
dmalysiak/Lazarus
925d92843e311d2cd5afd437766563d0d5ab9052
[ "Apache-2.0" ]
null
null
null
src/XML/XMLConfigMarkISection.cpp
dmalysiak/Lazarus
925d92843e311d2cd5afd437766563d0d5ab9052
[ "Apache-2.0" ]
null
null
null
/* * XMLConfigMarkISection.cpp * * Created on: Feb 11, 2014 * Author: clustro */ #include "XMLConfigMarkISection.h" #include <stdexcept> namespace Lazarus { XMLConfigMarkISection::XMLConfigMarkISection(const std::string& name) { m_name = name; } XMLConfigMarkISection::~XMLConfigMarkISection() { for(auto it : m_parameter_map) delete it.second; } void XMLConfigMarkISection::addParameter(XMLConfigParameter* param) { m_params.appendLast(param); //register the parameter in the lookup map m_parameter_map[param->getName()]=param; } XMLConfigParameter* XMLConfigMarkISection::getParameter(const std::string& name) { XMLConfigParameter* r = NULL; try { r = m_parameter_map.at(name); } catch(std::out_of_range e) { printf("ERROR: Parameter '%s' has not been found in section map\n",name.c_str()); throw; } return r; } Lazarus::FastNCSList<XMLConfigParameter*>* XMLConfigMarkISection::getParameters() { return &m_params; } const std::string& XMLConfigMarkISection::getName() { return m_name; } } /* namespace Lazarus */
17.409836
83
0.731638
dmalysiak
cfa0a7342f3511014fb9e13475eba0260af4b4fa
360
cpp
C++
src/prob_171.cpp
SummerSad/Leet-Code
d0dff86b1b85579738d23d832c795d38c1789672
[ "MIT" ]
null
null
null
src/prob_171.cpp
SummerSad/Leet-Code
d0dff86b1b85579738d23d832c795d38c1789672
[ "MIT" ]
null
null
null
src/prob_171.cpp
SummerSad/Leet-Code
d0dff86b1b85579738d23d832c795d38c1789672
[ "MIT" ]
null
null
null
/* 171. Excel Sheet Column Number * A -> 1 * B -> 2 * C -> 3 * ... * Z -> 26 * AA -> 27 * AB -> 28 * ... */ #include <stdio.h> int titleToNumber(char *s) { int n = 0; for (int i = 0; s[i] != '\0'; ++i) { n *= 26; n += s[i] - 'A' + 1; } return n; } int main() { printf("%d\n", titleToNumber("ZY")); return 0; }
12.413793
38
0.402778
SummerSad
cfa1320511ff52f0a2845363b9d048156e4db389
984
cpp
C++
CodeForces/1191 D.cpp
windcry1/My-ACM-ICPC
b85b1c83b72c6b51731dae946a0df57c31d3e7a1
[ "MIT" ]
null
null
null
CodeForces/1191 D.cpp
windcry1/My-ACM-ICPC
b85b1c83b72c6b51731dae946a0df57c31d3e7a1
[ "MIT" ]
null
null
null
CodeForces/1191 D.cpp
windcry1/My-ACM-ICPC
b85b1c83b72c6b51731dae946a0df57c31d3e7a1
[ "MIT" ]
null
null
null
//Author: WindCry1 //Mail: lanceyu120@gmail.com //Website: https://windcry1.com #include<cstring> #include<cmath> #include<cstdio> #include<cctype> #include<cstdlib> #include<ctime> #include<vector> #include<iostream> #include<string> #include<queue> #include<set> #include<map> #include<algorithm> #include<complex> #include<stack> #include<bitset> #include<iomanip> #define ll long long using namespace std; const double clf=1e-8; const int MMAX=0x7fffffff; const int INF=0xfffffff; const int mod=1e9+7; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); //freopen("C:\\Users\\LENOVO\\Desktop\\in.txt","r",stdin); //freopen("C:\\Users\\LENOVO\\Desktop\\out.txt","w",stdout); ll n,t,m1=0,m2=0,res=0; cin>>n; int flag=0; for(int i=0;i<n;i++) { cin>>t; if(t!=0) flag=1; if(t%2)m1++; else m2++; } if(!flag)res=1; else if(n==1) { if(n%2==0) res=1; else res=0; } else res=(m1*m2)%2; cout<<(res?"cslnb":"sjfnb")<<endl; return 0; }
17.263158
61
0.654472
windcry1
cfa513fb403af0c1b44258b41759fa11b473937c
11,545
cpp
C++
uav_interface/OLED.cpp
NHLStenden-CVDS/TwirreArduino
2832c6d7fa0f46e41bac3bf4124b24446f8dcde8
[ "MIT" ]
null
null
null
uav_interface/OLED.cpp
NHLStenden-CVDS/TwirreArduino
2832c6d7fa0f46e41bac3bf4124b24446f8dcde8
[ "MIT" ]
null
null
null
uav_interface/OLED.cpp
NHLStenden-CVDS/TwirreArduino
2832c6d7fa0f46e41bac3bf4124b24446f8dcde8
[ "MIT" ]
null
null
null
/* * Twirre: architecture for autonomous UAVs using interchangeable commodity components * * Copyright© 2017 Centre of expertise in Computer Vision & Data Science, NHL Stenden University of applied sciences * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <Wire.h> #include "OLED.h" #include "Arduino.h" #ifndef _BV #define _BV(bit) (1 << (bit)) #endif #define TOTALFONTS 2 #include "font/font5x7.h" #include "font/font8x16.h" // Add the font name as declared in the header file. Remove as many as possible to conserve FLASH memory. const unsigned char *OLED::fontsPointer[] = { font5x7, font8x16 }; static uint8_t screenmemory[] = { //SparkFun Electronics LOGO // ROW0, BYTE0 to BYTE63 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ROW1, BYTE64 to BYTE127 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ROW2, BYTE128 to BYTE191 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ROW3, BYTE192 to BYTE255 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ROW4, BYTE256 to BYTE319 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ROW5, BYTE320 to BYTE383 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; OLED::OLED(const char* name) : Device(name, "OLED Display") { //_printstring = reinterpret_cast<uint8_t*>(malloc(sizeof(uint8_t) * (_printstringLength + 1))); _AddVariable("cursorx", &_cursorX); _AddVariable("cursory", &_cursorY); _AddVariable("font", &_font); _AddVariable("printchar", &_printchar); _AddVariable("printflag", &_printflag); _AddVariable("clearflag", &_clearflag); //_AddVariable("printstring", _printstring, &_printstringLength); pinMode(PIN_RESET, OUTPUT); // Set RST pin as OUTPUT digitalWrite(PIN_RESET, HIGH); // Initially set RST HIGH delay(5); // VDD (3.3V) goes high at start, lets just chill for 5 ms digitalWrite(PIN_RESET, LOW); // Bring RST low, reset the display delay(10); // wait 10ms digitalWrite(PIN_RESET, HIGH); // Set RST HIGH, bring out of reset setColor(WHITE); setDrawMode(NORM); // Display Init sequence for 64x48 OLED module command(DISPLAYOFF); // 0xAE command(SETDISPLAYCLOCKDIV); // 0xD5 command(0x80); // the suggested ratio 0x80 command(SETMULTIPLEX); // 0xA8 command(0x2F); command(SETDISPLAYOFFSET); // 0xD3 command(0x0); // no offset command(SETSTARTLINE | 0x0); // line #0 command(CHARGEPUMP); // enable charge pump command(0x14); command(NORMALDISPLAY); // 0xA6 command(DISPLAYALLONRESUME); // 0xA4 command(SEGREMAP | 0x1); command(COMSCANDEC); command(SETCOMPINS); // 0xDA command(0x12); command(SETCONTRAST); // 0x81 command(0x8F); command(SETPRECHARGE); // 0xd9 command(0xF1); command(SETVCOMDESELECT); // 0xDB command(0x40); command(DISPLAYON); //--turn on oled panel clear(ALL); // Erase hardware memory inside the OLED controller to avoid random data in memory. /* for(int i = 0; i < 40 ; i++){ pixel(i,i); pixel(40-i,i); } */ setCursor(1, 2); setFontType(1); print("Twirre V2"); display(); } void OLED::ValuesChanged() { //setFontType(0); //setCursor(0,0); //print(String("") + _printstringLength); //display(); if (_clearflag) { clear(PAGE); _clearflag = 0; } if (_printflag) { //_printstring[_printstringLength] = 0; setFontType(_font); if (_cursorX < 255 && _cursorY < 255) { setCursor(_cursorX, _cursorY); _cursorX = 255; _cursorY = 255; } write(_printchar); //print(reinterpret_cast<const char*>(_printstring)); _printflag = 0; display(); } } void OLED::command(uint8_t c) { Wire1.beginTransmission(I2CADDRESS); Wire1.write(0x00); Wire1.write(c); Wire1.endTransmission(); } void OLED::data(uint8_t c) { Wire1.beginTransmission(I2CADDRESS); Wire1.write(0x40); Wire1.write(c); Wire1.endTransmission(); } void OLED::setPageAddress(uint8_t add) { add = 0xb0 | add; command(add); return; } void OLED::setColumnAddress(uint8_t add) { command((0x10 | (add >> 4)) + 0x02); command((0x0f & add)); return; } void OLED::clear(uint8_t mode) { // uint8_t page=6, col=0x40; if (mode == ALL) { for (int i = 0; i < 8; i++) { setPageAddress(i); setColumnAddress(0); for (int j = 0; j < 0x80; j++) { data(0); } } } else { memset(screenmemory, 0, 384); // (64 x 48) / 8 = 384 //display(); } } void OLED::setCursor(uint8_t x, uint8_t y) { cursorX = x; cursorY = y; } void OLED::pixel(uint8_t x, uint8_t y) { pixel(x, y, foreColor, drawMode); } void OLED::pixel(uint8_t x, uint8_t y, uint8_t color, uint8_t mode) { if ((x < 0) || (x >= LCDWIDTH) || (y < 0) || (y >= LCDHEIGHT)) return; if (mode == XOR) { if (color == WHITE) screenmemory[x + (y / 8) * LCDWIDTH] ^= _BV((y & 0x7)); } else { if (color == WHITE) screenmemory[x + (y / 8) * LCDWIDTH] |= _BV((y & 0x7)); else screenmemory[x + (y / 8) * LCDWIDTH] &= ~_BV((y & 0x7)); } } void OLED::display(void) { uint8_t i, j; for (i = 0; i < 6; i++) { setPageAddress(i); setColumnAddress(0); for (j = 0; j < 0x40; j++) { data(screenmemory[i * 0x40 + j]); } } } void OLED::setColor(uint8_t color) { foreColor = color; } /** \brief Set draw mode. Set current draw mode with NORM or XOR. */ void OLED::setDrawMode(uint8_t mode) { drawMode = mode; } uint8_t OLED::setFontType(uint8_t type) { if ((type >= TOTALFONTS) || (type < 0)) return false; fontType = type; fontWidth = pgm_read_byte(fontsPointer[fontType] + 0); fontHeight = pgm_read_byte(fontsPointer[fontType] + 1); fontStartChar = pgm_read_byte(fontsPointer[fontType] + 2); fontTotalChar = pgm_read_byte(fontsPointer[fontType] + 3); fontMapWidth = (pgm_read_byte(fontsPointer[fontType]+4) * 100) + pgm_read_byte(fontsPointer[fontType] + 5); // two bytes values into integer 16 return true; } size_t OLED::write(uint8_t c) { if (c == '\n') { cursorY += fontHeight; cursorX = 0; } else if (c == '\r') { // skip } else { drawChar(cursorX, cursorY, c, foreColor, drawMode); cursorX += fontWidth + 1; if ((cursorX > (LCDWIDTH - fontWidth))) { cursorY += fontHeight; cursorX = 0; } } return 1; } void OLED::drawChar(uint8_t x, uint8_t y, uint8_t c, uint8_t color, uint8_t mode) { // TODO - New routine to take font of any height, at the moment limited to font height in multiple of 8 pixels uint8_t rowsToDraw, row, tempC; uint8_t i, j, temp; uint16_t charPerBitmapRow, charColPositionOnBitmap, charRowPositionOnBitmap, charBitmapStartPosition; if ((c < fontStartChar) || (c > (fontStartChar + fontTotalChar - 1))) // no bitmap for the required c return; tempC = c - fontStartChar; // each row (in datasheet is call page) is 8 bits high, 16 bit high character will have 2 rows to be drawn rowsToDraw = fontHeight / 8; // 8 is LCD's page size, see SSD1306 datasheet if (rowsToDraw <= 1) rowsToDraw = 1; // the following draw function can draw anywhere on the screen, but SLOW pixel by pixel draw if (rowsToDraw == 1) { for (i = 0; i < fontWidth + 1; i++) { if (i == fontWidth) // this is done in a weird way because for 5x7 font, there is no margin, this code add a margin after col 5 temp = 0; else temp = pgm_read_byte(fontsPointer[fontType]+FONTHEADERSIZE+(tempC*fontWidth)+i); for (j = 0; j < 8; j++) { // 8 is the LCD's page height (see datasheet for explanation) if (temp & 0x1) { pixel(x + i, y + j, color, mode); } else { pixel(x + i, y + j, !color, mode); } temp >>= 1; } } return; } // font height over 8 bit // take character "0" ASCII 48 as example charPerBitmapRow = fontMapWidth / fontWidth; // 256/8 =32 char per row charColPositionOnBitmap = tempC % charPerBitmapRow; // =16 charRowPositionOnBitmap = int(tempC / charPerBitmapRow); // =1 charBitmapStartPosition = (charRowPositionOnBitmap * fontMapWidth * (fontHeight / 8)) + (charColPositionOnBitmap * fontWidth); // each row on LCD is 8 bit height (see datasheet for explanation) for (row = 0; row < rowsToDraw; row++) { for (i = 0; i < fontWidth; i++) { temp = pgm_read_byte(fontsPointer[fontType]+FONTHEADERSIZE+(charBitmapStartPosition+i+(row*fontMapWidth))); for (j = 0; j < 8; j++) { // 8 is the LCD's page height (see datasheet for explanation) if (temp & 0x1) { pixel(x + i, y + j + (row * 8), color, mode); } else { pixel(x + i, y + j + (row * 8), !color, mode); } temp >>= 1; } } } }
29.678663
463
0.661758
NHLStenden-CVDS
cfa6559ed374df5ed9d3535040d86d09a4e33776
1,810
hpp
C++
extlibs/include/Jopnal/Utility/DateTime.hpp
Jopnal/Jopmodel
cfd50b9fd24eaf63497bf5bed883f0b831d9ad65
[ "Zlib" ]
2
2016-07-16T17:21:10.000Z
2016-08-09T11:41:33.000Z
extlibs/include/Jopnal/Utility/DateTime.hpp
Jopnal/Jopmodel
cfd50b9fd24eaf63497bf5bed883f0b831d9ad65
[ "Zlib" ]
null
null
null
extlibs/include/Jopnal/Utility/DateTime.hpp
Jopnal/Jopmodel
cfd50b9fd24eaf63497bf5bed883f0b831d9ad65
[ "Zlib" ]
null
null
null
// Jopnal Engine C++ Library // Copyright (c) 2016 Team Jopnal // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgement in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. ////////////////////////////////////////////// #ifndef JOP_DATETIME_HPP #define JOP_DATETIME_HPP // Headers #include <Jopnal/Header.hpp> #include <string> ////////////////////////////////////////////// namespace jop { class JOP_API DateTime { public: struct Date { uint16 year; uint8 month; uint8 day; }; struct Time { uint8 hour; uint8 minute; uint8 second; }; public: DateTime(); DateTime& update(const bool date = true, const bool time = true); const Date& getDate() const; const Time& getTime() const; bool operator ==(const DateTime& right) const; bool operator !=(const DateTime& right) const; private: Date m_date; Time m_time; }; } #endif
24.133333
77
0.61105
Jopnal
cfa6e83d21638c08d9c9441c4e5b89bbed2ebb51
302
cpp
C++
src/main.cpp
z3t0/Game
cda8dccebd488519d4a018c0d11cccc69e5e5859
[ "MIT" ]
null
null
null
src/main.cpp
z3t0/Game
cda8dccebd488519d4a018c0d11cccc69e5e5859
[ "MIT" ]
null
null
null
src/main.cpp
z3t0/Game
cda8dccebd488519d4a018c0d11cccc69e5e5859
[ "MIT" ]
null
null
null
// Main file // Copyright (C) Rafi Khan 2016 // Includes #include "Game.hpp" #include <iostream> // Defines #define WINDOW_WIDTH 800 #define WINDOW_HEIGHT 600 #define WINDOW_TITLE "Game" int main() { Game game (WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE); game.update(); return 0; }
13.130435
58
0.688742
z3t0
bbb92752b7acc8ba023e6962380f66d29ec08c1b
2,850
cpp
C++
lumeview/src/lumeview/cmd/active_command_queues.cpp
miho/lume
c0bddf68228af2817dc31c27c7fbc618e80c6017
[ "BSD-2-Clause" ]
6
2018-09-11T12:05:55.000Z
2021-11-27T11:56:33.000Z
lumeview/src/lumeview/cmd/active_command_queues.cpp
miho/lume
c0bddf68228af2817dc31c27c7fbc618e80c6017
[ "BSD-2-Clause" ]
2
2019-10-06T21:05:15.000Z
2019-10-08T09:09:30.000Z
lumeview/src/lumeview/cmd/active_command_queues.cpp
miho/lume
c0bddf68228af2817dc31c27c7fbc618e80c6017
[ "BSD-2-Clause" ]
2
2018-12-25T00:57:17.000Z
2019-10-06T21:05:39.000Z
// This file is part of lumeview, a lightweight viewer for unstructured meshes // // Copyright (C) 2019 Sebastian Reiter <s.b.reiter@gmail.com> // 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. // // 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 HOLDERS 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 <map> #include <vector> #include <lumeview/cmd/active_command_queues.h> #include <lumeview/cmd/command_queue.h> namespace { // We use a map here so that we can set the value to nullptr without affecting an ongoing iteration. std::map <lumeview::cmd::CommandQueue*, lumeview::cmd::CommandQueue*> s_activeQueues; std::vector <lumeview::cmd::CommandQueue*> s_addedQueues; std::vector <lumeview::cmd::CommandQueue*> s_removedQueues; } namespace lumeview::cmd { void ActiveCommandQueues::tick () { for (auto queue : s_removedQueues) { s_activeQueues.erase (queue); } s_removedQueues.clear (); for (auto queue : s_addedQueues) { s_activeQueues.insert (std::make_pair (queue, queue)); } s_addedQueues.clear (); if (s_activeQueues.empty ()) { return; } for (auto entry : s_activeQueues) { if (entry.second != nullptr) { entry.second->tick (); } } } void ActiveCommandQueues::add (CommandQueue* queue) { s_addedQueues.push_back (queue); } void ActiveCommandQueues::remove (CommandQueue* queue) { auto const iter = s_activeQueues.find (queue); if (iter != s_activeQueues.end ()) { iter->second = nullptr; } s_removedQueues.push_back (queue); } }// end of namespace lumeview::cmd
35.625
104
0.701404
miho
bbc1bbb95bd10f881dd3d39f332bc8700fff32ce
3,881
cpp
C++
test/unit_test/sql_test.cpp
KaiserLancelot/klib
5fe789c24dae999ab3512e5882f14a194dd34699
[ "MIT" ]
1
2022-02-28T12:31:44.000Z
2022-02-28T12:31:44.000Z
test/unit_test/sql_test.cpp
KaiserLancelot/klib
5fe789c24dae999ab3512e5882f14a194dd34699
[ "MIT" ]
null
null
null
test/unit_test/sql_test.cpp
KaiserLancelot/klib
5fe789c24dae999ab3512e5882f14a194dd34699
[ "MIT" ]
1
2021-11-06T14:23:21.000Z
2021-11-06T14:23:21.000Z
#include <cstdint> #include <filesystem> #include <iostream> #include <string> #include <vector> #include <catch2/catch.hpp> #include "klib/sql.h" #include "klib/util.h" TEST_CASE("sql", "[sql]") { { klib::SqlDatabase db("test.db", klib::SqlDatabase::ReadWrite, "6K4VpQY5&b*WRR^Y"); REQUIRE_NOTHROW(db.transaction()); REQUIRE_NOTHROW(db.drop_table_if_exists("Cars")); REQUIRE_NOTHROW(db.exec("CREATE TABLE Cars(Name TEXT, Price INT);")); std::vector<std::string> names = {"Audi", "Mercedes", "Skoda", "Volvo", "Bentley", "Citroen", "Hummer", "Volkswagen"}; std::vector<std::int32_t> prices = {52642, 57127, 9000, 29000, 350000, 21000, 41400, 21600}; klib::SqlQuery query(db); REQUIRE_NOTHROW( query.prepare("INSERT INTO Cars(Name, Price) VALUES(?, ?);")); for (std::size_t i = 0; i < 8; ++i) { REQUIRE_NOTHROW(query.bind(1, names[i])); REQUIRE_NOTHROW(query.bind(2, prices[i])); REQUIRE(query.exec() == 1); } REQUIRE(db.exec("UPDATE Cars SET Name='aaa' WHERE Price > 50000") == 3); REQUIRE_NOTHROW(db.commit()); REQUIRE_NOTHROW(db.transaction()); for (std::size_t i = 0; i < 8; ++i) { REQUIRE_NOTHROW(query.bind(1, names[i])); REQUIRE_NOTHROW(query.bind(2, prices[i])); REQUIRE(query.exec() == 1); } REQUIRE_NOTHROW(db.rollback()); REQUIRE_NOTHROW(db.vacuum()); REQUIRE(std::filesystem::exists("test.db")); REQUIRE(db.table_exists("Cars")); REQUIRE(db.table_line_count("Cars") == 8); REQUIRE_NOTHROW(query.prepare("SELECT * FROM Cars WHERE Price > ?")); REQUIRE_NOTHROW(query.bind(1, 50000)); while (query.next()) { REQUIRE(query.get_column_name(0) == "Name"); REQUIRE(query.get_column_name(1) == "Price"); REQUIRE_NOTHROW(std::cout << query.get_column(0).as_text() << ' '); REQUIRE_NOTHROW(std::cout << query.get_column(1).as_int32() << '\n'); } std::cout << '\n'; REQUIRE_NOTHROW(query.prepare("SELECT * FROM Cars")); while (query.next()) { REQUIRE_NOTHROW(std::cout << query.get_column(0).as_text() << ' '); REQUIRE_NOTHROW(std::cout << query.get_column(1).as_int32() << '\n'); } std::cout << '\n'; while (query.next()) { REQUIRE_NOTHROW(std::cout << query.get_column(0).as_text() << ' '); REQUIRE_NOTHROW(std::cout << query.get_column(1).as_int32() << '\n'); } } { klib::SqlDatabase db("test.db", klib::SqlDatabase::ReadWrite, "6K4VpQY5&b*WRR^Y"); REQUIRE(db.table_exists("Cars")); REQUIRE(db.table_line_count("Cars") == 8); klib::SqlQuery query(db); REQUIRE_NOTHROW(query.prepare("SELECT * FROM Cars")); std::cout << '\n'; while (query.next()) { REQUIRE_NOTHROW(std::cout << query.get_column(0).as_text() << ' '); REQUIRE_NOTHROW(std::cout << query.get_column(1).as_int32() << '\n'); } } } TEST_CASE("blob", "[sql]") { klib::SqlDatabase db("test2.db", klib::SqlDatabase::ReadWrite, ""); REQUIRE_NOTHROW(db.transaction()); REQUIRE_NOTHROW(db.drop_table_if_exists("BlobTest")); REQUIRE_NOTHROW(db.exec("CREATE TABLE BlobTest(Data BLOB);")); REQUIRE(std::filesystem::exists("zlib-v1.2.11.tar.gz")); std::string blob = klib::read_file("zlib-v1.2.11.tar.gz", true); klib::SqlQuery query(db); REQUIRE_NOTHROW(query.prepare("INSERT INTO BlobTest(Data) VALUES(?);")); REQUIRE_NOTHROW(query.bind(1, std::data(blob), std::size(blob))); REQUIRE(query.exec() == 1); REQUIRE_NOTHROW(db.commit()); REQUIRE_NOTHROW(query.prepare("SELECT * FROM BlobTest")); REQUIRE(query.next()); REQUIRE(query.get_column(0).as_blob() == blob); REQUIRE_NOTHROW(query.finalize()); REQUIRE_NOTHROW(db.vacuum()); }
33.456897
76
0.605514
KaiserLancelot
bbc427345988366e65b5972a4f9f05ea6d5a3cb6
1,678
cc
C++
art/Framework/Modules/RandomNumberSaver_module.cc
drbenmorgan/fnal-art
31b8a5c76af364bbbfd8960bc2039b4f3cd47ae3
[ "BSD-3-Clause" ]
null
null
null
art/Framework/Modules/RandomNumberSaver_module.cc
drbenmorgan/fnal-art
31b8a5c76af364bbbfd8960bc2039b4f3cd47ae3
[ "BSD-3-Clause" ]
16
2021-11-05T14:29:41.000Z
2022-03-24T15:43:39.000Z
art/Framework/Modules/RandomNumberSaver_module.cc
drbenmorgan/fnal-art
31b8a5c76af364bbbfd8960bc2039b4f3cd47ae3
[ "BSD-3-Clause" ]
2
2020-09-26T01:37:11.000Z
2021-05-03T13:02:24.000Z
// vim: set sw=2 expandtab : // // Store state of the RandomNumberGenerator service into the event. // #include "art/Framework/Core/ModuleMacros.h" #include "art/Framework/Core/ProcessingFrame.h" #include "art/Framework/Core/SharedProducer.h" #include "art/Framework/Principal/Event.h" #include "art/Framework/Services/Optional/RandomNumberGenerator.h" #include "fhiclcpp/types/Atom.h" #include <memory> #include <vector> using namespace std; using namespace fhicl; namespace art { class RandomNumberSaver : public SharedProducer { public: struct Config { Atom<bool> debug{Name{"debug"}, false}; }; using Parameters = Table<Config>; explicit RandomNumberSaver(Parameters const&, ProcessingFrame const&); private: void produce(Event&, ProcessingFrame const&) override; // When true makes produce call rng->print_(). bool const debug_; }; RandomNumberSaver::RandomNumberSaver(Parameters const& config, ProcessingFrame const&) : SharedProducer{config}, debug_{config().debug()} { produces<vector<RNGsnapshot>>(); if (debug_) { // If debugging information is desired, serialize so that the // printing is not garbled. serialize<InEvent>(); } else { async<InEvent>(); } } void RandomNumberSaver::produce(Event& e, ProcessingFrame const& frame) { auto const sid = frame.scheduleID(); auto rng = frame.serviceHandle<RandomNumberGenerator const>(); e.put(make_unique<vector<RNGsnapshot>>(rng->accessSnapshot_(sid))); if (debug_) { rng->print_(); } } } // namespace art DEFINE_ART_MODULE(art::RandomNumberSaver)
26.634921
74
0.68534
drbenmorgan
bbc46436074f66ad626ed22ae76c5725ba929f9e
741
hh
C++
F/src/transformation.hh
vaginessa/Ctrl-Alt-Test
b981ebdbc6b0678f004c4052d70ebb56af2d89a0
[ "Apache-2.0" ]
114
2015-04-14T10:30:05.000Z
2021-06-11T02:57:59.000Z
F/src/transformation.hh
vaginessa/Ctrl-Alt-Test
b981ebdbc6b0678f004c4052d70ebb56af2d89a0
[ "Apache-2.0" ]
null
null
null
F/src/transformation.hh
vaginessa/Ctrl-Alt-Test
b981ebdbc6b0678f004c4052d70ebb56af2d89a0
[ "Apache-2.0" ]
11
2015-07-26T02:11:32.000Z
2020-04-02T21:06:15.000Z
// // 3D transformation // #ifndef TRANSFORMATION_HH # define TRANSFORMATION_HH #include "quaternion.hh" #include "vector.hh" struct Transformation { quaternion q; vector3f v; Transformation(const quaternion & q, const vector3f & v): q(q), v(v) {} Transformation() {} }; Transformation operator * (const Transformation & t1, const Transformation & t2); Transformation interpolate(const Transformation & t1, const Transformation & t2, float weight); Transformation interpolate(const Transformation & t1, const Transformation & t2, const Transformation & t3, const Transformation & t4, float weights[4]); void getFromModelView(Transformation & t); #endif // TRANSFORMATION_HH
19.5
59
0.700405
vaginessa
bbc58aee5660d9dc5d34996e548f5e2d89307840
1,077
cpp
C++
clang-tools-extra/test/clang-reorder-fields/FieldDependencyWarningDerived.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
clang-tools-extra/test/clang-reorder-fields/FieldDependencyWarningDerived.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang-tools-extra/test/clang-reorder-fields/FieldDependencyWarningDerived.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
// RUN: clang-reorder-fields -record-name bar::Derived -fields-order z,y %s -- 2>&1 | FileCheck --check-prefix=CHECK-MESSAGES %s // FIXME: clang-reorder-fields should provide -verify mode to make writing these checks // easier and more accurate, for now we follow clang-tidy's approach. namespace bar { struct Base { int x; int p; }; class Derived : public Base { public: Derived(long ny); Derived(char nz); private: long y; char z; }; Derived::Derived(long ny) : Base(), y(ny), z(static_cast<char>(y)) // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: reordering field y after z makes y uninitialized when used in init expression {} Derived::Derived(char nz) : Base(), y(nz), // Check that base class fields are correctly ignored in reordering checks // x has field index 1 and so would improperly warn if this wasn't the case since the command for this file swaps field indexes 1 and 2 z(x) // CHECK-MESSAGES-NOT: :[[@LINE-1]]:3: warning: reordering field x after z makes x uninitialized when used in init expression {} } // namespace bar
29.108108
137
0.697307
medismailben
bbc7b559c1c6530d70446f6bd8bd5d7db83e2534
950
cpp
C++
LeetCode/100/78.cpp
K-ona/C-_Training
d54970f7923607bdc54fc13677220d1b3daf09e5
[ "Apache-2.0" ]
null
null
null
LeetCode/100/78.cpp
K-ona/C-_Training
d54970f7923607bdc54fc13677220d1b3daf09e5
[ "Apache-2.0" ]
null
null
null
LeetCode/100/78.cpp
K-ona/C-_Training
d54970f7923607bdc54fc13677220d1b3daf09e5
[ "Apache-2.0" ]
null
null
null
// created by Kona @VSCode #include <algorithm> #include <iostream> #include <map> #include <string> #include <queue> #include <vector> #include <string.h> #define LOCAL_TEST typedef long long ll; using std::cin; using std::cout; using std::endl; using std::map; using std::queue; using std::string; using std::vector; class Solution { public: vector<vector<int>> subsets(vector<int>& nums) { int n = nums.size(); vector<vector<int>> res; res.reserve(1 << n); for (int vis = (1 << n) - 1; vis >= 0; --vis) { vector<int> tmp; tmp.reserve(10); for (int i = 0; i < n; ++i) { if (vis & (1 << i)) tmp.push_back(nums[i]); } res.push_back(std::move(tmp)); } return res; } }; int main() { std::ios_base::sync_with_stdio(false); #ifdef LOCAL_TEST freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif /* code */ return 0; }
19.791667
53
0.578947
K-ona
bbca9eb05c36ad544f2a78cb82deed6307ef8ea1
912
cpp
C++
test/src/test_kvector.cpp
OrhanKupusoglu/find-first-id
025061782cfb6b1300bebeaa1f3c0e4df27211a5
[ "MIT" ]
1
2020-06-14T20:27:53.000Z
2020-06-14T20:27:53.000Z
test/src/test_kvector.cpp
OrhanKupusoglu/find-first-id
025061782cfb6b1300bebeaa1f3c0e4df27211a5
[ "MIT" ]
null
null
null
test/src/test_kvector.cpp
OrhanKupusoglu/find-first-id
025061782cfb6b1300bebeaa1f3c0e4df27211a5
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "../include/kcommon_tests.h" #include "../../src/include/kvector.h" kcommon_tests<kupid::kvector> test_kvector{"kupid::kvector"}; TEST(TestKVector, SizeZero) { test_kvector.test_size_zero(); } TEST(TestKVector, SizeOne) { test_kvector.test_size_one(); } TEST(TestKVector, SizeTwo) { test_kvector.test_size_two(); } TEST(TestKVector, ClearUseHalf) { test_kvector.test_clear_use_half(); } TEST(TestKVector, SizeSmall) { test_kvector.test_size_small(); } TEST(TestKVector, SizeMedium) { test_kvector.test_size_medium(); } TEST(TestKVector, SizeLarge) { test_kvector.test_size_large(); } #ifdef TEST_XLARGE TEST(TestKVector, SizeXLarge) { test_kvector.test_size_xlarge(); } #endif TEST(TestKVector, RandomUnordered) { test_kvector.test_random_unordered(); } TEST(TestKVector, RandomOrdered) { test_kvector.test_random_ordered(); }
19
61
0.736842
OrhanKupusoglu
bbcab6e5eb97ed4e4c7d6b2bca67ec20f072dc1f
1,690
tcc
C++
ulmblas/level2/hpur2.tcc
sneha0401/ulmBLAS
2b7665c6abc1784fe4041febd9d12de519ef4f08
[ "BSD-3-Clause" ]
95
2015-05-14T15:21:44.000Z
2022-03-17T08:02:08.000Z
ulmblas/level2/hpur2.tcc
sneha0401/ulmBLAS
2b7665c6abc1784fe4041febd9d12de519ef4f08
[ "BSD-3-Clause" ]
4
2020-06-25T14:59:49.000Z
2022-02-16T12:45:00.000Z
ulmblas/level2/hpur2.tcc
sneha0401/ulmBLAS
2b7665c6abc1784fe4041febd9d12de519ef4f08
[ "BSD-3-Clause" ]
40
2015-09-14T02:43:43.000Z
2021-12-26T11:43:36.000Z
#ifndef ULMBLAS_LEVEL2_HPUR2_TCC #define ULMBLAS_LEVEL2_HPUR2_TCC 1 #include <ulmblas/auxiliary/conjugate.h> #include <ulmblas/auxiliary/real.h> #include <ulmblas/level1extensions/axpy2v.h> #include <ulmblas/level2/hpur2.h> namespace ulmBLAS { template <typename IndexType, typename Alpha, typename TX, typename TY, typename TA> void hpur2(IndexType n, bool conj, const Alpha &alpha, const TX *x, IndexType incX, const TY *y, IndexType incY, TA *A) { if (n==0 || alpha==Alpha(0)) { return; } if (!conj) { for (IndexType j=0; j<n; ++j) { axpy2v(j+1, alpha*conjugate(y[j*incY]), conjugate(alpha*x[j*incX]), x, incX, y, incY, A, IndexType(1)); A[j] = real(A[j]); A += j+1; } } else { for (IndexType j=0; j<n; ++j) { acxpy(j+1, conjugate(alpha)*y[j*incY], x, incX, A, IndexType(1)); acxpy(j+1, alpha*x[j*incX], y, incY, A, IndexType(1)); A[j] = real(A[j]); A += j+1; } } } template <typename IndexType, typename Alpha, typename TX, typename TY, typename TA> void hpur2(IndexType n, const Alpha &alpha, const TX *x, IndexType incX, const TY *y, IndexType incY, TA *A) { hpur2(n, false, alpha, x, incX, y, incY, A); } } // namespace ulmBLAS #endif // ULMBLAS_LEVEL2_HPUR2_TCC
23.802817
71
0.478107
sneha0401
bbcb7f036369bf66a496a344ac3d96e25f6c73be
6,964
cpp
C++
common/Uart.cpp
loliot/lot-API
cec96c68450c1f3730480a8c142dc98e0fd35f17
[ "MIT" ]
2
2021-03-07T22:54:42.000Z
2021-07-07T23:56:10.000Z
common/Uart.cpp
loliot/lot-API
cec96c68450c1f3730480a8c142dc98e0fd35f17
[ "MIT" ]
16
2019-10-10T06:37:59.000Z
2020-01-29T09:56:06.000Z
common/Uart.cpp
loliot/lot-API
cec96c68450c1f3730480a8c142dc98e0fd35f17
[ "MIT" ]
20
2019-10-08T11:16:11.000Z
2020-01-05T13:26:45.000Z
/* * MIT License * Copyright (c) 2019-2020 Hyeonki Hong <hhk7734@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "../Uart.h" #include "../lot.h" #include <stdio.h> // sprintf() #include <unistd.h> // write(), close(), usleep() #include <string.h> // strcpy(), strlen() #include <fcntl.h> // open(), fcntl() #include <termios.h> #include <sys/ioctl.h> // ioctl() #include <errno.h> // errno #include <stdexcept> static inline ssize_t unistd_write( int fd, const void *buf, size_t n ) { return write( fd, buf, n ); } namespace lot { Uart::Uart( uint16_t bus_num ) : m_fd( -1 ) { sprintf( m_device, "%s%d", "/dev/ttyS", bus_num ); init(); } Uart::Uart( const char *device ) : m_fd( -1 ) { if( device != NULL ) { strcpy( m_device, device ); } init(); } Uart::~Uart() { close( m_fd ); } void Uart::baudrate( uint32_t baud_rate ) { struct termios options; speed_t baud_rate_ = B0; // clang-format off switch( baud_rate ) { case 50: baud_rate_ = B50; break; case 75: baud_rate_ = B75; break; case 110: baud_rate_ = B110; break; case 134: baud_rate_ = B134; break; case 150: baud_rate_ = B150; break; case 200: baud_rate_ = B200; break; case 300: baud_rate_ = B300; break; case 600: baud_rate_ = B600; break; case 1200: baud_rate_ = B1200; break; case 1800: baud_rate_ = B1800; break; case 2400: baud_rate_ = B2400; break; case 4800: baud_rate_ = B4800; break; case 9600: baud_rate_ = B9600; break; case 19200: baud_rate_ = B19200; break; case 38400: baud_rate_ = B38400; break; case 57600: baud_rate_ = B57600; break; case 115200: baud_rate_ = B115200; break; case 230400: baud_rate_ = B230400; break; case 460800: baud_rate_ = B460800; break; case 500000: baud_rate_ = B500000; break; case 576000: baud_rate_ = B576000; break; case 921600: baud_rate_ = B921600; break; case 1000000: baud_rate_ = B1000000; break; case 1152000: baud_rate_ = B1152000; break; case 1500000: baud_rate_ = B1500000; break; case 2000000: baud_rate_ = B2000000; break; case 2500000: baud_rate_ = B2500000; break; case 3000000: baud_rate_ = B3000000; break; case 3500000: baud_rate_ = B3500000; break; case 4000000: baud_rate_ = B4000000; break; default: baud_rate_ = B115200; Log::warning( "The baudrate is invalid. It will set default buadrate(115200).\r\n" ); break; }; // clang-format on tcgetattr( m_fd, &options ); cfsetispeed( &options, baud_rate_ ); cfsetospeed( &options, baud_rate_ ); tcsetattr( m_fd, TCSANOW, &options ); usleep( 10000 ); } void Uart::mode( UartMode uart_mode ) { struct termios options; tcgetattr( m_fd, &options ); // Raw level read/write. Non-standard. cfmakeraw( &options ); options.c_cc[VMIN] = 0; options.c_cc[VTIME] = 100; // timeout = 10s // Ignore Error. options.c_iflag |= IGNPAR; // Disable implementation-defined output processing. options.c_oflag &= ~OPOST; options.c_cflag |= ( CLOCAL | CREAD ); options.c_cflag &= ~CSIZE; switch( uart_mode % 4 ) { case 0: options.c_cflag |= CS5; case 1: options.c_cflag |= CS6; case 2: options.c_cflag |= CS7; case 3: options.c_cflag |= CS8; } switch( static_cast<uint8_t>( uart_mode / 8 ) ) { case 0: // None options.c_cflag &= ~PARENB; options.c_iflag &= ~INPCK; break; case 1: // Even options.c_iflag |= INPCK; options.c_cflag |= PARENB; options.c_cflag &= ~PARODD; break; case 2: // Odd options.c_iflag |= INPCK; options.c_cflag |= PARENB; options.c_cflag |= PARODD; break; case 3: // Mark break; case 4: // Space break; } switch( static_cast<uint8_t>( uart_mode / 4 ) % 2 ) { case 0: options.c_cflag &= ~CSTOPB; break; case 1: options.c_cflag |= CSTOPB; break; } options.c_lflag &= ~( ISIG | ICANON | ECHO | ECHOE ); tcsetattr( m_fd, TCSANOW, &options ); usleep( 10000 ); } uint16_t Uart::available( void ) { int result; if( ioctl( m_fd, FIONREAD, &result ) < 0 ) { Log::warning( "Failed to read UART RX buffer size.\r\n" ); return 0; } return result; } void Uart::transmit( uint8_t *buffer, uint16_t size ) { unistd_write( m_fd, buffer, size ); } void Uart::transmit( uint8_t data ) { unistd_write( m_fd, &data, 1 ); } void Uart::receive( uint8_t *buffer, uint16_t size ) { if( read( m_fd, buffer, size ) != size ) { Log::warning( "Failed to read UART RX buffer.\r\n" ); } } uint8_t Uart::receive( void ) { uint8_t data; receive( &data, 1 ); return data; } void Uart::init( void ) { // No controlling tty, Enables nonblocking mode. m_fd = open( m_device, O_RDWR | O_NOCTTY | O_NONBLOCK ); if( m_fd < 0 ) { Log::error( "Failed to open %s.\r\n", m_device ); throw std::runtime_error( strerror( errno ) ); } // Explicit reset due to O_NONBLOCK. fcntl( m_fd, F_SETFL, O_RDWR ); baudrate( 115200 ); mode( lot::U8N1 ); } } // namespace lot
27.309804
97
0.572229
loliot
bbd36d23c059c09b16b1a684061a261146c07123
802
cpp
C++
89-Gray Code.cpp
iaxax/leetcode
47f0ed33fe943c40c31e237453b82731688b70ce
[ "MIT" ]
null
null
null
89-Gray Code.cpp
iaxax/leetcode
47f0ed33fe943c40c31e237453b82731688b70ce
[ "MIT" ]
null
null
null
89-Gray Code.cpp
iaxax/leetcode
47f0ed33fe943c40c31e237453b82731688b70ce
[ "MIT" ]
null
null
null
class Solution { public: vector<int> grayCode(int n) { vector<int> v(n + 1, 1); for (int i = 1; i <= n; ++i) { v[i] = v[i - 1] * 2; } vector<int> result = {0}; result.reserve(v[n]); for (int i = 0; i < n; ++i) { int sz = result.size(); for (int j = sz - 1; j >= 0; --j) { result.push_back(result[j] + v[i]); } } return result; } }; // Excellent but not understandable solution class Solution { public: vector<int> grayCode(int n) { int sz = 1 << n; vector<int> result(sz); for (int i = 0; i < sz; ++i) { result[i] = (i ^ (i >> 1)); } return result; } };
23.588235
52
0.387781
iaxax
bbd3b343fce753023dfc6462e0fb3caa48a0136e
1,415
cpp
C++
src/frontend/Gui/Gui_textures.cpp
bpapaspyros/RobSim
b126e892910085fde4d14f50380b8db44fa7cd24
[ "MIT" ]
null
null
null
src/frontend/Gui/Gui_textures.cpp
bpapaspyros/RobSim
b126e892910085fde4d14f50380b8db44fa7cd24
[ "MIT" ]
null
null
null
src/frontend/Gui/Gui_textures.cpp
bpapaspyros/RobSim
b126e892910085fde4d14f50380b8db44fa7cd24
[ "MIT" ]
null
null
null
#include <iostream> #include <SOIL/SOIL.h> #include "frontend/Gui/Gui_textures.h" Gui_textures::Gui_textures(){ background = "../res/world/moon.jpg"; } /*- -------------------------------------------------------------- -*/ GLuint Gui_textures::loadEpicTex(std::string filename){ GLuint tex; tex = SOIL_load_OGL_texture( filename.c_str(), SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT | SOIL_FLAG_INVERT_Y ); if( !tex ) { std::cerr << "Could not load the texture from file: " << filename << std::endl; } return tex; } /*- -------------------------------------------------------------- -*/ void Gui_textures::drawEpicBackground() { glEnable(GL_TEXTURE_2D); glBegin(GL_QUADS); glColor3f(1, 1, 1); glTexCoord2f(0.0f, 0.0f); glVertex3f(-30, -30, 0); glTexCoord2f(1.0f, 0.0f); glVertex3f( 30, -30, 0); glTexCoord2f(1.0f, 1.0f); glVertex3f( 30, 30, 0); glTexCoord2f(0.0f, 1.0f); glVertex3f(-30, 30, 0); glEnd(); glDisable(GL_TEXTURE_2D); } /*- -------------------------------------------------------------- -*/
24.824561
91
0.475618
bpapaspyros
bbd6b046403f207d4c30199808bc32c1844dd87a
462
cpp
C++
Smallest_Numbers_of_Notes.cpp
omkarugale7/codechef-questions
05cb8f4f9e5bded9ca3b8ee4e913bdd314cb0585
[ "MIT" ]
null
null
null
Smallest_Numbers_of_Notes.cpp
omkarugale7/codechef-questions
05cb8f4f9e5bded9ca3b8ee4e913bdd314cb0585
[ "MIT" ]
null
null
null
Smallest_Numbers_of_Notes.cpp
omkarugale7/codechef-questions
05cb8f4f9e5bded9ca3b8ee4e913bdd314cb0585
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int t; cin >> t; for (int i = 0; i < t; i++) { int n, ans = 0, j = 0; cin >> n; int re[6] = {100, 50, 10, 5, 2, 1}; while (n > 0) { int b = n / re[j]; if (b != 0) { ans += b; n -= b * re[j]; } j++; } cout << ans << endl; } return 0; }
17.111111
43
0.292208
omkarugale7
bbd8e68c1fd78dd58ba6e7301382aa1174829bbe
1,552
cpp
C++
test/unit-tests/allocator/context_manager/gc_ctx/gc_ctx_test.cpp
so931/poseidonos
2aa82f26bfbd0d0aee21cd0574779a655634f08c
[ "BSD-3-Clause" ]
1
2022-02-07T23:30:50.000Z
2022-02-07T23:30:50.000Z
test/unit-tests/allocator/context_manager/gc_ctx/gc_ctx_test.cpp
so931/poseidonos
2aa82f26bfbd0d0aee21cd0574779a655634f08c
[ "BSD-3-Clause" ]
null
null
null
test/unit-tests/allocator/context_manager/gc_ctx/gc_ctx_test.cpp
so931/poseidonos
2aa82f26bfbd0d0aee21cd0574779a655634f08c
[ "BSD-3-Clause" ]
null
null
null
#include "src/allocator/context_manager/gc_ctx/gc_ctx.h" #include <gtest/gtest.h> #include "test/unit-tests/allocator/context_manager/block_allocation_status_mock.h" using testing::NiceMock; namespace pos { TEST(GcCtx, GetCurrentGcMode_TestModeNoGC) { // given NiceMock<MockBlockAllocationStatus> allocStatus; GcCtx gcCtx(&allocStatus); gcCtx.SetNormalGcThreshold(10); gcCtx.SetUrgentThreshold(5); gcCtx.GetCurrentGcMode(8); // when gcCtx.GetCurrentGcMode(13); } TEST(GcCtx, GetCurrentGcMode_TestGetCurrentGcMode_ByNumberOfFreeSegment) { // given NiceMock<MockBlockAllocationStatus> blockAllocStatus; GcCtx* gcCtx = new GcCtx(&blockAllocStatus); gcCtx->SetNormalGcThreshold(10); gcCtx->SetUrgentThreshold(5); // when 1. GcMode ret = gcCtx->GetCurrentGcMode(11); // then 1. EXPECT_EQ(MODE_NO_GC, ret); // when 2. ret = gcCtx->GetCurrentGcMode(10); // then 2. EXPECT_EQ(MODE_NORMAL_GC, ret); // when 3. ret = gcCtx->GetCurrentGcMode(9); // then 3. EXPECT_EQ(MODE_NORMAL_GC, ret); EXPECT_CALL(blockAllocStatus, ProhibitUserBlockAllocation); // when 4. ret = gcCtx->GetCurrentGcMode(5); // then 4. EXPECT_EQ(MODE_URGENT_GC, ret); // when 5. ret = gcCtx->GetCurrentGcMode(4); // then 5. EXPECT_EQ(MODE_URGENT_GC, ret); EXPECT_CALL(blockAllocStatus, PermitUserBlockAllocation); // when 6. ret = gcCtx->GetCurrentGcMode(8); // then 6. EXPECT_EQ(MODE_NORMAL_GC, ret); } } // namespace pos
22.823529
83
0.691366
so931
bbd98f5647e0f85eb95a40172c343e4062d678b9
3,683
cpp
C++
src/src/CVDecoder.cpp
AydinyanNarek/OpenCV
202551bd10cbd66f77e8dc008808cb499be21cc3
[ "MIT" ]
1
2020-06-22T08:48:51.000Z
2020-06-22T08:48:51.000Z
src/src/CVDecoder.cpp
AydinyanNarek/OpenCV
202551bd10cbd66f77e8dc008808cb499be21cc3
[ "MIT" ]
null
null
null
src/src/CVDecoder.cpp
AydinyanNarek/OpenCV
202551bd10cbd66f77e8dc008808cb499be21cc3
[ "MIT" ]
null
null
null
#include "../include/CVDecoder.h" #include "opencv2/videoio/legacy/constants_c.h" #include "opencv2/video/background_segm.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/video.hpp" #include <future> void BaseVideo::registerErrors() { Errors::ErrorRegister::registerErrors({ {"FileOpenError", "Failed to open input file."}, {"InvalidInputArgumentError", "Invalid input argument."}, {"InvalidFileFormatError", "Output file format not supported."}, {"InvalidCodecError", "Video Encoder not supported or not available for container."}, {"UnregisteredTypeError", "Failed to use the type as it is not supported."} }); } CVDecoder::CVDecoder(const std::vector<std::string>& file) : BaseVideo(file), mVideoCap(BaseVideo::CVMAKE<cv::VideoCapture*>(0)) { try{ initialize(); } catch(...) { releaseBuffers(); Errors::ErrorRegister::Throw("FileOpenError"); } } CVDecoder::~CVDecoder() { auto future = std::async(&CVDecoder::releaseFrames, this); releaseBuffers(); future.get(); } void CVDecoder::free(std::unique_ptr<typename std::remove_pointer<video>::type, void (*)(video)> ptr) { if(nullptr != ptr) { ptr->release(); ptr.reset(); } } void CVDecoder::releaseBuffers() { free(std::move(mVideoCap)); for (auto&& it : mVideoCapturesBuffer) { free(std::move(it)); } } void CVDecoder::releaseFrames() { for(auto&& overlays : mOverlayBuffer) { for(auto&& it : overlays) { it.release(); } } for(auto&& it : mBackground) { it.release(); } } void CVDecoder::openFile() { std::lock_guard<std::mutex>lock(mt); mVideoCap = BaseVideo::CVMAKE(new cv::VideoCapture(mFile)); if(!mVideoCap->isOpened()) { Errors::ErrorRegister::Throw("FileOpenError"); } mFrameRate = mVideoCap->get(CV_CAP_PROP_FPS); mWidth = mVideoCap->get(CV_CAP_PROP_FRAME_WIDTH); mHeight = mVideoCap->get(CV_CAP_PROP_FRAME_HEIGHT); mFrameCount = mVideoCap->get(CV_CAP_PROP_FRAME_COUNT); } void CVDecoder::initialize() { std::thread fileThread(&CVDecoder::openFile, this); for(auto&& it : mOverlays) { auto temp = BaseVideo::CVMAKE(new cv::VideoCapture(it)); if(!temp->isOpened()) { Errors::ErrorRegister::Throw("FileOpenError"); } mVideoCapturesBuffer.emplace_back(std::move(temp)); } if (fileThread.joinable()) { fileThread.join(); } } std::vector<cv::Mat> CVDecoder::readVideo(std::unique_ptr<typename std::remove_pointer<video>::type, void (*)(video)> ptr) { std::lock_guard<std::mutex>lock(mVideoReaderMutex); std::vector<cv::Mat> temp; cv::Mat dest; for(;;) { cv::Mat frame; *(ptr) >> frame; if (frame.empty()) { break; } cv::resize(frame, dest, cv::Size(mWidth, mHeight)); temp.emplace_back(std::move(dest)); frame.release(); dest.release(); } return temp; } void CVDecoder::decode() { auto future = std::async(&CVDecoder::readVideo, this, std::move(mVideoCap)); for(auto&& it : mVideoCapturesBuffer) { auto overlay = readVideo(std::move(it)); mOverlayBuffer.emplace_back(std::move(overlay)); } mBackground = future.get(); } std::vector<cv::Mat> CVDecoder::resize(const std::vector<cv::Mat>& moveing) { std::vector<cv::Mat> dest; dest.resize(moveing.size()); int i = 0; for (auto & it : moveing) { cv::resize(it, dest[i], cv::Size(mWidth, mHeight)); ++i; } return dest; }
29.230159
130
0.609014
AydinyanNarek
bbda226ea166b485f1acf2d086c965e59642a6ae
1,815
cpp
C++
Source/Scene/CommonTool.cpp
hipiPan/effects
d9003f71e6fb485d054fb198cfdf5b944e2e158f
[ "MIT" ]
2
2019-10-14T14:48:29.000Z
2019-10-14T15:45:25.000Z
Source/Scene/CommonTool.cpp
hipiPan/effects
d9003f71e6fb485d054fb198cfdf5b944e2e158f
[ "MIT" ]
null
null
null
Source/Scene/CommonTool.cpp
hipiPan/effects
d9003f71e6fb485d054fb198cfdf5b944e2e158f
[ "MIT" ]
null
null
null
#include "CommonTool.h" #include "Core/Utility/Log.h" #include "UI/UISystem.h" EFFECTS_NAMESPACE_BEGIN Camera::Camera(glm::vec3 position, float yaw, float pitch) { m_position = position; m_front = glm::vec3(0, 0, -1); m_up = glm::vec3(0, 1, 0); m_yaw = yaw; m_pitch = pitch; } Camera::~Camera() { } void Camera::Move(float wheel) { m_position += m_front * wheel * 0.1f; } void Camera::Rotate(glm::vec2 offset) { m_yaw += offset.x * 0.1f; m_pitch += -offset.y * 0.1f; updateVectors(); } glm::mat4 Camera::getViewMatrix() { return glm::lookAt(m_position, m_position + m_front, m_up); } glm::mat4 Camera::getProjectionMatrix(int width, int height, float fov, float near, float far) { float ratio = width / float(height); return glm::perspective(glm::radians(fov), ratio, near, far); } void Camera::updateVectors() { glm::vec3 front; front.x = cos(glm::radians(m_yaw)) * cos(glm::radians(m_pitch)); front.y = sin(glm::radians(m_pitch)); front.z = sin(glm::radians(m_yaw)) * cos(glm::radians(m_pitch)); m_front = glm::normalize(front); m_right = glm::normalize(glm::cross(m_front, glm::vec3(0, 1, 0))); m_up = glm::normalize(glm::cross(m_right, m_front)); } Input::Input() { memset(m_mouse_button_up, 0, sizeof(m_mouse_button_up)); memset(m_mouse_button_held, 0, sizeof(m_mouse_button_held)); memset(m_mouse_button_down, 0, sizeof(m_mouse_button_down)); m_mouse_scroll_wheel = 0.0; } Input::~Input() { } void Input::update() { memset(m_mouse_button_up, 0, sizeof(m_mouse_button_up)); memset(m_mouse_button_down, 0, sizeof(m_mouse_button_down)); m_mouse_scroll_wheel = 0.0; } Context::Context() { } Context::~Context() { } void Context::update(float t) { m_time += t; m_input->update(); m_ui_system->update(); } void Context::drawUI() { m_ui_system->draw(); } EFFECTS_NAMESPACE_END
20.862069
94
0.699174
hipiPan
bbdaddc5a5d700c11c383e5d4c60e5373fd34440
1,788
cpp
C++
Util/GetFilenameForFileURL.cpp
yoann01/FabricUI
d4d24f25245b8ccd2d206aded2b6c5f2aca09155
[ "BSD-3-Clause" ]
null
null
null
Util/GetFilenameForFileURL.cpp
yoann01/FabricUI
d4d24f25245b8ccd2d206aded2b6c5f2aca09155
[ "BSD-3-Clause" ]
null
null
null
Util/GetFilenameForFileURL.cpp
yoann01/FabricUI
d4d24f25245b8ccd2d206aded2b6c5f2aca09155
[ "BSD-3-Clause" ]
null
null
null
// // Copyright (c) 2010-2017 Fabric Software Inc. All rights reserved. // // Must come first!! #include <FTL/Config.h> #if defined(FTL_OS_DARWIN) #include <CoreFoundation/CoreFoundation.h> #endif #include <FabricUI/Util/GetFilenameForFileURL.h> namespace FabricUI { namespace Util { QString GetFilenameForFileURL( QUrl url ) { QString scheme = url.scheme(); if ( scheme == "file" ) { QString filename = url.toLocalFile(); #if defined(FTL_OS_DARWIN) // [pzion 20150805] Work around // https://bugreports.qt.io/browse/QTBUG-40449 if ( filename.startsWith("/.file/id=") ) { CFStringRef relCFStringRef = CFStringCreateWithCString( kCFAllocatorDefault, filename.toUtf8().constData(), kCFStringEncodingUTF8 ); CFURLRef relCFURL = CFURLCreateWithFileSystemPath( kCFAllocatorDefault, relCFStringRef, kCFURLPOSIXPathStyle, false // isDirectory ); CFErrorRef error = 0; CFURLRef absCFURL = CFURLCreateFilePathURL( kCFAllocatorDefault, relCFURL, &error ); if ( !error ) { static const CFIndex maxAbsPathCStrBufLen = 4096; char absPathCStr[maxAbsPathCStrBufLen]; if ( CFURLGetFileSystemRepresentation( absCFURL, true, // resolveAgainstBase reinterpret_cast<UInt8 *>( &absPathCStr[0] ), maxAbsPathCStrBufLen ) ) { filename = QString( absPathCStr ); } } CFRelease( absCFURL ); CFRelease( relCFURL ); CFRelease( relCFStringRef ); } #endif // FTL_OS_DARWIN return filename; } else return QString(); } } // namespace Util } // namespace FabricUI
24.493151
68
0.612975
yoann01
bbdd15c899c408ad89073c84f54de3654bf7bdec
131
hh
C++
src/Exception/StopPropagationUnsafeException.hh
GroovyCarrot/hhvm-event-dispatcher
0140f298c06ce60eeb2f07e7cc1f95aeca5ca853
[ "MIT" ]
null
null
null
src/Exception/StopPropagationUnsafeException.hh
GroovyCarrot/hhvm-event-dispatcher
0140f298c06ce60eeb2f07e7cc1f95aeca5ca853
[ "MIT" ]
null
null
null
src/Exception/StopPropagationUnsafeException.hh
GroovyCarrot/hhvm-event-dispatcher
0140f298c06ce60eeb2f07e7cc1f95aeca5ca853
[ "MIT" ]
null
null
null
<?hh // strict namespace GroovyCarrot\Event\Exception; final class StopPropagationUnsafeException extends \RuntimeException { }
14.555556
68
0.80916
GroovyCarrot
bbde5f10bf85a778b7cc6e6582601b3d1b8ab41b
1,522
cpp
C++
src/minoru_driver.cpp
srv/minoru_driver
24718626df4856546c92ba67ec1aa614f10d63f9
[ "MIT" ]
null
null
null
src/minoru_driver.cpp
srv/minoru_driver
24718626df4856546c92ba67ec1aa614f10d63f9
[ "MIT" ]
null
null
null
src/minoru_driver.cpp
srv/minoru_driver
24718626df4856546c92ba67ec1aa614f10d63f9
[ "MIT" ]
null
null
null
#include <ros/ros.h> #include "opencv2/opencv.hpp" using namespace std; class MinoruDriver { ros::NodeHandle nh_; ros::NodeHandle nh_private_; int left_dev_idx_, right_dev_idx_; public: MinoruDriver() : nh_private_("~") { nh_private_.param("left_dev_idx", left_dev_idx_, 0); nh_private_.param("right_dev_idx", right_dev_idx_, 1); } void stream() { // Open left cv::VideoCapture l_cap(left_dev_idx_); cv::VideoCapture r_cap(right_dev_idx_); if(!l_cap.isOpened()) { ROS_ERROR("Error opening left camera"); return; } if(!r_cap.isOpened()) { ROS_WARN("Error opening right camera"); return; } // Setup l_cap.set(CV_CAP_PROP_FRAME_WIDTH, 320); l_cap.set(CV_CAP_PROP_FRAME_HEIGHT, 240); l_cap.set(CV_CAP_PROP_FPS, 15); r_cap.set(CV_CAP_PROP_FRAME_WIDTH, 320); r_cap.set(CV_CAP_PROP_FRAME_HEIGHT, 240); r_cap.set(CV_CAP_PROP_FPS, 15); while(ros::ok()) { cv::Mat l_frame, r_frame; // Left frame l_cap >> l_frame; ros::Duration(0.5).sleep(); // Right frame r_cap >> r_frame; ROS_INFO_STREAM("FRAME PROCESSED: " << l_frame.cols << "x" << l_frame.rows << " | " << r_frame.cols << "x" << r_frame.rows); } // the camera will be deinitialized automatically in VideoCapture destructor return; } }; int main(int argc, char** argv) { ros::init(argc, argv, "minoru_driver"); MinoruDriver node; node.stream(); ros::spin(); return 0; }
20.293333
135
0.632063
srv
bbe077c3c4c2315afac111f90087d1336a11f9a2
2,357
cc
C++
src/fdb5/pmem/PMemIndexLocation.cc
dvuckovic/fdb
c529bf5293d1f5e33048b1b12e7fdfbf4d7448b2
[ "Apache-2.0" ]
5
2020-01-03T10:23:05.000Z
2021-10-21T12:52:47.000Z
src/fdb5/pmem/PMemIndexLocation.cc
dvuckovic/fdb
c529bf5293d1f5e33048b1b12e7fdfbf4d7448b2
[ "Apache-2.0" ]
null
null
null
src/fdb5/pmem/PMemIndexLocation.cc
dvuckovic/fdb
c529bf5293d1f5e33048b1b12e7fdfbf4d7448b2
[ "Apache-2.0" ]
1
2021-07-08T16:26:06.000Z
2021-07-08T16:26:06.000Z
/* * (C) Copyright 1996- ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. */ /* * This software was developed as part of the EC H2020 funded project NextGenIO * (Project ID: 671951) www.nextgenio.eu */ /// @author Simon Smart /// @date Nov 2016 #include "fdb5/pmem/PMemIndexLocation.h" #include "fdb5/pmem/PBranchingNode.h" #include "pmem/PoolRegistry.h" using namespace eckit; namespace fdb5 { namespace pmem { // PMemIndexLocation cannot be sensibly reconstructed on a remote. // Create something that gives info without needing the pmem library, that // could be remapped into a PMemIndexLocation if we later so chose. // --> For info purposes we return a TocIndexLocation which has the required // components. // --> Obviously, if this needs to be reconstructed, then we need to do // something else magical. //::eckit::ClassSpec PMemFieldLocation::classSpec_ = {&FieldLocation::classSpec(), "PMemFieldLocation",}; //::eckit::Reanimator<PMemFieldLocation> PMemFieldLocation::reanimator_; //---------------------------------------------------------------------------------------------------------------------- PMemIndexLocation::PMemIndexLocation(PBranchingNode& node, DataPoolManager& mgr) : node_(node), poolManager_(mgr) {} PBranchingNode& PMemIndexLocation::node() const { return node_; } DataPoolManager& PMemIndexLocation::pool_manager() const { return poolManager_; } PathName PMemIndexLocation::url() const { ::pmem::PersistentPool& pool(::pmem::PoolRegistry::instance().poolFromPointer(&node_)); return pool.path(); } IndexLocation* PMemIndexLocation::clone() const { return new PMemIndexLocation(node_, poolManager_); } void PMemIndexLocation::encode(Stream &) const { NOTIMP; // See comment at top of file } void PMemIndexLocation::print(std::ostream &out) const { out << "(" << url() << ")"; } //---------------------------------------------------------------------------------------------------------------------- } // namespace pmem } // namespace fdb5
28.059524
120
0.654221
dvuckovic
bbe2dceeb3a33c2ad9ec4e423208ef9ccfbd0662
677
cpp
C++
core/fxcodec/jpeg/jpeg_common.cpp
sanarea/pdfium
632a6cb844457a97dd48b97ad69ab365aeb17491
[ "Apache-2.0" ]
25
2019-05-07T16:16:40.000Z
2022-03-30T09:04:00.000Z
core/fxcodec/jpeg/jpeg_common.cpp
sanarea/pdfium
632a6cb844457a97dd48b97ad69ab365aeb17491
[ "Apache-2.0" ]
4
2020-10-20T13:09:56.000Z
2021-04-10T00:23:35.000Z
core/fxcodec/jpeg/jpeg_common.cpp
sanarea/pdfium
632a6cb844457a97dd48b97ad69ab365aeb17491
[ "Apache-2.0" ]
11
2019-09-11T20:43:10.000Z
2022-03-30T09:04:01.000Z
// Copyright 2020 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "core/fxcodec/jpeg/jpeg_common.h" extern "C" { void src_do_nothing(jpeg_decompress_struct* cinfo) {} boolean src_fill_buffer(j_decompress_ptr cinfo) { return FALSE; } boolean src_resync(j_decompress_ptr cinfo, int desired) { return FALSE; } void error_do_nothing(j_common_ptr cinfo) {} void error_do_nothing_int(j_common_ptr cinfo, int) {} void error_do_nothing_char(j_common_ptr cinfo, char*) {} } // extern "C"
24.178571
80
0.763663
sanarea
bbe62e6c7c990f0e77c045f19f8681629a5d5230
1,112
cpp
C++
1st/binary_tree_maximum_path_sum.cpp
buptlxb/leetcode
b641419de040801c4f54618d7ee26edcf10ee53c
[ "BSD-3-Clause" ]
null
null
null
1st/binary_tree_maximum_path_sum.cpp
buptlxb/leetcode
b641419de040801c4f54618d7ee26edcf10ee53c
[ "BSD-3-Clause" ]
null
null
null
1st/binary_tree_maximum_path_sum.cpp
buptlxb/leetcode
b641419de040801c4f54618d7ee26edcf10ee53c
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: int maxPathSum(TreeNode* root) { if (!root) return 0; int max = root->val; maxPathSum(root, max); return max; } int maxPathSum(TreeNode *root, int &max) { if (!root) return 0; int left_max = maxPathSum(root->left, max); int right_max = maxPathSum(root->right, max); int tmp = root->val; if (left_max > 0) tmp += left_max; if (right_max > 0) tmp += right_max; max = max > tmp ? max : tmp; int tmp_max = (left_max > right_max ? left_max : right_max) + root->val; return tmp_max > root->val ? tmp_max : root->val; } }; int main(void) { TreeNode t1(1); TreeNode t2(-2); TreeNode t3(3); TreeNode t4(3); t1.left = &t2; t1.right = &t3; //t3.left = &t4; cout << Solution().maxPathSum(&t1) << endl; return 0; }
20.981132
80
0.530576
buptlxb
bbec70110e809c6967064542c7d91bb44ba9dd5a
345
hpp
C++
src/engine/effects/transition.hpp
Blackhawk-TA/32blit-rpg
eaad46e1eeab6765a6b8f6e31a2d196aeeaba6f9
[ "MIT" ]
1
2021-12-31T23:52:57.000Z
2021-12-31T23:52:57.000Z
src/engine/effects/transition.hpp
Blackhawk-TA/GateKeeper
49a260bf7ba2304f1649b5ed487bc1e55028e672
[ "MIT" ]
null
null
null
src/engine/effects/transition.hpp
Blackhawk-TA/GateKeeper
49a260bf7ba2304f1649b5ed487bc1e55028e672
[ "MIT" ]
null
null
null
// // Created by daniel on 04.09.21. // #pragma once #include "../../utils/utils.hpp" namespace transition { enum TransitionState { INACTIVE = 0, FADING_IN = 1, BLACKED_OUT = 2, CALLBACK_EXECUTED = 3, FADING_OUT = 4, }; bool in_process(); void draw(); void update(uint32_t time); void start(std::function<void()> callback); }
15.681818
44
0.657971
Blackhawk-TA
bbedf375e29f6763894e3215a28d18a7eeb1c5ac
622
cpp
C++
EJERCICIOS/EJERCICIO C++/Examen II parcial/main.cpp
dianaM182/cpp
45b0e688b00f5a6f4483aba13904b5d760806726
[ "MIT" ]
null
null
null
EJERCICIOS/EJERCICIO C++/Examen II parcial/main.cpp
dianaM182/cpp
45b0e688b00f5a6f4483aba13904b5d760806726
[ "MIT" ]
null
null
null
EJERCICIOS/EJERCICIO C++/Examen II parcial/main.cpp
dianaM182/cpp
45b0e688b00f5a6f4483aba13904b5d760806726
[ "MIT" ]
null
null
null
#include <iostream> #include <windows.h> #include <conio.h> #include <stdlib.h> #include <time.h> #include "juego.h" using namespace std; int main () { char tecla; int puntos = 0 ; int xPos = 30 , yPos = 20 ; inicializarArreglo (); dificultad (); gotoxy(50,2); cout << puntos; pintar (); gotoxy (xPos, yPos); cout << ( char ) 4 ; while (tecla != 27 && gameover ()) { proceso (tecla, puntos); } if (! gameover ()) { MessageBox ( NULL , " Has perdido " , " Perdedor " , MB_OK); system ( " cls " ); } system ( " pausa> NULO " ); return 0 ; }
16.810811
63
0.533762
dianaM182
bbf0a7a66b0ee02ead8c4c703ec62112b95514a8
880
hpp
C++
src/config.hpp
niclasr/crosswrench
6853721d4915bda559daa8941fcbf268230959e6
[ "MIT" ]
null
null
null
src/config.hpp
niclasr/crosswrench
6853721d4915bda559daa8941fcbf268230959e6
[ "MIT" ]
null
null
null
src/config.hpp
niclasr/crosswrench
6853721d4915bda559daa8941fcbf268230959e6
[ "MIT" ]
null
null
null
#if !defined(_SRC_CONFIG_HPP_) #define _SRC_CONFIG_HPP_ #include <cxxopts.hpp> #include <map> #include <string> namespace crosswrench { class config { public: static config *instance(); bool setup(cxxopts::ParseResult &); bool setup(std::map<std::string, std::string> &); std::string get_value(std::string); void print_all(); config(const config &) = delete; config &operator=(const config &) = delete; std::string dotdatakeydir2config(std::string &); private: bool get_algos(cxxopts::ParseResult &); bool set_python_value(std::string, cxxopts::ParseResult &); bool verify_python_interpreter(cxxopts::ParseResult &pr); config(); std::map<std::string, std::string> db; std::map<std::string, std::string> new_db; std::map<std::string, std::string> dotdatakeydir2config_map; }; } // namespace crosswrench #endif
24.444444
64
0.6875
niclasr
bbf2d90c98fd385db609fd3dcfe93d0f8c9bed99
2,911
cxx
C++
main/connectivity/source/drivers/jdbc/JBigDecimal.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/connectivity/source/drivers/jdbc/JBigDecimal.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/connectivity/source/drivers/jdbc/JBigDecimal.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include "java/math/BigDecimal.hxx" #include "java/tools.hxx" #include "resource/jdbc_log.hrc" using namespace connectivity; //************************************************************** //************ Class: java.lang.Boolean //************************************************************** jclass java_math_BigDecimal::theClass = 0; java_math_BigDecimal::~java_math_BigDecimal() {} jclass java_math_BigDecimal::getMyClass() const { // die Klasse muss nur einmal geholt werden, daher statisch if( !theClass ) theClass = findMyClass("java/math/BigDecimal"); return theClass; } java_math_BigDecimal::java_math_BigDecimal( const ::rtl::OUString& _par0 ): java_lang_Object( NULL, (jobject)NULL ) { SDBThreadAttach t; if( !t.pEnv ) return; // Java-Call fuer den Konstruktor absetzen // temporaere Variable initialisieren static const char * cSignature = "(Ljava/lang/String;)V"; jobject tempObj; static jmethodID mID(NULL); obtainMethodId(t.pEnv, "<init>",cSignature, mID); jstring str = convertwchar_tToJavaString(t.pEnv,_par0.replace(',','.')); tempObj = t.pEnv->NewObject( getMyClass(), mID, str ); t.pEnv->DeleteLocalRef(str); saveRef( t.pEnv, tempObj ); t.pEnv->DeleteLocalRef( tempObj ); ThrowSQLException( t.pEnv, NULL ); // und aufraeumen } java_math_BigDecimal::java_math_BigDecimal( const double& _par0 ): java_lang_Object( NULL, (jobject)NULL ) { SDBThreadAttach t; if( !t.pEnv ) return; // Java-Call fuer den Konstruktor absetzen // temporaere Variable initialisieren static const char * cSignature = "(D)V"; jobject tempObj; static jmethodID mID(NULL); obtainMethodId(t.pEnv, "<init>",cSignature, mID); tempObj = t.pEnv->NewObject( getMyClass(), mID, _par0 ); saveRef( t.pEnv, tempObj ); t.pEnv->DeleteLocalRef( tempObj ); ThrowSQLException( t.pEnv, NULL ); // und aufraeumen }
33.848837
115
0.666438
Grosskopf
bbf53e86095496ff574033e1ca25641b62a54cdd
2,333
cc
C++
vcs/src/model/GetDeviceVideoUrlRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
vcs/src/model/GetDeviceVideoUrlRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
vcs/src/model/GetDeviceVideoUrlRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/vcs/model/GetDeviceVideoUrlRequest.h> using AlibabaCloud::Vcs::Model::GetDeviceVideoUrlRequest; GetDeviceVideoUrlRequest::GetDeviceVideoUrlRequest() : RpcServiceRequest("vcs", "2020-05-15", "GetDeviceVideoUrl") { setMethod(HttpRequest::Method::Post); } GetDeviceVideoUrlRequest::~GetDeviceVideoUrlRequest() {} std::string GetDeviceVideoUrlRequest::getOutProtocol()const { return outProtocol_; } void GetDeviceVideoUrlRequest::setOutProtocol(const std::string& outProtocol) { outProtocol_ = outProtocol; setBodyParameter("OutProtocol", outProtocol); } std::string GetDeviceVideoUrlRequest::getCorpId()const { return corpId_; } void GetDeviceVideoUrlRequest::setCorpId(const std::string& corpId) { corpId_ = corpId; setBodyParameter("CorpId", corpId); } std::string GetDeviceVideoUrlRequest::getGbId()const { return gbId_; } void GetDeviceVideoUrlRequest::setGbId(const std::string& gbId) { gbId_ = gbId; setBodyParameter("GbId", gbId); } long GetDeviceVideoUrlRequest::getEndTime()const { return endTime_; } void GetDeviceVideoUrlRequest::setEndTime(long endTime) { endTime_ = endTime; setBodyParameter("EndTime", std::to_string(endTime)); } long GetDeviceVideoUrlRequest::getStartTime()const { return startTime_; } void GetDeviceVideoUrlRequest::setStartTime(long startTime) { startTime_ = startTime; setBodyParameter("StartTime", std::to_string(startTime)); } std::string GetDeviceVideoUrlRequest::getDeviceId()const { return deviceId_; } void GetDeviceVideoUrlRequest::setDeviceId(const std::string& deviceId) { deviceId_ = deviceId; setBodyParameter("DeviceId", deviceId); }
24.302083
78
0.74925
iamzken
bbf5b2c4c0f9c577a3cf2e2b567844544922714c
2,615
cpp
C++
solved_problems/276D.cpp
archit-1997/codeforces
6f78a3ed5930531159ae22f7b70dc56e37a9e240
[ "MIT" ]
1
2021-01-27T16:37:31.000Z
2021-01-27T16:37:31.000Z
solved_problems/276D.cpp
archit-1997/codeforces
6f78a3ed5930531159ae22f7b70dc56e37a9e240
[ "MIT" ]
null
null
null
solved_problems/276D.cpp
archit-1997/codeforces
6f78a3ed5930531159ae22f7b70dc56e37a9e240
[ "MIT" ]
null
null
null
/*A little girl loves problems on bitwise operations very much. Here's one of them. You are given two integers l and r. Let's consider the values of for all pairs of integers a and b (l ≤ a ≤ b ≤ r). Your task is to find the maximum value among all considered ones. Expression means applying bitwise excluding or operation to integers x and y. The given operation exists in all modern programming languages, for example, in languages C++ and Java it is represented as "^", in Pascal — as «xor». Input The single line contains space-separated integers l and r (1 ≤ l ≤ r ≤ 1018). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Output In a single line print a single integer — the maximum value of for all pairs of integers a, b (l ≤ a ≤ b ≤ r). Examples Input Copy 1 2 Output Copy 3 Input Copy 8 16 Output Copy 31 Input Copy 1 1 Output Copy 0 */ // Chochu Singh #include <bits/stdc++.h> using namespace std; #define ll long long int #define ld long double #define line cout << "-------------" << endl; #define F first #define S second #define P pair<ll, ll> #define PP pair<pair<ll, ll>, ll> #define V vector<ll> #define VP vector<pair<ll, ll>> #define VS vector<string> #define VV vector<vector<ll>> #define VVP vector<vector<pair<ll, ll>>> #define pb push_back #define pf push_front #define PQ priority_queue<ll> #define PQ_G priority_queue<ll, vector<ll>, greater<ll>> #define FOR(i, a, b) for (ll i = a; i < b; i++) #define FAST \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); string binary(ll n) { string ans; while (n != 0) { ans = ans + to_string(n % 2); n /= 2; } reverse(ans.begin(), ans.end()); return ans; } ll decimal(string s) { reverse(s.begin(), s.end()); ll ans = 0, n = s.size(); FOR(i, 0, n) { if (s[i] == '1') ans += pow(2, i); } return ans; } int main() { FAST; ll l, r; cin >> l >> r; if (l == r) cout << 0; else if (r == l + 1) cout << (l ^ r); else { ll x = l ^ r; string s = binary(x); ll n = s.size(), index; for (ll i = 0; i < n; i++) { if (s[i] == '1') { index = i; break; } } for (ll i = index; i < n; i++) s[i] = '1'; ll ans = decimal(s); cout << ans << endl; } return 0; }
19.810606
81
0.555641
archit-1997
bbf775190e7cb605a20e6a75a4f952682d6c5ab7
2,597
cc
C++
tests/si/rendering.cc
juliusnehring/arcana-samples
b5d71c114f353b278323b96450b1bfcd947336b7
[ "MIT" ]
null
null
null
tests/si/rendering.cc
juliusnehring/arcana-samples
b5d71c114f353b278323b96450b1bfcd947336b7
[ "MIT" ]
null
null
null
tests/si/rendering.cc
juliusnehring/arcana-samples
b5d71c114f353b278323b96450b1bfcd947336b7
[ "MIT" ]
null
null
null
#include <nexus/app.hh> #include <resource-system/res.hh> #include <phantasm-renderer/pr.hh> #include <structured-interface/element_tree.hh> #include <structured-interface/gui.hh> #include <structured-interface/layout/aabb_layout.hh> #include <structured-interface/si.hh> #include <arcana-incubator/device-abstraction/device_abstraction.hh> namespace { constexpr auto shader_code_clear = R"( struct vs_in { uint vid : SV_VertexID; }; struct vs_out { float4 SV_P : SV_POSITION; float2 Texcoord : TEXCOORD; }; vs_out main_vs(vs_in In) { vs_out Out; Out.Texcoord = float2((In.vid << 1) & 2, In.vid & 2); Out.SV_P = float4(Out.Texcoord * 2.0f + -1.0f, 0.0f, 1.0f); Out.SV_P.y = -Out.SV_P.y; return Out; } float4 main_ps(vs_out In) : SV_TARGET { return float4(0.6,0.6,0.6, 1); } )"; } APP("ui rendering") { auto window = inc::da::SDLWindow("structured interface"); auto ctx = pr::Context(pr::backend::vulkan); auto swapchain = ctx.make_swapchain({window.getSdlWindow()}, window.getSize()); auto vs_clear = ctx.make_shader(shader_code_clear, "main_vs", pr::shader::vertex); auto ps_clear = ctx.make_shader(shader_code_clear, "main_ps", pr::shader::pixel); si::gui ui; while (!window.isRequestingClose()) { window.pollEvents(); auto r = ui.record([&] { si::button("press me"); si::text("i'm a test text."); }); auto tree = si::element_tree::from_record(r); si::compute_aabb_layout(tree); auto backbuffer = ctx.acquire_backbuffer(swapchain); auto frame = ctx.make_frame(); { auto fb = frame.make_framebuffer(backbuffer); auto pass = fb.make_pass(pr::graphics_pass({}, vs_clear, ps_clear)); pass.draw(3); } frame.present_after_submit(backbuffer, swapchain); ctx.submit(cc::move(frame)); } }
32.873418
93
0.471698
juliusnehring
bbf8a32a55fd0365ced4e6755b380389560f0481
239
cpp
C++
Sources/Core/cpp_cli/LinguisticsKernel/AnaphoraResolution.cpp
elzin/SentimentAnalysisService
41fba2ef49746473535196e89a5e49250439fd83
[ "MIT" ]
2
2021-07-07T19:39:11.000Z
2021-12-02T15:54:15.000Z
Sources/Core/cpp_cli/LinguisticsKernel/AnaphoraResolution.cpp
elzin/SentimentAnalysisService
41fba2ef49746473535196e89a5e49250439fd83
[ "MIT" ]
null
null
null
Sources/Core/cpp_cli/LinguisticsKernel/AnaphoraResolution.cpp
elzin/SentimentAnalysisService
41fba2ef49746473535196e89a5e49250439fd83
[ "MIT" ]
1
2021-12-01T17:48:20.000Z
2021-12-01T17:48:20.000Z
#include "StdAfx.h" #include "AnaphoraResolution.h" namespace SS { namespace LinguisticProcessor { System::String* CAnaphoraResolution::ResovleAnaphoras(System::String* xmlData) { //System::Xml::XmlDocument* xdoc = return ""; } } }
13.277778
78
0.732218
elzin
bbf8daeb17bf1b808e9e5fcdc0a99a7314a4bba0
342
cpp
C++
alignment/format/CompareSequencesPrinter.cpp
ggraham/blasr_libcpp
4abef36585bbb677ebc4acb9d4e44e82331d59f7
[ "RSA-MD" ]
4
2015-07-03T11:59:54.000Z
2018-05-17T00:03:22.000Z
alignment/format/CompareSequencesPrinter.cpp
ggraham/blasr_libcpp
4abef36585bbb677ebc4acb9d4e44e82331d59f7
[ "RSA-MD" ]
79
2015-06-29T18:07:21.000Z
2018-09-19T13:38:39.000Z
alignment/format/CompareSequencesPrinter.cpp
ggraham/blasr_libcpp
4abef36585bbb677ebc4acb9d4e44e82331d59f7
[ "RSA-MD" ]
19
2015-06-23T08:43:29.000Z
2021-04-28T18:37:47.000Z
#include <alignment/format/CompareSequencesPrinter.hpp> void CompareSequencesOutput::PrintHeader(std::ostream &out) { out << "qName qLength qStart qEnd qStrand " << "tName tLength tStart tEnd tStrand " << "score numMatch numMismatch numIns numDel " << "mapQV qAlignedSeq matchPattern tAlignedSeq" << std::endl; }
34.2
69
0.704678
ggraham
bbf93efa86bcd22abe2d82d7272be8dbc773bbe7
4,577
cpp
C++
Tools/EditorFramework/Assets/Implementation/AssetBrowserDlg.cpp
eltld/ezEngine
3230235249dd2769f166872b753efd6bd8347c98
[ "CC-BY-3.0" ]
null
null
null
Tools/EditorFramework/Assets/Implementation/AssetBrowserDlg.cpp
eltld/ezEngine
3230235249dd2769f166872b753efd6bd8347c98
[ "CC-BY-3.0" ]
null
null
null
Tools/EditorFramework/Assets/Implementation/AssetBrowserDlg.cpp
eltld/ezEngine
3230235249dd2769f166872b753efd6bd8347c98
[ "CC-BY-3.0" ]
1
2020-03-08T04:55:16.000Z
2020-03-08T04:55:16.000Z
#include <PCH.h> #include <EditorFramework/Assets/AssetBrowserDlg.moc.h> #include <EditorFramework/EditorApp/EditorApp.moc.h> #include <QSettings> #include <QFileDialog> bool ezAssetBrowserDlg::s_bShowItemsInSubFolder = true; bool ezAssetBrowserDlg::s_bSortByRecentUse = true; ezMap<ezString, ezString> ezAssetBrowserDlg::s_sTextFilter; ezMap<ezString, ezString> ezAssetBrowserDlg::s_sPathFilter; ezMap<ezString, ezString> ezAssetBrowserDlg::s_sTypeFilter; ezAssetBrowserDlg::ezAssetBrowserDlg(QWidget* parent, const char* szPreselectedAsset, const char* szVisibleFilters) : QDialog(parent) { setupUi(this); m_sVisibleFilters = szVisibleFilters; /// \todo Implement this //m_sSelectedPath = szPreselectedAsset; // Ok / Cancel buttons are disable atm ButtonOk->setVisible(false); ButtonCancel->setVisible(false); AssetBrowserWidget->SetSelectedAsset(szPreselectedAsset); AssetBrowserWidget->ShowOnlyTheseTypeFilters(szVisibleFilters); QSettings Settings; Settings.beginGroup(QLatin1String("AssetBrowserDlg")); { restoreGeometry(Settings.value("WindowGeometry", saveGeometry()).toByteArray()); move(Settings.value("WindowPosition", pos()).toPoint()); resize(Settings.value("WindowSize", size()).toSize()); } Settings.endGroup(); AssetBrowserWidget->SetDialogMode(); AssetBrowserWidget->RestoreState("AssetBrowserDlg"); AssetBrowserWidget->GetAssetBrowserModel()->SetSortByRecentUse(s_bSortByRecentUse); AssetBrowserWidget->GetAssetBrowserModel()->SetShowItemsInSubFolders(s_bShowItemsInSubFolder); if (!s_sTextFilter[m_sVisibleFilters].IsEmpty()) AssetBrowserWidget->GetAssetBrowserModel()->SetTextFilter(s_sTextFilter[m_sVisibleFilters]); if (!s_sPathFilter[m_sVisibleFilters].IsEmpty()) AssetBrowserWidget->GetAssetBrowserModel()->SetPathFilter(s_sPathFilter[m_sVisibleFilters]); if (!s_sTypeFilter[m_sVisibleFilters].IsEmpty()) AssetBrowserWidget->GetAssetBrowserModel()->SetTypeFilter(s_sTypeFilter[m_sVisibleFilters]); AssetBrowserWidget->LineSearchFilter->setFocus(); } ezAssetBrowserDlg::~ezAssetBrowserDlg() { s_bShowItemsInSubFolder = AssetBrowserWidget->GetAssetBrowserModel()->GetShowItemsInSubFolders(); s_bSortByRecentUse = AssetBrowserWidget->GetAssetBrowserModel()->GetSortByRecentUse(); s_sTextFilter[m_sVisibleFilters] = AssetBrowserWidget->GetAssetBrowserModel()->GetTextFilter(); s_sPathFilter[m_sVisibleFilters] = AssetBrowserWidget->GetAssetBrowserModel()->GetPathFilter(); s_sTypeFilter[m_sVisibleFilters] = AssetBrowserWidget->GetAssetBrowserModel()->GetTypeFilter(); QSettings Settings; Settings.beginGroup(QLatin1String("AssetBrowserDlg")); { Settings.setValue("WindowGeometry", saveGeometry()); Settings.setValue("WindowPosition", pos()); Settings.setValue("WindowSize", size()); } Settings.endGroup(); AssetBrowserWidget->SaveState("AssetBrowserDlg"); } void ezAssetBrowserDlg::on_AssetBrowserWidget_ItemSelected(QString sAssetGUID, QString sAssetPathRelative, QString sAssetPathAbsolute) { m_sSelectedAssetGuid = sAssetGUID.toUtf8().data(); m_sSelectedAssetPathRelative = sAssetPathRelative.toUtf8().data(); m_sSelectedAssetPathAbsolute = sAssetPathAbsolute.toUtf8().data(); } void ezAssetBrowserDlg::on_AssetBrowserWidget_ItemChosen(QString sAssetGUID, QString sAssetPathRelative, QString sAssetPathAbsolute) { m_sSelectedAssetGuid = sAssetGUID.toUtf8().data(); m_sSelectedAssetPathRelative = sAssetPathRelative.toUtf8().data(); m_sSelectedAssetPathAbsolute = sAssetPathAbsolute.toUtf8().data(); accept(); } void ezAssetBrowserDlg::on_ButtonFileDialog_clicked() { hide(); static QString sLastPath; m_sSelectedAssetGuid.Clear(); m_sSelectedAssetPathRelative.Clear(); m_sSelectedAssetPathAbsolute.Clear(); const QString sFile = QFileDialog::getOpenFileName(QApplication::activeWindow(), QLatin1String("Open File"), sLastPath); if (sFile.isEmpty()) { reject(); return; } m_sSelectedAssetPathAbsolute = sFile.toUtf8().data(); m_sSelectedAssetPathRelative = m_sSelectedAssetPathAbsolute; if (!ezEditorApp::GetInstance()->MakePathDataDirectoryRelative(m_sSelectedAssetPathRelative)) { // \todo Message Box: Invalid Path //reject(); //return; } sLastPath = sFile; on_AssetBrowserWidget_ItemChosen("", QString::fromUtf8(m_sSelectedAssetPathRelative.GetData()), sFile); } void ezAssetBrowserDlg::on_ButtonOk_clicked() { /// \todo Deactivate Ok button, when nothing is selectable accept(); } void ezAssetBrowserDlg::on_ButtonCancel_clicked() { reject(); }
33.903704
134
0.785667
eltld
bbfb4ef8311162faaec0768c6d394198f212dd38
1,934
hpp
C++
include/codegen/include/UnityEngine/Playables/ScriptPlayableBinding.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/Playables/ScriptPlayableBinding.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/Playables/ScriptPlayableBinding.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:32 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine::Playables namespace UnityEngine::Playables { // Forward declaring type: PlayableBinding struct PlayableBinding; // Forward declaring type: PlayableOutput struct PlayableOutput; // Forward declaring type: PlayableGraph struct PlayableGraph; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Object class Object; } // Forward declaring namespace: System namespace System { // Forward declaring type: Type class Type; } // Completed forward declares // Type namespace: UnityEngine.Playables namespace UnityEngine::Playables { // Autogenerated type: UnityEngine.Playables.ScriptPlayableBinding class ScriptPlayableBinding : public ::Il2CppObject { public: // static public UnityEngine.Playables.PlayableBinding Create(System.String name, UnityEngine.Object key, System.Type type) // Offset: 0x1403C64 static UnityEngine::Playables::PlayableBinding Create(::Il2CppString* name, UnityEngine::Object* key, System::Type* type); // static private UnityEngine.Playables.PlayableOutput CreateScriptOutput(UnityEngine.Playables.PlayableGraph graph, System.String name) // Offset: 0x1403D48 static UnityEngine::Playables::PlayableOutput CreateScriptOutput(UnityEngine::Playables::PlayableGraph graph, ::Il2CppString* name); }; // UnityEngine.Playables.ScriptPlayableBinding } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Playables::ScriptPlayableBinding*, "UnityEngine.Playables", "ScriptPlayableBinding"); #pragma pack(pop)
40.291667
140
0.751293
Futuremappermydud
01023635c6b74cc4156bb6c32a9ac47db8f07603
13,177
cpp
C++
tst/amazon/dsstne/engine/TestNNDataSet.cpp
farruhnet/AmazonDeepEngine
f64044d1e467333d0c9bb0643f0edf75328c503b
[ "Apache-2.0" ]
3,924
2016-05-10T22:40:39.000Z
2017-05-02T17:54:20.000Z
tst/amazon/dsstne/engine/TestNNDataSet.cpp
saminfante/amazon-dsstne
f64044d1e467333d0c9bb0643f0edf75328c503b
[ "Apache-2.0" ]
88
2016-05-11T05:11:45.000Z
2017-04-24T02:34:20.000Z
tst/amazon/dsstne/engine/TestNNDataSet.cpp
saminfante/amazon-dsstne
f64044d1e467333d0c9bb0643f0edf75328c503b
[ "Apache-2.0" ]
633
2016-05-10T23:07:33.000Z
2017-05-02T11:33:50.000Z
#include <cppunit/extensions/HelperMacros.h> #include "amazon/dsstne/engine/GpuTypes.h" #include "amazon/dsstne/engine/NNTypes.h" #include "amazon/dsstne/engine/NNLayer.h" class TestNNDataSet : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(TestNNDataSet); CPPUNIT_TEST(testCreateDenseDataset); CPPUNIT_TEST(testCreateDenseIndexedDataset); CPPUNIT_TEST(testCreateSparseDataset); CPPUNIT_TEST(testCreateSparseWeightedDataset); CPPUNIT_TEST(testCreateSparseIndexedDataset); CPPUNIT_TEST(testCreateSparseWeightedIndexedDataset); CPPUNIT_TEST(testLoadDenseData); CPPUNIT_TEST_EXCEPTION(testSetDenseData_OnSparseDataset, std::runtime_error); CPPUNIT_TEST(testLoadSparseData); CPPUNIT_TEST_EXCEPTION(testLoadSparseData_Overflow, std::length_error); CPPUNIT_TEST_EXCEPTION(testLoadSparseData_SparseStartNotZeroIndexed, std::runtime_error); CPPUNIT_TEST_EXCEPTION(testLoadSparseData_OnDenseDataset, std::runtime_error); CPPUNIT_TEST(testLoadIndexedData); CPPUNIT_TEST_EXCEPTION(testLoadIndexedData_OnNotIndexedDataset, std::runtime_error); CPPUNIT_TEST(testLoadDataWeights); CPPUNIT_TEST_EXCEPTION(testLoadDataWeights_OnNotWeightedDataset, std::runtime_error); CPPUNIT_TEST(testNNDataSetTypes); CPPUNIT_TEST_SUITE_END(); private: NNDataSetDimensions datasetDim = NNDataSetDimensions(128, 1, 1); uint32_t examples = 32; uint32_t uniqueExamples = 16; double sparseDensity = 0.1; size_t stride = datasetDim._height * datasetDim._width * datasetDim._length; size_t dataLength = stride * examples; public: void setUp() { } void testCreateDenseDataset() { NNDataSet<uint32_t> dataset(32, datasetDim); CPPUNIT_ASSERT(dataset._stride == 128); CPPUNIT_ASSERT(dataset._bIndexed == false); CPPUNIT_ASSERT(dataset._bStreaming == false); CPPUNIT_ASSERT(dataset._dimensions == 1); CPPUNIT_ASSERT(dataset._attributes == NNDataSetEnums::None); CPPUNIT_ASSERT(dataset._dataType == NNDataSetEnums::DataType::UInt); CPPUNIT_ASSERT(dataset._width == 128); CPPUNIT_ASSERT(dataset._height == 1); CPPUNIT_ASSERT(dataset._length == 1); CPPUNIT_ASSERT(dataset._examples == 32); CPPUNIT_ASSERT(dataset._uniqueExamples == 32); CPPUNIT_ASSERT(dataset._localExamples == 32); CPPUNIT_ASSERT(dataset._sparseDataSize == 0); } void testCreateDenseIndexedDataset() { NNDataSet<uint32_t> dataset(examples, uniqueExamples, datasetDim); CPPUNIT_ASSERT(dataset._stride == 128); CPPUNIT_ASSERT(dataset._bIndexed == true); CPPUNIT_ASSERT(dataset._bStreaming == false); CPPUNIT_ASSERT(dataset._dimensions == 1); CPPUNIT_ASSERT(dataset._attributes == NNDataSetEnums::Indexed); CPPUNIT_ASSERT(dataset._dataType == NNDataSetEnums::DataType::UInt); CPPUNIT_ASSERT(dataset._width == 128); CPPUNIT_ASSERT(dataset._height == 1); CPPUNIT_ASSERT(dataset._length == 1); CPPUNIT_ASSERT(dataset._examples == examples); CPPUNIT_ASSERT(dataset._uniqueExamples == uniqueExamples); CPPUNIT_ASSERT(dataset._localExamples == examples); CPPUNIT_ASSERT(dataset._sparseDataSize == 0); } void testCreateSparseDataset() { bool isWeighted = false; NNDataSet<int> dataset(examples, sparseDensity, datasetDim, isWeighted); CPPUNIT_ASSERT(dataset._stride == 0); CPPUNIT_ASSERT(dataset._bIndexed == false); CPPUNIT_ASSERT(dataset._bStreaming == false); CPPUNIT_ASSERT(dataset._dimensions == 1); CPPUNIT_ASSERT(dataset._attributes == NNDataSetEnums::Sparse); CPPUNIT_ASSERT(dataset._dataType == NNDataSetEnums::DataType::Int); CPPUNIT_ASSERT(dataset._width == 128); CPPUNIT_ASSERT(dataset._height == 1); CPPUNIT_ASSERT(dataset._length == 1); CPPUNIT_ASSERT(dataset._examples == examples); CPPUNIT_ASSERT(dataset._uniqueExamples == examples); CPPUNIT_ASSERT(dataset._localExamples == examples); CPPUNIT_ASSERT(dataset._sparseDataSize == (uint64_t ) (128.0 * 0.1 * 32.0)); } void testCreateSparseWeightedDataset() { bool isWeighted = true; NNDataSet<int> dataset(examples, sparseDensity, datasetDim, isWeighted); CPPUNIT_ASSERT(dataset._stride == 0); CPPUNIT_ASSERT(dataset._bIndexed == false); CPPUNIT_ASSERT(dataset._bStreaming == false); CPPUNIT_ASSERT(dataset._dimensions == 1); CPPUNIT_ASSERT(dataset._attributes == (NNDataSetEnums::Sparse | NNDataSetEnums::Weighted)); CPPUNIT_ASSERT(dataset._dataType == NNDataSetEnums::DataType::Int); CPPUNIT_ASSERT(dataset._width == 128); CPPUNIT_ASSERT(dataset._height == 1); CPPUNIT_ASSERT(dataset._length == 1); CPPUNIT_ASSERT(dataset._examples == examples); CPPUNIT_ASSERT(dataset._uniqueExamples == examples); CPPUNIT_ASSERT(dataset._localExamples == examples); CPPUNIT_ASSERT(dataset._sparseDataSize == (uint64_t ) (128.0 * 0.1 * 32.0)); } void testCreateSparseIndexedDataset() { size_t sparseDataSize = 128 * uniqueExamples / 10; bool isIndexed = true; bool isWeighted = false; NNDataSet<long> dataset(examples, uniqueExamples, sparseDataSize, datasetDim, isIndexed, isWeighted); CPPUNIT_ASSERT(dataset._stride == 0); CPPUNIT_ASSERT(dataset._bIndexed == true); CPPUNIT_ASSERT(dataset._bStreaming == false); CPPUNIT_ASSERT(dataset._dimensions == 1); CPPUNIT_ASSERT(dataset._attributes == (NNDataSetEnums::Sparse | NNDataSetEnums::Indexed)); CPPUNIT_ASSERT(dataset._dataType == NNDataSetEnums::DataType::LLInt); CPPUNIT_ASSERT(dataset._width == 128); CPPUNIT_ASSERT(dataset._height == 1); CPPUNIT_ASSERT(dataset._length == 1); CPPUNIT_ASSERT(dataset._examples == examples); CPPUNIT_ASSERT(dataset._uniqueExamples == uniqueExamples); CPPUNIT_ASSERT(dataset._localExamples == examples); CPPUNIT_ASSERT(dataset._sparseDataSize == sparseDataSize); } void testCreateSparseWeightedIndexedDataset() { size_t sparseDataSize = 128 * uniqueExamples / 10; bool isIndexed = true; bool isWeighted = true; NNDataSet<long> dataset(examples, uniqueExamples, sparseDataSize, datasetDim, isIndexed, isWeighted); CPPUNIT_ASSERT(dataset._stride == 0); CPPUNIT_ASSERT(dataset._bIndexed == true); CPPUNIT_ASSERT(dataset._bStreaming == false); CPPUNIT_ASSERT(dataset._dimensions == 1); CPPUNIT_ASSERT( dataset._attributes == (NNDataSetEnums::Sparse | NNDataSetEnums::Indexed | NNDataSetEnums::Weighted)); CPPUNIT_ASSERT(dataset._dataType == NNDataSetEnums::DataType::LLInt); CPPUNIT_ASSERT(dataset._width == 128); CPPUNIT_ASSERT(dataset._height == 1); CPPUNIT_ASSERT(dataset._length == 1); CPPUNIT_ASSERT(dataset._examples == examples); CPPUNIT_ASSERT(dataset._uniqueExamples == uniqueExamples); CPPUNIT_ASSERT(dataset._localExamples == examples); CPPUNIT_ASSERT(dataset._sparseDataSize == (uint64_t ) (128.0 * 0.1 * 16.0)); } void testLoadDenseData() { NNDataSet<uint32_t> dataset(examples, datasetDim); uint32_t srcData[dataLength]; for (size_t i = 0; i < dataLength; ++i) { srcData[i] = i; } dataset.LoadDenseData(srcData); for (size_t i = 0; i < examples; ++i) { for(size_t j = 0; j < stride; ++j) { CPPUNIT_ASSERT_EQUAL((uint32_t) (i * stride + j), dataset.GetDataPoint(i, j)); } } } void testSetDenseData_OnSparseDataset() { NNDataSet<uint32_t> dataset(examples, sparseDensity, datasetDim, false); uint32_t srcData[dataLength]; dataset.LoadDenseData(srcData); } void testLoadSparseData() { NNDataSet<NNFloat> dataset(examples, sparseDensity, datasetDim, false); NNDataSetDimensions dim = dataset.GetDimensions(); size_t sparseDataSize = (size_t) (((double) dim._height * dim._width * dim._length) * examples * sparseDensity); uint64_t sparseStart[examples]; uint64_t sparseEnd[examples]; NNFloat sparseData[sparseDataSize]; uint32_t sparseIndex[sparseDataSize]; size_t sparseExampleSize = (sparseDataSize + examples - 1) / examples; sparseStart[0] = 0; sparseEnd[0] = sparseDataSize - (sparseExampleSize * (examples - 1)); for (uint32_t i = 1; i < examples; i++) { sparseStart[i] = sparseEnd[i - 1]; sparseEnd[i] = sparseStart[i] + sparseExampleSize; } // data: 1,2,3,.... for (uint32_t i = 0; i < sparseDataSize; ++i) { sparseData[i] = i + 1; } // index: 0,1,2,... for (size_t i = 0; i < sparseDataSize; ++i) { sparseIndex[i] = i; } dataset.LoadSparseData(sparseStart, sparseEnd, sparseData, sparseIndex); CPPUNIT_ASSERT_EQUAL(sparseEnd[0], dataset.GetSparseDataPoints(0)); for (uint32_t i = 0; i < sparseEnd[0]; ++i) { CPPUNIT_ASSERT_EQUAL((NNFloat ) i + 1, dataset.GetSparseDataPoint(0, i)); CPPUNIT_ASSERT_EQUAL(i, dataset.GetSparseIndex(0, i)); } } void testLoadSparseData_Overflow() { NNDataSet<NNFloat> dataset(examples, sparseDensity, datasetDim, false); NNDataSetDimensions dim = dataset.GetDimensions(); size_t sparseDataSize = (size_t) (((double) dim._height * dim._width * dim._length) * examples * sparseDensity); uint64_t sparseStart[examples]; sparseStart[0] = 0; uint64_t sparseEnd[examples]; NNFloat sparseData[1]; uint32_t sparseIndex[1]; sparseEnd[examples - 1] = sparseDataSize + 1; dataset.LoadSparseData(sparseStart, sparseEnd, sparseData, sparseIndex); } void testLoadSparseData_SparseStartNotZeroIndexed() { NNDataSet<NNFloat> dataset(examples, sparseDensity, datasetDim, false); NNDataSetDimensions dim = dataset.GetDimensions(); size_t sparseDataSize = (size_t) (((double) dim._height * dim._width * dim._length) * examples * sparseDensity); uint64_t sparseStart[examples]; sparseStart[0] = 1; uint64_t sparseEnd[examples]; NNFloat sparseData[1]; uint32_t sparseIndex[1]; sparseEnd[examples - 1] = sparseDataSize + 1; dataset.LoadSparseData(sparseStart, sparseEnd, sparseData, sparseIndex); } void testLoadSparseData_OnDenseDataset() { NNDataSet<NNFloat> dataset(examples, datasetDim); uint64_t sparseStart[examples]; uint64_t sparseEnd[examples]; NNFloat sparseData[1]; uint32_t sparseIndex[1]; dataset.LoadSparseData(sparseStart, sparseEnd, sparseData, sparseIndex); } void testLoadIndexedData() { NNDataSet<NNFloat> dataset(examples, uniqueExamples, datasetDim); uint32_t indexedData[uniqueExamples]; for (uint32_t i = 0; i < uniqueExamples; ++i) { indexedData[i] = i; } dataset.LoadIndexedData(indexedData); for (uint32_t i = 0; i < uniqueExamples; ++i) { CPPUNIT_ASSERT_EQUAL(i, dataset._vIndex[i]); } } void testLoadIndexedData_OnNotIndexedDataset() { NNDataSet<NNFloat> dataset(examples, datasetDim); uint32_t indexedData[examples]; dataset.LoadIndexedData(indexedData); } void testLoadDataWeights() { NNDataSet<uint32_t> dataset(examples, sparseDensity, datasetDim, true); NNFloat dataWeights[examples]; for (uint32_t i = 0; i < examples; ++i) { dataWeights[i] = (NNFloat) i; } dataset.LoadDataWeight(dataWeights); for(uint32_t i = 0; i < examples; ++i) { CPPUNIT_ASSERT_EQUAL((NNFloat) i, dataset._vDataWeight[i]); } } void testLoadDataWeights_OnNotWeightedDataset() { NNDataSet<uint32_t> dataset(examples, sparseDensity, datasetDim, false); NNFloat dataWeights[examples]; dataset.LoadDataWeight(dataWeights); } void testNNDataSetTypes() { // ensure that we can instantiate the expected data types NNDataSet<NNFloat> floatDataset(examples, datasetDim); NNDataSet<double> doubleDataset(examples, datasetDim); NNDataSet<unsigned char> unsignedCharDataset(examples, datasetDim); NNDataSet<char> charDataset(examples, datasetDim); NNDataSet<uint32_t> unsingedIntDataset(examples, datasetDim); NNDataSet<uint64_t> unsingedLongDataset(examples, datasetDim); NNDataSet<int32_t> intDataset(examples, datasetDim); NNDataSet<int64_t> longDataset(examples, datasetDim); } }; CPPUNIT_TEST_SUITE_REGISTRATION(TestNNDataSet);
37.648571
120
0.667982
farruhnet
0104f5a20428da8cf4052c000b8a9516779a986b
6,076
cc
C++
chrome/browser/extensions/extension_user_script_loader.cc
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/extensions/extension_user_script_loader.cc
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/extensions/extension_user_script_loader.cc
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-04-04T13:34:56.000Z
2020-11-04T07:17:52.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_user_script_loader.h" #include <set> #include <string> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/version.h" #include "chrome/browser/profiles/profile.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_process_host.h" #include "extensions/browser/component_extension_resource_manager.h" #include "extensions/browser/content_verifier.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/common/file_util.h" #include "extensions/common/manifest_handlers/default_locale_handler.h" #include "extensions/common/message_bundle.h" #include "extensions/common/one_shot_event.h" #include "ui/base/resource/resource_bundle.h" namespace extensions { namespace { // Verifies file contents as they are read. void VerifyContent(const scoped_refptr<ContentVerifier>& verifier, const std::string& extension_id, const base::FilePath& extension_root, const base::FilePath& relative_path, const std::string& content) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); scoped_refptr<ContentVerifyJob> job( verifier->CreateJobFor(extension_id, extension_root, relative_path)); if (job.get()) { job->Start(); job->BytesRead(content.size(), content.data()); job->DoneReading(); } } // Loads user scripts from the extension who owns these scripts. bool ExtensionLoadScriptContent( const HostID& host_id, UserScript::File* script_file, const UserScriptLoader::SubstitutionMap* localization_messages, const scoped_refptr<ContentVerifier>& verifier) { DCHECK(script_file); std::string content; const base::FilePath& path = ExtensionResource::GetFilePath( script_file->extension_root(), script_file->relative_path(), ExtensionResource::SYMLINKS_MUST_RESOLVE_WITHIN_ROOT); if (path.empty()) { int resource_id = 0; if (ExtensionsBrowserClient::Get() ->GetComponentExtensionResourceManager() ->IsComponentExtensionResource(script_file->extension_root(), script_file->relative_path(), &resource_id)) { const ResourceBundle& rb = ResourceBundle::GetSharedInstance(); content = rb.GetRawDataResource(resource_id).as_string(); } else { LOG(WARNING) << "Failed to get file path to " << script_file->relative_path().value() << " from " << script_file->extension_root().value(); return false; } } else { if (!base::ReadFileToString(path, &content)) { LOG(WARNING) << "Failed to load user script file: " << path.value(); return false; } if (verifier.get()) { content::BrowserThread::PostTask( content::BrowserThread::IO, FROM_HERE, base::Bind(&VerifyContent, verifier, host_id.id(), script_file->extension_root(), script_file->relative_path(), content)); } } // Localize the content. if (localization_messages) { std::string error; MessageBundle::ReplaceMessagesWithExternalDictionary(*localization_messages, &content, &error); if (!error.empty()) LOG(WARNING) << "Failed to replace messages in script: " << error; } // Remove BOM from the content. std::string::size_type index = content.find(base::kUtf8ByteOrderMark); if (index == 0) script_file->set_content(content.substr(strlen(base::kUtf8ByteOrderMark))); else script_file->set_content(content); return true; } } // namespace ExtensionUserScriptLoader::ExtensionUserScriptLoader( Profile* profile, const HostID& host_id, bool listen_for_extension_system_loaded) : UserScriptLoader(profile, host_id, ExtensionSystem::Get(profile)->content_verifier()), extension_registry_observer_(this), weak_factory_(this) { extension_registry_observer_.Add(ExtensionRegistry::Get(profile)); if (listen_for_extension_system_loaded) { ExtensionSystem::Get(profile)->ready().Post( FROM_HERE, base::Bind(&ExtensionUserScriptLoader::OnExtensionSystemReady, weak_factory_.GetWeakPtr())); } else { SetReady(true); } } ExtensionUserScriptLoader::~ExtensionUserScriptLoader() { } void ExtensionUserScriptLoader::UpdateHostsInfo( const std::set<HostID>& changed_hosts) { ExtensionRegistry* registry = ExtensionRegistry::Get(profile()); for (const HostID& host_id : changed_hosts) { const Extension* extension = registry->GetExtensionById(host_id.id(), ExtensionRegistry::ENABLED); // |changed_hosts_| may include hosts that have been removed, // which leads to the above lookup failing. In this case, just continue. if (!extension) continue; AddHostInfo(host_id, ExtensionSet::ExtensionPathAndDefaultLocale( extension->path(), LocaleInfo::GetDefaultLocale(extension))); } } UserScriptLoader::LoadUserScriptsContentFunction ExtensionUserScriptLoader::GetLoadUserScriptsFunction() { return base::Bind(&ExtensionLoadScriptContent); } void ExtensionUserScriptLoader::OnExtensionUnloaded( content::BrowserContext* browser_context, const Extension* extension, UnloadedExtensionInfo::Reason reason) { RemoveHostInfo(HostID(HostID::EXTENSIONS, extension->id())); } void ExtensionUserScriptLoader::OnExtensionSystemReady() { SetReady(true); } } // namespace extensions
36.383234
80
0.691409
hefen1
0107174051aedc2d3deca281915d982f230b7543
51
cpp
C++
grafi/mst.cpp
malorubiuz/tutorato_olimpiadi2021
86736147af5f47da5cc3276bd9a894977bdee073
[ "Unlicense" ]
null
null
null
grafi/mst.cpp
malorubiuz/tutorato_olimpiadi2021
86736147af5f47da5cc3276bd9a894977bdee073
[ "Unlicense" ]
null
null
null
grafi/mst.cpp
malorubiuz/tutorato_olimpiadi2021
86736147af5f47da5cc3276bd9a894977bdee073
[ "Unlicense" ]
null
null
null
// https://training.olinfo.it/#/task/mst/statement
25.5
50
0.72549
malorubiuz
010ca98526703b0679373efbc1558ea33f88ce19
13,270
hpp
C++
src/kre/Color.hpp
sweetkristas/swiftly
0b5c2badc88637b8bdaa841a45d1babd8f12a703
[ "BSL-1.0", "Zlib", "BSD-3-Clause" ]
null
null
null
src/kre/Color.hpp
sweetkristas/swiftly
0b5c2badc88637b8bdaa841a45d1babd8f12a703
[ "BSL-1.0", "Zlib", "BSD-3-Clause" ]
null
null
null
src/kre/Color.hpp
sweetkristas/swiftly
0b5c2badc88637b8bdaa841a45d1babd8f12a703
[ "BSL-1.0", "Zlib", "BSD-3-Clause" ]
null
null
null
/* Copyright (C) 2013-2014 by Kristina Simpson <sweet.kristas@gmail.com> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgement in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #pragma once #include <memory> #include <string> #include <glm/gtc/type_precision.hpp> #include "variant.hpp" namespace KRE { class Color; typedef std::shared_ptr<Color> ColorPtr; enum class ColorByteOrder { RGBA, ARGB, BGRA, ABGR, }; class Color { public: Color(); ~Color(); explicit Color(const double r, const double g, const double b, const double a=1.0); explicit Color(const int r, const int g, const int b, const int a=255); explicit Color(const std::string& s); explicit Color(const variant& node); explicit Color(unsigned long n, ColorByteOrder order=ColorByteOrder::RGBA); double r() const { return color_[0]; } double g() const { return color_[1]; } double b() const { return color_[2]; } double a() const { return color_[3]; } double red() const { return color_[0]; } double green() const { return color_[1]; } double blue() const { return color_[2]; } double alpha() const { return color_[3]; } float rf() const { return static_cast<float>(color_[0]); } float gf() const { return static_cast<float>(color_[1]); } float bf() const { return static_cast<float>(color_[2]); } float af() const { return static_cast<float>(color_[3]); } int r_int() const { return static_cast<int>(255*color_[0]); } int g_int() const { return static_cast<int>(255*color_[1]); } int b_int() const { return static_cast<int>(255*color_[2]); } int a_int() const { return static_cast<int>(255*color_[3]); } void setRed(int a); void setRed(double a); void setGreen(int a); void setGreen(double a); void setBlue(int a); void setBlue(double a); void setAlpha(int a); void setAlpha(double a); unsigned long asARGB() const { return (a_int() << 24) | (r_int() << 16) | (g_int() << 8) | b_int(); } unsigned long asRGBA() const { return (r_int() << 24) | (b_int() << 16) | (b_int() << 8) | a_int(); } glm::u8vec4 as_u8vec4() const { return glm::u8vec4(r_int(), g_int(), b_int(), a_int()); } const float* asFloatVector() const { return color_; } variant write() const; static ColorPtr factory(const std::string& name); static Color colorAliceblue() { return Color(240, 248, 255); } static Color colorAntiquewhite() { return Color(250, 235, 215); } static Color colorAqua() { return Color(0, 255, 255); } static Color colorAquamarine() { return Color(127, 255, 212); } static Color colorAzure() { return Color(240, 255, 255); } static Color colorBeige() { return Color(245, 245, 220); } static Color colorBisque() { return Color(255, 228, 196); } static Color colorBlack() { return Color(0, 0, 0); } static Color colorBlanchedalmond() { return Color(255, 235, 205); } static Color colorBlue() { return Color(0, 0, 255); } static Color colorBlueviolet() { return Color(138, 43, 226); } static Color colorBrown() { return Color(165, 42, 42); } static Color colorBurlywood() { return Color(222, 184, 135); } static Color colorCadetblue() { return Color(95, 158, 160); } static Color colorChartreuse() { return Color(127, 255, 0); } static Color colorChocolate() { return Color(210, 105, 30); } static Color colorCoral() { return Color(255, 127, 80); } static Color colorCornflowerblue() { return Color(100, 149, 237); } static Color colorCornsilk() { return Color(255, 248, 220); } static Color colorCrimson() { return Color(220, 20, 60); } static Color colorCyan() { return Color(0, 255, 255); } static Color colorDarkblue() { return Color(0, 0, 139); } static Color colorDarkcyan() { return Color(0, 139, 139); } static Color colorDarkgoldenrod() { return Color(184, 134, 11); } static Color colorDarkgray() { return Color(169, 169, 169); } static Color colorDarkgreen() { return Color(0, 100, 0); } static Color colorDarkgrey() { return Color(169, 169, 169); } static Color colorDarkkhaki() { return Color(189, 183, 107); } static Color colorDarkmagenta() { return Color(139, 0, 139); } static Color colorDarkolivegreen() { return Color(85, 107, 47); } static Color colorDarkorange() { return Color(255, 140, 0); } static Color colorDarkorchid() { return Color(153, 50, 204); } static Color colorDarkred() { return Color(139, 0, 0); } static Color colorDarksalmon() { return Color(233, 150, 122); } static Color colorDarkseagreen() { return Color(143, 188, 143); } static Color colorDarkslateblue() { return Color(72, 61, 139); } static Color colorDarkslategray() { return Color(47, 79, 79); } static Color colorDarkslategrey() { return Color(47, 79, 79); } static Color colorDarkturquoise() { return Color(0, 206, 209); } static Color colorDarkviolet() { return Color(148, 0, 211); } static Color colorDeeppink() { return Color(255, 20, 147); } static Color colorDeepskyblue() { return Color(0, 191, 255); } static Color colorDimgray() { return Color(105, 105, 105); } static Color colorDimgrey() { return Color(105, 105, 105); } static Color colorDodgerblue() { return Color(30, 144, 255); } static Color colorFirebrick() { return Color(178, 34, 34); } static Color colorFloralwhite() { return Color(255, 250, 240); } static Color colorForestgreen() { return Color(34, 139, 34); } static Color colorFuchsia() { return Color(255, 0, 255); } static Color colorGainsboro() { return Color(220, 220, 220); } static Color colorGhostwhite() { return Color(248, 248, 255); } static Color colorGold() { return Color(255, 215, 0); } static Color colorGoldenrod() { return Color(218, 165, 32); } static Color colorGray() { return Color(128, 128, 128); } static Color colorGrey() { return Color(128, 128, 128); } static Color colorGreen() { return Color(0, 128, 0); } static Color colorGreenyellow() { return Color(173, 255, 47); } static Color colorHoneydew() { return Color(240, 255, 240); } static Color colorHotpink() { return Color(255, 105, 180); } static Color colorIndianred() { return Color(205, 92, 92); } static Color colorIndigo() { return Color(75, 0, 130); } static Color colorIvory() { return Color(255, 255, 240); } static Color colorKhaki() { return Color(240, 230, 140); } static Color colorLavender() { return Color(230, 230, 250); } static Color colorLavenderblush() { return Color(255, 240, 245); } static Color colorLawngreen() { return Color(124, 252, 0); } static Color colorLemonchiffon() { return Color(255, 250, 205); } static Color colorLightblue() { return Color(173, 216, 230); } static Color colorLightcoral() { return Color(240, 128, 128); } static Color colorLightcyan() { return Color(224, 255, 255); } static Color colorLightgoldenrodyellow() { return Color(250, 250, 210); } static Color colorLightgray() { return Color(211, 211, 211); } static Color colorLightgreen() { return Color(144, 238, 144); } static Color colorLightgrey() { return Color(211, 211, 211); } static Color colorLightpink() { return Color(255, 182, 193); } static Color colorLightsalmon() { return Color(255, 160, 122); } static Color colorLightseagreen() { return Color(32, 178, 170); } static Color colorLightskyblue() { return Color(135, 206, 250); } static Color colorLightslategray() { return Color(119, 136, 153); } static Color colorLightslategrey() { return Color(119, 136, 153); } static Color colorLightsteelblue() { return Color(176, 196, 222); } static Color colorLightyellow() { return Color(255, 255, 224); } static Color colorLime() { return Color(0, 255, 0); } static Color colorLimegreen() { return Color(50, 205, 50); } static Color colorLinen() { return Color(250, 240, 230); } static Color colorMagenta() { return Color(255, 0, 255); } static Color colorMaroon() { return Color(128, 0, 0); } static Color colorMediumaquamarine() { return Color(102, 205, 170); } static Color colorMediumblue() { return Color(0, 0, 205); } static Color colorMediumorchid() { return Color(186, 85, 211); } static Color colorMediumpurple() { return Color(147, 112, 219); } static Color colorMediumseagreen() { return Color(60, 179, 113); } static Color colorMediumslateblue() { return Color(123, 104, 238); } static Color colorMediumspringgreen() { return Color(0, 250, 154); } static Color colorMediumturquoise() { return Color(72, 209, 204); } static Color colorMediumvioletred() { return Color(199, 21, 133); } static Color colorMidnightblue() { return Color(25, 25, 112); } static Color colorMintcream() { return Color(245, 255, 250); } static Color colorMistyrose() { return Color(255, 228, 225); } static Color colorMoccasin() { return Color(255, 228, 181); } static Color colorNavajowhite() { return Color(255, 222, 173); } static Color colorNavy() { return Color(0, 0, 128); } static Color colorOldlace() { return Color(253, 245, 230); } static Color colorOlive() { return Color(128, 128, 0); } static Color colorOlivedrab() { return Color(107, 142, 35); } static Color colorOrange() { return Color(255, 165, 0); } static Color colorOrangered() { return Color(255, 69, 0); } static Color colorOrchid() { return Color(218, 112, 214); } static Color colorPalegoldenrod() { return Color(238, 232, 170); } static Color colorPalegreen() { return Color(152, 251, 152); } static Color colorPaleturquoise() { return Color(175, 238, 238); } static Color colorPalevioletred() { return Color(219, 112, 147); } static Color colorPapayawhip() { return Color(255, 239, 213); } static Color colorPeachpuff() { return Color(255, 218, 185); } static Color colorPeru() { return Color(205, 133, 63); } static Color colorPink() { return Color(255, 192, 203); } static Color colorPlum() { return Color(221, 160, 221); } static Color colorPowderblue() { return Color(176, 224, 230); } static Color colorPurple() { return Color(128, 0, 128); } static Color colorRed() { return Color(255, 0, 0); } static Color colorRosybrown() { return Color(188, 143, 143); } static Color colorRoyalblue() { return Color(65, 105, 225); } static Color colorSaddlebrown() { return Color(139, 69, 19); } static Color colorSalmon() { return Color(250, 128, 114); } static Color colorSandybrown() { return Color(244, 164, 96); } static Color colorSeagreen() { return Color(46, 139, 87); } static Color colorSeashell() { return Color(255, 245, 238); } static Color colorSienna() { return Color(160, 82, 45); } static Color colorSilver() { return Color(192, 192, 192); } static Color colorSkyblue() { return Color(135, 206, 235); } static Color colorSlateblue() { return Color(106, 90, 205); } static Color colorSlategray() { return Color(112, 128, 144); } static Color colorSlategrey() { return Color(112, 128, 144); } static Color colorSnow() { return Color(255, 250, 250); } static Color colorSpringgreen() { return Color(0, 255, 127); } static Color colorSteelblue() { return Color(70, 130, 180); } static Color colorTan() { return Color(210, 180, 140); } static Color colorTeal() { return Color(0, 128, 128); } static Color colorThistle() { return Color(216, 191, 216); } static Color colorTomato() { return Color(255, 99, 71); } static Color colorTurquoise() { return Color(64, 224, 208); } static Color colorViolet() { return Color(238, 130, 238); } static Color colorWheat() { return Color(245, 222, 179); } static Color colorWhite() { return Color(255, 255, 255); } static Color colorWhitesmoke() { return Color(245, 245, 245); } static Color colorYellow() { return Color(255, 255, 0); } static Color colorYellowgreen() { return Color(154, 205, 50); } // XXX We should have a ColorCallable, in a seperate file, then move these two into the ColorCallable. static std::string getSetFieldType() { return "string" "|[int,int,int,int]" "|[int,int,int]" "|{red:int|decimal,green:int|decimal,blue:int|decimal,alpha:int|decimal|null}" "|{r:int|decimal,g:int|decimal,b:int|decimal,a:int|decimal|null}"; } static std::string getDefineFieldType() { return "[int,int,int,int]"; } private: float color_[4]; }; inline bool operator<(const Color& lhs, const Color& rhs) { return lhs.asARGB() < rhs.asARGB(); } inline bool operator==(const Color& lhs, const Color& rhs) { return lhs.asARGB() == rhs.asARGB(); } inline bool operator!=(const Color& lhs, const Color& rhs) { return !operator==(lhs, rhs); } typedef std::shared_ptr<Color> ColorPtr; }
46.725352
104
0.685757
sweetkristas
010d96856a034d744699b0f519c2b53f6f22f4f2
1,949
cpp
C++
examples/BlockOut3000/src/BlockOut.cpp
iboB/maibo
df43ddf82b3c79e00f3d2c8b38db181e5edae264
[ "MIT" ]
4
2015-08-07T09:11:15.000Z
2018-01-03T15:47:04.000Z
examples/BlockOut3000/src/BlockOut.cpp
iboB/maibo
df43ddf82b3c79e00f3d2c8b38db181e5edae264
[ "MIT" ]
null
null
null
examples/BlockOut3000/src/BlockOut.cpp
iboB/maibo
df43ddf82b3c79e00f3d2c8b38db181e5edae264
[ "MIT" ]
null
null
null
// MaiBo - BlockOut3000 // Copyright(c) 2015 Borislav Stanimirov // // Distributed under the MIT Software License // See accompanying file LICENSE.txt or copy at // http://opensource.org/licenses/MIT // #include "BlockOut.h" #include <maibo/Resources/ResourceManager.h> #include <maibo/Common/high_res_clock.h> #include <maibo/GUI/ImGui/ImGuiManager.h> #include "LoadAllState.h" #include "Resources.h" #include "FigureManager.h" #include "CubeTemplate.h" using namespace std; using namespace maibo; bool BlockOut::initialize() { Application::CreationParameters params; params.desiredFrameTimeMs = 10; if (!Application::initialize(params)) { return false; } glEnable(GL_DEPTH_TEST); // z buffer glEnable(GL_CULL_FACE); // cull back (CW) faces glClearColor(0.0f, 0.1f, 0.4f, 1); // backbuffer clear color Resources::createInstance(); CubeTemplate::createInstance(); FigureManager::createInstance(); setState(new LoadAllState); ImGuiManager::createInstance(); startRunning(); return true; } void BlockOut::deinitialize() { ImGuiManager::destroyInstance(); FigureManager::destroyInstance(); CubeTemplate::destroyInstance(); Resources::destroyInstance(); Application::deinitialize(); cout << "Total frames: " << totalFrames() << endl; } void BlockOut::update() { Application::update(); } void BlockOut::render() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); Application::render(); } void BlockOut::onSetStateError(AppState* state) { // nothing to do yet } // maibo integration namespace maibo { namespace { BlockOut* app = nullptr; } void Application_CreateInstance(int argc, char* argv[]) { app = new BlockOut(); } Application& Application_Instance() { return *app; } void Application_DestroyInstance(int retCode) { delete app; } }
18.740385
64
0.675731
iboB
0115223ec2252299710c1da0003e077f5d7f1d70
2,054
cpp
C++
src/python/rcl/signal_routing.cpp
s3a-spatialaudio/VISR
55f6289bc5058d4898106f3520e1a60644ffb3ab
[ "ISC" ]
17
2019-03-12T14:52:22.000Z
2021-11-09T01:16:23.000Z
src/python/rcl/signal_routing.cpp
s3a-spatialaudio/VISR
55f6289bc5058d4898106f3520e1a60644ffb3ab
[ "ISC" ]
null
null
null
src/python/rcl/signal_routing.cpp
s3a-spatialaudio/VISR
55f6289bc5058d4898106f3520e1a60644ffb3ab
[ "ISC" ]
2
2019-08-11T12:53:07.000Z
2021-06-22T10:08:08.000Z
/* Copyright Institute of Sound and Vibration Research - All rights reserved */ #include <librcl/signal_routing.hpp> #include <libpml/signal_routing_parameter.hpp> #include <libvisr/atomic_component.hpp> #include <libvisr/composite_component.hpp> #include <libvisr/signal_flow_context.hpp> #include <pybind11/pybind11.h> namespace visr { namespace python { namespace rcl { namespace py = pybind11; void exportSignalRouting( pybind11::module & m ) { using visr::rcl::SignalRouting; py::class_<SignalRouting, visr::AtomicComponent>( m, "SignalRouting" ) .def( py::init( []( SignalFlowContext const & context, char const * name, CompositeComponent * parent, std::size_t inputWidth, std::size_t outputWidth, bool controlInput ) { SignalRouting * inst = new SignalRouting( context, name, parent ); inst->setup( inputWidth, outputWidth, controlInput ); return inst; }), py::arg("context"), py::arg("name"), py::arg("parent"), py::arg( "inputWidth" ), py::arg( "outputWidth" ), py::arg( "controlInput" ) = true, "Constructor with an empty initial routing." ) .def( py::init( []( SignalFlowContext const & context, char const * name, CompositeComponent * parent, std::size_t inputWidth, std::size_t outputWidth, pml::SignalRoutingParameter const & initialRouting, bool controlInput ) { SignalRouting * inst = new SignalRouting( context, name, parent ); inst->setup( inputWidth, outputWidth, initialRouting, controlInput ); return inst; }), py::arg("context"), py::arg("name"), py::arg("parent"), py::arg( "inputWidth" ), py::arg( "outputWidth" ), py::arg( "initialRouting" ), py::arg( "controlInput" ) = true, "Constructor with an initial routing list.") ; } } // namepace rcl } // namespace python } // namespace visr
34.813559
90
0.61149
s3a-spatialaudio
011826155d71a772bbc03d9e112238400f826590
1,500
cpp
C++
books/tech/cpp/std-17/n_m_josuttis-cpp_std_lib/ch_18-concurrency/03-std_thread/main.cpp
ordinary-developer/education
1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58
[ "MIT" ]
null
null
null
books/tech/cpp/std-17/n_m_josuttis-cpp_std_lib/ch_18-concurrency/03-std_thread/main.cpp
ordinary-developer/education
1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58
[ "MIT" ]
null
null
null
books/tech/cpp/std-17/n_m_josuttis-cpp_std_lib/ch_18-concurrency/03-std_thread/main.cpp
ordinary-developer/education
1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58
[ "MIT" ]
null
null
null
#include <thread> #include <chrono> #include <random> #include <exception> #include <iostream> void doSomething(int num, char c) noexcept { try { std::default_random_engine dre{ (long unsigned int)(42 * c) }; std::uniform_int_distribution<int> id{ 10, 1000 }; for (int i{0}; i < num; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds{ id(dre) }); std::cout.put(c).flush(); } } catch (std::exception const& e) { std::cerr << "THREAD-EXCEPTION (thread " << std::this_thread::get_id() << "): " << e.what() << std::endl; } catch (...) { std::cerr << "THREAD-EXCEPTION (thred " << std::this_thread::get_id() << ")" << std::endl; } } int main() { try { std::thread t1{ doSomething, 5, '.' }; std::cout << "- started fg thread " << t1.get_id() << std::endl; for (int i{0}; i < 5; ++i) { std::thread t{ doSomething, 10, 'a' + i }; std::cout << "- detach started bg thread " << t.get_id() << std::endl; t.detach(); } std::cin.get(); std::cout << "- join fg thread " << t1.get_id() << std::endl; t1.join(); } catch (std::system_error const& e) { std::cerr << "can't start the thread " << e.what() << std::endl; } catch (std::exception const& e) { std::cerr << "EXCEPTION: " << e.what() << std::endl; } return 0; }
30
82
0.49
ordinary-developer
01199bd7dec47b449ce3b993524232a2e30e2273
4,723
cc
C++
mojo/edk/system/channel_endpoint_unittest.cc
jason-simmons/flutter_buildroot
1c9494e60378bd119d910d530344077fc091b3a5
[ "BSD-3-Clause" ]
1
2020-04-28T14:35:10.000Z
2020-04-28T14:35:10.000Z
mojo/edk/system/channel_endpoint_unittest.cc
jason-simmons/flutter_buildroot
1c9494e60378bd119d910d530344077fc091b3a5
[ "BSD-3-Clause" ]
null
null
null
mojo/edk/system/channel_endpoint_unittest.cc
jason-simmons/flutter_buildroot
1c9494e60378bd119d910d530344077fc091b3a5
[ "BSD-3-Clause" ]
1
2020-04-28T14:35:11.000Z
2020-04-28T14:35:11.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "mojo/edk/system/channel_endpoint.h" #include <memory> #include <utility> #include "mojo/edk/system/channel_test_base.h" #include "mojo/edk/system/message_in_transit_queue.h" #include "mojo/edk/system/message_in_transit_test_utils.h" #include "mojo/edk/system/test/timeouts.h" #include "mojo/edk/system/test_channel_endpoint_client.h" #include "mojo/edk/util/ref_ptr.h" #include "mojo/edk/util/waitable_event.h" #include "mojo/public/cpp/system/macros.h" using mojo::util::MakeRefCounted; using mojo::util::ManualResetWaitableEvent; namespace mojo { namespace system { namespace { class ChannelEndpointTest : public test::ChannelTestBase { public: ChannelEndpointTest() {} ~ChannelEndpointTest() override {} void SetUp() override { test::ChannelTestBase::SetUp(); io_thread()->PostTaskAndWait([this]() { CreateAndInitChannelOnIOThread(0); CreateAndInitChannelOnIOThread(1); }); } void TearDown() override { io_thread()->PostTaskAndWait([this]() { ShutdownChannelOnIOThread(0); ShutdownChannelOnIOThread(1); }); test::ChannelTestBase::TearDown(); } private: MOJO_DISALLOW_COPY_AND_ASSIGN(ChannelEndpointTest); }; TEST_F(ChannelEndpointTest, Basic) { auto client0 = MakeRefCounted<test::TestChannelEndpointClient>(); auto endpoint0 = MakeRefCounted<ChannelEndpoint>(client0.Clone(), 0); client0->Init(0, endpoint0.Clone()); channel(0)->SetBootstrapEndpoint(std::move(endpoint0)); auto client1 = MakeRefCounted<test::TestChannelEndpointClient>(); auto endpoint1 = MakeRefCounted<ChannelEndpoint>(client1.Clone(), 1); client1->Init(1, endpoint1.Clone()); channel(1)->SetBootstrapEndpoint(endpoint1.Clone()); // We'll receive a message on channel/client 0. ManualResetWaitableEvent read_event; client0->SetReadEvent(&read_event); // Make a test message. unsigned message_id = 0x12345678; std::unique_ptr<MessageInTransit> send_message = test::MakeTestMessage(message_id); // Check that our test utility works (at least in one direction). test::VerifyTestMessage(send_message.get(), message_id); // Event shouldn't be signaled yet. EXPECT_FALSE(read_event.IsSignaledForTest()); // Send it through channel/endpoint 1. EXPECT_TRUE(endpoint1->EnqueueMessage(std::move(send_message))); // Wait to receive it. EXPECT_FALSE(read_event.WaitWithTimeout(test::TinyTimeout())); client0->SetReadEvent(nullptr); // Check the received message. ASSERT_EQ(1u, client0->NumMessages()); std::unique_ptr<MessageInTransit> read_message = client0->PopMessage(); ASSERT_TRUE(read_message); test::VerifyTestMessage(read_message.get(), message_id); } // Checks that prequeued messages and messages sent at various stages later on // are all sent/received (and in the correct order). (Note: Due to the way // bootstrap endpoints work, the receiving side has to be set up first.) TEST_F(ChannelEndpointTest, Prequeued) { auto client0 = MakeRefCounted<test::TestChannelEndpointClient>(); auto endpoint0 = MakeRefCounted<ChannelEndpoint>(client0.Clone(), 0); client0->Init(0, endpoint0.Clone()); channel(0)->SetBootstrapEndpoint(std::move(endpoint0)); MessageInTransitQueue prequeued_messages; prequeued_messages.AddMessage(test::MakeTestMessage(1)); prequeued_messages.AddMessage(test::MakeTestMessage(2)); auto client1 = MakeRefCounted<test::TestChannelEndpointClient>(); auto endpoint1 = MakeRefCounted<ChannelEndpoint>(client1.Clone(), 1, &prequeued_messages); client1->Init(1, endpoint1.Clone()); EXPECT_TRUE(endpoint1->EnqueueMessage(test::MakeTestMessage(3))); EXPECT_TRUE(endpoint1->EnqueueMessage(test::MakeTestMessage(4))); channel(1)->SetBootstrapEndpoint(endpoint1.Clone()); EXPECT_TRUE(endpoint1->EnqueueMessage(test::MakeTestMessage(5))); EXPECT_TRUE(endpoint1->EnqueueMessage(test::MakeTestMessage(6))); // Wait for the messages. ManualResetWaitableEvent read_event; client0->SetReadEvent(&read_event); for (size_t i = 0; client0->NumMessages() < 6 && i < 6; i++) { EXPECT_FALSE(read_event.WaitWithTimeout(test::TinyTimeout())); read_event.Reset(); } client0->SetReadEvent(nullptr); // Check the received messages. ASSERT_EQ(6u, client0->NumMessages()); for (unsigned message_id = 1; message_id <= 6; message_id++) { std::unique_ptr<MessageInTransit> read_message = client0->PopMessage(); ASSERT_TRUE(read_message); test::VerifyTestMessage(read_message.get(), message_id); } } } // namespace } // namespace system } // namespace mojo
33.978417
79
0.745501
jason-simmons
011dbcc21459af503b5f4cbd95f68d50159949ae
2,863
cpp
C++
src/qmf/PosixEventNotifierImpl.cpp
irinabov/debian-qpid-cpp-1.35.0
98b0597071c0a5f0cc407a35d5a4690d9189065e
[ "Apache-2.0" ]
1
2017-11-29T09:19:02.000Z
2017-11-29T09:19:02.000Z
src/qmf/PosixEventNotifierImpl.cpp
irinabov/debian-qpid-cpp-1.35.0
98b0597071c0a5f0cc407a35d5a4690d9189065e
[ "Apache-2.0" ]
null
null
null
src/qmf/PosixEventNotifierImpl.cpp
irinabov/debian-qpid-cpp-1.35.0
98b0597071c0a5f0cc407a35d5a4690d9189065e
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "PosixEventNotifierImpl.h" #include "qpid/log/Statement.h" #include <fcntl.h> #include <unistd.h> #include <errno.h> #define BUFFER_SIZE 10 using namespace qmf; PosixEventNotifierImpl::PosixEventNotifierImpl(AgentSession& agentSession) : EventNotifierImpl(agentSession) { openHandle(); } PosixEventNotifierImpl::PosixEventNotifierImpl(ConsoleSession& consoleSession) : EventNotifierImpl(consoleSession) { openHandle(); } PosixEventNotifierImpl::~PosixEventNotifierImpl() { closeHandle(); } void PosixEventNotifierImpl::update(bool readable) { char buffer[BUFFER_SIZE]; if(readable && !this->isReadable()) { if (::write(myHandle, "1", 1) == -1) QPID_LOG(error, "PosixEventNotifierImpl::update write failed: " << errno); } else if(!readable && this->isReadable()) { if (::read(yourHandle, buffer, BUFFER_SIZE) == -1) QPID_LOG(error, "PosixEventNotifierImpl::update read failed: " << errno); } } void PosixEventNotifierImpl::openHandle() { int pair[2]; if(::pipe(pair) == -1) throw QmfException("Unable to open event notifier handle."); yourHandle = pair[0]; myHandle = pair[1]; int flags; flags = ::fcntl(yourHandle, F_GETFL); if((::fcntl(yourHandle, F_SETFL, flags | O_NONBLOCK)) == -1) throw QmfException("Unable to make remote handle non-blocking."); flags = ::fcntl(myHandle, F_GETFL); if((::fcntl(myHandle, F_SETFL, flags | O_NONBLOCK)) == -1) throw QmfException("Unable to make local handle non-blocking."); } void PosixEventNotifierImpl::closeHandle() { if(myHandle > 0) { ::close(myHandle); myHandle = -1; } if(yourHandle > 0) { ::close(yourHandle); yourHandle = -1; } } PosixEventNotifierImpl& PosixEventNotifierImplAccess::get(posix::EventNotifier& notifier) { return *notifier.impl; } const PosixEventNotifierImpl& PosixEventNotifierImplAccess::get(const posix::EventNotifier& notifier) { return *notifier.impl; }
25.336283
101
0.691233
irinabov
012666f0744f3fa671c5ef6e95a63055ea599901
4,812
hpp
C++
RobWork/src/rw/loaders/WorkCellLoader.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
1
2021-12-29T14:16:27.000Z
2021-12-29T14:16:27.000Z
RobWork/src/rw/loaders/WorkCellLoader.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
RobWork/src/rw/loaders/WorkCellLoader.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #ifndef RW_LOADERS_WORKCELLLOADER_HPP #define RW_LOADERS_WORKCELLLOADER_HPP /** * @file WorkCellLoader.hpp */ #include <rw/core/ExtensionPoint.hpp> #include <rw/graphics/WorkCellScene.hpp> #include <rw/models/WorkCell.hpp> #include <string> // Forward declarations // namespace rw { namespace models { class WorkCell; }} namespace rw { namespace loaders { /** @addtogroup loaders */ /* @{*/ /** * @brief Extendible interface for loading of WorkCells from files. * * By default, the following formats are supported: * * - All file extensions will be loaded using the standard %RobWork * %XML format (XMLRWLoader). * * The Factory defines an extension point "rw.loaders.WorkCellLoader" * that makes it possible to add loaders for other file formats than the * ones above. Extensions take precedence over the default loaders. * * The WorkCell loader is chosen based on a case-insensitive file extension * name. So "scene.wc.xml" will be loaded by the same loader as * "scene.WC.XML" * * WorkCells are supposed to be loaded using the Factory::load function: * \code{.cpp} * WorkCell::Ptr wc = WorkCellLoader::Factory::load("scene.wc.xml"); * if (wc.isNull()) * RW_TRHOW("WorkCell could not be loaded."); * \endcode * * Alternatively a WorkCell can be loaded in the less convenient way: * \code{.cpp} * WorkCellLoader::Ptr loader = WorkCellLoader::Factory::getWorkCellLoader(".wc.xml"); * WorkCell::Ptr wc = loader.loadWorkCell("scene.wc.xml"); * if (wc.isNull()) * RW_TRHOW("WorkCell could not be loaded."); * \endcode */ class WorkCellLoader { public: //! @brief Smart pointer of WorkCellLoader. typedef rw::core::Ptr< WorkCellLoader > Ptr; //! @brief Destructor. virtual ~WorkCellLoader () {} /** * @brief Load a WorkCell from a file. * @param filename [in] path to workcell file. */ virtual models::WorkCell::Ptr loadWorkCell (const std::string& filename) = 0; /** * @addtogroup extensionpoints * @extensionpoint{rw::loaders::WorkCellLoader::Factory, rw::loaders::WorkCellLoader, * rw.loaders.WorkCellLoader} */ /** * @brief A factory for WorkCellLoader. This factory also defines the * "rw.loaders.WorkCellLoader" extension point where new loaders can be * registered. */ class Factory : public rw::core::ExtensionPoint< WorkCellLoader > { public: /** * @brief Get loaders for a specific format. * @param format [in] the extension (including initial dot). * The extension name is case-insensitive. * @return a suitable loader. */ static rw::core::Ptr< WorkCellLoader > getWorkCellLoader (const std::string& format); /** * @brief Loads/imports a WorkCell from a file. * * An exception is thrown if the file can't be loaded. * The %RobWork %XML format is supported by default. * @param filename [in] name of the WorkCell file. */ static models::WorkCell::Ptr load (const std::string& filename); private: Factory () : rw::core::ExtensionPoint< WorkCellLoader > ( "rw.loaders.WorkCellLoader", "Extension point for for WorkCell loaders.") {} }; protected: //! @brief Constructor. WorkCellLoader () {} }; /** * @brief Shortcut type for the WorkCellLoader::Factory * @deprecated Please use WorkCellLoader::Factory instead. */ typedef WorkCellLoader::Factory WorkCellFactory; /**@}*/ }} // namespace rw::loaders #endif // end include guard
35.124088
97
0.602868
ZLW07
01291c7f1b1339e2224cb7beea76d52c251d5911
2,556
cpp
C++
QuantExt/qle/pricingengines/discountingcommodityforwardengine.cpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
335
2016-10-07T16:31:10.000Z
2022-03-02T07:12:03.000Z
QuantExt/qle/pricingengines/discountingcommodityforwardengine.cpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
59
2016-10-31T04:20:24.000Z
2022-01-03T16:39:57.000Z
QuantExt/qle/pricingengines/discountingcommodityforwardengine.cpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
180
2016-10-08T14:23:50.000Z
2022-03-28T10:43:05.000Z
/* Copyright (C) 2018 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include <ql/event.hpp> #include <qle/pricingengines/discountingcommodityforwardengine.hpp> using namespace std; using namespace QuantLib; namespace QuantExt { DiscountingCommodityForwardEngine::DiscountingCommodityForwardEngine(const Handle<YieldTermStructure>& discountCurve, boost::optional<bool> includeSettlementDateFlows, const Date& npvDate) : discountCurve_(discountCurve), includeSettlementDateFlows_(includeSettlementDateFlows), npvDate_(npvDate) { registerWith(discountCurve_); } void DiscountingCommodityForwardEngine::calculate() const { const auto& index = arguments_.index; Date npvDate = npvDate_; if (npvDate == Null<Date>()) { const auto& priceCurve = index->priceCurve(); QL_REQUIRE(!priceCurve.empty(), "DiscountingCommodityForwardEngine: need a non-empty price curve."); npvDate = priceCurve->referenceDate(); } const Date& maturity = arguments_.maturityDate; Date paymentDate = maturity; if (!arguments_.physicallySettled && arguments_.paymentDate != Date()) { paymentDate = arguments_.paymentDate; } results_.value = 0.0; if (!detail::simple_event(paymentDate).hasOccurred(Date(), includeSettlementDateFlows_)) { Real buySell = arguments_.position == Position::Long ? 1.0 : -1.0; Real forwardPrice = index->fixing(maturity); results_.value = arguments_.quantity * buySell * (forwardPrice - arguments_.strike) * discountCurve_->discount(paymentDate) / discountCurve_->discount(npvDate); results_.additionalResults["currentNotional"] = forwardPrice * arguments_.quantity; } } } // namespace QuantExt
38.149254
118
0.70579
mrslezak
012a9a9a9d63054e55210b2b055421000c502c34
12,570
cpp
C++
Attic/AtomicEditorReference/Source/UI/UIResourceFrame.cpp
honigbeutler123/AtomicGameEngine
c53425f19b216eb21ecd3bda85052aaa1a6f2aaa
[ "Apache-2.0", "MIT" ]
null
null
null
Attic/AtomicEditorReference/Source/UI/UIResourceFrame.cpp
honigbeutler123/AtomicGameEngine
c53425f19b216eb21ecd3bda85052aaa1a6f2aaa
[ "Apache-2.0", "MIT" ]
null
null
null
Attic/AtomicEditorReference/Source/UI/UIResourceFrame.cpp
honigbeutler123/AtomicGameEngine
c53425f19b216eb21ecd3bda85052aaa1a6f2aaa
[ "Apache-2.0", "MIT" ]
null
null
null
// Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved // Please see LICENSE.md in repository root for license information // https://github.com/AtomicGameEngine/AtomicGameEngine #include "AtomicEditor.h" #include <Atomic/Container/ArrayPtr.h> #include <Atomic/UI/UI.h> #include <Atomic/IO/Log.h> #include <Atomic/IO/File.h> #include <Atomic/IO/FileSystem.h> #include <Atomic/Resource/ResourceCache.h> #include <Atomic/Core/CoreEvents.h> #include <AtomicJS/Javascript/JSEvents.h> #include "UIResourceFrame.h" #include "../Editors/JSResourceEditor.h" #include "../Editors/SceneEditor3D/SceneEditor3D.h" #include "../Editors/ModelResourceEditor.h" #include "../Editors/TextResourceEditor.h" #include "../AEEvents.h" #include "../AEEditor.h" #include "UIIssuesWidget.h" #include "UIErrorsWidget.h" #include "UIConsoleWidget.h" #include "License/AELicenseSystem.h" #include "Modal/UIModalOps.h" #include "../Tools/External/AEExternalTooling.h" using namespace tb; namespace AtomicEditor { ResourceFrame::ResourceFrame(Context* context) : AEWidget(context), tabcontainer_(0), resourceLayout_(0) { UI* tbui = GetSubsystem<UI>(); tbui->LoadResourceFile(delegate_, "AtomicEditor/editor/ui/resourceframe.tb.txt"); tabcontainer_ = delegate_->GetWidgetByIDAndType<TBTabContainer>(TBIDC("tabcontainer")); assert(tabcontainer_); resourceLayout_ = delegate_->GetWidgetByIDAndType<TBLayout>(TBIDC("resourcelayout")); assert(resourceLayout_); delegate_->SetGravity(WIDGET_GRAVITY_ALL); issueswidget_ = new IssuesWidget(context_); errorswidget_ = new ErrorsWidget(context_); consolewidget_ = new ConsoleWidget(context_); SubscribeToEvent(E_FINDTEXT, HANDLER(ResourceFrame, HandleFindText)); SubscribeToEvent(E_FINDTEXTCLOSE, HANDLER(ResourceFrame, HandleFindTextClose)); SubscribeToEvent(E_EDITORPLAYSTARTED, HANDLER(ResourceFrame, HandlePlayStarted)); SubscribeToEvent(E_EDITORPLAYSTOPPED, HANDLER(ResourceFrame, HandlePlayStopped)); } ResourceFrame::~ResourceFrame() { } void ResourceFrame::HandleFindText(StringHash eventType, VariantMap& eventData) { using namespace FindText; if (!editors_.Size()) return; int page = tabcontainer_->GetCurrentPage(); TBWidget* widget = tabcontainer_->GetCurrentPageWidget(); if (editorLookup_.Contains(widget)) editorLookup_[widget]->FindText(eventData[P_TEXT].ToString(), (unsigned) eventData[P_FLAGS].GetInt()); } void ResourceFrame::HandleFindTextClose(StringHash eventType, VariantMap& eventData) { if (!editors_.Size()) return; TBWidget* widget = tabcontainer_->GetCurrentPageWidget(); if (editorLookup_.Contains(widget)) return editorLookup_[widget]->FindTextClose(); } void ResourceFrame::EditResource(const String& fullpath) { if (editors_.Contains(fullpath)) { NavigateToResource(fullpath); if (GetSubsystem<Editor>()->IsPlayingProject()) { SendEvent(E_EDITORPLAYSTOP); } return; } delegate_->SetVisibilility(WIDGET_VISIBILITY_VISIBLE); String ext = GetExtension(fullpath); ResourceEditor* editor = NULL; if (ext == ".js") { JSResourceEditor* jse = new JSResourceEditor(context_, fullpath, tabcontainer_); editor = jse; } else if (ext == ".scene") { SceneEditor3D* sre = new SceneEditor3D(context_, fullpath, tabcontainer_); editor = sre; } else if (ext == ".xml" || ext == ".txt") { //SceneResourceEditor* sre = new SceneResourceEditor(context_, fullpath, tabcontainer_); TextResourceEditor* tre = new TextResourceEditor(context_, fullpath, tabcontainer_); editor = tre; } else if (ext == ".mdl") { //ModelResourceEditor* mre = new ModelResourceEditor(context_, fullpath, tabcontainer_); //editor = mre; } else if (ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" || ext == ".ogg") { FileSystem* fs = GetSubsystem<FileSystem>(); fs->SystemOpen(fullpath); } else if (ext == ".tmx") { ExternalTooling* tooling = GetSubsystem<ExternalTooling>(); tooling->LaunchOrOpen("AtomicTiled", fullpath); } if (editor) { // We have a new editor so send a stop playing if we are playing if (GetSubsystem<Editor>()->IsPlayingProject()) { SendEvent(E_EDITORPLAYSTOP); } editors_[fullpath] = editor; editorLookup_[editor->GetRootContentWidget()] = editor; tabcontainer_->SetCurrentPage(tabcontainer_->GetNumPages()-1); editor->SetFocus(); // BEGIN LICENSE MANAGEMENT LicenseSystem* licenseSystem = GetSubsystem<LicenseSystem>(); if(licenseSystem->IsStandardLicense()) { if (ext == ".scene" ) { UIModalOps* ops = GetSubsystem<UIModalOps>(); ops->ShowInfoModule3D(); } } // END LICENSE MANAGEMENT } } void ResourceFrame::FocusCurrentTab() { TBWidget* widget = tabcontainer_->GetCurrentPageWidget(); if (widget && editorLookup_.Contains(widget)) return editorLookup_[widget]->SetFocus(); } bool ResourceFrame::OnEvent(const TBWidgetEvent &ev) { if (ev.type == EVENT_TYPE_TAB_CHANGED && ev.target == tabcontainer_) { TBWidget* widget = tabcontainer_->GetCurrentPageWidget(); if (widget) { if (editorLookup_.Contains(widget)) { ResourceEditor* editor = editorLookup_[widget]; if (editor != currentResourceEditor_) { VariantMap eventData; eventData[EditorResourceEditorChanged::P_RESOURCEEDITOR] = editor; SendEvent(E_EDITORRESOURCEEDITORCHANGED, eventData); currentResourceEditor_ = editor; } } } return true; } if (ev.type == EVENT_TYPE_KEY_DOWN || ev.type == EVENT_TYPE_SHORTCUT || ev.type == EVENT_TYPE_CLICK || ev.type == EVENT_TYPE_RIGHT_POINTER_UP) { if (!editors_.Size()) return false; TBWidget* widget = tabcontainer_->GetCurrentPageWidget(); if (editorLookup_.Contains(widget)) return editorLookup_[widget]->OnEvent(ev); } return false; } bool ResourceFrame::IssuesWidgetVisible() { TBWidget *child; for (child = resourceLayout_->GetFirstChild(); child; child = child->GetNext()) { if (child == issueswidget_->GetWidgetDelegate()) break; } return child != NULL; } void ResourceFrame::ShowIssuesWidget(bool show) { if (show && ErrorsWidgetVisible()) ShowErrorsWidget(false); if (show && ConsoleWidgetVisible()) ShowConsoleWidget(false); TBWidget *child; for (child = resourceLayout_->GetFirstChild(); child; child = child->GetNext()) { if (child == issueswidget_->GetWidgetDelegate()) break; } if (show) { if (!child) { resourceLayout_->AddChild(issueswidget_->GetWidgetDelegate()); } issueswidget_->UpdateIssues(); } else { if (child) resourceLayout_->RemoveChild(child); } } bool ResourceFrame::ErrorsWidgetVisible() { TBWidget *child; for (child = resourceLayout_->GetFirstChild(); child; child = child->GetNext()) { if (child == errorswidget_->GetWidgetDelegate()) break; } return child != NULL; } void ResourceFrame::ShowErrorsWidget(bool show) { if (show && ConsoleWidgetVisible()) ShowConsoleWidget(false); if (show && IssuesWidgetVisible()) ShowIssuesWidget(false); TBWidget *child; for (child = resourceLayout_->GetFirstChild(); child; child = child->GetNext()) { if (child == errorswidget_->GetWidgetDelegate()) break; } if (show) { if (!child) { resourceLayout_->AddChild(errorswidget_->GetWidgetDelegate()); } errorswidget_->UpdateErrors(); } else { if (child) resourceLayout_->RemoveChild(child); } } bool ResourceFrame::ConsoleWidgetVisible() { TBWidget *child; for (child = resourceLayout_->GetFirstChild(); child; child = child->GetNext()) { if (child == consolewidget_->GetWidgetDelegate()) break; } return child != NULL; } void ResourceFrame::ShowConsoleWidget(bool show) { if (show && ErrorsWidgetVisible()) ShowErrorsWidget(false); if (show && IssuesWidgetVisible()) ShowIssuesWidget(false); TBWidget *child; for (child = resourceLayout_->GetFirstChild(); child; child = child->GetNext()) { if (child == consolewidget_->GetWidgetDelegate()) break; } if (show) { if (!child) { resourceLayout_->AddChild(consolewidget_->GetWidgetDelegate()); } } else { if (child) resourceLayout_->RemoveChild(child); } } void ResourceFrame::SendCurrentEditorEvent(const TBWidgetEvent &ev) { TBWidget* widget = tabcontainer_->GetCurrentPageWidget(); if (!widget) return; if (editorLookup_.Contains(widget)) editorLookup_[widget]->OnEvent(ev); } void ResourceFrame::NavigateToResource(const String& fullpath, int lineNumber, int tokenPos) { if (!editors_.Contains(fullpath)) return; ResourceEditor* editor = editors_[fullpath]; TBWidget* root = tabcontainer_->GetContentRoot(); int i = 0; for (TBWidget *child = root->GetFirstChild(); child; child = child->GetNext(), i++) { if (editorLookup_.Contains(child)) { if (editorLookup_[child] == editor) { break; } } } if (i < tabcontainer_->GetNumPages()) { tabcontainer_->SetCurrentPage(i); editor->SetFocus(); // this cast could be better String ext = GetExtension(fullpath); if (ext == ".js" && lineNumber != -1) { JSResourceEditor* jse = (JSResourceEditor*) editor; jse->GotoLineNumber(lineNumber); } else if (ext == ".js" && tokenPos != -1) { JSResourceEditor* jse = (JSResourceEditor*) editor; jse->GotoTokenPos(tokenPos); } } } bool ResourceFrame::HasUnsavedModifications() { HashMap<String, SharedPtr<ResourceEditor> >::ConstIterator itr; for (itr = editors_.Begin(); itr != editors_.End(); itr++) { if (itr->second_->HasUnsavedModifications()) return true; } return false; } void ResourceFrame::CloseResourceEditor(ResourceEditor* editor, bool navigateToAvailableResource) { assert(editors_.Contains(editor->GetFullPath())); editors_.Erase(editor->GetFullPath()); TBWidget* root = tabcontainer_->GetContentRoot(); bool found = false; for (TBWidget *child = root->GetFirstChild(); child; child = child->GetNext()) { if (editorLookup_.Contains(child)) { if (editorLookup_[child] == editor) { found = true; root->RemoveChild(child); editorLookup_.Erase(child); break; } } } assert(found); tabcontainer_->SetCurrentPage(-1); if (navigateToAvailableResource) { if (editors_.Size()) { HashMap<String, SharedPtr<ResourceEditor> >::ConstIterator itr = editors_.End(); itr--; NavigateToResource(itr->second_->GetFullPath()); } } } void ResourceFrame::HandlePlayStarted(StringHash eventType, VariantMap& eventData) { //delegate_->SetVisibilility(WIDGET_VISIBILITY_INVISIBLE); //delegate_->SetIgnoreInput(true); //delegate_->SetState(WIDGET_STATE_DISABLED, true); } void ResourceFrame::HandlePlayStopped(StringHash eventType, VariantMap& eventData) { //delegate_->SetVisibilility(WIDGET_VISIBILITY_VISIBLE); //delegate_->SetIgnoreInput(false); //delegate_->SetState(WIDGET_STATE_DISABLED, false); } void ResourceFrame::CloseAllResourceEditors() { Vector<SharedPtr<ResourceEditor> > editors = editors_.Values(); for (unsigned i = 0; i < editors.Size(); i++) editors[i]->Close(false); } }
25.705521
97
0.626571
honigbeutler123
012e389215c245c995bada2c7188cf25d9b0c1c2
758
cpp
C++
examples/cat.cpp
davidwed/sqlrelay_rudiments
6ccffdfc5fa29f8c0226f3edc2aa888aa1008347
[ "BSD-2-Clause-NetBSD" ]
null
null
null
examples/cat.cpp
davidwed/sqlrelay_rudiments
6ccffdfc5fa29f8c0226f3edc2aa888aa1008347
[ "BSD-2-Clause-NetBSD" ]
null
null
null
examples/cat.cpp
davidwed/sqlrelay_rudiments
6ccffdfc5fa29f8c0226f3edc2aa888aa1008347
[ "BSD-2-Clause-NetBSD" ]
null
null
null
#include <rudiments/file.h> #include <rudiments/stdio.h> int main(int argc, const char **argv) { file f; char buffer[1024]; // for each file specified on the command line... for (int32_t i=1; i<argc; i++) { // open the file if (!f.open(argv[i],O_RDONLY)) { continue; } // read chunks from the file and print each chunk.. ssize_t bytesread=0; do { // attempt to read 1024 bytes into the buffer bytesread=f.read(buffer,1024); // bytesread will be the number of bytes that were // actually read, 0 at EOF, or a negative number // if an error occurred if (bytesread>0) { // print the buffer stdoutput.write(buffer,bytesread); } // exit if we read fewer than 1024 bytes } while (bytesread==1024); } }
20.486486
53
0.649077
davidwed
01364d67efa8f300831d925aede8ec3d2bc52368
1,722
cpp
C++
UVA/AdHoc/195_Anagram.cpp
shiva92/Contests
720bb3699f774a6ea1f99e888e0cd784e63130c8
[ "Apache-2.0" ]
null
null
null
UVA/AdHoc/195_Anagram.cpp
shiva92/Contests
720bb3699f774a6ea1f99e888e0cd784e63130c8
[ "Apache-2.0" ]
null
null
null
UVA/AdHoc/195_Anagram.cpp
shiva92/Contests
720bb3699f774a6ea1f99e888e0cd784e63130c8
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cstdlib> #include <cstring> #include <vector> #include <algorithm> #include <sstream> #include <set> #include <climits> #include <cstdio> #include <string> using namespace std; bool next_permute(int arr[], int start, int end) { if (start == end) return false; if (end - start == 1) return false; int i, j, k; i = end; while (true) { j = i; i--; if (arr[i] < arr[j]) { k = end; while (!(arr[i] < arr[--k])); swap(arr[i], arr[k]); reverse(arr + j, arr + end); return true; } if (i == start) { reverse(arr, arr + end); return false; } } return true; } bool compare(const string & first, const string & second) { string a = first; string b = second; int alen = a.length(), blen = b.length(); int i = 0, j = 0; char x, y; while (i < alen && j < blen) { if (a[i] < b[j]) { if (isupper(a[i]) && islower(b[j])) { if (tolower(a[i]) <= b[j]) return true; return false; } return true; } else if (a[i] > b[j]) { if (islower(a[i]) && isupper(b[j])) { if (a[i] >= tolower(b[j])) return false; return true; } return false; } i++; j++; } // if (i == alen && j == blen) // return true; // else if (i < alen) // return true; return true; } int main() { std::ios_base::sync_with_stdio(false); // freopen("1.txt", "r", stdin); // freopen("2.txt", "w", stdout); string str, temp; int t; int i, len; cin >> t; while (t--) { cin >> str; sort(str.begin(), str.end()); vector<string> v; do { v.push_back(str); } while (next_permutation(str.begin(), str.end())); len = (int)v.size(); sort(v.begin(), v.end(), compare); for (i = 0; i < len; i++) cout << v[i] << '\n'; } }
18.717391
59
0.54007
shiva92
01365e9f3734e85a8a8317b257856a288f23c9aa
278
cpp
C++
src/guiobject.cpp
Groogy/derelict
5ca82ae5a5a553e292e388706a27b53840cf3afa
[ "Zlib" ]
null
null
null
src/guiobject.cpp
Groogy/derelict
5ca82ae5a5a553e292e388706a27b53840cf3afa
[ "Zlib" ]
null
null
null
src/guiobject.cpp
Groogy/derelict
5ca82ae5a5a553e292e388706a27b53840cf3afa
[ "Zlib" ]
null
null
null
#include "guiobject.hpp" GuiObject::~GuiObject() { } void GuiObject::update() { for(auto& hook : myUpdateHooks) { hook(*this); } } void GuiObject::processEvent(const sf::Event&) { } void GuiObject::attachUpdateHook(UpdateHook hook) { myUpdateHooks.push_back(hook); }
11.583333
49
0.697842
Groogy
0136a96208f2b3890c4d90590887df753d7e3658
118
cpp
C++
app/src/app_main.cpp
Darckore/CmakeTemplate
f2d5ba1a17fd7304518e3b8ededfea1d638f8dc8
[ "Unlicense" ]
null
null
null
app/src/app_main.cpp
Darckore/CmakeTemplate
f2d5ba1a17fd7304518e3b8ededfea1d638f8dc8
[ "Unlicense" ]
null
null
null
app/src/app_main.cpp
Darckore/CmakeTemplate
f2d5ba1a17fd7304518e3b8ededfea1d638f8dc8
[ "Unlicense" ]
null
null
null
#include "libsomething/libsource.h" int main() { something::derpy::init(); something::derpy::msg(); return 0; }
14.75
35
0.661017
Darckore
013dc4f0bac66a539b63e706331a85a7f75971f9
1,461
cpp
C++
NetworkManager/SynchrounousTcp/SyncTcpClient.cpp
lahmer/lbcms
5910aecae63082f838c7be28316764c3ed3a08f1
[ "MIT" ]
null
null
null
NetworkManager/SynchrounousTcp/SyncTcpClient.cpp
lahmer/lbcms
5910aecae63082f838c7be28316764c3ed3a08f1
[ "MIT" ]
null
null
null
NetworkManager/SynchrounousTcp/SyncTcpClient.cpp
lahmer/lbcms
5910aecae63082f838c7be28316764c3ed3a08f1
[ "MIT" ]
null
null
null
// // Created by lahmer on 8/12/16. // #include "SyncTcpClient.h" namespace lbcms{ namespace network{ SyncTcpClient::SyncTcpClient(std::string ipv4, int port){ m_ios = new boost::asio::io_service(); m_endPoint = new boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::from_string(ipv4),port); m_socket = new boost::asio::ip::tcp::socket(*m_ios); m_socket->open(m_endPoint->protocol()); } void SyncTcpClient::Connect() { m_socket->connect(*m_endPoint); } void SyncTcpClient::Close() { m_socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both); m_socket->close(); } SyncTcpClient::~SyncTcpClient() { Close(); delete m_socket; delete m_ios; delete m_endPoint; } void SyncTcpClient::SendMessage(const std::string& msg) { std::string result = msg; if(result.at(result.length()-1) != '\n') result+='\n'; boost::asio::write(*m_socket , boost::asio::buffer(result)); } std::string SyncTcpClient::RecieveMessage() { boost::asio::streambuf buf; boost::asio::read_until(*m_socket,buf,'\n'); std::istream input(&buf); std::string response ; std::getline(input , response); return response; } } }
32.466667
113
0.540041
lahmer
014008b449ed269a8223297ad23cb343eb3f7aaf
4,505
cpp
C++
to/lang/OpenCV-2.2.0/modules/gpu/src/initialization.cpp
eirTony/INDI1
42642d8c632da53f60f2610b056547137793021b
[ "MIT" ]
null
null
null
to/lang/OpenCV-2.2.0/modules/gpu/src/initialization.cpp
eirTony/INDI1
42642d8c632da53f60f2610b056547137793021b
[ "MIT" ]
14
2016-11-24T10:46:39.000Z
2016-12-10T07:24:15.000Z
to/lang/OpenCV-2.2.0/modules/gpu/src/initialization.cpp
eirTony/INDI1
42642d8c632da53f60f2610b056547137793021b
[ "MIT" ]
null
null
null
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" using namespace cv; using namespace cv::gpu; #if !defined (HAVE_CUDA) CV_EXPORTS int cv::gpu::getCudaEnabledDeviceCount() { return 0; } CV_EXPORTS string cv::gpu::getDeviceName(int /*device*/) { throw_nogpu(); return 0; } CV_EXPORTS void cv::gpu::setDevice(int /*device*/) { throw_nogpu(); } CV_EXPORTS int cv::gpu::getDevice() { throw_nogpu(); return 0; } CV_EXPORTS void cv::gpu::getComputeCapability(int /*device*/, int& /*major*/, int& /*minor*/) { throw_nogpu(); } CV_EXPORTS int cv::gpu::getNumberOfSMs(int /*device*/) { throw_nogpu(); return 0; } CV_EXPORTS void cv::gpu::getGpuMemInfo(size_t& /*free*/, size_t& /*total*/) { throw_nogpu(); } CV_EXPORTS bool cv::gpu::hasNativeDoubleSupport(int /*device*/) { throw_nogpu(); return false; } CV_EXPORTS bool cv::gpu::hasAtomicsSupport(int /*device*/) { throw_nogpu(); return false; } #else /* !defined (HAVE_CUDA) */ CV_EXPORTS int cv::gpu::getCudaEnabledDeviceCount() { int count; cudaSafeCall( cudaGetDeviceCount( &count ) ); return count; } CV_EXPORTS string cv::gpu::getDeviceName(int device) { cudaDeviceProp prop; cudaSafeCall( cudaGetDeviceProperties( &prop, device) ); return prop.name; } CV_EXPORTS void cv::gpu::setDevice(int device) { cudaSafeCall( cudaSetDevice( device ) ); } CV_EXPORTS int cv::gpu::getDevice() { int device; cudaSafeCall( cudaGetDevice( &device ) ); return device; } CV_EXPORTS void cv::gpu::getComputeCapability(int device, int& major, int& minor) { cudaDeviceProp prop; cudaSafeCall( cudaGetDeviceProperties( &prop, device) ); major = prop.major; minor = prop.minor; } CV_EXPORTS int cv::gpu::getNumberOfSMs(int device) { cudaDeviceProp prop; cudaSafeCall( cudaGetDeviceProperties( &prop, device ) ); return prop.multiProcessorCount; } CV_EXPORTS void cv::gpu::getGpuMemInfo(size_t& free, size_t& total) { cudaSafeCall( cudaMemGetInfo( &free, &total ) ); } CV_EXPORTS bool cv::gpu::hasNativeDoubleSupport(int device) { int major, minor; getComputeCapability(device, major, minor); return major > 1 || (major == 1 && minor >= 3); } CV_EXPORTS bool cv::gpu::hasAtomicsSupport(int device) { int major, minor; getComputeCapability(device, major, minor); return major > 1 || (major == 1 && minor >= 1); } #endif
35.472441
113
0.698779
eirTony
014956f089ee6588a275ffed9fd8f4f07189301e
1,943
hpp
C++
src/programs/libpfasst_swe_sphere/x/SWE_Sphere_TS_PFASST_lg_irk_lc_n_erk_ver01.hpp
raaphy/sweet
69fcf1920becd4fd762ded2f726614aae00b3f69
[ "MIT" ]
6
2017-11-20T08:12:46.000Z
2021-03-11T15:32:36.000Z
src/programs/libpfasst_swe_sphere/x/SWE_Sphere_TS_PFASST_lg_irk_lc_n_erk_ver01.hpp
raaphy/sweet
69fcf1920becd4fd762ded2f726614aae00b3f69
[ "MIT" ]
4
2018-02-02T21:46:33.000Z
2022-01-11T11:10:27.000Z
src/programs/libpfasst_swe_sphere/x/SWE_Sphere_TS_PFASST_lg_irk_lc_n_erk_ver01.hpp
raaphy/sweet
69fcf1920becd4fd762ded2f726614aae00b3f69
[ "MIT" ]
12
2016-03-01T18:33:34.000Z
2022-02-08T22:20:31.000Z
/* * SWE_Sphere_TS_PFASST_lg_irk_lf_n_erk.hpp * * Created on: 30 May 2017 * Author: Martin Schreiber <SchreiberX@gmail.com> */ #ifndef SRC_PROGRAMS_SWE_SPHERE_REXI_SWE_SPHERE_TS_PFASST_LG_IRK_LF_N_ERK_HPP_ #define SRC_PROGRAMS_SWE_SPHERE_REXI_SWE_SPHERE_TS_PFASST_LG_IRK_LF_N_ERK_HPP_ #include <sweet/sphere/SphereData_Spectral.hpp> #include <sweet/sphere/SphereOperators_SphereData.hpp> #include <sweet/sphere/SphereTimestepping_ExplicitRK.hpp> #include <limits> #include <sweet/SimulationVariables.hpp> #include "SWE_Sphere_TS_PFASST_interface.hpp" #include "SWE_Sphere_TS_PFASST_lg_irk.hpp" #include "SWE_Sphere_TS_PFASST_lg_cn.hpp" #include "SWE_Sphere_TS_PFASST_lg_erk_lc_n_erk.hpp" class SWE_Sphere_TS_PFASST_lg_irk_lc_n_erk : public SWE_Sphere_TS_PFASST_interface { SimulationVariables &simVars; SphereOperators_SphereData &op; int version_id; int timestepping_order; int timestepping_order2; double timestep_size; /* * Linear time steppers */ SWE_Sphere_TS_PFASST_lg_irk timestepping_lg_irk; SWE_Sphere_TS_PFASST_lg_cn timestepping_lg_cn; /* * Non-linear time steppers */ SWE_Sphere_TS_PFASST_lg_erk_lc_n_erk timestepping_lg_erk_lc_n_erk; SphereTimestepping_ExplicitRK timestepping_rk_nonlinear; public: SWE_Sphere_TS_PFASST_lg_irk_lc_n_erk( SimulationVariables &i_simVars, SphereOperators_SphereData &i_op ); void setup( int i_order, ///< order of RK time stepping method int i_order2, ///< order of RK time stepping method for non-linear parts int i_version_id ); void run_timestep_nonpert( SphereData_Spectral &io_phi, ///< prognostic variables SphereData_Spectral &io_vort, ///< prognostic variables SphereData_Spectral &io_div, ///< prognostic variables double i_fixed_dt = 0, double i_simulation_timestamp = -1 ); virtual ~SWE_Sphere_TS_PFASST_lg_irk_lc_n_erk(); }; #endif /* SRC_PROGRAMS_SWE_PLANE_REXI_SWE_PLANE_TS_PFASST_LN_ERK_HPP_ */
25.233766
82
0.808029
raaphy
0149eb6a10551bf132bfad7527c9f751d3a9a640
1,936
cpp
C++
src/Evel/Signal.cpp
hleclerc/Evel
c607adda555f417dfc9fb4de310c07c48ea3642f
[ "Apache-2.0" ]
null
null
null
src/Evel/Signal.cpp
hleclerc/Evel
c607adda555f417dfc9fb4de310c07c48ea3642f
[ "Apache-2.0" ]
null
null
null
src/Evel/Signal.cpp
hleclerc/Evel
c607adda555f417dfc9fb4de310c07c48ea3642f
[ "Apache-2.0" ]
null
null
null
#include "System/SocketUtil.h" #include "EvLoop.h" #include "Signal.h" #include <sys/signalfd.h> #include <string.h> #include <signal.h> #include <unistd.h> #include <errno.h> namespace Evel { static int make_signal_fd( const int *sigs ) { // set up a mask sigset_t mask; sigemptyset( &mask ); for( int i = 0; sigs[ i ] >= 0; ++i ) sigaddset( &mask, sigs[ i ] ); // block signals if ( sigprocmask( SIG_BLOCK, &mask, 0 ) == -1 ) { perror( "sigprocmask" ); return -1; } // get a (non blocking) file descriptor while ( true ) { int fd = signalfd( -1, &mask, 0 ); if ( fd < 0 ) { if ( errno == EINTR ) continue; perror( "signalfd" ); return -1; } if ( set_non_block( fd ) < 0 ) { perror( "non blocking signalfd" ); close( fd ); return -1; } return fd; } } Signal::Signal( const int *sigs, bool need_wait ) : Event( make_signal_fd( sigs ), need_wait ) { } void Signal::on_inp() { signalfd_siginfo sig_info; while ( true ) { ssize_t s = read( fd, &sig_info, sizeof( sig_info ) ); // end of the connection if ( s == 0 ) return close(); // error if ( s < 0 ) { if ( errno == EINTR ) continue; if ( errno == EAGAIN or errno == EWOULDBLOCK ) return; ev_loop->err( "Pb reading signals: {}", strerror( errno ) ); close(); return; } if ( s < (ssize_t)sizeof( sig_info ) ) { ev_loop->err( "TODO: partial read with signals" ); close(); return; } signal( sig_info.ssi_signo ); } } bool Signal::out_are_sent() const { return true; } bool Signal::may_have_out() const { return false; } } // namespace Evel
22
96
0.496384
hleclerc
014b3775fe75b815c2ff0d8d59dcf819ecac80a6
498
hpp
C++
inference-engine/src/low_precision_transformations/include/low_precision/variadic_split.hpp
monroid/openvino
8272b3857ef5be0aaa8abbf7bd0d5d5615dc40b6
[ "Apache-2.0" ]
2,406
2020-04-22T15:47:54.000Z
2022-03-31T10:27:37.000Z
inference-engine/src/low_precision_transformations/include/low_precision/variadic_split.hpp
thomas-yanxin/openvino
031e998a15ec738c64cc2379d7f30fb73087c272
[ "Apache-2.0" ]
4,948
2020-04-22T15:12:39.000Z
2022-03-31T18:45:42.000Z
inference-engine/src/low_precision_transformations/include/low_precision/variadic_split.hpp
thomas-yanxin/openvino
031e998a15ec738c64cc2379d7f30fb73087c272
[ "Apache-2.0" ]
991
2020-04-23T18:21:09.000Z
2022-03-31T18:40:57.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <vector> #include "split.hpp" #include "ngraph/node.hpp" namespace ngraph { namespace pass { namespace low_precision { class LP_TRANSFORMATIONS_API VariadicSplitTransformation : public SplitTransformation { public: NGRAPH_RTTI_DECLARATION; VariadicSplitTransformation(const Params& params = Params()); }; } // namespace low_precision } // namespace pass } // namespace ngraph
20.75
87
0.761044
monroid
014b650e6d099d9a88f5e71c15b7534533e440d2
13,819
cpp
C++
src/core/primitives/Instance.cpp
chaosink/tungsten
88ea02044dbaf20472a8173b6752460b50c096d8
[ "Apache-2.0", "Unlicense" ]
1,655
2015-01-12T13:05:37.000Z
2022-03-31T13:37:57.000Z
src/core/primitives/Instance.cpp
chaosink/tungsten
88ea02044dbaf20472a8173b6752460b50c096d8
[ "Apache-2.0", "Unlicense" ]
65
2015-01-13T08:34:28.000Z
2021-06-08T05:07:58.000Z
src/core/primitives/Instance.cpp
chaosink/tungsten
88ea02044dbaf20472a8173b6752460b50c096d8
[ "Apache-2.0", "Unlicense" ]
190
2015-01-12T14:53:05.000Z
2022-03-30T17:30:00.000Z
#include "Instance.hpp" #include "TriangleMesh.hpp" #include "sampling/PathSampleGenerator.hpp" #include "sampling/SampleWarp.hpp" #include "bsdfs/NullBsdf.hpp" #include "io/JsonObject.hpp" #include "io/Scene.hpp" #include <iomanip> namespace Tungsten { void Instance::buildProxy() { std::vector<Vec3f> masterSize; for (const auto &m : _master) { m->prepareForRender(); masterSize.emplace_back(m->bounds().diagonal()/m->transform().extractScaleVec()); } std::vector<Vertex> verts(_instanceCount*4); std::vector<TriangleI> tris(_instanceCount*2); for (uint32 i = 0; i < _instanceCount; ++i) { Vec3f diag = masterSize[_instanceId[i]]; float size = diag.length(); Vec3f v0 = _master[_instanceId[i]]->transform()*Vec3f( size, 0.0f, size); Vec3f v1 = _master[_instanceId[i]]->transform()*Vec3f(-size, 0.0f, size); Vec3f v2 = _master[_instanceId[i]]->transform()*Vec3f(-size, 0.0f, -size); Vec3f v3 = _master[_instanceId[i]]->transform()*Vec3f( size, 0.0f, -size); v0 = _instancePos[i] + _instanceRot[i]*v0; v1 = _instancePos[i] + _instanceRot[i]*v1; v2 = _instancePos[i] + _instanceRot[i]*v2; v3 = _instancePos[i] + _instanceRot[i]*v3; verts[i*4 + 0] = v0; verts[i*4 + 1] = v1; verts[i*4 + 2] = v2; verts[i*4 + 3] = v3; tris[i*2 + 0] = TriangleI(i*4 + 0, i*4 + 1, i*4 + 2, _instanceId[i]); tris[i*2 + 1] = TriangleI(i*4 + 0, i*4 + 2, i*4 + 3, _instanceId[i]); } _proxy = std::make_shared<TriangleMesh>(std::move(verts), std::move(tris), std::make_shared<NullBsdf>(), "Instances", false, false); } const Primitive &Instance::getMaster(const IntersectionTemporary &data) const { return *_master[_instanceId[data.flags]]; } float Instance::powerToRadianceFactor() const { return 0.0f; } void Instance::fromJson(JsonPtr value, const Scene &scene) { Primitive::fromJson(value, scene); _master.clear(); if (auto master = value["masters"]) for (unsigned i = 0; i < master.size(); ++i) _master.emplace_back(scene.fetchPrimitive(master[i])); if (auto instances = value["instances"]) { if (instances.isString()) { _instanceFileA = scene.fetchResource(instances); } else { _instanceFileA = nullptr; _instanceCount = instances.size(); _instancePos = zeroAlloc<Vec3f>(_instanceCount); _instanceRot = zeroAlloc<QuaternionF>(_instanceCount); _instanceId = zeroAlloc<uint8>(_instanceCount); for (unsigned i = 0; i < _instanceCount; ++i) { instances[i].getField("id", _instanceId[i]); Mat4f transform; instances[i].getField("transform", transform); _instancePos[i] = transform.extractTranslationVec(); _instanceRot[i] = QuaternionF::fromMatrix(transform.extractRotation()); } } } if (auto instanceA = value["instancesA"]) _instanceFileA = scene.fetchResource(instanceA); if (auto instanceB = value["instancesB"]) _instanceFileB = scene.fetchResource(instanceB); value.getField("ratio", _ratio); } rapidjson::Value Instance::toJson(Allocator &allocator) const { rapidjson::Value masters; masters.SetArray(); for (const auto &m : _master) masters.PushBack(m->toJson(allocator), allocator); JsonObject result{Primitive::toJson(allocator), allocator, "type", "instances", "masters", std::move(masters), "ratio", _ratio }; if (_instanceFileB) { result.add("instancesB", *_instanceFileB); if (_instanceFileA) result.add("instancesA", *_instanceFileA); } else if (_instanceFileA) { result.add("instances", *_instanceFileA); } else { rapidjson::Value instances; instances.SetArray(); for (uint32 i = 0; i < _instanceCount; ++i) { JsonObject instance{allocator, "id", _instanceId[i], "transform", Mat4f::translate(_instancePos[i])*_instanceRot[i].toMatrix() }; instances.PushBack(rapidjson::Value(instance), allocator); } result.add("instances", std::move(instances)); } return result; } const uint32 CompressionLossy = 1; const uint32 CompressionLZO = 2; void loadLossyInstance(InputStreamHandle &in, const Box3f &bounds, Vec3f &pos, QuaternionF &f) { CONSTEXPR uint32 PosW = 21; CONSTEXPR uint32 RotW = 8; CONSTEXPR uint32 AxisW = 12; uint32 a, b, c; FileUtils::streamRead(in, a); FileUtils::streamRead(in, b); FileUtils::streamRead(in, c); uint32 mask = ((1 << 21) - 1); uint32 x = (a >> 11); uint32 y = ((a << 10) | (b >> 22)) & mask; uint32 z = ((b >> 1) & mask); uint32 rot = c & ((1 << RotW) - 1); uint32 axisX = (c >> RotW) & ((1 << AxisW) - 1); uint32 axisY = (c >> (RotW + AxisW)) & ((1 << AxisW) - 1); float axisXf = (axisX/float(1 << AxisW))*2.0f - 1.0f; float axisYf = (axisY/float(1 << AxisW))*2.0f - 1.0f; float rotW = TWO_PI*rot/(1 << RotW); Vec3f w(axisXf, axisYf, std::sqrt(max(1 - sqr(axisXf) - sqr(axisYf), 0.0f))); pos = lerp(bounds.min(), bounds.max(), Vec3f(Vec3u(x, y, z))/float(1 << PosW)); f = QuaternionF(rotW, w); } void loadLosslessInstance(InputStreamHandle &in, Vec3f &pos, QuaternionF &f) { FileUtils::streamRead(in, pos); Vec3f w; FileUtils::streamRead(in, w); float angle = w.length(); w = (angle > 0 ? w/angle : Vec3f(0.0f, 1.0f, 0.0f)); f = QuaternionF(angle, w); } void saveLossyInstance(OutputStreamHandle &out, const Box3f &bounds, Vec3f pos, QuaternionF f) { CONSTEXPR uint32 RotW = 8; CONSTEXPR uint32 AxisW = 12; Vec3u xyz(clamp(Vec3i(((pos - bounds.min())/(bounds.max() - bounds.min()))*(1 << 21)), Vec3i(0), Vec3i((1 << 21) - 1))); uint32 a, b; a = (xyz[0] << 11) | (xyz[1] >> 10); b = (xyz[1] << 22) | (xyz[2] << 1); float angle = std::acos(clamp(f.x(), -1.0f, 1.0f))*2.0f; Vec3f w = Vec3f(f[1], f[2], f[3]).normalized(); if (f[3] < 0) { w = -w; angle = TWO_PI - angle; } uint32 rot = clamp(int(angle/TWO_PI*(1 << RotW)), 0, (1 << RotW) - 1); uint32 axisX = clamp(int((w[0]*0.5f + 0.5f)*(1 << AxisW)), 0, (1 << AxisW) - 1); uint32 axisY = clamp(int((w[1]*0.5f + 0.5f)*(1 << AxisW)), 0, (1 << AxisW) - 1); uint32 c = (axisY << (RotW + AxisW)) | (axisX << RotW) | rot; FileUtils::streamWrite(out, a); FileUtils::streamWrite(out, b); FileUtils::streamWrite(out, c); } void saveLosslessInstance(OutputStreamHandle &out, Vec3f pos, QuaternionF f) { FileUtils::streamWrite(out, pos); float angle = std::acos(clamp(f.x(), -1.0f, 1.0f))*2.0f; Vec3f w = Vec3f(f[1], f[2], f[3]).normalized()*angle; FileUtils::streamWrite(out, w); } bool loadInstances(const Path &path, Box3f &bounds, uint32 &instanceCount, std::unique_ptr<Vec3f[]> &instancePos, std::unique_ptr<QuaternionF[]> &instanceRot, std::unique_ptr<uint8[]> &instanceId) { InputStreamHandle in = FileUtils::openInputStream(path); if (!in) return false; FileUtils::streamRead(in, instanceCount); uint32 compressed; FileUtils::streamRead(in, compressed); FileUtils::streamRead(in, bounds); instancePos.reset(new Vec3f[instanceCount]); instanceRot.reset(new QuaternionF[instanceCount]); instanceId.reset(new uint8[instanceCount]); if (compressed & CompressionLossy) for (uint32 i = 0; i < instanceCount; ++i) loadLossyInstance(in, bounds, instancePos[i], instanceRot[i]); else for (uint32 i = 0; i < instanceCount; ++i) loadLosslessInstance(in, instancePos[i], instanceRot[i]); FileUtils::streamRead(in, instanceId.get(), instanceCount); return true; } bool saveInstances(const Path &path, uint32 instanceCount, const Vec3f *instancePos, const QuaternionF *instanceRot, const uint8 *instanceId, bool compress) { OutputStreamHandle out = FileUtils::openOutputStream(path); if (!out) return false; FileUtils::streamWrite(out, instanceCount); FileUtils::streamWrite(out, uint32(compress ? CompressionLossy : 0)); Box3f bounds; for (uint32 i = 0; i < instanceCount; ++i) bounds.grow(instancePos[i]); FileUtils::streamWrite(out, bounds); if (compress) for (uint32 i = 0; i < instanceCount; ++i) saveLossyInstance(out, bounds, instancePos[i], instanceRot[i]); else for (uint32 i = 0; i < instanceCount; ++i) saveLosslessInstance(out, instancePos[i], instanceRot[i]); FileUtils::streamWrite(out, instanceId, instanceCount); return true; } Instance::Instance() : _ratio(0), _instanceCount(0) { } void Instance::loadResources() { Box3f bounds; if (_instanceFileA) loadInstances(*_instanceFileA, bounds, _instanceCount, _instancePos, _instanceRot, _instanceId); if (_instanceFileB) { uint32 instanceCountB; std::unique_ptr<Vec3f[]> instancePosB; std::unique_ptr<QuaternionF[]> instanceRotB; std::unique_ptr<uint8[]> instanceIdB; if (loadInstances(*_instanceFileB, bounds, instanceCountB, instancePosB, instanceRotB, instanceIdB) && _instanceCount == instanceCountB) { for (uint32 i = 0; i < _instanceCount; ++i) { _instancePos[i] = lerp(_instancePos[i], instancePosB[i], _ratio); _instanceRot[i] = _instanceRot[i].slerp(instanceRotB[i], _ratio); } } } } void Instance::saveResources() { if (_instanceFileA && !_instanceFileB) saveInstances(*_instanceFileA, _instanceCount, _instancePos.get(), _instanceRot.get(), _instanceId.get(), false); } bool Instance::intersect(Ray &ray, IntersectionTemporary &data) const { bool hit = false; uint32 prim; _bvh->trace(ray, [&](Ray &ray, uint32 id, float tMin, const Vec3pf &/*bounds*/) { QuaternionF invRot = _instanceRot[id].conjugate(); Ray localRay = ray.scatter(invRot*(ray.pos() - _instancePos[id]), invRot*ray.dir(), tMin); bool hitI = _master[_instanceId[id]]->intersect(localRay, data); if (hitI) { hit = true; prim = id; ray.setFarT(localRay.farT()); } }); if (hit) { data.primitive = this; data.flags = prim; } return hit; } bool Instance::occluded(const Ray &ray) const { Ray tmpRay = ray; bool occluded = false; _bvh->trace(tmpRay, [&](Ray &ray, uint32 id, float tMin, const Vec3pf &/*bounds*/) { QuaternionF invRot = _instanceRot[id].conjugate(); Ray localRay = ray.scatter(invRot*(ray.pos() - _instancePos[id]), invRot*ray.dir(), tMin); bool occludedI = _master[_instanceId[id]]->occluded(localRay); if (occludedI) { occluded = true; ray.setFarT(ray.farT() - 1); } }); return occluded; } bool Instance::hitBackside(const IntersectionTemporary &data) const { return getMaster(data).hitBackside(data); } void Instance::intersectionInfo(const IntersectionTemporary &data, IntersectionInfo &info) const { getMaster(data).intersectionInfo(data, info); QuaternionF rot = _instanceRot[data.flags]; info.Ng = rot*info.Ng; info.Ns = rot*info.Ns; info.p = _instancePos[data.flags] + rot*info.p; info.primitive = this; } bool Instance::tangentSpace(const IntersectionTemporary &/*data*/, const IntersectionInfo &/*info*/, Vec3f &/*T*/, Vec3f &/*B*/) const { return false; } bool Instance::isSamplable() const { return false; } void Instance::makeSamplable(const TraceableScene &/*scene*/, uint32 /*threadIndex*/) { } bool Instance::invertParametrization(Vec2f /*uv*/, Vec3f &/*pos*/) const { return false; } bool Instance::isDirac() const { return false; } bool Instance::isInfinite() const { return false; } float Instance::approximateRadiance(uint32 /*threadIndex*/, const Vec3f &/*p*/) const { return -1.0f; } Box3f Instance::bounds() const { return _bounds; } const TriangleMesh &Instance::asTriangleMesh() { if (!_proxy) buildProxy(); return *_proxy; } void Instance::prepareForRender() { for (auto &m : _master) m->prepareForRender(); Bvh::PrimVector prims; prims.reserve(_instanceCount); auto rot = QuaternionF::fromMatrix(_transform.extractRotation()); for (uint32 i = 0; i < _instanceCount; ++i) { _instancePos[i] = _transform*_instancePos[i]; _instanceRot[i] = rot*_instanceRot[i]; } std::vector<Box3f> masterBounds; for (const auto &m : _master) masterBounds.emplace_back(m->bounds()); _bounds = Box3f(); for (uint32 i = 0; i < _instanceCount; ++i) { Box3f bLocal = masterBounds[_instanceId[i]]; Box3f bGlobal; for (float x : {0, 1}) for (float y : {0, 1}) for (float z : {0, 1}) bGlobal.grow(_instancePos[i] + _instanceRot[i]*lerp(bLocal.min(), bLocal.max(), Vec3f(x, y, z))); _bounds.grow(bGlobal); prims.emplace_back(Bvh::Primitive(bGlobal, bGlobal.center(), i)); } _bvh.reset(new Bvh::BinaryBvh(std::move(prims), 2)); Primitive::prepareForRender(); } void Instance::teardownAfterRender() { _bvh.reset(); loadResources(); Primitive::teardownAfterRender(); } int Instance::numBsdfs() const { return _master.size(); } std::shared_ptr<Bsdf> &Instance::bsdf(int index) { return _master[index]->bsdf(0); } void Instance::setBsdf(int index, std::shared_ptr<Bsdf> &bsdf) { _master[index]->setBsdf(0, bsdf); } Primitive *Instance::clone() { return nullptr; } }
30.106754
196
0.619799
chaosink
014bc0069b9e903f3dac59f1bcb180f4f51c96e5
2,258
cpp
C++
core/unittest/wrapper/test_knowhere.cpp
Gracieeea/milvus
e44e455acd2731ad7c8f645e6fd13dd8f0eeea86
[ "Apache-2.0" ]
null
null
null
core/unittest/wrapper/test_knowhere.cpp
Gracieeea/milvus
e44e455acd2731ad7c8f645e6fd13dd8f0eeea86
[ "Apache-2.0" ]
null
null
null
core/unittest/wrapper/test_knowhere.cpp
Gracieeea/milvus
e44e455acd2731ad7c8f645e6fd13dd8f0eeea86
[ "Apache-2.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "server/Config.h" #include "wrapper/KnowhereResource.h" #include "wrapper/utils.h" #include <fiu-local.h> #include <fiu-control.h> #include <gtest/gtest.h> TEST_F(KnowhereTest, KNOWHERE_RESOURCE_TEST) { std::string config_path(CONFIG_PATH); config_path += CONFIG_FILE; milvus::server::Config& config = milvus::server::Config::GetInstance(); milvus::Status s = config.LoadConfigFile(config_path); ASSERT_TRUE(s.ok()); milvus::engine::KnowhereResource::Initialize(); milvus::engine::KnowhereResource::Finalize(); #ifdef MILVUS_GPU_VERSION fiu_init(0); fiu_enable("check_config_gpu_resource_enable_fail", 1, NULL, 0); s = milvus::engine::KnowhereResource::Initialize(); ASSERT_FALSE(s.ok()); fiu_disable("check_config_gpu_resource_enable_fail"); fiu_enable("KnowhereResource.Initialize.disable_gpu", 1, NULL, 0); s = milvus::engine::KnowhereResource::Initialize(); ASSERT_TRUE(s.ok()); fiu_disable("KnowhereResource.Initialize.disable_gpu"); fiu_enable("check_gpu_resource_config_build_index_fail", 1, NULL, 0); s = milvus::engine::KnowhereResource::Initialize(); ASSERT_FALSE(s.ok()); fiu_disable("check_gpu_resource_config_build_index_fail"); fiu_enable("check_gpu_resource_config_search_fail", 1, NULL, 0); s = milvus::engine::KnowhereResource::Initialize(); ASSERT_FALSE(s.ok()); fiu_disable("check_gpu_resource_config_search_fail"); #endif }
38.271186
75
0.741364
Gracieeea
014caf9301b4fcc559a661bf05d0866733468fc2
32,217
cpp
C++
src/interpreter/instructions/integer.cpp
lioncash/riscv-emu
e903baf122cbbc2b40f58f4c50ff970893ffe746
[ "MIT" ]
1
2021-09-17T04:07:26.000Z
2021-09-17T04:07:26.000Z
src/interpreter/instructions/integer.cpp
lioncash/riscv-emu
e903baf122cbbc2b40f58f4c50ff970893ffe746
[ "MIT" ]
null
null
null
src/interpreter/instructions/integer.cpp
lioncash/riscv-emu
e903baf122cbbc2b40f58f4c50ff970893ffe746
[ "MIT" ]
null
null
null
#include <riscy/interpreter/state.hpp> #include <algorithm> #include <array> #include <bit> #include <type_traits> #include "common/bit_util.hpp" #include "interpreter/instructions/helper.hpp" #include "interpreter/instructions/instructions.hpp" namespace riscy { using UnaryBitFn = RISCVState::GPRType (*)(RISCVState::GPRType value); // For implementing CLZ{W}, CPOP{W}, CTZ{W}, ORC.B, REV8, SEXT.{B, H}, and ZEXT.H static void UnaryBitInstruction(RISCVState& state, const uint32_t opcode, UnaryBitFn unary_fn) noexcept { const auto rd = Bits<7, 11>(opcode); if (rd == 0) [[unlikely]] { return; } const auto rs = Bits<15, 19>(opcode); const auto input = state.GPR(rs); const auto result = unary_fn(input); state.GPR(rd) = result; } using BinaryBitFn = RISCVState::GPRType (*)(RISCVState::GPRType lhs, RISCVState::GPRType rhs); // Handles an instruction that takes two register inputs static void BinaryBitInstruction(RISCVState& state, const uint32_t opcode, BinaryBitFn binary_fn) noexcept { const auto rd = Bits<7, 11>(opcode); if (rd == 0) [[unlikely]] { return; } const auto rs1 = Bits<15, 19>(opcode); const auto rs2 = Bits<20, 24>(opcode); const auto lhs = state.GPR(rs1); const auto rhs = state.GPR(rs2); const auto result = binary_fn(lhs, rhs); state.GPR(rd) = result; } // Handles an instruction that takes one register input and one immediate input static void BinaryBitInstructionWithImm(RISCVState& state, const uint32_t opcode, BinaryBitFn binary_fn) noexcept { const auto rd = Bits<7, 11>(opcode); if (rd == 0) [[unlikely]] { return; } const auto rs = Bits<15, 19>(opcode); const auto imm = Bits<20, 25>(opcode); const auto lhs = state.GPR(rs); const auto result = binary_fn(lhs, imm); state.GPR(rd) = result; } using ITypeFn = RISCVState::GPRType (*)(RISCVState::GPRType lhs, RISCVState::GPRType imm); // Handles a RISC-V I-type instruction. Allows injecting different behavior through // the imm_fn function parameter. static void ITypeInstruction(RISCVState& state, const uint32_t opcode, ITypeFn imm_fn) noexcept { const auto rd = Bits<7, 11>(opcode); if (rd == 0) [[unlikely]] { return; } const auto rs = Bits<15, 19>(opcode); const auto& s = state.GPR(rs); const auto imm = SignExtend<12, RISCVState::GPRType>(Bits<20, 31>(opcode)); const auto result = imm_fn(s, imm); state.GPR(rd) = result; } using RTypeFn = RISCVState::GPRType (*)(RISCVState::GPRType lhs, RISCVState::GPRType rhs); // Handles a RISC-V R-type instruction. Allows injecting different behavior through // the reg_fn function parameter. static void RTypeInstruction(RISCVState& state, const uint32_t opcode, RTypeFn reg_fn) noexcept { const auto rd = Bits<7, 11>(opcode); if (rd == 0) [[unlikely]] { return; } const auto rs1 = Bits<15, 19>(opcode); const auto rs2 = Bits<20, 24>(opcode); const auto& s1 = state.GPR(rs1); const auto& s2 = state.GPR(rs2); const auto result = reg_fn(s1, s2); state.GPR(rd) = result; } using CATypeFn = RISCVState::GPRType (*)(RISCVState::GPRType lhs, RISCVState::GPRType rhs); // Handles a RISC-V CA-type instruction. Allows injecting different behavior through // the ca_fn function parameter. static void CATypeInstruction(RISCVState& state, const uint32_t opcode, CATypeFn ca_fn) noexcept { const auto rds = ExpandCompressedRegisterIndex<7, 9>(opcode); const auto rs = ExpandCompressedRegisterIndex<2, 4>(opcode); const auto lhs = state.GPR(rds); const auto rhs = state.GPR(rs); const auto result = ca_fn(lhs, rhs); state.GPR(rds) = result; } using CompressedArithImmTypeFn = RISCVState::GPRType (*)(RISCVState::GPRType lhs, RISCVState::GPRType rhs); static void CompressedArithImmInstruction(RISCVState& state, const uint32_t opcode, CompressedArithImmTypeFn cai_fn) { const auto rds = ExpandCompressedRegisterIndex<7, 9>(opcode); const auto shift_amount = Bits<2, 6>(opcode) | (static_cast<uint32_t>(Bit<12>(opcode)) << 5); const auto value = state.GPR(rds); const auto result = cai_fn(value, shift_amount); state.GPR(rds) = result; } void ADD(RISCVState& state, const uint32_t opcode) { RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return lhs + rhs; }); } void ADDI(RISCVState& state, const uint32_t opcode) { ITypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType imm) { return lhs + imm; }); } void ADDIW(RISCVState& state, const uint32_t opcode) { ITypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType imm) { const auto result = static_cast<uint32_t>(lhs + imm); return SignExtend<32, RISCVState::GPRType>(result); }); } void ADDW(RISCVState& state, const uint32_t opcode) { RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto result = static_cast<uint32_t>(lhs + rhs); return SignExtend<32, RISCVState::GPRType>(result); }); } void ADD_UW(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return (lhs & 0xFFFFFFFFU) + rhs; }); } void AND(RISCVState& state, const uint32_t opcode) { RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return lhs & rhs; }); } void ANDI(RISCVState& state, const uint32_t opcode) { ITypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType imm) { return lhs & imm; }); } void ANDN(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return lhs & ~rhs; }); } void AUIPC(RISCVState& state, const uint32_t opcode) { const auto rd = Bits<7, 11>(opcode); if (rd == 0) [[unlikely]] { return; } const auto imm = SignExtend<32, RISCVState::GPRType>(opcode & 0xFFFFF000); const auto offset = imm + state.PC(); state.GPR(rd) = offset; } void BCLR(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { constexpr auto mask = BitSize<RISCVState::GPRType>() - 1; const auto index = rhs & mask; const auto bit = RISCVState::GPRType{1} << index; return lhs & ~bit; }); } void BCLRI(RISCVState& state, const uint32_t opcode) { BinaryBitInstructionWithImm(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto bit = RISCVState::GPRType{1} << rhs; return lhs & ~bit; }); } void BEXT(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { constexpr auto mask = BitSize<RISCVState::GPRType>() - 1; const auto index = rhs & mask; const auto bit = lhs >> index; return bit & 1; }); } void BEXTI(RISCVState& state, const uint32_t opcode) { BinaryBitInstructionWithImm(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto bit = lhs >> rhs; return bit & 1; }); } void BINV(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { constexpr auto mask = BitSize<RISCVState::GPRType>() - 1; const auto index = rhs & mask; const auto bit = RISCVState::GPRType{1} << index; return lhs ^ bit; }); } void BINVI(RISCVState& state, const uint32_t opcode) { BinaryBitInstructionWithImm(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto bit = RISCVState::GPRType{1} << rhs; return lhs ^ bit; }); } void BSET(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { constexpr auto mask = BitSize<RISCVState::GPRType>() - 1; const auto index = rhs & mask; const auto bit = RISCVState::GPRType{1} << index; return lhs | bit; }); } void BSETI(RISCVState& state, const uint32_t opcode) { BinaryBitInstructionWithImm(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto bit = RISCVState::GPRType{1} << rhs; return lhs | bit; }); } void C_ADD(RISCVState& state, const uint32_t opcode) { const auto rds = Bits<7, 11>(opcode); const auto rs = Bits<2, 6>(opcode); const auto lhs = state.GPR(rds); const auto rhs = state.GPR(rs); const auto result = lhs + rhs; state.GPR(rds) = result; } void C_ADDI(RISCVState& state, const uint32_t opcode) { const auto rds = Bits<7, 11>(opcode); const auto imm = Bits<2, 6>(opcode) | (static_cast<uint32_t>(Bit<12>(opcode)) << 5); const auto simm = SignExtend<6, RISCVState::GPRType>(imm); const auto result = state.GPR(rds) + simm; state.GPR(rds) = result; } void C_ADDI4SPN(RISCVState& state, const uint32_t opcode) { constexpr auto make_imm = [](const uint32_t op) { // clang-format off return ((op & 0x0020) >> 2) | ((op & 0x0040) >> 4) | ((op & 0x0780) >> 1) | ((op & 0x1800) >> 7); // clang-format on }; const auto rd = ExpandCompressedRegisterIndex<2, 4>(opcode); const auto increment = make_imm(opcode); const auto result = state.GPR(2) + increment; state.GPR(rd) = result; } void C_ADDI16SP(RISCVState& state, const uint32_t opcode) { constexpr auto make_imm = [](const uint32_t op) { // clang-format off return ((op & 0x0004) << 3) | ((op & 0x0018) << 4) | ((op & 0x0020) << 1) | ((op & 0x0040) >> 2) | ((op & 0x1000) >> 3); // clang-format on }; const auto imm = make_imm(opcode); const auto increment = SignExtend<10, RISCVState::GPRType>(imm); state.GPR(2) += increment; } void C_ADDIW(RISCVState& state, const uint32_t opcode) { const auto rds = Bits<7, 11>(opcode); const auto imm = Bits<2, 6>(opcode) | (static_cast<uint32_t>(Bit<12>(opcode)) << 5); const auto simm = SignExtend<6, RISCVState::GPRType>(imm); const auto sum = static_cast<uint32_t>(state.GPR(rds) + simm); const auto result = SignExtend<32, RISCVState::GPRType>(sum); state.GPR(rds) = result; } void C_ADDW(RISCVState& state, const uint32_t opcode) { CATypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto add = static_cast<uint32_t>(lhs + rhs); return SignExtend<32, RISCVState::GPRType>(add); }); } void C_AND(RISCVState& state, const uint32_t opcode) { CATypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return lhs & rhs; }); } void C_ANDI(RISCVState& state, const uint32_t opcode) { CompressedArithImmInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return lhs & SignExtend<6, RISCVState::GPRType>(rhs); }); } void C_LI(RISCVState& state, const uint32_t opcode) { const auto rd = Bits<7, 11>(opcode); const auto imm = Bits<2, 6>(opcode) | (static_cast<uint32_t>(Bit<12>(opcode)) << 5); const auto simm = SignExtend<6, RISCVState::GPRType>(imm); state.GPR(rd) = simm; } void C_LUI(RISCVState& state, const uint32_t opcode) { const auto rd = Bits<7, 11>(opcode); const auto imm = (Bits<2, 6>(opcode) << 12) | (static_cast<uint32_t>(Bit<12>(opcode)) << 17); const auto simm = SignExtend<18, RISCVState::GPRType>(imm); state.GPR(rd) = simm; } void C_MV(RISCVState& state, const uint32_t opcode) { const auto rd = Bits<7, 11>(opcode); const auto rs = Bits<2, 6>(opcode); state.GPR(rd) = state.GPR(rs); } void C_NOP([[maybe_unused]] RISCVState& state, [[maybe_unused]] const uint32_t opcode) { // Do nothing. } void C_OR(RISCVState& state, const uint32_t opcode) { CATypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return lhs | rhs; }); } void C_SLLI(RISCVState& state, const uint32_t opcode) { const auto rds = Bits<7, 11>(opcode); const auto shift_amount = Bits<2, 6>(opcode) | (static_cast<uint32_t>(Bit<12>(opcode)) << 5); const auto result = state.GPR(rds) << shift_amount; state.GPR(rds) = result; } void C_SRAI(RISCVState& state, const uint32_t opcode) { CompressedArithImmInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { using Signed = std::make_signed_t<RISCVState::GPRType>; using Unsigned = RISCVState::GPRType; const auto result_signed = static_cast<Signed>(lhs) >> rhs; const auto result_unsigned = static_cast<Unsigned>(result_signed); return result_unsigned; }); } void C_SRLI(RISCVState& state, const uint32_t opcode) { CompressedArithImmInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return lhs >> rhs; }); } void C_SUB(RISCVState& state, const uint32_t opcode) { CATypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return lhs - rhs; }); } void C_SUBW(RISCVState& state, const uint32_t opcode) { CATypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto sub = static_cast<uint32_t>(lhs - rhs); return SignExtend<32, RISCVState::GPRType>(sub); }); } void C_XOR(RISCVState& state, const uint32_t opcode) { CATypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return lhs ^ rhs; }); } void CLMUL(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { RISCVState::GPRType result{}; constexpr auto bit_size = BitSize<RISCVState::GPRType>(); for (size_t i = 0; i < bit_size; i++) { if ((rhs & (1ULL << i)) == 0) { continue; } result ^= lhs << i; } return result; }); } // Functional bits of a reversed carryless multiply. // This is also used to implement CLMULH, since it's equivalent to performing // a CLMULR and then shifting the result to the right by 1. static RISCVState::GPRType CLMULRImpl(const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) noexcept { RISCVState::GPRType result{}; constexpr auto bit_size = BitSize<RISCVState::GPRType>(); for (size_t i = 0; i < bit_size; i++) { if ((rhs & (1ULL << i)) == 0) { continue; } result ^= lhs >> (bit_size - i - 1); } return result; } void CLMULH(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return CLMULRImpl(lhs, rhs) >> 1; }); } void CLMULR(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { RISCVState::GPRType result{}; constexpr auto bit_size = BitSize<RISCVState::GPRType>(); for (size_t i = 0; i < bit_size; i++) { if ((rhs & (1ULL << i)) == 0) { continue; } result ^= lhs >> (bit_size - i - 1); } return result; }); } void CLZ(RISCVState& state, const uint32_t opcode) { UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) { return static_cast<RISCVState::GPRType>(std::countl_zero(input)); }); } void CLZW(RISCVState& state, const uint32_t opcode) { UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) { return static_cast<RISCVState::GPRType>(std::countl_zero(static_cast<uint32_t>(input))); }); } void CPOP(RISCVState& state, const uint32_t opcode) { UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) { return static_cast<RISCVState::GPRType>(std::popcount(input)); }); } void CPOPW(RISCVState& state, const uint32_t opcode) { UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) { return static_cast<RISCVState::GPRType>(std::popcount(static_cast<uint32_t>(input))); }); } void CTZ(RISCVState& state, const uint32_t opcode) { UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) { return static_cast<RISCVState::GPRType>(std::countr_zero(input)); }); } void CTZW(RISCVState& state, const uint32_t opcode) { UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) { return static_cast<RISCVState::GPRType>(std::countr_zero(static_cast<uint32_t>(input))); }); } void LUI(RISCVState& state, const uint32_t opcode) { const auto rd = Bits<7, 11>(opcode); if (rd == 0) [[unlikely]] { return; } const auto imm = SignExtend<32, RISCVState::GPRType>(opcode & 0xFFFFF000); state.GPR(rd) = imm; } void MAX(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { using Unsigned = RISCVState::GPRType; using Signed = std::make_signed_t<Unsigned>; const auto signed_lhs = static_cast<Signed>(lhs); const auto signed_rhs = static_cast<Signed>(rhs); const auto max_value = std::max(signed_lhs, signed_rhs); return static_cast<Unsigned>(max_value); }); } void MAXU(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return std::max(lhs, rhs); }); } void MIN(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { using Unsigned = RISCVState::GPRType; using Signed = std::make_signed_t<Unsigned>; const auto signed_lhs = static_cast<Signed>(lhs); const auto signed_rhs = static_cast<Signed>(rhs); const auto max_value = std::min(signed_lhs, signed_rhs); return static_cast<Unsigned>(max_value); }); } void MINU(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return std::min(lhs, rhs); }); } void OR(RISCVState& state, const uint32_t opcode) { RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return lhs | rhs; }); } void ORC_B(RISCVState& state, const uint32_t opcode) { UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) { static constexpr std::array byte_masks{ UINT64_C(0x00000000000000FF), UINT64_C(0x000000000000FF00), UINT64_C(0x0000000000FF0000), UINT64_C(0x00000000FF000000), UINT64_C(0x000000FF00000000), UINT64_C(0x0000FF0000000000), UINT64_C(0x00FF000000000000), UINT64_C(0xFF00000000000000), }; RISCVState::GPRType result = 0; constexpr auto num_bytes = sizeof(RISCVState::GPRType); for (size_t i = 0; i < num_bytes; i++) { if ((input & byte_masks[i]) == 0) { continue; } result |= byte_masks[i]; } return result; }); } void ORI(RISCVState& state, const uint32_t opcode) { ITypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType imm) { return lhs | imm; }); } void ORN(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return lhs | ~rhs; }); } void REV8(RISCVState& state, const uint32_t opcode) { UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) { return ByteSwap64(input); }); } void ROL(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { constexpr auto mask = BitSize<RISCVState::GPRType>() - 1; const auto index = static_cast<int32_t>(rhs & mask); return std::rotl(lhs, index); }); } void ROLW(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { constexpr auto mask = BitSize<RISCVState::GPRType>() - 1; const auto index = static_cast<int32_t>(rhs & mask); const auto result = std::rotl(static_cast<uint32_t>(lhs), index); return SignExtend<32, RISCVState::GPRType>(result); }); } void ROR(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { constexpr auto mask = BitSize<RISCVState::GPRType>() - 1; const auto index = static_cast<int32_t>(rhs & mask); return std::rotr(lhs, index); }); } void RORI(RISCVState& state, const uint32_t opcode) { BinaryBitInstructionWithImm(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto index = static_cast<int32_t>(rhs); const auto result = std::rotr(lhs, index); return result; }); } void RORIW(RISCVState& state, const uint32_t opcode) { BinaryBitInstructionWithImm(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto index = static_cast<int32_t>(rhs); const auto result = std::rotr(static_cast<uint32_t>(lhs), index); return SignExtend<32, RISCVState::GPRType>(result); }); } void RORW(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { constexpr auto mask = BitSize<RISCVState::GPRType>() - 1; const auto index = static_cast<int32_t>(rhs & mask); const auto result = std::rotr(static_cast<uint32_t>(lhs), index); return SignExtend<32, RISCVState::GPRType>(result); }); } void SEXT_B(RISCVState& state, const uint32_t opcode) { UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) { return SignExtend<8, RISCVState::GPRType>(input & 0xFF); }); } void SEXT_H(RISCVState& state, const uint32_t opcode) { UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) { return SignExtend<16, RISCVState::GPRType>(input & 0xFFFF); }); } void SH1ADD(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return (lhs << 1U) + rhs; }); } void SH1ADD_UW(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto index = RISCVState::GPRType{static_cast<uint32_t>(lhs)}; return (index << 1U) + rhs; }); } void SH2ADD(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return (lhs << 2U) + rhs; }); } void SH2ADD_UW(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto index = RISCVState::GPRType{static_cast<uint32_t>(lhs)}; return (index << 2U) + rhs; }); } void SH3ADD(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return (lhs << 3U) + rhs; }); } void SH3ADD_UW(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto index = RISCVState::GPRType{static_cast<uint32_t>(lhs)}; return (index << 3U) + rhs; }); } void SLL(RISCVState& state, const uint32_t opcode) { RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto shift_amount = rhs & 0b111111; return lhs << shift_amount; }); } void SLLI(RISCVState& state, const uint32_t opcode) { const auto rd = Bits<7, 11>(opcode); if (rd == 0) [[unlikely]] { return; } const auto rs = Bits<15, 19>(opcode); const auto shift_amount = Bits<20, 25>(opcode); const auto& s = state.GPR(rs); const auto result = s << shift_amount; state.GPR(rd) = result; } void SLLIW(RISCVState& state, const uint32_t opcode) { const auto rd = Bits<7, 11>(opcode); if (rd == 0) [[unlikely]] { return; } const auto rs = Bits<15, 19>(opcode); const auto shift_amount = Bits<20, 24>(opcode); const auto& s = state.GPR(rs); const auto shifted = static_cast<uint32_t>(s) << shift_amount; const auto result = SignExtend<32, RISCVState::GPRType>(shifted); state.GPR(rd) = result; } void SLLI_UW(RISCVState& state, const uint32_t opcode) { BinaryBitInstructionWithImm(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto word = lhs & 0xFFFFFFFF; return word << rhs; }); } void SLLW(RISCVState& state, const uint32_t opcode) { RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto shift_amount = rhs & 0b11111; const auto shifted = static_cast<uint32_t>(lhs) << shift_amount; return SignExtend<32, RISCVState::GPRType>(shifted); }); } void SLT(RISCVState& state, const uint32_t opcode) { RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { using Signed = std::make_signed_t<RISCVState::GPRType>; using Unsigned = RISCVState::GPRType; const auto result = static_cast<Signed>(lhs) < static_cast<Signed>(rhs); return static_cast<Unsigned>(result); }); } void SLTI(RISCVState& state, const uint32_t opcode) { ITypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType imm) { using Signed = std::make_signed_t<RISCVState::GPRType>; const auto result = static_cast<Signed>(lhs) < static_cast<Signed>(imm); return static_cast<RISCVState::GPRType>(result); }); } void SLTIU(RISCVState& state, const uint32_t opcode) { ITypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType imm) { const auto result = lhs < imm; return static_cast<RISCVState::GPRType>(result); }); } void SLTU(RISCVState& state, const uint32_t opcode) { RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto result = lhs < rhs; return static_cast<RISCVState::GPRType>(result); }); } void SRA(RISCVState& state, const uint32_t opcode) { RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { using Signed = std::make_signed_t<RISCVState::GPRType>; using Unsigned = RISCVState::GPRType; const auto shift_amount = rhs & 0b111111; const auto result = static_cast<Signed>(lhs) >> shift_amount; return static_cast<Unsigned>(result); }); } void SRAI(RISCVState& state, const uint32_t opcode) { const auto rd = Bits<7, 11>(opcode); if (rd == 0) [[unlikely]] { return; } const auto rs = Bits<15, 19>(opcode); const auto shift_amount = Bits<20, 25>(opcode); using Signed = std::make_signed_t<RISCVState::GPRType>; using Unsigned = RISCVState::GPRType; const auto& s = state.GPR(rs); const auto result = static_cast<Signed>(s) >> shift_amount; state.GPR(rd) = static_cast<Unsigned>(result); } void SRAIW(RISCVState& state, const uint32_t opcode) { const auto rd = Bits<7, 11>(opcode); if (rd == 0) [[unlikely]] { return; } const auto rs = Bits<15, 19>(opcode); const auto shift_amount = Bits<20, 25>(opcode); const auto& s = state.GPR(rs); const auto shifted = static_cast<uint32_t>(static_cast<int32_t>(s) >> shift_amount); const auto result = SignExtend<32, RISCVState::GPRType>(shifted); state.GPR(rd) = result; } void SRAW(RISCVState& state, const uint32_t opcode) { RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto shift_amount = rhs & 0b11111; const auto shifted = static_cast<uint32_t>(static_cast<int32_t>(lhs) >> shift_amount); return SignExtend<32, RISCVState::GPRType>(shifted); }); } void SRL(RISCVState& state, const uint32_t opcode) { RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto shift_amount = rhs & 0b111111; return lhs >> shift_amount; }); } void SRLI(RISCVState& state, const uint32_t opcode) { const auto rd = Bits<7, 11>(opcode); if (rd == 0) [[unlikely]] { return; } const auto rs = Bits<15, 19>(opcode); const auto shift_amount = Bits<20, 25>(opcode); const auto& s = state.GPR(rs); const auto result = s >> shift_amount; state.GPR(rd) = result; } void SRLIW(RISCVState& state, const uint32_t opcode) { const auto rd = Bits<7, 11>(opcode); if (rd == 0) [[unlikely]] { return; } const auto rs = Bits<15, 19>(opcode); const auto shift_amount = Bits<20, 25>(opcode); const auto& s = state.GPR(rs); const auto shifted = static_cast<uint32_t>(s) >> shift_amount; const auto result = SignExtend<32, RISCVState::GPRType>(shifted); state.GPR(rd) = result; } void SRLW(RISCVState& state, const uint32_t opcode) { RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto shift_amount = rhs & 0b11111; const auto shift = static_cast<uint32_t>(lhs) >> shift_amount; return SignExtend<32, RISCVState::GPRType>(shift); }); } void SUB(RISCVState& state, const uint32_t opcode) { RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return lhs - rhs; }); } void SUBW(RISCVState& state, const uint32_t opcode) { RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { const auto sub = static_cast<uint32_t>(lhs - rhs); return SignExtend<32, RISCVState::GPRType>(sub); }); } void XNOR(RISCVState& state, const uint32_t opcode) { BinaryBitInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return ~(lhs ^ rhs); }); } void XOR(RISCVState& state, const uint32_t opcode) { RTypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType rhs) { return lhs ^ rhs; }); } void XORI(RISCVState& state, const uint32_t opcode) { ITypeInstruction(state, opcode, [](const RISCVState::GPRType lhs, const RISCVState::GPRType imm) { return lhs ^ imm; }); } void ZEXT_H(RISCVState& state, const uint32_t opcode) { UnaryBitInstruction(state, opcode, [](const RISCVState::GPRType input) { return input & 0xFFFF; }); } } // namespace riscy
34.236982
118
0.660055
lioncash
014e3fe2bfff7730be6a123335e6461b388f9042
232
cpp
C++
problems/sortingundersquaredistance/util/generator.cpp
stoman/CompetitiveProgramming
0000b64369b50e31c6f48939e837bdf6cece8ce4
[ "MIT" ]
2
2020-12-22T13:21:25.000Z
2021-12-12T22:26:26.000Z
problems/sortingundersquaredistance/util/generator.cpp
stoman/CompetitiveProgramming
0000b64369b50e31c6f48939e837bdf6cece8ce4
[ "MIT" ]
null
null
null
problems/sortingundersquaredistance/util/generator.cpp
stoman/CompetitiveProgramming
0000b64369b50e31c6f48939e837bdf6cece8ce4
[ "MIT" ]
null
null
null
#include <stdio.h> int main() { int n = 100000; printf("%d\n", n); for (int i = 0; i < n; i++) { printf("%d", 1000000000 - i); if(i < n - 1) { printf(" "); } } printf("\n"); }
17.846154
37
0.37069
stoman
014f17a2c334271589647c73aac1ff688bd40192
5,360
cpp
C++
WebKit/Source/WebCore/rendering/RenderFullScreen.cpp
JavaScriptTesting/LJS
9818dbdb421036569fff93124ac2385d45d01c3a
[ "Apache-2.0" ]
1
2019-06-18T06:52:54.000Z
2019-06-18T06:52:54.000Z
WebKit/Source/WebCore/rendering/RenderFullScreen.cpp
JavaScriptTesting/LJS
9818dbdb421036569fff93124ac2385d45d01c3a
[ "Apache-2.0" ]
null
null
null
WebKit/Source/WebCore/rendering/RenderFullScreen.cpp
JavaScriptTesting/LJS
9818dbdb421036569fff93124ac2385d45d01c3a
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2010 Apple 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #if ENABLE(FULLSCREEN_API) #include "RenderFullScreen.h" #include "RenderLayer.h" #if USE(ACCELERATED_COMPOSITING) #include "RenderLayerCompositor.h" #endif using namespace WebCore; class RenderFullScreenPlaceholder : public RenderBlock { public: RenderFullScreenPlaceholder(RenderFullScreen* owner) : RenderBlock(owner->document()) , m_owner(owner) { } private: virtual bool isRenderFullScreenPlaceholder() const { return true; } virtual void willBeDestroyed(); RenderFullScreen* m_owner; }; void RenderFullScreenPlaceholder::willBeDestroyed() { m_owner->setPlaceholder(0); RenderBlock::willBeDestroyed(); } RenderFullScreen::RenderFullScreen(Node* node) : RenderDeprecatedFlexibleBox(node) , m_placeholder(0) { setReplaced(false); } void RenderFullScreen::willBeDestroyed() { if (m_placeholder) { remove(); if (!m_placeholder->beingDestroyed()) m_placeholder->destroy(); ASSERT(!m_placeholder); } // RenderObjects are unretained, so notify the document (which holds a pointer to a RenderFullScreen) // if it's RenderFullScreen is destroyed. if (document() && document()->fullScreenRenderer() == this) document()->fullScreenRendererDestroyed(); RenderDeprecatedFlexibleBox::willBeDestroyed(); } static PassRefPtr<RenderStyle> createFullScreenStyle() { RefPtr<RenderStyle> fullscreenStyle = RenderStyle::createDefaultStyle(); // Create a stacking context: fullscreenStyle->setZIndex(INT_MAX); fullscreenStyle->setFontDescription(FontDescription()); fullscreenStyle->font().update(0); fullscreenStyle->setDisplay(BOX); fullscreenStyle->setBoxPack(Center); fullscreenStyle->setBoxAlign(BCENTER); fullscreenStyle->setBoxOrient(VERTICAL); fullscreenStyle->setPosition(FixedPosition); fullscreenStyle->setWidth(Length(100.0, Percent)); fullscreenStyle->setHeight(Length(100.0, Percent)); fullscreenStyle->setLeft(Length(0, WebCore::Fixed)); fullscreenStyle->setTop(Length(0, WebCore::Fixed)); fullscreenStyle->setBackgroundColor(Color::black); return fullscreenStyle.release(); } RenderObject* RenderFullScreen::wrapRenderer(RenderObject* object, Document* document) { RenderFullScreen* fullscreenRenderer = new (document->renderArena()) RenderFullScreen(document); fullscreenRenderer->setStyle(createFullScreenStyle()); if (object) { if (RenderObject* parent = object->parent()) { parent->addChild(fullscreenRenderer, object); object->remove(); } fullscreenRenderer->addChild(object); } document->setFullScreenRenderer(fullscreenRenderer); if (fullscreenRenderer->placeholder()) return fullscreenRenderer->placeholder(); return fullscreenRenderer; } void RenderFullScreen::unwrapRenderer() { RenderObject* holder = placeholder() ? placeholder() : this; if (holder->parent()) { RenderObject* child; while ((child = firstChild())) { child->remove(); holder->parent()->addChild(child, holder); } } remove(); document()->setFullScreenRenderer(0); } void RenderFullScreen::setPlaceholder(RenderBlock* placeholder) { m_placeholder = placeholder; } void RenderFullScreen::createPlaceholder(PassRefPtr<RenderStyle> style, const IntRect& frameRect) { if (style->width().isAuto()) style->setWidth(Length(frameRect.width(), Fixed)); if (style->height().isAuto()) style->setHeight(Length(frameRect.height(), Fixed)); if (!m_placeholder) { m_placeholder = new (document()->renderArena()) RenderFullScreenPlaceholder(this); m_placeholder->setStyle(style); if (parent()) { parent()->addChild(m_placeholder, this); remove(); } m_placeholder->addChild(this); } else m_placeholder->setStyle(style); } #endif
32.682927
105
0.707276
JavaScriptTesting
015443921d65bc1db235a2359a9a93972df22e2d
1,232
cpp
C++
examples/future_types/promises.cpp
alandefreitas/futures
326957b2bc4238716faecd7a5bff4616d967b4ce
[ "MIT" ]
10
2022-01-07T02:20:54.000Z
2022-03-11T05:24:13.000Z
examples/future_types/promises.cpp
alandefreitas/futures
326957b2bc4238716faecd7a5bff4616d967b4ce
[ "MIT" ]
null
null
null
examples/future_types/promises.cpp
alandefreitas/futures
326957b2bc4238716faecd7a5bff4616d967b4ce
[ "MIT" ]
null
null
null
#include <futures/algorithm.hpp> #include <futures/futures.hpp> #include <futures/executor/new_thread_executor.hpp> #include <iostream> int main() { using namespace futures; //[inline Inline promise promise<int> p1; cfuture<int> f1 = p1.get_future(); p1.set_value(2); std::cout << f1.get() << '\n'; //] //[thread Promise set by new thread promise<int> p2; cfuture<int> f2 = p2.get_future(); std::thread t2([&p2]() { p2.set_value(2); }); std::cout << f2.get() << '\n'; t2.join(); //] //[thread-executor Promise set by new thread executor auto f3 = async(make_new_thread_executor(), []() { return 2; }); std::cout << f3.get() << '\n'; //] //[thread_pool Promise set by thread pool promise<int> p4; cfuture<int> f4 = p4.get_future(); asio::thread_pool pool(1); asio::post(pool, [&p4]() { p4.set_value(2); }); std::cout << f4.get() << '\n'; //] //[custom_options Promise with custom options promise<int, future_options<>> p5; vfuture<int> f5 = p5.get_future(); std::thread t5([&p5]() { p5.set_value(2); }); std::cout << f5.get() << '\n'; t5.join(); //] }
23.245283
57
0.553571
alandefreitas
01564c8a718824868e1cc0161d0162ecb5505980
45
cpp
C++
cpp/cpp_class/friend/use_tv.cpp
lolyu/aoi
a26e5eb205aafadc7301b2e4acc67915d3bcc935
[ "MIT" ]
null
null
null
cpp/cpp_class/friend/use_tv.cpp
lolyu/aoi
a26e5eb205aafadc7301b2e4acc67915d3bcc935
[ "MIT" ]
null
null
null
cpp/cpp_class/friend/use_tv.cpp
lolyu/aoi
a26e5eb205aafadc7301b2e4acc67915d3bcc935
[ "MIT" ]
null
null
null
#include "tv.h" int main() { return 0; }
7.5
15
0.533333
lolyu
0158305873ffccd56f72565a3b3ed3305923a407
370
cpp
C++
OJ/PT/PT16.cpp
doan201203/truong_doan
68350b7a24ea266320cd41e1a4878e8a58b3f707
[ "Apache-2.0" ]
null
null
null
OJ/PT/PT16.cpp
doan201203/truong_doan
68350b7a24ea266320cd41e1a4878e8a58b3f707
[ "Apache-2.0" ]
null
null
null
OJ/PT/PT16.cpp
doan201203/truong_doan
68350b7a24ea266320cd41e1a4878e8a58b3f707
[ "Apache-2.0" ]
null
null
null
#include<stdio.h> int main(){ int N[100000], n, count = 0, kt; scanf("%d", &n); for(int i = 1 ; i <= n ; i++ ){ scanf("%d", &N[i]); } for(int i = 1 ; i <= n ; i++){ kt = N[i] % 19; if(kt == 0 || kt == 3 || kt == 6 || kt == 9 || kt == 11 || kt == 14 || kt == 17){ count++; } } printf("%d", count); }
24.666667
89
0.337838
doan201203
0158d2856b65209b7976459ad302259436420369
2,278
hpp
C++
include/game.hpp
vvbv/AlphaZero-Univalle
eb4ba2253ea266e3c5cad2cee24401ff95073c23
[ "MIT" ]
null
null
null
include/game.hpp
vvbv/AlphaZero-Univalle
eb4ba2253ea266e3c5cad2cee24401ff95073c23
[ "MIT" ]
null
null
null
include/game.hpp
vvbv/AlphaZero-Univalle
eb4ba2253ea266e3c5cad2cee24401ff95073c23
[ "MIT" ]
1
2018-06-20T19:15:14.000Z
2018-06-20T19:15:14.000Z
#ifndef GAME_HPP_ #define GAME_HPP_ #include "board.hpp" #include "state_game.hpp" #include <climits> #include <tuple> class Game{ private: int max_depth; struct minmax_game_elements { int pos_max_row; int pos_max_column; int pos_min_row; int pos_min_column; int min_items_quantity; int max_items_quantity; int depth; Board board; }; struct index_in_non_dynamic_expansions{ int index; }; Board board; int items_to_collect; int items_collected_by_human; int items_collected_by_pc; enum Action { up_right, up_left, left_up, left_down, down_left, down_right, right_down, right_up }; bool compare_minmax_game_elements( minmax_game_elements *a, minmax_game_elements *b ); State_game max_move( State_game state, std::vector < State_game > previous_moves_x ); State_game min_move( State_game state, std::vector < State_game > previous_moves_x ); State_game get_pos_up_right( State_game state, int current_pos[2], bool is_max ); State_game get_pos_up_left( State_game state, int current_pos[2], bool is_max ); State_game get_pos_left_up( State_game state, int current_pos[2], bool is_max ); State_game get_pos_left_down( State_game state, int current_pos[2], bool is_max ); State_game get_pos_down_left( State_game state, int current_pos[2], bool is_max ); State_game get_pos_down_right( State_game state, int current_pos[2], bool is_max ); State_game get_pos_right_down( State_game state, int current_pos[2], bool is_max ); State_game get_pos_right_up( State_game state, int current_pos[2], bool is_max ); bool game_ended( State_game state ); bool states_equals( State_game a, State_game b, bool is_max ); void print_game( State_game game ); public: Game(); ~Game(); void set_board( Board board ); void set_items_to_collect( int items_quantity ); Board get_board(); void start_new_game( Board board, int max_depth ); void start_new_game(); }; #endif
36.741935
108
0.64662
vvbv
015af092012a1520d753ae693e0c98ff3a70396c
1,991
cpp
C++
clang-tools-extra/clangd/unittests/support/ThreadingTests.cpp
ingve/llvm-project
13a467c8d169fc8caf142240382e9fce82a20e5e
[ "Apache-2.0" ]
1
2020-09-10T01:00:18.000Z
2020-09-10T01:00:18.000Z
clang-tools-extra/clangd/unittests/support/ThreadingTests.cpp
coolstar/llvm-project
e21ccdd5b5667de50de65ee8903a89a21020e89a
[ "Apache-2.0" ]
null
null
null
clang-tools-extra/clangd/unittests/support/ThreadingTests.cpp
coolstar/llvm-project
e21ccdd5b5667de50de65ee8903a89a21020e89a
[ "Apache-2.0" ]
null
null
null
//===-- ThreadingTests.cpp --------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "support/Threading.h" #include "gtest/gtest.h" #include <mutex> namespace clang { namespace clangd { class ThreadingTest : public ::testing::Test {}; TEST_F(ThreadingTest, TaskRunner) { const int TasksCnt = 100; // This should be const, but MSVC does not allow to use const vars in lambdas // without capture. On the other hand, clang gives a warning that capture of // const var is not required. // Making it non-const makes both compilers happy. int IncrementsPerTask = 1000; std::mutex Mutex; int Counter(0); /* GUARDED_BY(Mutex) */ { AsyncTaskRunner Tasks; auto scheduleIncrements = [&]() { for (int TaskI = 0; TaskI < TasksCnt; ++TaskI) { Tasks.runAsync("task", [&Counter, &Mutex, IncrementsPerTask]() { for (int Increment = 0; Increment < IncrementsPerTask; ++Increment) { std::lock_guard<std::mutex> Lock(Mutex); ++Counter; } }); } }; { // Make sure runAsync is not running tasks synchronously on the same // thread by locking the Mutex used for increments. std::lock_guard<std::mutex> Lock(Mutex); scheduleIncrements(); } Tasks.wait(); { std::lock_guard<std::mutex> Lock(Mutex); ASSERT_EQ(Counter, TasksCnt * IncrementsPerTask); } { std::lock_guard<std::mutex> Lock(Mutex); Counter = 0; scheduleIncrements(); } } // Check that destructor has waited for tasks to finish. std::lock_guard<std::mutex> Lock(Mutex); ASSERT_EQ(Counter, TasksCnt * IncrementsPerTask); } } // namespace clangd } // namespace clang
30.630769
80
0.60673
ingve
015b325f0a46dfd8a5c86b43e9fedf1cea828ee7
2,420
cpp
C++
src/jaegertracing/utils/RateLimiterTest.cpp
dvzubarev/jaeger-client-cpp
278947e0a87fd310421b6d3170ac005bc51bca82
[ "Apache-2.0" ]
193
2021-03-27T00:46:13.000Z
2022-03-29T07:25:00.000Z
src/jaegertracing/utils/RateLimiterTest.cpp
dvzubarev/jaeger-client-cpp
278947e0a87fd310421b6d3170ac005bc51bca82
[ "Apache-2.0" ]
220
2018-04-05T15:25:20.000Z
2022-01-21T02:38:57.000Z
src/jaegertracing/utils/RateLimiterTest.cpp
dvzubarev/jaeger-client-cpp
278947e0a87fd310421b6d3170ac005bc51bca82
[ "Apache-2.0" ]
122
2018-04-08T01:07:20.000Z
2022-03-03T21:14:02.000Z
/* * Copyright (c) 2017 Uber Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "jaegertracing/utils/RateLimiter.h" #include <chrono> #include <gtest/gtest.h> namespace jaegertracing { namespace utils { namespace { std::chrono::steady_clock::time_point currentTime; class MockClock { public: using rep = std::chrono::steady_clock::rep; using period = std::chrono::steady_clock::period; using duration = std::chrono::steady_clock::duration; using time_point = std::chrono::steady_clock::time_point; static const bool is_steady() { return false; } static time_point now() { return currentTime; } }; } // anonymous namespace TEST(RateLimiter, testRateLimiter) { const auto timestamp = std::chrono::steady_clock::now(); currentTime = timestamp; RateLimiter<MockClock> limiter(2, 2); ASSERT_TRUE(limiter.checkCredit(1)); ASSERT_TRUE(limiter.checkCredit(1)); ASSERT_FALSE(limiter.checkCredit(1)); currentTime = timestamp + std::chrono::milliseconds(250); ASSERT_FALSE(limiter.checkCredit(1)); currentTime = timestamp + std::chrono::milliseconds(750); ASSERT_TRUE(limiter.checkCredit(1)); ASSERT_FALSE(limiter.checkCredit(1)); currentTime = timestamp + std::chrono::seconds(5); ASSERT_TRUE(limiter.checkCredit(1)); ASSERT_TRUE(limiter.checkCredit(1)); ASSERT_FALSE(limiter.checkCredit(1)); ASSERT_FALSE(limiter.checkCredit(1)); ASSERT_FALSE(limiter.checkCredit(1)); } TEST(RateLimiter, testMaxBalance) { const auto timestamp = std::chrono::steady_clock::now(); currentTime = timestamp; RateLimiter<MockClock> limiter(0.1, 1.0); ASSERT_TRUE(limiter.checkCredit(1.0)); currentTime = timestamp + std::chrono::seconds(20); ASSERT_TRUE(limiter.checkCredit(1.0)); ASSERT_FALSE(limiter.checkCredit(1.0)); } } // namespace utils } // namespace jaegertracing
29.876543
75
0.720248
dvzubarev
015d16aa95d2f873537d151bfddce2ef8e744bf3
11,875
cpp
C++
medialibrary/src/main/cpp/Common/decoder/DecodeVideoThread.cpp
WakeHao/CainCamera
34549c18150201d68967f02246991b8bf2d3bfb7
[ "Apache-2.0" ]
2,564
2017-11-14T07:22:16.000Z
2022-03-30T13:39:41.000Z
medialibrary/src/main/cpp/Common/decoder/DecodeVideoThread.cpp
WakeHao/CainCamera
34549c18150201d68967f02246991b8bf2d3bfb7
[ "Apache-2.0" ]
166
2017-12-15T02:26:24.000Z
2022-03-05T10:50:03.000Z
medialibrary/src/main/cpp/Common/decoder/DecodeVideoThread.cpp
WakeHao/CainCamera
34549c18150201d68967f02246991b8bf2d3bfb7
[ "Apache-2.0" ]
693
2017-09-12T12:20:23.000Z
2022-03-30T13:39:43.000Z
// // Created by CainHuang on 2020-02-24. // #include "DecodeVideoThread.h" DecodeVideoThread::DecodeVideoThread() { LOGD("DecodeVideoThread::constructor()"); av_register_all(); mFrameQueue = nullptr; mVideoDemuxer = std::make_shared<AVMediaDemuxer>(); mVideoDecoder = std::make_shared<AVVideoDecoder>(mVideoDemuxer); mVideoDecoder->setDecoder("h264_mediacodec"); // 初始化数据包 av_init_packet(&mPacket); mPacket.data = nullptr; mPacket.size = 0; mMaxFrame = MAX_FRAME / 3; mThread = nullptr; mAbortRequest = true; mPauseRequest = true; mDecodeOnPause = false; mSeekRequest = false; mSeekTime = -1; mStartPosition = -1; mEndPosition = -1; } DecodeVideoThread::~DecodeVideoThread() { release(); LOGD("DecodeVideoThread::destructor()"); } void DecodeVideoThread::release() { stop(); LOGD("DecodeVideoThread::release()"); if (mVideoDecoder != nullptr) { mVideoDecoder->closeDecoder(); mVideoDecoder.reset(); mVideoDecoder = nullptr; } if (mVideoDemuxer != nullptr) { mVideoDemuxer->closeDemuxer(); mVideoDemuxer.reset(); mVideoDemuxer = nullptr; } av_packet_unref(&mPacket); mAbortRequest = true; mFrameQueue = nullptr; } /** * 设置解码监听器 * @param listener */ void DecodeVideoThread::setOnDecodeListener(const std::shared_ptr<OnDecodeListener> &listener) { LOGD("DecodeVideoThread::setOnDecodeListener()"); mDecodeListener = listener; mCondition.signal(); } /** * 设置解码后的存放队列 * @param frameQueue */ void DecodeVideoThread::setDecodeFrameQueue(SafetyQueue<Picture *> *frameQueue) { mFrameQueue = frameQueue; } void DecodeVideoThread::setDataSource(const char *url) { LOGD("DecodeVideoThread::setDataSource(): %s", url); mVideoDemuxer->setInputPath(url); } /** * 指定解封装格式名称,比如pcm、aac、h264、mp4之类的 * @param format */ void DecodeVideoThread::setInputFormat(const char *format) { LOGD("DecodeVideoThread::setInputFormat(): %s", format); mVideoDemuxer->setInputFormat(format); } /** * 指定解码器名称 * @param decoder */ void DecodeVideoThread::setDecodeName(const char *decoder) { LOGD("DecodeVideoThread::setDecodeName(): %s", decoder); mVideoDecoder->setDecoder(decoder); } /** * 添加解封装参数 */ void DecodeVideoThread::addFormatOptions(std::string key, std::string value) { LOGD("DecodeVideoThread::addFormatOptions(): {%s, %s}", key.c_str(), value.c_str()); mFormatOptions[key] = value; } /** * 添加解码参数 */ void DecodeVideoThread::addDecodeOptions(std::string key, std::string value) { LOGD("DecodeVideoThread::addDecodeOptions(): {%s, %s}", key.c_str(), value.c_str()); mDecodeOptions[key] = value; } /** * 设置解码 * @param decodeOnPause */ void DecodeVideoThread::setDecodeOnPause(bool decodeOnPause) { LOGD("DecodeVideoThread::setDecodeOnPause(): %d", decodeOnPause); mDecodeOnPause = decodeOnPause; mCondition.signal(); } /** * 跳转到某个时间 * @param timeMs */ void DecodeVideoThread::seekTo(float timeMs) { LOGD("DecodeVideoThread::seekTo(): %f ms", timeMs); mSeekRequest = true; mSeekTime = timeMs; mCondition.signal(); } /** * 设置是否需要循环解码 * @param looping */ void DecodeVideoThread::setLooping(bool looping) { LOGD("DecodeVideoThread::setLooping(): %d", looping); mLooping = looping; mCondition.signal(); } /** * 设置解码区间 * @param start * @param end */ void DecodeVideoThread::setRange(float start, float end) { LOGD("DecodeVideoThread::setRange(): {%f, %f}", start, end); mStartPosition = start; mEndPosition = end; mCondition.signal(); } /** * 准备解码 * @return */ int DecodeVideoThread::prepare() { int ret; LOGD("DecodeVideoThread::prepare()"); // 打开解封装器 ret = mVideoDemuxer->openDemuxer(mFormatOptions); if (ret < 0) { LOGE("Failed to open media demuxer"); mVideoDemuxer.reset(); mVideoDemuxer = nullptr; return ret; } // 打开视频解码器 if (mVideoDemuxer->hasVideoStream()) { ret = mVideoDecoder->openDecoder(mDecodeOptions); if (ret < 0) { LOGE("Failed to open audio decoder"); return ret; } } // 打印信息 mVideoDemuxer->printInfo(); return ret; } /** * 开始解码 */ void DecodeVideoThread::start() { LOGD("DecodeVideoThread::start()"); mAbortRequest = false; mPauseRequest = false; mCondition.signal(); if (mThread == nullptr) { mThread = new Thread(this); } if (!mThread->isActive()) { mThread->start(); } } /** * 暂停解码 */ void DecodeVideoThread::pause() { LOGD("DecodeVideoThread::pause()"); mPauseRequest = true; mCondition.signal(); } /** * 停止解码 */ void DecodeVideoThread::stop() { LOGD("DecodeVideoThread::stop()"); mAbortRequest = true; mCondition.signal(); if (mThread != nullptr && mThread->isActive()) { mThread->join(); } if (mThread) { delete mThread; mThread = nullptr; } } /** * 清空解码缓冲区和视频帧队列 */ void DecodeVideoThread::flush() { LOGD("DecodeVideoThread::flush()"); if (mVideoDecoder != nullptr) { mVideoDecoder->flushBuffer(); } } /** * 获取宽度 */ int DecodeVideoThread::getWidth() { return mVideoDecoder->getWidth(); } /** * 获取高度 */ int DecodeVideoThread::getHeight() { return mVideoDecoder->getHeight(); } /** * 获取平均帧率 */ int DecodeVideoThread::getFrameRate() { return mVideoDecoder->getFrameRate(); } /** * 获取时长(ms) */ int64_t DecodeVideoThread::getDuration() { return mVideoDemuxer->getDuration(); } /** * 获取旋转角度 */ double DecodeVideoThread::getRotation() { AutoMutex lock(mMutex); return mVideoDecoder->getRotation(); } void DecodeVideoThread::run() { readPacket(); } /** * 读取数据包并解码 * @return */ int DecodeVideoThread::readPacket() { int ret = 0; mDecodeEnd = false; LOGD("DecodeVideoThread::readePacket"); // 解码开始回调 if (mDecodeListener.lock() != nullptr) { mDecodeListener.lock()->onDecodeStart(AVMEDIA_TYPE_VIDEO); } if (mStartPosition >= 0) { mVideoDemuxer->seekVideo(mStartPosition); } while (true) { mMutex.lock(); // 退出解码 if (mAbortRequest) { flush(); mMutex.unlock(); break; } // 定位处理 if (mSeekRequest) { ret = seekFrame(); mSeekTime = -1; mSeekRequest = false; mCondition.signal(); mMutex.unlock(); if (ret >= 0) { // 计算出准确的seek time float seekTime = (float)(ret * 1000.0f * av_q2d(mVideoDecoder->getStream()->time_base)); // seek结束回调 if (mDecodeListener.lock() != nullptr) { mDecodeListener.lock()->onSeekComplete(AVMEDIA_TYPE_VIDEO, seekTime); } } continue; } // 处于暂停状态下,暂停解码 if (mPauseRequest && !mDecodeOnPause) { mCondition.wait(mMutex); mMutex.unlock(); continue; } // 锁定10毫秒之后继续下一轮做法 if (isDecodeWaiting()) { mCondition.waitRelativeMs(mMutex, 10); mMutex.unlock(); continue; } // 如果需要循环播放等待音频帧队列消耗完,然后定位到起始位置 if (mDecodeEnd) { // 非循环解码,直接退出解码线程 if (!mLooping) { break; } // 等待音频帧消耗完 if (!mFrameQueue->empty()) { mCondition.waitRelativeMs(mMutex, 50); mMutex.unlock(); continue; } mDecodeEnd = false; // 定位到开始位置 float position = mStartPosition; if (position < 0) { position = 0; } seekTo(position); mMutex.unlock(); continue; } mMutex.unlock(); ret = readAndDecode(); if (ret < 0) { break; } } // 解码结束回调 if (mDecodeListener.lock() != nullptr) { mDecodeListener.lock()->onDecodeFinish(AVMEDIA_TYPE_VIDEO); } LOGD("DecodeVideoThread exit!"); return ret; } /** * 读取并解码 * @return */ int DecodeVideoThread::readAndDecode() { // 读取数据包 int ret = mVideoDemuxer->readFrame(&mPacket); // 解码到结尾位置,如果需要循环播放,则记录解码完成标记,等待队列消耗完 if (ret == AVERROR_EOF && mLooping) { mDecodeEnd = true; LOGD("need to decode looping"); return 0; } else if (ret < 0) { // 解码出错直接退出解码线程 LOGE("Failed to call av_read_frame: %s", av_err2str(ret)); return ret; } if (mPacket.stream_index < 0 || mPacket.stream_index != mVideoDecoder->getStreamIndex() || (mPacket.flags & AV_PKT_FLAG_CORRUPT)) { av_packet_unref(&mPacket); return 0; } decodePacket(&mPacket); av_packet_unref(&mPacket); return 0; } /** * 解码数据包 * @param packet * @return 0为解码成功,小于为解码失败 */ int DecodeVideoThread::decodePacket(AVPacket *packet) { int ret = 0; if (!packet || packet->stream_index < 0) { return -1; } if (mAbortRequest) { return -1; } // 非视频数据包则直接释放内存并返回 if (packet->stream_index != mVideoDecoder->getStreamIndex()) { av_packet_unref(packet); return 0; } // 将数据包送去解码 auto pCodecContext = mVideoDecoder->getContext(); ret = avcodec_send_packet(pCodecContext, packet); if (ret < 0) { LOGE("Failed to call avcodec_send_packet: %s", av_err2str(ret)); return ret; } while (ret == 0 && !mAbortRequest) { // 取出解码后的AVFrame AVFrame *frame = av_frame_alloc(); ret = avcodec_receive_frame(pCodecContext, frame); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { freeFrame(frame); break; } else if (ret < 0) { LOGE("Failed to call avcodec_receive_frame: %s", av_err2str(ret)); freeFrame(frame); break; } // 计算出实际的pts值 frame->pts = av_frame_get_best_effort_timestamp(frame); // 将解码后数据帧转码后放入队列 if (mFrameQueue != nullptr) { Picture *picture = (Picture *) malloc(sizeof(Picture)); memset(picture, 0, sizeof(Picture)); picture->frame = frame; picture->pts = calculatePts(frame->pts, mVideoDecoder->getStream()->time_base); // 将数据放入帧队列中 mFrameQueue->push(picture); // 比较播放结束位置的pts if (mEndPosition > 0 && picture->pts >= mEndPosition) { mDecodeEnd = true; } } else { freeFrame(frame); } } return ret; } /** * 是否需要解码等待 * @return */ bool DecodeVideoThread::isDecodeWaiting() { return (mFrameQueue && mFrameQueue->size() >= mMaxFrame); } /** * 计算当前时间戳 * @param pts * @param time_base * @return */ int64_t DecodeVideoThread::calculatePts(int64_t pts, AVRational time_base) { return (int64_t)(av_q2d(time_base) * 1000 * pts); } /** * 释放帧对象 * @param frame */ void DecodeVideoThread::freeFrame(AVFrame *frame) { if (frame) { av_frame_unref(frame); av_frame_free(&frame); } } /** * 跳转到某个帧 */ int DecodeVideoThread::seekFrame() { int64_t ret; int stream_index; if (!mVideoDecoder || mSeekTime == -1) { return -1; } // 定位到实际位置中 stream_index = mVideoDecoder->getStreamIndex(); int64_t time = (int64_t)(mSeekTime / (1000.0f * av_q2d(mVideoDecoder->getStream()->time_base))); ret = mVideoDemuxer->seekVideo(time, stream_index, AVSEEK_FLAG_BACKWARD); if (ret < 0) { // seek出错回调 if (mDecodeListener.lock() != nullptr) { mDecodeListener.lock()->onSeekError(AVMEDIA_TYPE_VIDEO, ret); } return ret; } // 清空队列的数据 flush(); return ret; }
22.836538
104
0.589221
WakeHao
015fb70636b9c7727e0ce79f8acaa0cb0e1496e4
5,398
cpp
C++
engine/src/Core/AppStatus.cpp
MajesticShekel/Strontium
e672e4f7ee0338ef4e29ac61dad3f10905e8d105
[ "MIT" ]
null
null
null
engine/src/Core/AppStatus.cpp
MajesticShekel/Strontium
e672e4f7ee0338ef4e29ac61dad3f10905e8d105
[ "MIT" ]
null
null
null
engine/src/Core/AppStatus.cpp
MajesticShekel/Strontium
e672e4f7ee0338ef4e29ac61dad3f10905e8d105
[ "MIT" ]
null
null
null
#include "Core/AppStatus.h" appStatus defaultEditorStatus = { { { "KEY_UNKNOWN", -1 }, { "KEY_SPACE", 32 }, { "KEY_APOSTROPHE", 39 }, { "KEY_COMMA", 44 }, { "KEY_MINUS", 45 }, { "KEY_PERIOD", 46 }, { "KEY_SLASH", 47 }, { "KEY_0", 48 }, { "KEY_1", 49 }, { "KEY_2", 50 }, { "KEY_3", 51 }, { "KEY_4", 52 }, { "KEY_5", 53 }, { "KEY_6", 54 }, { "KEY_7", 55 }, { "KEY_8", 56 }, { "KEY_9", 57 }, { "KEY_SEMICOLON", 59 }, { "KEY_EQUAL", 61 }, { "KEY_A", 65 }, { "KEY_B", 66 }, { "KEY_C", 67 }, { "KEY_D", 68 }, { "KEY_E", 69 }, { "KEY_F", 70 }, { "KEY_G", 71 }, { "KEY_H", 72 }, { "KEY_I", 73 }, { "KEY_J", 74 }, { "KEY_K", 75 }, { "KEY_L", 76 }, { "KEY_M", 77 }, { "KEY_N", 78 }, { "KEY_O", 79 }, { "KEY_P", 80 }, { "KEY_Q", 81 }, { "KEY_R", 82 }, { "KEY_S", 83 }, { "KEY_T", 84 }, { "KEY_U", 85 }, { "KEY_V", 86 }, { "KEY_W", 87 }, { "KEY_X", 88 }, { "KEY_Y", 89 }, { "KEY_Z", 90 }, { "KEY_LEFT_BRACKET", 91 }, { "KEY_BACKSLASH", 92 }, { "KEY_RIGHT_BRACKET", 93 }, { "KEY_GRAVE_ACCENT", 96 }, { "KEY_WORLD_1", 161 }, { "KEY_WORLD_2", 162 }, { "KEY_ESCAPE", 256 }, { "KEY_ENTER", 257 }, { "KEY_TAB", 258 }, { "KEY_BAKCSPACE", 259 }, { "KEY_INSERT", 260 }, { "KEY_DELETE", 261 }, { "KEY_RIGHT", 262 }, { "KEY_LEFT", 263 }, { "KEY_DOWN", 264 }, { "KEY_UP", 265 }, { "KEY_PAGE_DOWN", 266 }, { "KEY_PAGE_UP", 267 }, { "KEY_HOME", 268 }, { "KEY_END", 269 }, { "KEY_CAPS_LOCK", 280 }, { "KEY_SCROLL_LOCK", 281 }, { "KEY_NUM_LOCK", 282 }, { "KEY_PRINT_SCREEN", 283 }, { "KEY_PAUSE", 284 }, { "KEY_F1", 290 }, { "KEY_F2", 291 }, { "KEY_F3", 292 }, { "KEY_F4", 293 }, { "KEY_F5", 294 }, { "KEY_F6", 295 }, { "KEY_F7", 296 }, { "KEY_F8", 297 }, { "KEY_F9", 298 }, { "KEY_F10", 299 }, { "KEY_F11", 300 }, { "KEY_F12", 301 }, { "KEY_F13", 302 }, { "KEY_F14", 303 }, { "KEY_F15", 304 }, { "KEY_F16", 305 }, { "KEY_F17", 306 }, { "KEY_F18", 307 }, { "KEY_F19", 308 }, { "KEY_F20", 309 }, { "KEY_F21", 310 }, { "KEY_F22", 311 }, { "KEY_F23", 312 }, { "KEY_F24", 313 }, { "KEY_F25", 314 }, { "KEY_KP_0", 320 }, { "KEY_KP_1", 321 }, { "KEY_KP_2", 322 }, { "KEY_KP_3", 323 }, { "KEY_KP_4", 324 }, { "KEY_KP_5", 325 }, { "KEY_KP_6", 326 }, { "KEY_KP_7", 327 }, { "KEY_KP_8", 328 }, { "KEY_KP_9", 329 }, { "KEY_KP_DECIMAL", 330 }, { "KEY_KP_DIVIDE", 331 }, { "KEY_KP_MULTIPLY", 332 }, { "KEY_KP_SUBTRACT", 333 }, { "KEY_KP_ADD", 334 }, { "KEY_KP_ENTER", 335 }, { "KEY_KP_EQUAL", 336 }, { "KEY_LEFT_SHIFT", 340 }, { "KEY_LEFT_CONTROL", 341 }, { "KEY_LEFT_ALT", 342 }, { "KEY_LEFT_SUPER", 343 }, { "KEY_RIGHT_SHIFT", 344 }, { "KEY_RIGHT_CONTROL", 345 }, { "KEY_RIGHT_ALT", 346 }, { "KEY_RIGHT_SUPER", 347 }, { "KEY_MENU", 348 }, { "KEY_LAST", 348 }, /*! @defgroup mods Modifier key flags * @brief Modifier key flags. * * See [key input](@ref input_key) for how these are used. * * @ingroup input * @{ */ /*! @brief If this bit is set one or more Shift keys were held down. * * If this bit is set one or more Shift keys were held down. */ { "MOD_SHIFT", 0x0001 }, /*! @brief If this bit is set one or more Control keys were held down. * * If this bit is set one or more Control keys were held down. */ { "MOD_CONTROL", 0x0002 }, /*! @brief If this bit is set one or more Alt keys were held down. * * If this bit is set one or more Alt keys were held down. */ { "MOD_ALT", 0x0004 }, /*! @brief If this bit is set one or more Super keys were held down. * * If this bit is set one or more Super keys were held down. */ { "MOD_SUPER", 0x0008 }, /*! @brief If this bit is set the Caps Lock key is enabled. * * If this bit is set the Caps Lock key is enabled and the @ref * SR_LOCK_KEY_MODS input mode is set. */ { "MOD_CAPS_LOCK", 0x0010 }, /*! @brief If this bit is set the Num Lock key is enabled. * * If this bit is set the Num Lock key is enabled and the @ref * SR_LOCK_KEY_MODS input mode is set. */ { "MOD_NUM_LOCK", 0x0020 }, /*! @} */ /*! @defgroup buttons Mouse buttons * @brief Mouse button IDs. * * See [mouse button input](@ref input_mouse_button) for how these are used. * * @ingroup input * @{ */ { "MOUSE_BUTTON_1", 0 }, { "MOUSE_BUTTON_2", 1 }, { "MOUSE_BUTTON_3", 2 }, { "MOUSE_BUTTON_4", 3 }, { "MOUSE_BUTTON_5", 4 }, { "MOUSE_BUTTON_6", 5 }, { "MOUSE_BUTTON_7", 6 }, { "MOUSE_BUTTON_8", 7 }, { "MOUSE_BUTTON_LAST", 7 }, { "MOUSE_BUTTON_LEFT", 0 }, { "MOUSE_BUTTON_RIGHT", 1 }, { "MOUSE_BUTTON_MIDDLE", 2 } }, //windows { { "AssetBrowserWindow", true }, { "CameraWindow", true }, { "FileBrowserWindow", true }, { "GuiWindow", true }, { "ModelWindow", false }, { "RendererWindow", true }, { "ShaderWindow", true }, { "ViewportWindow", true } }, //editor camera settings { {0, 1, 4}, {0, 0, -1}, 90, 0.1, 200, 2.5, 0.1 } }; appStatus editorStatus = { }; /*std::map<std::string, std::pair<std::any, std::string>> camData::toMap() { return { { "Position", position }, { "Front", front }, { "FOV", fov }, { "Near", near }, { "Far", far }, { "Speed", speed }, { "Sensitivity", sens } }; }*/
22.491667
79
0.524639
MajesticShekel
0162b501d7b3cd246245f560572d30c8091d75cc
1,101
cpp
C++
LeetCode/Problems/Algorithms/#658_FindKClosestElements_sol1_binary_search_and_two_pointers_approach_O(logN+K)_time_O(1)_extra_space_32ms_30.8MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#658_FindKClosestElements_sol1_binary_search_and_two_pointers_approach_O(logN+K)_time_O(1)_extra_space_32ms_30.8MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#658_FindKClosestElements_sol1_binary_search_and_two_pointers_approach_O(logN+K)_time_O(1)_extra_space_32ms_30.8MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: vector<int> findClosestElements(vector<int>& arr, int k, int x) { const int N = arr.size(); // Step 1: binary search the (lower_bound) position of x in arr int xPos = lower_bound(arr.begin(), arr.end(), x) - arr.begin(); xPos = min(N - 1, xPos); if(xPos - 1 >= 0 && xPos <= N - 1 && abs(arr[xPos - 1] - x) <= abs(arr[xPos] - x)){ xPos -= 1; } // Step 2 (two pointers approach): // expand [startPos, endPos] range including closest integers to x int startPos = xPos; int endPos = xPos; while(endPos - startPos + 1 < k){ if(startPos == 0){ endPos += 1; }else if(endPos == N - 1){ startPos -= 1; }else if(abs(arr[startPos - 1] - x) <= abs(arr[endPos + 1] - x)){ startPos -= 1; }else{ endPos += 1; } } return vector<int>(arr.begin() + startPos, arr.begin() + endPos + 1); } };
35.516129
92
0.448683
Tudor67
01648bffc83e30c7daeacfa0ab8001392574c991
549
cpp
C++
AOC2017/day2/day_2_puzzle_2.cpp
schneiderl/problems-solved
881895fc262ccd49c278ce38a06c1d2686fb72b6
[ "Unlicense" ]
null
null
null
AOC2017/day2/day_2_puzzle_2.cpp
schneiderl/problems-solved
881895fc262ccd49c278ce38a06c1d2686fb72b6
[ "Unlicense" ]
2
2017-09-29T14:09:48.000Z
2018-01-25T01:07:31.000Z
AOC2017/day2/day_2_puzzle_2.cpp
schneiderl/problems-solved
881895fc262ccd49c278ce38a06c1d2686fb72b6
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> #include <iostream> #include <string> using namespace std; int main(int argc, char const *argv[]) { int sum = 0; for (int i = 0; i < 16; ++i){ //because there are 16 rows int lowest = 5000000000; int largest = 0; int curr = 0; int line[16]; for (int j = 0; j < 16; ++j){ cin>>line[j]; } cout<<line<<endl; for (int j = 0; j < 16; ++j){ for (int k = 0; k < 16; ++k){ if(k!=j){ if(line[j]%line[k]==0){ sum = sum + line[j]/line[k]; } } } } } cout<<sum<<endl; return 0; }
17.709677
58
0.513661
schneiderl
0166081927ed5e32c9e1002953709b8a5d537a90
437
cpp
C++
PAT/B1008.cpp
iphelf/Programming-Practice
2a95bb7153957b035427046b250bf7ffc6b00906
[ "WTFPL" ]
null
null
null
PAT/B1008.cpp
iphelf/Programming-Practice
2a95bb7153957b035427046b250bf7ffc6b00906
[ "WTFPL" ]
null
null
null
PAT/B1008.cpp
iphelf/Programming-Practice
2a95bb7153957b035427046b250bf7ffc6b00906
[ "WTFPL" ]
null
null
null
#include<stdio.h> #include<algorithm> using namespace std; const int MAXN=100; int a[MAXN]; int main(void) { // freopen("in.txt","r",stdin); int N; long long M; scanf("%d%lld",&N,&M); for(int i=0;i<N;i++) scanf("%d",&a[i]); M=M%N; reverse(a,a+N-M); reverse(a+N-M,a+N); reverse(a,a+N); for(int i=0;i<N;i++) printf("%d%c",a[i],i==N-1?'\n':' '); return 0; } /* 6 2 1 2 3 4 5 6 5 6 1 2 3 4 */
15.068966
61
0.510297
iphelf
0166fb1d2f6af68b9d32f6594b2a0ce4cdfa1be2
1,041
hpp
C++
EasyFramework3d/core/gui/ButtonEvent.hpp
sizilium/FlexChess
f12b94e800ddcb00535067eca3b560519c9122e0
[ "MIT" ]
null
null
null
EasyFramework3d/core/gui/ButtonEvent.hpp
sizilium/FlexChess
f12b94e800ddcb00535067eca3b560519c9122e0
[ "MIT" ]
null
null
null
EasyFramework3d/core/gui/ButtonEvent.hpp
sizilium/FlexChess
f12b94e800ddcb00535067eca3b560519c9122e0
[ "MIT" ]
null
null
null
/** * @file ButtonEvent.hpp * @author sizilium * @date 26.12.2007 * @brief This file is part of the Vision Synthesis Easy Framework.\n * This file has no copyright; you can change everything. * Visit www.vision-synthesis.de or www.easy-framework.de for further informations.\n * If there is a bug please send a mail to bug@vision-synthesis.de. No warranty is given! */ #ifndef BUTTON_EVENT_H #define BUTTON_EVENT_H // includes #include <vs/Build.hpp> #include <vs/base/interfaces/Event.hpp> #include <string> namespace vs { namespace core { namespace gui { /** @class ButtonEvent * */ class VS_EXPORT ButtonEvent : public base::interfaces::Event { public: ButtonEvent(const std::string &name, int x, int y) :base::interfaces::Event(base::interfaces::Event::GuiEvent), name(name), x(x), y(y) {} std::string getName() const { return name; } void getClickCoords(int &x, int &y) const { x = this->x; y = this->y; } private: std::string name; int x, y; }; } // gui } // core } // vs #endif // BUTTON_EVENT_H
18.263158
89
0.68684
sizilium
016803f139985567256a115aae95e6d70b3971f6
550
hpp
C++
include/Particles/TriangularPrism.hpp
mtortora/chiralDFT
d5ea5e940d6bc72d96fd9728d042de1e09d3ef85
[ "MIT" ]
2
2018-01-03T09:33:09.000Z
2019-06-14T13:29:37.000Z
include/Particles/TriangularPrism.hpp
mtortora/chiralDFT
d5ea5e940d6bc72d96fd9728d042de1e09d3ef85
[ "MIT" ]
null
null
null
include/Particles/TriangularPrism.hpp
mtortora/chiralDFT
d5ea5e940d6bc72d96fd9728d042de1e09d3ef85
[ "MIT" ]
null
null
null
#ifndef TRIANGULAR_PRISM_HPP_ #define TRIANGULAR_PRISM_HPP_ #include "rapid2/RAPID.H" #include "BaseParticle.hpp" template<typename number> class TriangularPrism: public BaseParticle<number> { public: TriangularPrism(); ~TriangularPrism() {delete Mesh;} RAPID_model* Mesh; void Build(int) override; void Tesselate(const Matrix3X<number>&); void Parse(std::mt19937_64&, ArrayX<uint>&) override {} private: number L_X_; number L_Y_; number L_Z_; number TWIST_; number GAMMA_; void SaveMesh(const Matrix3X<number>&); }; #endif
16.666667
56
0.747273
mtortora
01681018a312e33a0fd253af2e0f9a3b206d1cf0
2,332
cpp
C++
lib/core/src/irods_threads.cpp
JustinKyleJames/irods
59e9db75200e95796ec51ec20eb3b185d9e4b5f5
[ "BSD-3-Clause" ]
333
2015-01-15T15:42:29.000Z
2022-03-19T19:16:15.000Z
lib/core/src/irods_threads.cpp
JustinKyleJames/irods
59e9db75200e95796ec51ec20eb3b185d9e4b5f5
[ "BSD-3-Clause" ]
3,551
2015-01-02T19:55:40.000Z
2022-03-31T21:24:56.000Z
lib/core/src/irods_threads.cpp
JustinKyleJames/irods
59e9db75200e95796ec51ec20eb3b185d9e4b5f5
[ "BSD-3-Clause" ]
148
2015-01-31T16:13:46.000Z
2022-03-23T20:23:43.000Z
#include "irods_threads.hpp" // =-=-=-=-=-=-=- // void thread_wait( thread_context* _ctx ) { if ( !_ct ) { return; } #ifdef __cplusplus #else // __cplusplus #endif // __cplusplus } // =-=-=-=-=-=-=- // void thread_notify( thread_context* _ctx ) { if ( !_ct ) { return; } #ifdef __cplusplus #else // __cplusplus #endif // __cplusplus } // =-=-=-=-=-=-=- // void thread_lock( thread_context* _ctx ) { if ( !_ct ) { return; } #ifdef __cplusplus _ctx->lock.; ock(); #else // __cplusplus #endif // __cplusplus } // =-=-=-=-=-=-=- // void thread_unlock( thread_context* _ctx ) { if ( !_ct ) { return; } #ifdef __cplusplus _ctx->lock.unlock(); #else // __cplusplus #endif // __cplusplus } // =-=-=-=-=-=-=- // int thread_alloc( thread_context* _ctx, thread_proc_t _proc, void* _data ) { int result = 0; _ctx->exit_flg = false; #ifdef __cplusplus _ctx->lock = new boost::mutex; _ctx->cond = new boost::condition_variable; _ctx->reconnThr = new boost::thread( _proc, _data ); #else // __cplusplus pthread_mutex_init( &_ctx->lock, NULL ); pthread_cond_init( &_ctx->cond, NULL ); result = pthread_create( &_ctx->reconnThr, pthread_attr_default, _proc, //(void *(*)(void *)) cliReconnManager, _data ); //(void *) conn); #endif // __cplusplus return result; } // =-=-=-=-=-=-=- // void thread_free( thread_context* _ctx ) { if ( !_ctx ) { return; } #ifdef __cplusplus delete conn->reconnThr; delete conn->lock; delete conn->cond; #else // __cplusplus pthread_cancel( conn->reconnThr ); pthread_detach( conn->reconnThr ); pthread_mutex_destroy( &conn->lock ); pthread_cond_destroy( &conn->cond ); #endif // __cplusplus } // =-=-=-=-=-=-=- // void thread_interrupt( thread_context* _ctx ) { if ( !_ct ) { return; } _ctx->exit_flg = true; // signal an exit #ifdef __cplusplus boost::system_time until = boost::get_system_time() + boost::posix_time::seconds( 2 ); _ctx->reconnThr->timed_join( until ); // force an interruption point #else // __cplusplus _ctx->reconnThr->interrupt(); #endif // __cplusplus }
19.931624
90
0.566038
JustinKyleJames
6c69bc5b037960781c1885b8ba02cc6577ef3ff3
885
hpp
C++
stringify/container_traits.hpp
5cript/SimpleJSON
878a6341baed91c29630447f6bd480391f563045
[ "MIT" ]
4
2015-06-25T02:06:13.000Z
2018-07-11T13:20:24.000Z
stringify/container_traits.hpp
5cript/SimpleJSON
878a6341baed91c29630447f6bd480391f563045
[ "MIT" ]
14
2015-03-29T10:32:21.000Z
2018-01-25T16:45:08.000Z
stringify/container_traits.hpp
5cript/SimpleJSON
878a6341baed91c29630447f6bd480391f563045
[ "MIT" ]
2
2017-07-16T09:43:22.000Z
2020-08-30T09:33:40.000Z
#pragma once // and iterator traits :D #include <iterator> #include <type_traits> template <typename T, template <typename, class = std::allocator <T> > class ContainerT> struct has_random_access_iterator : std::is_same < typename std::iterator_traits<typename ContainerT<T>::iterator>::iterator_category , std::random_access_iterator_tag> {}; template <typename T, template <typename, class = std::allocator <T> > class ContainerT> struct has_bidirectional_iterator : std::is_same < typename std::iterator_traits<typename ContainerT<T>::iterator>::iterator_category , std::bidirectional_iterator_tag> {}; template <typename T, template <typename, class = std::allocator <T> > class ContainerT> struct has_forward_iterator : std::is_same < typename std::iterator_traits<typename ContainerT<T>::iterator>::iterator_category , std::forward_iterator_tag> {};
35.4
88
0.757062
5cript
6c6aaa6a485e39b792983c293ac84c7384ebb0bd
3,427
hpp
C++
include/jwt/error_codes.hpp
ValBaturin/cpp-jwt
8272256dd0105e2e66838dc081e30e638966ca12
[ "MIT" ]
324
2017-12-27T09:57:20.000Z
2022-03-30T15:43:27.000Z
include/jwt/error_codes.hpp
ValBaturin/cpp-jwt
8272256dd0105e2e66838dc081e30e638966ca12
[ "MIT" ]
68
2018-01-28T15:08:11.000Z
2021-10-16T15:59:06.000Z
include/jwt/error_codes.hpp
ValBaturin/cpp-jwt
8272256dd0105e2e66838dc081e30e638966ca12
[ "MIT" ]
100
2018-01-04T08:09:14.000Z
2021-12-02T13:37:37.000Z
/* Copyright (c) 2017 Arun Muralidharan 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 CPP_JWT_ERROR_CODES_HPP #define CPP_JWT_ERROR_CODES_HPP #include <system_error> namespace jwt { /** * All the algorithm errors */ enum class AlgorithmErrc { SigningErr = 1, VerificationErr, KeyNotFoundErr, InvalidKeyErr, NoneAlgorithmUsed, // Not an actual error! }; /** * Algorithm error conditions * TODO: Remove it or use it! */ enum class AlgorithmFailureSource { }; /** * Decode error conditions */ enum class DecodeErrc { // No algorithms provided in decode API EmptyAlgoList = 1, // The JWT signature has incorrect format SignatureFormatError, // The JSON library failed to parse JsonParseError, // Algorithm field in header is missing AlgHeaderMiss, // Type field in header is missing TypHeaderMiss, // Unexpected type field value TypMismatch, // Found duplicate claims DuplClaims, // Key/Secret not passed as decode argument KeyNotPresent, // Key/secret passed as argument for NONE algorithm. // Not a hard error. KeyNotRequiredForNoneAlg, }; /** * Errors handled during verification process. */ enum class VerificationErrc { //Algorithms provided does not match with header InvalidAlgorithm = 1, //Token is expired at the time of decoding TokenExpired, //The issuer specified does not match with payload InvalidIssuer, //The subject specified does not match with payload InvalidSubject, //The field IAT is not present or is of invalid type InvalidIAT, //Checks for the existence of JTI //if validate_jti is passed in decode InvalidJTI, //The audience specified does not match with payload InvalidAudience, //Decoded before nbf time ImmatureSignature, //Signature match error InvalidSignature, // Invalid value type used for known claims TypeConversionError, }; /** */ std::error_code make_error_code(AlgorithmErrc err); /** */ std::error_code make_error_code(DecodeErrc err); /** */ std::error_code make_error_code(VerificationErrc err); } // END namespace jwt /** * Make the custom enum classes as error code * adaptable. */ namespace std { template <> struct is_error_code_enum<jwt::AlgorithmErrc> : true_type {}; template <> struct is_error_code_enum<jwt::DecodeErrc>: true_type {}; template <> struct is_error_code_enum<jwt::VerificationErrc>: true_type {}; } #include "jwt/impl/error_codes.ipp" #endif
25.014599
78
0.753137
ValBaturin
6c6b1b2db504ed65d544f18498e337eb6b79563c
1,980
inl
C++
thrust/detail/copy.inl
UIKit0/thrust
7bcbe7e4400ec06463d4c9c8001e0fe57e47b719
[ "Apache-2.0" ]
1
2021-03-19T07:13:36.000Z
2021-03-19T07:13:36.000Z
thrust/detail/copy.inl
UIKit0/thrust
7bcbe7e4400ec06463d4c9c8001e0fe57e47b719
[ "Apache-2.0" ]
null
null
null
thrust/detail/copy.inl
UIKit0/thrust
7bcbe7e4400ec06463d4c9c8001e0fe57e47b719
[ "Apache-2.0" ]
2
2017-03-09T19:54:24.000Z
2021-06-03T22:49:59.000Z
/* * Copyright 2008-2012 NVIDIA Corporation * * 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 <thrust/detail/config.h> #include <thrust/detail/copy.h> #include <thrust/system/detail/generic/select_system.h> #include <thrust/system/detail/generic/copy.h> #include <thrust/detail/adl_helper.h> namespace thrust { template<typename InputIterator, typename OutputIterator> OutputIterator copy(InputIterator first, InputIterator last, OutputIterator result) { using thrust::system::detail::generic::select_system; using thrust::system::detail::generic::copy; typedef typename thrust::iterator_system<InputIterator>::type system1; typedef typename thrust::iterator_system<OutputIterator>::type system2; return copy(select_system(system1(),system2()), first, last, result); } // end copy() template<typename InputIterator, typename Size, typename OutputIterator> OutputIterator copy_n(InputIterator first, Size n, OutputIterator result) { using thrust::system::detail::generic::select_system; using thrust::system::detail::generic::copy_n; typedef typename thrust::iterator_system<InputIterator>::type system1; typedef typename thrust::iterator_system<OutputIterator>::type system2; return copy_n(select_system(system1(),system2()), first, n, result); } // end copy_n() } // end namespace thrust
31.428571
76
0.713636
UIKit0