hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
ec3bdcc5af887ba086db9ae3c637e9fe3731d529
855
cpp
C++
src/gamedata/formations.cpp
Kor-Hal/SisterRay
4e8482525a5d7f77dee186f438ddb16523a61e7e
[ "BSD-3-Clause" ]
null
null
null
src/gamedata/formations.cpp
Kor-Hal/SisterRay
4e8482525a5d7f77dee186f438ddb16523a61e7e
[ "BSD-3-Clause" ]
null
null
null
src/gamedata/formations.cpp
Kor-Hal/SisterRay
4e8482525a5d7f77dee186f438ddb16523a61e7e
[ "BSD-3-Clause" ]
null
null
null
#include "formations.h" #include "../impl.h" SISTERRAY_API FormationData srGetFormation(u16 modFormationID, const char* modName) { auto name = std::string(modName) + std::to_string(modFormationID); return gContext.formations.getElement(name); } SISTERRAY_API void srAddFormation(FormationData formationData, u16 modFormationID, const char* modName) { auto name = std::string(modName) + std::to_string(modFormationID); return gContext.formations.addElement(name, formationData); } // For internal use, we reference by index FormationData& getFormation(u16 modFormationID) { return gContext.formations.getResource(modFormationID); } FormationActorData& getFormationActorData(u16 modFormationID, u16 enemyActorIdx) { return gContext.formations.getResource(modFormationID).formationActorDataArray.formationDatas[enemyActorIdx]; }
37.173913
113
0.790643
Kor-Hal
ec3d72ac8ed58260b84faa5f2b758dfe7a64986d
8,429
cpp
C++
ToolKit/Controls/Deprecated/XTOutBarCtrlTheme.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
2
2018-03-30T06:40:08.000Z
2022-02-23T12:40:13.000Z
ToolKit/Controls/Deprecated/XTOutBarCtrlTheme.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
null
null
null
ToolKit/Controls/Deprecated/XTOutBarCtrlTheme.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
1
2020-08-11T05:48:02.000Z
2020-08-11T05:48:02.000Z
// XTOutBarCtrlTheme.cpp: implementation of the CXTOutBarCtrlTheme class. // // This file is a part of the XTREME CONTROLS MFC class library. // (c)1998-2011 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Common/XTPResourceManager.h" #include "Common/XTPColorManager.h" #include "Common/XTPDrawHelpers.h" #include "Common/XTPMaskEditT.h" #include "Common/XTPWinThemeWrapper.h" #include "Controls/Resource.h" #include "Controls/Defines.h" #include "Controls/Util/XTPGlobal.h" #include "Controls/Util/XTPControlTheme.h" #include "Controls/Util/XTPFunctions.h" #include "Controls/Edit/XTPEdit.h" #include "XTVC50Helpers.h" #include "XTOutBarCtrl.h" #include "XTOutBarCtrlTheme.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[] = __FILE__; #define new DEBUG_NEW #endif IMPLEMENT_THEME_FACTORY(CXTOutBarCtrlTheme) //=========================================================================== // CXTOutBarCtrlTheme class //=========================================================================== CXTOutBarCtrlTheme::CXTOutBarCtrlTheme() { m_bFlatIcon = FALSE; m_bPlainText = FALSE; } CXTOutBarCtrlTheme::~CXTOutBarCtrlTheme() { } void CXTOutBarCtrlTheme::RefreshMetrics() { CXTThemeManagerStyle ::RefreshMetrics(); m_clrBack.SetStandardValue(GetXtremeColor(COLOR_3DSHADOW)); m_clrText.SetStandardValue(GetXtremeColor(COLOR_WINDOW)); } void CXTOutBarCtrlTheme::DrawItemIcon(CDC* pDC, CPoint pt, CXTOutBarItem* pBarItem, CImageList* pImageList) { int nIndex = pBarItem->GetIndex(); if (pBarItem->IsEnabled()) { pImageList->Draw(pDC, nIndex, pt, ILD_NORMAL); } else { HICON hIcon = pImageList->ExtractIcon(nIndex); if (m_bFlatIcon) { CBrush brush(GetXtremeColor(COLOR_3DSHADOW)); pDC->DrawState(pt, CSize(0, 0), hIcon, DST_ICON | DSS_MONO, (HBRUSH)brush); } else { pDC->DrawState(pt, CSize(0, 0), hIcon, DSS_DISABLED | DST_ICON, (HBRUSH)NULL); } DestroyIcon(hIcon); } } void CXTOutBarCtrlTheme::DrawItemText(CDC* pDC, CRect rc, CXTOutBarItem* pBarItem, UINT nFormat) { CString strText = pBarItem->GetName(); if (pBarItem->IsEnabled()) { pDC->DrawText(strText, rc, nFormat); } else { if (m_bPlainText) { pDC->SetTextColor(GetXtremeColor(COLOR_3DSHADOW)); pDC->DrawText(strText, rc, nFormat); } else { rc.OffsetRect(1, 1); pDC->SetTextColor(GetXtremeColor(COLOR_WINDOW)); pDC->DrawText(strText, rc, nFormat); rc.OffsetRect(-1, -1); pDC->SetTextColor(GetXtremeColor(COLOR_3DSHADOW)); pDC->DrawText(strText, rc, nFormat); } } } void CXTOutBarCtrlTheme::DrawFolder(CDC* pDC, CRect rect, CXTOutBarFolder* pBarFolder, const XTMouseState eHilight) { CRect rcFolder(rect); CXTPFontDC fnt(pDC, pBarFolder->GetControl()->GetFontX()); pDC->SetBkMode(TRANSPARENT); pDC->SetTextColor(GetXtremeColor(COLOR_BTNTEXT)); pDC->FillSolidRect(rect, GetXtremeColor(COLOR_3DFACE)); switch (eHilight) { case xtMouseNormal: pDC->Draw3dRect(rect, GetXtremeColor(COLOR_3DHILIGHT), GetXtremeColor(COLOR_3DSHADOW)); break; case xtMouseSelect: pDC->Draw3dRect(rect, GetXtremeColor(COLOR_3DDKSHADOW), GetXtremeColor(COLOR_3DFACE)); rect.InflateRect(-1, -1); pDC->Draw3dRect(rect, GetXtremeColor(COLOR_3DSHADOW), GetXtremeColor(COLOR_3DHILIGHT)); break; case xtMouseHover: pDC->Draw3dRect(rect, GetXtremeColor(COLOR_3DFACE), GetXtremeColor(COLOR_3DDKSHADOW)); rect.InflateRect(-1, -1); pDC->Draw3dRect(rect, GetXtremeColor(COLOR_3DHILIGHT), GetXtremeColor(COLOR_3DSHADOW)); break; } rcFolder.DeflateRect(4, 0); pDC->DrawText(pBarFolder->GetName(), rcFolder, DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); } void CXTOutBarCtrlTheme::FillInsideRect(CDC* pDC, CRect rc) { pDC->FillSolidRect(rc, m_clrBack); } void CXTOutBarCtrlTheme::DrawIconFrame(CDC* pDC, CRect rcIcon, BOOL bSelected, BOOL bPressed) { if (!bSelected) { if (bPressed) pDC->Draw3dRect(rcIcon, GetXtremeColor(COLOR_WINDOWFRAME), GetXtremeColor(COLOR_3DFACE)); else pDC->Draw3dRect(rcIcon, GetXtremeColor(COLOR_3DFACE), GetXtremeColor(COLOR_WINDOWFRAME)); } else { pDC->Draw3dRect(rcIcon, GetXtremeColor(COLOR_WINDOWFRAME), GetXtremeColor(COLOR_3DFACE)); } } ////////////////////////////////////////////////////////////////////////// // CXTOutBarCtrlThemeOfficeXP CXTOutBarCtrlThemeOfficeXP::CXTOutBarCtrlThemeOfficeXP() { m_bFlatIcon = TRUE; m_bPlainText = TRUE; } void CXTOutBarCtrlThemeOfficeXP::RefreshMetrics() { CXTOutBarCtrlTheme::RefreshMetrics(); m_clrBack.SetStandardValue(GetXtremeColor(XPCOLOR_TOOLBAR_FACE)); m_clrText.SetStandardValue(GetXtremeColor(COLOR_BTNTEXT)); } void CXTOutBarCtrlThemeOfficeXP::DrawIconFrame(CDC* pDC, CRect rcIcon, BOOL bSelected, BOOL bPressed) { if (!bSelected) { pDC->FillSolidRect(rcIcon, GetXtremeColor(bPressed ? XPCOLOR_HIGHLIGHT_PUSHED : XPCOLOR_HIGHLIGHT)); pDC->Draw3dRect(rcIcon, GetXtremeColor(COLOR_HIGHLIGHT), GetXtremeColor(COLOR_HIGHLIGHT)); } else { pDC->Draw3dRect(rcIcon, GetXtremeColor(COLOR_HIGHLIGHT), GetXtremeColor(COLOR_HIGHLIGHT)); } } ////////////////////////////////////////////////////////////////////////// // CXTOutBarCtrlThemeOffice2003::CXTOutBarCtrlThemeOffice2003() { RefreshMetrics(); } void CXTOutBarCtrlThemeOffice2003::RefreshMetrics() { CXTOutBarCtrlThemeOfficeXP::RefreshMetrics(); m_grcPushed.SetStandardValue(GetXtremeColor(XPCOLOR_HIGHLIGHT_PUSHED)); m_grcHot.SetStandardValue(GetXtremeColor(XPCOLOR_HIGHLIGHT)); m_grcSelected.SetStandardValue(GetXtremeColor(XPCOLOR_HIGHLIGHT_CHECKED)); m_bLunaTheme = FALSE; if (!XTPColorManager()->IsLunaColorsDisabled()) { XTPCurrentSystemTheme systemTheme = XTPColorManager()->GetCurrentSystemTheme(); switch (systemTheme) { case xtpSystemThemeBlue: case xtpSystemThemeRoyale: case xtpSystemThemeAero: m_clrBack.SetStandardValue(RGB(216, 231, 252)); break; case xtpSystemThemeOlive: m_clrBack.SetStandardValue(RGB(226, 231, 191)); break; case xtpSystemThemeSilver: m_clrBack.SetStandardValue(RGB(223, 223, 234)); break; } if (systemTheme != xtpSystemThemeUnknown) { m_grcSelected.SetStandardValue(RGB(251, 230, 148), RGB(238, 149, 21)); m_grcPushed.SetStandardValue(RGB(232, 127, 8), RGB(247, 218, 124)); m_grcHot.SetStandardValue(RGB(255, 255, 220), RGB(247, 192, 91)); m_bLunaTheme = TRUE; } } } void CXTOutBarCtrlThemeOffice2003::DrawFolder(CDC* pDC, CRect rect, CXTOutBarFolder* pBarFolder, const XTMouseState eHilight) { CRect rcFolder(rect); CXTPFontDC fnt(pDC, pBarFolder->GetControl()->GetFontX()); pDC->SetBkMode(TRANSPARENT); pDC->SetTextColor(GetXtremeColor(COLOR_BTNTEXT)); switch (eHilight) { case xtMouseNormal: XTPDrawHelpers()->GradientFill(pDC, rect, XTPColorManager()->grcDockBar.clrDark, XTPColorManager()->grcDockBar.clrLight, FALSE); break; case xtMouseSelect: XTPDrawHelpers()->GradientFill(pDC, rect, m_grcPushed, FALSE); break; case xtMouseHover: XTPDrawHelpers()->GradientFill(pDC, rect, m_grcSelected, FALSE); break; } pDC->Draw3dRect(rect, GetXtremeColor(COLOR_3DHILIGHT), GetXtremeColor(XPCOLOR_FRAME)); rcFolder.DeflateRect(4, 0); pDC->DrawText(pBarFolder->GetName(), rcFolder, DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); } void CXTOutBarCtrlThemeOffice2003::DrawIconFrame(CDC* pDC, CRect rcIcon, BOOL bSelected, BOOL bPressed) { if (!m_bLunaTheme) { CXTOutBarCtrlThemeOfficeXP::DrawIconFrame(pDC, rcIcon, bSelected, bPressed); return; } if (!bSelected) { if (bPressed) XTPDrawHelpers()->GradientFill(pDC, rcIcon, m_grcPushed, FALSE); else XTPDrawHelpers()->GradientFill(pDC, rcIcon, m_grcHot, FALSE); } else { XTPDrawHelpers()->GradientFill(pDC, rcIcon, m_grcSelected, FALSE); } pDC->Draw3dRect(rcIcon, GetXtremeColor(XPCOLOR_FRAME), GetXtremeColor(XPCOLOR_FRAME)); }
26.75873
130
0.723455
11Zero
ec3e17bff6330d41841ad86e8219857421661671
3,565
cpp
C++
src/test/TestSystem.cpp
innatewonder/mythril
9f656a58650ac7a8c195b3868232983809205b68
[ "MIT" ]
null
null
null
src/test/TestSystem.cpp
innatewonder/mythril
9f656a58650ac7a8c195b3868232983809205b68
[ "MIT" ]
null
null
null
src/test/TestSystem.cpp
innatewonder/mythril
9f656a58650ac7a8c195b3868232983809205b68
[ "MIT" ]
null
null
null
#include "CommonPrecompiled.h" #include "CoreUtils.h" #include "TestSystem.h" #include "TestComponent.h" #include "TestMath.h" #include "TestNetworking.h" namespace Test { TestSystem::TestSystem() {} TestSystem::~TestSystem() {} TEST(ObjectTest, Make_Destroy_Object) { EXPECT_EQ(0, Core::gCore->NumObjects()); Object* obj = Factory::MakeObject(); EXPECT_EQ(1, Core::gCore->NumObjects()); obj->Kill(); Core::gCore->Tick(0); EXPECT_EQ(0, Core::gCore->NumObjects()); } TEST(ComponentTest, Make_Destroy_Component) { System* testSys = Core::gCore->GetSystem(Sys::TestSystem); EXPECT_EQ(0, testSys->NumComponents()); Component* c1 = Factory::MakeComponent(Comp::TestComponent); EXPECT_EQ(sizeof(TestComponent), sizeof(*c1)); EXPECT_EQ("TestComponent", c1->GetName()); EXPECT_EQ(1, testSys->NumComponents()); Factory::DestroyComponent(c1); EXPECT_EQ(0, testSys->NumComponents()); } TEST(ComponentTest, Make_Unique_Should_Allow_1) { Object* obj = Factory::MakeObject(); EXPECT_TRUE(obj->AddComponent(Comp::TestComponent) != nullptr); EXPECT_FALSE(obj->AddComponent(Comp::TestComponent) != nullptr); obj->RemoveComponent(Comp::TestComponent); EXPECT_TRUE(obj->AddComponent(Comp::TestComponent) != nullptr); } TEST(RandomTest, Test_Min_Max_10000) { Generation::Random random; u32 min = 7; u32 max = 45; for(int i = 0; i < 10000; ++i) { u32 num = random.Get(min, max); EXPECT_LE(min, num); EXPECT_GE(max, num); } } TEST(RandomTest, Test_Float_10000) { Generation::Random random; for(int i = 0; i < 10000; ++i) { f32 num = random.Getf(); EXPECT_LE(0.0f, num); EXPECT_GE(1.0f, num); } } struct testStruct { int i, v; float f, s; }; TEST(PoolTest, Allocate_1) { Memory::PoolAllocator p = Memory::PoolAllocator(sizeof(testStruct)); testStruct* one = p.New<testStruct>(); p.Delete(one); p.Log(); } TEST(PoolTest, Reallocate) { Memory::PoolAllocator p = Memory::PoolAllocator(sizeof(testStruct)); testStruct* one = p.New<testStruct>(); p.Delete(one); one = p.New<testStruct>(); p.Delete(one); p.Log(); } TEST(PoolTest, Allocate100) { Containers::Vector<testStruct*> cont; cont.reserve(100); Memory::PoolAllocator p = Memory::PoolAllocator(sizeof(testStruct)); for(u32 i = 0; i < 100; ++i) { cont.push_back(p.New<testStruct>()); } for(u32 i = 0; i < 100; ++i) { p.Delete(cont[i]); } p.Log(); } TEST(PoolTest, RandomAccess100) { Containers::Vector<testStruct*> cont; cont.reserve(100); Memory::PoolAllocator p = Memory::PoolAllocator(sizeof(testStruct)); for(u32 i = 0; i < 100; ++i) { cont.push_back(p.New<testStruct>()); } for(u32 i = 0; i < 100; i += 10) { p.Delete(cont[i]); } for(u32 i = 0; i < 100; i += 10) { cont[i] = p.New<testStruct>(); } for(u32 i = 0; i < 100; ++i) { p.Delete(cont[i]); } p.Log(); } bool TestSystem::Initialize(ArgParser& args) { int argc = args.GetArgC(); testing::InitGoogleMock(&argc, args.GetArgV()); return true; } void TestSystem::Destroy() {} void TestSystem::Test() { // get rid of warning on linux about unused ret u32 ret = RUN_ALL_TESTS(); //Test_Math(); TestNetworking(); } void TestSystem::Tick(f32 dt) {} void TestSystem::HandleMessage(Message* msg) {} }
21.220238
72
0.608976
innatewonder
ec40edc09bbd55395591c151fb7c2309c88c58c7
5,306
hpp
C++
include/util/types.hpp
wavefunction91/HAXX
e0c282b70ee009a2a01871979f505bcca89713ba
[ "BSD-3-Clause" ]
6
2018-11-05T22:20:28.000Z
2020-12-28T22:22:55.000Z
include/util/types.hpp
wavefunction91/HAXX
e0c282b70ee009a2a01871979f505bcca89713ba
[ "BSD-3-Clause" ]
null
null
null
include/util/types.hpp
wavefunction91/HAXX
e0c282b70ee009a2a01871979f505bcca89713ba
[ "BSD-3-Clause" ]
null
null
null
/* * This file is a part of HAXX * * Copyright (c) 2017 David Williams-Young * All rights reserved. * * See LICENSE.txt */ #ifndef __INCLUDED_UTIL_TYPES_HPP__ #define __INCLUDED_UTIL_TYPES_HPP__ namespace HAXX { struct null_t {}; // Null struct to handle various situations template <typename T, typename _LoadT = T> struct GenericType { typedef T value_type; // value_type typedef _LoadT load_t; // Load typename typedef null_t noscalar_t; // Null load type // Ratio of load_t / T static constexpr size_t sz_ratio = sizeof(load_t) / sizeof(T); // Sanity checks static_assert( sizeof(load_t) % sizeof(T) == 0, "sizeof(load_t) must be an integer multiple of sizeof(T)" ); static_assert( sizeof(load_t) >= sizeof(T), "sizeof(load_t) must >= sizeof(T)" ); // Load from memory static inline load_t Load( const T* const x ){ return load_t(*x); } static inline load_t Load( ){ return load_t(0.); } // Store to memory static inline void Store( T* const x, const load_t y ){ *x = y; } // Conjugate static inline load_t Conj( const load_t &x ){ return SmartConj(x); } static inline noscalar_t Conj( const noscalar_t &x ){ return noscalar_t{}; } // Load a passed scalar without modification template <typename U> static inline U LoadScalar( const U &alpha ){ return alpha; } // LoadScalar with no scalar Passed static inline noscalar_t LoadScalar(){ return noscalar_t{}; } // Multiply load_t with anything template <typename U, typename V> static inline load_t Mul(const U &a, const V &b){ return a * b; } // Specializations for noscalar_t static inline load_t Mul( const load_t &a, const noscalar_t &b ){ return a; } static inline load_t Mul( const noscalar_t &a, const load_t &b ){ return b; } }; // GenericType // Forward decl template <typename T> struct AVXType; template<> struct AVXType<double> : public GenericType<double, __m256d> { // Scalar types struct real_t { __m256d x; }; ///< Real (double) struct complex_t { __m256d x; __m256d y; }; ///< Complex (double) struct quaternion_t { __m256d x; }; ///< Quaternion (double) // Aliases using d = double; using cd = std::complex<double>; using qd = quaternion<double>; // Inherit using GenericType<double,__m256d>::LoadScalar; using GenericType<double,__m256d>::Mul; // Load from memory static inline __m256d Load( const qd * const x ){ return LOAD_256D_UNALIGNED_AS(d,x); } static inline __m256d Load(){ return _mm256_setzero_pd(); } // Store to memory static inline void Store( qd * const x, const __m256d &y ){ STORE_256D_UNALIGNED_AS(d,x,y); } // Conjugate static inline __m256d Conj( const __m256d &x){ return QCONJ_256D(x); } // Load double as q = { x, x, x, x } static inline real_t LoadScalar( const double &x ){ return real_t{ _mm256_broadcast_sd(&x) }; } // Load complex double as q = { { x(R), x(I),x(R), x(I) }, // { x(I),-x(R),x(I),-x(R) } } static inline complex_t LoadScalar( const std::complex<double> & x ){ const __m256i maskConj = _mm256_set_epi64x( 0x8000000000000000, 0, 0x8000000000000000, 0 ); __m128d alphaC = LOAD_128D_UNALIGNED_AS(double,&x); __m256d alpha = SET_256D_FROM_128D(alphaC,alphaC); __m256d alpha_C = _mm256_xor_pd(_mm256_permute_pd(alpha, 0x5), _mm256_castsi256_pd(maskConj) ); return complex_t{ alpha, alpha_C }; } // Load quaternion double as is static inline quaternion_t LoadScalar( const qd &x ){ return quaternion_t{ Load(&x) }; } // Multiply load_t with real_t static inline __m256d Mul( const __m256d &a, const real_t &b ) { return _mm256_mul_pd(b.x, a); } static inline __m256d Mul( const real_t &a, const __m256d &b ) { return _mm256_mul_pd(a.x, b); } // Multiply load_t with complex_t static inline __m256d Mul( const complex_t &a, const __m256d &b ) { __m256d p1 = _mm256_mul_pd(b, a.x); __m256d p2 = _mm256_mul_pd(b, a.y); return _mm256_hsub_pd(p1,p2); } static inline __m256d Mul( const __m256d &a, const complex_t &b ) { // FIXME: NEEDS VALIDATAION const __m256i mask1 = _mm256_set_epi64x(0x8000000000000000,0,0,0); const __m256i mask2 = _mm256_set_epi64x(0,0x8000000000000000,0,0); __m256d b1 = _mm256_xor_pd(b.x,_mm256_castsi256_pd(mask1)); __m256d b2 = _mm256_xor_pd(b.y,_mm256_castsi256_pd(mask2)); __m256d p1 = _mm256_mul_pd(a, b1); __m256d p2 = _mm256_mul_pd(a, b2); return _mm256_hsub_pd(p1,p2); } // Multiply load_t with quaternion_t static inline __m256d Mul( const __m256d &a, const quaternion_t &b ){ return MULDQ_NN(a,b.x); } static inline __m256d Mul( const quaternion_t &a, const __m256d &b ){ return MULDQ_NN(a.x,b); } }; // AVXType<double> }; #endif
23.170306
80
0.615718
wavefunction91
ec417dfd50cfb5bc6a527592cdd9fc96d30579ed
692
cc
C++
src/platform/platform.cc
AnthonyBrunasso/test_games
31354d2bf95aae9a880e7292bc78ad8577b3f09c
[ "MIT" ]
null
null
null
src/platform/platform.cc
AnthonyBrunasso/test_games
31354d2bf95aae9a880e7292bc78ad8577b3f09c
[ "MIT" ]
null
null
null
src/platform/platform.cc
AnthonyBrunasso/test_games
31354d2bf95aae9a880e7292bc78ad8577b3f09c
[ "MIT" ]
2
2019-11-12T23:15:18.000Z
2020-01-15T17:49:27.000Z
#pragma once #if _WIN32 // Windows #defines min/max. This stops it from doing so. #define NOMINMAX // Reduce header size. #define WIN32_LEAN_AND_MEAN // Disable unneeded warnings. // Warns about using %lu to printf uint64_t #pragma warning(disable : 4477) #endif #include "common/macro.h" #include "type.cc" #include "x64_intrin.h" #include "clock.cc" #include "platform_getopt.cc" #include "window.cc" #if _WIN32 #include "win32_filesystem.cc" #include "win32_sleep.cc" #include "win32_thread.cc" #include "win32_udp.cc" #include "win32_tcp.cc" #else #include "unix_filesystem.cc" #include "unix_sleep.cc" #include "unix_thread.cc" #include "unix_udp.cc" #endif #include "affinity.cc"
19.222222
57
0.75
AnthonyBrunasso
ec4468c1fabf68759c724aba021479c2fd0c9ece
1,041
cpp
C++
VFrame/V3DBatchModelGroup.cpp
gamepopper/Vigilante-Game-Framework
72db889de7d41c331b484f7bb230f78096bde2c5
[ "MIT" ]
80
2017-04-05T19:55:31.000Z
2022-02-08T18:28:48.000Z
VFrame/V3DBatchModelGroup.cpp
gamepopper/Vigilante-Game-Framework
72db889de7d41c331b484f7bb230f78096bde2c5
[ "MIT" ]
2
2017-04-09T13:11:28.000Z
2018-06-04T19:46:08.000Z
VFrame/V3DBatchModelGroup.cpp
gamepopper/Vigilante-Game-Framework
72db889de7d41c331b484f7bb230f78096bde2c5
[ "MIT" ]
5
2017-04-05T19:55:38.000Z
2020-11-08T08:13:15.000Z
#include "V3DBatchModelGroup.h" #ifndef VFRAME_NO_3D #include "V3DCamera.h" #include "V3DShader.h" V3DBatchModelGroup::V3DBatchModelGroup(V3DObject* BaseObject, unsigned int MaxSize) : VGroup(MaxSize) { baseObject = BaseObject; } void V3DBatchModelGroup::Destroy() { VSUPERCLASS::Destroy(); delete baseObject; } void V3DBatchModelGroup::UpdateShader(V3DCamera* Camera, V3DShader* Shader) { currentCamera = Camera; currentShader = Shader; } void V3DBatchModelGroup::Draw(sf::RenderTarget& RenderTarget) { for (unsigned int i = 0; i < members.size(); i++) { V3DObject* base = dynamic_cast<V3DObject*>(members[i]); if (base != nullptr && base->exists && base->visible && currentCamera->BoxInView(base->Position, baseObject->GetMinimum(), baseObject->GetMaximum())) { baseObject->Position = base->Position; baseObject->Rotation = base->Rotation; baseObject->Scale = base->Scale; baseObject->UpdateShader(currentShader, currentCamera); baseObject->Update(0.0f); baseObject->Draw(RenderTarget); } } } #endif
25.390244
151
0.731988
gamepopper
ec455dfdd733e47d4985e79535db9a0a0095f36f
1,707
hpp
C++
src/xalanc/XercesParserLiaison/XercesDOMFormatterWalker.hpp
rherardi/xml-xalan-c-src_1_10_0
24e6653a617a244e4def60d67b57e70a192a5d4d
[ "Apache-2.0" ]
null
null
null
src/xalanc/XercesParserLiaison/XercesDOMFormatterWalker.hpp
rherardi/xml-xalan-c-src_1_10_0
24e6653a617a244e4def60d67b57e70a192a5d4d
[ "Apache-2.0" ]
null
null
null
src/xalanc/XercesParserLiaison/XercesDOMFormatterWalker.hpp
rherardi/xml-xalan-c-src_1_10_0
24e6653a617a244e4def60d67b57e70a192a5d4d
[ "Apache-2.0" ]
null
null
null
/* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(XERCESDOMFORMATTERWALKER_HEADER_GUARD_1357924680) #define XERCESDOMFORMATTERWALKER_HEADER_GUARD_1357924680 #include <xalanc/XercesParserLiaison/XercesParserLiaisonDefinitions.hpp> #include <xalanc/Include/XalanMemoryManagement.hpp> #include <xalanc/XercesParserLiaison/XercesDOMWalker.hpp> XALAN_CPP_NAMESPACE_BEGIN class FormatterListener; class XALAN_XERCESPARSERLIAISON_EXPORT XercesDOMFormatterWalker : public XercesDOMWalker { public: typedef XercesDOMWalker ParentType; /** * Constructor. */ XercesDOMFormatterWalker(FormatterListener& theFormatterListener); virtual ~XercesDOMFormatterWalker(); protected: virtual bool startNode(const DOMNodeType* node); virtual bool endNode(const DOMNodeType* node); #if !defined(XALAN_NO_USING_DECLARATION) using ParentType::startNode; using ParentType::endNode; #endif private: FormatterListener& m_formatterListener; }; XALAN_CPP_NAMESPACE_END #endif // XERCESDOMFORMATTERWALKER_HEADER_GUARD_1357924680
21.884615
89
0.756883
rherardi
ec478fa570148f703e1691c582a3aa25fceb2127
482
cpp
C++
src/arg/detail/Token.cpp
jaredmpayne/arg
2f6fd891f9ca2cd8d970df358909334545870b66
[ "Apache-2.0" ]
null
null
null
src/arg/detail/Token.cpp
jaredmpayne/arg
2f6fd891f9ca2cd8d970df358909334545870b66
[ "Apache-2.0" ]
null
null
null
src/arg/detail/Token.cpp
jaredmpayne/arg
2f6fd891f9ca2cd8d970df358909334545870b66
[ "Apache-2.0" ]
null
null
null
#include "arg/detail/Token.hpp" #include <string> arg::detail::Token::Token(const std::string &value, LexType lex_type) : _value(value), _lex_type(lex_type) { } bool arg::detail::Token::operator==(const Token &other) const { return this->lex_type() == other.lex_type() && this->value() == other.value(); } const std::string &arg::detail::Token::value() const { return _value; } arg::detail::Token::LexType arg::detail::Token::lex_type() const { return _lex_type; }
25.368421
82
0.678423
jaredmpayne
ec48a48536d13444b8d8162433196e1f181bc19a
200
cpp
C++
MIT_CPP_2009/Classes/IntroClasses/Vehicle.cpp
AlexandrPirogov/MIT_CPP-1
ec63b2fa9a65c1fcc29cc68fc66fe60c21add4c9
[ "MIT" ]
2
2021-09-20T09:40:13.000Z
2021-09-20T09:40:35.000Z
Classes/IntroClasses/Vehicle.cpp
AlexandrPirogov/MIT_CPP
6c9fa29be431f161472262e464d1377242013a0d
[ "MIT" ]
null
null
null
Classes/IntroClasses/Vehicle.cpp
AlexandrPirogov/MIT_CPP
6c9fa29be431f161472262e464d1377242013a0d
[ "MIT" ]
1
2021-09-09T14:51:34.000Z
2021-09-09T14:51:34.000Z
#include "Vehicle.h" void Vehicle::getModel(){ std::cout << "This is model " << this->model << std::endl; }; void Vehicle::getInfo(){ std::cout << "This is Parent Vehicle " << std::endl; }
15.384615
61
0.595
AlexandrPirogov
ec496d87b1c126fcd4a5015cd73e6f32fd729fd7
20,906
cpp
C++
old-prototypes/src/PrototypeFramework.cpp
davedissian/gl-graphics-prototypes
c68e84faf0a3129edfde95eaca73634f36cdf790
[ "MIT" ]
1
2016-06-04T01:15:15.000Z
2016-06-04T01:15:15.000Z
old-prototypes/src/PrototypeFramework.cpp
davedissian/graphics-prototypes
c68e84faf0a3129edfde95eaca73634f36cdf790
[ "MIT" ]
null
null
null
old-prototypes/src/PrototypeFramework.cpp
davedissian/graphics-prototypes
c68e84faf0a3129edfde95eaca73634f36cdf790
[ "MIT" ]
null
null
null
/* Prototype Framework Copyright (c) 2013-2014 David Avedissian (avedissian.david@gmail.com) Author: David Avedissian */ #include "PrototypeFramework.h" Ogre::MaterialPtr cloneMaterial(const string& originalName, const string& newName) { return Ogre::MaterialManager::getSingleton().getByName(originalName)->clone(newName); } string generateName(const string& prefix) { static std::map<string, uint> prefixCounter; if (prefixCounter.find(prefix) == prefixCounter.end()) prefixCounter.insert(std::make_pair<string, uint>(string(prefix), 0)); return prefix + Ogre::StringConverter::toString(prefixCounter[prefix]++); } Ogre::MeshPtr generateSphereMesh(const string& name, const float r, const int nRings, const int nSegments, bool texCoords, bool normals) { using namespace Ogre; MeshPtr pSphere = MeshManager::getSingleton().createManual( name, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); SubMesh* pSphereVertex = pSphere->createSubMesh(); pSphere->sharedVertexData = new VertexData(); VertexData* vertexData = pSphere->sharedVertexData; // define the vertex format VertexDeclaration* vertexDecl = vertexData->vertexDeclaration; size_t currOffset = 0; // positions vertexDecl->addElement(0, currOffset, VET_FLOAT3, VES_POSITION); currOffset += VertexElement::getTypeSize(VET_FLOAT3); // normals vertexDecl->addElement(0, currOffset, VET_FLOAT3, VES_NORMAL); currOffset += VertexElement::getTypeSize(VET_FLOAT3); // two dimensional texture coordinates vertexDecl->addElement(0, currOffset, VET_FLOAT2, VES_TEXTURE_COORDINATES, 0); currOffset += VertexElement::getTypeSize(VET_FLOAT2); // allocate the vertex buffer vertexData->vertexCount = (nRings + 1) * (nSegments + 1); HardwareVertexBufferSharedPtr vBuf = HardwareBufferManager::getSingleton().createVertexBuffer( vertexDecl->getVertexSize(0), vertexData->vertexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY, false); VertexBufferBinding* binding = vertexData->vertexBufferBinding; binding->setBinding(0, vBuf); float* pVertex = static_cast<float*>(vBuf->lock(HardwareBuffer::HBL_DISCARD)); // allocate index buffer pSphereVertex->indexData->indexCount = 6 * nRings * (nSegments + 1); pSphereVertex->indexData->indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( HardwareIndexBuffer::IT_16BIT, pSphereVertex->indexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY, false); HardwareIndexBufferSharedPtr iBuf = pSphereVertex->indexData->indexBuffer; unsigned short* pIndices = static_cast<unsigned short*>(iBuf->lock(HardwareBuffer::HBL_DISCARD)); float fDeltaRingAngle = (Math::PI / nRings); float fDeltaSegAngle = (2 * Math::PI / nSegments); unsigned short wVerticeIndex = 0; // Generate the group of rings for the sphere for (int ring = 0; ring <= nRings; ring++) { float r0 = r * sinf(ring * fDeltaRingAngle); float y0 = r * cosf(ring * fDeltaRingAngle); // Generate the group of segments for the current ring for (int seg = 0; seg <= nSegments; seg++) { float x0 = r0 * sinf(seg * fDeltaSegAngle); float z0 = r0 * cosf(seg * fDeltaSegAngle); // Add one vertex to the strip which makes up the sphere *pVertex++ = x0; *pVertex++ = y0; *pVertex++ = z0; Vector3 vNormal = Vector3(x0, y0, z0).normalisedCopy(); *pVertex++ = vNormal.x; *pVertex++ = vNormal.y; *pVertex++ = vNormal.z; *pVertex++ = (float)seg / (float)nSegments; *pVertex++ = (float)ring / (float)nRings; if (ring != nRings) { // each vertex (except the last) has six indices pointing to it *pIndices++ = wVerticeIndex + nSegments + 1; *pIndices++ = wVerticeIndex; *pIndices++ = wVerticeIndex + nSegments; *pIndices++ = wVerticeIndex + nSegments + 1; *pIndices++ = wVerticeIndex + 1; *pIndices++ = wVerticeIndex; wVerticeIndex++; } }; // end for seg } // end for ring // Unlock vBuf->unlock(); iBuf->unlock(); // Generate face list pSphereVertex->useSharedVertices = true; // the original code was missing this line: pSphere->_setBounds(AxisAlignedBox(Vector3(-r, -r, -r), Vector3(r, r, r)), false); pSphere->_setBoundingSphereRadius(r); // this line makes clear the mesh is loaded (avoids memory leaks) pSphere->load(); return pSphere; } //------------------------------------------------------------------------------------- PrototypeFramework::PrototypeFramework() : mRoot(0), mCamera(0), mActiveCamera(0), mSceneMgr(0), mWindow(0), mCameraControlEnabled(true), mCameraSpeed(10.0f), mCameraSpeedMultiplier(50.0f), mGoingForward(false), mGoingBack(false), mGoingLeft(false), mGoingRight(false), mGoingUp(false), mGoingDown(false), mFastMove(false), mSlowMove(false), mTrayMgr(0), mDetailsPanel(0), mCursorWasVisible(false), mShutDown(false), mInputManager(0), mMouse(0), mKeyboard(0), mOverlaySystem(0) { } //------------------------------------------------------------------------------------- PrototypeFramework::~PrototypeFramework() { if (mTrayMgr) delete mTrayMgr; if (mOverlaySystem) delete mOverlaySystem; // Remove ourself as a Window listener Ogre::WindowEventUtilities::removeWindowEventListener(mWindow, this); windowClosed(mWindow); delete mRoot; } //------------------------------------------------------------------------------------- bool PrototypeFramework::configure() { // Try to restore config, if that fails then show the config dialog box // If the user presses cancel then return false. if (!mRoot->restoreConfig()) { if (!mRoot->showConfigDialog()) return false; } // Initialise Ogre mWindow = mRoot->initialise(true, "Prototype"); return true; } //------------------------------------------------------------------------------------- void PrototypeFramework::chooseSceneManager() { // Get the SceneManager, in this case a generic one mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC); } //------------------------------------------------------------------------------------- void PrototypeFramework::createCamera() { // Create the camera mCamera = mSceneMgr->createCamera("PlayerCam"); // Position it at 500 in Z direction mCamera->setPosition(Ogre::Vector3(0, 0, 80)); // Look back along -Z mCamera->lookAt(Ogre::Vector3(0, 0, -300)); mCamera->setNearClipDistance(5); mActiveCamera = mCamera; } //------------------------------------------------------------------------------------- void PrototypeFramework::createFrameListener() { Ogre::LogManager::getSingletonPtr()->logMessage("*** Initializing OIS ***"); OIS::ParamList pl; size_t windowHnd = 0; std::ostringstream windowHndStr; mWindow->getCustomAttribute("WINDOW", &windowHnd); windowHndStr << windowHnd; pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str())); mInputManager = OIS::InputManager::createInputSystem(pl); mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject(OIS::OISKeyboard, true)); mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject(OIS::OISMouse, true)); mMouse->setEventCallback(this); mKeyboard->setEventCallback(this); // Set initial mouse clipping size windowResized(mWindow); // Register as a Window listener Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this); OgreBites::InputContext input; input.mAccelerometer = NULL; input.mKeyboard = mKeyboard; input.mMouse = mMouse; input.mMultiTouch = NULL; mTrayMgr = new OgreBites::SdkTrayManager("InterfaceName", mWindow, input, this); mTrayMgr->showFrameStats(OgreBites::TL_BOTTOMLEFT); mTrayMgr->hideCursor(); // create a params panel for displaying sample details Ogre::StringVector items; items.push_back("cam.pX"); items.push_back("cam.pY"); items.push_back("cam.pZ"); items.push_back(""); items.push_back("cam.oW"); items.push_back("cam.oX"); items.push_back("cam.oY"); items.push_back("cam.oZ"); items.push_back(""); items.push_back("Filtering"); items.push_back("Poly Mode"); mDetailsPanel = mTrayMgr->createParamsPanel(OgreBites::TL_NONE, "DetailsPanel", 200, items); mDetailsPanel->setParamValue(9, "Bilinear"); mDetailsPanel->setParamValue(10, "Solid"); mDetailsPanel->hide(); mRoot->addFrameListener(this); mSceneMgr->addRenderQueueListener(mOverlaySystem); } //------------------------------------------------------------------------------------- void PrototypeFramework::destroyScene() { mSceneMgr->removeRenderQueueListener(mOverlaySystem); } //------------------------------------------------------------------------------------- void PrototypeFramework::createViewports() { // Create one viewport, entire window Ogre::Viewport* vp = mWindow->addViewport(mCamera); vp->setBackgroundColour(Ogre::ColourValue(0, 0, 0)); // Alter the camera aspect ratio to match the viewport mCamera->setAspectRatio(Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight())); } //------------------------------------------------------------------------------------- void PrototypeFramework::setupResources() { // Load resource paths from config file Ogre::ConfigFile cf; cf.load("resources.cfg"); // Go through all sections & settings in the file Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator(); Ogre::String secName, typeName, archName; while (seci.hasMoreElements()) { secName = seci.peekNextKey(); Ogre::ConfigFile::SettingsMultiMap* settings = seci.getNext(); Ogre::ConfigFile::SettingsMultiMap::iterator i; for (i = settings->begin(); i != settings->end(); ++i) { typeName = i->first; archName = i->second; Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName); } } } //------------------------------------------------------------------------------------- void PrototypeFramework::createResourceListener() { } //------------------------------------------------------------------------------------- void PrototypeFramework::loadResources() { Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); } //------------------------------------------------------------------------------------- void PrototypeFramework::go() { if (!setup()) return; mRoot->startRendering(); // clean up destroyScene(); } //------------------------------------------------------------------------------------- bool PrototypeFramework::setup() { #ifdef _DEBUG mRoot = new Ogre::Root("plugins_d.cfg"); #else mRoot = new Ogre::Root("plugins.cfg"); #endif mOverlaySystem = new Ogre::OverlaySystem(); setupResources(); if (!configure()) return false; chooseSceneManager(); createCamera(); createViewports(); // Set default mipmap level (NB some APIs ignore this) Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5); // Create any resource listeners (for loading screens) createResourceListener(); // Load resources loadResources(); // Create the scene createScene(); createFrameListener(); return true; }; //------------------------------------------------------------------------------------- bool PrototypeFramework::frameRenderingQueued(const Ogre::FrameEvent& evt) { if (mWindow->isClosed()) return false; if (mShutDown) return false; mMouse->capture(); mKeyboard->capture(); mTrayMgr->frameRenderingQueued(evt); if (!mTrayMgr->isDialogVisible() && mCameraControlEnabled) { // Control the camera Ogre::Vector3 velocity = Ogre::Vector3::ZERO; if (mGoingForward) velocity += mCamera->getDirection(); if (mGoingBack) velocity -= mCamera->getDirection(); if (mGoingRight) velocity += mCamera->getRight(); if (mGoingLeft) velocity -= mCamera->getRight(); if (mGoingUp) velocity += mCamera->getUp(); if (mGoingDown) velocity -= mCamera->getUp(); // Apply velocity speed to the direction vector float speed; if (mFastMove) speed = mSlowMove ? mCameraSpeed : mCameraSpeed * mCameraSpeedMultiplier; else if (mSlowMove) speed = mCameraSpeed / mCameraSpeedMultiplier; else speed = mCameraSpeed; if (velocity.squaredLength() > 0.0f) { velocity.normalise(); velocity *= speed; } // Move the camera if (velocity != Ogre::Vector3::ZERO) mCamera->move(velocity * evt.timeSinceLastFrame); if (mDetailsPanel->isVisible()) // if details panel is visible, then update // its contents { mDetailsPanel->setParamValue( 0, Ogre::StringConverter::toString(mActiveCamera->getDerivedPosition().x)); mDetailsPanel->setParamValue( 1, Ogre::StringConverter::toString(mActiveCamera->getDerivedPosition().y)); mDetailsPanel->setParamValue( 2, Ogre::StringConverter::toString(mActiveCamera->getDerivedPosition().z)); mDetailsPanel->setParamValue( 4, Ogre::StringConverter::toString(mActiveCamera->getDerivedOrientation().w)); mDetailsPanel->setParamValue( 5, Ogre::StringConverter::toString(mActiveCamera->getDerivedOrientation().x)); mDetailsPanel->setParamValue( 6, Ogre::StringConverter::toString(mActiveCamera->getDerivedOrientation().y)); mDetailsPanel->setParamValue( 7, Ogre::StringConverter::toString(mActiveCamera->getDerivedOrientation().z)); } } return true; } //------------------------------------------------------------------------------------- bool PrototypeFramework::keyPressed(const OIS::KeyEvent& arg) { if (mTrayMgr->isDialogVisible()) return true; // don't process any more keys if dialog is up if (arg.key == OIS::KC_F) // toggle visibility of advanced frame stats { mTrayMgr->toggleAdvancedFrameStats(); } else if (arg.key == OIS::KC_G) // toggle visibility of even rarer debugging details { if (mDetailsPanel->getTrayLocation() == OgreBites::TL_NONE) { mTrayMgr->moveWidgetToTray(mDetailsPanel, OgreBites::TL_TOPRIGHT, 0); mDetailsPanel->show(); } else { mTrayMgr->removeWidgetFromTray(mDetailsPanel); mDetailsPanel->hide(); } } else if (arg.key == OIS::KC_T) // cycle polygon rendering mode { Ogre::String newVal; Ogre::TextureFilterOptions tfo; unsigned int aniso; switch (mDetailsPanel->getParamValue(9).asUTF8()[0]) { case 'B': newVal = "Trilinear"; tfo = Ogre::TFO_TRILINEAR; aniso = 1; break; case 'T': newVal = "Anisotropic"; tfo = Ogre::TFO_ANISOTROPIC; aniso = 8; break; case 'A': newVal = "None"; tfo = Ogre::TFO_NONE; aniso = 1; break; default: newVal = "Bilinear"; tfo = Ogre::TFO_BILINEAR; aniso = 1; } Ogre::MaterialManager::getSingleton().setDefaultTextureFiltering(tfo); Ogre::MaterialManager::getSingleton().setDefaultAnisotropy(aniso); mDetailsPanel->setParamValue(9, newVal); } else if (arg.key == OIS::KC_R) // cycle polygon rendering mode { Ogre::String newVal; Ogre::PolygonMode pm; switch (mActiveCamera->getPolygonMode()) { case Ogre::PM_SOLID: newVal = "Wireframe"; pm = Ogre::PM_WIREFRAME; break; case Ogre::PM_WIREFRAME: newVal = "Points"; pm = Ogre::PM_POINTS; break; default: newVal = "Solid"; pm = Ogre::PM_SOLID; } mActiveCamera->setPolygonMode(pm); mDetailsPanel->setParamValue(10, newVal); } else if (arg.key == OIS::KC_F5) // refresh all textures { Ogre::TextureManager::getSingleton().reloadAll(); } else if (arg.key == OIS::KC_SYSRQ) // take a screenshot { mWindow->writeContentsToTimestampedFile("screenshot", ".jpg"); } else if (arg.key == OIS::KC_ESCAPE) { mShutDown = true; } // Camera Control if (arg.key == OIS::KC_W || arg.key == OIS::KC_UP) mGoingForward = true; else if (arg.key == OIS::KC_S || arg.key == OIS::KC_DOWN) mGoingBack = true; else if (arg.key == OIS::KC_A || arg.key == OIS::KC_LEFT) mGoingLeft = true; else if (arg.key == OIS::KC_D || arg.key == OIS::KC_RIGHT) mGoingRight = true; else if (arg.key == OIS::KC_PGUP) mGoingUp = true; else if (arg.key == OIS::KC_PGDOWN) mGoingDown = true; else if (arg.key == OIS::KC_LSHIFT) mFastMove = true; else if (arg.key == OIS::KC_LCONTROL) mSlowMove = true; return true; } bool PrototypeFramework::keyReleased(const OIS::KeyEvent& arg) { if (mTrayMgr->isDialogVisible()) return true; // don't process any more keys if dialog is up // Camera Control if (arg.key == OIS::KC_W || arg.key == OIS::KC_UP) mGoingForward = false; else if (arg.key == OIS::KC_S || arg.key == OIS::KC_DOWN) mGoingBack = false; else if (arg.key == OIS::KC_A || arg.key == OIS::KC_LEFT) mGoingLeft = false; else if (arg.key == OIS::KC_D || arg.key == OIS::KC_RIGHT) mGoingRight = false; else if (arg.key == OIS::KC_PGUP) mGoingUp = false; else if (arg.key == OIS::KC_PGDOWN) mGoingDown = false; else if (arg.key == OIS::KC_LSHIFT) mFastMove = false; else if (arg.key == OIS::KC_LCONTROL) mSlowMove = false; return true; } bool PrototypeFramework::mouseMoved(const OIS::MouseEvent& arg) { mTrayMgr->injectMouseMove(arg); if (mTrayMgr->isDialogVisible()) return true; // don't process any more keys if dialog is up /* mCamera->yaw(Ogre::Degree(-arg.state.X.rel * 0.15f)); mCamera->pitch(Ogre::Degree(-arg.state.Y.rel * 0.15f)); */ mCamera->setOrientation(mCamera->getOrientation() * Quat(Ogre::Degree(-arg.state.X.rel * 0.15f), Vec3::UNIT_Y) * Quat(Ogre::Degree(-arg.state.Y.rel * 0.15f), Vec3::UNIT_X)); return true; } bool PrototypeFramework::mousePressed(const OIS::MouseEvent& arg, OIS::MouseButtonID id) { mTrayMgr->injectMouseDown(arg, id); if (mTrayMgr->isDialogVisible()) return true; // don't process any more keys if dialog is up return true; } bool PrototypeFramework::mouseReleased(const OIS::MouseEvent& arg, OIS::MouseButtonID id) { mTrayMgr->injectMouseUp(arg, id); if (mTrayMgr->isDialogVisible()) return true; // don't process any more keys if dialog is up return true; } // Adjust mouse clipping area void PrototypeFramework::windowResized(Ogre::RenderWindow* rw) { unsigned int width, height, depth; int left, top; rw->getMetrics(width, height, depth, left, top); const OIS::MouseState& ms = mMouse->getMouseState(); ms.width = width; ms.height = height; } // Unattach OIS before window shutdown (very important under Linux) void PrototypeFramework::windowClosed(Ogre::RenderWindow* rw) { // Only close for window that created OIS (the main window in these demos) if (rw == mWindow) { if (mInputManager) { mInputManager->destroyInputObject(mMouse); mInputManager->destroyInputObject(mKeyboard); OIS::InputManager::destroyInputSystem(mInputManager); mInputManager = 0; } } }
32.974763
100
0.58543
davedissian
ec4b1f7a1f99fa016ae51bfb3a92b8b53d2a3d5c
2,754
cpp
C++
antlisp/lib/varname/namespace.cpp
akindyakov/antlisp
6a772dbdc728a031b1f8b25f9c7a6f7a168d0177
[ "MIT" ]
2
2018-03-22T19:42:17.000Z
2018-03-29T04:07:33.000Z
antlisp/lib/varname/namespace.cpp
AKindyakov/antlisp
6a772dbdc728a031b1f8b25f9c7a6f7a168d0177
[ "MIT" ]
null
null
null
antlisp/lib/varname/namespace.cpp
AKindyakov/antlisp
6a772dbdc728a031b1f8b25f9c7a6f7a168d0177
[ "MIT" ]
null
null
null
#include "namespace.h" namespace AntLisp { template<> std::string CellType<NamespacePtr>::toString() const { return value_->toString(); } template<> ICellType::Ptr CellType<NamespacePtr>::copy() const { return std::make_unique<CellType<NamespacePtr>>( std::make_shared<Namespace>(value_->copy()) ); } /** * Depricated, for backward compatiblity * Use set() instead */ void Namespace::emplace(const VarName& name, Cell cell) { set(name, std::move(cell)); } /** * Depricated, for backward compatiblity * Use set() instead */ void Namespace::insert(const VarName& name, Cell cell) { set(name, std::move(cell)); } void Namespace::set(const VarName& name, Cell cell) { auto it = table_.find(name); if (it == table_.end()) { table_.emplace(name, std::move(cell)); } else { it->second = std::move(cell); } } /** * Depricated, for backward compatiblity * Use get() instead */ Cell const& Namespace::at(const VarName& name) { return get(name); } Cell const& Namespace::get(const VarName& name) const { return get( VarNamePrefix(name) ); } Cell const& Namespace::get(VarNamePrefix prefix) const { auto const it = table_.find( prefix.firstName() ); if (it == table_.end()) { throw Error() << "No such suffix " << Str::Quotes(prefix.fullName()) << " in namespace"; } if (not prefix.isComplex()) { return it->second; } if (not it->second.is<NamespacePtr>()) { throw Error() << "Look up in the namespace for suffix " << Str::Quotes(prefix.fullName()) << "failed: Cell is not a namespace"; } return it->second.as<NamespacePtr>()->get(prefix.next()); } bool Namespace::has(const VarName& name) const { return table_.find(name) != table_.end(); } void Namespace::remove(const VarName& name) { table_.erase(name); } Namespace Namespace::copy() const { auto newNamespace = Namespace{}; for (const auto& var : table_) { newNamespace.emplace(var.first, var.second.copy()); } return newNamespace; } void Namespace::update(const Namespace& other) { for (const auto& var : other.table_) { set(var.first, var.second.copy()); } } std::string Namespace::toString() const { auto str = std::string{}; for (const auto& var : table_) { str.append(" {"); str.append(var.first); str.push_back(' '); if (var.second.is<FunctionPtr>()) { str.append("<function>"); } else { str.append( var.second.toString() ); } str.append("}\n"); } return str; } } // namespace AntLisp {
23.142857
61
0.585694
akindyakov
ec5339b8dcb83ec1b7314dcfab4522e89693a4d7
3,222
hh
C++
dune/gdt/operators/fv/datahandle.hh
tobiasleibner/dune-gdt
5d3dc6c7f5fd66db78ebb294d7ee4803f8e0bf5b
[ "BSD-2-Clause" ]
null
null
null
dune/gdt/operators/fv/datahandle.hh
tobiasleibner/dune-gdt
5d3dc6c7f5fd66db78ebb294d7ee4803f8e0bf5b
[ "BSD-2-Clause" ]
null
null
null
dune/gdt/operators/fv/datahandle.hh
tobiasleibner/dune-gdt
5d3dc6c7f5fd66db78ebb294d7ee4803f8e0bf5b
[ "BSD-2-Clause" ]
null
null
null
#ifndef DUNE_GDT_OPERATORS_FV_DATAHANDLE_HH #define DUNE_GDT_OPERATORS_FV_DATAHANDLE_HH #include <dune/grid/common/datahandleif.hh> namespace Dune { namespace GDT { template <class ReconstructedValuesType, class GridLayerType> class ReconstructionDataHandle : public Dune::CommDataHandleIF<ReconstructionDataHandle<ReconstructedValuesType, GridLayerType>, typename ReconstructedValuesType::value_type::mapped_type::value_type> { typedef typename ReconstructedValuesType::value_type::mapped_type RangeType; public: ReconstructionDataHandle(ReconstructedValuesType& reconstructed_values, const GridLayerType& grid_layer) : reconstructed_values_(reconstructed_values) , grid_layer_(grid_layer) { } //! export type of data for message buffer typedef typename RangeType::value_type DataType; //! returns true if data for this codim should be communicated bool contains(int /*dim*/, int codim) const { return (codim == 0); } //! returns true if size per entity of given dim and codim is a constant bool fixedsize(int /*dim*/, int /*codim*/) const { return true; } /*! how many objects of type DataType have to be sent for a given entity Note: Only the sender side needs to know this size. */ template <class EntityType> std::enable_if_t<EntityType::codimension != 0, size_t> size(const EntityType& /*entity*/) const { return 0; } /*! how many objects of type DataType have to be sent for a given entity Note: Only the sender side needs to know this size. */ template <class EntityType> std::enable_if_t<EntityType::codimension == 0, size_t> size(const EntityType& entity) const { return reconstructed_values_[grid_layer_.indexSet().index(entity)].size() * RangeType::dimension; } //! pack data from user to message buffer template <class MessageBuffer, class EntityType> std::enable_if_t<EntityType::codimension != 0> gather(MessageBuffer& /*buff*/, const EntityType& /*entity*/) const { } template <class MessageBuffer, class EntityType> std::enable_if_t<EntityType::codimension == 0> gather(MessageBuffer& buff, const EntityType& entity) const { for (const auto& pair : reconstructed_values_[grid_layer_.indexSet().index(entity)]) for (size_t rr = 0; rr < RangeType::dimension; ++rr) buff.write(pair.second[rr]); } /*! unpack data from message buffer to user n is the number of objects sent by the sender */ template <class MessageBuffer, class EntityType> std::enable_if_t<EntityType::codimension != 0> scatter(MessageBuffer& /*buff*/, const EntityType& /*entity*/, size_t /*n*/) { } template <class MessageBuffer, class EntityType> std::enable_if_t<EntityType::codimension == 0> scatter(MessageBuffer& buff, const EntityType& entity, size_t /*n*/) { for (auto& pair : reconstructed_values_[grid_layer_.indexSet().index(entity)]) for (size_t rr = 0; rr < RangeType::dimension; ++rr) buff.read(pair.second[rr]); } private: ReconstructedValuesType& reconstructed_values_; const GridLayerType& grid_layer_; }; } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_FV_DATAHANDLE_HH
32.545455
117
0.721912
tobiasleibner
ec6539e12caf317522e6677366ccf003bd175302
768
hpp
C++
src/config/interfaces.hpp
project-trident/pc-firewall
ef08c96faff5bdb4b1d3c2341f35a65587512fba
[ "BSD-2-Clause" ]
1
2019-12-10T03:51:34.000Z
2019-12-10T03:51:34.000Z
src/config/interfaces.hpp
project-trident/pc-firewall
ef08c96faff5bdb4b1d3c2341f35a65587512fba
[ "BSD-2-Clause" ]
null
null
null
src/config/interfaces.hpp
project-trident/pc-firewall
ef08c96faff5bdb4b1d3c2341f35a65587512fba
[ "BSD-2-Clause" ]
null
null
null
#ifndef __INTERFACES_H #define __INTERFACES_H #include <qstring.h> #include <qprocess.h> #include <vector> class interfaces : public QObject { Q_OBJECT private: static interfaces *_instance; std::vector<QString> _ifs; interfaces ( void ); ~interfaces ( void ); void load ( void ); public: typedef std::vector<QString>::const_iterator ifs_cit; typedef std::vector<QString>::iterator ifs_it; inline static interfaces* getInstance ( void ) { if ( _instance == 0 ) { _instance = new interfaces; _instance->load(); } return _instance; } inline const std::vector<QString>& ifs ( void ) const { return _ifs; } }; #endif
16
57
0.588542
project-trident
ec6623be162a0cb7eb42868bfb90c0a02b0aaa30
3,734
cpp
C++
webots_ros2_driver/src/plugins/static/Ros2RangeFinder.cpp
TaoYibo1866/webots_ros2
a72c164825663cebbfd27e0649ea51d3abf9bbed
[ "Apache-2.0" ]
176
2019-09-06T07:02:05.000Z
2022-03-27T12:41:10.000Z
webots_ros2_driver/src/plugins/static/Ros2RangeFinder.cpp
harshag37/webots_ros2
08a061e73e3b88d57cc27b662be0f907d8b9f15b
[ "Apache-2.0" ]
308
2019-08-20T12:56:23.000Z
2022-03-29T09:49:22.000Z
webots_ros2_driver/src/plugins/static/Ros2RangeFinder.cpp
harshag37/webots_ros2
08a061e73e3b88d57cc27b662be0f907d8b9f15b
[ "Apache-2.0" ]
67
2019-11-03T00:58:09.000Z
2022-03-18T07:11:28.000Z
// Copyright 1996-2021 Cyberbotics Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <webots_ros2_driver/plugins/static/Ros2RangeFinder.hpp> #include <sensor_msgs/image_encodings.hpp> #include <std_msgs/msg/color_rgba.hpp> namespace webots_ros2_driver { void Ros2RangeFinder::init(webots_ros2_driver::WebotsNode *node, std::unordered_map<std::string, std::string> &parameters) { Ros2SensorPlugin::init(node, parameters); mIsEnabled = false; mRangeFinder = mNode->robot()->getRangeFinder(parameters["name"]); assert(mRangeFinder != NULL); // Image publisher mImagePublisher = mNode->create_publisher<sensor_msgs::msg::Image>(mTopicName, rclcpp::SensorDataQoS().reliable()); mImageMessage.header.frame_id = mFrameName; mImageMessage.height = mRangeFinder->getHeight(); mImageMessage.width = mRangeFinder->getWidth(); mImageMessage.is_bigendian = false; mImageMessage.step = sizeof(unsigned char) * 4 * mRangeFinder->getWidth(); mImageMessage.data.resize(4 * mRangeFinder->getWidth() * mRangeFinder->getHeight()); mImageMessage.encoding = sensor_msgs::image_encodings::TYPE_32FC1; // CameraInfo publisher rclcpp::QoS cameraInfoQos(1); cameraInfoQos.reliable(); cameraInfoQos.transient_local(); cameraInfoQos.keep_last(1); mCameraInfoPublisher = mNode->create_publisher<sensor_msgs::msg::CameraInfo>(mTopicName + "/camera_info", cameraInfoQos); mCameraInfoMessage.header.stamp = mNode->get_clock()->now(); mCameraInfoMessage.header.frame_id = mFrameName; mCameraInfoMessage.height = mRangeFinder->getHeight(); mCameraInfoMessage.width = mRangeFinder->getWidth(); mCameraInfoMessage.distortion_model = "plumb_bob"; const double focalLength = 570.34; mCameraInfoMessage.d = {0.0, 0.0, 0.0, 0.0, 0.0}; mCameraInfoMessage.r = {1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0}; mCameraInfoMessage.k = { focalLength, 0.0, (double)mRangeFinder->getWidth() / 2, 0.0, focalLength, (double)mRangeFinder->getHeight() / 2, 0.0, 0.0, 1.0}; mCameraInfoMessage.p = { focalLength, 0.0, (double)mRangeFinder->getWidth() / 2, 0.0, 0.0, focalLength, (double)mRangeFinder->getHeight() / 2, 0.0, 0.0, 0.0, 1.0, 0.0}; mCameraInfoPublisher->publish(mCameraInfoMessage); if (mAlwaysOn) { mRangeFinder->enable(mPublishTimestepSyncedMs); mIsEnabled = true; } } void Ros2RangeFinder::step() { if (!preStep()) return; if (mIsEnabled) publishImage(); if (mAlwaysOn) return; // Enable/Disable sensor const bool shouldBeEnabled = mImagePublisher->get_subscription_count() > 0; if (shouldBeEnabled != mIsEnabled) { if (shouldBeEnabled) mRangeFinder->enable(mPublishTimestepSyncedMs); else mRangeFinder->disable(); mIsEnabled = shouldBeEnabled; } } void Ros2RangeFinder::publishImage() { auto image = mRangeFinder->getRangeImage(); if (image) { mImageMessage.header.stamp = mNode->get_clock()->now(); memcpy(mImageMessage.data.data(), image, mImageMessage.data.size()); mImagePublisher->publish(mImageMessage); } } }
35.903846
125
0.695233
TaoYibo1866
ec6637767355450fbd22575fca82b14fbff35b7d
16,830
cpp
C++
FELICITY/Static_Codes/AHF/Unit_Test_src/test_2d_manifold_mesh_1.cpp
brianchowlab/BcLOV4-FEM
f54bd8efa0e0f2c7ca2de4a6688ef1a403376285
[ "MIT" ]
null
null
null
FELICITY/Static_Codes/AHF/Unit_Test_src/test_2d_manifold_mesh_1.cpp
brianchowlab/BcLOV4-FEM
f54bd8efa0e0f2c7ca2de4a6688ef1a403376285
[ "MIT" ]
null
null
null
FELICITY/Static_Codes/AHF/Unit_Test_src/test_2d_manifold_mesh_1.cpp
brianchowlab/BcLOV4-FEM
f54bd8efa0e0f2c7ca2de4a6688ef1a403376285
[ "MIT" ]
null
null
null
/* ============================================================================================ This is a unit test for the AHF data structure implementation. This example stores a 2-D manifold mesh (consisting of 4 triangles) that has 0 non-manifold edges and 0 non-manifold vertices. It also does some basic processing. See 'Manifold_Triangle_Mesh_1.jpg' for a picture of the mesh embedded in 2-D. Copyright (c) 05-21-2020, Shawn W. Walker ============================================================================================ */ #include <TypedefMeshes.h> using namespace std; // unit test int main() { // init output code int OUTPUT_CODE = 0; // 0 indicates success, > 0 is failure // create the object: manifold 2-D mesh example BasePtCoord<2> VX; TriMesh(TM,VX); //Mesh<2,2> TM(&VX); // alternative // define the cell connectivity TM.Reserve_Cells(4); TM.Append_Cell(0,1,4); TM.Append_Cell(1,2,4); TM.Append_Cell(2,3,4); TM.Append_Cell(3,0,4); // now add the vertex point coordinates VX.Init_Points(5); VX.Set_Coord(0, 0.0,0.0); VX.Set_Coord(1, 1.0,0.0); VX.Set_Coord(2, 1.0,1.0); VX.Set_Coord(3, 0.0,1.0); VX.Set_Coord(4, 0.5,0.5); // now display coordinates cout << endl; VX.Display_Vtx_Coord(); // we now stop adding cells and coordinates TM.Finalize_v2hfs_DEBUG(); // now display the half-facets (attached to vertices) of the intermediate structure 'v2hfs' cout << endl; TM.Display_v2hfs(); // check 'v2hfs' against reference data VtxHalfFacetType v2hfs_REF[12]; v2hfs_REF[ 0].Set(1,0,2); v2hfs_REF[ 1].Set(2,1,2); v2hfs_REF[ 2].Set(3,2,2); v2hfs_REF[ 3].Set(3,3,2); v2hfs_REF[ 4].Set(4,0,0); v2hfs_REF[ 5].Set(4,0,1); v2hfs_REF[ 6].Set(4,1,0); v2hfs_REF[ 7].Set(4,1,1); v2hfs_REF[ 8].Set(4,2,0); v2hfs_REF[ 9].Set(4,2,1); v2hfs_REF[10].Set(4,3,0); v2hfs_REF[11].Set(4,3,1); // error check const Vtx2HalfFacet_Mapping& c_V2HF_Map = TM.Get_v2hfs(); const std::vector<VtxHalfFacetType>& c_v2hfs = c_V2HF_Map.Get_VtxMap(); for (VtxIndType jj = 0; jj < c_v2hfs.size(); ++jj) if (!c_v2hfs[jj].Equal(v2hfs_REF[jj])) { cout << "Intermediate data 'v2hfs' failed!" << endl; OUTPUT_CODE = 1; break; } // fill out the sibling half-facet data in 'Cell' TM.Build_Sibling_HalfFacets_DEBUG(); // display that cell connectivity data cout << endl; TM.Display_Cell(); cout << endl; // check 'Cell' against reference data CellSimplexType<2> Cell_REF[4]; HalfFacetType hf; // Cell #1 Cell_REF[ 0].Set(0,0,hf.Set(1,1)); Cell_REF[ 0].Set(1,1,hf.Set(3,0)); Cell_REF[ 0].Set(2,4,hf.Set()); // Cell #2 Cell_REF[ 1].Set(0,1,hf.Set(2,1)); Cell_REF[ 1].Set(1,2,hf.Set(0,0)); Cell_REF[ 1].Set(2,4,hf.Set()); // Cell #3 Cell_REF[ 2].Set(0,2,hf.Set(3,1)); Cell_REF[ 2].Set(1,3,hf.Set(1,0)); Cell_REF[ 2].Set(2,4,hf.Set()); // Cell #4 Cell_REF[ 3].Set(0,3,hf.Set(0,1)); Cell_REF[ 3].Set(1,0,hf.Set(2,0)); Cell_REF[ 3].Set(2,4,hf.Set()); // error check for (CellIndType cc = 0; cc < TM.Num_Cells(); ++cc) { const VtxIndType* C_vtx = NULL; const HalfFacetType* C_hf = NULL; TM.Get_Cell(cc, C_vtx, C_hf); if (!Cell_REF[cc].Equal(C_vtx, C_hf)) { cout << "Cell connectivity (and sibling half-facets) is incorrect!" << endl; OUTPUT_CODE = 2; break; } } // generate the Vtx2HalfFacets data struct TM.Build_Vtx2HalfFacets_DEBUG(); TM.Close(); // we can close it now, i.e. no more modifications // now display half-facets attached to vertices for final data structure TM.Display_Vtx2HalfFacets(); cout << endl; // check 'Vtx2HalfFacets' against reference data VtxHalfFacetType Vtx2HalfFacets_REF[5]; Vtx2HalfFacets_REF[ 0].Set( 0,3,2); Vtx2HalfFacets_REF[ 1].Set( 1,1,2); Vtx2HalfFacets_REF[ 2].Set( 2,2,2); Vtx2HalfFacets_REF[ 3].Set( 3,3,2); Vtx2HalfFacets_REF[ 4].Set( 4,0,0); // error check const std::vector<VtxHalfFacetType>& c_Vtx2HF = TM.Get_Vtx2HalfFacets().Get_VtxMap(); for (VtxIndType jj = 0; jj < c_Vtx2HF.size(); ++jj) { if (!c_Vtx2HF[jj].Equal(Vtx2HalfFacets_REF[jj])) { cout << "'Vtx2HalfFacets' data is incorrect!" << endl; OUTPUT_CODE = 3; break; } } // display cells attached to a vertex VtxIndType V_IN = 2; TM.Display_Cells_Attached_To_Vertex(V_IN); cout << endl; // check attached cells against reference data std::vector<CellIndType> cell_ind_1; TM.Get_Cells_Attached_To_Vertex(V_IN, 2, cell_ind_1); const CellIndType cell_ind_1_REF[2] = {2, 1}; for (unsigned int jj = 0; jj < cell_ind_1.size(); ++jj) if (cell_ind_1[jj]!=cell_ind_1_REF[jj]) { cout << "Cell attachment data is incorrect!" << endl; OUTPUT_CODE = 4; break; } // display if two cells are facet connected const VtxIndType V1 = 1; const CellIndType C1 = 0; const CellIndType C2 = 1; TM.Display_Two_Cells_Are_Facet_Connected(V1, C1, C2); cout << endl; // check facet connected cells against reference data const bool CHK_Facet_Connected = TM.Two_Cells_Are_Facet_Connected(V1, C1, C2); const bool CHK_Facet_Connected_REF = true; if (CHK_Facet_Connected!=CHK_Facet_Connected_REF) { cout << "Facet connected cell data is incorrect!" << endl; OUTPUT_CODE = 5; } // display half-facets attached to given half-facet HalfFacetType TEST_attached; TEST_attached.Set(3,1); TM.Display_HalfFacets_Attached_To_HalfFacet(TEST_attached); cout << endl; // check attached half-facets against reference data HalfFacetType attached_REF[2]; attached_REF[0].Set(3,1); attached_REF[1].Set(2,0); std::vector<HalfFacetType> attached; TM.Get_HalfFacets_Attached_To_HalfFacet(TEST_attached, attached); for (unsigned int jj = 0; jj < attached.size(); ++jj) if (!attached[jj].Equal(attached_REF[jj])) { cout << "HalfFacet attachment data is incorrect!" << endl; OUTPUT_CODE = 6; break; } // check that half-facet has no neighbor TEST_attached.Set(2,2); TM.Get_HalfFacets_Attached_To_HalfFacet(TEST_attached, attached); if (attached.size()!=1) { cout << "HalfFacet attachment data is incorrect!" << endl; OUTPUT_CODE = 7; } else if (!TEST_attached.Equal(attached[0])) { cout << "HalfFacet attachment should only include the initial given half-facet..." << endl; cout << " but it does not!" << endl; OUTPUT_CODE = 8; } // display non-manifold facets (edges) TM.Display_Nonmanifold_HalfFacets(); cout << endl; // check non-manifold facets (edges) against reference data std::vector<HalfFacetType> non_manifold_hf; TM.Get_Nonmanifold_HalfFacets(non_manifold_hf); if (non_manifold_hf.size()!=0) { cout << "Non-manifold facet data is incorrect!" << endl; OUTPUT_CODE = 9; } // display non-manifold vertices TM.Display_Nonmanifold_Vertices(); cout << endl; // check non-manifold vertices against reference data std::vector<VtxIndType> non_manifold_vtx; TM.Get_Nonmanifold_Vertices(non_manifold_vtx); if (non_manifold_vtx.size()!=0) { cout << "Non-manifold vertex data is incorrect!" << endl; OUTPUT_CODE = 10; } TM.Display_Unique_Vertices(); cout << endl; // check unique vertices against reference data std::vector<VtxIndType> uv; TM.Get_Unique_Vertices(uv); const VtxIndType uv_REF[5] = {0, 1, 2, 3, 4}; for (unsigned int jj = 0; jj < uv.size(); ++jj) if (uv[jj]!=uv_REF[jj]) { cout << "Unique vertex data is incorrect!" << endl; OUTPUT_CODE = 11; break; } // display all edges in the mesh std::vector<MeshEdgeType> edges; TM.Get_Edges(edges); cout << "A unique list of edges in the mesh:" << endl; std::vector<MeshEdgeType>::const_iterator it; for (it = edges.begin(); it!=edges.end(); ++it) { cout << "[" << (*it).vtx[0] << ", " << (*it).vtx[1] << "]" << endl; } cout << endl; // test if a pair of vertices is connected by an edge cout << "Vtx #0 and Vtx #4 are connected." << endl; if (!TM.Is_Connected(0, 4)) { cout << "Incorrect! They are NOT connected!" << endl; OUTPUT_CODE = 12; } // test if a pair of vertices is connected by an edge cout << "Vtx #0 and Vtx #2 are NOT connected." << endl; if (TM.Is_Connected(0, 2)) { cout << "Incorrect! They ARE connected!" << endl; OUTPUT_CODE = 13; } cout << endl; // display all cells attached to an edge std::vector<CellIndType> attached_cells; MeshEdgeType EE; EE.Set(1,4); TM.Get_Cells_Attached_To_Edge(EE, attached_cells); cout << "Here are the cell indices of cells attached to the edge [1, 4]:" << endl; std::vector<CellIndType>::const_iterator ic; for (ic = attached_cells.begin(); ic!=attached_cells.end(); ++ic) cout << "Cell #" << (*ic) << endl; cout << endl; // display the free boundary std::vector<HalfFacetType> free_bdy; TM.Get_FreeBoundary(free_bdy); cout << "Here are the half-facets that lie on the free boundary:" << endl; std::vector<HalfFacetType>::const_iterator hfi; for (hfi = free_bdy.begin(); hfi!=free_bdy.end(); ++hfi) { (*hfi).Print(); cout << endl; } cout << endl; // test: Barycentric_To_Cartesian const CellIndType CI_A[2] = {0, 2}; const PointType PB_in[6] = {(1.0/3.0), (1.0/3.0), (1.0/3.0), 0.2, 0.6, 0.2}; // two sets of barycentric coordinates PointType PC_out[4]; TM.Barycentric_To_Cartesian(2, CI_A, PB_in, PC_out); cout << "These are the two points (from given barycenters):" << endl; for (CellIndType ii = 0; ii < 2; ++ii) cout << "Point (cartesian): (" << PC_out[2*ii + 0] << ", " << PC_out[2*ii + 1] << ")" << endl; const bool PC_CHK = (abs(PC_out[0]-0.5) > 1E-14) || (abs(PC_out[1]-(1.0/6.0)) > 1E-14) || (abs(PC_out[2]-0.3) > 1E-14) || (abs(PC_out[3]-0.9) > 1E-14); if (PC_CHK) { cout << "Incorrect! The two points should be: (0.5, 0.1666667) and (0.3, 0.9)!" << endl; OUTPUT_CODE = 14; } cout << endl; // test: Cartesian_To_Barycentric const CellIndType CI_B[2] = {1, 3}; const PointType PC_in[4] = {0.75, 0.5, 0.2, 0.6}; // two sets of cartesian coordinates PointType PB_out[6]; TM.Cartesian_To_Barycentric(2, CI_B, PC_in, PB_out); cout << "These are the two points (from given cartesian coordinates):" << endl; for (CellIndType ii = 0; ii < 2; ++ii) cout << "Point (barycentric): (" << PB_out[3*ii + 0] << ", " << PB_out[3*ii + 1] << ", " << PB_out[3*ii + 2] << ")" << endl; const bool PB_CHK = (abs(PB_out[0]-0.25) > 1E-14) || (abs(PB_out[1]-0.25) > 1E-14) || (abs(PB_out[2]-0.5) > 1E-14) || (abs(PB_out[3]-0.4) > 1E-14) || (abs(PB_out[4]-0.2) > 1E-14) || (abs(PB_out[5]-0.4) > 1E-14); if (PB_CHK) { cout << "Incorrect! The two points should be: (0.25, 0.25, 0.5) and (0.4, 0.2, 0.4)!" << endl; OUTPUT_CODE = 15; } cout << endl; // test: Circumcenter PointType CB_out[6]; RealType CR_out[2]; TM.Circumcenter(2, CI_A, CB_out, CR_out); cout << "Here are circumcenters and circumradii for cell #s: " << CI_A[0] << " and " << CI_A[1] << ":" << endl; for (CellIndType ii = 0; ii < 2; ++ii) cout << "circumcenter (barycentric): (" << CB_out[3*ii + 0] << ", " << CB_out[3*ii + 1] << ", " << CB_out[3*ii + 2] << ")" << ", circumradius: " << CR_out[ii] << endl; const bool CB_CHK = (abs(CB_out[0]-0.5) > 1E-14) || (abs(CB_out[1]-0.5) > 1E-14) || (abs(CB_out[2]-0.0) > 1E-14) || (abs(CB_out[3]-0.5) > 1E-14) || (abs(CB_out[4]-0.5) > 1E-14) || (abs(CB_out[5]-0.0) > 1E-14) || (abs(CR_out[0]-0.5) > 1E-14) || (abs(CR_out[1]-0.5) > 1E-14); if (CB_CHK) { cout << "Incorrect! The two circumcenters should be: (0.5, 0.5, 0.0) and (0.5, 0.5, 0.0)," << endl; cout << " with a circumradius of 0.5 each!" << endl; OUTPUT_CODE = 16; } cout << endl; // test: incenter PointType IB_out[6]; RealType IR_out[2]; TM.Incenter(2, CI_A, IB_out, IR_out); cout << "Here are incenters and inradii for cell #s: " << CI_A[0] << " and " << CI_A[1] << ":" << endl; for (CellIndType ii = 0; ii < 2; ++ii) cout << "incenter (barycentric): (" << IB_out[3*ii + 0] << ", " << IB_out[3*ii + 1] << ", " << IB_out[3*ii + 2] << ")" << ", inradius: " << IR_out[ii] << endl; const bool IB_CHK = (abs(IB_out[0]-0.292893218813452) > 1E-14) || (abs(IB_out[1]-0.292893218813452) > 1E-14) || (abs(IB_out[2]-0.414213562373095) > 1E-14) || (abs(IB_out[3]-0.292893218813452) > 1E-14) || (abs(IB_out[4]-0.292893218813452) > 1E-14) || (abs(IB_out[5]-0.414213562373095) > 1E-14) || (abs(IR_out[0]-0.207106781186548) > 1E-14) || (abs(IR_out[1]-0.207106781186548) > 1E-14); if (IB_CHK) { cout << "Incorrect! The two incenters should be (both): ( (1/sqrt(2))/(1+sqrt(2)), (1/sqrt(2))/(1+sqrt(2)), 1/(1+sqrt(2)))," << endl; cout << " with an inradius of (1/2) / (1+sqrt(2)) for both!" << endl; OUTPUT_CODE = 17; } cout << endl; // test: diameter const CellIndType CI_all[4] = {0, 1, 2, 3}; RealType Diam_out[4]; TM.Diameter(4, CI_all, Diam_out); cout << "Here are the diameters for these cells: " << endl; for (CellIndType ii = 0; ii < 4; ++ii) cout << "Cell #" << CI_all[ii] << ", Diameter: " << Diam_out[ii] << endl; const bool DIAM_CHK = (abs(Diam_out[0]-1.0) > 1E-14) || (abs(Diam_out[1]-1.0) > 1E-14) || (abs(Diam_out[2]-1.0) > 1E-14) || (abs(Diam_out[3]-1.0) > 1E-14); if (DIAM_CHK) { cout << "Incorrect! The diameters should be 1.0 for all." << endl; OUTPUT_CODE = 18; } cout << endl; // test: volume RealType Vol_out[4]; TM.Volume(4, CI_all, Vol_out); cout << "Here are the 2-volumes (areas) for these cells: " << endl; for (CellIndType ii = 0; ii < 4; ++ii) cout << "Cell #" << CI_all[ii] << ", Volume: " << Vol_out[ii] << endl; const bool VOL_CHK = (abs(Vol_out[0]-0.25) > 1E-14) || (abs(Vol_out[1]-0.25) > 1E-14) || (abs(Vol_out[2]-0.25) > 1E-14) || (abs(Vol_out[3]-0.25) > 1E-14); if (VOL_CHK) { cout << "Incorrect! The volumes (areas) should be 0.25 for all." << endl; OUTPUT_CODE = 19; } cout << endl; // test: shape regularity RealType SR_out[4]; TM.Shape_Regularity(4, CI_all, SR_out); cout << "Here are the shape regularity ratios for these cells: " << endl; for (CellIndType ii = 0; ii < 4; ++ii) cout << "Cell #" << CI_all[ii] << ", SR: " << SR_out[ii] << endl; const bool SR_CHK = (abs(SR_out[0]-2.4142135623730950488) > 1E-14) || (abs(SR_out[1]-2.4142135623730950488) > 1E-14) || (abs(SR_out[2]-2.4142135623730950488) > 1E-14) || (abs(SR_out[3]-2.4142135623730950488) > 1E-14); if (SR_CHK) { cout << "Incorrect! The shape regularity ratios should be ~2.41421356 for all." << endl; OUTPUT_CODE = 20; } cout << endl; // test: bounding box PointType BB_min[2]; PointType BB_max[2]; TM.Bounding_Box(4, CI_all, BB_min, BB_max); cout << "Here is the bounding box of the mesh: " << endl; cout << " BB_min = {" << BB_min[0] << ", " << BB_min[1] << "}," << endl; cout << " BB_max = {" << BB_max[0] << ", " << BB_max[1] << "}." << endl; const bool BB_CHK = (abs(BB_min[0]-0.0) > 1E-14) || (abs(BB_min[1]-0.0) > 1E-14) || (abs(BB_max[0]-1.0) > 1E-14) || (abs(BB_max[1]-1.0) > 1E-14); if (BB_CHK) { cout << "Incorrect! The bounding box should be {0.0, 0.0} to {1.0, 1.0}." << endl; OUTPUT_CODE = 21; } cout << endl; if (OUTPUT_CODE==0) cout << "Unit test is successful!" << endl; else cout << "Unit test failed!" << endl; cout << endl; return OUTPUT_CODE; } /***/
36.907895
142
0.563755
brianchowlab
ec6648f334fd04b8a9546bc823dd96c82f67ef6f
124
cpp
C++
src/VulkanLoader.cpp
FelixFifi/rtx-pathtracer
9bf5616c47880e8fa536a822b39b9661bb666352
[ "Zlib", "Apache-2.0", "MIT" ]
5
2021-04-18T15:49:10.000Z
2021-09-15T10:23:44.000Z
src/VulkanLoader.cpp
FelixFifi/rtx-pathtracer
9bf5616c47880e8fa536a822b39b9661bb666352
[ "Zlib", "Apache-2.0", "MIT" ]
1
2021-12-27T12:11:53.000Z
2021-12-27T12:11:53.000Z
src/VulkanLoader.cpp
FelixFifi/rtx-pathtracer
9bf5616c47880e8fa536a822b39b9661bb666352
[ "Zlib", "Apache-2.0", "MIT" ]
2
2021-06-18T12:27:36.000Z
2021-12-26T22:06:44.000Z
// // Created by felixfifi on 05.05.20. // #include "VulkanLoader.h" VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE;
13.777778
51
0.774194
FelixFifi
ec68903e3137a902726a37dfffaec14a2b6e0217
5,086
cpp
C++
TetrisEngine/srcLib/block.cpp
mwthinker/MWetris
8d7d75cade1eb44567e182b569ebf5af16b522d7
[ "MIT" ]
null
null
null
TetrisEngine/srcLib/block.cpp
mwthinker/MWetris
8d7d75cade1eb44567e182b569ebf5af16b522d7
[ "MIT" ]
null
null
null
TetrisEngine/srcLib/block.cpp
mwthinker/MWetris
8d7d75cade1eb44567e182b569ebf5af16b522d7
[ "MIT" ]
null
null
null
#include "block.h" #include <algorithm> namespace tetris { Block::Block(BlockType blockType, int startColumn, int lowestStartRow, int currentRotation) : Block{blockType, startColumn, lowestStartRow} { for (int i = 0; i < currentRotation; ++i) { rotateLeft(); } } Block::Block(BlockType blockType, int startColumn, int lowestStartRow) : blockType_{blockType} , startColumn_{startColumn} , lowestStartRow_{lowestStartRow} { int nbrOfSquares = 0; switch (blockType) { case BlockType::Empty: maxRotations_ = 0; squares_[nbrOfSquares++] = Square{0, 0}; squares_[nbrOfSquares++] = Square{0, 0}; squares_[nbrOfSquares++] = Square{0, 0}; squares_[nbrOfSquares++] = Square{0, 0}; break; case BlockType::I: squares_[nbrOfSquares++] = Square{startColumn, lowestStartRow_ + 3}; squares_[nbrOfSquares++] = Square{startColumn, lowestStartRow_ + 2}; rotationSquareIndex_ = nbrOfSquares; squares_[nbrOfSquares++] = Square{startColumn, lowestStartRow_ + 1}; squares_[nbrOfSquares++] = Square{startColumn, lowestStartRow_}; maxRotations_ = 1; break; case BlockType::J: squares_[nbrOfSquares++] = Square{startColumn + 1, lowestStartRow_ + 2}; rotationSquareIndex_ = nbrOfSquares; squares_[nbrOfSquares++] = Square{startColumn + 1, lowestStartRow_ + 1}; squares_[nbrOfSquares++] = Square{startColumn + 1, lowestStartRow_}; squares_[nbrOfSquares++] = Square{startColumn, lowestStartRow_}; break; case BlockType::L: squares_[nbrOfSquares++] = Square{startColumn, lowestStartRow_ + 2}; rotationSquareIndex_ = nbrOfSquares; squares_[nbrOfSquares++] = Square{startColumn, lowestStartRow_ + 1}; squares_[nbrOfSquares++] = Square{startColumn, lowestStartRow_}; squares_[nbrOfSquares++] = Square{startColumn + 1, lowestStartRow_}; break; case BlockType::O: squares_[nbrOfSquares++] = Square{startColumn, lowestStartRow_ + 1}; squares_[nbrOfSquares++] = Square{startColumn + 1, lowestStartRow_ + 1}; squares_[nbrOfSquares++] = Square{startColumn, lowestStartRow_}; squares_[nbrOfSquares++] = Square{startColumn + 1, lowestStartRow_}; maxRotations_ = 0; break; case BlockType::S: squares_[nbrOfSquares++] = Square{startColumn + 1, lowestStartRow_ + 1}; squares_[nbrOfSquares++] = Square{startColumn, lowestStartRow_ + 1}; rotationSquareIndex_ = nbrOfSquares; squares_[nbrOfSquares++] = Square{startColumn, lowestStartRow_}; squares_[nbrOfSquares++] = Square{startColumn - 1, lowestStartRow_}; maxRotations_ = 1; break; case BlockType::T: squares_[nbrOfSquares++] = Square{startColumn, lowestStartRow_ + 1}; squares_[nbrOfSquares++] = Square{startColumn + 1, lowestStartRow_}; rotationSquareIndex_ = nbrOfSquares; squares_[nbrOfSquares++] = Square{startColumn, lowestStartRow_}; squares_[nbrOfSquares++] = Square{startColumn - 1, lowestStartRow_}; break; case BlockType::Z: squares_[nbrOfSquares++] = Square{startColumn - 1, lowestStartRow_ + 1}; squares_[nbrOfSquares++] = Square{startColumn, lowestStartRow_ + 1}; rotationSquareIndex_ = nbrOfSquares; squares_[nbrOfSquares++] = Square{startColumn, lowestStartRow_}; squares_[nbrOfSquares++] = Square{startColumn + 1, lowestStartRow_}; maxRotations_ = 1; break; } } void Block::moveLeft() { --startColumn_; for (auto& sq : squares_) { --sq.column; } } void Block::moveRight() { ++startColumn_; for (auto& sq : squares_) { ++sq.column; } } void Block::moveDown() { --lowestStartRow_; for (auto& sq : squares_) { --sq.row; } } void Block::rotate(int rotate) { int row = squares_[rotationSquareIndex_].row; int column = squares_[rotationSquareIndex_].column; if (rotate > 0) { // Rotate left. for (int i = 0; i < rotate; ++i) { for (auto& sq : squares_) { auto tmp = sq; tmp.column = column + row - sq.row; tmp.row = sq.column + row - column; sq = tmp; } } } else { rotate *= -1; for (int i = 0; i < rotate; ++i) { // Rotate right. for (Square& sq : squares_) { Square tmp = sq; tmp.column = sq.row + column - row; tmp.row = column + row - sq.column; sq = tmp; } } } } void Block::rotateLeft() { int row = squares_[rotationSquareIndex_].row; int column = squares_[rotationSquareIndex_].column; currentRotation_ = (currentRotation_ + 1) % 4; // Rotate back to start orientation? if (currentRotation_ > maxRotations_) { currentRotation_ = 0; // Rotate right in order to get back to default orientation. rotate(-maxRotations_); } else { // Rotate to the left! rotate(1); } } void Block::rotateRight() { int row = squares_[rotationSquareIndex_].row; int column = squares_[rotationSquareIndex_].column; currentRotation_ = (currentRotation_ + 3) % 4; // Rotate back to start orientation? if (currentRotation_ > maxRotations_) { currentRotation_ = 0; rotate(maxRotations_); } else { // Rotate to the right! rotate(-1); } } }
30.824242
92
0.673024
mwthinker
ec6a25261804308c2c3e4ecefbc27d0b5f4b267d
9,199
cpp
C++
Actor/Characters/Enemy/E3/EnemyE3.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
Actor/Characters/Enemy/E3/EnemyE3.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
Actor/Characters/Enemy/E3/EnemyE3.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "EnemyE3.h" #include "Libraries/Components/AnimationMng/Cpt_AnimationMng.h" #include "Kismet/KismetMathLibrary.h" #include "Actor/Characters/Player/GBox/GBox.h" #include "Libraries/Components/MaterialEffect/Cpt_MaterialEffect.h" #include "Libraries/Components/ParticleMng/Cpt_ParticleMng.h" #include "Libraries/Components/SoundMng/Cpt_SoundMng.h" #include "Libraries/Components/CamShake/Cpt_CamShake.h" #include "Actor/Props/FootPush/Cpt_FootPushLine.h" #include "UI/Enemy/NHpSystem/Cpt_EnemyHpComponent.h" #include "AnimInst_EnemyE3.h" #include "State/StateMng_EnemyE3.h" #include "AIC_EnemyE3.h" #include "Libraries/Components/WarningSpace/Cpt_WarningSpace.h" #include "Instance/GameInst_JoyContinue.h" AEnemyE3::AEnemyE3() { PrimaryActorTick.bCanEverTick = true; Tags.Add(FName("Enemy")); Tags.Add(FName("Enemy_Close")); SetGenericTeamId(FGenericTeamId(1)); bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; GetCharacterMovement()->bOrientRotationToMovement = true; GetCharacterMovement()->MaxWalkSpeed = 600.0f; GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); m_pAnimationMng = CreateDefaultSubobject<UCpt_AnimationMng>(TEXT("AnimMngComponent")); m_pAnimationMng->SetAnimList(TEXT("/Game/1_Project_Main/1_Blueprints/Actor/Characters/Enemy/EnemyE3/BP_AnimList_E3.BP_AnimList_E3_C")); static ConstructorHelpers::FClassFinder<UAnimInstance> Const_AnimInst(TEXT("/Game/1_Project_Main/2_Contents/Actors/Enemy/E3/Animation/BP_Anim_E3.BP_Anim_E3_C")); if (Const_AnimInst.Succeeded()) GetMesh()->SetAnimInstanceClass(Const_AnimInst.Class); static ConstructorHelpers::FClassFinder<AAIC_EnemyE3> Const_AIC(TEXT("/Game/1_Project_Main/1_Blueprints/Actor/Characters/Enemy/EnemyE3/BP_AIC_EnemyE3.BP_AIC_EnemyE3_C")); if (Const_AIC.Succeeded()) AIControllerClass = Const_AIC.Class; m_pMaterialEffect = CreateDefaultSubobject<UCpt_MaterialEffect>(TEXT("MaterialEffect")); m_pParticleMng = CreateDefaultSubobject<UCpt_ParticleMng>(TEXT("ParticleMng")); m_pParticleMng->AddParticleInstance(TEXT("Hit"), TEXT("ParticleSystem'/Game/1_Project_Main/2_Contents/Effects/HitEffect/V_HitImpact.V_HitImpact'")); m_pParticleMng->AddParticleInstance(TEXT("EyeLight"), TEXT("ParticleSystem'/Game/1_Project_Main/2_Contents/Effects/EyeLight/V_EyeLight.V_EyeLight'")); m_pParticleMng->AddParticleInstance(TEXT("GroundHit"), TEXT("ParticleSystem'/Game/2_Contents/VFX/Mobile_Fantasy_FX/ParticleSystems/P_Thunder_Strike.P_Thunder_Strike'")); m_pParticleMng->AddParticleInstance(TEXT("Smoke"), TEXT("ParticleSystem'/Game/0_Assets/MarketPlace/VFXS/VFX_Toolkit_V1/ParticleSystems/356Days/Par_Smoke.Par_Smoke'")); m_pParticleMng->AddParticleInstance(TEXT("Disint"), TEXT("ParticleSystem'/Game/1_Project_Main/2_Contents/Effects/V_Disint.V_Disint'")); m_pSoundMng = CreateDefaultSubobject<UCpt_SoundMng>(TEXT("SoundMng")); m_pSoundMng->Set_SoundList(TEXT("/Game/1_Project_Main/1_Blueprints/Actor/Characters/Enemy/EnemyE3/BP_SoundList_E3.BP_SoundList_E3_C")); m_pFootPushLine = CreateDefaultSubobject<UCpt_FootPushLine>(TEXT("FootPushLine")); m_pFootPushLine->SetSKMesh(this); m_pFootPushLine->AddBone(TEXT("Bone_Body")); m_pHpHud = CreateDefaultSubobject<UCpt_EnemyHpComponent>(TEXT("EnemyHpCpt")); m_pWarningSpace = CreateDefaultSubobject<UCpt_WarningSpace>(TEXT("WarningSpace")); } void AEnemyE3::PossessedBy(AController* NewController) { Super::PossessedBy(NewController); } void AEnemyE3::PostInitializeComponents() { Super::PostInitializeComponents(); } void AEnemyE3::BeginPlay() { Super::BeginPlay(); GetController()->SetControlRotation(FRotator::ZeroRotator); SetStartLoc(GetActorLocation()); m_fCurrentHp = GetEnemyHp(); GetCharacterMovement()->MaxWalkSpeed = GetEnemySpeed(); if (m_pHpHud != nullptr) { m_pHpHud->CreateHp(m_fCurrentHp); } m_pAnimInstance = Cast<UAnimInst_EnemyE3>(GetMesh()->GetAnimInstance()); if (m_pAnimInstance == nullptr) { ULOG(TEXT("AnimInstance is Nullptr")); return; } m_pAIController = Cast<AAIC_EnemyE3>(GetController()); if (m_pAIController != nullptr) { m_pAIController->InitAI(); } else { ULOG(TEXT("AIController is nullptr")); return; } m_pStateMng = NewObject<UStateMng_EnemyE3>(); if (m_pStateMng != nullptr) { m_pStateMng->Init(this); m_pStateMng->ChangeState(static_cast<int32>(E_State_EnemyE3::E_Spawn)); } else { ULOG(TEXT("StateMng is nullptr")); return; } m_bLife = true; m_pMaterialEffect->Init(GetMesh()); m_pMaterialEffect->AddEffect(E_MaterialEffect::E_Hit2); m_pMaterialEffect->AddEffect(E_MaterialEffect::E_Disint); AddOisEnemy(this, 0); } void AEnemyE3::EndPlay(const EEndPlayReason::Type EndPlayReason) { Super::EndPlay(EndPlayReason); if (m_pStateMng != nullptr) { if (m_pStateMng->IsValidLowLevel()) { m_pStateMng->Destroy(); m_pStateMng = nullptr; } } if (m_pWarningSpace != nullptr) { if (m_pWarningSpace->IsValidLowLevel()) { m_pWarningSpace = nullptr; } } if (m_pFootPushLine != nullptr) { if (m_pFootPushLine->IsValidLowLevel()) { m_pFootPushLine = nullptr; } } if (m_pHpHud != nullptr) { if (m_pHpHud->IsValidLowLevel()) { m_pHpHud = nullptr; } } } void AEnemyE3::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (m_pStateMng != nullptr) m_pStateMng->Update(DeltaTime); if (m_pAnimInstance != nullptr) { m_pAnimInstance->SetStat_Acceleration(GetVelocity().Size()); m_pAnimInstance->SetStat_MovementDirection(m_fMovementDir); } if (m_bHpDestroy == false) { AActor* pPlayer = m_pAIController->DetectInPerceptionDie(); if (pPlayer != nullptr) { AGBox* pTarget = Cast<AGBox>(pPlayer); if (pTarget != nullptr) { if (pTarget->ActorHasTag("PlayerDie")) { //ULOG(TEXT("player is Die")); m_pHpHud->DestroyComponent(); DestroyOsiEnemy(); m_bHpDestroy = true; return; } } } } /*if (GetLife() == false) return; if (m_pHpHud != nullptr ) m_pHpHud->Tick_Transform(GetActorLocation(), DeltaTime); AActor* pPlayer = m_pAIController->DetectInPerception(); if (pPlayer != nullptr) { AGameCharacter* pTarget = Cast<AGameCharacter>(pPlayer); if (pTarget != nullptr) { if (pTarget->GetLife() == false) { m_pHpHud->SetDestroy(); return; } } }*/ } float AEnemyE3::TakeDamage(float DamageAmount, struct FDamageEvent const & DamageEvent, class AController * EventInstigator, AActor * DamageCauser) { float fDamage = Super::TakeDamage(DamageAmount, DamageEvent, EventInstigator, DamageCauser); if (GetLife() == false) return 0.0f; E_DamageEventClass eDamageEventClass = ULib_DamageEvent::GetDamageEventClass(DamageEvent.GetTypeID()); if (fDamage > 0.0f) { if (eDamageEventClass == E_DamageEventClass::E_Hit) { //ULOG(TEXT("Hit")); FDamageEvent_Hit* pBloodDamageEvent = (FDamageEvent_Hit*)&DamageEvent; m_fCurrentHp -= fDamage; if (m_pHpHud != nullptr) { m_pHpHud->Hit(); } bool bIsDead = m_fCurrentHp <= 0 ? true : false; if (bIsDead == true) { Tags.Empty(); Tags.Add("EnemyDie"); SetLife(false); if (m_pHpHud != nullptr) { m_pHpHud->DestroyComponent(); } UState_EnemyE3_Die* pState = Cast<UState_EnemyE3_Die>(m_pStateMng->GetStateClassRef(static_cast<int32>(E_State_EnemyE3::E_Die))); if (pState != nullptr) { //SetRagdollPhysics(pDamageEvent->m_vHitPoint, 10.0f); pState->SetHitDirection(pBloodDamageEvent->m_vAttackerLocaction); m_pStateMng->ChangeState(static_cast<int32>(E_State_EnemyE3::E_Die)); return fDamage; } } UState_EnemyE3_Hit* pState = Cast<UState_EnemyE3_Hit>(m_pStateMng->GetStateClassRef(static_cast<int32>(E_State_EnemyE3::E_Hit))); if (pState != nullptr) { pState->SetHitDirection(pBloodDamageEvent->m_vAttackerLocaction); m_pStateMng->ChangeState(static_cast<int32>(E_State_EnemyE3::E_Hit)); return fDamage; } } else if (eDamageEventClass == E_DamageEventClass::E_Parring) { FDamageEvent_Parring* pBloodDamageEvent = (FDamageEvent_Parring*)&DamageEvent; UState_EnemyE3_Hit* pState = Cast<UState_EnemyE3_Hit>(m_pStateMng->GetStateClassRef(static_cast<int32>(E_State_EnemyE3::E_Hit))); if (pState != nullptr) { pState->SetHitDirection(pBloodDamageEvent->m_vAttackerLocaction); m_pStateMng->ChangeState(static_cast<int32>(E_State_EnemyE3::E_Hit)); return fDamage; } } } return fDamage; } void AEnemyE3::CharacterMessage(FString sMessage) { Super::CharacterMessage(sMessage); if (m_pStateMng != nullptr) m_pStateMng->StateMessage(sMessage); } void AEnemyE3::Inter_Notify_Message_Implementation(FName sMessage) { CharacterMessage(sMessage.ToString()); } bool AEnemyE3::Controll_Attack(class AActor* pActor) { UState_EnemyE3_Attack* pState = Cast<UState_EnemyE3_Attack>(m_pStateMng->GetStateClassRef(static_cast<int32>(E_State_EnemyE3::E_Attack))); if (pState != nullptr) { pState->SetTarget(pActor); m_pStateMng->ChangeState(static_cast<int32>(E_State_EnemyE3::E_Attack)); return true; } return false; }
28.304615
171
0.749973
Bornsoul
ec702cbe9f1d97ef65c883da236fe22cb43b5c07
9,296
cpp
C++
cm-cuda/io.cpp
BeauJoh/HeCBench
594b845171d686dc951971ce36ed59cf114dd2b4
[ "BSD-3-Clause" ]
25
2021-11-01T03:36:10.000Z
2022-03-30T03:07:33.000Z
cm-cuda/io.cpp
BeauJoh/HeCBench
594b845171d686dc951971ce36ed59cf114dd2b4
[ "BSD-3-Clause" ]
1
2021-12-14T11:04:14.000Z
2021-12-14T13:22:32.000Z
cm-cuda/io.cpp
BeauJoh/HeCBench
594b845171d686dc951971ce36ed59cf114dd2b4
[ "BSD-3-Clause" ]
8
2021-11-13T14:28:05.000Z
2022-03-09T10:24:54.000Z
#include "utils.h" //----------------------------------------------------------------------------------- // USER INPUT FUNCTIONS //----------------------------------------------------------------------------------- /* * Prompt the user to input the required number of random gene signatures used to assess significance */ int requestNRandomGenerations() { std::cout << "Please enter the number of random generations required over " << minRandomGenerations << " and under " << maxRandomGenerations << " (default " << defaultRandomGenerations << "): "; int nRandomGenerations = defaultRandomGenerations; std::string inputRG = ""; getline(std::cin, inputRG); std::stringstream StreamRG(inputRG); if (StreamRG >> nRandomGenerations && !(StreamRG >> inputRG)) { if(nRandomGenerations > maxRandomGenerations || nRandomGenerations < minRandomGenerations) { nRandomGenerations = defaultRandomGenerations; std::cout << "Random generations choice out of range - will default to " << nRandomGenerations << std::endl; } std::cin.clear(); } else nRandomGenerations = defaultRandomGenerations; return nRandomGenerations; } /* * Prompt the user to get the required expected number of false positives */ int requestENFP() { std::string inputENFP = ""; std::cout << "Please enter the number expected number of false positives (ENFP) required, limited to "<< maxENFP << " (default " << defaultENFP << ") :"; int ENFPvalue = defaultENFP; getline(std::cin, inputENFP); std::stringstream StreamE(inputENFP); if (StreamE >> ENFPvalue && !(StreamE >> inputENFP)) { if (ENFPvalue > maxENFP || ENFPvalue < 1) { ENFPvalue = defaultENFP; std::cout << "ENFP choice out of range - will default to " << ENFPvalue << std::endl; } std::cin.clear(); } else ENFPvalue = defaultENFP; return ENFPvalue; } /* * Prompt the user to select whether to select compounds by name with/without dose and cell line etc. */ int requestCompoundChoice() { std::cout << "Compound choice 1: Compound" << std::endl; std::cout << "Compound choice 2: Compound and dose" << std::endl; std::cout << "Compound choice 3: Compound, dose and cell line" << std::endl; std::cout << "Compound choice 4: Each profile is individually analysed" << std::endl; std::cout << "Please enter the number the compound choice (1-4) (default 1) :"; std::string inputCC; int compoundChoice = defaultCompoundChoice; getline(std::cin, inputCC); std::stringstream StreamCC(inputCC); if (StreamCC >> compoundChoice && !(StreamCC >> compoundChoice)) { if(compoundChoice > 4 || compoundChoice < 1) { compoundChoice = defaultCompoundChoice; std::cout << "Compound choice out of range - will default to " << compoundChoice << std::endl; } std::cin.clear(); } else compoundChoice = defaultCompoundChoice; return compoundChoice; } //----------------------------------------------------------------------------------- // GENERAL FILE & DIRECTORY FUNCTIONS //----------------------------------------------------------------------------------- /* * Change the current working directory */ int changeToDirectory(const std::string &newPath) { return chdir(newPath.c_str()); } /* * Or Else take the default */ int getCurrentPath(char* buffer) { getcwd(buffer, FILENAME_MAX); return 0; } /* * Change the current working directory to some specified sub-directory off the base */ int changeToSubDirectory(const std::string &basePath, const std::string &subDir) { int success = changeToDirectory(basePath); if (success == 0) return changeToDirectory(subDir); else return success; } /* * Populate a vector containing the names of all the files in a directory that have extensions likely to be useful */ int getFilesInDirectory(const std::string &dir, std::vector<std::string> &files, const std::string &extRequired){ DIR *inputDir; struct dirent *currentFile; // Try to open the directory if((inputDir = opendir(dir.c_str())) == NULL) { std::cout << "Error(" << errno << ") opening " << dir << std::endl; return errno; } // Loop through the files in the directory while ((currentFile = readdir(inputDir)) != NULL) { // Get the file name std::string fName(currentFile->d_name); // We want to ignore current/previous directories, and hidden files starting with '.' if (fName.size() < extRequired.size() || fName[0] == '.') continue; // Extract the final 4 characters std::string ext = fName.substr(fName.size() - extRequired.size()); // If we have a valid extension, add the file name to the vector if (ext.compare(extRequired) == 0) files.push_back(fName); } closedir(inputDir); // Sort the file names std::sort(files.begin(), files.end()); return 0; } //----------------------------------------------------------------------------------- // FILE READING / PARSING FUNCTIONS //----------------------------------------------------------------------------------- /* * Read and decipher a query file, populating the geneNameList and regulationValue vectors (which should have the same length) */ void parseQueryFile(const std::string &queries, std::vector<std::string> &geneNameList, std::vector<int> &regulationValue) { std::string line; std::ifstream inp; inp.open(queries.c_str(), std::ifstream::in); while (getline(inp, line)) { if (line.find("#") == 0 || line.find("AffyProbeSetID") == 0 || line.find("uniqueID") == 0) continue; std::stringstream ss(line); std::string str; int regulationNum = 0; while(ss >> str >> regulationNum) { regulationValue.push_back(regulationNum); geneNameList.push_back(str); } } inp.close(); } /* * Parse a nice string for a drug from a file name */ std::string parseDrugInfoFromFilename(const std::string &fName, const int &compoundChoice) { std::stringstream liness(fName); std::string drug, dose, cellLine, cellNo; getline(liness, drug, separator); getline(liness, dose, separator); getline(liness, cellLine,separator); getline(liness, cellNo, '.'); switch (compoundChoice) { case 2: return drug + "_" + dose; case 3: return drug + "_" + dose + '_' + cellLine; case 4: return drug + "_" + dose + '_' + cellLine + '_' + cellNo; default: return drug; } } /* * Extract the names for all genes within a single .tab file */ void populateRefGeneNameList(const std::string &fName, std::vector<std::string> &refGeneNameList) { std::ifstream inFile(fName.c_str()); // Skip the first line std::string tmp; std::getline(inFile, tmp); // Ensure the vector is cleared refGeneNameList.clear(); // Read and parse the file contents for (int j = 0; j < U133AArrayLength; j++) { // Read the next line into a temporary buffer std::getline(inFile, tmp); // Find the location of the first tab character int tab = tmp.find_first_of("\t"); // Extract the first column as everything in the line up to the first tab refGeneNameList.push_back(tmp.substr(0, tab)); } inFile.close(); } /* * Extract the regulation values for all genes within a single .tab file - * optionally adding them to the existing values, otherwise just replacing anything that was there */ void populateRefRegulationValues(const std::string &fName, int *refRegNum, const bool addToCurrent = false) { std::ifstream inFile(fName.c_str()); // Skip the first line std::string tmp; std::getline(inFile, tmp); // Read and parse the file contents for (int j = 0; j < U133AArrayLength; j++) { // Read the next line into a temporary buffer std::getline(inFile, tmp); // Find the location of the first tab character int tab = tmp.find_first_of("\t"); // Extract an integer from everything after the first tab character, putting the result into the output array // (either adding to what's there or not) if (addToCurrent) refRegNum[j] += std::atoi(tmp.substr(tab).c_str()); else refRegNum[j] = std::atoi(tmp.substr(tab).c_str()); } inFile.close(); } //----------------------------------------------------------------------------------- // OUTPUT FUNCTION //----------------------------------------------------------------------------------- /* * Write the header of the output file, giving some info about the results */ void writeOutputFileHeader(std::ofstream &outdata, const std::string &sigFilename, const int &randomGenerations, const std::vector<std::string> &geneNameList, const std::vector<int> &regNum) { // Provide some meaningful output outdata << "This is the output file for signature: \t " << sigFilename << std::endl; outdata << "The number of random generations to generate the P-value: \t " << randomGenerations << std::endl; outdata << "The array size is for U133A :\t "<< U133AArrayLength << std::endl; outdata << std::endl; outdata << "The signature input was: "<< sigFilename << std::endl; outdata << "The signature length was: "<< geneNameList.size() << std::endl; // Record information about the query for (size_t printSig = 0; printSig < geneNameList.size(); printSig++) outdata << geneNameList[printSig] << "\t "<< regNum[printSig] << std::endl; outdata << std::endl; }
36.3125
196
0.628657
BeauJoh
ec704eb3d4e7c4d02413b4cfdc8e209817f9e314
123
cpp
C++
ExodusImport/Source/ExodusImport/Private/JsonObjects/ResId.cpp
AldeRoberge/ProjectExodus
74ecd6c8719e6365b51458c65954bff2910bc36e
[ "BSD-3-Clause" ]
288
2019-04-02T08:02:59.000Z
2022-03-28T23:53:28.000Z
ExodusImport/Source/ExodusImport/Private/JsonObjects/ResId.cpp
adamgoodrich/ProjectExodus
29a9fa87f981ad41e3b323702dc2b0d4523889d8
[ "BSD-3-Clause" ]
54
2019-04-19T08:24:05.000Z
2022-03-28T19:44:42.000Z
ExodusImport/Source/ExodusImport/Private/JsonObjects/ResId.cpp
adamgoodrich/ProjectExodus
29a9fa87f981ad41e3b323702dc2b0d4523889d8
[ "BSD-3-Clause" ]
56
2019-04-07T03:55:39.000Z
2022-03-20T04:54:57.000Z
#include "JsonImportPrivatePCH.h" #include "ResId.h" uint32 GetTypeHash(const ResId &id){ return (uint32)id.toIndex(); }
17.571429
36
0.739837
AldeRoberge
ec7414dd2224e715efdf6043e6211ea8cedf0687
103
cpp
C++
main.cpp
rtlayzell/math
953bcdbb9d08f9e84df634034bc940989fcf9574
[ "MIT" ]
null
null
null
main.cpp
rtlayzell/math
953bcdbb9d08f9e84df634034bc940989fcf9574
[ "MIT" ]
null
null
null
main.cpp
rtlayzell/math
953bcdbb9d08f9e84df634034bc940989fcf9574
[ "MIT" ]
null
null
null
#include <iostream> #include <vector.hpp> #include <angle.hpp> int main(int, char**) { return 0; }
10.3
23
0.650485
rtlayzell
3f3a77c530db26e2e54b7e71222110a882a1e8f7
5,739
cpp
C++
uart_dma/src/board_pins.cpp
Bergi84/vihaltests
f338e6aff3e389501dc8a018f1dbde862b7971a1
[ "BSD-2-Clause" ]
null
null
null
uart_dma/src/board_pins.cpp
Bergi84/vihaltests
f338e6aff3e389501dc8a018f1dbde862b7971a1
[ "BSD-2-Clause" ]
null
null
null
uart_dma/src/board_pins.cpp
Bergi84/vihaltests
f338e6aff3e389501dc8a018f1dbde862b7971a1
[ "BSD-2-Clause" ]
null
null
null
/* * file: board_pins.cpp (uart_dma) * brief: UART DMA DEMO board specific initializations * version: 1.00 * date: 2021-10-29 * authors: nvitya */ #include "board_pins.h" #include "uartcomm.h" unsigned pin_led_count = 1; TGpioPin pin_led[MAX_LEDS] = { TGpioPin(), TGpioPin(), TGpioPin(), TGpioPin() }; /* NOTE: for direct GPIO pin definitions is simpler to define with port and pin number: TGpioPin pin_mygpio(PORTNUM_C, 13, false); but don't forget to initialize it in the setup code: pin_mygpio.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_0); */ void board_pins_init_leds() { for (unsigned n = 0; n < pin_led_count; ++n) { pin_led[n].Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_0); } } #if 0 // to use elif everywhere //------------------------------------------------------------------------------- // Risc-V (RV32I) //------------------------------------------------------------------------------- //------------------------------------------------------------------------------- // ARM Cortex-M //------------------------------------------------------------------------------- // STM32 #elif defined(BOARD_NUCLEO_F446) || defined(BOARD_NUCLEO_F746) || defined(BOARD_NUCLEO_H743) void board_pins_init() { pin_led_count = 3; pin_led[0].Assign(PORTNUM_B, 0, false); pin_led[1].Assign(PORTNUM_B, 7, false); pin_led[2].Assign(PORTNUM_B, 14, false); board_pins_init_leds(); } bool TUartComm::InitHw() { // USART3: Stlink USB / Serial converter hwpinctrl.PinSetup(PORTNUM_D, 8, PINCFG_OUTPUT | PINCFG_AF_7); // USART3_TX: PD.8 hwpinctrl.PinSetup(PORTNUM_D, 9, PINCFG_INPUT | PINCFG_AF_7); // USART3_RX: Pd.9 uart.Init(3); // USART3 dma_tx.Init(1, 3, 4); // dma1, stream3, ch4 = USART3_TX dma_rx.Init(1, 1, 4); // dma1, stream1, ch4 = USART3_RX return true; } #elif defined(BOARD_MIN_F103) // blue pill void board_pins_init() { pin_led_count = 1; pin_led[0].Assign(PORTNUM_C, 13, false); board_pins_init_leds(); } bool TUartComm::InitHw() { // USART1 hwpinctrl.PinSetup(PORTNUM_A, 9, PINCFG_OUTPUT | PINCFG_AF_0); // USART1_TX // on this older silicon it must be configured as input and no Alternate Function: hwpinctrl.PinSetup(PORTNUM_A, 10, PINCFG_INPUT | PINCFG_PULLUP); // USART1_RX uart.Init(1); // the third parameter is ignored here dma_tx.Init(1, 4, 4); // dma1, ch4 = USART1_TX dma_rx.Init(1, 5, 4); // dma1, ch5 = USART1_RX return true; } #elif defined(BOARD_MIN_F401) || defined(BOARD_MIN_F411) \ || defined(BOARD_MIBO48_STM32F303) \ || defined(BOARD_MIBO64_STM32F405) \ || defined(BOARD_MIBO48_STM32G473) void board_pins_init() { pin_led_count = 1; pin_led[0].Assign(PORTNUM_C, 13, false); board_pins_init_leds(); } bool TUartComm::InitHw() { // USART1 hwpinctrl.PinSetup(PORTNUM_A, 9, PINCFG_OUTPUT | PINCFG_AF_7); // USART1_TX hwpinctrl.PinSetup(PORTNUM_A, 10, PINCFG_INPUT | PINCFG_AF_7 | PINCFG_PULLUP); // USART1_RX uart.Init(1); dma_tx.Init(2, 7, 4); // dma2, stream7, ch4 = USART1_TX dma_rx.Init(2, 5, 4); // dma2, stream5, ch4 = USART1_RX return true; } // ATSAM #elif defined(BOARD_ARDUINO_DUE) void board_pins_init() { pin_led_count = 1; pin_led[0].Assign(PORTNUM_B, 27, false); board_pins_init_leds(); } bool TUartComm::InitHw() { #if 1 // UART - On the Arduino programmer interface hwpinctrl.PinSetup(PORTNUM_A, 8, PINCFG_INPUT | PINCFG_AF_0); // UART_RXD hwpinctrl.PinSetup(PORTNUM_A, 9, PINCFG_OUTPUT | PINCFG_AF_0); // UART_TXD uart.Init(0); // UART // peripheral DMA only! // the dma_rx.Remaining() must be called reqularly in order to work properly // (it is called normally regularly for circular mode) uart.PdmaInit(true, &dma_tx); uart.PdmaInit(false, &dma_rx); #else // USART0 - D18=TX1, D19=RX1 hwpinctrl.PinSetup(PORTNUM_A, 10, PINCFG_INPUT | PINCFG_AF_0); // USART0_RXD hwpinctrl.PinSetup(PORTNUM_A, 11, PINCFG_OUTPUT | PINCFG_AF_0); // USART0_TXD uart.Init(0x100); // USART0 (+ 0x100 = use the USART unit instead of the UART) // DMAC dma_tx.Init(0, 11); // perid: 11 = USART0_TX dma_rx.Init(1, 12); // perid: 12 = USART0_RX #endif return true; } #elif defined(BOARD_XPLAINED_SAME70) void board_pins_init() { pin_led_count = 1; pin_led[0].Assign(PORTNUM_C, 8, false); board_pins_init_leds(); } bool TUartComm::InitHw() { // USART1 - EDBG hwpinctrl.PinSetup(PORTNUM_A, 21, PINCFG_INPUT | PINCFG_AF_0); // USART1_RXD MATRIX->CCFG_SYSIO |= (1 << 4); // select PB4 instead of TDI !!!!!!!!! hwpinctrl.PinSetup(PORTNUM_B, 4, PINCFG_OUTPUT | PINCFG_AF_3); // USART1_TXD uart.Init(0x101); // USART1 (+ 0x100 = use the USART unit instead of the UART) // the DMA channel (first parameter) can be chosen freely dma_tx.Init(0, 9); // perid: 9 = USART1_TX dma_rx.Init(1, 10); // perid: 10 = USART1_RX return true; } #elif defined(BOARD_MIBO64_ATSAME5X) void board_pins_init() { pin_led_count = 1; pin_led[0].Assign(PORTNUM_A, 1, false); board_pins_init_leds(); } bool TUartComm::InitHw() { // SERCOM0 hwpinctrl.PinSetup(PORTNUM_A, 4, PINCFG_OUTPUT | PINCFG_AF_3); // PAD[0] = TX hwpinctrl.PinSetup(PORTNUM_A, 5, PINCFG_INPUT | PINCFG_AF_3); // PAD[1] = RX uart.Init(0); // the DMA channel (first parameter) can be chosen freely // the Trigger sources (second parameter) can be found in the DMA datasheet // at the TRIGSRC[7:0] field definition dma_tx.Init(0, 0x05); // 0x05 = SERCOM0_TX dma_rx.Init(1, 0x04); // 0x04 = SERCOM0_RX return true; } #else #error "Define board_pins_init here" #endif #ifndef HEXNUM_DISPLAY void board_show_hexnum(unsigned ahexnum) { // nothing } #endif
25.171053
96
0.647674
Bergi84
3f4004f424f97a3d13369bb94e178bcc4d403c8b
3,472
cpp
C++
wsettings/wsettingdirs2indexmodel.cpp
privet56/qDesktopSearch
702aac770a11895e19180bd4ed2279c7a8ab64be
[ "Apache-2.0" ]
10
2016-04-15T15:31:08.000Z
2019-10-02T01:19:48.000Z
wsettings/wsettingdirs2indexmodel.cpp
privet56/qDesktopSearch
702aac770a11895e19180bd4ed2279c7a8ab64be
[ "Apache-2.0" ]
null
null
null
wsettings/wsettingdirs2indexmodel.cpp
privet56/qDesktopSearch
702aac770a11895e19180bd4ed2279c7a8ab64be
[ "Apache-2.0" ]
5
2016-04-15T15:31:10.000Z
2022-02-22T02:00:06.000Z
#include "wsettingdirs2indexmodel.h" #include <QBrush> #include <QIcon> #include "globalinclude.h" #include "str.h" /*! * Creates a model object with the given \a ds and \a parent. */ wsettingdirs2indexModel::wsettingdirs2indexModel(QObject *parent) :QAbstractTableModel(parent), m_pLog(nullptr) { } /*! * Destroys the model. */ wsettingdirs2indexModel::~wsettingdirs2indexModel() { } int wsettingdirs2indexModel::rowCount(const QModelIndex &/*parent*/) const { if(!this->m_pLog)return 0; QString sDirs2Index(this->m_pLog->GetCfg()->getValue(DIRS2INDEX)); QStringList sl = sDirs2Index.split('|', QString::SkipEmptyParts); return sl.size(); } int wsettingdirs2indexModel::columnCount(const QModelIndex &/*parent*/) const { return 1; } Qt::ItemFlags wsettingdirs2indexModel::flags(const QModelIndex &index) const { if (!index.isValid()) return Qt::NoItemFlags; return Qt::ItemIsSelectable | Qt::ItemIsEnabled;// | Qt::ItemIsEditable; } QVariant wsettingdirs2indexModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); int iRow = index.row(); int iCol = index.column(); if((role == Qt::DisplayRole) || (role == Qt::ToolTipRole) || (role == Qt::StatusTipRole)) { QString sDirs2Index(this->m_pLog->GetCfg()->getValue(DIRS2INDEX)); QStringList sl = sDirs2Index.split('|', QString::SkipEmptyParts); return sl.at(iRow); } else if (role == Qt::EditRole) { return QVariant(); //should not happen } else if (role == Qt::TextAlignmentRole) { Qt::Alignment align; switch (iCol) { case 0: align |= Qt::AlignJustify; default: align |= Qt::AlignLeft;//Qt::AlignRight,Qt::AlignHCenter,Qt::AlignJustify break; } switch (iCol) { case 0: align |= Qt::AlignVCenter; default: align |= Qt::AlignVCenter;//Qt::AlignRight,Qt::AlignHCenter,Qt::AlignJustify break; } return QVariant(align); } else if (role == Qt::FontRole) { return QVariant(); } else if (role == Qt::ForegroundRole) { return QVariant(); } else if (role == Qt::BackgroundRole) { return QVariant(); } return QVariant(); } QVariant wsettingdirs2indexModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DecorationRole) { if (orientation == Qt::Horizontal) { return QIcon(":/res/indexedDB.png"); } } else if(role == Qt::SizeHintRole) { } else if (role == Qt::DisplayRole) { if (orientation == Qt::Horizontal) { //column headers if(section == 0)return "Directories to be indexed"; } else { //row 'header' return QString::number(section + 1); } } return QVariant(); } bool wsettingdirs2indexModel::setData(const QModelIndex &index, const QVariant &value, int role) { Q_UNUSED(value) if (!index.isValid()) return false; if (role == Qt::EditRole) { //should not happen return false; } return false; } void wsettingdirs2indexModel::setEnv(logger* pLog) { this->m_pLog = pLog; } QModelIndex wsettingdirs2indexModel::buddy(const QModelIndex &index) const { return index; }
22.4
102
0.604263
privet56
3f405cc13394ac4e29dabbf7a5098076e1acde35
5,525
cpp
C++
applications/paint/PaintTool.cpp
busybox11/skift
778ae3a0dc5ac29d7de02200c49d3533e47854c5
[ "MIT" ]
2
2020-07-14T21:16:54.000Z
2020-10-08T08:40:47.000Z
applications/paint/PaintTool.cpp
busybox11/skift
778ae3a0dc5ac29d7de02200c49d3533e47854c5
[ "MIT" ]
null
null
null
applications/paint/PaintTool.cpp
busybox11/skift
778ae3a0dc5ac29d7de02200c49d3533e47854c5
[ "MIT" ]
null
null
null
#include <libsystem/Assert.h> #include <libsystem/Logger.h> #include <libutils/Vector.h> #include "paint/PaintDocument.h" #include "paint/PaintTool.h" void pencil_tool_mouse_event(PaintTool *tool, PaintDocument *document, Event event) { __unused(tool); if (event.type == Event::MOUSE_MOVE || event.type == Event::MOUSE_BUTTON_PRESS) { Vec2i from = event.mouse.old_position; Vec2i to = event.mouse.position; if (event.mouse.buttons & MOUSE_BUTTON_LEFT) { document->painter.draw_line_antialias(from, to, document->primary_color); document->dirty = true; } else if (event.mouse.buttons & MOUSE_BUTTON_RIGHT) { document->painter.draw_line_antialias(from, to, document->secondary_color); document->dirty = true; } } } PaintTool *pencil_tool_create() { PaintTool *tool = __create(PaintTool); tool->on_mouse_event = pencil_tool_mouse_event; return tool; } void brush_tool_mouse_event(PaintTool *tool, PaintDocument *document, Event event) { __unused(tool); if (event.type == Event::MOUSE_MOVE || event.type == Event::MOUSE_BUTTON_PRESS) { if (event.mouse.buttons & MOUSE_BUTTON_LEFT) { Color color = document->primary_color; document->painter.fill_rectangle(Rectangle(event.mouse.position - Vec2i(16), Vec2i(32, 32)), color); document->dirty = true; } else if (event.mouse.buttons & MOUSE_BUTTON_RIGHT) { Color color = document->secondary_color; document->painter.fill_rectangle(Rectangle(event.mouse.position - Vec2i(16), Vec2i(32, 32)), color); document->dirty = true; } } } PaintTool *brush_tool_create() { PaintTool *tool = __create(PaintTool); tool->on_mouse_event = brush_tool_mouse_event; return tool; } void eraser_tool_mouse_event(PaintTool *tool, PaintDocument *document, Event event) { __unused(tool); if (event.type == Event::MOUSE_MOVE || event.type == Event::MOUSE_BUTTON_PRESS) { if (event.mouse.buttons & MOUSE_BUTTON_LEFT) { Color color = COLOR_RGBA(0, 0, 0, 0); document->painter.clear_rectangle(Rectangle(event.mouse.position - Vec2i(16), Vec2i(32, 32)), color); document->dirty = true; } else if (event.mouse.buttons & MOUSE_BUTTON_RIGHT) { Color color = document->secondary_color; document->painter.clear_rectangle(Rectangle(event.mouse.position - Vec2i(16), Vec2i(32, 32)), color); document->dirty = true; } } } PaintTool *eraser_tool_create() { PaintTool *tool = __create(PaintTool); tool->on_mouse_event = eraser_tool_mouse_event; return tool; } static void flood_fill(Bitmap &bitmap, Vec2i position, Color target, Color fill) { if (!bitmap.bound().containe(position)) return; if (color_equals(bitmap.get_pixel(position), fill)) return; if (!color_equals(bitmap.get_pixel(position), target)) return; auto queue = Vector<Vec2i>(256); queue.push_back(position); while (!queue.empty()) { Vec2i current = queue.pop_back(); if (!color_equals(bitmap.get_pixel(current), target)) { continue; } bitmap.set_pixel(current, fill); if (current.x() != 0) { queue.push_back(current + Vec2i(-1, 0)); } if (current.x() != bitmap.width() - 1) { queue.push_back(current + Vec2i(1, 0)); } if (current.y() != 0) { queue.push_back(current + Vec2i(0, -1)); } if (current.y() != bitmap.height() - 1) { queue.push_back(current + Vec2i(0, 1)); } } } void fill_tool_mouse_event(PaintTool *tool, PaintDocument *document, Event event) { __unused(tool); if (event.type == Event::MOUSE_BUTTON_PRESS) { if (event.mouse.buttons & MOUSE_BUTTON_LEFT) { Color fill_color = document->primary_color; Color target_color = document->bitmap->get_pixel(event.mouse.position); flood_fill(*document->bitmap, event.mouse.position, target_color, fill_color); document->dirty = true; } else if (event.mouse.buttons & MOUSE_BUTTON_RIGHT) { Color fill_color = document->secondary_color; Color target_color = document->bitmap->get_pixel(event.mouse.position); flood_fill(*document->bitmap, event.mouse.position, target_color, fill_color); document->dirty = true; } } } PaintTool *fill_tool_create() { PaintTool *tool = __create(PaintTool); tool->on_mouse_event = fill_tool_mouse_event; return tool; } void picker_tool_mouse_event(PaintTool *tool, PaintDocument *document, Event event) { __unused(tool); if (event.type == Event::MOUSE_BUTTON_PRESS) { if (event.mouse.buttons & MOUSE_BUTTON_LEFT) { document->primary_color = document->bitmap->get_pixel(event.mouse.position); } else if (event.mouse.buttons & MOUSE_BUTTON_RIGHT) { document->secondary_color = document->bitmap->get_pixel(event.mouse.position); } } } PaintTool *picker_tool_create() { PaintTool *tool = __create(PaintTool); tool->on_mouse_event = picker_tool_mouse_event; return tool; }
26.95122
113
0.618281
busybox11
3f409b1856ff34a49b0bc168ed52b11858a94a50
222
cpp
C++
model.cpp
SsorryQaQ/Algorithm-competition
ee2ed79438ecaf15015d9b043d3e099cfa3829c5
[ "MIT" ]
1
2019-12-01T01:37:56.000Z
2019-12-01T01:37:56.000Z
model.cpp
SsorryQaQ/Algorithm-competition
ee2ed79438ecaf15015d9b043d3e099cfa3829c5
[ "MIT" ]
null
null
null
model.cpp
SsorryQaQ/Algorithm-competition
ee2ed79438ecaf15015d9b043d3e099cfa3829c5
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define _for(i,a,b) for (int i=(a);i<(b);i++) #define _rep(i,a,b) for (int i=(a);i<=(b);i++) using namespace std; int readint(){ int x; scanf("%d",&x); return x; } int main(){ return 0; }
18.5
46
0.554054
SsorryQaQ
3f4ed9be0af37d6ef20903910a873e1dea10d994
1,835
hpp
C++
include/eve/module/real/core/function/regular/generic/ldexp.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
include/eve/module/real/core/function/regular/generic/ldexp.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
include/eve/module/real/core/function/regular/generic/ldexp.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #pragma once #include <eve/function/inc.hpp> #include <eve/function/is_less.hpp> #include <eve/function/if_else.hpp> #include <eve/function/trunc.hpp> #include <eve/detail/implementation.hpp> #include <eve/function/bit_cast.hpp> #include <eve/function/converter.hpp> #include <eve/function/dec.hpp> #include <eve/constant/limitexponent.hpp> #include <eve/constant/minexponent.hpp> #include <eve/constant/maxexponent.hpp> #include <eve/constant/nbmantissabits.hpp> #include <eve/constant/smallestposval.hpp> #include <eve/detail/skeleton_calls.hpp> #include <eve/concept/value.hpp> #include <eve/detail/apply_over.hpp> namespace eve::detail { // ----------------------------------------------------------------------------------------------- // regular case template<real_value T, real_value U> EVE_FORCEINLINE T ldexp_(EVE_SUPPORTS(cpu_) , T const &a , U const &b) noexcept { if constexpr(has_native_abi_v<T> && has_native_abi_v<U>) { using elt_t = element_type_t<T>; if constexpr(integral_value<U>) { auto ik = b+maxexponent(eve::as<elt_t>()); ik <<= nbmantissabits(eve::as<elt_t>()); if constexpr(scalar_value<decltype(ik)>) return a*bit_cast(ik, as<elt_t>()); else return a*bit_cast(ik, as<T>()); } else if constexpr(floating_value<U>) { return ldexp(a, int_(trunc)(b)); } } else return apply_over(ldexp, a, b); } }
32.192982
100
0.544959
orao
3f50d5193072992ff491a9e65f448724c3a5b792
14,796
cpp
C++
ixplugins/jsonrpc/JsonObject.cpp
algamza/ixwss
fc323df76754d9f8aa24a36a24f640378c9e86bb
[ "Unlicense" ]
1
2020-02-11T02:42:31.000Z
2020-02-11T02:42:31.000Z
ixplugins/jsonrpc/JsonObject.cpp
algamza/ixwss
fc323df76754d9f8aa24a36a24f640378c9e86bb
[ "Unlicense" ]
null
null
null
ixplugins/jsonrpc/JsonObject.cpp
algamza/ixwss
fc323df76754d9f8aa24a36a24f640378c9e86bb
[ "Unlicense" ]
null
null
null
/** * @file JsonObject.cpp * @author Group(SW_Browser) <gsw_browser@humaxdigital.com> * @brief * * (c) 2017 Humax Co., Ltd. * This program is produced by Humax Co., Ltd. ("Humax") and * the proprietary Software of Humax and its licensors. Humax provides you, as an Authorized Licensee, * non-assignable, non-transferable and non-exclusive license to use this Software. * You acknowledge that this Software contains valuable trade secrets of Humax and by using this Software * you agree to the responsibility to take all reasonable efforts to protect the any information * you receive from Humax. You are not permitted to duplicate, modify, distribute, sell or lease and * reverse engineer or extract the source code of this Software unless you have Humax's written permission to do so. * If you have no authorized license, discontinue using this Software immediately. * * THE SOFTWARE IS PROVIDED "AS IS" AND HUMAX MAKES NO PROMISES, REPRESENTATIONS OR WARRANTIES, EITHER EXPRESS, * IMPLIED OR STATUTORY, OR OTHERWISE, WITH RESPECT TO THE SOFTWARE. * IN NO EVENT SHALL HUMAX BE LIABLE FOR LOST PROFITS, REVENUES, OR DATA, FINANCIAL LOSSES OR INDIRECT, SPECIAL, * CONSEQUENTIAL, EXEMPLARTY OR PUNITIVE DAMAGES WHATSOEVER RELATING TO YOUR USE OR INABILITY TO USE THE SOFTWARE. * This License is effective until terminated. You may terminate this License at any time by destroying all copies * of the Software including all documentation. This License will terminate immediately without notice from Humax * to you if you fail to comply with any provision of this License. Upon termination, you must destroy all copies * of the Software and all documentation. * The laws of the Republic of Korea will apply to any disputes arising out of or relating to this Copyright Notice. * All claims arising out of or relating to this Copyright Notice will be litigated in the Seoul Central District Court, * in the Republic of Korea. */ #include "JsonObject.h" #include <jansson.h> #include <math.h> #define DEBUG_ON 1 #define DEBUG_MEMORY_ON 0 #ifdef LOG #undef LOG #endif #ifdef ASSERT #undef ASSERT #endif #if (DEBUG_ON) #define LOG(...) \ printf(__VA_ARGS__) #define ASSERT(condition) \ if (!(condition)) { \ LOG("ASSERTION FAIL! (%s) %s#%d\n", #condition, __FILE__, __LINE__); \ CRASH(); \ } #define ASSERT_VALID_DATA(data) \ assert_valid_data((json_t*)data, __FILE__, __LINE__) #define CRASH() \ *(int *)(unsigned int *)0xbbadbeef = 0; static bool s_backendInitialized = false; #define MY_DEBUG_MAGIC_DEAD (0xbbadbeef) #define MY_DEBUG_MAGIC_NUM_1 (0xffee11aa) #define MY_DEBUG_MAGIC_NUM_2 (0xff11eebb) typedef struct { unsigned int magic_num; size_t size; } my_mem_debug_hdr; static unsigned int s_debugTotalMemAllocCount = 0; static size_t s_debugTotalMemAllocSize = 0; static void* my_malloc(size_t size) { void* ptr = malloc(sizeof(my_mem_debug_hdr) + size + sizeof(unsigned int)); ASSERT(ptr); my_mem_debug_hdr* hdr = (my_mem_debug_hdr*)ptr; hdr->magic_num = MY_DEBUG_MAGIC_NUM_1; hdr->size = size; *(unsigned int*)((char*)ptr + sizeof(my_mem_debug_hdr) + size) = MY_DEBUG_MAGIC_NUM_2; s_debugTotalMemAllocCount++; s_debugTotalMemAllocSize += size; #if (DEBUG_MEMORY_ON) LOG("mem + %04u %08lu , %p %lu\n", s_debugTotalMemAllocCount, s_debugTotalMemAllocSize, (char*)ptr + sizeof(my_mem_debug_hdr), size); #endif return ((char*)ptr + sizeof(my_mem_debug_hdr)); } static void my_free(void* ptr) { ASSERT(ptr); my_mem_debug_hdr* hdr = (my_mem_debug_hdr*)((char*)ptr - sizeof(my_mem_debug_hdr)); ASSERT(hdr->magic_num == MY_DEBUG_MAGIC_NUM_1); ASSERT(*(unsigned int*)((char*)ptr + hdr->size) == MY_DEBUG_MAGIC_NUM_2); hdr->magic_num = MY_DEBUG_MAGIC_DEAD; s_debugTotalMemAllocCount--; s_debugTotalMemAllocSize -= hdr->size; free((char*)ptr - sizeof(my_mem_debug_hdr)); #if (DEBUG_MEMORY_ON) LOG("mem - %04u %08lu , %p %lu\n", s_debugTotalMemAllocCount, s_debugTotalMemAllocSize, ptr, hdr->size); #endif } static void assert_valid_data(json_t* data, const char* file, unsigned int line) { if (data == NULL) { LOG("ASSERTION FAIL! (null pointer) %s#%d\n", file, line); CRASH(); } if (data->refcount == (size_t)-1) { return; } if (data->refcount == 0) { LOG("ASSERTION FAIL! (refcount == 0) %s#%d\n", file, line); CRASH(); } my_mem_debug_hdr* hdr = (my_mem_debug_hdr*)(((char*)data) - sizeof(my_mem_debug_hdr)); if (hdr->magic_num != MY_DEBUG_MAGIC_NUM_1) { LOG("ASSERTION FAIL! (invalid magic num 1) %s#%d\n", file, line); CRASH(); } if (*(unsigned int*)(((char*)data) + hdr->size) != MY_DEBUG_MAGIC_NUM_2) { LOG("ASSERTION FAIL! (invalid magic num 2) %s#%d\n", file, line); CRASH(); } } #define INIT_BACKEND_ONCE() \ if (!s_backendInitialized) { \ json_set_alloc_funcs(my_malloc, my_free); \ s_backendInitialized = true; \ } #else #define LOG(format, ...) ((void)0) #define ASSERT(condition) ((void)0) #define ASSERT_VALID_DATA(data) ((void)0) #define INIT_BACKEND_ONCE() ((void)0) #define my_malloc(s) malloc(s) #define my_free(p) free(p) #endif JsonObject JsonObject::create(JSONObjectType type) { return JsonObject(type); } JsonObject JsonObject::create(const string& json) { JsonObject obj = JsonObject(JO_NULL); obj.parse(json); return obj; } JsonObject JsonObject::create(const char* buffer, size_t buflen) { return create(string(buffer, buflen)); } JsonObject JsonObject::valueOf(const string& str) { return JsonObject(json_string(str.c_str())); } JsonObject JsonObject::valueOf(const char* str) { return JsonObject(json_string(str)); } JsonObject JsonObject::valueOf(int i) { return JsonObject(json_integer(i)); } JsonObject JsonObject::valueOf(double d) { return JsonObject(json_real(d)); } JsonObject JsonObject::valueOf(bool b) { return JsonObject(json_boolean(b)); } JsonObject::JsonObject(JSONObjectType type) : m_data(json_null()) { INIT_BACKEND_ONCE(); setToDefaultValue(type); } JsonObject::JsonObject(JSONObjectData data, bool isNewData) : m_data(json_null()) { INIT_BACKEND_ONCE(); setPrivateData(data, isNewData); } JsonObject::JsonObject(const JsonObject& other) : m_data(json_null()) { INIT_BACKEND_ONCE(); setPrivateData(other.getPrivateData(), false); } JsonObject::~JsonObject() { ASSERT_VALID_DATA(m_data); json_decref((json_t*)m_data); } bool JsonObject::parse(const string& json) { json_error_t res; json_t* data = json_loads(json.c_str(), JSON_REJECT_DUPLICATES|JSON_DISABLE_EOF_CHECK|JSON_DECODE_ANY, &res); if (data == NULL) { setPrivateData(json_null()); return false; } setPrivateData(data); return true; } string JsonObject::dump() { ASSERT_VALID_DATA(m_data); char* dump = json_dumps((json_t*)m_data, JSON_INDENT(4)|JSON_PRESERVE_ORDER|JSON_ENCODE_ANY); if (dump == NULL) { return string(); } string str = string(dump); my_free(dump); return str; } JSONObjectType JsonObject::getType() const { ASSERT_VALID_DATA(m_data); switch (json_typeof((json_t*)m_data)) { case JSON_NULL: return JO_NULL; case JSON_OBJECT: return JO_OBJECT; case JSON_ARRAY: return JO_ARRAY; case JSON_STRING: return JO_STRING; case JSON_INTEGER: return JO_INTEGER; case JSON_REAL: return JO_REAL; case JSON_TRUE: return JO_BOOLEAN; case JSON_FALSE: return JO_BOOLEAN; } return JO_UNKOWN; } size_t JsonObject::size() const { ASSERT_VALID_DATA(m_data); JSONObjectType type = getType(); if (type == JO_OBJECT) { return json_object_size((json_t*)m_data); } else if (type == JO_ARRAY) { return json_array_size((json_t*)m_data); } return 0; } JsonObject JsonObject::get(const char* key) const { ASSERT_VALID_DATA(m_data); if (!json_is_object((json_t*)m_data)) { return JsonObject(); } json_t* value = json_object_get((json_t*)m_data, key); if (value == NULL) { return JsonObject(); } return JsonObject(value, false); } bool JsonObject::put(string key, JSONObjectData data, bool isNewData) { ASSERT_VALID_DATA(m_data); if (!ensureValidType(JO_OBJECT)) { return false; } int res = json_object_set((json_t*)m_data, key.c_str(), (json_t*)data); if (res < 0) { return false; } if (isNewData) { json_decref((json_t*)data); } return true; } bool JsonObject::put(string key, string str) { return put(key, json_string(str.c_str())); } bool JsonObject::put(string key, char* s) { return put(key, json_string(s)); } bool JsonObject::put(string key, int i) { return put(key, json_integer(i)); } bool JsonObject::put(string key, double d) { return put(key, json_real(d)); } bool JsonObject::put(string key, bool b) { return put(key, json_boolean(b)); } JsonObject JsonObject::getAt(int index) const { ASSERT_VALID_DATA(m_data); if (index < 0 || index >= (int)size() || !json_is_array((json_t*)m_data)) { return JsonObject(); } JSONObjectData data = json_array_get((json_t*)m_data, index); if (data == NULL) { return JsonObject(); } return JsonObject(data, false); } bool JsonObject::setAt(int index, JsonObject obj) { ASSERT_VALID_DATA(m_data); if (index < 0 || index >= (int)size() || !json_is_array((json_t*)m_data)) { return JsonObject(); } int res = json_array_set((json_t*)m_data, index, (json_t*)obj.getPrivateData()); if (res < 0) { return false; } return true; } bool JsonObject::append(JsonObject obj) { ASSERT_VALID_DATA(m_data); if (!ensureValidType(JO_ARRAY)) { return false; } return json_array_append((json_t*)m_data, (json_t*)obj.getPrivateData()); } bool JsonObject::insert(int index, JsonObject obj) { if (!ensureValidType(JO_ARRAY)) { return false; } return json_array_insert((json_t*)m_data, index, (json_t*)obj.getPrivateData()); } bool JsonObject::remove(int index) { ASSERT_VALID_DATA(m_data); if (!json_is_array((json_t*)m_data)) { return false; } return json_array_remove((json_t*)m_data, index); } JSONObjectData JsonObject::setPrivateData(JSONObjectData data, bool isNewData) { ASSERT_VALID_DATA(m_data); if (data == NULL) { json_decref((json_t*)m_data); m_data = json_null(); } else if (isNewData) { json_decref((json_t*)m_data); m_data = data; ASSERT_VALID_DATA(m_data); } else { json_t* other_data = json_incref((json_t*)data); if (m_data) { json_decref((json_t*)m_data); } m_data = other_data; ASSERT_VALID_DATA(m_data); } return data; } JsonObject& JsonObject::operator=(const JsonObject& other) { setPrivateData(other.getPrivateData(), false); return *this; } bool JsonObject::operator==(const JsonObject& other) const { ASSERT_VALID_DATA(m_data); if (m_data == other.getPrivateData()) return true; return json_equal((json_t*)m_data, (json_t*)other.getPrivateData()); } JsonObject& JsonObject::operator=(string str) { JSONObjectType type = getType(); if (type == JO_NULL || type == JO_STRING) { setPrivateData(json_string(str.c_str())); } return *this; } JsonObject& JsonObject::operator=(const char* str) { JSONObjectType type = getType(); if (type == JO_NULL || type == JO_STRING) { setPrivateData(json_string(str)); } return *this; } JsonObject& JsonObject::operator=(int i) { JSONObjectType type = getType(); if (type == JO_NULL || type == JO_INTEGER) { setPrivateData(json_integer(i)); } else if (type == JO_REAL) { setPrivateData(json_real(i)); } return *this; } JsonObject& JsonObject::operator=(double d) { JSONObjectType type = getType(); if (type == JO_NULL || type == JO_REAL) { setPrivateData(json_real(d)); } return *this; } JsonObject& JsonObject::operator=(bool b) { JSONObjectType type = getType(); if (type == JO_NULL || type == JO_BOOLEAN) { setPrivateData(json_boolean(b)); } else if (type == JO_INTEGER) { setPrivateData(json_integer(b)); } else if (type == JO_REAL) { setPrivateData(json_real(b)); } return *this; } JsonObject::operator string() const { ASSERT_VALID_DATA(m_data); if (!json_is_string((json_t*)m_data)) return string(); return string(json_string_value((const json_t*)m_data)); } JsonObject::operator int() const { ASSERT_VALID_DATA(m_data); JSONObjectType type = getType(); if (type == JO_INTEGER) { return json_integer_value((const json_t*)m_data); } else if (type == JO_REAL) { return round(json_real_value((const json_t*)m_data)); } else if (type == JO_BOOLEAN) { return json_is_true((json_t*)m_data); } return 0; } JsonObject::operator double() const { ASSERT_VALID_DATA(m_data); JSONObjectType type = getType(); if (type == JO_INTEGER || type == JO_REAL) { return json_number_value((const json_t*)m_data); } else if (type == JO_BOOLEAN) { return json_is_true((json_t*)m_data); } return 0.0; } JsonObject::operator bool() const { ASSERT_VALID_DATA(m_data); JSONObjectType type = getType(); if (type == JO_INTEGER) { return (json_integer_value((const json_t*)m_data) != 0); } else if (type == JO_REAL) { return (json_real_value((const json_t*)m_data) != 0.0); } else if (type == JO_BOOLEAN) { return json_is_true((json_t*)m_data); } return false; } void JsonObject::setToDefaultValue(JSONObjectType type) { switch (type) { case JO_NULL: setPrivateData(json_null()); break; case JO_OBJECT: setPrivateData(json_object()); break; case JO_ARRAY: setPrivateData(json_array()); break; case JO_STRING: setPrivateData(json_string(""));break; case JO_INTEGER:setPrivateData(json_integer(0));break; case JO_REAL: setPrivateData(json_real(0.0)); break; case JO_BOOLEAN:setPrivateData(json_false()); break; default: setPrivateData(json_null()); break; } } bool JsonObject::ensureValidType(JSONObjectType type) { if (isNull()) { setToDefaultValue(type); } if (getType() != type) { return false; } return true; }
24.993243
137
0.662544
algamza
3f54fd87607f33197ed7270711ec3cca42827e86
990
cpp
C++
c++/Virtual_Base_class.cpp
zexhan17/Problem-Solving
94a4d2181ada7152a584a7b03dcedef6c915e18f
[ "MIT" ]
null
null
null
c++/Virtual_Base_class.cpp
zexhan17/Problem-Solving
94a4d2181ada7152a584a7b03dcedef6c915e18f
[ "MIT" ]
null
null
null
c++/Virtual_Base_class.cpp
zexhan17/Problem-Solving
94a4d2181ada7152a584a7b03dcedef6c915e18f
[ "MIT" ]
null
null
null
/* VIRTUAL BASE CLASSES A class that is inherited by child classes using virtual keyword is called virtual base class. The virtual base classes are necessary in a situation where the member of base class is duplicated in multilevel inheritance. */ #include <iostream> using namespace std; //Declaring four classes "parent,child1,child2,baby" class Parent{ protected: //protected acces specfier can be inherited by its own child classes by default int n; //declaring data member }; class Child1 :virtual public Parent //Both child1, Child2 classes makes copy of 'n' data member //after writing virtual copy of n.now compiler execute the original n data member { }; class Child2 :virtual public Parent { }; class Baby : public Child1, public Child2 { public: void set(){ n = 10; cout<<"n = "<<n<<endl; } }; int main(){ Baby a; //creating object of class baby a.set(); //calling set function }
21.521739
97
0.678788
zexhan17
3f55f5f52fce8257a6133bb2878f695c96d4b36c
30,111
cpp
C++
tests/nn_tests.cpp
adeobootpin/light-tensor
dfc2d19495848e773b7367427cf848e4ac30b29d
[ "MIT" ]
null
null
null
tests/nn_tests.cpp
adeobootpin/light-tensor
dfc2d19495848e773b7367427cf848e4ac30b29d
[ "MIT" ]
null
null
null
tests/nn_tests.cpp
adeobootpin/light-tensor
dfc2d19495848e773b7367427cf848e4ac30b29d
[ "MIT" ]
null
null
null
#include <iostream> #include <chrono> #include <float.h> #include "lten.h" int LoadMNISTImages(const char* pchFileName, float** ppfImages, int* piTotalImages); int LoadMNISTLabels(const char* pchFileName, char** ppchLabels); //------------------------------------------------------------------------------- // x = [x0, x1, x2, x3], y = [y0 = x0 * 2, y1 = x1 * 4, y2 = x2 * 6, y3 = x3 * 8] // learn mapping between x and y // data generated on the fly so no need to download a dataset //------------------------------------------------------------------------------- int neural_network_test() { class Net : public lten::NeuralNetwork { public: Net() { fc1 = register_module("fc1", lten::FullyConnected(4, 4, true)); fc2 = register_module("fc2", lten::FullyConnected(4, 4, true)); fc3 = register_module("fc3", lten::FullyConnected(4, 4, true)); } lten::Tensor forward(lten::Tensor input) { lten::Tensor output; output = fc1->forward(input); output = fc2->forward(output); output = fc3->forward(output); return output; } private: lten::FullyConnected* fc1; lten::FullyConnected* fc2; lten::FullyConnected* fc3; }; int i; int j; int k; float val; uint64_t batch_size; int64_t numels_per_batch; int index; lten::Tensor input; lten::Tensor target; lten::Tensor output; lten::Tensor loss; Net net; float* input_ptr; float* target_ptr; float lr = 0.0002f; batch_size = 32; input = lten::AllocateTensor({ batch_size, 1, 1, 4 }, nullptr); target = lten::AllocateTensor({ batch_size, 1, 1, 4 }, nullptr); input.set_autograd(true); input_ptr = (float*)input.get_data_ptr(); target_ptr = (float*)target.get_data_ptr(); lten::AdamOptimizer optimizer; optimizer.attach_network(net); optimizer.set_learning_rate(lr); numels_per_batch = input.get_numels() / batch_size; index = 0; printf("\ntraining regression model on CPU...\n"); for (i = 0; i < 15000; i++) { for (j = 0; j < batch_size; j++) { for (k = 0; k < numels_per_batch; k++) { input_ptr[numels_per_batch * j + k] = rand() % 10 + ((rand() % 100) / 1000.0f); if (rand() % 2) { input_ptr[numels_per_batch * j + k] *= -1.0f; } target_ptr[numels_per_batch * j + k] = input_ptr[numels_per_batch * j + k] * ((k + 1) * 2); target_ptr[numels_per_batch * j + k] += ((rand() % 100) / 1000.0f); // add some noise } } output = net.forward(input); loss = mse_loss(output, target); if ((index++ % 1000) == 0) { val = *((float*)loss.get_data_ptr()); printf(" loss: %f\n", val); } loss.backward(); optimizer.step(); optimizer.zero_grad(); } val = *((float*)loss.get_data_ptr()); printf(" loss: %f\n", val); if (val < 50.0f) { return 0; } return -1; } //----------------------------------- // train MNIST data set using the CPU //----------------------------------- int MNIST_test(const char* MNIST_training_images, const char* MNIST_training_labels, const char* MNIST_test_images, const char* MNIST_test_labels) { class Net : public lten::NeuralNetwork { public: Net(int channels_in, int channels_out, int kernel_h, int kernel_w, int pad_h = 0, int pad_w = 0, int stride_h = 1, int stride_w = 1) { conv1 = register_module("conv1", lten::Conv2d(channels_in, channels_out, false, kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w)); fc1 = register_module("fc1", lten::FullyConnected(5760, 50)); drop1 = register_module("drop1", lten::Dropout(0.5f)); fc2 = register_module("fc2", lten::FullyConnected(50, 10)); } lten::Tensor forward(lten::Tensor input) { lten::Tensor output; output = conv1->forward(input); output = output.reshape({ output.get_sizes()[0], 1, 1, 5760 }); output = relu(output); output = fc1->forward(output); output = drop1->forward(output); output = fc2->forward(output); output = log_softmax(output, 3); return output; } private: lten::Conv2d* conv1; lten::FullyConnected * fc1; lten::Dropout* drop1; lten::FullyConnected * fc2; }; int ret; float* training_images; char* training_labels; int total_training_examples; float* test_images; char* test_labels; int total_test_examples; int i; int j; int index; lten::Tensor input; lten::Tensor label; lten::Tensor output; lten::Tensor loss; uint64_t img_dim = 28; uint64_t data_len = img_dim * img_dim; uint64_t label_len = 10; float label_array[10]; float lr = 0.001f; Net net(1, 10, 5, 5); int batch_size; int epochs; float val; ret = LoadMNISTImages(MNIST_training_images, &training_images, &total_training_examples); if (ret) { std::cout << "unable to load MNIST images [" << MNIST_training_images << " file failed to load]" << std::endl; return -1; } ret = LoadMNISTLabels(MNIST_training_labels, &training_labels); if (ret) { std::cout << "unable to load MNIST labels [" << MNIST_training_labels << " file failed to load]" << std::endl; return -1; } ret = LoadMNISTImages(MNIST_test_images, &test_images, &total_test_examples); if (ret) { std::cout << "unable to load MNIST images [" << MNIST_test_images << " file failed to load]" << std::endl; return -1; } ret = LoadMNISTLabels(MNIST_test_labels, &test_labels); if (ret) { std::cout << "unable to load MNIST labels [" << MNIST_test_labels << " file failed to load]" << std::endl; return -1; } for (i = 0; i < total_training_examples * data_len; i++) { training_images[i] = training_images[i] / 255.0f; } for (i = 0; i < total_test_examples * data_len; i++) { test_images[i] = test_images[i] / 255.0f; } batch_size = 32; input = lten::AllocateTensor({ static_cast<uint64_t>(batch_size), 1, img_dim, img_dim }, nullptr); label = lten::AllocateTensor({ static_cast<uint64_t>(batch_size), 1, 1, label_len }, nullptr); input.set_autograd(true); lten::SGDOptimizer optimizer; //lten::AdamOptimizer also works fine optimizer.attach_network(net); optimizer.set_learning_rate(lr); index = 0; epochs = 1; int training_iterations = epochs * (total_training_examples / batch_size); printf("\ntraining MNIST model on CPU for %d epoch(s)...\n", epochs); for (i = 0; i < training_iterations; i++) { //-------------------------------------------------------------------------------------- for (j = 0; j < batch_size; j++) { float* data_ptr; float* label_ptr; data_ptr = (float*)input.get_data_ptr(); label_ptr = (float*)label.get_data_ptr(); int example_idx = (i * batch_size + j) % total_training_examples; memcpy(data_ptr + data_len * j, training_images + example_idx * data_len, sizeof(float) * data_len); memset(label_array, 0, sizeof(label_array)); label_array[training_labels[example_idx]] = 1.0f; memcpy(label_ptr + label_len * j, label_array, sizeof(label_array)); } //-------------------------------------------------------------------------------------- output = net.forward(input); loss = nll_loss(output, label); if ((index++ % 200) == 0) { val = *((float*)loss.get_data_ptr()); printf(" loss: %f [%d%% completed]\n",val, i * 100 / training_iterations); } loss.backward(); optimizer.step(); optimizer.zero_grad(); } val = *((float*)loss.get_data_ptr()); printf(" loss: %f [%d%% completed]\n", val, i * 100 / training_iterations); printf("running inference...\n"); net.train(false); int total_correct = 0; for (i = 0; i < total_test_examples; i++) { int example_idx = i; memcpy(input.get_data_ptr(), test_images + example_idx * data_len, sizeof(float) * data_len); output = net.forward(input); float* output_ptr = (float*)output.get_data_ptr(); int label = 0; float max = output_ptr[0]; for (j = 1; j < 10; j++) { if (output_ptr[j] > max) { max = output_ptr[j]; label = j; } } if (label == test_labels[example_idx]) { total_correct++; } } printf("score: %d/%d [%f%%]\n", total_correct, total_test_examples, (100.0f * total_correct) / total_test_examples); if ((100.0f * total_correct) / total_test_examples > 85.0f) { return 0; } return -1; } //--------------------------------- // train MNIST data set using a GPU //--------------------------------- int MNIST_test_gpu(const char* MNIST_training_images, const char* MNIST_training_labels, const char* MNIST_test_images, const char* MNIST_test_labels) { class Net : public lten::NeuralNetwork { public: Net(int channels_in, int channels_out, int kernel_h, int kernel_w, int pad_h = 0, int pad_w = 0, int stride_h = 1, int stride_w = 1) { conv1 = register_module("conv1", lten::Conv2d(channels_in, channels_out, false, kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w)); fc1 = register_module("fc1", lten::FullyConnected(5760, 50)); drop1 = register_module("drop1", lten::Dropout(0.5f)); fc2 = register_module("fc2", lten::FullyConnected(50, 10)); } lten::Tensor forward(lten::Tensor input) { lten::Tensor output; output = conv1->forward(input); output = relu(output); output = output.reshape({ output.get_sizes()[0], 1, 1, 5760 }); output = fc1->forward(output); output = drop1->forward(output); output = fc2->forward(output); output = log_softmax(output, 3); return output; } private: lten::Conv2d* conv1; lten::FullyConnected * fc1; lten::Dropout* drop1; lten::FullyConnected * fc2; }; int ret; float* training_images; char* training_labels; int total_training_examples; float* test_images; char* test_labels; int total_test_examples; int i; int j; int index; lten::Tensor input; lten::Tensor input_gpu; lten::Tensor label; lten::Tensor label_gpu; lten::Tensor output; lten::Tensor loss; uint64_t img_dim = 28; uint64_t data_len = img_dim * img_dim; uint64_t label_len = 10; float label_array[10]; float lr = 0.0001f; Net net(1, 10, 5, 5); int batch_size; int epochs; float val; lten::Tensor temp; ret = LoadMNISTImages(MNIST_training_images, &training_images, &total_training_examples); if (ret) { std::cout << "unable to load MNIST images [" << MNIST_training_images << " file failed to load]" << std::endl; return -1; } ret = LoadMNISTLabels(MNIST_training_labels, &training_labels); if (ret) { std::cout << "unable to load MNIST labels [" << MNIST_training_labels << " file failed to load]" << std::endl; return -1; } ret = LoadMNISTImages(MNIST_test_images, &test_images, &total_test_examples); if (ret) { std::cout << "unable to load MNIST images [" << MNIST_test_images << " file failed to load]" << std::endl; return -1; } ret = LoadMNISTLabels(MNIST_test_labels, &test_labels); if (ret) { std::cout << "unable to load MNIST labels [" << MNIST_test_labels << " file failed to load]" << std::endl; return -1; } for (i = 0; i < total_training_examples * data_len; i++) { training_images[i] = training_images[i] / 255.0f; } for (i = 0; i < total_test_examples * data_len; i++) { test_images[i] = test_images[i] / 255.0f; } batch_size = 32; input = lten::AllocateTensor({ static_cast<uint64_t>(batch_size), 1, img_dim, img_dim }, nullptr); label = lten::AllocateTensor({ static_cast<uint64_t>(batch_size), 1, 1, label_len }, nullptr); input.set_autograd(true); lten::AdamOptimizer optimizer; //lten::SGDOptimizer also works fine optimizer.attach_network(net); optimizer.set_learning_rate(lr); net.to(lten::GPU); index = 0; epochs = 1; int training_iterations = epochs * (total_training_examples / batch_size); printf("\ntraining MNIST model on GPU for %d epoch(s)...\n", epochs); for (i = 0; i < training_iterations; i++) { //-------------------------------------------------------------------------------------- for (j = 0; j < batch_size; j++) { float* data_ptr; float* label_ptr; data_ptr = (float*)input.get_data_ptr(); label_ptr = (float*)label.get_data_ptr(); int example_idx = (i * batch_size + j) % total_training_examples; memcpy(data_ptr + data_len * j, training_images + example_idx * data_len, sizeof(float) * data_len); memset(label_array, 0, sizeof(label_array)); label_array[training_labels[example_idx]] = 1.0f; memcpy(label_ptr + label_len * j, label_array, sizeof(label_array)); } //-------------------------------------------------------------------------------------- input_gpu = input.to(lten::GPU); label_gpu = label.to(lten::GPU); output = net.forward(input_gpu); loss = nll_loss(output, label_gpu); if ((index++ % 200) == 0) { temp = loss.to(lten::CPU); val = *((float*)temp.get_data_ptr()); printf(" loss: %f [%d%% completed]\n", val, i * 100 / training_iterations); } loss.backward(); optimizer.step(); optimizer.zero_grad(); } temp = loss.to(lten::CPU); val = *((float*)temp.get_data_ptr()); printf(" loss: %f [%d%% completed]\n", val, i * 100 / training_iterations); printf("running inference...\n"); net.train(false); int total_correct = 0; for (i = 0; i < total_test_examples; i++) { int example_idx = i; memcpy(input.get_data_ptr(), test_images + example_idx * data_len, sizeof(float) * data_len); input_gpu = input.to(lten::GPU); output = net.forward(input_gpu); output = output.to(lten::CPU); float* output_ptr = (float*)output.get_data_ptr(); int label = 0; float max = output_ptr[0]; for (j = 1; j < 10; j++) { if (output_ptr[j] > max) { max = output_ptr[j]; label = j; } } if (label == test_labels[example_idx]) { total_correct++; } } printf("score: %d/%d [%f%%]\n", total_correct, total_test_examples, (100.0f * total_correct) / total_test_examples); if ((100.0f * total_correct) / total_test_examples > 85.0f) { return 0; } return -1; } //----------------------------------------------------------------------------------------------- // 1. train an MNIST model using FP32 (train for only a few iterations to make this a quick test) // 2. run inference using the FP32 model // 3. quantize the FP32 weights to UINT8 // 4. run inference using the UINT8 model // 5. compare FP32 and UINT8 results //----------------------------------------------------------------------------------------------- int quantized_MNIST_test(const char* MNIST_training_images, const char* MNIST_training_labels, const char* MNIST_test_images, const char* MNIST_test_labels) { struct blob_statistics // structure for storing data statistics during FP32 training { blob_statistics() { min = FLT_MAX; max = -FLT_MAX; } float min; float max; }; blob_statistics layer_stats[4]; // input, conv1, fc1, fc2 class Net : public lten::NeuralNetwork // FP32 neural network { public: Net(int channels_in, int channels_out, int kernel_h, int kernel_w, int pad_h = 0, int pad_w = 0, int stride_h = 1, int stride_w = 1) { conv1 = register_module("conv1", lten::Conv2d(channels_in, channels_out, false, kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w)); fc1 = register_module("fc1", lten::FullyConnected(5760, 50)); fc2 = register_module("fc2", lten::FullyConnected(50, 10)); } void update_statistics(lten::Tensor* x, blob_statistics* x_stats) { uint64_t i; uint64_t len; float min = x_stats->min; float max = x_stats->max; float* data; len = x->get_numels(); data = (float*)x->get_data_ptr(); for (i = 0; i < len; i++) { if (data[i] > max) { max = data[i]; } if (data[i] < min) { min = data[i]; } } x_stats->min = min; x_stats->max = max; } lten::Tensor forward(lten::Tensor input, blob_statistics* layer_stats) { lten::Tensor output; if (layer_stats) update_statistics(&input, &layer_stats[0]); output = conv1->forward(input); if (layer_stats) update_statistics(&output, &layer_stats[1]); output = output.reshape({ output.get_sizes()[0], 1, 1, 5760 }); output = fc1->forward(output); if (layer_stats) update_statistics(&output, &layer_stats[2]); output = fc2->forward(output); if (layer_stats) update_statistics(&output, &layer_stats[3]); output = log_softmax(output, 3); return output; } private: lten::Conv2d* conv1; lten::FullyConnected * fc1; lten::FullyConnected * fc2; }; class QNet : public lten::NeuralNetwork // UINT8 neural network (uses quantized weights from the FP32 network for inference) { public: QNet(int channels_in, int channels_out, int kernel_h, int kernel_w, int pad_h = 0, int pad_w = 0, int stride_h = 1, int stride_w = 1) { conv1 = register_module("conv1", lten::Conv2d_q(channels_in, channels_out, false, kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w)); fc1 = register_module("fc1", lten::FullyConnected_q(5760, 50)); fc2 = register_module("fc2", lten::FullyConnected_q(50, 10)); } lten::Tensor forward(lten::Tensor input) { lten::Tensor output; output = conv1->forward(input); output = output.reshape({ output.get_sizes()[0], 1, 1, 5760 }); output = fc1->forward(output); output = fc2->forward(output); return output; } private: lten::Conv2d_q* conv1; lten::FullyConnected_q* fc1; lten::FullyConnected_q* fc2; }; int ret; float* training_images; char* training_labels; int total_training_examples; float* test_images; char* test_labels; int total_test_examples; int i; int j; int index; lten::Tensor input; lten::Tensor q_input; lten::Tensor label; lten::Tensor output; lten::Tensor q_output; lten::Tensor loss; uint64_t img_dim = 28; uint64_t data_len = img_dim * img_dim; uint64_t label_len = 10; float label_array[10]; float lr = 0.001f; Net net(1, 10, 5, 5); int batch_size; int epochs; float val; float fp32_score; float uint8_score; //------------------------------------------------------------------------------------------ // load MNIST data //------------------------------------------------------------------------------------------ ret = LoadMNISTImages(MNIST_training_images, &training_images, &total_training_examples); if (ret) { std::cout << "unable to load MNIST images [" << MNIST_training_images << " file failed to load]" << std::endl; return -1; } ret = LoadMNISTLabels(MNIST_training_labels, &training_labels); if (ret) { std::cout << "unable to load MNIST labels [" << MNIST_training_labels << " file failed to load]" << std::endl; return -1; } ret = LoadMNISTImages(MNIST_test_images, &test_images, &total_test_examples); if (ret) { std::cout << "unable to load MNIST images [" << MNIST_test_images << " file failed to load]" << std::endl; return -1; } ret = LoadMNISTLabels(MNIST_test_labels, &test_labels); if (ret) { std::cout << "unable to load MNIST labels [" << MNIST_test_labels << " file failed to load]" << std::endl; return -1; } for (i = 0; i < total_training_examples * data_len; i++) { training_images[i] = training_images[i] / 255.0f; } for (i = 0; i < total_test_examples * data_len; i++) { test_images[i] = test_images[i] / 255.0f; } //------------------------------------------------------------------------------------------ batch_size = 32; input = lten::AllocateTensor({ static_cast<uint64_t>(batch_size), 1, img_dim, img_dim }, nullptr); label = lten::AllocateTensor({ static_cast<uint64_t>(batch_size), 1, 1, label_len }, nullptr); input.set_autograd(true); lten::SGDOptimizer optimizer; optimizer.attach_network(net); optimizer.set_learning_rate(lr); index = 0; epochs = 10; int training_iterations = epochs * (total_training_examples / batch_size); training_iterations = 1000; // for quick testing //----------------- // train FP32 model //----------------- printf("\nrunning quantization test...\ntraining FP32 MNIST model on CPU for %d iterations\n", training_iterations); for (i = 0; i < training_iterations; i++) { //-------------------------------------------------------------------------------------- for (j = 0; j < batch_size; j++) { float* data_ptr; float* label_ptr; data_ptr = (float*)input.get_data_ptr(); label_ptr = (float*)label.get_data_ptr(); int example_idx = (i * batch_size + j) % total_training_examples; memcpy(data_ptr + data_len * j, training_images + example_idx * data_len, sizeof(float) * data_len); memset(label_array, 0, sizeof(label_array)); label_array[training_labels[example_idx]] = 1.0f; memcpy(label_ptr + label_len * j, label_array, sizeof(label_array)); } //-------------------------------------------------------------------------------------- output = net.forward(input, layer_stats); loss = nll_loss(output, label); if ((index++ % 100) == 0) { val = *((float*)loss.get_data_ptr()); printf(" loss: %f [%d%% completed]\n", val, i * 100 / training_iterations); } loss.backward(); optimizer.step(); optimizer.zero_grad(); } val = *((float*)loss.get_data_ptr()); printf(" loss: %f [%d%% completed]\n", val, i * 100 / training_iterations); printf("\ntraining FP32 MNIST model completed\n"); //------------------------- // set up quantized network //------------------------- printf("quantizing FP32 MNIST model for UINT8 inference\n"); QNet qnet(1, 10, 5, 5); QuantizationParams qp_input; QuantizationParams qp_fc1; QuantizationParams qp_fc2; QuantizationParams qp_fc3; QuantizationParams qp_wts[2]; lten::Module* mod; lten::Module* q_mod; float minimum; float maximum; int count; ComputeQuantizationParams(layer_stats[0].min, layer_stats[0].max, &qp_input); ComputeQuantizationParams(layer_stats[1].min, layer_stats[1].max, &qp_fc1); ComputeQuantizationParams(layer_stats[2].min, layer_stats[2].max, &qp_fc2); ComputeQuantizationParams(layer_stats[3].min, layer_stats[3].max, &qp_fc3); mod = net.get_module(0); q_mod = qnet.get_module(0); q_mod->set_qparams_in(qp_input); q_mod->set_qparams_out(qp_fc1); count = 0; for (auto wts : mod->get_all_weights()) { // count = 0: weight (uint8_t) // count = 1: bias (int32) if (count == 0) { GetMinMax((float*)wts->get_data_ptr(), wts->get_numels(), &minimum, &maximum); ComputeQuantizationParams(minimum, maximum, &qp_wts[count]); Quantize((float*)wts->get_data_ptr(), (uint8_t*)q_mod->get_all_weights()[count]->get_data_ptr(), wts->get_numels(), &qp_wts[count]); } else { qp_wts[count].scale = qp_input.scale * qp_wts[0].scale; // arXiv:1712.05877 Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference (see qp_wts[count].zero_point = 0; Quantize((float*)wts->get_data_ptr(), (int*)q_mod->get_all_weights()[count]->get_data_ptr(), wts->get_numels(), &qp_wts[count]); } count++; } q_mod->set_qparams_params(qp_wts, count); mod = net.get_module(1); q_mod = qnet.get_module(1); q_mod->set_qparams_in(qp_fc1); q_mod->set_qparams_out(qp_fc2); count = 0; for (auto wts : mod->get_all_weights()) { // count = 0: weight (uint8_t) // count = 1: bias (int32) if (count == 0) { GetMinMax((float*)wts->get_data_ptr(), wts->get_numels(), &minimum, &maximum); ComputeQuantizationParams(minimum, maximum, &qp_wts[count]); Quantize((float*)wts->get_data_ptr(), (uint8_t*)q_mod->get_all_weights()[count]->get_data_ptr(), wts->get_numels(), &qp_wts[count]); } else { qp_wts[count].scale = qp_fc1.scale * qp_wts[0].scale; // arXiv:1712.05877 Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference (see qp_wts[count].zero_point = 0; Quantize((float*)wts->get_data_ptr(), (int*)q_mod->get_all_weights()[count]->get_data_ptr(), wts->get_numels(), &qp_wts[count]); } count++; } q_mod->set_qparams_params(qp_wts, count); mod = net.get_module(2); q_mod = qnet.get_module(2); q_mod->set_qparams_in(qp_fc2); q_mod->set_qparams_out(qp_fc3); count = 0; for (auto wts : mod->get_all_weights()) { // count = 0: weight (uint8_t) // count = 1: bias (int32) if (count == 0) { GetMinMax((float*)wts->get_data_ptr(), wts->get_numels(), &minimum, &maximum); ComputeQuantizationParams(minimum, maximum, &qp_wts[count]); Quantize((float*)wts->get_data_ptr(), (uint8_t*)q_mod->get_all_weights()[count]->get_data_ptr(), wts->get_numels(), &qp_wts[count]); } else { qp_wts[count].scale = qp_fc2.scale * qp_wts[0].scale; // arXiv:1712.05877 Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference (see qp_wts[count].zero_point = 0; Quantize((float*)wts->get_data_ptr(), (int*)q_mod->get_all_weights()[count]->get_data_ptr(), wts->get_numels(), &qp_wts[count]); } count++; } q_mod->set_qparams_params(qp_wts, count); lten::TensorOps options; options.data_type = lten::UINT8; input = lten::AllocateTensor({ 1, 1, img_dim, img_dim }, nullptr); q_input = lten::AllocateTensor({ 1, 1, img_dim, img_dim }, &options); //------------------------------ // run inference with FP32 model //------------------------------ printf("running inference...\n"); input.set_autograd(false); int total_correct = 0; for (i = 0; i < total_test_examples; i++) { int example_idx = i; memcpy(input.get_data_ptr(), test_images + example_idx * data_len, sizeof(float) * data_len); output = net.forward(input, nullptr); float* output_ptr = (float*)output.get_data_ptr(); int label = 0; float max = output_ptr[0]; for (j = 1; j < 10; j++) { if (output_ptr[j] > max) { max = output_ptr[j]; label = j; } } if (label == test_labels[example_idx]) { total_correct++; } } fp32_score = (100.0f * total_correct) / total_test_examples; printf("score [fp32]: %d/%d [%f%%]\n", total_correct, total_test_examples, fp32_score); //------------------------------- // run inference with UINT8 model //------------------------------- output.set_autograd(false); total_correct = 0; for (i = 0; i < total_test_examples; i++) { int example_idx = i; memcpy(input.get_data_ptr(), test_images + example_idx * data_len, sizeof(float) * data_len); Quantize((float*)input.get_data_ptr(), (uint8_t*)q_input.get_data_ptr(), q_input.get_numels(), &qp_input); q_output = qnet.forward(q_input); Dequantize((float*)output.get_data_ptr(), (uint8_t*)q_output.get_data_ptr(), q_output.get_numels(), &qp_fc3); output = log_softmax(output, 3); float* output_ptr = (float*)output.get_data_ptr(); int label = 0; float max = output_ptr[0]; for (j = 1; j < 10; j++) { if (output_ptr[j] > max) { max = output_ptr[j]; label = j; } } if (label == test_labels[example_idx]) { total_correct++; } } uint8_score = (100.0f * total_correct) / total_test_examples; printf("score [uint8]: %d/%d [%f%%]\n", total_correct, total_test_examples, uint8_score); if (uint8_score / fp32_score > 0.95f) { return 0; } return -1; } void ReverseBytes(unsigned char* bytes, int byte_count) { int i; unsigned char* temp; temp = new unsigned char[byte_count]; memcpy(temp, bytes, byte_count); for (i = 0; i < byte_count; i++) { bytes[byte_count - i - 1] = temp[i]; } delete temp; } int LoadMNISTImages(const char* filename, float** pp_images, int* total_images) { int ret; int i; int j; int k; unsigned char* data; size_t data_size; int magic; int image_count; int height; int width; unsigned char* char_index; unsigned char* char_images; float* float_images; int index; ret = ReadDataFromFile(filename, (void**)&data, &data_size); if (ret) { printf("Failed to load MNIST images [%s]\n", filename); return ret; } char_index = data; ReverseBytes(char_index, sizeof(int)); memcpy(&magic, char_index, sizeof(int)); char_index += sizeof(int); ReverseBytes(char_index, sizeof(int)); memcpy(&image_count, char_index, sizeof(int)); char_index += sizeof(int); ReverseBytes(char_index, sizeof(int)); memcpy(&height, char_index, sizeof(int)); char_index += sizeof(int); ReverseBytes(char_index, sizeof(int)); memcpy(&width, char_index, sizeof(int)); char_index += sizeof(int); char_images = new unsigned char[height * width]; float_images = new float[image_count * height * width]; index = 0; for (i = 0; i < image_count; i++) { for (j = 0; j < height; j++) { for (k = 0; k < width; k++) { float_images[index++] = *char_index++; } } } delete data; *total_images = image_count; *pp_images = float_images; return 0; } int LoadMNISTLabels(const char* filename, char** pp_labels) { int ret; int i; unsigned char* data; size_t data_size; int magic; int image_count; unsigned char* pch; char* labels; ret = ReadDataFromFile(filename, (void**)&data, &data_size); if (ret) { printf("Failed to load MNIST labels [%s]\n", filename); return ret; } pch = data; ReverseBytes(pch, sizeof(int)); memcpy(&magic, pch, sizeof(int)); pch += sizeof(int); ReverseBytes(pch, sizeof(int)); memcpy(&image_count, pch, sizeof(int)); pch += sizeof(int); labels = new char[image_count]; for (i = 0; i < image_count; i++) { double dd = (double)(*pch); labels[i] = (*pch++); } delete data; *pp_labels = labels; return 0; }
27.348774
178
0.611803
adeobootpin
3f58d5bccc1d35a4b8b648d6f82f6f83ee5dbbfe
2,483
hpp
C++
src/file/Util.hpp
hotwatermorning/Vst3SampleHost
405f8f9ca89467de46ee3fd9b819503e556022e7
[ "MIT" ]
19
2019-09-15T11:35:11.000Z
2021-12-02T12:27:09.000Z
src/file/Util.hpp
hotwatermorning/Vst3SampleHost
405f8f9ca89467de46ee3fd9b819503e556022e7
[ "MIT" ]
3
2019-09-15T12:48:49.000Z
2019-09-18T10:43:19.000Z
src/file/Util.hpp
hotwatermorning/Vst3SampleHost
405f8f9ca89467de46ee3fd9b819503e556022e7
[ "MIT" ]
1
2021-08-27T23:07:27.000Z
2021-08-27T23:07:27.000Z
#pragma once #include <string> #include <vector> #include <optional> #include <sstream> #include "../device/DeviceType.hpp" #include "../plugin/vst3/Vst3PluginFactory.hpp" #include "../gui/PluginViewType.hpp" #include "../app/OscillatorType.hpp" NS_HWM_BEGIN Int32 stoi_or(std::string const &str, Int32 default_value); double stof_or(std::string const &str, double default_value); std::string get_trimmed_line(std::istream &is); std::vector<std::string> read_lines(std::istream &is); std::optional<std::string> find_value(std::vector<std::string> const &lines, std::string const &key); struct write_line_object { std::string const key; std::string const value; friend std::ostream & operator<<(std::ostream &os, write_line_object const &self); }; write_line_object write_line(std::string const &key, std::string const &value); std::string base64_encode(std::vector<char> const &data); std::string base64_encode(char const *data, size_t length); std::optional<std::vector<char>> base64_decode(std::string const &data); template<class T> std::string to_s(T const &v) { std::stringstream ss; ss << v; return ss.str(); } template<class T> std::string to_s(std::optional<T> const &v) { if(v) { return to_s(*v); } else { return ""; } } template<class T> bool from_s(std::string const &str, T &v) { std::istringstream ss(str); ss >> v; return !!ss; } template<class T> bool from_s(std::string const &str, std::optional<T> &v) { T tmp; if(from_s(str, tmp)) { v = tmp; return true; } else { return false; } } #if !defined(INSTANCIATE_STRING_CONVERSION_FUNCTIONS) extern template std::string to_s(String const &s); extern template std::string to_s(AudioDriverType const &v); extern template std::string to_s(ClassInfo::CID const &v); extern template std::string to_s(std::vector<char> const &v); extern template std::string to_s(PluginViewType const &v); extern template std::string to_s(OscillatorType const &v); extern template bool from_s(std::string const &str, String &s); extern template bool from_s(std::string const &str, AudioDriverType &v); extern template bool from_s(std::string const &str, std::vector<char> &v); extern template bool from_s(std::string const &str, ClassInfo::CID &v); extern template bool from_s(std::string const &str, PluginViewType &v); extern template bool from_s(std::string const &str, OscillatorType &v); #endif NS_HWM_END
26.414894
101
0.701973
hotwatermorning
3f5962b79931093121d4303758388a7410c1ffdf
3,284
cpp
C++
438-find-all-anagrams-in-a-string/438-find-all-anagrams-in-a-string.cpp
ComputerScientist-01/SDE-Sheet
e0ebd6e6a21ed07ce0a1ae123f552e7a4da3ac3a
[ "MIT" ]
null
null
null
438-find-all-anagrams-in-a-string/438-find-all-anagrams-in-a-string.cpp
ComputerScientist-01/SDE-Sheet
e0ebd6e6a21ed07ce0a1ae123f552e7a4da3ac3a
[ "MIT" ]
null
null
null
438-find-all-anagrams-in-a-string/438-find-all-anagrams-in-a-string.cpp
ComputerScientist-01/SDE-Sheet
e0ebd6e6a21ed07ce0a1ae123f552e7a4da3ac3a
[ "MIT" ]
null
null
null
class Solution { public: vector<int> findAnagrams(string s, string p) { //sliding window technique using my own template int n = s.size(); //length of source string int m = p.size(); //length of target string //init an array or var to save the result as per the question requirement vector<int> startIndices; //if target string size is greater than source string size if(m > n) { return startIndices; } //create a hashmap to save the characters count of the target substring. //<char, int> = (Character, Frequency of the Characters) unordered_map<char,int> charCount; for(int i=0; i<m; i++) { if(charCount.find(p[i]) == charCount.end()) { charCount[p[i]] = 1; } else { charCount[p[i]]++; } } //num of unique chars in target string int uniqueCharCount = charCount.size(); //Two Pointers: left -> first pointer of the window, //right -> last pointer of the window int left = 0; int right = 0; //maintain a counter to check whether curr window in source string //matches the given condition with target string. int numHits = 0; //loop the source string till right pointer reaches end of source string while(right < n) { //add the character at the right pointer which is now //a part of the window and update hashmap accordingly if(charCount.find(s[right]) != charCount.end()) { if(charCount[s[right]] == 0) { numHits--; } //modify the counter as per the requirement charCount[s[right]]--; if(charCount[s[right]] == 0) { numHits++; } } if( right - left + 1 > m) { //increment left pointer whenever the window size //crosses the target string size to keep the window size //equal to the target string size left++; //remove the character which is no longer part of the window //and update hashmap accordingly if(charCount.find(s[left-1]) != charCount.end()) { if(charCount[s[left-1]] == 0) { numHits--; } //modify the counter as per the requirement charCount[s[left-1]]++; if(charCount[s[left-1]] == 0) { numHits++; } } } //whenever the current window in source string fulfils the //given conditions in the target string, add it to the result if(numHits == uniqueCharCount) { startIndices.push_back(left); } //increment right pointer in each iteration right++; } //return result return startIndices; } };
37.318182
81
0.482034
ComputerScientist-01
3f5f69882c487a14a530d9440da69b8ec252633d
99
hpp
C++
source/utils.hpp
in1tiate/OoT3D_Randomizer
baa1f4a0f4a2e1aadec9547120b29d1617211f45
[ "MIT" ]
133
2020-08-25T20:27:08.000Z
2022-03-28T04:38:44.000Z
source/utils.hpp
in1tiate/OoT3D_Randomizer
baa1f4a0f4a2e1aadec9547120b29d1617211f45
[ "MIT" ]
112
2020-11-27T18:51:33.000Z
2022-03-28T21:58:21.000Z
source/utils.hpp
in1tiate/OoT3D_Randomizer
baa1f4a0f4a2e1aadec9547120b29d1617211f45
[ "MIT" ]
57
2020-08-24T08:54:39.000Z
2022-03-27T18:08:51.000Z
#pragma once #include <algorithm> #include <string> std::string RemoveLineBreaks(std::string s);
14.142857
44
0.747475
in1tiate
3f623ac4d3bd86e6c28225657cab32022928a474
360
hpp
C++
src/But/Log/Backend/NonPrintableTrimmer.hpp
el-bart/but
eee2e7e34dde415f4c87461f75c2bab38fc56407
[ "BSD-3-Clause" ]
27
2016-01-12T19:30:57.000Z
2022-01-27T15:52:39.000Z
src/But/Log/Backend/NonPrintableTrimmer.hpp
el-bart/but
eee2e7e34dde415f4c87461f75c2bab38fc56407
[ "BSD-3-Clause" ]
4
2017-04-10T16:30:22.000Z
2019-04-24T21:02:55.000Z
src/But/Log/Backend/NonPrintableTrimmer.hpp
el-bart/but
eee2e7e34dde415f4c87461f75c2bab38fc56407
[ "BSD-3-Clause" ]
2
2016-12-09T17:09:59.000Z
2019-07-16T00:19:31.000Z
#pragma once #include <array> #include <string> #include <cinttypes> namespace But { namespace Log { namespace Backend { struct NonPrintableTrimmer final { NonPrintableTrimmer(); std::string operator()(std::string in) const { for(auto& e: in) e = lut_[ (uint8_t)e ]; return in; } private: const std::array<char,256> lut_; }; } } }
11.612903
46
0.652778
el-bart
3f6a5237cf58e6cbf1214210f841b753b071dc6a
3,906
hpp
C++
DGP/AxisAlignedBox3.hpp
sidch/DGP
20a2d47563b6e36cd89bea0b1326e5267df8e9a6
[ "BSD-3-Clause" ]
14
2016-03-15T16:24:10.000Z
2022-01-06T13:43:17.000Z
a3/src/DGP/AxisAlignedBox3.hpp
meetps/CS-749
f1ddc4ed003b3a9f222f2a724d53076ddec697a6
[ "MIT" ]
null
null
null
a3/src/DGP/AxisAlignedBox3.hpp
meetps/CS-749
f1ddc4ed003b3a9f222f2a724d53076ddec697a6
[ "MIT" ]
5
2017-04-12T17:40:57.000Z
2022-01-06T13:43:20.000Z
//============================================================================ // // DGP: Digital Geometry Processing toolkit // Copyright (C) 2016, Siddhartha Chaudhuri // // This software is covered by a BSD license. Portions derived from other // works are covered by their respective licenses. For full licensing // information see the LICENSE.txt file. // //============================================================================ #ifndef __DGP_AxisAlignedBox3_hpp__ #define __DGP_AxisAlignedBox3_hpp__ #include "Common.hpp" #include "AxisAlignedBoxN.hpp" namespace DGP { /** A 3-dimensional axis-aligned box. */ template <typename T> class /* DGP_API */ AxisAlignedBoxN<3, T> : public Internal::AxisAlignedBoxNBase<3, T> { private: typedef Internal::AxisAlignedBoxNBase<3, T> BaseT; public: typedef typename BaseT::VectorT VectorT; /** Default constructor, creates a null box. */ AxisAlignedBoxN() : BaseT() {} /** Constructor. Sets the box to be a single point. */ AxisAlignedBoxN(VectorT const & v) : BaseT(v) {} /** Constructor. Sets the extents of the box. */ AxisAlignedBoxN(VectorT const & lo_, VectorT const & hi_) : BaseT(lo_, hi_) {} /** * Transform the box and return a new axis-aligned box which tightly encloses the result. * * Algorithm taken from the Ogre source code, http://www.ogre3d.org. */ template <typename TransformT> AxisAlignedBoxN transformAndBound(TransformT const & tr) const { Vector3 const & lo_ = this->getLow(); Vector3 const & hi_ = this->getHigh(); // We sequentially compute the corners in the following order: // 0, 6, 5, 1, 2, 4, 7, 3 // This sequence allows us to only change one member at a time to get at all corners. For each one, we transform it and // merge the resulting point. // min min min Vector3 current_corner = lo_; AxisAlignedBoxN result = AxisAlignedBoxN(tr * current_corner); // min min max current_corner.z() = hi_.z(); result.merge(tr * current_corner); // min max max current_corner.y() = hi_.y(); result.merge(tr * current_corner); // min max min current_corner.z() = lo_.z(); result.merge(tr * current_corner); // max max min current_corner.x() = hi_.x(); result.merge(tr * current_corner); // max max max current_corner.z() = hi_.z(); result.merge(tr * current_corner); // max min max current_corner.y() = lo_.y(); result.merge(tr * current_corner); // max min min current_corner.z() = lo_.z(); result.merge(tr * current_corner); return result; } /** * Get edge number \a i of the box, where i is between 0 and 11. * * @param i Index of edge, between 0 and 11 inclusive. * @param start Used to return the starting point of the edge. * @param end Used to return the endpoint of the edge. */ void getEdge(int i, Vector3 & start, Vector3 & end) const { static int const INDICES[12][6] = { { 0, 0, 0, 0, 0, 1 }, { 0, 0, 0, 0, 1, 0 }, { 0, 0, 0, 1, 0, 0 }, { 1, 1, 0, 1, 1, 1 }, { 1, 1, 0, 1, 0, 0 }, { 1, 1, 0, 0, 1, 0 }, { 1, 0, 1, 0, 0, 1 }, { 1, 0, 1, 1, 1, 1 }, { 1, 0, 1, 1, 0, 0 }, { 0, 1, 1, 1, 1, 1 }, { 0, 1, 1, 0, 0, 1 }, { 0, 1, 1, 0, 1, 0 } }; Vector3 const * v[2] = { &this->getLow(), &this->getHigh() }; start = Vector3((*v[INDICES[i][0]])[0], (*v[INDICES[i][1]])[1], (*v[INDICES[i][2]])[2]); end = Vector3((*v[INDICES[i][3]])[0], (*v[INDICES[i][4]])[1], (*v[INDICES[i][5]])[2]); } }; // class AxisAlignedBoxN<3, T> /** The default axis-aligned box class in 3-dimensional real space. */ typedef AxisAlignedBoxN<3, Real> AxisAlignedBox3; } // namespace DGP #endif
30.27907
125
0.566052
sidch
3f6b94d39409cea97b6afe617ca64ffba13ceedf
17,031
cpp
C++
ToolKit/Chart/Types/XTPChartTypes.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
2
2018-03-30T06:40:08.000Z
2022-02-23T12:40:13.000Z
ToolKit/Chart/Types/XTPChartTypes.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
null
null
null
ToolKit/Chart/Types/XTPChartTypes.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
1
2020-08-11T05:48:02.000Z
2020-08-11T05:48:02.000Z
// XTPChartTypes.cpp // // This file is a part of the XTREME TOOLKIT PRO MFC class library. // (c)1998-2011 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Common/XTPPropExchange.h" #include "Common/XTPDrawHelpers.h" #include "Common/XTPVC80Helpers.h" #include "XTPChartTypes.h" #include "../Utils/XTPChartMathUtils.h" ////////////////////////////////////////////////////////////////////////// // CXTPChartColor const CXTPChartColor::ARGB CXTPChartColor::AliceBlue = 0xFFF0F8FF; const CXTPChartColor::ARGB CXTPChartColor::AntiqueWhite = 0xFFFAEBD7; const CXTPChartColor::ARGB CXTPChartColor::Aqua = 0xFF00FFFF; const CXTPChartColor::ARGB CXTPChartColor::Aquamarine = 0xFF7FFFD4; const CXTPChartColor::ARGB CXTPChartColor::Azure = 0xFFF0FFFF; const CXTPChartColor::ARGB CXTPChartColor::Beige = 0xFFF5F5DC; const CXTPChartColor::ARGB CXTPChartColor::Bisque = 0xFFFFE4C4; const CXTPChartColor::ARGB CXTPChartColor::Black = 0xFF000000; const CXTPChartColor::ARGB CXTPChartColor::BlanchedAlmond = 0xFFFFEBCD; const CXTPChartColor::ARGB CXTPChartColor::Blue = 0xFF0000FF; const CXTPChartColor::ARGB CXTPChartColor::BlueViolet = 0xFF8A2BE2; const CXTPChartColor::ARGB CXTPChartColor::Brown = 0xFFA52A2A; const CXTPChartColor::ARGB CXTPChartColor::BurlyWood = 0xFFDEB887; const CXTPChartColor::ARGB CXTPChartColor::CadetBlue = 0xFF5F9EA0; const CXTPChartColor::ARGB CXTPChartColor::Chartreuse = 0xFF7FFF00; const CXTPChartColor::ARGB CXTPChartColor::Chocolate = 0xFFD2691E; const CXTPChartColor::ARGB CXTPChartColor::Coral = 0xFFFF7F50; const CXTPChartColor::ARGB CXTPChartColor::CornflowerBlue = 0xFF6495ED; const CXTPChartColor::ARGB CXTPChartColor::Cornsilk = 0xFFFFF8DC; const CXTPChartColor::ARGB CXTPChartColor::Crimson = 0xFFDC143C; const CXTPChartColor::ARGB CXTPChartColor::Cyan = 0xFF00FFFF; const CXTPChartColor::ARGB CXTPChartColor::DarkBlue = 0xFF00008B; const CXTPChartColor::ARGB CXTPChartColor::DarkCyan = 0xFF008B8B; const CXTPChartColor::ARGB CXTPChartColor::DarkGoldenrod = 0xFFB8860B; const CXTPChartColor::ARGB CXTPChartColor::DarkGray = 0xFFA9A9A9; const CXTPChartColor::ARGB CXTPChartColor::DarkGreen = 0xFF006400; const CXTPChartColor::ARGB CXTPChartColor::DarkKhaki = 0xFFBDB76B; const CXTPChartColor::ARGB CXTPChartColor::DarkMagenta = 0xFF8B008B; const CXTPChartColor::ARGB CXTPChartColor::DarkOliveGreen = 0xFF556B2F; const CXTPChartColor::ARGB CXTPChartColor::DarkOrange = 0xFFFF8C00; const CXTPChartColor::ARGB CXTPChartColor::DarkOrchid = 0xFF9932CC; const CXTPChartColor::ARGB CXTPChartColor::DarkRed = 0xFF8B0000; const CXTPChartColor::ARGB CXTPChartColor::DarkSalmon = 0xFFE9967A; const CXTPChartColor::ARGB CXTPChartColor::DarkSeaGreen = 0xFF8FBC8B; const CXTPChartColor::ARGB CXTPChartColor::DarkSlateBlue = 0xFF483D8B; const CXTPChartColor::ARGB CXTPChartColor::DarkSlateGray = 0xFF2F4F4F; const CXTPChartColor::ARGB CXTPChartColor::DarkTurquoise = 0xFF00CED1; const CXTPChartColor::ARGB CXTPChartColor::DarkViolet = 0xFF9400D3; const CXTPChartColor::ARGB CXTPChartColor::DeepPink = 0xFFFF1493; const CXTPChartColor::ARGB CXTPChartColor::DeepSkyBlue = 0xFF00BFFF; const CXTPChartColor::ARGB CXTPChartColor::DimGray = 0xFF696969; const CXTPChartColor::ARGB CXTPChartColor::DodgerBlue = 0xFF1E90FF; const CXTPChartColor::ARGB CXTPChartColor::Firebrick = 0xFFB22222; const CXTPChartColor::ARGB CXTPChartColor::FloralWhite = 0xFFFFFAF0; const CXTPChartColor::ARGB CXTPChartColor::ForestGreen = 0xFF228B22; const CXTPChartColor::ARGB CXTPChartColor::Fuchsia = 0xFFFF00FF; const CXTPChartColor::ARGB CXTPChartColor::Gainsboro = 0xFFDCDCDC; const CXTPChartColor::ARGB CXTPChartColor::GhostWhite = 0xFFF8F8FF; const CXTPChartColor::ARGB CXTPChartColor::Gold = 0xFFFFD700; const CXTPChartColor::ARGB CXTPChartColor::Goldenrod = 0xFFDAA520; const CXTPChartColor::ARGB CXTPChartColor::Gray = 0xFF808080; const CXTPChartColor::ARGB CXTPChartColor::Green = 0xFF008000; const CXTPChartColor::ARGB CXTPChartColor::GreenYellow = 0xFFADFF2F; const CXTPChartColor::ARGB CXTPChartColor::Honeydew = 0xFFF0FFF0; const CXTPChartColor::ARGB CXTPChartColor::HotPink = 0xFFFF69B4; const CXTPChartColor::ARGB CXTPChartColor::IndianRed = 0xFFCD5C5C; const CXTPChartColor::ARGB CXTPChartColor::Indigo = 0xFF4B0082; const CXTPChartColor::ARGB CXTPChartColor::Ivory = 0xFFFFFFF0; const CXTPChartColor::ARGB CXTPChartColor::Khaki = 0xFFF0E68C; const CXTPChartColor::ARGB CXTPChartColor::Lavender = 0xFFE6E6FA; const CXTPChartColor::ARGB CXTPChartColor::LavenderBlush = 0xFFFFF0F5; const CXTPChartColor::ARGB CXTPChartColor::LawnGreen = 0xFF7CFC00; const CXTPChartColor::ARGB CXTPChartColor::LemonChiffon = 0xFFFFFACD; const CXTPChartColor::ARGB CXTPChartColor::LightBlue = 0xFFADD8E6; const CXTPChartColor::ARGB CXTPChartColor::LightCoral = 0xFFF08080; const CXTPChartColor::ARGB CXTPChartColor::LightCyan = 0xFFE0FFFF; const CXTPChartColor::ARGB CXTPChartColor::LightGoldenrodYellow = 0xFFFAFAD2; const CXTPChartColor::ARGB CXTPChartColor::LightGray = 0xFFD3D3D3; const CXTPChartColor::ARGB CXTPChartColor::LightGreen = 0xFF90EE90; const CXTPChartColor::ARGB CXTPChartColor::LightPink = 0xFFFFB6C1; const CXTPChartColor::ARGB CXTPChartColor::LightSalmon = 0xFFFFA07A; const CXTPChartColor::ARGB CXTPChartColor::LightSeaGreen = 0xFF20B2AA; const CXTPChartColor::ARGB CXTPChartColor::LightSkyBlue = 0xFF87CEFA; const CXTPChartColor::ARGB CXTPChartColor::LightSlateGray = 0xFF778899; const CXTPChartColor::ARGB CXTPChartColor::LightSteelBlue = 0xFFB0C4DE; const CXTPChartColor::ARGB CXTPChartColor::LightYellow = 0xFFFFFFE0; const CXTPChartColor::ARGB CXTPChartColor::Lime = 0xFF00FF00; const CXTPChartColor::ARGB CXTPChartColor::LimeGreen = 0xFF32CD32; const CXTPChartColor::ARGB CXTPChartColor::Linen = 0xFFFAF0E6; const CXTPChartColor::ARGB CXTPChartColor::Magenta = 0xFFFF00FF; const CXTPChartColor::ARGB CXTPChartColor::Maroon = 0xFF800000; const CXTPChartColor::ARGB CXTPChartColor::MediumAquamarine = 0xFF66CDAA; const CXTPChartColor::ARGB CXTPChartColor::MediumBlue = 0xFF0000CD; const CXTPChartColor::ARGB CXTPChartColor::MediumOrchid = 0xFFBA55D3; const CXTPChartColor::ARGB CXTPChartColor::MediumPurple = 0xFF9370DB; const CXTPChartColor::ARGB CXTPChartColor::MediumSeaGreen = 0xFF3CB371; const CXTPChartColor::ARGB CXTPChartColor::MediumSlateBlue = 0xFF7B68EE; const CXTPChartColor::ARGB CXTPChartColor::MediumSpringGreen = 0xFF00FA9A; const CXTPChartColor::ARGB CXTPChartColor::MediumTurquoise = 0xFF48D1CC; const CXTPChartColor::ARGB CXTPChartColor::MediumVioletRed = 0xFFC71585; const CXTPChartColor::ARGB CXTPChartColor::MidnightBlue = 0xFF191970; const CXTPChartColor::ARGB CXTPChartColor::MintCream = 0xFFF5FFFA; const CXTPChartColor::ARGB CXTPChartColor::MistyRose = 0xFFFFE4E1; const CXTPChartColor::ARGB CXTPChartColor::Moccas = 0xFFFFE4B5; const CXTPChartColor::ARGB CXTPChartColor::NavajoWhite = 0xFFFFDEAD; const CXTPChartColor::ARGB CXTPChartColor::Navy = 0xFF000080; const CXTPChartColor::ARGB CXTPChartColor::OldLace = 0xFFFDF5E6; const CXTPChartColor::ARGB CXTPChartColor::Olive = 0xFF808000; const CXTPChartColor::ARGB CXTPChartColor::OliveDrab = 0xFF6B8E23; const CXTPChartColor::ARGB CXTPChartColor::Orange = 0xFFFFA500; const CXTPChartColor::ARGB CXTPChartColor::OrangeRed = 0xFFFF4500; const CXTPChartColor::ARGB CXTPChartColor::Orchid = 0xFFDA70D6; const CXTPChartColor::ARGB CXTPChartColor::PaleGoldenrod = 0xFFEEE8AA; const CXTPChartColor::ARGB CXTPChartColor::PaleGreen = 0xFF98FB98; const CXTPChartColor::ARGB CXTPChartColor::PaleTurquoise = 0xFFAFEEEE; const CXTPChartColor::ARGB CXTPChartColor::PaleVioletRed = 0xFFDB7093; const CXTPChartColor::ARGB CXTPChartColor::PapayaWhip = 0xFFFFEFD5; const CXTPChartColor::ARGB CXTPChartColor::PeachPuff = 0xFFFFDAB9; const CXTPChartColor::ARGB CXTPChartColor::Peru = 0xFFCD853F; const CXTPChartColor::ARGB CXTPChartColor::Pink = 0xFFFFC0CB; const CXTPChartColor::ARGB CXTPChartColor::Plum = 0xFFDDA0DD; const CXTPChartColor::ARGB CXTPChartColor::PowderBlue = 0xFFB0E0E6; const CXTPChartColor::ARGB CXTPChartColor::Purple = 0xFF800080; const CXTPChartColor::ARGB CXTPChartColor::Red = 0xFFFF0000; const CXTPChartColor::ARGB CXTPChartColor::RosyBrown = 0xFFBC8F8F; const CXTPChartColor::ARGB CXTPChartColor::RoyalBlue = 0xFF4169E1; const CXTPChartColor::ARGB CXTPChartColor::SaddleBrown = 0xFF8B4513; const CXTPChartColor::ARGB CXTPChartColor::Salmon = 0xFFFA8072; const CXTPChartColor::ARGB CXTPChartColor::SandyBrown = 0xFFF4A460; const CXTPChartColor::ARGB CXTPChartColor::SeaGreen = 0xFF2E8B57; const CXTPChartColor::ARGB CXTPChartColor::SeaShell = 0xFFFFF5EE; const CXTPChartColor::ARGB CXTPChartColor::Sienna = 0xFFA0522D; const CXTPChartColor::ARGB CXTPChartColor::Silver = 0xFFC0C0C0; const CXTPChartColor::ARGB CXTPChartColor::SkyBlue = 0xFF87CEEB; const CXTPChartColor::ARGB CXTPChartColor::SlateBlue = 0xFF6A5ACD; const CXTPChartColor::ARGB CXTPChartColor::SlateGray = 0xFF708090; const CXTPChartColor::ARGB CXTPChartColor::Snow = 0xFFFFFAFA; const CXTPChartColor::ARGB CXTPChartColor::SpringGreen = 0xFF00FF7F; const CXTPChartColor::ARGB CXTPChartColor::SteelBlue = 0xFF4682B4; const CXTPChartColor::ARGB CXTPChartColor::Tan = 0xFFD2B48C; const CXTPChartColor::ARGB CXTPChartColor::Teal = 0xFF008080; const CXTPChartColor::ARGB CXTPChartColor::Thistle = 0xFFD8BFD8; const CXTPChartColor::ARGB CXTPChartColor::Tomato = 0xFFFF6347; const CXTPChartColor::ARGB CXTPChartColor::Transparent = 0x00FFFFFF; const CXTPChartColor::ARGB CXTPChartColor::Turquoise = 0xFF40E0D0; const CXTPChartColor::ARGB CXTPChartColor::Violet = 0xFFEE82EE; const CXTPChartColor::ARGB CXTPChartColor::Wheat = 0xFFF5DEB3; const CXTPChartColor::ARGB CXTPChartColor::White = 0xFFFFFFFF; const CXTPChartColor::ARGB CXTPChartColor::WhiteSmoke = 0xFFF5F5F5; const CXTPChartColor::ARGB CXTPChartColor::Yellow = 0xFFFFFF00; const CXTPChartColor::ARGB CXTPChartColor::YellowGreen = 0xFF9ACD32; const CXTPChartColor::ARGB CXTPChartColor::Empty = 0x00000000; void CXTPChartColor::SetFromString(LPCTSTR lpsz) { int clr[4]; int res = SCANF_S(lpsz, _T("%d, %d, %d, %d"), &clr[0], &clr[1], &clr[2], &clr[3]); if (res == 3) { Argb = MakeARGB(255, (BYTE)clr[0], (BYTE)clr[1], (BYTE)clr[2]); } else if (res == 4) { Argb = MakeARGB((BYTE)clr[0], (BYTE)clr[1], (BYTE)clr[2], (BYTE)clr[3]); } else { ASSERT(FALSE); } } ////////////////////////////////////////////////////////////////////////// // CXTPChartRectF void CXTPChartRectF::Round() { int r = CXTPChartMathUtils::Round(X + Width); int d = CXTPChartMathUtils::Round(Y + Height); X = (float)CXTPChartMathUtils::Round(X); Y = (float)CXTPChartMathUtils::Round(Y); Width = r - X; Height = d - Y; } ////////////////////////////////////////////////////////////////////////// // CXTPChartFont CXTPChartFont::CXTPChartFont() { ZeroMemory(&m_lf, sizeof(LOGFONT)); #ifdef _XTP_ACTIVEX EnableAutomation(); EnableTypeLib(); #endif } CXTPChartFont::CXTPChartFont(LOGFONT* pLogFont) { if (pLogFont) { m_lf = *pLogFont; } else { ZeroMemory(&m_lf, sizeof(LOGFONT)); } #ifdef _XTP_ACTIVEX EnableAutomation(); EnableTypeLib(); #endif } CXTPChartFont::~CXTPChartFont() { } void CXTPChartFont::Release() { InternalRelease(); } void CXTPChartFont::SetLogFont(LOGFONT* lf) { m_lf = *lf; } CXTPChartFont* CXTPChartFont::GetTahoma18() { LOGFONT lf; ZeroMemory(&lf, sizeof(LOGFONT)); lf.lfHeight = 29; lf.lfWeight = FW_NORMAL; STRCPY_S(lf.lfFaceName, LF_FACESIZE, _T("Tahoma")); return new CXTPChartFont(&lf); } CXTPChartFont* CXTPChartFont::GetTahoma8() { LOGFONT lf; ZeroMemory(&lf, sizeof(LOGFONT)); lf.lfHeight = -11; lf.lfWeight = FW_NORMAL; STRCPY_S(lf.lfFaceName, LF_FACESIZE, _T("Tahoma")); return new CXTPChartFont(&lf); } CXTPChartFont* CXTPChartFont::GetTahoma12() { LOGFONT lf; ZeroMemory(&lf, sizeof(LOGFONT)); lf.lfHeight = -16; lf.lfWeight = FW_NORMAL; STRCPY_S(lf.lfFaceName, LF_FACESIZE, _T("Tahoma")); return new CXTPChartFont(&lf); } ////////////////////////////////////////////////////////////////////////// // CXTPChartColor CXTPChartColor CXTPChartColor::GetDarkColor() const { COLORREF clrBackground = RGB(GetRed(), GetGreen(), GetBlue()); DWORD dwHSLBackground = CXTPDrawHelpers::RGBtoHSL(clrBackground); DWORD dwL = GetBValue(dwHSLBackground); DWORD dwDark = MulDiv(dwL, 3, 4); COLORREF clrDark = CXTPDrawHelpers::HSLtoRGB(RGB(GetRValue(dwHSLBackground), GetGValue(dwHSLBackground), dwDark)); return CXTPChartColor(GetAlpha(), GetRValue(clrDark), GetGValue(clrDark), GetBValue(clrDark)); } ////////////////////////////////////////////////////////////////////////// // BOOL AFX_CDECL PX_Color(CXTPPropExchange* pPX, LPCTSTR pszPropName, CXTPChartColor& clrValue) { if (pPX->IsStoring()) { CString str; if (!clrValue.IsEmpty()) str.Format(_T("%d, %d, %d"), clrValue.GetRed(), clrValue.GetGreen(), clrValue.GetBlue()); return PX_String(pPX, pszPropName, str, _T("")); } else { CString str; if (!PX_String(pPX, pszPropName, str, _T(""))) return FALSE; if (str.IsEmpty()) clrValue = CXTPChartColor::Empty; else clrValue.SetFromString(str); } return TRUE; } BOOL AFX_CDECL PX_Font(CXTPPropExchange* pPX, LPCTSTR pszPropName, CXTPChartFont* pFont) { CXTPPropExchangeSection sec(pPX->GetSection(pszPropName)); LOGFONT& lf = pFont->m_lf; CString strFaceName = lf.lfFaceName; int nHeight = lf.lfHeight; int nWeight = lf.lfWeight; PX_String(&sec, _T("FaceName"), strFaceName, _T("Tahoma")); PX_Int(&sec, _T("Height"), nHeight); PX_Int(&sec, _T("Weight"), nWeight, FW_NORMAL); if (!pPX->IsStoring()) { lf.lfHeight = nHeight; lf.lfWeight = nWeight; STRCPY_S(lf.lfFaceName, LF_FACESIZE, strFaceName); } return TRUE; } #ifdef _XTP_ACTIVEX BEGIN_DISPATCH_MAP(CXTPChartFont, CCmdTarget) DISP_PROPERTY_EX_ID(CXTPChartFont, "StdFont", 1, OleGetFont, OleSetFont, VT_DISPATCH) END_DISPATCH_MAP() // {57DBCC77-27BF-4cb1-9ABF-4558D9835223} static const GUID IID_IChartFont = { 0x57dbcc77, 0x27bf, 0x4cb1, { 0x9a, 0xbf, 0x45, 0x58, 0xd9, 0x83, 0x52, 0x23 } }; BEGIN_INTERFACE_MAP(CXTPChartFont, CCmdTarget) INTERFACE_PART(CXTPChartFont, IID_IChartFont, Dispatch) END_INTERFACE_MAP() IMPLEMENT_OLETYPELIB_EX(CXTPChartFont, IID_IChartFont) void CXTPChartFont::OleSetFont(LPFONTDISP pFontDisp) { ASSERT((pFontDisp == NULL) || AfxIsValidAddress(pFontDisp, sizeof(IDispatch), FALSE)); LOGFONT lf; if (AxGetLogFontFromDispatch(&lf, pFontDisp)) { SetLogFont(&lf); } else { } } LPFONTDISP CXTPChartFont::OleGetFont() { return AxCreateOleFont(m_lf, this, (LPFNFONTCHANGED)&CXTPChartFont::OleSetFont); } OLE_COLOR CXTPChartColor::ToOleColor() { if (IsEmpty()) return GetValue(); return RGB(GetR(), GetG(), GetB()); } CXTPChartColor AFX_CDECL CXTPChartColor::FromOleColor(OLE_COLOR clr) { CXTPChartColor res; res.SetFromCOLORREF(AxTranslateColor(clr)); return res; } #endif
40.453682
115
0.697434
11Zero
3f6beebf9679c937728810fac22739c31178c3ec
386
hpp
C++
pythran/pythonic/include/numpy/array_equal.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/numpy/array_equal.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/numpy/array_equal.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_INCLUDE_NUMPY_ARRAYEQUAL_HPP #define PYTHONIC_INCLUDE_NUMPY_ARRAYEQUAL_HPP #include "pythonic/utils/proxy.hpp" #include "pythonic/types/ndarray.hpp" #include "pythonic/numpy/all.hpp" namespace pythonic { namespace numpy { template <class U, class V> bool array_equal(U const &u, V const &v); PROXY_DECL(pythonic::numpy, array_equal); } } #endif
17.545455
45
0.748705
artas360
3f6f7d7f0cdb5415e678aaa66db993794286c42d
1,532
cpp
C++
UnitTests/unit_tests_main.cpp
krulis-martin/Moccarduino
3cb200ea6e3c271a664355ba5a26162fec8ec95d
[ "MIT" ]
1
2021-01-22T00:57:15.000Z
2021-01-22T00:57:15.000Z
UnitTests/unit_tests_main.cpp
krulis-martin/Moccarduino
3cb200ea6e3c271a664355ba5a26162fec8ec95d
[ "MIT" ]
null
null
null
UnitTests/unit_tests_main.cpp
krulis-martin/Moccarduino
3cb200ea6e3c271a664355ba5a26162fec8ec95d
[ "MIT" ]
null
null
null
#include "test.hpp" #include <map> #include <string> #include <iostream> using tests_t = const std::map<std::string, const MoccarduinoTest*>; /** * Check that given test name is on the argument list. * More precisely, whether one of the given keywords (in arguments) is a substring of the name. */ bool on_list(const std::string& name, char* argv[]) { if (*argv == nullptr) return true; // list is empty, let's accept everything ... while (*argv != nullptr && name.find(*argv) == std::string::npos) { ++argv; } return (*argv != nullptr); // not null => match was found } int main(int argc, char* argv[]) { try { tests_t& tests = MoccarduinoTest::getTests(); std::size_t errors = 0, executed = 0; for (tests_t::const_iterator it = tests.begin(); it != tests.end(); ++it) { if (!on_list(it->first, argv + 1)) continue; // argv + 1 ... skip the application name ++executed; std::cout << "TEST: " << it->first << " ... "; std::cout.flush(); try { it->second->run(); std::cout << "passed" << std::endl; } catch (TestException &e) { std::cout << "FAILED!" << std::endl; ++errors; std::cout << e.what() << std::endl; } } std::cout << std::endl << "Total " << (executed-errors) << " / " << executed << " tests passed"; if (errors > 0) { std::cout << ", but " << errors << " tests FAILED!"; } std::cout << std::endl; return errors == 0 ? 0 : 1; } catch (std::exception& e) { std::cerr << "Uncaught exception: " << e.what() << std::endl; return 2; } }
26.413793
98
0.583551
krulis-martin
3f709a87c2abd7e403077a0384c290e058518a91
2,076
cpp
C++
ConsoleLog.cpp
EmuraDaisuke/iostream.OperationCheck
37bc548bca79023cd7d2c99055e923520672ef51
[ "Unlicense" ]
null
null
null
ConsoleLog.cpp
EmuraDaisuke/iostream.OperationCheck
37bc548bca79023cd7d2c99055e923520672ef51
[ "Unlicense" ]
null
null
null
ConsoleLog.cpp
EmuraDaisuke/iostream.OperationCheck
37bc548bca79023cd7d2c99055e923520672ef51
[ "Unlicense" ]
null
null
null
#include <cstdio> #include "./ConsoleLog.h" ConsoleLog::~ConsoleLog() noexcept {} ConsoleLog::ConsoleLog() :mp(ma){} void ConsoleLog::Out() const noexcept { std::puts(ma); std::fflush(stdout); } void ConsoleLog::Put() noexcept { Tail(std::snprintf(Tail(), Size(), " ")); } void ConsoleLog::Put(bool v) noexcept { Tail(std::snprintf(Tail(), Size(), "%d", (v)? 1:0)); } void ConsoleLog::Put(i8 v) noexcept { Tail(std::snprintf(Tail(), Size(), I8, v)); } void ConsoleLog::Put(i16 v) noexcept { Tail(std::snprintf(Tail(), Size(), I16, v)); } void ConsoleLog::Put(i32 v) noexcept { Tail(std::snprintf(Tail(), Size(), I32, v)); } void ConsoleLog::Put(i64 v) noexcept { Tail(std::snprintf(Tail(), Size(), I64, v)); } void ConsoleLog::Put(u8 v) noexcept { Tail(std::snprintf(Tail(), Size(), U8, v)); } void ConsoleLog::Put(u16 v) noexcept { Tail(std::snprintf(Tail(), Size(), U16, v)); } void ConsoleLog::Put(u32 v) noexcept { Tail(std::snprintf(Tail(), Size(), U32, v)); } void ConsoleLog::Put(u64 v) noexcept { Tail(std::snprintf(Tail(), Size(), U64, v)); } void ConsoleLog::Put(float v) noexcept { Tail(std::snprintf(Tail(), Size(), F32, v)); } void ConsoleLog::Put(double v) noexcept { Tail(std::snprintf(Tail(), Size(), F64, v)); } void ConsoleLog::Put(const char* v) noexcept { Tail(std::snprintf(Tail(), Size(), "%s", (v)? v:"")); } void ConsoleLog::Put(const void* v) noexcept { Tail(std::snprintf(Tail(), Size(), "%p", v)); } void ConsoleLog::Put(const std::string& v) noexcept { Tail(std::snprintf(Tail(), Size(), "%s", v.c_str())); } void ConsoleLog::Tail(int s) noexcept { mp += s; } char* ConsoleLog::Tail() const noexcept { return mp; } std::size_t ConsoleLog::Size() const noexcept { return (&ma[sizeof(ma)] - mp); } void ConsoleLog::Log() noexcept {}
56.108108
109
0.551541
EmuraDaisuke
3f75dcee1933da78259b2f3876233847c8c52e56
5,678
cpp
C++
OptiScada/devicemodbusethernet.cpp
optimasiti/optiscada
12a9a49558160649d4ce7c665a85b4fa9d1e1fa2
[ "MIT" ]
2
2020-06-17T13:53:48.000Z
2022-02-19T05:32:46.000Z
OptiScada/devicemodbusethernet.cpp
optimasiti/optiscada
12a9a49558160649d4ce7c665a85b4fa9d1e1fa2
[ "MIT" ]
null
null
null
OptiScada/devicemodbusethernet.cpp
optimasiti/optiscada
12a9a49558160649d4ce7c665a85b4fa9d1e1fa2
[ "MIT" ]
1
2018-11-04T14:03:24.000Z
2018-11-04T14:03:24.000Z
#include <QModbusTcpClient> #include <QDateTime> #include <QThread> #include <QCoreApplication> #include <QVariant> #include <QMutexLocker> #include "writecommand.h" #include "devicemodbusethernet.h" #include "modbuscommon.h" #include "modbusmemory.h" #include "log.h" const int DeviceModbusEthernet::NumberOfRetries = 0; const int DeviceModbusEthernet::MaxReadCount = 20; int DeviceModbusEthernet::get_Id() { return m_Id; } int DeviceModbusEthernet::get_TimeOutMs() { return m_TimeOutMs; } QUrl DeviceModbusEthernet::get_ServerUrl() { return m_ServerUrl; } int DeviceModbusEthernet::get_DeviceNumber() { return m_pMemory->get_DeviceNumber(); } DeviceModbusEthernet::DeviceModbusEthernet( int deviceId, QUrl serverUrl, int timeOutMs ): m_Id( deviceId ), m_TimeOutMs( timeOutMs), m_ServerUrl( serverUrl ) { m_pMemory = new ModbusMemory( deviceId ); m_pModbusClient = nullptr; m_Finish = false; } DeviceModbusEthernet::~DeviceModbusEthernet() { } void DeviceModbusEthernet::Finish() { m_Finish = true; } void DeviceModbusEthernet::TouchAddress( int address ) { for( int i = 0; i < m_RefreshBlocks.size(); i++ ) { if( address >= m_RefreshBlocks.at(i) && address < ( m_RefreshBlocks.at(i) + MaxReadCount ) ) return; } m_RefreshBlocks.append( address ); } bool DeviceModbusEthernet::ReadWords( int startAddress, int count, QVector<quint16> &readValues ) { return m_pMemory->GetValues( startAddress, count, readValues ); } bool DeviceModbusEthernet::ReadBits( int startAddress, int count, QVector<bool> &readValues ) { QVector<quint16> rawValues; if( !m_pMemory->GetValues( startAddress, count, rawValues )) return false; for( int i = 0; i < count; i++ ) readValues.append( rawValues.at(i) > 0 ); return true; } void DeviceModbusEthernet::WriteWords( int startAddress, QVector<quint16> values ) { QMutexLocker locker( &m_WritesMutex); m_Writes.append( new WriteCommand( m_pMemory->get_DeviceNumber(), startAddress, values ) ); } void DeviceModbusEthernet::WriteBits( int startAddress, QVector<bool> values ) { QMutexLocker locker( &m_WritesMutex); QVector<quint16> rawValues; for( int i = 0; i < values.size(); i++ ) rawValues.append( values.at( i )); m_Writes.append( new WriteCommand( m_pMemory->get_DeviceNumber(), startAddress, rawValues ) ); } void DeviceModbusEthernet::UpdateMemory() { if( m_RefreshBlocks.size() == 0 ) { Log::AddLog( Log::Error, QString( "DeviceModbusEthernet::UpdateMemory No tags to Refresh for device %1").arg(m_ServerUrl.url())); return; } while( !m_Finish ) { for( int i = 0; i < m_RefreshBlocks.size(); i++ ) { WriteCommand *pWriteCommand = nullptr; m_WritesMutex.lock(); if( m_Writes.size() > 0 ) { pWriteCommand = m_Writes.first(); m_Writes.removeFirst(); } m_WritesMutex.unlock(); if( !Connect()) { { QDateTime e = QDateTime::currentDateTime().addMSecs(m_TimeOutMs); while(QDateTime::currentDateTime()<e) { QThread::usleep(50000); QCoreApplication::processEvents(); } continue; } } if( pWriteCommand ) { ModbusCommon::ModbusWriteData( m_pModbusClient, pWriteCommand->get_DeviceNumber(), pWriteCommand->get_StartAddress(), pWriteCommand->get_Values(), m_pMemory ); delete pWriteCommand; } else { ModbusCommon::ModbusReadData( m_pModbusClient, m_pMemory->get_DeviceNumber(), m_RefreshBlocks.at(i), MaxReadCount, m_pMemory ); } } } } bool DeviceModbusEthernet::Connect() { if( !m_pModbusClient ) m_pModbusClient = new QModbusTcpClient(this); if( m_pModbusClient->state() == QModbusDevice::ConnectedState ) return true; m_pModbusClient->setConnectionParameter(QModbusDevice::NetworkPortParameter, m_ServerUrl.port() ); m_pModbusClient->setConnectionParameter(QModbusDevice::NetworkAddressParameter, m_ServerUrl.host()); m_pModbusClient->setTimeout(m_TimeOutMs); m_pModbusClient->setNumberOfRetries(NumberOfRetries); if( !m_pModbusClient->connectDevice() ) { Log::AddLog( Log::Warning, QString("DeviceModbusEthernet::Connect Cannot connect to device Host=%1 Port=%2").arg(m_ServerUrl.host()).arg(m_ServerUrl.port())); return false; } QDateTime e = QDateTime::currentDateTime().addMSecs(m_pModbusClient->timeout()); while(QDateTime::currentDateTime()<e) { QThread::usleep(50000); QCoreApplication::processEvents(); if( m_pModbusClient->state() == QModbusDevice::ConnectedState ) { break; } } if( m_pModbusClient->state() != QModbusDevice::ConnectedState) { Log::AddLog( Log::Warning, QString("DeviceModbusEthernet::Connect Cannot connect to device Host=%1 Port=%2").arg(m_ServerUrl.host()).arg(m_ServerUrl.port())); return false; } Log::AddLog( Log::Info, QString("DeviceModbusEthernet::Connect Connection status to device Host=%1 Port=%2 Status=%3").arg(m_ServerUrl.host()).arg(m_ServerUrl.port()).arg(m_pModbusClient->state() == QModbusDevice::ConnectedState)); return m_pModbusClient->state() == QModbusDevice::ConnectedState; } void DeviceModbusEthernet::update() { UpdateMemory(); }
28.248756
235
0.647411
optimasiti
3f8859cc9bfa0f0c363eba2f2d3c47934d73adf0
2,337
cpp
C++
connections/SubunitConn.cpp
PetaVision/ObsoletePV
e99a42bf4292e944b252e144b5e07442b0715697
[ "MIT" ]
null
null
null
connections/SubunitConn.cpp
PetaVision/ObsoletePV
e99a42bf4292e944b252e144b5e07442b0715697
[ "MIT" ]
null
null
null
connections/SubunitConn.cpp
PetaVision/ObsoletePV
e99a42bf4292e944b252e144b5e07442b0715697
[ "MIT" ]
null
null
null
/* * LineSegments.cpp * * Created on: Jan 26, 2009 * Author: rasmussn */ #ifdef OBSOLETE // Use KernelConn or HyperConn and set the param "weightInitType" to "SubUnitWeight" in the params file #include "SubunitConn.hpp" #include "../io/io.h" #include <assert.h> #include <string.h> namespace PV { /** * This connection is for retina to layer with 4 x 16 features. The post-synaptic layer * exhaustively computes presence of a hierarchy of 4 x 2x2 (on/off) patch of pixels * (embedded in a 3x3 pixel patch). */ SubunitConn::SubunitConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, ChannelType channel) { initialize_base(); initialize(name, hc, pre, post, channel, NULL); } /** * Initialize weights to all values of 4 x 2x2 patch */ int SubunitConn::initializeWeights(const char * filename) { assert(post->clayer->loc.nf == 4*16); const int arbor = 0; const int numPatches = numWeightPatches(arbor); for (int i = 0; i < numPatches; i++) { weights(wPatches[arbor][i]); } return 0; } int SubunitConn::weights(PVPatch * wp) { pvdata_t * w = wp->data; const int nx = wp->nx; const int ny = wp->ny; const int nf = wp->nf; const int sx = wp->sx; assert(sx == nf); const int sy = wp->sy; assert(sy == nf*nx); const int sf = wp->sf; assert(sf == 1); assert(nx == 3); assert(ny == 3); assert(nf == 4*16); // TODO - already initialized to zero (so delete) for (int k = 0; k < nx*ny*nf; k++) { w[k] = 0.0; } for (int f = 0; f < nf; f++) { int i0 = 0, j0 = 0; int kf = f / 16; if (kf == 0) {i0 = 0; j0 = 0;} if (kf == 1) {i0 = 1; j0 = 0;} if (kf == 2) {i0 = 0; j0 = 1;} if (kf == 3) {i0 = 1; j0 = 1;} kf = f % 16; for (int j = 0; j < 2; j++) { for (int i = 0; i < 2; i++) { int n = i + 2*j; int r = kf >> n; r = 0x1 & r; w[(i+i0)*sx + (j+j0)*sy + f*sf] = r; } } } // normalize for (int f = 0; f < nf; f++) { float sum = 0; for (int i = 0; i < nx*ny; i++) sum += w[f + i*nf]; if (sum == 0) continue; float factor = 1.0/sum; for (int i = 0; i < nx*ny; i++) w[f + i*nf] *= factor; } return 0; } } // namespace PV #endif
23.138614
119
0.527172
PetaVision
3f8a4210c819759e66bedfe255903cc41b71d932
620
cpp
C++
codes/CodeForces/Round #228/cf388A.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/CodeForces/Round #228/cf388A.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/CodeForces/Round #228/cf388A.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; const int N = 105; int n, cnt[N], tmp; void init () { int a; tmp = 0; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a); tmp = max(a, tmp); cnt[a]++; } } void set(int x, int c) { if (x > tmp) return; if (c > x || cnt[x] == 0) { set(x+1, c); } else { cnt[x]--; set(x, c+1); } } int solve () { int ans = 0; for (int i = 0; i <= tmp; i++) { while (cnt[i]) { set(i, 0); ans++; } } return ans; } int main () { memset(cnt, 0, sizeof(cnt)); init(); printf("%d\n", solve()); return 0; }
12.653061
33
0.480645
JeraKrs
3f94f720768a83a7f4c7a4fe8d4e86404d89f7d9
1,778
cpp
C++
src/dfm/overlay/impl/Message.cpp
dfm-official/dfm
97f133aa87b17c760b90f2358d6ba10bc7ad9d1f
[ "ISC" ]
null
null
null
src/dfm/overlay/impl/Message.cpp
dfm-official/dfm
97f133aa87b17c760b90f2358d6ba10bc7ad9d1f
[ "ISC" ]
null
null
null
src/dfm/overlay/impl/Message.cpp
dfm-official/dfm
97f133aa87b17c760b90f2358d6ba10bc7ad9d1f
[ "ISC" ]
null
null
null
#include <ripple/basics/safe_cast.h> #include <ripple/overlay/Message.h> #include <ripple/overlay/impl/TrafficCount.h> #include <cstdint> namespace ripple { Message::Message (::google::protobuf::Message const& message, int type) { unsigned const messageBytes = message.ByteSize (); assert (messageBytes != 0); mBuffer.resize (kHeaderBytes + messageBytes); encodeHeader (messageBytes, type); if (messageBytes != 0) { message.SerializeToArray (&mBuffer [Message::kHeaderBytes], messageBytes); } mCategory = TrafficCount::categorize(message, type, false); } bool Message::operator== (Message const& other) const { return mBuffer == other.mBuffer; } unsigned Message::getLength (std::vector <uint8_t> const& buf) { unsigned result; if (buf.size () >= Message::kHeaderBytes) { result = buf [0]; result <<= 8; result |= buf [1]; result <<= 8; result |= buf [2]; result <<= 8; result |= buf [3]; } else { result = 0; } return result; } int Message::getType (std::vector<uint8_t> const& buf) { if (buf.size () < Message::kHeaderBytes) return 0; int ret = buf[4]; ret <<= 8; ret |= buf[5]; return ret; } void Message::encodeHeader (unsigned size, int type) { assert (mBuffer.size () >= Message::kHeaderBytes); mBuffer[0] = static_cast<std::uint8_t> ((size >> 24) & 0xFF); mBuffer[1] = static_cast<std::uint8_t> ((size >> 16) & 0xFF); mBuffer[2] = static_cast<std::uint8_t> ((size >> 8) & 0xFF); mBuffer[3] = static_cast<std::uint8_t> (size & 0xFF); mBuffer[4] = static_cast<std::uint8_t> ((type >> 8) & 0xFF); mBuffer[5] = static_cast<std::uint8_t> (type & 0xFF); } }
21.166667
82
0.605174
dfm-official
3fa1e55debd8b766bd7fc91a64b1d93f55cc68d8
855
cpp
C++
Scripts/BasicEnemyAIScript/EnemyStateCooldown.cpp
solidajenjo/Engine
409516f15e0f083e79b749b9c9184f2f04184325
[ "MIT" ]
10
2019-02-25T11:36:23.000Z
2021-11-03T22:51:30.000Z
Scripts/BasicEnemyAIScript/EnemyStateCooldown.cpp
solidajenjo/Engine
409516f15e0f083e79b749b9c9184f2f04184325
[ "MIT" ]
146
2019-02-05T13:57:33.000Z
2019-11-07T16:21:31.000Z
Scripts/BasicEnemyAIScript/EnemyStateCooldown.cpp
FractalPuppy/Engine
409516f15e0f083e79b749b9c9184f2f04184325
[ "MIT" ]
3
2019-11-17T20:49:12.000Z
2020-04-19T17:28:28.000Z
#include "EnemyStateCooldown.h" #include "BasicEnemyAIScript.h" #include "EnemyControllerScript.h" EnemyStateCooldown::EnemyStateCooldown(BasicEnemyAIScript* AIScript) { enemy = AIScript; trigger = "Cooldown"; } EnemyStateCooldown::~EnemyStateCooldown() { } void EnemyStateCooldown::Enter() { enemy->enemyController->LookAt2D(enemy->enemyController->GetPlayerPosition()); } void EnemyStateCooldown::HandleIA() { float distance = enemy->enemyController->GetDistanceToPlayer2D(); if (enemy->scared) { enemy->currentState = (EnemyState*)enemy->flee; } else if (distance > enemy->attackRange) { enemy->currentState = (EnemyState*)enemy->chase; } else if (timer > enemy->cooldownTime) { enemy->currentState = (EnemyState*)enemy->attack; auxTimer = 0.0f; } } void EnemyStateCooldown::Update() { waitedTime = (timer - auxTimer); }
18.586957
79
0.733333
solidajenjo
3faebeed6ed8fac2a6be16787de72cba1aee9bb4
620
cpp
C++
Corpos Editor/NewMapForms.cpp
Tomislaw/corpos
bf971cba98a92b8de68547d4f77252f645c9ef28
[ "MIT" ]
null
null
null
Corpos Editor/NewMapForms.cpp
Tomislaw/corpos
bf971cba98a92b8de68547d4f77252f645c9ef28
[ "MIT" ]
null
null
null
Corpos Editor/NewMapForms.cpp
Tomislaw/corpos
bf971cba98a92b8de68547d4f77252f645c9ef28
[ "MIT" ]
null
null
null
#include "NewMapForms.h" #include "CorposEditor.h" #include "game\utility\Logger.hpp" #include <QErrorMessage> NewMapForms::NewMapForms(CorposEditor *callback) : QWidget() { this->callback = callback; ui.setupUi(this); } NewMapForms::~NewMapForms() { } void NewMapForms::validate(QString v) { if (v.size() != 0)ui.pushButtonCreate->setEnabled(true); else ui.pushButtonCreate->setEnabled(false); } void NewMapForms::createMap() { if (callback != nullptr) { callback->createMap(ui.spinBoxWidth->value(), ui.spinBoxHeight->value(), ui.lineEditMapName->text().toStdString());; this->setVisible(false); } }
20
74
0.719355
Tomislaw
3fb06f4f965f8a72420b08d8ac0828c48b596e48
206
hpp
C++
libs/gfxm/src/gfxm/mat4.hpp
janucaria/Molphene
e5374599512ff4400d04c7c16d79d3a111cc1911
[ "MIT" ]
3
2018-05-18T06:30:48.000Z
2018-09-01T13:59:58.000Z
libs/gfxm/src/gfxm/mat4.hpp
janucaria/Molphene
e5374599512ff4400d04c7c16d79d3a111cc1911
[ "MIT" ]
null
null
null
libs/gfxm/src/gfxm/mat4.hpp
janucaria/Molphene
e5374599512ff4400d04c7c16d79d3a111cc1911
[ "MIT" ]
null
null
null
#ifndef MOLPHENE_GFXM_MAT4_HPP #define MOLPHENE_GFXM_MAT4_HPP #include <cppid/gm3d/mat4.hpp> namespace molphene { template<typename T> using mat4 = cppid::gm3d::mat4<T>; } // namespace molphene #endif
14.714286
34
0.76699
janucaria
3fb3d4e77d8aece08c63d24c0fd9264f9a8a1aad
7,346
cpp
C++
GLES3Renderer/GLES3Renderer/GfxProgram.cpp
LiangYue1981816/CrossEngine-GLES3Renderer
8d092307c22164895c4f92395ef291c87f2811e6
[ "Apache-2.0" ]
null
null
null
GLES3Renderer/GLES3Renderer/GfxProgram.cpp
LiangYue1981816/CrossEngine-GLES3Renderer
8d092307c22164895c4f92395ef291c87f2811e6
[ "Apache-2.0" ]
null
null
null
GLES3Renderer/GLES3Renderer/GfxProgram.cpp
LiangYue1981816/CrossEngine-GLES3Renderer
8d092307c22164895c4f92395ef291c87f2811e6
[ "Apache-2.0" ]
1
2020-09-17T12:24:42.000Z
2020-09-17T12:24:42.000Z
#include "stdio.h" #include "stdlib.h" #include "GfxUtils.h" #include "GfxRenderer.h" static size_t fsize(FILE *stream) { long pos; size_t size; pos = ftell(stream); { fseek(stream, 0, SEEK_END); size = ftell(stream); } fseek(stream, pos, SEEK_SET); return size; } static std::string LoadShader(const char *szFileName) { if (FILE *pFile = fopen(szFileName, "rb")) { static char szSource[128 * 1024]; size_t size = fsize(pFile); fread(szSource, 1, size, pFile); fclose(pFile); return szSource; } return ""; } static std::vector<GLuint> LoadShaderBinary(const char *szFileName) { std::vector<GLuint> words; if (FILE *pFile = fopen(szFileName, "rb")) { size_t size = fsize(pFile); words.resize(size / sizeof(GLuint)); fread(words.data(), sizeof(GLuint), words.size(), pFile); fclose(pFile); } return words; } CGfxProgram::CGfxProgram(void) : m_program(0) , m_vertexShader(0) , m_fragmentShader(0) , m_pShaderCompilers{ NULL } { } CGfxProgram::~CGfxProgram(void) { Free(); } bool CGfxProgram::Load(const char *szVertexFileName, const char *szFragmentFileName) { try { Free(); if (LoadShader(szVertexFileName, GL_VERTEX_SHADER, m_vertexShader, m_pShaderCompilers[0]) == false) throw 0; if (LoadShader(szFragmentFileName, GL_FRAGMENT_SHADER, m_fragmentShader, m_pShaderCompilers[1]) == false) throw 1; if (CreateProgram() == false) throw 2; if (CreateLocations() == false) throw 3; return true; } catch (int) { Free(); return false; } } bool CGfxProgram::LoadShader(const char *szFileName, GLenum type, GLuint &shader, spirv_cross::CompilerGLSL *&pShaderCompiler) { shader = 0; pShaderCompiler = NULL; char szFullPath[260]; CGfxRenderer::GetInstance()->GetShaderFullPath(szFileName, szFullPath); std::vector<GLuint> words = LoadShaderBinary(szFullPath); pShaderCompiler = new spirv_cross::CompilerGLSL(words.data(), words.size()); spirv_cross::CompilerGLSL::Options options; options.version = 310; options.es = true; options.vertex.fixup_clipspace = false; pShaderCompiler->set_options(options); const std::string strSource = pShaderCompiler->compile(); const char *szSource[1] = { strSource.c_str() }; shader = glCreateShader(type); glShaderSource(shader, 1, szSource, NULL); glCompileShader(shader); GLint success; glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (success == GL_FALSE) { static char szError[128 * 1024]; GLsizei length = 0; memset(szError, sizeof(szError), 0); glGetShaderInfoLog(shader, sizeof(szError), &length, szError); LogOutput("Shader: %s\n", szFileName); LogOutput("%s\n", strSource.c_str()); LogOutput("Compile Error:\n"); LogOutput("%s\n", szError); } return success == GL_TRUE; } bool CGfxProgram::CreateProgram(void) { m_program = glCreateProgram(); glAttachShader(m_program, m_vertexShader); glAttachShader(m_program, m_fragmentShader); glLinkProgram(m_program); GLint success; glGetProgramiv(m_program, GL_LINK_STATUS, &success); if (success == GL_FALSE) { static char szError[128 * 1024]; GLsizei length = 0; memset(szError, sizeof(szError), 0); glGetProgramInfoLog(m_program, sizeof(szError), &length, szError); LogOutput("Program Link Error:\n"); LogOutput("%s\n", szError); } return success == GL_TRUE; } bool CGfxProgram::CreateLocations(void) { for (int index = 0; index < 2; index++) { const spirv_cross::ShaderResources shaderResources = m_pShaderCompilers[index]->get_shader_resources(); for (const auto &itUniform : shaderResources.uniform_buffers) { if (m_pShaderCompilers[index]->get_type(itUniform.type_id).basetype == spirv_cross::SPIRType::Struct) { SetUniformLocation(itUniform.name.c_str()); } } for (const auto &itSampledImage : shaderResources.sampled_images) { if (m_pShaderCompilers[index]->get_type(itSampledImage.type_id).basetype == spirv_cross::SPIRType::SampledImage) { SetTextureLocation(itSampledImage.name.c_str()); } } } return true; } void CGfxProgram::Free(void) { if (m_program) { glDeleteProgram(m_program); } if (m_vertexShader) { glDeleteShader(m_vertexShader); } if (m_fragmentShader) { glDeleteShader(m_fragmentShader); } if (m_pShaderCompilers[0]) { delete m_pShaderCompilers[0]; } if (m_pShaderCompilers[1]) { delete m_pShaderCompilers[1]; } m_program = 0; m_vertexShader = 0; m_fragmentShader = 0; m_pShaderCompilers[0] = NULL; m_pShaderCompilers[1] = NULL; m_names.clear(); m_uniformBlockLocations.clear(); m_sampledImageLocations.clear(); } bool CGfxProgram::SetUniformLocation(const char *szName) { GLuint name = HashValue(szName); if (m_uniformBlockLocations.find(name) == m_uniformBlockLocations.end()) { GLuint location = glGetUniformBlockIndex(m_program, szName); if (location != GL_INVALID_INDEX) { m_names[name] = szName; m_uniformBlockLocations[name] = location; glUniformBlockBinding(m_program, location, location); return true; } } return false; } bool CGfxProgram::SetTextureLocation(const char *szName) { GLuint name = HashValue(szName); if (m_sampledImageLocations.find(name) == m_sampledImageLocations.end()) { GLuint location = glGetUniformLocation(m_program, szName); if (location != GL_INVALID_INDEX) { m_names[name] = szName; m_sampledImageLocations[name] = location; return true; } } return false; } void CGfxProgram::UseProgram(void) const { glUseProgram(m_program); } bool CGfxProgram::BindUniformBuffer(GLuint name, GLuint buffer, GLsizeiptr size, GLintptr offset) const { const auto &itLocation = m_uniformBlockLocations.find(name); if (itLocation != m_uniformBlockLocations.end()) { glBindBufferRange(GL_UNIFORM_BUFFER, itLocation->second, buffer, offset, size); return true; } return false; } bool CGfxProgram::BindTexture2D(GLuint name, GLuint texture, GLuint sampler, GLuint unit) const { const auto &itLocation = m_sampledImageLocations.find(name); if (itLocation != m_sampledImageLocations.end()) { glActiveTexture(GL_TEXTURE0 + unit); glBindSampler(unit, sampler); glBindTexture(GL_TEXTURE_2D, texture); glUniform1i(itLocation->second, unit); return true; } return false; } bool CGfxProgram::BindTextureArray(GLuint name, GLuint texture, GLuint sampler, GLuint unit) const { const auto &itLocation = m_sampledImageLocations.find(name); if (itLocation != m_sampledImageLocations.end()) { glActiveTexture(GL_TEXTURE0 + unit); glBindSampler(unit, sampler); glBindTexture(GL_TEXTURE_2D_ARRAY, texture); glUniform1i(itLocation->second, unit); return true; } return false; } bool CGfxProgram::BindTextureCubeMap(GLuint name, GLuint texture, GLuint sampler, GLuint unit) const { const auto &itLocation = m_sampledImageLocations.find(name); if (itLocation != m_sampledImageLocations.end()) { glActiveTexture(GL_TEXTURE0 + unit); glBindSampler(unit, sampler); glBindTexture(GL_TEXTURE_CUBE_MAP, texture); glUniform1i(itLocation->second, unit); return true; } return false; } bool CGfxProgram::IsValid(void) const { return m_program != 0; } bool CGfxProgram::IsUniformValid(GLuint name) const { return m_uniformBlockLocations.find(name) != m_uniformBlockLocations.end(); } bool CGfxProgram::IsTextureValid(GLuint name) const { return m_sampledImageLocations.find(name) != m_sampledImageLocations.end(); }
23.246835
126
0.73278
LiangYue1981816
3fb92271a4a10900af54b35b778c0fcf7c6a7836
1,287
cpp
C++
D3D11-Engine/src/VertexBuffer.cpp
BEASTSM96/D3D11
d5bad6fb06ff0cba04df4422094425e29b95fdce
[ "MIT" ]
null
null
null
D3D11-Engine/src/VertexBuffer.cpp
BEASTSM96/D3D11
d5bad6fb06ff0cba04df4422094425e29b95fdce
[ "MIT" ]
null
null
null
D3D11-Engine/src/VertexBuffer.cpp
BEASTSM96/D3D11
d5bad6fb06ff0cba04df4422094425e29b95fdce
[ "MIT" ]
null
null
null
#include "VertexBuffer.h" #include "RendererContext.h" VertexBuffer::~VertexBuffer() { } void VertexBuffer::Load( ID3D11Device* pDevice, void* pListVertices, uint32_t SizeVertex, uint32_t SizeList, void* ShaderByteCode, uint32_t SizeOfShader ) { SAFE_RELEASE( m_pLayout ); SAFE_RELEASE( m_pBuffer ); D3D11_BUFFER_DESC BufferDesc = {}; // GPU, Read and Write. BufferDesc.Usage = D3D11_USAGE_DEFAULT; // Size in bytes. BufferDesc.ByteWidth = SizeVertex * SizeList; // Bind as a vertex buffer. BufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; BufferDesc.CPUAccessFlags = 0; BufferDesc.MiscFlags = 0; D3D11_SUBRESOURCE_DATA SubResData = {}; SubResData.pSysMem = pListVertices; m_SizeVertex = SizeVertex; m_SizeList = SizeList; D3D_CHECK( pDevice->CreateBuffer( &BufferDesc, &SubResData, &m_pBuffer ) ); // NAME - INDEX - FORMAT - SLOT - BYTE OFFSET - SLOT CLASS - DATA STEP RATE std::vector<D3D11_INPUT_ELEMENT_DESC> Layouts; Layouts.push_back( { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 } ); D3D_CHECK( pDevice->CreateInputLayout( Layouts.data(), Layouts.size(), ShaderByteCode, SizeOfShader, &m_pLayout ) ); } void VertexBuffer::Terminate() { SAFE_RELEASE( m_pLayout ); SAFE_RELEASE( m_pBuffer ); delete this; }
27.382979
154
0.750583
BEASTSM96
3fbc2717f64d5d5cd6078e8a143be49ce15eb69e
4,297
cc
C++
src/third_party/ceres/internal/ceres/cxsparse.cc
paulinus/libmv
6656bde5aea4c715695fa98fca6e2b3417e82d76
[ "MIT" ]
null
null
null
src/third_party/ceres/internal/ceres/cxsparse.cc
paulinus/libmv
6656bde5aea4c715695fa98fca6e2b3417e82d76
[ "MIT" ]
null
null
null
src/third_party/ceres/internal/ceres/cxsparse.cc
paulinus/libmv
6656bde5aea4c715695fa98fca6e2b3417e82d76
[ "MIT" ]
null
null
null
// Ceres Solver - A fast non-linear least squares minimizer // Copyright 2012 Google Inc. All rights reserved. // http://code.google.com/p/ceres-solver/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Google Inc. nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Author: strandmark@google.com (Petter Strandmark) #ifndef CERES_NO_CXSPARSE #include "ceres/cxsparse.h" #include "ceres/compressed_row_sparse_matrix.h" #include "ceres/triplet_sparse_matrix.h" #include "glog/logging.h" namespace ceres { namespace internal { CXSparse::CXSparse() : scratch_(NULL), scratch_size_(0) { } CXSparse::~CXSparse() { if (scratch_size_ > 0) { cs_free(scratch_); } } bool CXSparse::SolveCholesky(cs_di* A, cs_dis* symbolic_factorization, double* b) { // Make sure we have enough scratch space available. if (scratch_size_ < A->n) { if (scratch_size_ > 0) { cs_free(scratch_); } scratch_ = reinterpret_cast<CS_ENTRY*>(cs_malloc(A->n, sizeof(CS_ENTRY))); scratch_size_ = A->n; } // Solve using Cholesky factorization csn* numeric_factorization = cs_chol(A, symbolic_factorization); if (numeric_factorization == NULL) { LOG(WARNING) << "Cholesky factorization failed."; return false; } // When the Cholesky factorization succeeded, these methods are guaranteed to // succeeded as well. In the comments below, "x" refers to the scratch space. // // Set x = P * b. cs_ipvec(symbolic_factorization->pinv, b, scratch_, A->n); // Set x = L \ x. cs_lsolve(numeric_factorization->L, scratch_); // Set x = L' \ x. cs_ltsolve(numeric_factorization->L, scratch_); // Set b = P' * x. cs_pvec(symbolic_factorization->pinv, scratch_, b, A->n); // Free Cholesky factorization. cs_nfree(numeric_factorization); return true; } cs_dis* CXSparse::AnalyzeCholesky(cs_di* A) { // order = 1 for Cholesky factorization. return cs_schol(1, A); } cs_di CXSparse::CreateSparseMatrixTransposeView(CompressedRowSparseMatrix* A) { cs_di At; At.m = A->num_cols(); At.n = A->num_rows(); At.nz = -1; At.nzmax = A->num_nonzeros(); At.p = A->mutable_rows(); At.i = A->mutable_cols(); At.x = A->mutable_values(); return At; } cs_di* CXSparse::CreateSparseMatrix(TripletSparseMatrix* tsm) { cs_di_sparse tsm_wrapper; tsm_wrapper.nzmax = tsm->num_nonzeros();; tsm_wrapper.nz = tsm->num_nonzeros();; tsm_wrapper.m = tsm->num_rows(); tsm_wrapper.n = tsm->num_cols(); tsm_wrapper.p = tsm->mutable_cols(); tsm_wrapper.i = tsm->mutable_rows(); tsm_wrapper.x = tsm->mutable_values(); return cs_compress(&tsm_wrapper); } void CXSparse::Free(cs_di* sparse_matrix) { cs_di_spfree(sparse_matrix); } void CXSparse::Free(cs_dis* symbolic_factorization) { cs_di_sfree(symbolic_factorization); } } // namespace internal } // namespace ceres #endif // CERES_NO_CXSPARSE
32.55303
79
0.716779
paulinus
3fd307884189101b6e36e37392332c1047accef6
240
cpp
C++
Valtrook/Valtrook/FileWriter.cpp
animeenginedev/Valtrook
10cf7332643765534f8a4263cc4e422c4356487b
[ "MIT" ]
null
null
null
Valtrook/Valtrook/FileWriter.cpp
animeenginedev/Valtrook
10cf7332643765534f8a4263cc4e422c4356487b
[ "MIT" ]
null
null
null
Valtrook/Valtrook/FileWriter.cpp
animeenginedev/Valtrook
10cf7332643765534f8a4263cc4e422c4356487b
[ "MIT" ]
null
null
null
#include "FileWriter.h" namespace Val { FileWriter::FileWriter(std::string path, std::string name) { File.open((path + name).c_str(), std::fstream::out); } FileWriter::~FileWriter() { if (File.is_open()) { File.close(); } } }
18.461538
61
0.633333
animeenginedev
3fdc25e71d5680c48f0be18d03feb358ef98da5b
3,023
cc
C++
src/ui/layout_engine_test.cc
ambuc/latis
bab48431a563619cdb2d8dfee3fd588e98ff255f
[ "Apache-2.0" ]
1
2020-05-03T18:18:39.000Z
2020-05-03T18:18:39.000Z
src/ui/layout_engine_test.cc
ambuc/latis
bab48431a563619cdb2d8dfee3fd588e98ff255f
[ "Apache-2.0" ]
null
null
null
src/ui/layout_engine_test.cc
ambuc/latis
bab48431a563619cdb2d8dfee3fd588e98ff255f
[ "Apache-2.0" ]
1
2020-04-18T01:57:07.000Z
2020-04-18T01:57:07.000Z
// Copyright 2020 Google LLC // // 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 "src/ui/layout_engine.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace latis { namespace ui { namespace { using ::testing::AllOf; using ::testing::DoubleEq; using ::testing::Eq; using ::testing::Field; using ::testing::Le; using ::testing::MockFunction; using ::testing::Not; using ::testing::Optional; using ::testing::StrictMock; class LayoutEngineTestBase : public ::testing::Test { public: LayoutEngineTestBase() : h_(10), w_(8), e_(/*y=*/h_, /*x=*/w_) {} protected: const int h_; const int w_; LayoutEngine e_; }; TEST_F(LayoutEngineTestBase, TooTall) { // too tall EXPECT_EQ(e_.Place(h_ + 1, 1), absl::nullopt); // just right EXPECT_NE(e_.Place(h_, 1), absl::nullopt); } TEST_F(LayoutEngineTestBase, TooWide) { // too wide EXPECT_EQ(e_.Place(1, w_ + 1), absl::nullopt); // just right EXPECT_NE(e_.Place(1, w_), absl::nullopt); } TEST_F(LayoutEngineTestBase, Placements) { { // AAAA Dimensions d = e_.Place(1, 4).value(); EXPECT_EQ(d.nlines, 1); EXPECT_EQ(d.ncols, 4); EXPECT_EQ(d.begin_y, 0); EXPECT_EQ(d.begin_x, 0); } { // AAAABBBB Dimensions d = e_.Place(1, 4).value(); EXPECT_EQ(d.nlines, 1); EXPECT_EQ(d.ncols, 4); EXPECT_EQ(d.begin_y, 0); EXPECT_EQ(d.begin_x, 4); } { // AAAABBBB // CCC Dimensions d = e_.Place(1, 3).value(); EXPECT_EQ(d.nlines, 1); EXPECT_EQ(d.ncols, 3); EXPECT_EQ(d.begin_y, 1); EXPECT_EQ(d.begin_x, 0); } { // AAAABBBB // CCCDDD // DDD Dimensions d = e_.Place(2, 3).value(); EXPECT_EQ(d.nlines, 2); EXPECT_EQ(d.ncols, 3); EXPECT_EQ(d.begin_y, 1); EXPECT_EQ(d.begin_x, 3); } { // AAAABBBB // CCCDDD // EEEDDD // EEE Dimensions d = e_.Place(2, 3).value(); EXPECT_EQ(d.nlines, 2); EXPECT_EQ(d.ncols, 3); EXPECT_EQ(d.begin_y, 2); EXPECT_EQ(d.begin_x, 0); } { // AAAABBBB // CCCDDDFF // EEEDDDFF // EEE Dimensions d = e_.Place(2, 2).value(); EXPECT_EQ(d.nlines, 2); EXPECT_EQ(d.ncols, 2); EXPECT_EQ(d.begin_y, 1); EXPECT_EQ(d.begin_x, 6); } { // AAAABBBB // CCCDDDFF // EEEDDDFF // EEEGGG // GGG Dimensions d = e_.Place(2, 3).value(); EXPECT_EQ(d.nlines, 2); EXPECT_EQ(d.ncols, 3); EXPECT_EQ(d.begin_y, 3); EXPECT_EQ(d.begin_x, 3); } } } // namespace } // namespace ui } // namespace latis
21.592857
75
0.62653
ambuc
3fdf086c232b4352780aadbe15c57d18d379b67a
433
cpp
C++
CAPSONGTO.cpp
phuongnam2002/testlib
a5cb8e2be7ac7a7e7dca7942a79ec20076f5d1aa
[ "MIT" ]
2
2022-01-14T13:34:09.000Z
2022-02-21T07:27:29.000Z
CAPSONGTO.cpp
phuongnam2002/testlib
a5cb8e2be7ac7a7e7dca7942a79ec20076f5d1aa
[ "MIT" ]
null
null
null
CAPSONGTO.cpp
phuongnam2002/testlib
a5cb8e2be7ac7a7e7dca7942a79ec20076f5d1aa
[ "MIT" ]
null
null
null
#include<stdio.h> #include<math.h> typedef long long ll; const int N=1e6+3; int ngto(int n) { if(n<2) return 0; for(int i=2;i*i<=n;i++) { if(n%i==0) return 0; } return 1; } void xuly() { int n; scanf("%d",&n); for(int i=2;i<=n/2;i++) { int x=n-i; if(ngto(i)&&ngto(x)) printf("%d %d ",i,x); } printf("\n"); } int main() { int t; scanf("%d",&t); while(t--) xuly(); return 0; }
13.121212
45
0.482679
phuongnam2002
3fe3fdac0407e52cd049ebc21eac11bde4903faa
283
cpp
C++
KeshUI/Public/KeshUI/KUICancellable.cpp
Daekesh/KeshUI
9cae4a74aab5bd33c526fedcb76264a66414a0dd
[ "MIT" ]
19
2015-03-12T20:30:42.000Z
2021-12-08T18:33:25.000Z
KeshUI/Public/KeshUI/KUICancellable.cpp
Daekesh/KeshUI
9cae4a74aab5bd33c526fedcb76264a66414a0dd
[ "MIT" ]
4
2015-03-14T12:26:54.000Z
2016-04-21T12:51:02.000Z
KeshUI/Public/KeshUI/KUICancellable.cpp
Daekesh/KeshUI
9cae4a74aab5bd33c526fedcb76264a66414a0dd
[ "MIT" ]
10
2015-03-12T15:04:06.000Z
2020-06-30T18:52:26.000Z
// Copyright 2014-2015 Matt Chapman. All Rights Reserved. #include "KeshUI/KeshUI.h" #include "KeshUI/KUICancellable.h" UKUICancellable::UKUICancellable( const class FObjectInitializer& oObjectInitializer ) : Super(oObjectInitializer) { } void IKUICancellable::Cancel() { }
14.894737
86
0.766784
Daekesh
684762ce8154c0bc3e6535b5db5e10f811b8c3de
2,344
cpp
C++
src/Engine/PieceTypes/ToriShogi/Goose.cpp
jweathers777/mShogi
941cd4dc37e6e6210d4f993c96a553753e228b19
[ "BSD-3-Clause" ]
4
2015-12-24T04:52:48.000Z
2021-11-09T11:31:36.000Z
src/Engine/PieceTypes/ToriShogi/Goose.cpp
jweathers777/mShogi
941cd4dc37e6e6210d4f993c96a553753e228b19
[ "BSD-3-Clause" ]
null
null
null
src/Engine/PieceTypes/ToriShogi/Goose.cpp
jweathers777/mShogi
941cd4dc37e6e6210d4f993c96a553753e228b19
[ "BSD-3-Clause" ]
null
null
null
//////////////////////////////////////////////////////////////////////////// // Name: Goose.cpp // Description: Implementation for a class that represents a goose // Created: 10/20/2004 01:21:22 Eastern Standard Time // Last Updated: $Date$ // Revision: $Revision$ // Author: John Weathers // Email: hotanguish@hotmail.com // Copyright: (c) 2004 John Weathers //////////////////////////////////////////////////////////////////////////// // mShogi header files #include "Goose.hpp" #include "Piece.hpp" #include "Move.hpp" #include "Board.hpp" using std::vector; using std::string; //-------------------------------------------------------------------------- // Class: Goose // Method: Goose // Description: Constructs an instance of a pawn //-------------------------------------------------------------------------- Goose::Goose(Board* board, int value, int typevalue) { mpBoard = board; mValue = value; mTypeValue = typevalue; mSize = mpBoard->GetSize(); mNotation = "Go"; mNames[0] = "Goose"; mNames[1] = "Kari"; //mNames[0] = "Goose"; mNames[1] = "Gan"; mDescription = "Jumps to the second square in the forward diagonally or backwards"; int finish; // Initialize the goose's attack patterns for (int color = 0; color < 2; color++) { mAttackBitboards[color] = new Bitboard [mSize]; for (int start = 0; start < mSize; start++) { // northwest jump finish = mpBoard->NorthWest(color, start); if (finish != Board::OFF_BOARD) { finish = mpBoard->NorthWest(color, start); if (finish != Board::OFF_BOARD) { mAttackBitboards[start].set(finish); } } // northeast jump finish = mpBoard->NorthEast(color, start); if (finish != Board::OFF_BOARD) { finish = mpBoard->NorthEast(color, start); if (finish != Board::OFF_BOARD) { mAttackBitboards[start].set(finish); } } // south jump finish = mpBoard->South(color, start); if (finish != Board::OFF_BOARD) { finish = mpBoard->South(color, start); if (finish != Board::OFF_BOARD) { mAttackBitboards[start].set(finish); } } } } }
32.109589
86
0.49616
jweathers777
6848bd5c1fa06b3f96ad6e7c5cc1f6c278def6ee
5,081
hpp
C++
GardenVexor/src/map/gridmap.hpp
kalsipp/vsxpanse
7887d234312283ce1ace03bed610642b0c6f96b1
[ "MIT" ]
null
null
null
GardenVexor/src/map/gridmap.hpp
kalsipp/vsxpanse
7887d234312283ce1ace03bed610642b0c6f96b1
[ "MIT" ]
null
null
null
GardenVexor/src/map/gridmap.hpp
kalsipp/vsxpanse
7887d234312283ce1ace03bed610642b0c6f96b1
[ "MIT" ]
null
null
null
#pragma once #include <map> #include <basics/vector2dint.hpp> #include "gameobject.hpp" #include "filesystem/resourcearchive.hpp" #define GRIDMAPSIZE 1024 #define GRIDTILESIZE 32 /*------------------------------------------------------- Represents a tile in the GridMap. ---------------------------------------------------------*/ class TileInfo { public: bool is_free()const; void register_agent(GameObject * obj, bool solid); void deregister_agent(GameObject * obj, bool solid); private: void register_solid_object(); void deregister_solid_object(); std::vector<GameObject*> m_gameobjects; int m_solidness; const int FREE_POSITION = 0; }; /*------------------------------------------------------- Contains the playable map organized in a square tile pattern Each position contains a MapTile ---------------------------------------------------------*/ class GridMap { public: static void initialize(ResourceArchive * archive); static void teardown(); /*------------------------------------ Move unit in grid. Returns true if the unit could move. -------------------------------------- Returns: bool, if the unit was able to move. false may indicate trying to move into a solid object. Parameter: GameObject * unit, unit to move. Parameter: const Vector2DInt & to, where to move Parameter: bool solid, if the unit is regarded as solid. ------------------------------------*/ static bool move_unit(GameObject * unit, const Vector2DInt & pixelpos_to, bool solid); static void register_unit(GameObject * const unit, bool solid); static void register_unit(GameObject * const unit, const Vector2DInt & pixelpos, bool solid); static TileInfo * const get_tileinfo(const Vector2DInt & gridpos); /*------------------------------------------------------- Gets the smallest x-position (inclusive) of the GridMap. ---------------------------------------------------------*/ static int get_min_x(); /*------------------------------------------------------- Gets the smallest y-position (inclusive) of the GridMap. ---------------------------------------------------------*/ static int get_min_y(); /*------------------------------------------------------- Gets the greatest x-position (exclusive) of the GridMap. ---------------------------------------------------------*/ static int get_max_x(); /*------------------------------------------------------- Gets the greatest y-position (exclusive) of the GridMap. ---------------------------------------------------------*/ static int get_max_y(); /*------------------------------------------------------- Get if the tile is currently impassable. ---------------------------------------------------------*/ static bool get_if_tile_is_free(const Vector2DInt & gridpos); /*------------------------------------------------------- Get if the position is within GridMap boundaries. ---------------------------------------------------------*/ static bool get_if_position_in_gridmap(const Vector2DInt & gridpos); /*------------------------------------------------------- Get size of the GridMap. ---------------------------------------------------------*/ static const Vector2DInt & get_size(); /*------------------------------------------------------- PixelSpace vs GridSpace: Each tile in the grid represents a square area. So if your unit is at tile (2,2) what does that translate to in real pixels? Here it's determined by the GRIDTILESIZE. If the GRIDTILESIZE is 32: tile(2,2) is at PixelSpace (64, 64). tile(-2,-2) is at PixelSpace (-64, -64). Note: PixelSpace does not take into account any offset that a camera may provide, so PixelSpace (64, 64) can still be outside your 1920x1080 screen, if any offset is applied. ---------------------------------------------------------*/ /*------------------------------------------------------- Converts a position from PixelSpace to GridSpace. e.g. with GRIDTILESIZE = 32 PixelSpace(0,0) = GridSpace(0,0) PixelSpace(1,1) = GridSpace(0,0) PixelSpace(31,31) = GridSpace(0,0) PixelSpace(32,32) = GridSpace(1,1) PixelSpace(-1,-1) = GridSpace(-1,-1) PixelSpace(-32,-32) = GridSpace(-1,-1) PixelSpace(-33,-33) = GridSpace(-2,-2) ---------------------------------------------------------*/ static Vector2DInt pixelspace_to_gridspace(const Vector2DInt & pixelpos); static int pixelspace_to_gridspace(int value); /*------------------------------------------------------- Converts a position from GridSpace to PixelSpace. e.g. with GRIDTILESIZE = 32 GridSpace(0,0) = PixelSpace(0,0) GridSpace(1,1) = PixelSpace(32,32) GridSpace(2,2) = PixelSpace(64,64) GridSpace(-1,-1) = PixelSpace(-32,-32) GridSpace(-2,-2) = PixelSpace(-64,-64) ---------------------------------------------------------*/ static Vector2DInt gridspace_to_pixelspace(const Vector2DInt & gridpos); static int gridspace_to_pixelspace(int value); private: GridMap() {} static Vector2DInt m_size; static void generate_resources(ResourceArchive * archive); static bool m_initialized; static TileInfo *** m_objects; };
36.553957
94
0.522338
kalsipp
684af639f7df4f21ea3683a94026921b6585f1d1
2,443
hpp
C++
include/codegen/include/Microsoft/Win32/IRegistryApi.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/Microsoft/Win32/IRegistryApi.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/Microsoft/Win32/IRegistryApi.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:09:38 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: Microsoft::Win32 namespace Microsoft::Win32 { // Forward declaring type: RegistryKey class RegistryKey; // Forward declaring type: RegistryValueOptions struct RegistryValueOptions; } // Forward declaring namespace: System namespace System { // Forward declaring type: IntPtr struct IntPtr; } // Completed forward declares // Type namespace: Microsoft.Win32 namespace Microsoft::Win32 { // Autogenerated type: Microsoft.Win32.IRegistryApi class IRegistryApi { public: // public Microsoft.Win32.RegistryKey OpenSubKey(Microsoft.Win32.RegistryKey rkey, System.String keyname, System.Boolean writtable) // Offset: 0xFFFFFFFF Microsoft::Win32::RegistryKey* OpenSubKey(Microsoft::Win32::RegistryKey* rkey, ::Il2CppString* keyname, bool writtable); // public System.Void Flush(Microsoft.Win32.RegistryKey rkey) // Offset: 0xFFFFFFFF void Flush(Microsoft::Win32::RegistryKey* rkey); // public System.Void Close(Microsoft.Win32.RegistryKey rkey) // Offset: 0xFFFFFFFF void Close(Microsoft::Win32::RegistryKey* rkey); // public System.Object GetValue(Microsoft.Win32.RegistryKey rkey, System.String name, System.Object default_value, Microsoft.Win32.RegistryValueOptions options) // Offset: 0xFFFFFFFF ::Il2CppObject* GetValue(Microsoft::Win32::RegistryKey* rkey, ::Il2CppString* name, ::Il2CppObject* default_value, Microsoft::Win32::RegistryValueOptions options); // public System.String[] GetSubKeyNames(Microsoft.Win32.RegistryKey rkey) // Offset: 0xFFFFFFFF ::Array<::Il2CppString*>* GetSubKeyNames(Microsoft::Win32::RegistryKey* rkey); // public System.String ToString(Microsoft.Win32.RegistryKey rkey) // Offset: 0xFFFFFFFF ::Il2CppString* ToString(Microsoft::Win32::RegistryKey* rkey); // public System.IntPtr GetHandle(Microsoft.Win32.RegistryKey key) // Offset: 0xFFFFFFFF System::IntPtr GetHandle(Microsoft::Win32::RegistryKey* key); }; // Microsoft.Win32.IRegistryApi } DEFINE_IL2CPP_ARG_TYPE(Microsoft::Win32::IRegistryApi*, "Microsoft.Win32", "IRegistryApi"); #pragma pack(pop)
45.240741
167
0.732296
Futuremappermydud
684e2b47b849f28f4194e97003916a5436e67a0b
2,376
hpp
C++
src/Engine/MoveGenerator.hpp
jweathers777/mShogi
941cd4dc37e6e6210d4f993c96a553753e228b19
[ "BSD-3-Clause" ]
4
2015-12-24T04:52:48.000Z
2021-11-09T11:31:36.000Z
src/Engine/MoveGenerator.hpp
jweathers777/mShogi
941cd4dc37e6e6210d4f993c96a553753e228b19
[ "BSD-3-Clause" ]
null
null
null
src/Engine/MoveGenerator.hpp
jweathers777/mShogi
941cd4dc37e6e6210d4f993c96a553753e228b19
[ "BSD-3-Clause" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Name: MoveGenerator.hpp // Description: Interface for class that generates moves for a board position // Created: Apr 20, 2004 11:43:23 AM // Author: John Weathers // Email: hotanguish@hotmail.com // Copyright: (c) 2004 John Weathers //////////////////////////////////////////////////////////////////////////////// #ifndef MOVEGENERATOR_HPP #define MOVEGENERATOR_HPP // STL header files #include <vector> // Boost header files #include <boost/dynamic_bitset.hpp> // mShogi header files #include "common.hpp" // Forward declarations class Game; class Move; class Piece; class MoveGenerator { public: // ====================================================================== // Construction and destruction // ====================================================================== MoveGenerator(Game* game, int piececount); ~MoveGenerator(); // ====================================================================== // Operations // ====================================================================== void GenerateMoves(std::vector<Move>& movelist, int side); Move* GetNextMove(std::vector<Move>& movelist, int& phase, int side, Move* hashmove=0); Move* GetNextCapture(std::vector<Move>& movelist, int& phase, int side); void CheckForPromotions(std::vector<Move>& movelist, int side); void CalculateSortValues(std::vector<Move>& movelist); // ====================================================================== // Constants // ====================================================================== enum { PROCESS_HASH_MOVE = 0, GENERATE_CAPTURES, RETURN_CAPTURES, GENERATE_DROPS, RETURN_DROPS, GENERATE_NONCAPTURES, RETURN_NONCAPTURES }; private: // ====================================================================== // Data // ====================================================================== int mPieceCount; // Number of pieces per side Game* mpGame; // Pointer to the game that we are playing std::vector<Piece>* mpPieces; // Pointers to the pieces in the game Bitboard* mpPromotionZones; // Pointer to Promotion Zone array }; #endif // MOVEGENERATOR_HPP
32.108108
80
0.452862
jweathers777
684f3049a62ca219096912108e08f50a7835c70f
6,522
cpp
C++
src/Cloud_optics.cpp
Chiil/rte-rrtmgp-cpp
b39b130c733b8a9633753398b57849826818b8c6
[ "BSD-3-Clause" ]
null
null
null
src/Cloud_optics.cpp
Chiil/rte-rrtmgp-cpp
b39b130c733b8a9633753398b57849826818b8c6
[ "BSD-3-Clause" ]
null
null
null
src/Cloud_optics.cpp
Chiil/rte-rrtmgp-cpp
b39b130c733b8a9633753398b57849826818b8c6
[ "BSD-3-Clause" ]
null
null
null
/* * This file is part of a C++ interface to the Radiative Transfer for Energetics (RTE) * and Rapid Radiative Transfer Model for GCM applications Parallel (RRTMGP). * * The original code is found at https://github.com/RobertPincus/rte-rrtmgp. * * Contacts: Robert Pincus and Eli Mlawer * email: rrtmgp@aer.com * * Copyright 2015-2020, Atmospheric and Environmental Research and * Regents of the University of Colorado. All right reserved. * * This C++ interface can be downloaded from https://github.com/Chiil/rrtmgp_cpp * * Contact: Chiel van Heerwaarden * email: chiel.vanheerwaarden@wur.nl * * Copyright 2020, Wageningen University & Research. * * Use and duplication is permitted under the terms of the * BSD 3-clause license, see http://opensource.org/licenses/BSD-3-Clause * */ #include "Cloud_optics.h" template<typename TF> Cloud_optics<TF>::Cloud_optics( const Array<TF,2>& band_lims_wvn, const TF radliq_lwr, const TF radliq_upr, const TF radliq_fac, const TF radice_lwr, const TF radice_upr, const TF radice_fac, const Array<TF,2>& lut_extliq, const Array<TF,2>& lut_ssaliq, const Array<TF,2>& lut_asyliq, const Array<TF,3>& lut_extice, const Array<TF,3>& lut_ssaice, const Array<TF,3>& lut_asyice) : Optical_props<TF>(band_lims_wvn) { const int nsize_liq = lut_extliq.dim(1); const int nsize_ice = lut_extice.dim(1); this->liq_nsteps = nsize_liq; this->ice_nsteps = nsize_ice; this->liq_step_size = (radliq_upr - radliq_lwr) / (nsize_liq - TF(1.)); this->ice_step_size = (radice_upr - radice_lwr) / (nsize_ice - TF(1.)); // Load LUT constants. this->radliq_lwr = radliq_lwr; this->radliq_upr = radliq_upr; this->radice_lwr = radice_lwr; this->radice_upr = radice_upr; // Load LUT coefficients. this->lut_extliq = lut_extliq; this->lut_ssaliq = lut_ssaliq; this->lut_asyliq = lut_asyliq; this->lut_extice = lut_extice; this->lut_ssaice = lut_ssaice; this->lut_asyice = lut_asyice; } template<typename TF> void compute_from_table( const int ncol, const int nlay, const int nbnd, const Array<int,2>& mask, const Array<TF,2>& size, const int nsteps, const TF step_size, const TF offset, const Array<TF,2>& table, Array<TF,3>& out) { for (int ilay=1; ilay<=nlay; ++ilay) for (int icol=1; icol<=ncol; ++icol) { if (mask({icol, ilay})) { const int index = std::min( static_cast<int>((size({icol, ilay}) - offset) / step_size) + 1, nsteps-1); const TF fint = (size({icol, ilay}) - offset) / step_size - (index-1); for (int ibnd=1; ibnd<=nbnd; ++ibnd) out({icol, ilay, ibnd}) = table({index, ibnd}) + fint * (table({index+1, ibnd}) - table({index, ibnd})); } else { for (int ibnd=1; ibnd<=nbnd; ++ibnd) out({icol, ilay, ibnd}) = TF(0.); } } } // Two-stream variant of cloud optics. template<typename TF> void Cloud_optics<TF>::cloud_optics( const Array<int,2>& liqmsk, const Array<int,2>& icemsk, const Array<TF,2>& clwp, const Array<TF,2>& ciwp, const Array<TF,2>& reliq, const Array<TF,2>& reice, Optical_props_2str<TF>& optical_props) { const int ncol = clwp.dim(1); const int nlay = clwp.dim(2); const int nbnd = this->get_nband(); Optical_props_2str<TF> clouds_liq(ncol, nlay, optical_props); // Liquid water. compute_from_table( ncol, nlay, nbnd, liqmsk, reliq, this->liq_nsteps, this->liq_step_size, this->radliq_lwr, this->lut_extliq, clouds_liq.get_tau()); compute_from_table( ncol, nlay, nbnd, liqmsk, reliq, this->liq_nsteps, this->liq_step_size, this->radliq_lwr, this->lut_ssaliq, clouds_liq.get_ssa()); compute_from_table( ncol, nlay, nbnd, liqmsk, reliq, this->liq_nsteps, this->liq_step_size, this->radliq_lwr, this->lut_asyliq, clouds_liq.get_g()); for (int ibnd=1; ibnd<=nbnd; ++ibnd) for (int ilay=1; ilay<=nlay; ++ilay) #pragma ivdep for (int icol=1; icol<=ncol; ++icol) clouds_liq.get_tau()({icol, ilay, ibnd}) *= clwp({icol, ilay}); // Add ice as soon as ice microphysics are added. // Process the calculated optical properties. for (int ibnd=1; ibnd<=nbnd; ++ibnd) for (int ilay=1; ilay<=nlay; ++ilay) #pragma ivdep for (int icol=1; icol<=ncol; ++icol) { optical_props.get_tau()({icol, ilay, ibnd}) = clouds_liq.get_tau()({icol, ilay, ibnd}); optical_props.get_ssa()({icol, ilay, ibnd}) = clouds_liq.get_ssa()({icol, ilay, ibnd}); optical_props.get_g ()({icol, ilay, ibnd}) = clouds_liq.get_g ()({icol, ilay, ibnd}); } } // 1scl variant of cloud optics. template<typename TF> void Cloud_optics<TF>::cloud_optics( const Array<int,2>& liqmsk, const Array<int,2>& icemsk, const Array<TF,2>& clwp, const Array<TF,2>& ciwp, const Array<TF,2>& reliq, const Array<TF,2>& reice, Optical_props_1scl<TF>& optical_props) { const int ncol = clwp.dim(1); const int nlay = clwp.dim(2); const int nbnd = this->get_nband(); Optical_props_1scl<TF> clouds_liq(ncol, nlay, optical_props); // Liquid water. compute_from_table( ncol, nlay, nbnd, liqmsk, reliq, this->liq_nsteps, this->liq_step_size, this->radliq_lwr, this->lut_extliq, clouds_liq.get_tau()); for (int ibnd=1; ibnd<=nbnd; ++ibnd) for (int ilay=1; ilay<=nlay; ++ilay) #pragma ivdep for (int icol=1; icol<=ncol; ++icol) clouds_liq.get_tau()({icol, ilay, ibnd}) *= clwp({icol, ilay}); // Add ice as soon as ice microphysics are added. // Process the calculated optical properties. for (int ibnd=1; ibnd<=nbnd; ++ibnd) for (int ilay=1; ilay<=nlay; ++ilay) #pragma ivdep for (int icol=1; icol<=ncol; ++icol) optical_props.get_tau()({icol, ilay, ibnd}) = clouds_liq.get_tau()({icol, ilay, ibnd}); } #ifdef FLOAT_SINGLE_RRTMGP template class Cloud_optics<float>; #else template class Cloud_optics<double>; #endif
35.835165
106
0.607176
Chiil
68527263f6d0d58744f8579527ab063e5a31f0d9
4,327
hpp
C++
library/src/conversion/rocsparse_gebsr2gebsr.hpp
scchan/rocSPARSE
6efc875765236a91d6b07ef42446b1b46de661e0
[ "MIT" ]
44
2018-10-03T19:02:58.000Z
2022-01-19T20:40:51.000Z
library/src/conversion/rocsparse_gebsr2gebsr.hpp
scchan/rocSPARSE
6efc875765236a91d6b07ef42446b1b46de661e0
[ "MIT" ]
30
2019-06-03T16:34:01.000Z
2022-03-14T19:21:19.000Z
library/src/conversion/rocsparse_gebsr2gebsr.hpp
scchan/rocSPARSE
6efc875765236a91d6b07ef42446b1b46de661e0
[ "MIT" ]
45
2018-09-26T08:11:59.000Z
2022-03-31T07:38:08.000Z
/*! \file */ /* ************************************************************************ * Copyright (c) 2020 Advanced Micro Devices, Inc. * * 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. * * ************************************************************************ */ #pragma once #ifndef ROCSPARSE_GEBSR2GEBSR_HPP #define ROCSPARSE_GEBSR2GEBSR_HPP #include "handle.h" template <typename T> rocsparse_status rocsparse_gebsr2gebsr_buffer_size_template(rocsparse_handle handle, rocsparse_direction dir, rocsparse_int mb, rocsparse_int nb, rocsparse_int nnzb, const rocsparse_mat_descr descr_A, const T* bsr_val_A, const rocsparse_int* bsr_row_ptr_A, const rocsparse_int* bsr_col_ind_A, rocsparse_int row_block_dim_A, rocsparse_int col_block_dim_A, rocsparse_int row_block_dim_C, rocsparse_int col_block_dim_C, size_t* buffer_size); template <typename T> rocsparse_status rocsparse_gebsr2gebsr_template(rocsparse_handle handle, rocsparse_direction dir, rocsparse_int mb, rocsparse_int nb, rocsparse_int nnzb, const rocsparse_mat_descr descr_A, const T* bsr_val_A, const rocsparse_int* bsr_row_ptr_A, const rocsparse_int* bsr_col_ind_A, rocsparse_int row_block_dim_A, rocsparse_int col_block_dim_A, const rocsparse_mat_descr descr_C, T* bsr_val_C, rocsparse_int* bsr_row_ptr_C, rocsparse_int* bsr_col_ind_C, rocsparse_int row_block_dim_C, rocsparse_int col_block_dim_C, void* temp_buffer); #endif // ROCSPARSE_GEBSR2GEBSR_HPP
63.632353
100
0.431708
scchan
68530fd062126afe1b73f393fe8babe4d76252a6
5,044
cxx
C++
Libraries/ITK/Common/itkFilenameUtils.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
13
2018-07-28T13:36:38.000Z
2021-11-01T19:17:39.000Z
Libraries/ITK/Common/itkFilenameUtils.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
null
null
null
Libraries/ITK/Common/itkFilenameUtils.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
10
2018-08-20T07:06:00.000Z
2021-07-07T07:55:27.000Z
/*============================================================================= NifTK: A software platform for medical image computing. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #ifndef __itkFilenameUtils_cxx #define __itkFilenameUtils_cxx #include "itkFilenameUtils.h" #include <iostream> #include <string> namespace itk { /* ---------------------------------------------------------------------- ModifyFilenameSuffix() ---------------------------------------------------------------------- */ std::string ModifyFilenameSuffix( std::string filename, std::string suffix ) { std::string tmpname, basename, extname; std::string compression; std::string::size_type idx; std::string::size_type idxZ = std::string::npos; std::string::size_type idxGZ = std::string::npos; std::string::size_type lenExt = std::string::npos; // Search for the last directory separator: '/' #ifdef MS_VISUAL_Cpp std::string::size_type diridx = filename.find_last_of('\\'); #else std::string::size_type diridx = filename.find_last_of('/'); #endif if (diridx == std::string::npos) { diridx = 0; } // Search for period in file name idx = filename.rfind('.'); if ((idx == std::string::npos) || (idx < diridx)) { // file name does not contain a period so add suffix tmpname = filename + suffix; } else { // check that we haven't found a '.Z' or '.gz' suffix if (filename.compare(idx, 2, ".Z") == 0) { idxZ = idx; idx = filename.rfind('.', idxZ-1); if ((idx == std::string::npos) || (idx < diridx)) { idx = idxZ; lenExt = filename.length() - idx; } else { lenExt = idxZ - idx - 1; compression = ".Z"; } } else if (filename.compare(idx, 3, ".gz") == 0) { idxGZ = idx; idx = filename.rfind('.', idxGZ-1); if ((idx == std::string::npos) || (idx < diridx)) { idx = idxGZ; lenExt = filename.length() - idx; } else { lenExt = idxGZ - idx - 1; compression = ".gz"; } } else { lenExt = filename.length() - idx; } // split file name into stem and extension basename = filename.substr(0, idx); extname = filename.substr(idx + 1, lenExt); if (extname.empty()) { // contains period but no extension tmpname = filename + suffix + compression; } else { // replace extension tmpname = filename; tmpname.replace(idx, lenExt+1, suffix); } } return tmpname; } /* ---------------------------------------------------------------------- ExtractSuffix ---------------------------------------------------------------------- */ std::string ExtractSuffix( std::string filename ) { std::string tmpname, basename, extname; std::string::size_type idx; std::string::size_type idxZ = std::string::npos; std::string::size_type idxGZ = std::string::npos; // Search for the last directory separator: '/' #ifdef MS_VISUAL_Cpp std::string::size_type diridx = filename.find_last_of('\\'); #else std::string::size_type diridx = filename.find_last_of('/'); #endif if (diridx == std::string::npos) { diridx = 0; } // Search for period in file name idx = filename.rfind('.'); // file name does not contain a period so return empty string if ((idx == std::string::npos) || (idx < diridx)) { extname = ""; } else { // check that we haven't found a '.Z' or '.gz' suffix if (filename.compare(idx, 2, ".Z") == 0) { idxZ = idx; idx = filename.rfind('.', idxZ-1); if ((idx == std::string::npos) || (idx < diridx)) { extname = ""; } else { // split file name into stem and extension extname = filename.substr(idx + 1, idxZ - idx - 1); if (extname.empty()) { // contains period but no extension extname = ""; } } } else if (filename.compare(idx, 3, ".gz") == 0) { idxGZ = idx; idx = filename.rfind('.', idxGZ-1); if ((idx == std::string::npos) || (idx < diridx)) { extname = ""; } else { // split file name into stem and extension extname = filename.substr(idx + 1, idxGZ - idx - 1); if (extname.empty()) { // contains period but no extension extname = ""; } } } else { // split file name into stem and extension extname = filename.substr(idx + 1); if (extname.empty()) { // contains period but no extension extname = ""; } } } return extname; } } #endif
23.460465
79
0.515662
NifTK
685f018452dc17270abcdb6b12663e8ff9d299b1
799
cpp
C++
Sources/EntitySystem/Entity/World.cpp
vit3k/entity_system
5b00804bb772229cab90ea7de589faced98bc001
[ "MIT" ]
null
null
null
Sources/EntitySystem/Entity/World.cpp
vit3k/entity_system
5b00804bb772229cab90ea7de589faced98bc001
[ "MIT" ]
null
null
null
Sources/EntitySystem/Entity/World.cpp
vit3k/entity_system
5b00804bb772229cab90ea7de589faced98bc001
[ "MIT" ]
null
null
null
#include "World.h" #include "../Events/EntityUpdatedEvent.h" #include "../Logger.h" #include "../Engine.h" EntitySP World::Create() { EntitySP entity(new Entity(this,entitySeq.Next())); entities[entity->ID] = entity; return entity; } void World::EntityUpdate(int id) { Engine::Instance().GetDispatcher()->Queue(EntityUpdatedEventSP(new EntityUpdatedEvent(id))); } SystemSP World::AddSystem(SystemSP system) { systems[systemSeq.Next()] = system; system->SetWorld(this); return system; } void World::Update(Time delta) { Logger::Log("World::Update start"); for(int i = 0;i<=systemSeq.Current();i++) systems[i]->Process(delta); Logger::Log("World::Update end"); } void World::RemoveEntities() { Logger::Log("World::RemoveEntities start"); Logger::Log("World::RemoveEntities stop"); }
22.194444
93
0.707134
vit3k
6864b90d618d48278b18fa5288789ce73e5f0f58
25,629
hpp
C++
include/NRGclasses.hpp
lgds/NRG_USP
ff66846e92498aa429cce6fc5793bec23ad03eb4
[ "MIT" ]
3
2015-09-21T20:58:45.000Z
2019-03-20T01:21:41.000Z
include/NRGclasses.hpp
lgds/NRG_USP
ff66846e92498aa429cce6fc5793bec23ad03eb4
[ "MIT" ]
null
null
null
include/NRGclasses.hpp
lgds/NRG_USP
ff66846e92498aa429cce6fc5793bec23ad03eb4
[ "MIT" ]
null
null
null
#include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/io.hpp> #include <boost/numeric/ublas/matrix_proxy.hpp> ////using namespace boost::numeric::ublas; extern "C"{ #include <cblas.h> } #include <gsl/gsl_integration.h> #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <cstring> #include <complex> // std::complex using namespace std; #ifndef _CPLXCONST_ #define _CPLXCONST_ const complex<double> ZeroC (0.0,0.0); const complex<double> OneC (1.0,0.0); const complex<double> OneImC (0.0,1.0); #endif //#ifndef _MYEPSCONST_ // #define _MYEPSCONST_ // const double MyEPS(1.0e-13); // #endif // Declares the classes //////////////////////////////////////////////// ////////////// Class CNRGarray \\\\\\\\\\\\\\\\\ //////////////////////////////////////////////// #ifndef _CNRGARRAY_ #define _CNRGARRAY_ class CNRGarray { /* Declares the class */ public: // Default constructor //CNRGarray():totalS(false){} CNRGarray():MyEPS(1.0e-18) {} // Constructor with NQNumbers defined CNRGarray(int Nqns){ NQNumbers=Nqns; } // Default Destructor ~CNRGarray(){} // Member variables (regular) int Nshell; int NQNumbers; // Member variables (STL vectors) vector<double> QNumbers; // Vectors that spam the full basis vector<double> dEigVec; vector<double> dEn; vector<complex<double> > cEigVec; vector<int> iDegen; vector<int> BlockBegEnd; // April 09: list of N+1 states generated // (to be used in DM-NRG) vector< vector<int> > ChildStates; // August 2011: mark kept states. (spans the full basis) vector<bool> Kept; // April 10: totalS qnumbers bool totalS; // tru -> there are totalS QNs vector<int> Sqnumbers; // position(s) of total S in QNumbers // Idea: This can be used in an updated version of BuildBasis... //bool ComplexEVec; // tru -> complex eigenvectors double MyEPS; // Member functions int NumBlocks(); int Nstates(); double EniBlockj(int i, int j); void SetDegen(); void SetE0zero(); void FilterQNumbers(); void PrintQNumbers(); void PrintEn(); void PrintAll(); void PrintBlockQNumbers(int iblock); void PrintBlockEn(int iblock); void PrintBlock(int iblock); void ClearAll(); double GetQNumber(int iblock, int whichqn); int GetBlockLimit(int iblock, int whichlimit); int GetBlockSize(int iblock); int GetBlockSize(int iblock,bool kp); int GetBlockFromSt(int ist,int &pos_in_block); int GetBlockLimitEigv(int iblock, int whichlimit); boost::numeric::ublas::matrix<double> EigVec2BLAS(int iblock); // 2013 boost::numeric::ublas::matrix<complex<double> > cEigVec2BLAS(int iblock); double GetEigVecComponent(int ist,int istbasis); // April 09 double Ecut(int Ncut); double GetBlockEmin(int iblock); double GetBlockEmax(int iblock); int GetBlockEcutPos(int iblock,double Ecut); void SetKept(int Ncutoff); bool CheckKept(int ist, bool kp); bool CheckKept(int iblock, int istbl, bool kp); int GetBlockFromQNumbers(double *qnums); double GetQNumberFromSt(int ist, int whichqn); // May 08 int GetiGS(); void SaveQSParameters(); // Sep 08 void AddQNumber(); // Feb 09 void SaveBin(char arqname[]); void ReadBin(char arqname[]); void ReadBinInStream(ifstream &InFile); // April 09 double PartitionFuncTeq0(); double PartitionFunc(double betabar); double PartitionFuncDisc(double betabar); // September 09 void SetEigVecToOne(); // Nov 2010 boost::numeric::ublas::matrix<double> ExpEi2BLAS(int iblock, double betabar); // March 2014 bool CheckComplex(); protected : }; #endif //////////////////////////////////////////////// /////////// Class CNRGbasisarray \\\\\\\\\\\\\\\ //////////////////////////////////////////////// // // Subclass of CNRGarray // #ifndef _CNRGBASISARRAY_ #define _CNRGBASISARRAY_ class CNRGbasisarray: public CNRGarray{ public : // Default constructor CNRGbasisarray(){} CNRGbasisarray(int Nqns){ NQNumbers=Nqns; } // Default Destructor // Constructor that copies members from a CNRGarray object CNRGbasisarray(CNRGarray A1){ CNRGarray::Nshell=A1.Nshell; CNRGarray::NQNumbers=A1.NQNumbers; CNRGarray::QNumbers=A1.QNumbers; CNRGarray::dEn=A1.dEn; CNRGarray::dEigVec=A1.dEigVec; CNRGarray::cEigVec=A1.cEigVec; CNRGarray::Kept=A1.Kept; CNRGarray::BlockBegEnd=A1.BlockBegEnd; CNRGarray::totalS=A1.totalS; // tru -> there are totalS QNs CNRGarray::Sqnumbers=A1.Sqnumbers; // position(s) of total S in QNumbers } ~CNRGbasisarray(){} vector<int> iType; vector<int> StCameFrom; // moved here // NEW vector<int> BlockBegEndBC; vector<int> BlockBegEndEigVec; // Newer: if the symmetry is reduced at a certain point, need to retain // old Qnumbers int NQNumbers_stcf; vector<double> StCameFromQNumbers; // Member functions void ClearAll(); void PrintAll(); void PrintBlockBasis(int iblock); void PrintBasisAll(){ for (int ibl=0;ibl<NumBlocks();ibl++) PrintBlockBasis(ibl); } void SetSCFfromdEn(); int GetBlockSizeBC(int iblock); int GetBlockFromStBC(int ist,int &pos_in_block); void SyncNRGarray(CNRGarray &A1){ CNRGarray::Nshell=A1.Nshell; CNRGarray::NQNumbers=A1.NQNumbers; CNRGarray::QNumbers=A1.QNumbers; CNRGarray::dEn=A1.dEn; CNRGarray::dEigVec=A1.dEigVec; CNRGarray::cEigVec=A1.cEigVec; CNRGarray::Kept=A1.Kept; CNRGarray::BlockBegEnd=A1.BlockBegEnd; CNRGarray::totalS=A1.totalS; // tru -> there are totalS QNs CNRGarray::Sqnumbers=A1.Sqnumbers; // position(s) of total S in QNumbers } // New void FalseCut(CNRGarray* pA1){ CNRGbasisarray::ClearAll(); CNRGbasisarray::SyncNRGarray(*pA1); CNRGbasisarray::SetSCFfromdEn(); CNRGbasisarray::BlockBegEndBC=pA1->BlockBegEnd; CNRGbasisarray::SetBlockBegEndEigVec(); } void SetBlockBegEndEigVec(); void RemoveBlock(int iblock); // StCameFrom keeps the pre-cut state indexes void RemoveState(int ist); // StCameFrom keeps the pre-cut state indexes void RemoveStatesFromBlock(int ibl, int ist1,int ist2); int GetBlockLimitEigv(int iblock, int whichlimit); // April 09, overloads double GetEigVecComponent(int ist,int istbasis); // April 09 overloads // Ubuntu's g++ does not like this... boost::numeric::ublas::matrix<double> EigVecCut2BLAS(int iblock); boost::numeric::ublas::matrix<complex<double> > cEigVecCut2BLAS(int iblock); // converts the non-square eigenvector matrix to BLAS format boost::numeric::ublas::matrix<double> EigVecCut2BLAS(int iblock, bool kp); // converts the non-square eigenvector matrix to BLAS format (kp states) // April 08 double GetStCameFromQNumberFromSt(int ist, int whichqn); // Sets dEn as the energies of the previous states in StCameFrom // SetdEnPrevious(); void CopyBlock(int iblock, int NoCopies); // Create copies of block states and set iDegen // Sep 08 void SetLastQNumber(vector<double> InputVec); // Feb 09 void SaveBin(char arqname[]); void ReadBin(char arqname[]); void ReadBinInStream(ifstream &InFile); }; #endif //////////////////////////////////////////////// /////////// Class CNRGmatrix \\\\\\\\\\\\\\\ //////////////////////////////////////////////// // // Subclass of CNRGarray // #ifndef _CNRGMATRIX_ #define _CNRGMATRIX_ class CNRGmatrix: public CNRGarray{ public : // Default constructor (with initialization list) CNRGmatrix():UpperTriangular(false),NeedOld(false),SaveMatYN(false),CalcAvg(false),IsComplex(false),WignerEckartL(0.5) {} //CNRGmatrix(){} // Constructor that copies members from a CNRGarray object CNRGmatrix(CNRGbasisarray A1){ UpperTriangular=false; SaveMatYN=false; CalcAvg=false; IsComplex=false; CNRGarray::Nshell=A1.Nshell; CNRGarray::NQNumbers=A1.NQNumbers; CNRGarray::QNumbers=A1.QNumbers; CNRGarray::BlockBegEnd=A1.BlockBegEnd; CNRGarray::Kept=A1.Kept; // CNRGarray::sizeBlock=A1.sizeBlock; iType=A1.iType; CNRGarray::totalS=A1.totalS; // tru -> there are totalS QNs CNRGarray::Sqnumbers=A1.Sqnumbers; // position(s) of total S in QNumbers } // Default Destructor ~CNRGmatrix(){} ////////////////////// // Static members // ////////////////////// vector<double> MatEl; // new //template <typename AnyType> vector< complex<double> > MatElCplx; // Best solution: look for MatEl everywhere and // add a if (IsComplex)-> use MatElCmplx instead vector<int> MatBlockMap; vector<int> MatBlockBegEnd; // New: same as in CNRGbasisarray vector<int> iType; // NEW: indicate kept-kept,disc-disc, disc-kept,... vector<bool> MatKept; // Does this matrix needs the "old" one on updating? bool NeedOld; // Stores upper triangular part of the blocks only? bool UpperTriangular; // Save matrix? bool SaveMatYN; // CalcAvg? bool CalcAvg; char MatName[20]; // Is complex? bool IsComplex; // Wigner-Eckart rank (usually 1/2 but it can be 1) // Needed when using SU(2) symmetry. double WignerEckartL; ////////////////////// // Function members // ////////////////////// void SyncNRGarray(CNRGarray A1){ CNRGarray::Nshell=A1.Nshell; CNRGarray::NQNumbers=A1.NQNumbers; CNRGarray::QNumbers=A1.QNumbers; CNRGarray::BlockBegEnd=A1.BlockBegEnd; CNRGarray::Kept=A1.Kept; CNRGarray::totalS=A1.totalS; // tru -> there are totalS QNs CNRGarray::Sqnumbers=A1.Sqnumbers; // position(s) of total S in QNumbers } /// Same for basis array void SyncNRGarray(CNRGbasisarray A1){ CNRGarray::Nshell=A1.Nshell; CNRGarray::NQNumbers=A1.NQNumbers; CNRGarray::QNumbers=A1.QNumbers; CNRGarray::BlockBegEnd=A1.BlockBegEnd; CNRGarray::Kept=A1.Kept; CNRGarray::totalS=A1.totalS; // tru -> there are totalS QNs CNRGarray::Sqnumbers=A1.Sqnumbers; // position(s) of total S in QNumbers iType=A1.iType; } // //// // void ReverseSyncNRGarray(CNRGarray &A1){ // A1.Nshell=CNRGarray::Nshell; // A1.NQNumbers=CNRGarray::NQNumbers; // A1.QNumbers=CNRGarray::QNumbers; // A1.BlockBegEnd=CNRGarray::BlockBegEnd; // } /// Same for basis array void ReverseSyncNRGarray(CNRGbasisarray &A1){ A1.Nshell=CNRGarray::Nshell; A1.NQNumbers=CNRGarray::NQNumbers; A1.QNumbers=CNRGarray::QNumbers; A1.BlockBegEnd=CNRGarray::BlockBegEnd; A1.Kept=CNRGarray::Kept; A1.totalS=CNRGarray::totalS; // tru -> there are totalS QNs A1.Sqnumbers=CNRGarray::Sqnumbers; // position(s) of total S in QNumbers A1.iType=iType; } bool ChkSync(CNRGarray* pA1){ if ( (CNRGarray::Nshell==pA1->Nshell)&& (CNRGarray::NQNumbers==pA1->NQNumbers)&& (CNRGarray::QNumbers==pA1->QNumbers)&& (CNRGarray::BlockBegEnd==pA1->BlockBegEnd)&& (CNRGarray::Kept==pA1->Kept)&& (CNRGarray::totalS==pA1->totalS)&& (CNRGarray::Sqnumbers==pA1->Sqnumbers) ){ return(true); } else{return(false);} } /// Same for basis array bool ChkSync(CNRGbasisarray* pA1){ if ( (CNRGarray::Nshell==pA1->Nshell)&& (CNRGarray::NQNumbers==pA1->NQNumbers)&& (CNRGarray::QNumbers==pA1->QNumbers)&& (CNRGarray::BlockBegEnd==pA1->BlockBegEnd)&& (CNRGarray::Kept==pA1->Kept)&& (CNRGarray::totalS==pA1->totalS)&& (CNRGarray::Sqnumbers==pA1->Sqnumbers)&& (iType==pA1->iType) // new (Sep 09, checking) ){ return(true); } else{return(false);} } //// void CopyData(CNRGmatrix* pMat1){ // Array data Nshell=pMat1->Nshell; NQNumbers=pMat1->NQNumbers; QNumbers=pMat1->QNumbers; BlockBegEnd=pMat1->BlockBegEnd; Kept=pMat1->Kept; iType=pMat1->iType; totalS=pMat1->totalS; Sqnumbers=pMat1->Sqnumbers; // Matrix data MatEl=pMat1->MatEl; MatElCplx=pMat1->MatElCplx; MatBlockMap=pMat1->MatBlockMap; MatBlockBegEnd=pMat1->MatBlockBegEnd; MatKept=pMat1->MatKept; UpperTriangular=pMat1->UpperTriangular; IsComplex=pMat1->IsComplex; WignerEckartL=pMat1->WignerEckartL; } int NumMatBlocks(); int FindMatBlock(int iblock1, int iblock2); int GetMatBlockLimit(int iblock1, int iblock2, int whichlimit); int GetMatBlockLimit(int imatblock, int whichlimit); int GetMatBlockSize(int iblock1, int iblock2); int GetMatBlockSize(int imatblock ); double GetBlockMatEl(int iblock1, int iblock2, int iel, int jel); double GetMatEl(int ist, int jst); complex<double> cGetBlockMatEl(int iblock1, int iblock2, int iel, int jel); complex<double> cGetMatEl(int ist, int jst); // April 2019 double CalcTrace(); int GetMatElPosition(int iblock1, int iblock2, int iel, int jel); // deprecated void PushBlockMatEl(double El, int iblock1, int iblock2, int iel, int jel); /// void PushMatEl(double El, int ist, int jst); void PushMatEl(complex<double> El, int ist, int jst); ////// TEMPLATES! Testing. Not easy. template<class T> void TemplateTest(T El){ cout << " This is the element: " << El << endl; return; } // Replace EXISTING matrix element ist,jst by El template <class T> void TPushMatEl(T El, int ist, int jst){ int ibl,jbl; int iblock1=CNRGarray::GetBlockFromSt(ist,ibl); int iblock2=CNRGarray::GetBlockFromSt(jst,jbl); int iPos=CNRGmatrix::GetMatElPosition(iblock1,iblock2,ibl,jbl); // This does not compile! // if (iPos>-1){ // if (IsComplex) MatElCplx[iPos]=El; // else MatEl[iPos]=El; // } } //// END TEMPLATE TESTING void FilterMap_SetBegEnd(); // double* Block2Array(int imatblock); void ClearAll(); void PrintMatBlockQNumbers(int imatblock); void PrintMatBlock(int imatblock); void PrintMatBlock(int iblock1, int iblock2); void PrintAllBlocks(); void DiagBlock(int iblock, vector<double> &eigvalues, vector<double> &eigvectors); void DiagBlock(int iblock, vector<double> &eigvalues, vector<complex<double> > &eigvectors); // Pointers to functions to be defined // Checks whether there are non-zero matrix elements bool (*CheckForMatEl)(CNRGbasisarray *pAeigCut, int iblock1, int iblock2); // Calculates matrix elements between iblock1 and iblock2 double (*CalcMatEl)(CNRGbasisarray *pAbasis, CNRGbasisarray *pSingleSite, int isti, int istj); complex<double> (*CalcMatElCplx)(CNRGbasisarray *pAbasis, CNRGbasisarray *pSingleSite, int isti, int istj); double (*CalcHNMatEl)(vector<double> Params, CNRGbasisarray* pAbasis, CNRGbasisarray* pSingleSite, CNRGmatrix* MatArray, int ist, int jst); complex<double> (*CalcHNMatElCplx)(vector<double> Params, CNRGbasisarray* pAbasis, CNRGbasisarray* pSingleSite, CNRGmatrix* MatArray, int ist, int jst); // // THIS one is looking good!!! // void DiagHN(vector<double> ParamsHN, CNRGbasisarray* pAbasis, CNRGbasisarray* pSingleSite, CNRGmatrix* MatArray, CNRGarray* pAeig,bool display=false); // // This one too! // void PutInRegularForm(int iblock); // // Save in Binary // void SaveBinary(char arqname[]); void SaveInOldFormat(); // Mar 09 void SaveBin(char arqname[]); void ReadBin(char arqname[]); void ReadBinInStream(ifstream &InFile); // April 09 // Given a block ibl_base, and stores the connecting blocks // and respective BlockMat in the two-column array // Connect_BlockMatBlock void GetConnectingBlocks(int ibl_base, vector < vector<int> > &Connect_BlockMatBlock, bool ToBase=false); // May 09 void GetBlocksFromMatBlock(int iMatBlock, int &ibl1, int &ibl2); boost::numeric::ublas::matrix<double> MatBlock2BLAS(int iMatBlock); boost::numeric::ublas::matrix<double> MatBlock2BLAS(int ibl1, int ibl2); boost::numeric::ublas::matrix<complex<double> > cMatBlock2BLAS(int ibl1, int ibl2); boost::numeric::ublas::matrix<double> RotateBlock2BLAS(CNRGbasisarray* pAcut, int iMatBlock); boost::numeric::ublas::matrix<double> RotateBlock2BLAS(CNRGbasisarray* pAcut, int ibl1, int ibl2); boost::numeric::ublas::matrix<complex<double> > cRotateBlock2BLAS(CNRGbasisarray* pAcut, int ibl1, int ibl2); boost::numeric::ublas::matrix<double> RotateBlock2BLAS_NoCut(CNRGarray* pAeig, int ibl1, int ibl2, bool forward); boost::numeric::ublas::matrix<complex<double> > cRotateBlock2BLAS_NoCut(CNRGarray* pAeig, int ibl1, int ibl2, bool forward); // August 2011 boost::numeric::ublas::matrix<double> MatBlock2BLAS(int iMatBlock, bool kp1, bool kp2); boost::numeric::ublas::matrix<double> MatBlock2BLAS(int ibl1, int ibl2, bool kp1, bool kp2); boost::numeric::ublas::matrix<complex<double> > cMatBlock2BLAS(int ibl1, int ibl2, bool kp1, bool kp2); boost::numeric::ublas::matrix<double> RotateBlock2BLAS(CNRGbasisarray* pAcut, int iMatBlock, bool kp1, bool kp2); boost::numeric::ublas::matrix<double> RotateBlock2BLAS(CNRGbasisarray* pAcut, int ibl1, int ibl2, bool kp1, bool kp2); // April 2019 void MatBlock2STL(vector<double>& Mout, int iMatBlock); void MatBlock2STL(vector<double>& Mout, int ibl1, int ibl2); void MatBlock2STL(vector<double>& Mout, int iMatBlock, bool kp1, bool kp2); void MatBlock2STL(vector<double>& Mout, int ibl1, int ibl2, bool kp1, bool kp2); void cMatBlock2STL(vector<complex<double> >& cMout, int iMatBlock); void cMatBlock2STL(vector<complex<double> >& cMout, int ibl1, int ibl2); void cMatBlock2STL(vector<complex<double> >& cMout, int iMatBlock, bool kp1, bool kp2); void cMatBlock2STL(vector<complex<double> >& cMout, int ibl1, int ibl2, bool kp1, bool kp2); // Sep 09 // Set as Diagonal matrix (diagonal, UpperTriang=false) void SetDiagonalMatrix(double El); void SetIdentityMatrix(); // Uses it's own QNumbers and iType to check for mat els. bool SelfCheckForMatEl(int iblock1, int iblock2); // Sets Matrix as zero, based on CheckForMatEl (SelfCheckForMatEl) void SetZeroMatrix(); // May 2011 // IF (*CalcMatEl) and (*CheckForMatEl) are defined, then it sets the matrix void SetMatrix(CNRGbasisarray* pAbasis, CNRGbasisarray* pSingleSite); }; #endif #ifndef _CNRGCHAIN_ #define _CNRGCHAIN_ class CNRGchain{ public : // Default constructor (with initialization list) CNRGchain():Lambda(2.5),z_twist(1.0),BandOffset(0.0),HybRef(1.0),HybRefIsSet(false),HybFuncIsSumDeltas(false),Fsq(2.0),DiscScheme(0) {} CNRGchain(double ThisLambda):z_twist(1.0),BandOffset(0.0),HybRef(1.0),HybRefIsSet(false),HybFuncIsSumDeltas(false),Fsq(2.0),DiscScheme(0){ Lambda=ThisLambda; } CNRGchain(double ThisLambda, int Nsitesmax):z_twist(1.0),BandOffset(0.0),HybRef(1.0),HybRefIsSet(false),HybFuncIsSumDeltas(false),Fsq(2.0),DiscScheme(0) { Lambda=ThisLambda; //z_twist=1.0; SetChainWilson(Nsitesmax); } // Default Destructor ~CNRGchain(){} // Static members //int Nshell; //vector<double> eps_chi; double Lambda; double z_twist; double BandOffset; vector<double> en; vector<double> chin; vector<double> *HybFuncParams; // pointer to an STL vector // It SHOULD NOT be a POINTER!! Should allocate this WITHIN THE OBJECT! // Leave it like that for now... //vector< vector<double> > HybFuncVecParams; // STL array double HybRef; bool HybRefIsSet; bool HybFuncIsSumDeltas; double Fsq; int DiscScheme; // 0- usual; 1- CampoOliveira // Function members //void SetChain(double Lambda); void PrintChain(int Nsites); void PrintAll(); void SetChainWilson(int Nsitesmax); void ReadParams(char arqname[],int Nparams); void ReadParams(char arqname[]); // Reads the whole thing into the STL vector // LAST NUMBER: Nlines. //void ReadVecParams(char arqname[], int Ncols); // Hybridization function in a GSL format (need to be defined externally!) double (*HybFunction)(double omega, void *params); double (*HybFuncWithEn)(double omega, void *params); // Ok, this is a bummer but... // hybridizations (Delta(en)) AND en*Delta(en) (or Delta(en)/en) // have to be defined OUTSIDE as static members // in order to be passed in here. // So, for every static HybFunction (=Delta(e)) // there HAS TO BE a HybFuncWithEn defined as well // Tried hard to pass non-static function to GSL... // ...doesn't work. Ditto (may 2010) // double HFtimesEn(double omega, // void *params); // static double HFtimesEnCallBack(double omega, // void* params); //////////// double GetEn(int Nsites); double GetChin(int Nsites); // GSL integration double GSL_Integration(gsl_function *pIntegrandGSL, gsl_integration_workspace *w_gsl, double x0, double x1); // Lanczos procedure void SetChainLanczos(int Nsitesmax); double GetHyb_w(double omega); double ScaleFactor(int n); private: // GSL stuff // gsl_function HybFunGSL; // gsl_function EnHybF; gsl_integration_workspace *wsp_gsl; void SetHybRef(); double CalcF2(gsl_integration_workspace *w_gsl); // Adds elements of *pFm and *pEm void CalcFabmEabm(int m, gsl_integration_workspace *w_gsl, char which, vector<double> *pFm, vector<double> *pEm); double RHS(int n, double eam, double um, double um1, double en, double chinm1, bool scale=true); }; // struct NRGchainGSLCallbackHolder // { // //CNRGchain* cls; // //void* data; // CNRGchain cls; // void* data; // }; #endif ///////////////////////////////////////////////// ////////////// Class CNRGthermo \\\\\\\\\\\\\\\\\ ///////////////////////////////////////////////// #ifndef _CNRGTHERMO_ #define _CNRGTHERMO_ class CNRGthermo{ public : // // Static members // Input/Output char ThermoName[64]; char ChainArqName[64]; char ArqName[64]; double dImpValue; bool CalcChain; int Nsite0Chain; double betabar; // vector<double> dChainValues; vector<double> dValues; vector<double> dTempValues; // pointer to function: double (*Calc)(vector<double> Params, CNRGarray* pAeig, int sqnumber,bool totalS); // // Function members void AddValue(vector<double> Params, CNRGarray* pAeig, int sqnumber,bool totalS, double Temp); int ReadChain(); void ReadNChainValue(int Nsites,int Nsites0); void SaveNValue(int Nsites, int Nsites0); void SaveToFile(); bool CheckForFile(); }; // end CNRGthermo #endif ////////////////////////////////////////////////////// ////////////// Class CNRGCodeHandler \\\\\\\\\\\\\\\\\ ////////////////////////////////////////////////////// #ifndef _CNRGCODEHANDLER_ #define _CNRGCODEHANDLER_ class CNRGCodeHandler{ public : // Default Constructor CNRGCodeHandler():NumChannels(1),Lambda(2.5){} // Default Destructor ~CNRGCodeHandler(){} // Static members char ModelOption[32]; char Symmetry[32]; char BandType[32]; int ModelNo; int SymNo; int BandNo; // Files char ParamFileName[64]; char BeginFileName[64]; char EndFileName[64]; char SaveArraysFileName[64]; char LancInFileName[64]; int NoInputParamsDouble; vector <double> dInitParams; // vector <string> cParamsName; int calcdens; int Ncutoff; int Nsitesmax; int Nsites0; int UpdateBefCut; int Nsites; int NumNRGmats; int NumThermoMats; int NumChannels; int NopsSaved; double Lambda; // double Dband; double ChemPot; double DN; double betabar; double HalfLambdaFactor; // totalS QNumbers bool totalS; int Sqnumber; // instream (perhaps not such a good idea) std::ifstream CodeInFile; // CNRGarray objects (pointers) CNRGbasisarray* pAcut; CNRGbasisarray* pAbasis; CNRGmatrix* MatArray; vector<CNRGthermo> ThermoSTLArray; // New Sep 09 bool SaveData; // Need an array of chains //CNRGchain chain; vector<CNRGchain> Chains; // I will have to add a general ztwist and DiscScheme //ThisCode.chain.z_twist double code_z_twist; int code_DiscScheme; // 0- usual; 1- CampoOliveira // ThisCode.chain.DiscScheme // Function members //void InitialSetUp(); // Trying this void InitialSetUp(bool ReadParamsOnly=false); void ReadParams(); void ReadParams(char FileName[], int NoAdditionalParams); void SetChain(); void SaveBegFile(); void WrapUp(); void SetSingleSite(CNRGbasisarray* pSingleSite); void CalcThermo(CNRGthermo* ThermoArray, CNRGarray* pAeig); void CalcStuff(CNRGarray* pAeig, CNRGbasisarray* pAeigCut); void DoesNothing(); void ZeroParams(); void SetTotS(); //void SaveGenPars(char idname[]); void SaveGenPars(); void SaveArrays(); void SaveArrays(char idname[]); //void ReadGenPars(char idname[]); //void ReadGenPars(); // Keep this until all ThisCodePars.dat have been updated :) void ReadGenPars(bool ReadModelBand=false); void ReadArrays(); void ReadArrays(char idname[]); void SetCurrentDN(); void SetNopsSaved(); bool CheckFileExists(char arqname[]); // New: May 2010 void ModelSwitch( vector<int> &CommonQNs, vector<int> &totSpos, CNRGarray* pAeig, CNRGbasisarray* pSingleSite, CNRGmatrix* pHN, vector<CNRGmatrix> &STLMatArray, CNRGthermo* ThermoArray, vector<double> &chi_m1); double chiN(int Nsites, double Lambda); void PrintSettings(); }; #endif
22.422572
154
0.670451
lgds
686970f7a4bc571bab16a5854bcec34a061af754
5,536
cpp
C++
moderngl/next/mgl/recorder.cpp
einarf/ModernGL
e4a7f53289043a0ac06130c67edc75b878484a0e
[ "MIT" ]
1
2019-10-18T03:23:16.000Z
2019-10-18T03:23:16.000Z
moderngl/next/mgl/recorder.cpp
einarf/ModernGL
e4a7f53289043a0ac06130c67edc75b878484a0e
[ "MIT" ]
null
null
null
moderngl/next/mgl/recorder.cpp
einarf/ModernGL
e4a7f53289043a0ac06130c67edc75b878484a0e
[ "MIT" ]
null
null
null
#include "recorder.hpp" #include "context.hpp" #include "internal/bytecode.hpp" #include "internal/modules.hpp" #include "internal/wrapper.hpp" #include "internal/tools.hpp" #include "internal/glsl.hpp" PyTypeObject * MGLRecorder_class; PyObject * MGLContext_meth_replay(MGLContext * self, PyObject * bytecode) { if (MGLBytecode::ptr != MGLBytecode::buffer) { return 0; } memcpy(&MGLBytecode::gl, &self->gl, sizeof(GLMethods)); MGLScope_begin_core(self->default_scope); Py_buffer view = {}; PyObject_GetBuffer(bytecode, &view, PyBUF_STRIDED_RO); PyBuffer_ToContiguous(MGLBytecode::buffer, &view, view.len, 'C'); PyBuffer_Release(&view); MGLBytecode::evaluate((int)view.len); MGLScope_end_core(self->default_scope); Py_RETURN_NONE; } MGLRecorder * MGLRecorder_meth_enter(MGLRecorder * self) { if (!MGLBytecode::buffer) { MGLBytecode::buffer = (char *)malloc(16384); MGLBytecode::ptr = MGLBytecode::buffer; } if (MGLBytecode::ptr != MGLBytecode::buffer) { return 0; } self->old_enable_only = self->context->current_enable_only; self->old_program_obj = self->context->current_program_obj; self->old_array_buffer_obj = self->context->current_array_buffer_obj; self->old_vertex_array_obj = self->context->current_vertex_array_obj; self->old_framebuffer_obj = self->context->current_framebuffer_obj; self->old_temp_texture_obj = self->context->current_temp_texture_obj; self->old_alignment = self->context->current_alignment; self->old_color_mask = self->context->current_color_mask; self->old_depth_mask = self->context->current_depth_mask; self->context->current_enable_only = 0; self->context->current_program_obj = 0; self->context->current_array_buffer_obj = 0; self->context->current_vertex_array_obj = 0; self->context->current_framebuffer_obj = 0; self->context->current_temp_texture_obj = 0; self->context->current_alignment = 0; self->context->current_color_mask = 0xffffffffffffffff; self->context->current_depth_mask = true; self->old_bound_framebuffer = self->context->bound_framebuffer; self->old_active_scope = self->context->active_scope; self->old_bound_scope = self->context->bound_scope; self->context->bound_framebuffer = self->context->default_framebuffer; self->context->active_scope = self->context->default_scope; self->context->bound_scope = self->context->default_scope; for (int i = 0; i < 32; ++i) { self->old_sampler_obj[i] = self->context->current_sampler_obj[i]; self->context->current_sampler_obj[i] = 0; } memcpy(&MGLBytecode::gl, &self->context->gl, sizeof(GLMethods)); void ** src = (void **)&MGLBytecode::rec; void ** dst = (void **)&self->context->gl; int size = sizeof(GLMethods) / sizeof(void *); for (int i = 0; i < size; ++i) { if (dst[i]) { dst[i] = src[i]; } } return NEW_REF(self); } PyObject * MGLRecorder_meth_exit(MGLRecorder * self) { self->context->current_enable_only = self->old_enable_only; self->context->current_program_obj = self->old_program_obj; self->context->current_array_buffer_obj = self->old_array_buffer_obj; self->context->current_vertex_array_obj = self->old_vertex_array_obj; self->context->current_framebuffer_obj = self->old_framebuffer_obj; self->context->current_temp_texture_obj = self->old_temp_texture_obj; self->context->current_alignment = self->old_alignment; self->context->current_color_mask = self->old_color_mask; self->context->current_depth_mask = self->old_depth_mask; self->context->bound_framebuffer = self->old_bound_framebuffer; self->context->active_scope = self->old_active_scope; self->context->bound_scope = self->old_bound_scope; for (int i = 0; i < 32; ++i) { self->context->current_sampler_obj[i] = self->old_sampler_obj[i]; } memcpy(&self->context->gl, &MGLBytecode::gl, sizeof(GLMethods)); Py_RETURN_NONE; } PyObject * MGLRecorder_meth_dump(MGLRecorder * self) { if (MGLBytecode::error) { MGLBytecode::error = false; MGLBytecode::ptr = MGLBytecode::buffer; return 0; } PyObject * res = PyBytes_FromStringAndSize(MGLBytecode::buffer, MGLBytecode::ptr - MGLBytecode::buffer); MGLBytecode::ptr = MGLBytecode::buffer; return res; } PyObject * MGLRecorder_meth_resize(MGLContext * self, PyObject * size) { if (MGLBytecode::ptr != MGLBytecode::buffer) { return 0; } Py_ssize_t alloc_size = unpack_size(size); free(MGLBytecode::buffer); if (alloc_size) { MGLBytecode::buffer = (char *)malloc(alloc_size); } else { MGLBytecode::buffer = 0; } MGLBytecode::ptr = MGLBytecode::buffer; Py_RETURN_NONE; } PyMethodDef MGLRecorder_methods[] = { {"__enter__", (PyCFunction)MGLRecorder_meth_enter, METH_NOARGS, 0}, {"__exit__", (PyCFunction)MGLRecorder_meth_exit, METH_VARARGS, 0}, {"dump", (PyCFunction)MGLRecorder_meth_dump, METH_NOARGS, 0}, {"resize", (PyCFunction)MGLRecorder_meth_resize, METH_O, 0}, {0}, }; PyType_Slot MGLRecorder_slots[] = { {Py_tp_methods, MGLRecorder_methods}, {0}, }; PyType_Spec MGLRecorder_spec = { mgl_ext ".Recorder", sizeof(MGLRecorder), 0, Py_TPFLAGS_DEFAULT, MGLRecorder_slots, }; void init_recording() { MGLBytecode::init(); MGLRecorder_class = (PyTypeObject *)PyType_FromSpec(&MGLRecorder_spec); }
33.96319
108
0.695448
einarf
687345c3397a7900c69085eea45bad4b1691fc32
961
cpp
C++
src/common/aggregator.cpp
paolofrb/cotson
1289b58ecc5d8279bc1124495ca0042f9586af11
[ "MIT" ]
null
null
null
src/common/aggregator.cpp
paolofrb/cotson
1289b58ecc5d8279bc1124495ca0042f9586af11
[ "MIT" ]
null
null
null
src/common/aggregator.cpp
paolofrb/cotson
1289b58ecc5d8279bc1124495ca0042f9586af11
[ "MIT" ]
null
null
null
// (C) Copyright 2006-2009 Hewlett-Packard Development Company, L.P. // // 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. // // $Id$ #include "aggregator.h" #include "error.h" Aggregator::Aggregator() : met(0),first(true) {} Aggregator::~Aggregator() {} void Aggregator::init(metric* m) { if(met) throw std::runtime_error("metric already set for this aggregator"); met=m; } void Aggregator::beat() { if(first) { first=false; do_first_beat(); } else do_beat(); } void Aggregator::last_beat() { do_end(); }
22.880952
77
0.71384
paolofrb
68747c42bf830d78e915ead8aa71da6ca7ae38fa
10,919
cc
C++
Graphs/Geometry/RecursiveGrid.cc
TrevorShelton/cplot
8bf40e94519cc4fd69b2e0677d3a3dcf8695245a
[ "MIT" ]
32
2017-11-27T03:04:44.000Z
2022-01-21T17:03:40.000Z
Graphs/Geometry/RecursiveGrid.cc
TrevorShelton/cplot
8bf40e94519cc4fd69b2e0677d3a3dcf8695245a
[ "MIT" ]
30
2017-11-10T09:47:16.000Z
2018-11-21T22:36:47.000Z
Graphs/Geometry/RecursiveGrid.cc
TrevorShelton/cplot
8bf40e94519cc4fd69b2e0677d3a3dcf8695245a
[ "MIT" ]
20
2018-01-05T17:15:11.000Z
2021-07-30T14:11:01.000Z
#include "RecursiveGrid.h" #include <queue> #include <cstring> //---------------------------------------------------------------------------------------------------------------------- // Constructors //---------------------------------------------------------------------------------------------------------------------- RecursiveGrid_2D::RecursiveGrid_2D(size_t nx, size_t ny, unsigned char d) : nx(nx), ny(ny) , nnx((nx+(1LL<<d)-1)>>d) , nny((ny+(1LL<<d)-1)>>d) , depth(d) , base(new Cells* [nnx*nny]) { assert(depth > 0); assert(nnx<<depth >= nx); assert(nny<<depth >= ny); memset(base.get(), 0, nnx*nny*sizeof(Cells*)); } RecursiveGrid_3D::RecursiveGrid_3D(size_t nx, size_t ny, size_t nz, unsigned char d) : nx(nx), ny(ny), nz(nz) , nnx((nx+(1LL<<d)-1)>>d) , nny((ny+(1LL<<d)-1)>>d) , nnz((nz+(1LL<<d)-1)>>d) , depth(d) , base(new Cells* [nnx*nny*nnz]) { assert(depth > 0); assert(nnx<<depth >= nx); assert(nny<<depth >= ny); assert(nnz<<depth >= nz); memset(base.get(), 0, nnx*nny*nnz*sizeof(Cells*)); } //---------------------------------------------------------------------------------------------------------------------- // get //---------------------------------------------------------------------------------------------------------------------- bool RecursiveGrid_2D::get(size_t x, size_t y) const { if (x >= nx || y >= ny) return false; Cells **b = base.get() + ((y>>depth)*nnx + (x>>depth)); for (int d = depth-1; d > 0; --d) { if (!*b) return false; b = (*b)->sub + (int)(((x>>d) & 1) | (((y>>d) & 1) << 1)); } int i = ((int)x & 1) | (((int)y & 1) << 1); return (*(unsigned*)b >> i) & 1; } bool RecursiveGrid_3D::get(size_t x, size_t y, size_t z) const { if (x >= nx || y >= ny || z >= nz) return false; Cells **b = base.get() + ((z>>depth)*nnx*nny + (y>>depth)*nnx + (x>>depth)); for (int d = depth-1; d > 0; --d) { if (!*b) return false; b = (*b)->sub + (int)(((x>>d) & 1) | (((y>>d) & 1) << 1) | (((z>>d) & 1) << 2)); } int i = ((int)x & 1) | (((int)y & 1) << 1) | (((int)z & 1) << 2); return (*(unsigned*)b >> i) & 1; } //---------------------------------------------------------------------------------------------------------------------- // set //---------------------------------------------------------------------------------------------------------------------- void RecursiveGrid_2D::set(size_t x, size_t y) { assert(x < nx && y < ny); Cells **b = base.get() + ((y>>depth)*nnx + (x>>depth)); for (int d = depth-1; d > 0; --d) { if (!*b) *b = new(pool) Cells; b = (*b)->sub + (int)(((x>>d) & 1) | (((y>>d) & 1) << 1)); } int j = ((int)x & 1) | (((int)y & 1) << 1); *(size_t*)b |= 1LL << j; } void RecursiveGrid_3D::set(size_t x, size_t y, size_t z) { assert(x < nx && y < ny && z < nz); Cells **b = base.get() + ((z>>depth)*nnx*nny + (y>>depth)*nnx + (x>>depth)); for (int d = depth-1; d > 0; --d) { if (!*b) *b = new(pool) Cells; b = (*b)->sub + (int)(((x>>d) & 1) | (((y>>d) & 1) << 1) | (((z>>d) & 1) << 2)); } int j = ((int)x & 1) | (((int)y & 1) << 1) | (((int)z & 1) << 2); *(size_t*)b |= 1LL << j; } //---------------------------------------------------------------------------------------------------------------------- // get_range - delegates to get_subblock for every top-level cell in the range //---------------------------------------------------------------------------------------------------------------------- bool RecursiveGrid_2D::get_range(size_t xm, size_t ym, int range) const { if (range <= 0) return range < 0 ? false : get(xm,ym); size_t x0 = xm>(size_t)range ? xm-range : 0, x1 = std::min(xm+range+1, nx); size_t y0 = ym>(size_t)range ? ym-range : 0, y1 = std::min(ym+range+1, ny); for (size_t x = x0, xx = ((x >> depth) << depth) + (1LL<<depth); x < x1; x = xx, xx += 1LL<<depth) { for (size_t y = y0, yy = ((y >> depth) << depth) + (1LL<<depth); y < y1; y = yy, yy += 1LL<<depth) { if (get_subblock(x,y, std::min(xx,x1),std::min(yy,y1))) return true; } } return false; } bool RecursiveGrid_3D::get_range(size_t xm, size_t ym, size_t zm, int range) const { if (range <= 0) return range < 0 ? false : get(xm,ym,zm); size_t x0 = xm>(size_t)range ? xm-range : 0, x1 = std::min(xm+range+1, nx); size_t y0 = ym>(size_t)range ? ym-range : 0, y1 = std::min(ym+range+1, ny); size_t z0 = zm>(size_t)range ? zm-range : 0, z1 = std::min(zm+range+1, nz); for (size_t x = x0, xx = ((x >> depth) << depth) + (1LL<<depth); x < x1; x = xx, xx += 1LL<<depth) { for (size_t y = y0, yy = ((y >> depth) << depth) + (1LL<<depth); y < y1; y = yy, yy += 1LL<<depth) { for (size_t z = z0, zz = ((z >> depth) << depth) + (1LL<<depth); z < z1; z = zz, zz += 1LL<<depth) { if (get_subblock(x,y,z, std::min(xx,x1),std::min(yy,y1),std::min(zz,z1))) return true; } } } return false; } //---------------------------------------------------------------------------------------------------------------------- // static helper functions for get_subblock //---------------------------------------------------------------------------------------------------------------------- static inline bool contains(size_t x, size_t y, size_t z, int w, size_t x0, size_t y0, size_t z0, size_t x1, size_t y1, size_t z1) { return (x >= x0 && x+w <= x1 && y >= y0 && y+w <= y1 && z >= z0 && z+w <= z1); } static inline bool intersects(size_t x, size_t y, size_t z, int w, size_t x0, size_t y0, size_t z0, size_t x1, size_t y1, size_t z1) { return (x < x1 && x0 < x+w && y < y1 && y0 < y+w && z < z1 && z0 < z+w); } static inline bool contains(size_t x, size_t y, size_t z, size_t x0, size_t y0, size_t z0, size_t x1, size_t y1, size_t z1) { return (x >= x0 && x < x1 && y >= y0 && y < y1 && z >= z0 && z < z1); } static inline bool contains(size_t x, size_t y, int w, size_t x0, size_t y0, size_t x1, size_t y1) { return (x >= x0 && x+w <= x1 && y >= y0 && y+w <= y1); } static inline bool intersects(size_t x, size_t y, int w, size_t x0, size_t y0, size_t x1, size_t y1) { return (x < x1 && x0 < x+w && y < y1 && y0 < y+w); } static inline bool contains(size_t x, size_t y, size_t x0, size_t y0, size_t x1, size_t y1) { return (x >= x0 && x < x1 && y >= y0 && y < y1); } //---------------------------------------------------------------------------------------------------------------------- // get_subblock 2D //---------------------------------------------------------------------------------------------------------------------- bool RecursiveGrid_2D::get_subblock(size_t x0, size_t y0, size_t x1, size_t y1) const { assert(x0 < x1 && y0 < y1); assert(x1-x0 <= 1ULL<<depth); assert(y1-y0 <= 1ULL<<depth); const Cells *b = base[(y0>>depth)*nnx + (x0>>depth)]; if (x1-x0 == 1ULL<<depth && y1-y0 == 1ULL<<depth) return b; if (!b) return false; size_t mask = (1 << depth)-1; x0 &= mask; x1 &= mask; if (!x1) x1 = 1ULL << mask; y0 &= mask; y1 &= mask; if (!y1) y1 = 1ULL << mask; struct Info { Info(size_t x, size_t y, const Cells *b, int d) : x(x), y(y), b(b), d(d){} size_t x,y; const Cells *b; int d; }; std::queue<Info> todo; for (todo.emplace(0,0,b,depth-1); !todo.empty(); todo.pop()) { Info &info = todo.front(); if (info.d > 0) { int w = 1 << info.d; #define CHK(i,dx,dy) do{ if (info.b->sub[i]){ \ if (contains(info.x+dx, info.y+dy, w, x0,y0,x1,y1)) return true; /*since info.b->sub[i] != NULL */ \ if (intersects(info.x+dx, info.y+dy, w, x0,y0,x1,y1)) todo.emplace(info.x+dx, info.y+dy, info.b->sub[i], info.d-1); \ }}while(0) CHK(0,0,0); CHK(1,w,0); CHK(2,0,w); CHK(3,w,w); #undef CHK } else { #define CHK(i,dx,dy) if ((((size_t)info.b >> i) & 1) && \ contains(info.x+dx, info.y+dy, x0,y0,x1,y1)) return true CHK(0,0,0); CHK(1,1,0); CHK(2,0,1); CHK(3,1,1); #undef CHK } } return false; } //---------------------------------------------------------------------------------------------------------------------- // get_subblock 3D //---------------------------------------------------------------------------------------------------------------------- bool RecursiveGrid_3D::get_subblock(size_t x0, size_t y0, size_t z0, size_t x1, size_t y1, size_t z1) const { assert(x0 < x1 && y0 < y1 && z0 < z1); assert(x1-x0 <= 1ULL<<depth); assert(y1-y0 <= 1ULL<<depth); assert(z1-z0 <= 1ULL<<depth); const Cells *b = base[(z0>>depth)*nnx*nny + (y0>>depth)*nnx + (x0>>depth)]; if (x1-x0 == 1ULL<<depth && y1-y0 == 1ULL<<depth && z1-z0 == 1ULL<<depth) return b; if (!b) return false; size_t mask = (1 << depth)-1; x0 &= mask; x1 &= mask; if (!x1) x1 = 1LL << mask; y0 &= mask; y1 &= mask; if (!y1) y1 = 1LL << mask; z0 &= mask; z1 &= mask; if (!z1) z1 = 1LL << mask; struct Info { Info(size_t x, size_t y, size_t z, const Cells *b, int d) : x(x), y(y), z(z), b(b), d(d){} size_t x,y,z; // top-left-front corner of this subblock const Cells *b; // the subblock int d; // its depth }; std::queue<Info> todo; for (todo.emplace(0,0,0,b,depth-1); !todo.empty(); todo.pop()) { Info &info = todo.front(); if (info.d > 0) { int w = 1 << info.d; #define CHK(i,dx,dy,dz) do{ if (info.b->sub[i]){ \ if (contains(info.x+dx, info.y+dy, info.z+dz, w, x0,y0,z0,x1,y1,z1)) return true; /*since b->sub[i] != NULL */ \ if (intersects(info.x+dx, info.y+dy, info.z+dz, w, x0,y0,z0,x1,y1,z1)) todo.emplace(info.x+dx, info.y+dy, info.z+dz, info.b->sub[i], info.d-1); \ }}while(0) CHK(0,0,0,0); CHK(1,w,0,0); CHK(2,0,w,0); CHK(3,w,w,0); CHK(4,0,0,w); CHK(5,w,0,w); CHK(6,0,w,w); CHK(7,w,w,w); #undef CHK } else { #define CHK(i,dx,dy,dz) if ((((size_t)info.b >> i) & 1) && \ contains(info.x+dx, info.y+dy, info.z+dz, x0,y0,z0,x1,y1,z1)) return true CHK(0,0,0,0); CHK(1,1,0,0); CHK(2,0,1,0); CHK(3,1,1,0); CHK(4,0,0,1); CHK(5,1,0,1); CHK(6,0,1,1); CHK(7,1,1,1); #undef CHK } } return false; } //---------------------------------------------------------------------------------------------------------------------- // printing // @todo way too slow, even for debugging //---------------------------------------------------------------------------------------------------------------------- std::ostream &operator<<(std::ostream &out, const RecursiveGrid_2D &g) { bool first = true; out << "G2D["; for (size_t y = 0; y < g.ny; ++y) { for (size_t x = 0; x < g.nx; ++x) { if (!g.get(x,y)) continue; if (!first) out << ", "; first = false; out << x << "-" << y; } } out << "]"; return out; } std::ostream &operator<<(std::ostream &out, const RecursiveGrid_3D &g) { bool first = true; out << "G3D["; for (size_t z = 0; z < g.nz; ++z) { for (size_t y = 0; y < g.ny; ++y) { for (size_t x = 0; x < g.nx; ++x) { if (!g.get(x,y,z)) continue; if (!first) out << ", "; first = false; out << x << "-" << y << "-" << z; } } } out << "]"; return out; }
31.557803
145
0.446927
TrevorShelton
68797e39a7b5007027a919354bb318ef2b711a69
2,906
cpp
C++
src/CTile.cpp
wlue/codename_portal
c7409cf9e756417974a7f284ade0bba24026c212
[ "MIT", "Unlicense" ]
1
2021-03-27T03:00:34.000Z
2021-03-27T03:00:34.000Z
src/CTile.cpp
wlue/codename_portal
c7409cf9e756417974a7f284ade0bba24026c212
[ "MIT", "Unlicense" ]
null
null
null
src/CTile.cpp
wlue/codename_portal
c7409cf9e756417974a7f284ade0bba24026c212
[ "MIT", "Unlicense" ]
null
null
null
#include "CTile.h" #include "CPortal.h" #include "CPlayer.h" CTile::CTile(string _type, int _x, int _y) : CObject(_x, _y), type(_type) { Initialize(); } CTile::~CTile() { Delete(); } void CTile::Initialize() { listtil.push_back(this); w = h = 32; TileSettings(); } void CTile::Delete() { RemoveElement<CTile*>(listtil, this); } void CTile::TileSettings() { setImage("tile", type); setDimensions(_img->w, _img->h); if(type == "spike") setLoc(getX(), getY() + TILE_HEIGHT/2 - getH()/2); else if(type == "nspike") setLoc(getX(), getY() - TILE_HEIGHT/2 + getH()/2); } void CTile::SetAttribute(string var, string val) { CObject::SetAttribute(var, val); } void CTile::LifeCycle() { CObject::LifeCycle(); if(type == "spike" && counter % 10 == 0) { vector<CPlayer*>::iterator a; for(a=listply.begin(); a!=listply.end(); ++a) if(collision::box(getX(), getY() - 1, getW(), getH(), (*a)->getX(), (*a)->getY(), (*a)->getW(), (*a)->getH())) { PlaySFX("spike"); (*a)->setHealth((*a)->getHealth() - 2); } } } bool CTile::isBase() { return type == "wall"; } bool CTile::isSupport() { return true; } bool CTile::canPassThrough() { return type == "glass" || type == "bglass"; } void CTile::Bumped(CDynamic* dyn) { CObject::Bumped(dyn); } bool CTile::canShatter() { return type == "bglass"; } bool CTile::canBreak() { return canShatter() || type == "bwall"; } void CTile::Shatter() { if(canShatter()) { PlaySFX("shatter"); DeleteObj(this); } } void CTile::Break() { PlaySFX("break"); DeleteObj(this); } bool CTile::inCollision(CObject* obj, double xloc, double yloc) { if(!isDense() || !obj->isDense() || obj == this || portal::inArea(this, getX(), getY())) return false; if(collision::box(xloc, yloc, getW(), getH(), obj->getX(), obj->getY(), obj->getW(), obj->getH())) return true; return false; } bool CTile::colException(CDynamic* dyn, double objXloc, double objYloc) { if(portal::inAreaOfEffect((CObject*) dyn, objXloc, objYloc) && portal::inAreaOfEffect(this, getX(), getY())) return true; return false; } bool CTile::canPlacePortal(int dir) { /* Conditions: - Tile must have adjacent valid blocks - Adjacent blocks must not have adjacent blocks blocking portal entrance */ CTile* left = getTileStep(this, dirTurn(dir, 90), 1); CTile* right = getTileStep(this, dirTurn(dir, -90), 1); CTile* center = getTileStep(this, dirTurn(dir, 180), 1); if(tile::isPortalBase(left) && tile::isPortalBase(right) && center == NULL) { CTile* leftLedge = getTileStep(left, dirTurn(dir, 180), 1); CTile* rightLedge = getTileStep(right, dirTurn(dir, 180), 1); if(leftLedge == NULL && rightLedge == NULL) return true; } return false; } // INDIV namespace tile { bool isPortalBase(CTile* t) { return t != NULL && t->isBase(); } bool isPortalSupport(CTile* t) { return t != NULL && t->isSupport(); } }
17.938272
113
0.628699
wlue
687a5c494ab31ef7cc673458fd0a5ffb12ea1f8d
2,444
cc
C++
src/buffered-stream-socket.cc
afett/clingeling
e6f6810dde5a1076e70f261ef738ae8f4dbd4e54
[ "BSD-2-Clause" ]
null
null
null
src/buffered-stream-socket.cc
afett/clingeling
e6f6810dde5a1076e70f261ef738ae8f4dbd4e54
[ "BSD-2-Clause" ]
null
null
null
src/buffered-stream-socket.cc
afett/clingeling
e6f6810dde5a1076e70f261ef738ae8f4dbd4e54
[ "BSD-2-Clause" ]
null
null
null
#include "buffered-stream-socket.h" #include "posix/socket.h" BufferedStreamSocket::BufferedStreamSocket( EPoll::Ctrl & poller, Posix::SocketFactory & socket_factory, Posix::SocketAddress const& addr) : sendbuf_{4096}, recvbuf_{4096}, socket_(socket_factory.make_stream_socket({ Posix::SocketFactory::Params::Domain::Inet, Posix::SocketFactory::Params::Type::Stream, Posix::Fd::Option::nonblock|Posix::Fd::Option::cloexec})), ev_{poll_events()}, poller_(poller) { connect(addr); recvbuf_.on_drain([this] () { update_poll_events(); }); poller.add(socket_, ev_, [this] (auto ev) { if (!ev) { return; } if (socket_->state() == Posix::StreamSocket::State::in_progress) { socket_->connect_continue(); update_poll_events(); return; } dispatch(ev, { {EPoll::Event::RdHup, [] () { throw std::runtime_error("RDHUP"); }}, {EPoll::Event::Pri, [] () { throw std::runtime_error("PRI"); }}, {EPoll::Event::Err, [] () { throw std::runtime_error("ERR"); }}, {EPoll::Event::Hup, [] () { throw std::runtime_error("HUP"); }}, {EPoll::Event::In, [this] () { on_readable(); }}, {EPoll::Event::Out, [this] () { on_writable(); }} }); update_poll_events(); }); } void BufferedStreamSocket::on_readable() { auto size = socket_->read(recvbuf_.wstart(), recvbuf_.wsize()); if (size == 0) { // FIXME throw std::runtime_error("Connection closed"); } recvbuf_.fill(size); } void BufferedStreamSocket::on_writable() { auto size = socket_->write(sendbuf_.rstart(), sendbuf_.rsize()); sendbuf_.drain(size); } void BufferedStreamSocket::connect(Posix::SocketAddress const& addr) { socket_->connect(addr); switch (socket_->state()) { case Posix::StreamSocket::State::init: throw std::runtime_error("Socket in state Init"); case Posix::StreamSocket::State::error: throw std::runtime_error("Socket in state Error"); case Posix::StreamSocket::State::in_progress: case Posix::StreamSocket::State::connected: break; } } void BufferedStreamSocket::update_poll_events() { if (auto ev = poll_events(); ev != ev_) { ev_ = ev; poller_.mod(socket_, ev_); } } EPoll::Events BufferedStreamSocket::poll_events() const { if (socket_->state() == Posix::StreamSocket::State::in_progress) { return EPoll::Events{EPoll::Event::Out}; } EPoll::Events ev; if (!sendbuf_.empty()) { ev |= EPoll::Event::Out; } if (!recvbuf_.full()) { ev |= EPoll::Event::In; } return ev; }
24.19802
71
0.664894
afett
6882bca9b740a50a803c687495c2bd33ff29de5e
1,433
cpp
C++
ABC188E_sequence_dp.cpp
pumbaacave/cppeers
454d286bdc4a62b5082b40ac80bd8d625a367b56
[ "Apache-2.0" ]
null
null
null
ABC188E_sequence_dp.cpp
pumbaacave/cppeers
454d286bdc4a62b5082b40ac80bd8d625a367b56
[ "Apache-2.0" ]
null
null
null
ABC188E_sequence_dp.cpp
pumbaacave/cppeers
454d286bdc4a62b5082b40ac80bd8d625a367b56
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <sstream> #include <vector> #include <string> #include <limits.h> #include <iomanip> #include <algorithm> #include <numeric> #include <functional> #include <unordered_map> #include <map> #include <unordered_set> #include <array> #include <math.h> #define rep(i, n) for (int i = 0; i < (n); i++) using namespace std; #define ll long long #define all(v) v.begin(),v.end() #define bootstrap ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); void solve() { long N, M; cin >> N >> M; vector<long> val; vector<unordered_set<long>> visit; rep(i, N) { long num; cin >> num; val.push_back(num); auto v = unordered_set<long>(); visit.push_back(v); } rep(i, M) { long l, r; cin >> l >> r; visit[l - 1].emplace(r - 1); } // lowest price possible before reaching city i. vector<long> dp(N, LONG_MAX); // dp[0] = 0; rep(l, N) { for (auto v: visit[l]) { // new min price from pre-cur cities dp[v] = min(dp[v], dp[l]); // new min price from cur city dp[v] = min(dp[v], val[l]); } } long ret = LONG_MIN; rep (i, N) { //cout << dp[i] << endl; if (dp[i] == LONG_MAX) continue; ret = max(ret, val[i] - dp[i]); } cout << ret << endl; return; } int main() { bootstrap solve(); }
21.38806
76
0.531752
pumbaacave
6888b42560113fed34540b4e167403525ab61ec3
1,410
cpp
C++
enemybullet.cpp
Loretac/ohlavache
2cbe309433cca0f7a61d8c08f6f4f383dd934f10
[ "MIT" ]
null
null
null
enemybullet.cpp
Loretac/ohlavache
2cbe309433cca0f7a61d8c08f6f4f383dd934f10
[ "MIT" ]
null
null
null
enemybullet.cpp
Loretac/ohlavache
2cbe309433cca0f7a61d8c08f6f4f383dd934f10
[ "MIT" ]
null
null
null
#include "enemybullet.h" #include <QTimer> /********************************************************************* ** *********************************************************************/ void EnemyBullet::setBulletPix(QPixmap map) { QPixmap scaled = map.scaled(getWidth(),getHeight()); setPixmap(scaled); } void EnemyBullet::setDimensions(int pixwidth, int pixheight) { width = pixwidth; height = pixheight; } int EnemyBullet::getCounter() { return counter; } void EnemyBullet::setCounter(int val) { counter = val; } int EnemyBullet::getWidth() { return width; } int EnemyBullet::getHeight() { return height; } void EnemyBullet::setSpeed(double val) { speed = val; } int EnemyBullet::getSpeed() { return speed; } void EnemyBullet::setXTrajectory(double val) { xTrajectory = val; } void EnemyBullet::setYTrajectory(double val) { yTrajectory = val; } double EnemyBullet::getXTrajectory() { return xTrajectory; } double EnemyBullet::getYTrajectory() { return yTrajectory; } void EnemyBullet::setMotion() { QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this,SLOT(move())); timer->start(5); } void EnemyBullet::checkStatus() { if(pos().y() > 600 || pos().y()+height < -100 || pos().x() > 800 || pos().x() + width < 0){ deleteLater(); } }
15.326087
71
0.562411
Loretac
688e96c51edbd75c5018d5fe7df6768d39ac5fd4
1,134
h++
C++
include/taussig/algorithms/flat_map.h++
rmartinho/taussig
896903e7cf47e943eba1253d2448cf193c61e97b
[ "CC0-1.0" ]
null
null
null
include/taussig/algorithms/flat_map.h++
rmartinho/taussig
896903e7cf47e943eba1253d2448cf193c61e97b
[ "CC0-1.0" ]
null
null
null
include/taussig/algorithms/flat_map.h++
rmartinho/taussig
896903e7cf47e943eba1253d2448cf193c61e97b
[ "CC0-1.0" ]
1
2020-07-09T19:41:00.000Z
2020-07-09T19:41:00.000Z
// Taussig // // Written in 2013 by Martinho Fernandes <martinho.fernandes@gmail.com> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // Sequence flat_map() algorithm #ifndef TAUSSIG_ALGORITHMS_FLAT_MAP_HPP #define TAUSSIG_ALGORITHMS_FLAT_MAP_HPP #include <taussig/algorithms/flatten.h++> #include <taussig/algorithms/map.h++> #include <utility> // declval namespace seq { namespace result_of { template <typename Fun, typename Seq> using flat_map = flatten<map<Fun, Seq>>; } // namespace result_of template <typename Fun, typename Seq> result_of::flat_map<Fun, Seq> flat_map(Fun&& fun, Seq&& s) { return seq::flatten(seq::map(std::forward<Fun>(fun), std::forward<Seq>(s))); } } // namespace seq #endif // TAUSSIG_ALGORITHMS_FLATTEN_HPP
30.648649
96
0.723986
rmartinho
688fd8fbd5cae4b587918b65f3ac6613136162dc
7,957
hpp
C++
SU2-Quantum/SU2_CFD/include/integration/CIntegration.hpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/SU2_CFD/include/integration/CIntegration.hpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/SU2_CFD/include/integration/CIntegration.hpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
1
2021-12-03T06:40:08.000Z
2021-12-03T06:40:08.000Z
/*! * \file CIntegration.hpp * \brief Declaration of the main routines to orchestrate space and time integration. * \author F. Palacios, T. Economon * \version 7.0.6 "Blackbird" * * SU2 Project Website: https://su2code.github.io * * The SU2 Project is maintained by the SU2 Foundation * (http://su2foundation.org) * * Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md) * * SU2 is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * SU2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with SU2. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <cmath> #include <iostream> #include <cstdlib> #include "../solvers/CSolver.hpp" #include "../../../Common/include/geometry/CGeometry.hpp" #include "../../../Common/include/CConfig.hpp" using namespace std; /*! * \class CIntegration * \brief Main class for doing the space integration, time integration, and monitoring * of a system of Partial Differential Equations (PDE). * \author F. Palacios */ class CIntegration { protected: int rank, /*!< \brief MPI Rank. */ size; /*!< \brief MPI Size. */ bool Convergence, /*!< \brief To indicate if the flow solver (direct, adjoint, or linearized) has converged or not. */ Convergence_FSI, /*!< \brief To indicate if the FSI problem has converged or not. */ Convergence_FullMG; /*!< \brief Initial value of the residual to evaluate the convergence level. */ /*! * \brief Do the space integration of the numerical system. * \param[in] geometry - Geometrical definition of the problem. * \param[in] solver_container - Container vector with all the solutions. * \param[in] solver - Description of the numerical method. * \param[in] config - Definition of the particular problem. * \param[in] iMesh - Index of the mesh in multigrid computations. * \param[in] iRKStep - Current step of the Runge-Kutta iteration. * \param[in] RunTime_EqSystem - System of equations which is going to be solved. */ void Space_Integration(CGeometry *geometry, CSolver **solver_container, CNumerics **numerics, CConfig *config, unsigned short iMesh, unsigned short iRKStep, unsigned short RunTime_EqSystem); /*! * \brief Do the time integration (explicit or implicit) of the numerical system. * \param[in] geometry - Geometrical definition of the problem. * \param[in] solver_container - Container vector with all the solutions. * \param[in] config - Definition of the particular problem. * \param[in] iRKStep - Current step of the Runge-Kutta iteration. * \param[in] RunTime_EqSystem - System of equations which is going to be solved. */ void Time_Integration(CGeometry *geometry, CSolver **solver_container, CConfig *config, unsigned short iRKStep, unsigned short RunTime_EqSystem); public: /*! * \brief Constructor of the class. */ CIntegration(); /*! * \brief Destructor of the class. */ virtual ~CIntegration(void) = default; /*! * \brief Get the indicator of the convergence for the direct, adjoint and linearized problem. * \return <code>TRUE</code> means that the convergence criteria is satisfied; * otherwise <code>FALSE</code>. */ inline bool GetConvergence(void) const { return Convergence; } /*! * \brief Get the indicator of the convergence for the Fluid-Structure Interaction problem. * \return <code>TRUE</code> means that the convergence criteria is satisfied; * otherwise <code>FALSE</code>. */ inline bool GetConvergence_FSI(void) const { return Convergence_FSI; } /*! * \brief Set the indicator of the convergence. * \param[in] value - <code>TRUE</code> means that the convergence criteria is satisfied; * otherwise <code>FALSE</code>. */ inline void SetConvergence(bool value) { Convergence = value; } /*! * \brief Set the indicator of the convergence for FSI. * \param[in] valueFSI - <code>TRUE</code> means that the convergence criteria for FSI is satisfied; * otherwise <code>FALSE</code>. */ inline void SetConvergence_FSI(bool valueFSI) { Convergence_FSI = valueFSI; } /*! * \brief Get the indicator of the convergence for the full multigrid problem. * \return <code>TRUE</code> means that the convergence criteria is satisfied; * otherwise <code>FALSE</code>. */ inline bool GetConvergence_FullMG(void) const { return Convergence_FullMG; } /*! * \brief Save the solution, and volume at different time steps. * \param[in] geometry - Geometrical definition of the problem. * \param[in] solution - Flow solution. * \param[in] config - Definition of the particular problem. */ void SetDualTime_Solver(CGeometry *geometry, CSolver *solver, CConfig *config, unsigned short iMesh); /*! * \brief Save the structural solution at different time steps. * \param[in] geometry - Geometrical definition of the problem. * \param[in] solver_container - Structural solution. * \param[in] config - Definition of the particular problem. */ void SetStructural_Solver(CGeometry *geometry, CSolver **solver_container, CConfig *config, unsigned short iMesh); /*! * \brief A virtual member. * \param[in] geometry - Geometrical definition of the problem. * \param[in] solver_container - Container vector with all the solutions. * \param[in] numerics_container - Description of the numerical method (the way in which the equations are solved). * \param[in] config - Definition of the particular problem. * \param[in] RunTime_EqSystem - System of equations which is going to be solved. */ virtual void MultiGrid_Iteration(CGeometry ****geometry, CSolver *****solver_container, CNumerics ******numerics_container, CConfig **config, unsigned short RunTime_EqSystem, unsigned short iZone, unsigned short iInst) { }; /*! * \brief A virtual member. * \param[in] geometry - Geometrical definition of the problem. * \param[in] solver_container - Container vector with all the solutions. * \param[in] numerics_container - Description of the numerical method (the way in which the equations are solved). * \param[in] config - Definition of the particular problem. * \param[in] RunTime_EqSystem - System of equations which is going to be solved. */ virtual void SingleGrid_Iteration(CGeometry ****geometry, CSolver *****solver_container, CNumerics ******numerics_container, CConfig **config, unsigned short RunTime_EqSystem, unsigned short iZone, unsigned short iInst) { }; /*! * \brief A virtual member. * \param[in] geometry - Geometrical definition of the problem. * \param[in] solver_container - Container vector with all the solutions. * \param[in] numerics_container - Description of the numerical method (the way in which the equations are solved). * \param[in] config - Definition of the particular problem. * \param[in] RunTime_EqSystem - System of equations which is going to be solved. */ virtual void Structural_Iteration(CGeometry ****geometry, CSolver *****solver_container, CNumerics ******numerics_container, CConfig **config, unsigned short RunTime_EqSystem, unsigned short iZone, unsigned short iInst) { }; };
44.205556
122
0.688073
Agony5757
689287b03d0d10ab674b209febe6a54401da6f99
1,619
cc
C++
deeplearning/ml4pl/graphs/graphviz_converter_py.cc
island255/ProGraML
6c4ea50639773009e7c287feb62c6994fa4f3445
[ "Apache-2.0" ]
1
2020-07-14T12:17:45.000Z
2020-07-14T12:17:45.000Z
deeplearning/ml4pl/graphs/graphviz_converter_py.cc
island255/ProGraML
6c4ea50639773009e7c287feb62c6994fa4f3445
[ "Apache-2.0" ]
null
null
null
deeplearning/ml4pl/graphs/graphviz_converter_py.cc
island255/ProGraML
6c4ea50639773009e7c287feb62c6994fa4f3445
[ "Apache-2.0" ]
null
null
null
// A python binding for the C++ graphviz conversion routine. // // Copyright 2019-2020 the ProGraML authors. // // Contact Chris Cummins <chrisc.101@gmail.com>. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <sstream> #include "deeplearning/ml4pl/graphs/graphviz_converter.h" #include "deeplearning/ml4pl/graphs/programl.pb.h" #include "labm8/cpp/string.h" #include <pybind11/pybind11.h> // Convert the given serialized program graph proto to a graphviz string. string ProgramGraphToGraphviz(const string& serializedProto, const string& nodeLabels) { // Parse the input protocol buffer. ml4pl::ProgramGraph graph; graph.ParseFromString(serializedProto); // Serialize to graphviz. std::stringstream buffer; ml4pl::SerializeGraphVizToString(graph, &buffer, nodeLabels); return buffer.str(); } PYBIND11_MODULE(graphviz_converter_py, m) { m.doc() = "Convert ProgramGraph protocol buffers to graphviz dot strings."; m.def("ProgramGraphToGraphviz", &ProgramGraphToGraphviz, "Convert the given serialized program graph proto to graphviz."); }
34.446809
77
0.742434
island255
68a05bbd8d0c192f7676a8f9ec52b1feeb3a091a
1,178
cpp
C++
HexGame/Engine/Graphics/View.cpp
kkorenev/HexGame
33aae3b589f9c032056eab27be653caefbc22f1c
[ "MIT" ]
null
null
null
HexGame/Engine/Graphics/View.cpp
kkorenev/HexGame
33aae3b589f9c032056eab27be653caefbc22f1c
[ "MIT" ]
null
null
null
HexGame/Engine/Graphics/View.cpp
kkorenev/HexGame
33aae3b589f9c032056eab27be653caefbc22f1c
[ "MIT" ]
null
null
null
#include <Engine/Graphics/View.hpp> View::View() : center(glm::vec2(0.f)), size(glm::vec2(1920.f, 1080.f)), scale(1.f), matrix(glm::mat4(1.f)), dirty(true) { } View::View(const glm::vec2& size) : center(glm::vec2(0.f)), size(size), scale(1.f), matrix(glm::mat4(1.f)), dirty(true) { } void View::setSize(const glm::vec2& value) { size = value; dirty = true; } const glm::vec2& View::getSize() const { return size; } void View::setScale(float value) { if (value <= 0) return; scale = value; dirty = true; } float View::getScale() const { return scale; } void View::setCenter(const glm::vec2& value) { center = value; dirty = true; } const glm::vec2& View::getCenter() const { return center; } void View::move(const glm::vec2& offset) { // должен быть +, но с - работает как надо center -= offset; dirty = true; } const glm::mat4& View::getMatrix() const { if (dirty) { matrix = glm::mat4(1.f); matrix = glm::ortho((-size.x / 2), (size.x / 2), (-size.y / 2), (size.y / 2)); matrix = glm::scale(matrix, glm::vec3(scale, scale, 1.f)); matrix = glm::translate(matrix, glm::vec3(center, 0.f)); dirty = false; } return matrix; }
14.365854
80
0.616299
kkorenev
68a4610a5b66548c03aecad85eb395290fbc53f4
512
cpp
C++
ftnoir_protocol_libevdev/ftnoir_protocol_libevdev_dialog.cpp
asarnow/opentrack
aed80a837d79eb6997435e062e5fbda0a140a715
[ "ISC" ]
null
null
null
ftnoir_protocol_libevdev/ftnoir_protocol_libevdev_dialog.cpp
asarnow/opentrack
aed80a837d79eb6997435e062e5fbda0a140a715
[ "ISC" ]
null
null
null
ftnoir_protocol_libevdev/ftnoir_protocol_libevdev_dialog.cpp
asarnow/opentrack
aed80a837d79eb6997435e062e5fbda0a140a715
[ "ISC" ]
null
null
null
#include "ftnoir_protocol_libevdev.h" #include "opentrack/plugin-api.hpp" LibevdevControls::LibevdevControls() { ui.setupUi( this ); connect(ui.btnOK, SIGNAL(clicked()), this, SLOT(doOK())); connect(ui.btnCancel, SIGNAL(clicked()), this, SLOT(doCancel())); } void LibevdevControls::doOK() { save(); this->close(); } void LibevdevControls::doCancel() { this->close(); } void LibevdevControls::save() { } extern "C" OPENTRACK_EXPORT IProtocolDialog* GetDialog( ) { return new LibevdevControls; }
18.962963
66
0.705078
asarnow
68a4c788264f3b50e1e3995b3aac7f8fa349d877
4,391
cpp
C++
src/misc/Timer.cpp
jmitchell24/cpp-utility-lib
76e7bae9f07b741c409a282604a999ab86fc0702
[ "Apache-2.0" ]
null
null
null
src/misc/Timer.cpp
jmitchell24/cpp-utility-lib
76e7bae9f07b741c409a282604a999ab86fc0702
[ "Apache-2.0" ]
null
null
null
src/misc/Timer.cpp
jmitchell24/cpp-utility-lib
76e7bae9f07b741c409a282604a999ab86fc0702
[ "Apache-2.0" ]
null
null
null
// Copyright 2013, James Mitchell, All rights reserved. #define _CRT_SECURE_NO_WARNINGS #include "Timer.hpp" using namespace util; using namespace std; Duration::Duration() : time(DefaultDuration::zero()) {} Duration::Duration(std::time_t const time) : time(Timer::Clock::from_time_t(time) - Timer::Clock::time_point()) {} Duration::CountType Duration::nanoseconds () const { return chrono::duration_cast<Nanoseconds> (time).count(); } Duration::CountType Duration::microseconds() const { return chrono::duration_cast<Microseconds>(time).count(); } Duration::CountType Duration::milliseconds() const { return chrono::duration_cast<Milliseconds>(time).count(); } Duration::CountType Duration::seconds () const { return chrono::duration_cast<Seconds> (time).count(); } Duration::CountType Duration::minutes () const { return chrono::duration_cast<Minutes> (time).count(); } Duration::CountType Duration::hours () const { return chrono::duration_cast<Hours> (time).count(); } Duration::CountType Duration::days () const { return chrono::duration_cast<Days> (time).count(); } Duration Duration::nanoseconds (CountParam c) { return (Duration)Nanoseconds (c); } Duration Duration::microseconds(CountParam c) { return (Duration)Microseconds(c); } Duration Duration::milliseconds(CountParam c) { return (Duration)Milliseconds(c); } Duration Duration::seconds (CountParam c) { return (Duration)Seconds (c); } Duration Duration::minutes (CountParam c) { return (Duration)Minutes (c); } Duration Duration::hours (CountParam c) { return (Duration)Hours (c); } Duration Duration::days (CountParam c) { return (Duration)Days (c); } time_t Duration::getTime() const { return Timer::Clock::to_time_t(Timer::Clock::time_point(chrono::duration_cast<Timer::Clock::duration>(time))); } Duration::DefaultDuration Duration::getDuration() const { return time; } Duration Duration::operator+ (Duration const& d) const { return Duration(time + d.time); } Duration Duration::operator- (Duration const& d) const { return Duration(time - d.time); } Duration& Duration::operator+=(Duration const& d) { return *this = *this + d; } Duration& Duration::operator-=(Duration const& d) { return *this = *this - d; } bool Duration::operator== (Duration const& d) const { return time == d.time; } bool Duration::operator!= (Duration const& d) const { return time != d.time; } bool Duration::operator< (Duration const& d) const { return time < d.time; } bool Duration::operator> (Duration const& d) const { return time > d.time; } bool Duration::operator<= (Duration const& d) const { return time <= d.time; } bool Duration::operator>= (Duration const& d) const { return time >= d.time; } string_t Duration::str() const { time_t const tme = getTime(); char const* const str = ctime(&tme); size_t const len = strlen(str); return string_t(str,str+len-1); } Duration Duration::durationFromCount(CountType count) { return Duration(DefaultDuration(count)); } Timer::Timer() : start_time(), last_duration(), is_recording(false) { } Timer::Timer(AutoStart) : Timer() { start(); } Timer::~Timer() {} void Timer::start() { is_recording = true; start_time = Clock::now(); } Duration Timer::stop() { if (is_recording) { is_recording = false; last_duration = Duration(Clock::now() - start_time); return last_duration; } return Duration(); } Duration Timer::reset() { Duration const d = stop(); start(); return d; } Duration Timer::getElapsedTime() const { return (is_recording) ? Duration(Clock::now() - start_time) : Duration(); } Duration Timer::getLastTime() const { return last_duration; } bool Timer::isRecording() const { return is_recording; } Duration Timer::getTimeSinceEpoch() { return Duration(Clock::now().time_since_epoch()); } ostream_t& util::formatToString(ostream_t& os, Segment const& format, Duration const& duration) { char_t buffer[64]; time_t const timeinfo = duration.getTime(); if (format.null_terminated) os.write(buffer, s_ftime(buffer, sizeof(buffer)/sizeof(char), format.begin , localtime(&timeinfo))); else os.write(buffer, s_ftime(buffer, sizeof(buffer)/sizeof(char), format.str().c_str(), localtime(&timeinfo))); return os; }
35.41129
147
0.685493
jmitchell24
68a4cd29b20ee961b7203aa3148535ce035a0c9e
241
cpp
C++
Zerojudge/d485.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
9
2017-10-08T16:22:03.000Z
2021-08-20T09:32:17.000Z
Zerojudge/d485.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
null
null
null
Zerojudge/d485.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
2
2018-01-15T16:35:44.000Z
2019-03-21T18:30:04.000Z
#include <iostream> #include <cmath> using namespace std; int main() { long long int a,b; int c,d; while(cin>>a>>b) { c=(b-b%2-(a+a%2))/2+1; cout<<c<<endl; } return 0; }
10.041667
31
0.431535
w181496
68ab106785f007571d03880dfb962c62808631f1
1,117
hpp
C++
Sources/AGEngine/Graphic/DRBPointLight.hpp
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
47
2015-03-29T09:44:25.000Z
2020-11-30T10:05:56.000Z
Sources/AGEngine/Graphic/DRBPointLight.hpp
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
313
2015-01-01T18:16:30.000Z
2015-11-30T07:54:07.000Z
Sources/AGEngine/Graphic/DRBPointLight.hpp
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
9
2015-06-07T13:21:54.000Z
2020-08-25T09:50:07.000Z
#pragma once #include "BFC/BFCCullableObject.hpp" #include "BFCCullableTypes.hpp" #include "AssetManagement\Instance\MeshInstance.hh" namespace AGE { struct DRBPointLightData; struct DRBPointLight : public BFCCullableObject { public: DRBPointLight(); virtual glm::vec4 setBFCTransform(const glm::mat4 &transformation) override; void setRange(const glm::vec4 &range); void updateRange(const glm::mat4 &transformation); inline const glm::vec3 &getRange() const { return _range; } inline const glm::vec3 &getPosition() const { return _position; } inline const glm::mat4 &getSphereTransform() const { return _sphereTransform; } inline const glm::vec3 &getColorLight() const { return _colorLight; } inline const glm::vec3 &getAmbiantColor() const { return _ambiantColor; } inline void setColorLight(const glm::vec4 &color) { _colorLight = glm::vec3(color); } inline void setAmbiantColor(const glm::vec4 &color) { _ambiantColor = glm::vec3(color); } private: glm::vec3 _range; glm::mat4 _sphereTransform; glm::vec3 _position; glm::vec3 _colorLight; glm::vec3 _ambiantColor; }; }
31.027778
91
0.743957
Another-Game-Engine
68b0adcd014e08499574ed21664b26e96fb5a914
1,949
cpp
C++
Graph Problems/BFS & DFS/UVA532 - Dungeon Master/Code.cpp
adelnobel/Training-for-ACM-ICPC-problems
8030d24ab3ce1f50821b22647bf9195b41f932b1
[ "MIT" ]
1
2020-03-05T09:09:36.000Z
2020-03-05T09:09:36.000Z
Graph Problems/BFS & DFS/UVA532 - Dungeon Master/Code.cpp
adelnobel/Training-for-ACM-ICPC-problems
8030d24ab3ce1f50821b22647bf9195b41f932b1
[ "MIT" ]
null
null
null
Graph Problems/BFS & DFS/UVA532 - Dungeon Master/Code.cpp
adelnobel/Training-for-ACM-ICPC-problems
8030d24ab3ce1f50821b22647bf9195b41f932b1
[ "MIT" ]
null
null
null
#include <vector> #include <cstdio> #include <cstring> #include <queue> #include <cctype> #include <cmath> #include <algorithm> #include <iostream> #include <bitset> #include <map> #include <complex> #include <ctime> #include <numeric> #include <set> using namespace std; typedef long long ll; int dz[] = {1, -1, 0, 0, 0, 0}; int dr[] = {0, 0, 1, -1, 0, 0}; int dc[] = {0, 0, 0, 0, 1, -1}; int Z, R, C; char g[32][32][32]; bool vis[32][32][32]; typedef struct node{ int z, r, c, cost; node(){}; node(int zz, int rr, int cc, int co){ z = zz, r = rr, c = cc, cost = co; } }node; bool isValid(node &c){ if(c.z < 0 || c.z == Z || c.r < 0 || c.r == R || c.c < 0 || c.c == C || vis[c.z][c.r][c.c]){ return false; } return true; } int bfs(node start){ queue< node > q; q.push(start); while(!q.empty()){ node c = q.front(); q.pop(); if(g[c.z][c.r][c.c] == 'E') return c.cost; for(int i = 0; i < 6; i++){ node cur = node(c.z + dz[i], c.r + dr[i], c.c + dc[i], c.cost + 1); if(isValid(cur)){ vis[cur.z][cur.r][cur.c] = true; q.push(cur); } } } return -1; } int main() { #ifndef ONLINE_JUDGE freopen("in.in", "r", stdin); #endif while(scanf("%d%d%d", &Z, &R, &C), Z || R || C){ memset(vis, false, sizeof vis); node start; for(int i = 0; i < Z; i++){ for(int j = 0; j < R; j++){ scanf("%s", g[i][j]); for(int k = 0; k < C; k++){ if(g[i][j][k] == '#') vis[i][j][k] = true; else if(g[i][j][k] == 'S') start = node(i, j, k, 0); } } } int res = bfs(start); if(res == -1){ printf("Trapped!\n"); }else{ printf("Escaped in %d minute(s).\n", res); } } return 0; }
21.417582
96
0.431503
adelnobel
68b1a069796a6be044bdbe66f97a8a58d2877366
12,428
cpp
C++
src/render/renderer.cpp
colintan95/gfx_engine
b873488141787825a78bf5a8d6de2679333554eb
[ "MIT" ]
null
null
null
src/render/renderer.cpp
colintan95/gfx_engine
b873488141787825a78bf5a8d6de2679333554eb
[ "MIT" ]
null
null
null
src/render/renderer.cpp
colintan95/gfx_engine
b873488141787825a78bf5a8d6de2679333554eb
[ "MIT" ]
null
null
null
#include "render/renderer.h" #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include <cassert> #include <cstddef> #include <cstdlib> #include <fstream> #include <iostream> #include <memory> #include <new> #include <optional> #include <utility> #include <vector> // #include "gal/gal_buffer.h" #include "gal/gal_command_buffer.h" #include "gal/gal_pipeline.h" #include "gal/gal_shader.h" // #include "gal/gal_texture_sampler.h" // #include "resource/resource_gal.h" // #include "resource/resource_manager_gal.h" #include "resource/image_loader.h" #include "resource/resource_system.h" #include "window/window.h" namespace { struct Vertex { glm::vec2 pos; glm::vec3 color; }; } // namespace namespace render { Renderer::Renderer(window::Window* window, resource::ResourceSystem* resource_system) { window_ = window; resource_system_ = resource_system; try { gal_platform_ = std::make_unique<gal::GALPlatform>(window_); } catch (gal::GALPlatform::InitException& e) { std::cerr << e.what() << std::endl; throw InitException(); } catch (std::bad_alloc& ba) { throw InitException(); } // TODO(colintan): Make this into a separate class std::ifstream vert_shader_file("shaders/triangle_vert.spv", std::ios::ate | std::ios::binary); if (!vert_shader_file.is_open()) { std::cerr << "Could not open vertex shader file." << std::endl; throw InitException(); } size_t vert_shader_file_size = static_cast<size_t>(vert_shader_file.tellg()); vert_shader_file.seekg(0); std::vector<std::byte> vert_shader_binary(vert_shader_file_size); vert_shader_file.read(reinterpret_cast<char*>(vert_shader_binary.data()), vert_shader_file_size); std::ifstream frag_shader_file("shaders/triangle_frag.spv", std::ios::ate | std::ios::binary); if (!frag_shader_file.is_open()) { std::cerr << "Could not open fragment shader file." << std::endl; throw InitException(); } size_t frag_shader_file_size = static_cast<size_t>(frag_shader_file.tellg()); frag_shader_file.seekg(0); std::vector<std::byte> frag_shader_binary(frag_shader_file_size); frag_shader_file.read(reinterpret_cast<char*>(frag_shader_binary.data()), frag_shader_file_size); gal::GALShader vert_shader; if (!vert_shader.CreateFromBinary(gal_platform_.get(), gal::ShaderType::Vertex, vert_shader_binary)) { std::cerr << "Failed to create GAL vertex shader." << std::endl; throw InitException(); } gal::GALShader frag_shader; if (!frag_shader.CreateFromBinary(gal_platform_.get(), gal::ShaderType::Fragment, frag_shader_binary)) { std::cerr << "Failed to create GAL fragment shader." << std::endl; throw InitException(); } gal::GALPipelineBuilder::Viewport viewport; viewport.x = 0; viewport.y = 0; viewport.width = window_->GetWidth(); viewport.height = window_->GetHeight(); gal::GALPipelineBuilder::VertexInput vert_input; vert_input.buffer_idx = 0; vert_input.stride = sizeof(Vertex); gal::GALPipelineBuilder::VertexDesc pos_desc; pos_desc.buffer_idx = 0; pos_desc.shader_idx = 0; pos_desc.num_components = 2; pos_desc.offset = 0; gal::GALPipelineBuilder::VertexDesc color_desc; color_desc.buffer_idx = 0; color_desc.shader_idx = 1; color_desc.num_components = 3; color_desc.offset = 2 * sizeof(float); gal::GALPipelineBuilder::UniformDesc uniform_desc; uniform_desc.shader_idx = 0; uniform_desc.shader_stage = gal::ShaderType::Vertex; try { pipeline_ = gal::GALPipeline::BeginBuild(gal_platform_.get()) .SetShader(gal::ShaderType::Vertex, vert_shader) .SetShader(gal::ShaderType::Fragment, frag_shader) .SetViewport(viewport) .AddVertexInput(vert_input) .AddVertexDesc(pos_desc) .AddVertexDesc(color_desc) .AddUniformDesc(uniform_desc) .Create(); } catch (gal::GALPipeline::InitException& e) { std::cerr << e.what() << std::endl; throw InitException(); } frag_shader.Destroy(); vert_shader.Destroy(); std::vector<Vertex> vertices = { {{0.f, -0.5f}, {1.f, 0.f, 0.f}}, {{0.5f, 0.5f}, {0.f, 1.f, 0.f}}, {{-0.5f, 0.5f,}, {0.f, 0.f, 1.f}} }; try { vert_buffer_ = gal::GALBuffer::BeginBuild(gal_platform_.get()) .SetType(gal::BufferType::Vertex) .SetBufferData(reinterpret_cast<uint8_t*>(vertices.data()), sizeof(Vertex) * vertices.size()) .Create(); } catch (gal::GALBuffer::InitException& e) { std::cerr << e.what() << std::endl; throw InitException(); } try { command_buffer_ = gal::GALCommandBuffer::BeginBuild(gal_platform_.get()).Create(); } catch (gal::GALCommandBuffer::InitException& e) { std::cerr << e.what() << std::endl; throw InitException(); } if (!command_buffer_.BeginRecording()) { std::cerr << "Command buffer could not begin recording." << std::endl; throw InitException(); } gal::command::SetPipeline set_pipeline; set_pipeline.pipeline = pipeline_; command_buffer_.SubmitCommand(set_pipeline); gal::command::SetVertexBuffer set_vert_buf; set_vert_buf.buffer = vert_buffer_; set_vert_buf.buffer_idx = 0; command_buffer_.SubmitCommand(set_vert_buf); gal::command::DrawTriangles draw_triangles; draw_triangles.num_triangles = 1; command_buffer_.SubmitCommand(draw_triangles); if (!command_buffer_.EndRecording()) { std::cerr << "Command buffer could not end recording." << std::endl; throw InitException(); } // resource_manager_ = std::make_unique<resource::ResourceManagerGAL>(gal_platform_.get()); // MeshId mesh_id; // if (std::optional<MeshId> mesh_id_opt = CreateMesh("assets/cube/cube.obj")) { // mesh_id = *mesh_id_opt; // } else { // std::cerr << "Failed to create mesh." << std::endl; // throw InitException(); // } // Mesh& cube_mesh = meshes_[mesh_id]; // resource::Handle<resource::Image> image_handle = // resource_system_->LoadImage("assets/cube/default.png"); // if (!image_handle.IsValid()) { // std::cerr << "Failed to load image." << std::endl; // throw InitException(); // } // resource::Image& image = image_handle.Get(); // command_buffer_.SetPlatform(gal_platform_.get()); // gal::command::SetViewport set_viewport; // set_viewport.x = 0; // set_viewport.y = 0; // set_viewport.width = window_->GetWidth(); // set_viewport.height = window_->GetHeight(); // command_buffer_.Add(set_viewport); // gal::GALShader vert_shader; // if (!vert_shader.Create(gal_platform_.get(), gal::ShaderType::Vertex, kVertShaderSrc)) { // std::cerr << "Failed to create GAL vertex shader." << std::endl; // throw InitException(); // } // gal::GALShader frag_shader; // if (!frag_shader.Create(gal_platform_.get(), gal::ShaderType::Fragment, kFragShaderSrc)) { // std::cerr << "Failed to create GAL fragment shader." << std::endl; // throw InitException(); // } // gal::GALPipeline pipeline; // if (!pipeline.Create(gal_platform_.get(), vert_shader, frag_shader)) { // std::cerr << "Failed to create GAL pipeline." << std::endl; // throw InitException(); // } // pipeline.GetVertexDesc().SetAttribute(0, 3); // pipeline.GetVertexDesc().SetAttribute(2, 2); // frag_shader.Destroy(); // vert_shader.Destroy(); // gal::command::SetPipeline set_pipeline; // set_pipeline.pipeline = pipeline; // command_buffer_.Add(set_pipeline); // struct { // glm::mat4 model_mat; // glm::mat4 view_mat; // glm::mat4 proj_mat; // } uniform_data; // float aspect_ratio = // static_cast<float>(window_->GetWidth()) / static_cast<float>(window_->GetHeight()); // uniform_data.model_mat = glm::mat4{1.f}; // uniform_data.view_mat = glm::translate(glm::mat4{1.f}, glm::vec3{0.f, 0.f, -10.f}) * // glm::rotate(glm::mat4{1.f}, glm::radians(-15.f), glm::vec3{0.f, 1.f, 0.f}); // uniform_data.proj_mat = glm::perspective(glm::radians(30.f), aspect_ratio, 0.1f, 1000.f); // resource::HandleGALBuffer uniform_buf_handle = // resource_manager_->CreateBuffer(gal::BufferType::Uniform, // reinterpret_cast<uint8_t*>(&uniform_data), // sizeof(uniform_data)); // if (!uniform_buf_handle.IsValid()) { // std::cerr << "Failed to create GAL buffer for uniforms." << std::endl; // throw InitException(); // } // gal::command::SetUniformBuffer set_uniform_buf; // set_uniform_buf.buffer = uniform_buf_handle.Get(); // set_uniform_buf.idx = 0; // command_buffer_.Add(set_uniform_buf); // resource::HandleGALTexture texture_handle = // resource_manager_->CreateTexture(gal::TextureType::Texture2D, gal::TextureFormat::RGB, // image.width, image.height, image.pixels.data()); // if (!texture_handle.IsValid()) { // std::cerr << "Failed to create GAL texture." << std::endl; // throw InitException(); // } // gal::GALTextureSampler tex_sampler; // if (!tex_sampler.Create(gal_platform_.get(), texture_handle.Get())) { // std::cerr << "Failed to create GAL texture sampler." << std::endl; // throw InitException(); // } // gal::command::SetTextureSampler set_tex_sampler; // set_tex_sampler.sampler = tex_sampler; // set_tex_sampler.idx = 1; // command_buffer_.Add(set_tex_sampler); // gal::command::SetVertexBuffer set_pos_vert_buf; // set_pos_vert_buf.buffer = cube_mesh.pos_buf_.Get(); // set_pos_vert_buf.vert_idx = 0; // command_buffer_.Add(set_pos_vert_buf); // gal::command::SetVertexBuffer set_texcoord_vert_buf; // set_texcoord_vert_buf.buffer = cube_mesh.texcoord_buf_.Get(); // set_texcoord_vert_buf.vert_idx = 2; // command_buffer_.Add(set_texcoord_vert_buf); // gal::command::ClearScreen clear_screen; // clear_screen.color = glm::vec4{0.f, 0.f, 0.f, 1.f}; // clear_screen.clear_color = true; // clear_screen.clear_depth = true; // command_buffer_.Add(clear_screen); // gal::command::DrawTriangles draw_triangles; // draw_triangles.num_triangles = cube_mesh.faces; // command_buffer_.Add(draw_triangles); // resource::ModelLoader model_loader; // std::shared_ptr<resource::Model> model = model_loader.LoadModel("assets/cube/cube.obj"); } Renderer::~Renderer() { command_buffer_.Destroy(); pipeline_.Destroy(); // resource_manager_.reset(); gal_platform_.reset(); resource_system_ = nullptr; window_ = nullptr; } void Renderer::Tick() { gal_platform_->StartTick(); gal_platform_->ExecuteCommandBuffer(command_buffer_); gal_platform_->EndTick(); // gal_platform_->ExecuteCommandBuffer(command_buffer_); } // std::optional<MeshId> Renderer::CreateMesh(const std::string& file_path) { // resource::Handle<resource::Model> model_handle = resource_system_->LoadModel(file_path); // if (!model_handle.IsValid()) { // return std::nullopt; // } // resource::Model& model = model_handle.Get(); // static int counter = 0; // ++counter; // MeshId mesh_id = counter; // Mesh& mesh = meshes_[mesh_id]; // if (!model.positions.empty()) { // resource::HandleGALBuffer pos_buf_handle = // resource_manager_->CreateBuffer(gal::BufferType::Vertex, // reinterpret_cast<uint8_t*>(model.positions.data()), // model.positions.size() * sizeof(glm::vec3)); // if (!pos_buf_handle.IsValid()) { // return std::nullopt; // } // mesh.pos_buf_ = std::move(pos_buf_handle); // } // // TODO(colintan): Add for normals data // if (!model.texcoords.empty()) { // resource::HandleGALBuffer texcoord_buf_handle = // resource_manager_->CreateBuffer(gal::BufferType::Vertex, // reinterpret_cast<uint8_t*>(model.texcoords.data()), // model.texcoords.size() * sizeof(glm::vec2)); // if (!texcoord_buf_handle.IsValid()) { // return std::nullopt; // } // mesh.texcoord_buf_ = std::move(texcoord_buf_handle); // } // mesh.faces = model.faces; // // TODO(colintan): Release the resource - automatically or via a call to ResourceManager // return mesh_id; // } } // namespace
33.319035
99
0.662778
colintan95
68b1f6ece4b200cf036c3a643561f41e755eb260
850
hh
C++
src/core/event/InputEventHandler.hh
eddiehoyle/sevengine
4f5bd2b16b1179784c831ef8a0d57ccecee0a92e
[ "MIT" ]
1
2019-08-21T05:06:04.000Z
2019-08-21T05:06:04.000Z
src/core/event/InputEventHandler.hh
eddiehoyle/sevengine
4f5bd2b16b1179784c831ef8a0d57ccecee0a92e
[ "MIT" ]
null
null
null
src/core/event/InputEventHandler.hh
eddiehoyle/sevengine
4f5bd2b16b1179784c831ef8a0d57ccecee0a92e
[ "MIT" ]
null
null
null
// // Created by Eddie Hoyle on 14/09/16. // #ifndef SEV_INPUTHANDLER_HH #define SEV_INPUTHANDLER_HH #include <iostream> #include <vector> #include <queue> #include "AbstractEvent.hh" typedef std::queue < AbstractEvent* > EventQueue; class InputEventHandler { public: InputEventHandler() { m_events = EventQueue(); }; ~InputEventHandler() {}; void push( AbstractEvent* event ); void push( int index ); AbstractEvent* next() { AbstractEvent* event = m_events.front(); m_events.pop(); return event; }; void flush() { // TODO } bool empty() { return m_events.empty(); } std::vector< int > m_nums; EventQueue m_events; // std::queue< AbstractEvent* > m_events; //private: }; #endif //SEV_INPUTHANDLER_HH
14.655172
50
0.595294
eddiehoyle
68b2511dffaad442afa47eddc0447b22a187895d
568
cpp
C++
173. Binary Search Tree Iterator.cpp
qinenergy/leetCode
79f960795445470a16a4755b05aa05f99e5c616b
[ "MIT" ]
3
2017-02-22T14:28:27.000Z
2017-04-26T16:26:06.000Z
173. Binary Search Tree Iterator.cpp
qinenergy/leetCode
79f960795445470a16a4755b05aa05f99e5c616b
[ "MIT" ]
null
null
null
173. Binary Search Tree Iterator.cpp
qinenergy/leetCode
79f960795445470a16a4755b05aa05f99e5c616b
[ "MIT" ]
null
null
null
class BSTIterator { public: BSTIterator(TreeNode *root) { _push(root); } /** @return whether we have a next smallest number */ bool hasNext() { return !_stack.empty(); } /** @return the next smallest number */ int next() { auto node = _stack.top(); _stack.pop(); _push(node->right); return node->val; } void _push(TreeNode* node){ while(node != nullptr){ _stack.push(node); node = node->left; } } private: stack<TreeNode*> _stack; };
20.285714
57
0.521127
qinenergy
68b64f1f1b55fe5563887a5eb7da36008996dceb
347
cc
C++
src/commands/APC.cc
jhhuh/imgui-terminal
134f9cb6779738ecf00d6aba8315702986f71115
[ "MIT" ]
32
2017-09-19T07:25:29.000Z
2022-03-21T08:21:48.000Z
src/commands/APC.cc
jhhuh/imgui-terminal
134f9cb6779738ecf00d6aba8315702986f71115
[ "MIT" ]
1
2017-10-24T18:56:36.000Z
2017-10-24T18:56:36.000Z
src/commands/APC.cc
jhhuh/imgui-terminal
134f9cb6779738ecf00d6aba8315702986f71115
[ "MIT" ]
10
2017-10-18T05:08:14.000Z
2022-03-21T09:29:04.000Z
#include <terminal/Terminal.hh> #include <algorithm> // min, max namespace terminal { // Application Program Command // ECMA-48 8.3.2 bool Terminal::APC(const std::string &p) { if (m_verbose) log("APC"); // noop // APC : <lots> ST DECEKBD extended keyboard report return false; } }
15.086957
70
0.570605
jhhuh
68bb49db9ed66b9268ba935756f86ba5534777f1
4,448
cpp
C++
test/feature/canvas_test.cpp
fuersten/sun_ray
b882d67cd9747f61b50def4c1414e7552ba917c0
[ "BSD-3-Clause" ]
2
2021-03-28T21:36:36.000Z
2021-08-10T14:44:04.000Z
test/feature/canvas_test.cpp
fuersten/sun_ray
b882d67cd9747f61b50def4c1414e7552ba917c0
[ "BSD-3-Clause" ]
null
null
null
test/feature/canvas_test.cpp
fuersten/sun_ray
b882d67cd9747f61b50def4c1414e7552ba917c0
[ "BSD-3-Clause" ]
null
null
null
// // tuple_test.cpp // sun_ray_test // // Created by Lars-Christian Fürstenberg on 25.12.19. // Copyright © 2019 Lars-Christian Fürstenberg. All rights reserved. // #include <sun_ray/feature/canvas.h> #include <sstream> #include <catch2/catch.hpp> TEST_CASE("create canvas", "[canvas]") { SECTION("create canvas") { sunray::Canvas canvas{10, 20}; CHECK(10 == canvas.width()); CHECK(20 == canvas.height()); const auto black = sunray::Color{0, 0, 0}; auto only_black{true}; for (uint32_t y = 0; y < 20; ++y) { for (uint32_t x = 0; x < 10; ++x) { if (canvas.pixel_at(x, y) != black) { only_black = false; } } } CHECK(only_black == true); } } TEST_CASE("stream canvas", "[canvas]") { SECTION("stream canvas") { sunray::Canvas canvas{10, 20}; std::stringstream ss; ss << canvas; CHECK("width: 10 height: 20" == ss.str()); } } TEST_CASE("copy canvas", "[canvas]") { SECTION("copy canvas") { sunray::Canvas canvas{10, 20}; const auto black = sunray::Color{0, 0, 0}; const auto red = sunray::Color{1.0f, 0, 0}; CHECK(10 == canvas.width()); CHECK(20 == canvas.height()); canvas.pixel_at(0, 0, red); canvas.pixel_at(0, 10, red); canvas.pixel_at(9, 0, red); canvas.pixel_at(9, 19, red); sunray::Canvas canvas2{canvas}; CHECK(10 == canvas2.width()); CHECK(20 == canvas2.height()); CHECK(canvas2.pixel_at(0, 0) == red); CHECK(canvas2.pixel_at(0, 10) == red); CHECK(canvas2.pixel_at(9, 0) == red); CHECK(canvas2.pixel_at(9, 19) == red); CHECK(canvas2.pixel_at(0, 1) == black); CHECK(canvas2.pixel_at(1, 10) == black); CHECK(canvas2.pixel_at(9, 1) == black); CHECK(canvas2.pixel_at(8, 19) == black); } SECTION("move canvas") { sunray::Canvas canvas{10, 20}; const auto black = sunray::Color{0, 0, 0}; const auto red = sunray::Color{1.0f, 0, 0}; CHECK(10 == canvas.width()); CHECK(20 == canvas.height()); canvas.pixel_at(0, 0, red); canvas.pixel_at(0, 10, red); canvas.pixel_at(9, 0, red); canvas.pixel_at(9, 19, red); sunray::Canvas canvas2{std::move(canvas)}; CHECK(10 == canvas2.width()); CHECK(20 == canvas2.height()); CHECK(canvas2.pixel_at(0, 0) == red); CHECK(canvas2.pixel_at(0, 10) == red); CHECK(canvas2.pixel_at(9, 0) == red); CHECK(canvas2.pixel_at(9, 19) == red); CHECK(canvas2.pixel_at(0, 1) == black); CHECK(canvas2.pixel_at(1, 10) == black); CHECK(canvas2.pixel_at(9, 1) == black); CHECK(canvas2.pixel_at(8, 19) == black); } } TEST_CASE("canvas pixels", "[canvas]") { SECTION("canvas read pixel out of range") { sunray::Canvas canvas{10, 20}; CHECK_THROWS_AS(canvas.pixel_at(10, 20), std::out_of_range); CHECK_THROWS_AS(canvas.pixel_at(9, 20), std::out_of_range); CHECK_THROWS_AS(canvas.pixel_at(11, 20), std::out_of_range); CHECK_THROWS_AS(canvas.pixel_at(9, 21), std::out_of_range); } SECTION("canvas write pixel out of range") { sunray::Canvas canvas{10, 20}; const auto red = sunray::Color{1.0f, 0, 0}; CHECK_THROWS_AS(canvas.pixel_at(10, 20, red), std::out_of_range); CHECK_THROWS_AS(canvas.pixel_at(9, 20, red), std::out_of_range); CHECK_THROWS_AS(canvas.pixel_at(11, 20, red), std::out_of_range); CHECK_THROWS_AS(canvas.pixel_at(9, 21, red), std::out_of_range); } SECTION("canvas write/read pixel") { sunray::Canvas canvas{10, 20}; const auto black = sunray::Color{0, 0, 0}; const auto red = sunray::Color{1.0f, 0, 0}; const auto green = sunray::Color{0, 1.0f, 0}; const auto blue = sunray::Color{0, 0, 1.0f}; const auto orange = sunray::Color{1.0f, 0.647f, 0}; canvas.pixel_at(0, 0, red); canvas.pixel_at(0, 10, orange); canvas.pixel_at(9, 0, green); canvas.pixel_at(9, 19, blue); for (uint32_t y = 0; y < 20; ++y) { for (uint32_t x = 0; x < 10; ++x) { if (x == 0 && y == 0) { CHECK(canvas.pixel_at(x, y) == red); } else if (x == 0 && y == 10) { CHECK(canvas.pixel_at(x, y) == orange); } else if (x == 9 && y == 0) { CHECK(canvas.pixel_at(x, y) == green); } else if (x == 9 && y == 19) { CHECK(canvas.pixel_at(x, y) == blue); } else { if (canvas.pixel_at(x, y) != black) { CHECK_FALSE(true); } } } } } }
28.151899
69
0.584982
fuersten
68bc1d3c85549ba8ed4d94583aa8ced473a5e2ef
3,983
cpp
C++
Test/SourceCppGen/WorkflowAttributesReflection.cpp
vczh2/Workflow
7ad7d53927ee66ae1df7d68b35e185ce9edcfcf1
[ "RSA-MD" ]
1
2018-10-17T16:00:38.000Z
2018-10-17T16:00:38.000Z
Test/SourceCppGen/WorkflowAttributesReflection.cpp
vczh2/Workflow
7ad7d53927ee66ae1df7d68b35e185ce9edcfcf1
[ "RSA-MD" ]
null
null
null
Test/SourceCppGen/WorkflowAttributesReflection.cpp
vczh2/Workflow
7ad7d53927ee66ae1df7d68b35e185ce9edcfcf1
[ "RSA-MD" ]
null
null
null
/*********************************************************************** !!!!!! DO NOT MODIFY !!!!!! Source: ../Resources/Codegen/WorkflowAttributes.txt This file is generated by Workflow compiler https://github.com/vczh-libraries ***********************************************************************/ #include "WorkflowAttributesReflection.h" #if defined( _MSC_VER) #pragma warning(push) #pragma warning(disable:4250) #elif defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wparentheses-equality" #elif defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wparentheses-equality" #endif /*********************************************************************** Reflection ***********************************************************************/ namespace vl { namespace reflection { namespace description { #ifndef VCZH_DEBUG_NO_REFLECTION IMPL_CPP_TYPE_INFO(calculator::BinaryExpression) IMPL_CPP_TYPE_INFO(calculator::BinaryExpression::BinaryOperator) IMPL_CPP_TYPE_INFO(calculator::Expression) IMPL_CPP_TYPE_INFO(calculator::NumberExpression) #define _ , BEGIN_CLASS_MEMBER(::calculator::BinaryExpression) CLASS_MEMBER_BASE(::calculator::Expression) CLASS_MEMBER_CONSTRUCTOR(::vl::Ptr<::calculator::BinaryExpression>(::vl::Ptr<::calculator::Expression>, ::calculator::BinaryExpression::BinaryOperator, ::vl::Ptr<::calculator::Expression>), { L"_left" _ L"_op" _ L"_right" }) CLASS_MEMBER_METHOD(GetLeft, NO_PARAMETER) CLASS_MEMBER_METHOD(GetOperator, NO_PARAMETER) CLASS_MEMBER_METHOD(GetRight, NO_PARAMETER) CLASS_MEMBER_METHOD(SetLeft, { L"__vwsn_value_" }) CLASS_MEMBER_METHOD(SetOperator, { L"__vwsn_value_" }) CLASS_MEMBER_METHOD(SetRight, { L"__vwsn_value_" }) CLASS_MEMBER_FIELD(__vwsn_prop_Left) CLASS_MEMBER_FIELD(__vwsn_prop_Operator) CLASS_MEMBER_FIELD(__vwsn_prop_Right) CLASS_MEMBER_PROPERTY_READONLY(Left, GetLeft) CLASS_MEMBER_PROPERTY_READONLY(Operator, GetOperator) CLASS_MEMBER_PROPERTY_READONLY(Right, GetRight) END_CLASS_MEMBER(::calculator::BinaryExpression) BEGIN_ENUM_ITEM(::calculator::BinaryExpression::BinaryOperator) ENUM_CLASS_ITEM(Add) ENUM_CLASS_ITEM(Div) ENUM_CLASS_ITEM(Mul) ENUM_CLASS_ITEM(Sub) END_ENUM_ITEM(::calculator::BinaryExpression::BinaryOperator) BEGIN_CLASS_MEMBER(::calculator::Expression) CLASS_MEMBER_BASE(::vl::reflection::DescriptableObject) CLASS_MEMBER_CONSTRUCTOR(::vl::Ptr<::calculator::Expression>(), NO_PARAMETER) CLASS_MEMBER_METHOD(Evaluate, NO_PARAMETER) CLASS_MEMBER_METHOD(Print, NO_PARAMETER) END_CLASS_MEMBER(::calculator::Expression) BEGIN_CLASS_MEMBER(::calculator::NumberExpression) CLASS_MEMBER_BASE(::calculator::Expression) CLASS_MEMBER_CONSTRUCTOR(::vl::Ptr<::calculator::NumberExpression>(::vl::vint), { L"_value" }) CLASS_MEMBER_METHOD(GetValue, NO_PARAMETER) CLASS_MEMBER_METHOD(SetValue, { L"__vwsn_value_" }) CLASS_MEMBER_FIELD(__vwsn_prop_Value) CLASS_MEMBER_PROPERTY_READONLY(Value, GetValue) END_CLASS_MEMBER(::calculator::NumberExpression) #undef _ class WorkflowAttributesTypeLoader : public Object, public ITypeLoader { public: void Load(ITypeManager* manager) { ADD_TYPE_INFO(::calculator::BinaryExpression) ADD_TYPE_INFO(::calculator::BinaryExpression::BinaryOperator) ADD_TYPE_INFO(::calculator::Expression) ADD_TYPE_INFO(::calculator::NumberExpression) } void Unload(ITypeManager* manager) { } }; #endif bool LoadWorkflowAttributesTypes() { #ifndef VCZH_DEBUG_NO_REFLECTION if (auto manager = GetGlobalTypeManager()) { return manager->AddTypeLoader(MakePtr<WorkflowAttributesTypeLoader>()); } #endif return false; } } } } #if defined( _MSC_VER) #pragma warning(pop) #elif defined(__GNUC__) #pragma GCC diagnostic pop #elif defined(__clang__) #pragma clang diagnostic pop #endif
33.470588
228
0.710269
vczh2
68d1d68d62e66c71dab062a174349b57c097200f
530
hpp
C++
src/Node.hpp
wagnrd/SFMLApp
f24ca8c8d36ab928e847e2d2d929226a0e70505d
[ "Unlicense" ]
4
2019-12-12T14:30:46.000Z
2021-07-28T03:03:16.000Z
src/Node.hpp
wagnrd/SFMLApp
f24ca8c8d36ab928e847e2d2d929226a0e70505d
[ "Unlicense" ]
1
2021-02-11T17:10:29.000Z
2021-02-11T20:54:03.000Z
src/Node.hpp
wagnrd/SFMLApp
f24ca8c8d36ab928e847e2d2d929226a0e70505d
[ "Unlicense" ]
null
null
null
// // Created by Denis Wagner on 1/14/19. // #ifndef PONG_NODE_HPP #define PONG_NODE_HPP #include <SFML/Window/Event.hpp> #include <SFML/Graphics/RenderWindow.hpp> #include "Application.hpp" class Node { protected: Application* application; Node * parent; public: void initChild( Application* application, Node* child ); Node* getParent(); virtual void init(); virtual void eventHandler( const sf::Event& event ); virtual void draw( sf::RenderWindow& window ) = 0; }; #endif //PONG_NODE_HPP
20.384615
60
0.692453
wagnrd
68d5acfae41b53ed4f58fc5808cdd56e1b19b57a
10,639
cpp
C++
Compressed.cpp
Rki009/RiscV-Fast
3c1e510f1c175cca7e7e43e854787726ba12a69c
[ "Unlicense" ]
null
null
null
Compressed.cpp
Rki009/RiscV-Fast
3c1e510f1c175cca7e7e43e854787726ba12a69c
[ "Unlicense" ]
null
null
null
Compressed.cpp
Rki009/RiscV-Fast
3c1e510f1c175cca7e7e43e854787726ba12a69c
[ "Unlicense" ]
null
null
null
//*************************************************************** // Compressed decoding //*************************************************************** #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <ctype.h> #include <string> #include "RiscVFast.h" #include "Cpu.h" Vliw* fastTable[0x10000]; // 64K fast VLIW access table // map 3-bit register to 5 bit value int regMap3[8] = { 8, 9, 10, 11, 12, 13, 14, 15 }; int fregMap3[8] = { 8, 9, 10, 11, 12, 13, 14, 15 }; int32_t mk_imm6(uint32_t code) { int32_t b5 = (code>>12)&0x1; int32_t b4_0 = (code>>2)&0x1f; int32_t imm = (b5<<5) | (b4_0<<0); if((imm&0x00000020) != 0) { imm |= 0xffffffc0; } return imm; }; int32_t jal_off(uint16_t code) { int32_t b5 = (code>>2)&0x1; int32_t b3_1 = (code>>3)&0x7; int32_t b7 = (code>>6)&0x1; int32_t b6 = (code>>7)&0x1; int32_t b10 = (code>>8)&0x1; int32_t b9_8 = (code>>9)&0x3; int32_t b4 = (code>>11)&0x1; int32_t b11 = (code>>12)&0x1; int32_t imm = (b11<<11) | (b10<<10) | (b9_8<<8) | (b7<<7) | (b6<<6) | (b5<<5) | (b4<<4) | (b3_1<<1); if(b11 != 0) { imm |= 0xfffff000; } return imm; }; // C_LWSP - zero extended (6 bits << 2) int32_t mk_lwsp(uint16_t code) { int32_t b5 = (code>>12)&0x1; int32_t b4_2 = (code>>4)&0x7; int32_t b7_6 = (code>>2)&0x3; int32_t imm = (b7_6<<6)| (b5<<5) | (b4_2<<2); // if ((imm&0x000080) != 0) imm |= 0xffffff00; return imm; }; int32_t mk_addi(uint16_t code) { int32_t b5 = (code>>12)&0x1; int32_t b4_0 = (code>>2)&0x1f; int32_t imm = (b5<<5) | (b4_0<<0); if((imm&0x00000020) != 0) { imm |= 0xffffffc0; } return imm; }; // shamt (6 bit unsigned) int32_t mk_shamt(uint16_t code) { int32_t b5 = (code>>12)&0x1; int32_t b4_0 = (code>>2)&0x1f; int32_t imm = (b5<<5) | (b4_0<<0); // if ((imm&0x00000020) != 0) imm |= 0xffffffc0; return imm; }; int32_t mk_addi16sp(uint16_t code) { int32_t b9 = (code>>12)&0x1; int32_t b4 = (code>>6)&0x1; int32_t b6 = (code>>5)&0x1; int32_t b8_7 = (code>>3)&0x3; int32_t b5 = (code>>2)&0x1; int32_t imm = (b9<<9) | (b8_7<<7) | (b6<<6) | (b5<<5) | (b4<<4); if((imm&0x00000200) != 0) { imm |= 0xfffffc00; } return imm; }; // nzuimm[5:4|9:6|2|3] int32_t mk_addi4spn(uint16_t code) { int32_t b5_4 = (code>>11)&0x3; int32_t b9_6 = (code>>7)&0xf; int32_t b2 = (code>>6)&0x1; int32_t b3 = (code>>5)&0x1; int32_t imm = (b9_6<<6) | (b5_4<<4) | (b3<<3) | (b2<<2); return imm; }; int32_t mk_beq(uint16_t code) { int32_t b8 = (code>>12)&0x1; int32_t b4_3 = (code>>10)&0x3; int32_t b7_6 = (code>>5)&0x3; int32_t b2_1 = (code>>3)&0x3; int32_t b5 = (code>>2)&0x1; int32_t imm = (b8<<8) | (b7_6<<6) | (b5<<5) | (b4_3<<3) | (b2_1<<1); if(b8) { imm |= 0xfffffe00; } return imm; }; int32_t mk_sw(uint16_t code) { int32_t b5_3 = (code>>10)&0x7; int32_t b2 = (code>>6)&0x1; int32_t b6 = (code>>5)&0x1; int32_t imm = (b6<<6) | (b5_3<<3) | (b2<<2); if(b6) { imm |= 0xffffffc0; } return imm; }; int32_t mk_sd(uint16_t code) { int32_t b5_3 = (code>>10)&0x7; int32_t b7_6 = (code>>5)&0x3; int32_t imm = (b7_6<<6) | (b5_3<<3); if((imm&0x0000080) != 0) { imm |= 0xffffff80; } return imm; }; // C_SWSP - zero extended (6 bits << 2) int32_t mk_swsp(uint16_t code) { int32_t b5_2 = (code>>9)&0xf; int32_t b7_6 = (code>>7)&0x3; int32_t imm = (b7_6<<6) | (b5_2<<2); return imm; }; bool decodeCompressed(uint32_t addr, uint32_t code, Vliw* vlp) { if(fastTable[code&0xffff] != NULL) { // printf("Fast: addr=0x%08x, code=0x%04x\n", addr, (uint16_t)code); Vliw* nvlp = fastTable[code&0xffff]; // copy to new vlp->opcode = nvlp->opcode; vlp->rd = nvlp->rd; vlp->rs1 = nvlp->rs1; vlp->rs2 = nvlp->rs2; vlp->imm = nvlp->imm; if(DEBUG) { printf("Fast32: addr=0x%08x, code=0x%04x\n", addr, (uint16_t)code); printf(" vlp: %d, %d, %d, %d, %08x\n", vlp->opcode, vlp->rd, vlp->rs1, vlp->rs2, vlp->imm); } return true; } if(DEBUG || cpu->verbose) { printf("Comp32: addr=0x%08x, code=0x%04x\n", addr, (uint16_t)code); } // init the Vliw to zero vlp->opcode = VLIW_NOP; vlp->rd = 0; vlp->rs1 = 0; vlp->rs2 = 0; vlp->imm = 0; Optable* otp = optable; for(; otp->bitText != NULL; ++otp) { // printf("%s, 0x%08x, 0x%09x, %s\n", otp->bitText, otp->code, otp->mask, otp->asmText); if((code&otp->mask) == otp->code) { break; } } if(otp->bitText == NULL) { printf("Code: 0x%08x, not found\n", code); return false; } if(cpu->verbose) { printf(" %s, 0x%08x, 0x%08x, %s\n", otp->bitText, otp->code, otp->mask, otp->asmText); } vlp->opcode = otp->vliw; // rd', rs1', rs2' int r3b2 = regMap3[(code>>2)&0x7]; // rs2' int r3b7 = regMap3[(code>>7)&0x7]; // rd', rs1' switch(vlp->opcode) { //****************************************************** // Base, RV32 //****************************************************** // RV32/64 Base instructions // lw rd',offset(rs1') case VLIW_C_LW: vlp->opcode = VLIW_LW; vlp->rd = r3b2; vlp->rs1 = r3b7; vlp->rs2 = 0; vlp->imm = mk_sw(code); break; // sw rs2',offset(rs1') case VLIW_C_SW: vlp->opcode = VLIW_SW; vlp->rd = 0; vlp->rs1 = r3b7; vlp->rs2 = r3b2; vlp->imm = mk_sw(code); break; // sw rs2,offset(sp) case VLIW_C_SWSP: vlp->opcode = VLIW_SW; vlp->rd = 0; vlp->rs1 = 2; // sp vlp->rs2 = (code>>2)&0x1f; vlp->imm = mk_swsp(code); // zero extended break; // beq rs1',x0,offset case VLIW_C_BEQZ: vlp->opcode = VLIW_BEQ; vlp->rd = 0; vlp->rs1 = r3b7; vlp->rs2 = 0; vlp->imm = mk_beq(code); break; // bne rs1',x0,offset case VLIW_C_BNEZ: vlp->opcode = VLIW_BNE; vlp->rd = 0; vlp->rs1 = r3b7; vlp->rs2 = 0; vlp->imm = mk_beq(code); break; // addi rd,rs1,0, alternate move case VLIW_C_MV: vlp->opcode = VLIW_ADDI; vlp->rd = (code>>7)&0x1f; vlp->rs1 = (code>>2)&0x1f; vlp->rs2 = 0; vlp->imm = 0; break; // add rd,rd,rs2 case VLIW_C_ADD: vlp->opcode = VLIW_ADD; vlp->rd = (code>>7)&0x1f; vlp->rs1 = vlp->rd; vlp->rs2 = (code>>2)&0x1f;; vlp->imm = 0; break; // addi rd, rd, nzimm case VLIW_C_ADDI: vlp->opcode = VLIW_ADDI; vlp->rd = (code>>7)&0x1f; vlp->rs1 = vlp->rd; vlp->rs2 = 0; vlp->imm = mk_addi(code); break; // addi x0,x0,0 case VLIW_C_NOP: vlp->opcode = VLIW_ADDI; vlp->rd = 0; vlp->rs1 = 0; vlp->rs2 = 0; vlp->imm = 0; break; case VLIW_C_ADDI16SP: vlp->opcode = VLIW_ADDI; vlp->rd = (code>>7)&0x1f; vlp->rs1 = 2; // sp vlp->rs2 = 0; vlp->imm = mk_addi16sp(code); break; // addi rd',x2,nzuimm case VLIW_C_ADDI4SPN: vlp->opcode = VLIW_ADDI; vlp->rd = r3b2; vlp->rs1 = 2; // sp vlp->rs2 = 0; vlp->imm = mk_addi4spn(code); break; case VLIW_C_LWSP: vlp->opcode = VLIW_LW; vlp->rd = (code>>7)&0x1f; vlp->rs1 = 2; // sp vlp->rs2 = 0; vlp->imm = mk_lwsp(code); break; case VLIW_C_LI: vlp->opcode = VLIW_ADDI; vlp->rd = (code>>7)&0x1f; vlp->rs1 = 0; vlp->rs2 = 0; vlp->imm = mk_imm6(code); break; case VLIW_C_LUI: vlp->opcode = VLIW_ADDI; vlp->rd = (code>>7)&0x1f; vlp->rs1 = 0; vlp->rs2 = 0; vlp->imm = mk_imm6(code)<<12; break; case VLIW_C_J: vlp->opcode = VLIW_JAL; // vlp->opcode = VLIW_J; vlp->rd = 0; vlp->rs1 = 0; vlp->rs2 = 0; vlp->imm = jal_off(code); break; case VLIW_C_JAL: vlp->opcode = VLIW_JAL; vlp->rd = 1; vlp->rs1 = 0; vlp->rs2 = 0; vlp->imm = jal_off(code); // printf("Jal: dest = %08x\n", addr+vlp->imm); break; // jalr x0,0(rs1) case VLIW_C_JR: vlp->opcode = VLIW_JALR; // vlp->opcode = VLIW_JR; vlp->rd = 0; vlp->rs1 = (code>>7)&0x1f; vlp->rs2 = 0; vlp->imm = 0; break; // jalr x1,0(rs1) case VLIW_C_JALR: vlp->opcode = VLIW_JALR; vlp->rd = 1; vlp->rs1 = (code>>7)&0x1f; vlp->rs2 = 0; vlp->imm = 0; break; case VLIW_C_SUB: vlp->opcode = VLIW_SUB; vlp->rd = r3b7; vlp->rs1 = r3b7; vlp->rs2 = r3b2; break; case VLIW_C_XOR: vlp->opcode = VLIW_XOR; vlp->rd = r3b7; vlp->rs1 = r3b7; vlp->rs2 = r3b2; break; // andi rd',rd',rs' case VLIW_C_OR: vlp->opcode = VLIW_OR; vlp->rd = r3b7; vlp->rs1 = r3b7; vlp->rs2 = r3b2; break; // andi rd',rd',rs' case VLIW_C_AND: vlp->opcode = VLIW_AND; vlp->rd = r3b7; vlp->rs1 = r3b7; vlp->rs2 = r3b2; break; // andi rd',rd',imm case VLIW_C_ANDI: vlp->opcode = VLIW_ANDI; vlp->rd = r3b7; vlp->rs1 = vlp->rd; vlp->rs2 = 0; vlp->imm = mk_addi(code); break; //****************************************************** // RV32 //****************************************************** // RV32 specific instructions #if RV32 // slli rd, rd, shamt case VLIW_C_SLLI: vlp->opcode = VLIW_SLLI; vlp->rd = regMap3[(code>>7)&0x7]; vlp->rs1 = vlp->rd; vlp->rs2 = 0; vlp->imm = mk_shamt(code); break; // srli rd, rd, shamt case VLIW_C_SRLI: vlp->opcode = VLIW_SRLI; vlp->rd = r3b7; vlp->rs1 = vlp->rd; vlp->rs2 = 0; vlp->imm = mk_shamt(code); break; // srai rd, rd, shamt case VLIW_C_SRAI: vlp->opcode = VLIW_SRAI; vlp->rd = r3b7; vlp->rs1 = vlp->rd; vlp->rs2 = 0; vlp->imm = mk_shamt(code); break; #endif //****************************************************** // RV64 //****************************************************** #if RV64 // addiw rd,rd,imm case VLIW_C_ADDIW: vlp->opcode = VLIW_ADDIW; vlp->rd = (code>>7)&0x1f; vlp->rs1 = vlp->rd; vlp->rs2 = 0; vlp->imm = mk_addi(code); break; case VLIW_C_ADDW: vlp->opcode = VLIW_ADDW; vlp->rd = r3b7; vlp->rs1 = r3b7; vlp->rs2 = r3b2; break; case VLIW_C_SUBW: vlp->opcode = VLIW_SUBW; vlp->rd = r3b7; vlp->rs1 = r3b7; vlp->rs2 = r3b2; break; // sw rs2',offset(rs1') case VLIW_C_LD: vlp->opcode = VLIW_LD; vlp->rd = r3b2; vlp->rs1 = r3b7; vlp->rs2 = 0; vlp->imm = mk_sd(code); break; // sd rs2',offset(rs1') case VLIW_C_SD: // RV64 vlp->opcode = VLIW_SD; vlp->rd = 0; vlp->rs1 = r3b7; vlp->rs2 = r3b2; vlp->imm = mk_sd(code); break; #endif // c.ebreak case VLIW_C_EBREAK: vlp->opcode = VLIW_EBREAK; vlp->rd = 0; vlp->rs1 = 0; vlp->rs2 = 0; vlp->imm = 0; break; default: printf("Not found: %s, 0x%08x, 0x%08x, %s\n", otp->bitText, otp->code, otp->mask, otp->asmText); exit(-1); break; } // vlp->dump(); // cpu->dump32(); if(DEBUG) { printf(" vlp: %d, %d, %d, %d, %08x\n", vlp->opcode, vlp->rd, vlp->rs1, vlp->rs2, vlp->imm); } // update fast table if(fastTable[code&0xffff] == NULL) { Vliw* nvlp = new Vliw; // copy to new nvlp->opcode = vlp->opcode; nvlp->rd = vlp->rd; nvlp->rs1 = vlp->rs1; nvlp->rs2 = vlp->rs2; nvlp->imm = vlp->imm; fastTable[code&0xffff] = nvlp; } return true; }
20.901768
98
0.553999
Rki009
68e03d82ed5e22be73f8b5c257df2782c004b84d
12,852
cc
C++
build/X86_MESI_Two_Level/python/m5/internal/param_EtherDevBase.py.cc
hoho20000000/gem5-fy
b59f6feed22896d6752331652c4d8a41a4ca4435
[ "BSD-3-Clause" ]
null
null
null
build/X86_MESI_Two_Level/python/m5/internal/param_EtherDevBase.py.cc
hoho20000000/gem5-fy
b59f6feed22896d6752331652c4d8a41a4ca4435
[ "BSD-3-Clause" ]
1
2020-08-20T05:53:30.000Z
2020-08-20T05:53:30.000Z
build/X86_MESI_Two_Level/python/m5/internal/param_EtherDevBase.py.cc
hoho20000000/gem5-fy
b59f6feed22896d6752331652c4d8a41a4ca4435
[ "BSD-3-Clause" ]
null
null
null
#include "sim/init.hh" namespace { const uint8_t data_m5_internal_param_EtherDevBase[] = { 120,156,237,90,221,83,28,199,17,239,217,59,14,14,56,56, 196,55,66,102,101,9,9,127,8,36,59,74,156,88,81,217, 178,100,71,174,8,171,14,87,36,147,84,109,45,183,115,176, 232,110,247,106,119,144,116,46,120,136,113,62,30,252,16,87, 229,45,255,66,170,146,74,94,226,127,33,111,249,139,146,238, 158,157,101,15,238,224,42,101,33,81,101,56,154,185,158,158, 153,238,233,238,223,204,236,78,21,146,159,121,252,251,192,6, 136,191,179,0,60,252,8,120,2,80,23,176,110,129,144,22, 120,231,97,187,15,194,89,16,94,31,124,13,176,158,3,153, 131,125,44,228,225,215,57,8,222,213,82,243,169,84,127,39, 169,18,86,96,223,3,240,36,207,44,11,90,131,32,251,96, 189,0,143,130,113,200,203,126,216,30,132,176,31,4,254,4, 56,242,227,86,25,146,22,3,176,94,68,169,5,148,26,100, 169,113,150,74,106,139,84,203,45,188,34,120,131,240,53,106, 62,4,222,16,107,49,12,222,48,23,74,224,149,184,48,2, 222,8,23,70,193,27,5,89,134,154,0,175,76,28,84,246, 139,245,49,144,121,240,207,193,250,57,144,248,25,131,125,129, 154,143,25,193,115,169,224,56,11,78,192,250,4,72,252,140, 107,193,113,42,145,224,68,42,56,201,130,83,176,62,5,18, 63,147,90,112,210,8,78,165,130,211,44,56,3,235,51,32, 241,51,173,5,181,145,179,176,62,103,166,227,124,166,60,159, 41,95,200,148,95,203,148,23,50,101,59,83,190,152,41,191, 158,41,95,202,148,47,103,202,139,153,242,149,76,249,106,166, 188,148,41,191,193,101,180,106,14,252,55,193,127,11,252,183, 217,226,153,212,226,107,108,241,50,172,47,131,196,207,53,109, 241,108,166,197,10,183,152,75,91,92,231,22,55,96,253,6, 72,252,92,215,45,6,96,109,233,2,134,177,255,95,252,89, 18,88,82,195,72,158,202,40,246,195,192,241,131,90,232,91, 84,223,79,132,130,190,74,36,135,127,5,252,251,136,162,63, 2,14,125,212,29,163,127,15,123,16,128,109,60,139,70,240, 114,48,187,39,232,139,159,131,93,44,228,161,198,21,126,62, 145,216,195,120,30,131,93,236,189,15,118,153,179,246,40,184, 0,121,85,224,128,29,227,128,213,213,216,152,170,49,92,1, 213,238,195,97,87,89,111,69,122,47,179,118,106,28,137,211, 116,35,183,225,220,83,91,50,186,43,159,222,113,99,185,68, 250,171,34,25,209,104,134,145,170,251,27,106,128,68,157,192, 109,72,199,81,131,248,37,194,118,202,87,104,184,202,227,215, 237,208,15,20,89,89,143,85,228,55,85,41,109,237,52,66, 111,167,46,213,16,114,238,51,231,94,20,133,209,18,77,75, 133,136,34,210,124,178,169,72,201,6,13,177,68,218,49,137, 127,133,100,101,43,108,72,36,193,102,107,103,101,83,54,110, 94,171,181,86,54,118,252,186,183,242,248,189,31,59,15,238, 173,221,119,62,127,22,58,191,148,79,101,125,165,217,82,40, 186,210,184,185,130,26,201,40,112,145,117,196,196,101,148,58, 71,253,63,243,55,157,68,207,45,89,111,202,136,204,142,71, 104,108,49,44,198,197,107,34,39,198,196,136,240,11,198,157, 52,57,37,227,206,191,38,238,180,18,48,67,143,138,196,189, 22,236,113,129,124,182,68,238,36,47,230,200,121,104,40,186, 102,83,192,190,5,191,201,145,192,30,210,60,98,143,157,186, 114,66,99,143,238,170,31,246,208,223,125,228,205,47,231,185, 171,1,238,202,130,93,164,232,232,60,236,33,192,161,40,178, 144,110,23,33,28,1,129,95,252,34,5,180,8,48,124,31, 239,22,48,16,242,105,32,232,0,38,107,60,63,162,89,175, 80,236,46,13,26,110,24,47,55,93,181,85,41,25,23,225, 52,177,171,87,195,64,123,179,230,7,158,241,174,142,143,154, 95,199,248,168,208,28,114,111,44,86,15,221,84,140,92,92, 173,135,73,140,113,223,149,81,18,36,233,90,147,187,161,81, 73,31,110,236,201,184,74,241,132,113,166,123,36,13,168,183, 83,137,145,10,229,247,4,141,49,199,17,81,198,152,40,96, 68,44,97,68,232,210,188,85,18,163,98,213,167,201,172,246, 37,153,158,55,225,241,79,208,46,17,176,109,113,122,238,50, 48,160,52,58,142,211,115,151,147,159,106,223,6,161,172,132, 143,249,143,254,37,238,57,108,195,65,131,209,131,178,183,40, 155,217,157,20,5,125,128,97,169,93,142,161,164,99,132,29, 223,71,45,168,43,139,134,200,67,115,26,59,31,160,104,216, 133,36,108,246,115,24,22,168,17,38,51,66,5,178,167,112, 220,175,56,222,18,184,224,40,80,91,126,28,62,211,57,78, 101,70,188,53,204,154,135,173,207,54,182,101,85,197,11,200, 248,34,220,177,171,110,16,132,202,118,61,207,118,21,98,192, 198,142,146,177,173,66,123,49,94,34,79,86,230,76,32,165, 253,181,154,178,194,5,29,61,158,95,85,136,46,140,74,14, 103,102,44,21,198,193,86,232,197,200,167,166,155,82,85,202, 212,130,166,57,100,5,56,76,28,18,165,97,81,142,146,247, 67,163,129,198,154,130,137,156,88,214,107,12,95,213,186,27, 199,14,105,192,124,142,55,178,250,169,91,223,145,220,123,140, 253,161,66,84,212,58,156,14,42,205,144,53,198,120,182,40, 8,3,175,133,10,250,213,119,105,236,25,142,196,18,162,82, 73,76,225,95,81,76,138,126,140,199,126,49,109,85,243,73, 244,165,235,205,20,89,14,236,118,145,120,30,163,113,31,177, 100,201,98,40,96,163,40,122,43,111,82,137,26,87,46,19, 89,36,114,133,200,85,99,247,11,55,190,116,216,248,143,104, 64,139,45,174,230,18,219,210,236,114,218,178,107,36,147,93, 251,148,37,187,188,180,250,185,76,134,228,200,254,112,200,228, 20,103,32,186,29,51,144,132,57,151,112,197,205,102,2,13, 186,90,153,37,53,46,34,185,186,24,95,181,117,220,217,91, 110,108,7,225,65,176,219,84,169,113,141,66,189,66,59,222, 108,48,111,102,130,185,98,147,4,69,114,229,18,145,124,183, 185,127,227,37,204,253,166,158,251,79,104,192,225,36,218,70, 56,202,134,68,149,66,133,28,210,111,188,176,134,133,214,52, 121,33,59,253,211,184,248,61,10,230,113,61,99,23,208,146, 86,210,75,26,175,139,122,35,109,128,205,239,51,133,2,57, 162,150,131,169,100,165,138,105,41,105,70,225,243,150,29,214, 108,5,70,165,91,139,241,242,98,252,62,98,139,125,251,96, 202,19,28,137,100,147,112,64,227,2,77,140,242,3,252,78, 93,221,123,94,149,188,152,240,55,199,209,48,160,119,52,78, 178,72,161,119,216,29,150,113,7,3,33,110,107,8,255,78, 199,23,131,169,47,200,150,135,52,218,32,59,34,39,166,49, 241,51,110,160,191,28,185,129,2,237,15,192,251,88,1,191, 7,154,100,156,202,36,203,57,119,76,254,140,147,56,109,101, 118,69,199,149,201,74,242,194,74,80,3,19,167,89,226,5, 39,89,169,112,111,242,199,12,164,164,43,73,46,217,223,100, 243,39,159,230,15,123,168,167,213,34,223,158,66,52,251,152, 107,36,198,201,162,119,142,151,219,225,137,55,51,57,70,120, 245,194,221,51,160,199,113,72,165,47,14,156,67,152,124,65, 76,88,58,70,56,124,126,66,228,189,52,135,133,225,189,72, 237,22,14,131,104,102,5,113,52,2,61,38,21,242,172,244, 104,63,79,48,118,242,161,231,69,188,195,165,31,90,11,239, 80,160,220,197,130,196,115,172,0,201,48,250,53,111,120,137, 90,228,238,125,75,208,25,28,79,219,124,228,160,19,111,1, 240,148,237,243,105,58,57,202,15,66,101,141,215,96,14,91, 243,199,232,65,168,211,6,219,153,201,75,67,64,123,151,200, 243,211,201,63,114,240,173,186,219,216,240,220,219,30,141,69, 3,86,77,190,89,70,249,114,86,121,202,20,209,69,127,254, 250,190,49,226,233,233,236,93,111,1,63,104,209,202,115,110, 120,97,149,113,226,243,45,105,55,100,99,3,15,174,91,126, 211,174,213,221,77,246,76,46,113,252,39,100,220,125,224,157, 131,182,236,27,125,142,153,96,115,205,162,74,135,98,126,94, 162,24,194,9,227,203,250,4,202,208,225,88,9,204,147,87, 169,251,85,142,129,131,131,65,32,159,57,73,220,105,248,166, 106,183,217,148,129,87,185,78,146,55,218,178,157,55,106,110, 180,25,179,240,233,5,130,131,39,123,31,55,166,155,7,153, 62,138,64,60,129,217,126,52,158,243,122,210,141,193,156,240, 229,52,245,47,159,150,226,236,252,192,56,95,239,191,25,86, 105,11,201,59,100,141,16,184,180,226,153,87,181,52,66,223, 36,178,66,228,78,234,40,146,245,36,30,221,164,241,149,42, 67,186,167,193,227,153,138,194,22,174,160,253,204,68,73,199, 57,176,240,133,155,249,51,208,167,114,246,75,65,156,23,5, 171,88,40,10,94,221,239,55,73,91,25,199,175,48,168,49, 40,156,94,68,196,223,39,150,85,126,254,114,116,175,220,134, 100,191,243,10,224,88,41,193,177,52,216,244,76,125,64,164, 3,134,85,62,52,147,121,58,19,71,121,252,244,172,225,214, 94,23,220,170,208,105,176,59,82,149,15,144,234,192,27,247, 168,250,227,54,245,95,184,13,116,112,138,186,130,210,42,30, 3,221,248,201,15,160,100,220,253,213,25,6,165,84,247,87, 20,148,146,96,123,245,64,233,119,103,13,148,190,249,30,64, 201,120,227,101,128,210,167,216,245,111,59,128,210,32,131,210, 35,95,109,61,12,35,245,3,42,25,127,127,123,134,81,41, 213,253,149,66,165,145,20,149,76,180,189,122,176,244,231,179, 6,75,127,249,255,96,105,44,11,75,169,59,94,6,46,61, 192,174,255,212,1,151,232,41,111,86,246,40,50,189,211,11, 50,37,152,148,79,46,129,84,244,187,173,51,132,67,127,63, 195,56,148,234,222,27,14,145,154,159,25,195,20,123,51,243, 36,153,31,100,199,244,146,106,53,180,171,97,16,171,104,167, 170,194,200,246,100,205,15,164,103,95,179,249,105,190,237,199, 182,187,129,181,110,85,105,135,29,122,104,76,176,194,143,154, 158,60,163,167,73,167,7,46,255,128,244,101,150,126,103,209, 41,91,239,180,165,236,41,38,34,189,101,248,27,141,81,208, 137,104,21,45,190,34,145,149,123,72,45,59,60,79,217,22, 61,111,18,80,64,22,232,138,12,209,1,122,185,128,251,132, 132,57,200,116,136,153,195,134,89,98,58,194,204,81,195,44, 51,29,99,230,57,195,28,103,58,193,204,73,195,156,98,58, 205,204,25,195,156,101,58,199,204,243,134,57,207,244,2,51, 95,51,204,5,166,54,51,47,26,230,235,76,47,49,243,178, 97,46,50,189,194,204,171,134,185,196,244,13,102,190,105,152, 111,49,125,155,153,215,12,115,153,233,10,51,175,27,216,186, 193,204,119,96,253,93,179,149,250,209,25,220,74,125,119,134, 33,44,213,253,100,8,179,146,140,96,195,62,6,179,149,218, 231,119,113,109,251,40,113,204,62,74,156,184,143,162,87,250, 201,163,243,67,137,217,113,63,149,190,198,60,229,173,212,191, 33,221,74,13,159,137,173,212,127,140,171,151,110,118,3,231, 131,173,20,123,98,177,35,60,58,94,195,117,34,233,122,244, 52,220,109,209,235,244,30,37,99,148,228,231,237,109,108,117, 229,132,198,53,151,214,65,30,167,71,81,26,104,52,59,144, 230,31,215,252,89,228,227,102,241,192,162,30,69,179,35,101, 248,234,234,73,205,51,70,245,42,75,99,149,219,198,74,204, 234,210,193,150,27,121,184,5,144,142,171,31,22,30,55,216, 17,89,51,216,225,10,117,177,115,7,24,128,81,102,250,78, 150,162,1,40,125,14,88,106,174,115,163,40,81,253,152,106, 234,140,118,64,88,230,247,195,157,196,158,103,212,59,73,134, 250,163,119,99,134,161,46,117,109,80,243,107,161,19,251,95, 74,238,184,23,57,234,124,88,119,158,50,149,125,76,195,58, 230,54,247,126,162,16,117,93,52,93,19,231,152,38,106,139, 83,227,248,126,19,161,76,191,154,211,109,6,85,15,179,172, 14,207,178,58,97,150,85,143,179,172,58,205,178,234,97,150, 85,47,179,161,142,204,70,202,225,5,65,17,132,30,188,74, 60,188,118,189,140,195,103,5,187,254,23,141,65,104,198,135, 79,49,217,253,151,15,166,124,144,56,116,205,59,195,43,164, 60,58,158,234,27,41,173,152,198,209,246,39,175,93,89,65, 39,123,115,156,175,154,234,101,133,47,193,154,23,179,180,248, 240,100,174,186,13,125,155,145,235,147,107,77,177,94,232,249, 194,45,29,141,42,111,17,185,150,174,85,63,37,66,88,195, 111,74,213,4,164,55,61,88,145,72,110,250,49,206,16,191, 178,224,141,69,250,230,164,189,254,211,131,250,228,33,102,123, 61,157,226,213,52,100,31,37,182,9,40,186,55,223,184,185, 108,252,177,220,238,15,191,42,249,6,112,227,166,58,223,81, 240,97,213,79,196,102,187,213,255,34,140,85,183,214,126,152, 180,158,233,88,191,214,66,29,27,71,26,203,96,167,225,60, 144,141,48,106,61,8,61,169,230,15,213,243,197,5,55,216, 148,232,72,94,103,46,30,22,72,142,161,186,15,35,101,119, 212,161,93,182,139,33,88,169,111,221,50,116,28,173,255,168, 30,86,159,72,47,145,233,60,231,44,115,55,108,184,200,239, 60,202,154,111,70,25,59,84,239,69,212,106,242,16,55,150, 145,239,214,9,62,58,247,119,183,225,38,211,63,160,215,51, 174,228,206,143,134,193,80,6,92,240,59,31,75,217,233,217, 220,109,143,173,177,246,38,9,158,80,206,117,67,216,108,243, 211,131,27,125,173,72,95,50,188,205,119,10,233,45,97,153, 238,240,14,20,69,63,253,31,197,255,22,110,151,173,156,24, 20,35,162,15,255,151,241,255,152,53,92,46,230,139,69,148, 27,154,26,46,138,65,235,40,29,22,199,255,46,20,72,106, 97,174,40,254,7,175,167,74,30, }; EmbeddedPython embedded_m5_internal_param_EtherDevBase( "m5/internal/param_EtherDevBase.py", "/home/hongyu/gem5-fy/build/X86_MESI_Two_Level/python/m5/internal/param_EtherDevBase.py", "m5.internal.param_EtherDevBase", data_m5_internal_param_EtherDevBase, 3193, 13716); } // anonymous namespace
59.225806
93
0.666355
hoho20000000
68f4601a4aeb1523be95b06737e1352a1413b7db
1,888
cc
C++
Modulation/daqana/slowdaq.cc
pumar/Projects
9d05c0fdf3dfc1b529f6fd3bd8318d5fc06c8a55
[ "MIT" ]
null
null
null
Modulation/daqana/slowdaq.cc
pumar/Projects
9d05c0fdf3dfc1b529f6fd3bd8318d5fc06c8a55
[ "MIT" ]
null
null
null
Modulation/daqana/slowdaq.cc
pumar/Projects
9d05c0fdf3dfc1b529f6fd3bd8318d5fc06c8a55
[ "MIT" ]
null
null
null
#include <string> #include <sstream> #include <cstdio> #include <cstdlib> #include <unistd.h> #include "driver.hh" #include "sdaq.hh" #include "sevent.hh" #include "srootdriver.hh" #include <TCanvas.h> using namespace std; // // MAIN program // int main(int argc, char **argv) { // switches int c = 0; string DriverFilename; // parse switches while((c = getopt(argc,argv,"i:")) != -1) { switch(c) { case 'i': // name of driver DriverFilename = optarg; break; default: exit(-1); } } // driver for the daq processing..... provided from the python script cout << "slowdaq:: driver file = " << DriverFilename << endl; bool slowOn = true; driver* myDriver = new driver(DriverFilename, slowOn); // TApplication is needed to plot a canvas with an event // create an instance of the daq datatype: controls all the binary file handling sdaq myDaq(myDriver); // root management srootdriver myRoot(myDriver); ULong64_t new_stime; // loop over the events int totalnumberofevents = myDriver->getNEvent(); slowevent *sev; int totalslowevents = myDaq.GetSlowFileSize(); cout << "slowdaq:: Found " << totalslowevents << " slow events" << endl; ULong64_t old_stime = 0; for (int iSlowEv = 0; iSlowEv < totalslowevents; iSlowEv++){ if(iSlowEv%10000 == 0) cout << " processed "<<iSlowEv<<" slow events"<<endl; sev = myDaq.readSlowEvent(); new_stime = myRoot.SlowFill(sev, old_stime); old_stime = new_stime; // delete sev; } //cout << "I am done processing slow events!!!! " << endl; //delete theApp; // write run parameters to file //myRoot.writeParameters(myDriver); myRoot.Close(); delete myDriver; return 0; }
27.362319
88
0.599576
pumar
68f4e547e0c764342b9d650c957e33c662b44244
728
cpp
C++
Binary trees/heightOfBT.cpp
PranavDherange/Data_Structures
9962b5145f6b42d9317e2c328c2b3124f028ca70
[ "MIT" ]
2
2021-02-25T11:54:50.000Z
2021-02-25T11:54:54.000Z
Binary trees/heightOfBT.cpp
PranavDherange/Data_Structures
9962b5145f6b42d9317e2c328c2b3124f028ca70
[ "MIT" ]
null
null
null
Binary trees/heightOfBT.cpp
PranavDherange/Data_Structures
9962b5145f6b42d9317e2c328c2b3124f028ca70
[ "MIT" ]
1
2021-10-03T17:39:10.000Z
2021-10-03T17:39:10.000Z
/* Code : Height of Binary Tree Given a binary tree, find and return the height of given tree. Input format : Nodes in the level order form (separated by space). If any node does not have left or right child, take -1 in its place Output format : Height Constraints : 1 <= N <= 10^5 Sample Input : 10 9 4 -1 -1 5 8 -1 6 -1 -1 3 -1 -1 -1 Sample Output : 5*/ #include <bits/stdc++.h> using namespace std; #include "binaryTree.h" int heightBT(BinaryTreeNode<int> *root) { if (root == NULL) { return 0; } int x = 0; if (heightBT(root->left) > heightBT(root->right)) { x = heightBT(root->left); } else { x = heightBT(root->right); } return 1 + x; }
14.56
119
0.596154
PranavDherange
d0ffd2a59b1dfd41df67aac59edcc42f4e9fd2cf
1,325
hpp
C++
proj/KSP/src/Utilities.hpp
bananu7/Arduino
56769c0850a6da873c29a0ac78fa2e1133bb7cc7
[ "MIT" ]
1
2020-02-24T09:14:02.000Z
2020-02-24T09:14:02.000Z
proj/KSP/src/Utilities.hpp
bananu7/Arduino
56769c0850a6da873c29a0ac78fa2e1133bb7cc7
[ "MIT" ]
2
2016-11-20T18:43:59.000Z
2016-11-20T18:44:11.000Z
proj/KSP/src/Utilities.hpp
bananu7/Arduino
56769c0850a6da873c29a0ac78fa2e1133bb7cc7
[ "MIT" ]
null
null
null
#pragma once #include "Structure.h" /* inline void Indicators(VesselData const& VData) { int caution = 0; int warning = 0; caution += VData.G > GCAUTION; warning += VData.G > GWARN; caution += VData.LiquidFuelS/VData.LiquidFuelTotS*100 < FUELCAUTION; warning += VData.LiquidFuelS/VData.LiquidFuelTotS*100 < FUELWARN; if (caution != 0) digitalWrite(YLED,HIGH); else digitalWrite(YLED,LOW); if (warning != 0) digitalWrite(RLED,HIGH); else digitalWrite(RLED,LOW); //digitalWrite(SASLED, VData.getControlStatus(AGSAS)); digitalWrite(RCSLED, VData.getControlStatus(AGRCS)); //digitalWrite(CG1LED, VData.getControlStatus(AGCustom01)); }*/ /* inline void initLEDS() { pinMode(GLED,OUTPUT); digitalWrite(GLED,HIGH); pinMode(YLED,OUTPUT); digitalWrite(YLED,HIGH); pinMode(RLED,OUTPUT); digitalWrite(RLED,HIGH); //pinMode(SASLED,OUTPUT); //digitalWrite(SASLED,HIGH); pinMode(RCSLED,OUTPUT); digitalWrite(RCSLED,HIGH); //pinMode(CG1LED,OUTPUT); //digitalWrite(CG1LED,HIGH); }*/ /* inline void LEDSAllOff() { digitalWrite(GLED,LOW); digitalWrite(YLED,LOW); digitalWrite(RLED,LOW); //digitalWrite(SASLED,LOW); digitalWrite(RCSLED,LOW); //digitalWrite(CG1LED,LOW); } */
21.721311
72
0.658113
bananu7
19023a59632b4f4a9de73bff7a5160c920f54d79
1,773
hpp
C++
include/OpenSpaceToolkit/Astrodynamics/Flight.hpp
oygx210/open-space-toolkit-astrodynamics
81b76d78bbe76719a34801778d4fb685cc67648f
[ "Apache-2.0" ]
13
2020-05-11T02:22:15.000Z
2022-01-27T09:42:18.000Z
include/OpenSpaceToolkit/Astrodynamics/Flight.hpp
oygx210/open-space-toolkit-astrodynamics
81b76d78bbe76719a34801778d4fb685cc67648f
[ "Apache-2.0" ]
10
2018-09-11T05:27:04.000Z
2020-01-06T03:48:28.000Z
include/OpenSpaceToolkit/Astrodynamics/Flight.hpp
open-space-collective/open-space-toolkit-astrodynamics
d709f5237f25e5ef40eafa5f87e39c00b8acbae1
[ "Apache-2.0" ]
4
2020-03-05T18:19:03.000Z
2021-06-24T04:25:05.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @project Open Space Toolkit ▸ Astrodynamics /// @file OpenSpaceToolkit/Astrodynamics/Flight.hpp /// @author Lucas Brémond <lucas@loftorbital.com> /// @license Apache License 2.0 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef __OpenSpaceToolkit_Astrodynamics_Flight__ #define __OpenSpaceToolkit_Astrodynamics_Flight__ #include <OpenSpaceToolkit/Astrodynamics/Flight/Profile/State.hpp> #include <OpenSpaceToolkit/Astrodynamics/Flight/Profile.hpp> //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace ostk { namespace astro { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Spacecraft flight /// /// @ref https://en.wikipedia.org/wiki/Flight_dynamics_(spacecraft) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
45.461538
160
0.250987
oygx210
1907a69bb7bba8c239fb313f1fcba7d10fee3ac0
1,550
cpp
C++
Hackerearth/Practice/Bob and Candies.cpp
coderanant/Competitive-Programming
45076af7894251080ac616c9581fbf2dc49604af
[ "MIT" ]
4
2019-06-04T11:03:38.000Z
2020-06-19T23:37:32.000Z
Hackerearth/Practice/Bob and Candies.cpp
coderanant/Competitive-Programming
45076af7894251080ac616c9581fbf2dc49604af
[ "MIT" ]
null
null
null
Hackerearth/Practice/Bob and Candies.cpp
coderanant/Competitive-Programming
45076af7894251080ac616c9581fbf2dc49604af
[ "MIT" ]
null
null
null
/*coderanant*/ #include <bits/stdc++.h> using namespace std; #define int long long #define ll long long #define f1(i,a,b) for(i=a;i<b;i++) #define f2(i,a,b) for(i=a;i>=b;i--) #define endl '\n' #define pb push_back #define gp " " #define ff first #define ss second #define mp make_pair const int mod=1000000007; vector<int> ans; vector<int> temp; void vcopy() { int k; ans.clear(); f1(k,0,temp.size()) ans.pb(temp[k]); } bool vcomp() { if(temp.size()!=ans.size()) return temp.size()<ans.size(); int k; f1(k,0,temp.size()) { if(temp[k]<ans[k]) return true; else if(ans[k]<temp[k]) return false; } } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); #ifndef ONLINE_JUDGE freopen("/home/akmittal/Desktop/Competitive Programming/in.txt","r",stdin); freopen("/home/akmittal/Desktop/Competitive Programming/out.txt","w",stdout); #endif int n,x; cin>>n>>x; int t,i; f1(i,0,n) ans.pb(9); //cout<<ans<<endl; int arr[n]; f1(i,0,n) cin>>arr[i]; int flag=0; for(int i=0;i<(1<<n);i++) { temp.clear(); int tempsum=0; for(int j=0;j<n;j++) { if(i&(1<<j)) { temp.pb(j); tempsum+=arr[j]; } } // int j; // f1(j,0,temp.size()) // cout<<temp[i]; if(tempsum==x) { if(vcomp()) { flag=1; vcopy(); } } } if(flag) { f1(i,0,ans.size()) cout<<ans[i]+1<<gp; } else cout<<-1; return 0; }
15.656566
82
0.523226
coderanant
1912c75c42d29f56b42fc8d7c75334aada01cddc
955
hpp
C++
apps/openmw/mwmechanics/autocalcspell.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/openmw/mwmechanics/autocalcspell.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/openmw/mwmechanics/autocalcspell.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
#ifndef OPENMW_AUTOCALCSPELL_H #define OPENMW_AUTOCALCSPELL_H #include <cfloat> #include <set> #include <components/esm/loadspel.hpp> #include <components/esm/loadskil.hpp> #include <components/esm/loadrace.hpp> namespace MWMechanics { /// Contains algorithm for calculating an NPC's spells based on stats /// @note We might want to move this code to a component later, so the editor can use it for preview purposes std::vector<std::string> autoCalcNpcSpells(const int* actorSkills, const int* actorAttributes, const ESM::Race* race); // Helpers bool attrSkillCheck (const ESM::Spell* spell, const int* actorSkills, const int* actorAttributes); ESM::Skill::SkillEnum mapSchoolToSkill(int school); void calcWeakestSchool(const ESM::Spell* spell, const int* actorSkills, int& effectiveSchool, float& skillTerm); float calcAutoCastChance(const ESM::Spell* spell, const int* actorSkills, const int* actorAttributes, int effectiveSchool); } #endif
29.84375
123
0.781152
Bodillium
19140d889dc35d732742158cdf0a9bbe7bdf98c5
5,075
cpp
C++
testsrc/io_tests.cpp
sat-clique/cnfkit
280605ef29c95df3d5b349d54b2410451a2f5564
[ "X11" ]
null
null
null
testsrc/io_tests.cpp
sat-clique/cnfkit
280605ef29c95df3d5b349d54b2410451a2f5564
[ "X11" ]
null
null
null
testsrc/io_tests.cpp
sat-clique/cnfkit
280605ef29c95df3d5b349d54b2410451a2f5564
[ "X11" ]
null
null
null
#include <cnfkit/io.h> #include <cnfkit/io/io_buf.h> #include <cnfkit/io/io_libarchive.h> #include <cnfkit/io/io_stdstream.h> #include <cnfkit/io/io_zlib.h> #include "test_utils.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include <filesystem> #include <fstream> #include <memory> #include <sstream> #include <string> #include <vector> namespace fs = std::filesystem; using ::testing::Eq; namespace cnfkit { namespace { std::string const uncompressed_input = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n"; std::vector<uint8_t> const gz_compressed_input = { 0x1f, 0x8b, 0x08, 0x08, 0xdd, 0xb5, 0xb8, 0x60, 0x02, 0x03, 0x6c, 0x6f, 0x72, 0x65, 0x6d, 0x5f, 0x69, 0x70, 0x73, 0x75, 0x6d, 0x00, 0x05, 0xc1, 0xd1, 0x09, 0xc0, 0x20, 0x0c, 0x05, 0xc0, 0xff, 0x4e, 0xf1, 0x06, 0x28, 0x9d, 0xc4, 0x25, 0x24, 0x06, 0x79, 0x60, 0x8c, 0x24, 0x71, 0xff, 0xde, 0x35, 0x0f, 0x35, 0xf0, 0xe4, 0x35, 0x0c, 0x5f, 0x1e, 0x48, 0x16, 0xba, 0x69, 0xbd, 0x10, 0xdf, 0xa9, 0x52, 0x5a, 0x37, 0xd0, 0x07, 0x0f, 0x53, 0xb8, 0x27, 0x74, 0xb1, 0xbe, 0xe7, 0x07, 0x3a, 0xed, 0x29, 0xfa, 0x39, 0x00, 0x00, 0x00}; void dump_to_file(std::vector<uint8_t> const& content, fs::path const& path) { std::ofstream file{path}; file.write(reinterpret_cast<char const*>(content.data()), gz_compressed_input.size()); } auto as_bytes(std::string const& str) -> std::vector<std::byte> { std::vector<std::byte> result; for (char const ch : str) { result.push_back(static_cast<std::byte>(ch)); } return result; } template <typename T> class decompressing_source_context { public: decompressing_source_context(std::vector<uint8_t> const& input) : m_temp_dir{"cnfkit_io"} { fs::path const input_file = m_temp_dir.get_path() / "input"; dump_to_file(input, input_file); m_source = std::make_unique<T>(input_file); } auto get_source() -> T& { return *m_source; } private: std::unique_ptr<T> m_source; temp_dir m_temp_dir; }; } template <typename T> class DecompressingSourceTests : public ::testing::Test { }; using decompressing_sources = ::testing::Types<zlib_source, libarchive_source>; TYPED_TEST_SUITE(DecompressingSourceTests, decompressing_sources); namespace { auto create_buffer() -> std::vector<std::byte> { std::vector<std::byte> result; result.resize(uncompressed_input.size()); return result; } } TYPED_TEST(DecompressingSourceTests, ThrowsOnConstructionWhenFileNotFound) { EXPECT_THROW(TypeParam{"does/not/exist"}, std::runtime_error); } TYPED_TEST(DecompressingSourceTests, ReadingCompleteValidInput) { decompressing_source_context<TypeParam> context{gz_compressed_input}; source& under_test = context.get_source(); auto buffer = create_buffer(); auto ptr_past_end = under_test.read_bytes(buffer.data(), buffer.data() + uncompressed_input.size()); buffer.resize(std::distance(buffer.data(), ptr_past_end)); EXPECT_THAT(buffer, Eq(as_bytes(uncompressed_input))); EXPECT_THAT(under_test.read_byte(), Eq(std::nullopt)); EXPECT_TRUE(under_test.is_eof()); } TYPED_TEST(DecompressingSourceTests, ReadingCompleteValidInputByteWise) { decompressing_source_context<TypeParam> context{gz_compressed_input}; source& under_test = context.get_source(); std::vector<std::byte> result; while (!under_test.is_eof()) { std::optional<std::byte> const byte = under_test.read_byte(); if (byte.has_value()) { result.push_back(*byte); } } EXPECT_TRUE(under_test.is_eof()); EXPECT_THAT(result, Eq(as_bytes(uncompressed_input))); } TYPED_TEST(DecompressingSourceTests, ReadingAfterMove) { decompressing_source_context<TypeParam> context{gz_compressed_input}; TypeParam& under_test = context.get_source(); TypeParam moved_source = std::move(under_test); EXPECT_THAT(moved_source.read_byte(), ::testing::Optional(std::byte{'L'})); } TEST(IStreamSourceTests, ReadCompleteInput) { std::stringstream test_input{uncompressed_input}; istream_source under_test{test_input}; auto buffer = create_buffer(); auto ptr_past_end = under_test.read_bytes(buffer.data(), buffer.data() + uncompressed_input.size()); buffer.resize(std::distance(buffer.data(), ptr_past_end)); EXPECT_THAT(buffer, Eq(as_bytes(uncompressed_input))); EXPECT_THAT(under_test.read_byte(), Eq(std::nullopt)); EXPECT_TRUE(under_test.is_eof()); } TEST(IStreamSourceTests, ReadCompleteInputBytewise) { std::stringstream test_input{uncompressed_input}; istream_source under_test{test_input}; std::vector<std::byte> result; while (!under_test.is_eof()) { std::optional<std::byte> const byte = under_test.read_byte(); if (byte.has_value()) { result.push_back(*byte); } } EXPECT_TRUE(under_test.is_eof()); EXPECT_THAT(result, Eq(as_bytes(uncompressed_input))); } TEST(IStreamSourceTests, ReadingAfterMove) { std::stringstream test_input{uncompressed_input}; istream_source under_test{test_input}; istream_source moved_source = std::move(under_test); EXPECT_THAT(moved_source.read_byte(), ::testing::Optional(std::byte{'L'})); } }
28.835227
100
0.731823
sat-clique
19194698392ffa0b61e8fbd0fec8d5b6185cb55f
201
cpp
C++
cardigan.cpp
kazunetakahashi/poh7
8ebf03f7b5a9db5277006678d23d1a0044e91c99
[ "MIT" ]
null
null
null
cardigan.cpp
kazunetakahashi/poh7
8ebf03f7b5a9db5277006678d23d1a0044e91c99
[ "MIT" ]
null
null
null
cardigan.cpp
kazunetakahashi/poh7
8ebf03f7b5a9db5277006678d23d1a0044e91c99
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { int n; cin >> n; int x = 1; for (auto i = 1; i <= n; i++) { x *= i; } cout << x << endl; }
13.4
33
0.517413
kazunetakahashi
191f5f2f1b94bc9069767a0ce3573e45e54b6983
9,240
cpp
C++
Test/System/String.cpp
SimmyPeet/Axis
a58c073d13f74d0224fbfca34a4dcd4b9d0c6726
[ "Apache-2.0" ]
1
2022-01-23T14:51:51.000Z
2022-01-23T14:51:51.000Z
Test/System/String.cpp
SimmyPeet/Axis
a58c073d13f74d0224fbfca34a4dcd4b9d0c6726
[ "Apache-2.0" ]
null
null
null
Test/System/String.cpp
SimmyPeet/Axis
a58c073d13f74d0224fbfca34a4dcd4b9d0c6726
[ "Apache-2.0" ]
1
2022-01-10T21:01:54.000Z
2022-01-10T21:01:54.000Z
#include <Axis/System> #include <doctest.h> using namespace Axis; using namespace Axis::System; DOCTEST_TEST_CASE("Axis string data structure : [Axis-System]") { DOCTEST_SUBCASE("`Axis::String` constructors") { DOCTEST_SUBCASE("Constructor") { // Default string (empty) String8 str; // Checks if the string is empty DOCTEST_CHECK(str == nullptr); // Constructs a string String8 helloWorld = "Hello World"; // Checks if the string contains the correct amount of characters DOCTEST_CHECK(helloWorld.GetLength() == 11); // Checks if the string contains the correct characters DOCTEST_CHECK(helloWorld == "Hello World"); // Constructs a string with a nullptr String8 nullString = nullptr; // Checks if the string contains the correct amount of characters DOCTEST_CHECK(nullString.GetLength() == 0); // Checks if the string contains the correct characters DOCTEST_CHECK(nullString == ""); // Compares string with a nullptr DOCTEST_CHECK(nullString == nullptr); // Constructs a string with a nullptr String8 emptyString = ""; // Checks if the string contains the correct amount of characters DOCTEST_CHECK(emptyString.GetLength() == 0); // Checks if the string contains the correct characters DOCTEST_CHECK(emptyString == ""); // Compares string with a nullptr DOCTEST_CHECK(emptyString == nullptr); // Creates a string which probably uses dynamic memory String8 longString = "This is a long string which probably uses dynamic memory"; // Checks if the string contains the correct amount of characters DOCTEST_CHECK(longString.GetLength() == 56); // Checks if the string contains the correct characters DOCTEST_CHECK(longString == "This is a long string which probably uses dynamic memory"); // Compares string with a nullptr DOCTEST_CHECK(longString != nullptr); // Compares string with an empty string DOCTEST_CHECK(longString != ""); // Creates `Axis::String8` from WChar string String8 helloWorldCross = L"Hello World"; // Checks if the string contains the correct amount of characters DOCTEST_CHECK(helloWorldCross.GetLength() == 11); // Checks if the string contains the correct characters DOCTEST_CHECK(helloWorldCross == "Hello World"); } DOCTEST_SUBCASE("Move constructor") { // Constructs a string String8 longString = "This is a long string which probably uses dynamic memory"; // Moves a string String8 movedLongString = std::move(longString); // Checks if the string contains the correct amount of characters DOCTEST_CHECK(movedLongString.GetLength() == 56); // Checks if the string contains the correct characters DOCTEST_CHECK(movedLongString == "This is a long string which probably uses dynamic memory"); // Compares string with a nullptr DOCTEST_CHECK(movedLongString != nullptr); // Compares string with an empty string DOCTEST_CHECK(movedLongString != ""); // Moved string is empty DOCTEST_CHECK(longString == nullptr); } DOCTEST_SUBCASE("Copy constructor") { // Constructs a string String8 helloWorld = "Hello World"; // Copy constructor String8 copyHelloWorld = helloWorld; // Checks if the string contains the correct amount of characters DOCTEST_CHECK(copyHelloWorld.GetLength() == 11); // Checks if the string contains the correct characters DOCTEST_CHECK(copyHelloWorld == "Hello World"); // Checks if the string contains the correct amount of characters DOCTEST_CHECK(helloWorld.GetLength() == 11); // Checks if the string contains the correct characters DOCTEST_CHECK(helloWorld == "Hello World"); // Constructs a long string String8 longString = "This is a long string which probably uses dynamic memory"; // Copy constructor String8 copyLongString = longString; // Checks if the string contains the correct amount of characters DOCTEST_CHECK(copyLongString.GetLength() == 56); // Checks if the string contains the correct characters DOCTEST_CHECK(copyLongString == "This is a long string which probably uses dynamic memory"); // Checks if the string contains the correct amount of characters DOCTEST_CHECK(longString.GetLength() == 56); // Checks if the string contains the correct characters DOCTEST_CHECK(longString == "This is a long string which probably uses dynamic memory"); } } DOCTEST_SUBCASE("`Axis::String` assignment operator") { DOCTEST_SUBCASE("Copy assignment operator") { // Constructs a string String8 helloWorld = "Hello World"; // Constructs another string String8 anotherString = "Another string"; // Checks if the string contains the correct amount of characters DOCTEST_CHECK(helloWorld.GetLength() == 11); // Checks if the string contains the correct characters DOCTEST_CHECK(helloWorld == "Hello World"); // Copy assignment operator helloWorld = anotherString; // Checks if the string contains the correct amount of characters DOCTEST_CHECK(helloWorld.GetLength() == 14); // Checks if the string contains the correct characters DOCTEST_CHECK(helloWorld == "Another string"); // Checks if the string contains the correct amount of characters DOCTEST_CHECK(anotherString.GetLength() == 14); // Checks if the string contains the correct characters DOCTEST_CHECK(anotherString == "Another string"); } DOCTEST_SUBCASE("Move assignment operator") { // Constructs a string String8 helloWorld = "Hello World"; // Constructs another string String8 anotherString = "Another string"; // Checks if the string contains the correct amount of characters DOCTEST_CHECK(helloWorld.GetLength() == 11); // Checks if the string contains the correct characters DOCTEST_CHECK(helloWorld == "Hello World"); // Move assignment operator helloWorld = std::move(anotherString); // Checks if the string contains the correct amount of characters DOCTEST_CHECK(helloWorld.GetLength() == 14); // Checks if the string contains the correct characters DOCTEST_CHECK(helloWorld == "Another string"); // Checks if the string contains the correct amount of characters DOCTEST_CHECK(anotherString.GetLength() == 0); // Checks if the string contains the correct characters DOCTEST_CHECK(anotherString == ""); } } DOCTEST_SUBCASE("`Axis::String` comparison operators") { // Compares two strings DOCTEST_CHECK(String8("Hello World") == String8("Hello World")); // Compares two strings DOCTEST_CHECK(String8("Hello World") != String8("Hello World!")); // Compares two strings with different character types DOCTEST_CHECK(String8("Hello World") == WString(L"Hello World")); // Compares with nullptr DOCTEST_CHECK(String8("Hello World") != nullptr); // Compares with empty string DOCTEST_CHECK(String8("Hello World") != ""); // Compares with a nullptr DOCTEST_CHECK(String8() == nullptr); // Compares with an empty string DOCTEST_CHECK(String8() == ""); } DOCTEST_SUBCASE("`Axis::String` subscript operator") { // Constructs a string String8 helloWorld = "Hello World"; // Subscripts the string with an index and checks if the character is correct DOCTEST_CHECK(helloWorld[0] == 'H'); DOCTEST_CHECK(helloWorld[1] == 'e'); DOCTEST_CHECK(helloWorld[2] == 'l'); DOCTEST_CHECK(helloWorld[3] == 'l'); DOCTEST_CHECK(helloWorld[4] == 'o'); DOCTEST_CHECK(helloWorld[5] == ' '); DOCTEST_CHECK(helloWorld[6] == 'W'); DOCTEST_CHECK(helloWorld[7] == 'o'); DOCTEST_CHECK(helloWorld[8] == 'r'); DOCTEST_CHECK(helloWorld[9] == 'l'); DOCTEST_CHECK(helloWorld[10] == 'd'); // Out of range subscript, should throws an exception try { helloWorld[11] = '!'; } catch (::Axis::System::Exception&) { DOCTEST_CHECK(true); } } }
36.09375
105
0.606169
SimmyPeet
1929904be94da08877b20a99828a66e40b39c52e
739
hpp
C++
includes/eeros/core/Fault.hpp
ClaudiaVisentin/eeros-framework
63739a2e33b0c5e9e573748fef675131c35181a6
[ "Apache-2.0" ]
10
2015-02-17T15:27:50.000Z
2021-12-10T08:34:13.000Z
includes/eeros/core/Fault.hpp
ClaudiaVisentin/eeros-framework
63739a2e33b0c5e9e573748fef675131c35181a6
[ "Apache-2.0" ]
6
2016-05-10T17:11:09.000Z
2022-03-31T07:52:11.000Z
includes/eeros/core/Fault.hpp
ClaudiaVisentin/eeros-framework
63739a2e33b0c5e9e573748fef675131c35181a6
[ "Apache-2.0" ]
13
2016-05-01T09:56:51.000Z
2022-03-28T09:27:49.000Z
#ifndef ORG_EEROS_CORE_FAULT_HPP #define ORG_EEROS_CORE_FAULT_HPP #include <string> #include <sstream> #include <exception> namespace eeros { /** * Base class for EEROS faults. */ class Fault : public std::exception { public: /** * Default constructor for a fault. */ Fault(); /** * Default constructor for a named fault. * * @param m - name of the fault */ explicit Fault(std::string m); /** * Default constructor for a fault. */ virtual ~Fault() throw(); /** Returns a C-style character string describing the general cause * of the current error. */ virtual const char* what() const throw(); protected: std::string message; }; } #endif // ORG_EEROS_CORE_FAULT_HPP
16.422222
69
0.649526
ClaudiaVisentin
192ba54326ea53473d483f1b6bc0546a16236938
6,677
cc
C++
orb_object_slam/src/MapObject.cc
Aceralon/cube_slam
1687e7cca6e77c96a507655c8dd6c1e7653535ae
[ "BSD-3-Clause" ]
619
2018-10-31T00:04:33.000Z
2022-03-28T13:25:41.000Z
orb_object_slam/src/MapObject.cc
Aceralon/cube_slam
1687e7cca6e77c96a507655c8dd6c1e7653535ae
[ "BSD-3-Clause" ]
48
2019-03-19T03:05:55.000Z
2022-01-20T03:57:44.000Z
orb_object_slam/src/MapObject.cc
Aceralon/cube_slam
1687e7cca6e77c96a507655c8dd6c1e7653535ae
[ "BSD-3-Clause" ]
207
2018-10-31T02:02:09.000Z
2022-03-30T08:25:36.000Z
#include "MapObject.h" #include "KeyFrame.h" #include "MapPoint.h" #include "Map.h" #include <Converter.h> #include "mutex" namespace ORB_SLAM2 { using namespace std; long int MapObject::nNextId = 0; mutex MapObject::mGlobalMutex; MapObject::MapObject(Map *pMap, bool update_index) : mbBad(false), mpMap(pMap) { if (update_index) mnId = nNextId++; else mnId = -1; nObs = 0; moRefKF = nullptr; mLatestKF = nullptr; largest_point_observations = 0; pointOwnedThreshold = 0; already_associated = false; become_candidate = false; association_refid_in_tracking = -1; associated_landmark = nullptr; object_id_in_localKF = -1; left_right_to_car = -1; isGood = false; truth_tracklet_id = -1; velocityTwist.setZero(); velocityPlanar.setZero(); } long int MapObject::getIncrementedIndex() { nNextId++; return nNextId; } vector<MapPoint *> MapObject::GetUniqueMapPoints() { unique_lock<mutex> lock(mMutexFeatures); return vector<MapPoint *>(mappoints_unique_own.begin(), mappoints_unique_own.end()); } int MapObject::NumUniqueMapPoints() { unique_lock<mutex> lock(mMutexFeatures); return mappoints_unique_own.size(); } void MapObject::AddUniqueMapPoint(MapPoint *pMP, int obs_num) { unique_lock<mutex> lock(mMutexFeatures); mappoints_unique_own.insert(pMP); if (obs_num > largest_point_observations) // exact way. largest_point_observations = obs_num; } void MapObject::EraseUniqueMapPoint(MapPoint *pMP, int obs_num) { unique_lock<mutex> lock(mMutexFeatures); mappoints_unique_own.erase(pMP); if (obs_num == largest_point_observations) largest_point_observations -= 1; // HACK only an approximate way. otherwise need to keep sorted the observations (heap). complicated, not worth it. } vector<MapPoint *> MapObject::GetPotentialMapPoints() { unique_lock<mutex> lock(mMutexFeatures); return vector<MapPoint *>(mappoints_potential_own.begin(), mappoints_potential_own.end()); } void MapObject::AddPotentialMapPoint(MapPoint *pMP) { unique_lock<mutex> lock(mMutexFeatures); mappoints_potential_own.insert(pMP); } bool MapObject::check_whether_valid_object(int own_point_thre) { if ((int)mappoints_potential_own.size() > own_point_thre) become_candidate = true; else become_candidate = false; return become_candidate; } void MapObject::SetAsLandmark() { for (set<MapPoint *>::iterator mit = mappoints_potential_own.begin(); mit != mappoints_potential_own.end(); mit++) { (*mit)->AddObjectObservation(this); // add into actual object landmark observation. make sure this->already_associated=true; } } void MapObject::MergeIntoLandmark(MapObject *otherLocalObject) { //NOTE other object is just local. not add to actual point-object observation yet. therefore no need to delete object-point observation. for (set<MapPoint *>::iterator mit = otherLocalObject->mappoints_potential_own.begin(); mit != otherLocalObject->mappoints_potential_own.end(); mit++) { (*mit)->AddObjectObservation(this); } } void MapObject::addObservation(KeyFrame *pKF, size_t idx) { unique_lock<mutex> lock(mMutexFeatures); if (mLatestKF == nullptr) mLatestKF = pKF; if (pKF->mnId >= mLatestKF->mnId) mLatestKF = pKF; if (mObservations.count(pKF)) return; mObservations[pKF] = idx; nObs++; observed_frames.push_back(pKF); } void MapObject::EraseObservation(KeyFrame *pKF) { bool bBad = false; { unique_lock<mutex> lock(mMutexFeatures); if (mObservations.count(pKF)) { mObservations.erase(pKF); if (moRefKF == pKF) //update reference keyframe if possible { long unsigned int min_kf_id = mLatestKF->mnId + 1; KeyFrame *smallest_kf = nullptr; for (unordered_map<KeyFrame *, size_t>::iterator mit = mObservations.begin(), mend = mObservations.end(); mit != mend; mit++) if (mit->first->mnId < min_kf_id) smallest_kf = mit->first; moRefKF = smallest_kf; } if (mLatestKF == pKF) //update latest KF if possible { observed_frames.pop_back(); mLatestKF = observed_frames.back(); } nObs--; if (nObs <= 0) bBad = true; } } if (bBad) SetBadFlag(); } unordered_map<KeyFrame *, size_t> MapObject::GetObservations() { unique_lock<mutex> lock(mMutexFeatures); return mObservations; } int MapObject::Observations() { unique_lock<mutex> lock(mMutexFeatures); return nObs; } std::vector<KeyFrame *> MapObject::GetObserveFrames() { unique_lock<mutex> lock(mMutexFeatures); vector<KeyFrame *> res; for (unordered_map<KeyFrame *, size_t>::iterator mit = mObservations.begin(), mend = mObservations.end(); mit != mend; mit++) { res.push_back(mit->first); } return res; } std::vector<KeyFrame *> MapObject::GetObserveFramesSequential() { unique_lock<mutex> lock(mMutexFeatures); return observed_frames; } bool MapObject::IsInKeyFrame(KeyFrame *pKF) { unique_lock<mutex> lock(mMutexFeatures); return (mObservations.count(pKF)); } int MapObject::GetIndexInKeyFrame(KeyFrame *pKF) { unique_lock<mutex> lock(mMutexFeatures); if (mObservations.count(pKF)) return mObservations[pKF]; else return -1; } void MapObject::SetBadFlag() { unordered_map<KeyFrame *, size_t> obs; { unique_lock<mutex> lock1(mMutexFeatures); unique_lock<mutex> lock2(mMutexPos); mbBad = true; obs = mObservations; // fully copy the contents, similar to vector mObservations.clear(); // remove observations from point side observed_frames.clear(); } for (unordered_map<KeyFrame *, size_t>::iterator mit = obs.begin(), mend = obs.end(); mit != mend; mit++) { KeyFrame *pKF = mit->first; // NOTE when use obj_landmark in association and BA, check if valid. pKF->EraseMapObjectMatch(mit->second); // remove observations from frame side } mpMap->EraseMapObject(this); } bool MapObject::isBad() { unique_lock<mutex> lock(mMutexFeatures); unique_lock<mutex> lock2(mMutexPos); return mbBad; } KeyFrame *MapObject::GetReferenceKeyFrame() { return moRefKF; } KeyFrame *MapObject::GetLatestKeyFrame() { unique_lock<mutex> lock(mMutexFeatures); return mLatestKF; } void MapObject::SetReferenceKeyFrame(KeyFrame *refkf) { moRefKF = refkf; } void MapObject::SetWorldPos(const g2o::cuboid &Pos) { unique_lock<mutex> lock2(mGlobalMutex); unique_lock<mutex> lock(mMutexPos); pose_Twc = Pos; pose_Tcw = pose_Twc; pose_Tcw.pose = pose_Twc.pose.inverse(); } g2o::cuboid MapObject::GetWorldPos() { unique_lock<mutex> lock(mMutexPos); if (is_dynamic) return pose_Twc_latestKF; return pose_Twc; } g2o::SE3Quat MapObject::GetWorldPosInv() { unique_lock<mutex> lock(mMutexPos); return pose_Tcw.pose; } g2o::cuboid MapObject::GetWorldPosBA() { unique_lock<mutex> lock(mMutexPos); return pose_Twc_afterba; } } // namespace ORB_SLAM2
23.510563
151
0.736409
Aceralon
193094f3d7f28da998e67b90526c3ce73af0766a
676
cpp
C++
ProyectoFinal-L1/cuenta.cpp
josedaviddubon/cpp
caa8db741065f3c6a7b9fc9dfddfb619a481c815
[ "MIT" ]
null
null
null
ProyectoFinal-L1/cuenta.cpp
josedaviddubon/cpp
caa8db741065f3c6a7b9fc9dfddfb619a481c815
[ "MIT" ]
null
null
null
ProyectoFinal-L1/cuenta.cpp
josedaviddubon/cpp
caa8db741065f3c6a7b9fc9dfddfb619a481c815
[ "MIT" ]
null
null
null
#include <iostream> #include "Includes/pinguino.h" using namespace std; void menu() { int opcion = 0; while(true) { system("cls"); cout << "******"; cout << "PINGUINO"; cout << "*****"; cout << endl; cout << endl; cout << endl; cout << "1- Agregar Precios y dividir cuentas: " << endl; cout << "2- Dejarlo en manos del Pinguino: " << endl; cout << "0- Salir: " << endl; cout << endl; cout << "Ingrese una opicion: "; cin >> opcion; if(opcion == 0) { break; } if (opcion == 2) { pinwuinos(); } else { pedidos(opcion); } } }
13.795918
61
0.457101
josedaviddubon
19332881fe050bf5c08e69096921dcd490f9f6cd
1,169
cpp
C++
ee21/common/src/token.cpp
ygor-rezende/Expression-Evaluator
52868ff11ce72a4ae6fa9a4052005c02f8485b3c
[ "FTL" ]
null
null
null
ee21/common/src/token.cpp
ygor-rezende/Expression-Evaluator
52868ff11ce72a4ae6fa9a4052005c02f8485b3c
[ "FTL" ]
null
null
null
ee21/common/src/token.cpp
ygor-rezende/Expression-Evaluator
52868ff11ce72a4ae6fa9a4052005c02f8485b3c
[ "FTL" ]
null
null
null
/*! \file token.cpp \brief Token class implementation. \author Garth Santor \date 2021-10-29 \copyright Garth Santor, Trinh Han ============================================================= Implementation of the Token class. ============================================================= Revision History ------------------------------------------------------------- Version 2021.10.02 C++ 20 validated Version 2019.11.05 C++ 17 cleanup Version 2012.11.13 Alpha release. ============================================================= Copyright Garth Santor/Trinh Han The copyright to the computer program(s) herein is the property of Garth Santor/Trinh Han, Canada. The program(s) may be used and/or copied only with the written permission of Garth Santor/Trinh Han or in accordance with the terms and conditions stipulated in the agreement/contract under which the program(s) have been supplied. =============================================================*/ #include <ee/token.hpp> using namespace std; [[nodiscard]] Token::string_type Token::str() const { return string_type("<") + string_type(typeid(*this).name()).substr(6) + string_type(">"); }
27.186047
90
0.55432
ygor-rezende
1939307ab598bc23f0a8a5891c75f10ef05429fe
1,803
hpp
C++
external/include/SFGUI/SFGUI.hpp
JevinJ/ConnectFour
3e131c9ff957c3ca108b6f79e8940ba3ae40e8d4
[ "MIT" ]
3
2018-09-09T01:50:13.000Z
2018-09-09T01:50:31.000Z
external/include/SFGUI/SFGUI.hpp
JevinJ/ConnectFour
3e131c9ff957c3ca108b6f79e8940ba3ae40e8d4
[ "MIT" ]
null
null
null
external/include/SFGUI/SFGUI.hpp
JevinJ/ConnectFour
3e131c9ff957c3ca108b6f79e8940ba3ae40e8d4
[ "MIT" ]
1
2021-04-30T13:49:57.000Z
2021-04-30T13:49:57.000Z
#pragma once #include <SFGUI/Config.hpp> #include <SFML/Config.hpp> namespace sf { class Window; class RenderWindow; class RenderTexture; } namespace sfg { class Renderer; /** A class to shield us from evil SFML and MSVC. */ class SFGUI_API SFGUI { public: /** Constructor. */ SFGUI(); /** Dtor. */ ~SFGUI(); /** Draw the GUI to an sf::Window. * Just a wrapper for the renderer. * @param target sf::Window to draw to. */ void Display( sf::Window& target ); /** Draw the GUI to an sf::RenderWindow. * Just a wrapper for the renderer. * @param target sf::RenderWindow to draw to. */ void Display( sf::RenderWindow& target ); /** Draw the GUI to an sf::RenderTexture. * Just a wrapper for the renderer. * @param target sf::RenderTexture to draw to. */ void Display( sf::RenderTexture& target ); /** Gets a reference to the currently active Renderer. * Just a wrapper for Renderer::Get(). * @return Reference to the currently active Renderer. */ Renderer& GetRenderer(); /** Check if an SFGUI object was created. * @return true if an SFGUI object was created. */ static bool IsAlive(); /** Add a required character set to the character sets that SFGUI will take into consideration for new fonts. * This is required if using a script whose glyphs are not smaller than codepoint 0x370 * such as Greek, Cyrillic, Hebrew, Arabic etc. * By default, only the Latin script and its extensions are taken into consideration. * @param low_bound Lower boundary of the character set, i.e. the glyph with the smallest codepoint. * @param high_bound Higher boundary of the character set, i.e. the glyph with the largest codepoint. */ void AddCharacterSet( sf::Uint32 low_bound, sf::Uint32 high_bound ); }; }
26.130435
111
0.687188
JevinJ