hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
7792a1082bf8019894311fd989b4766c94970307
1,963
cpp
C++
src/Platform.Cocoa/MouseCocoa.cpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
src/Platform.Cocoa/MouseCocoa.cpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
src/Platform.Cocoa/MouseCocoa.cpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2015 mogemimi. // Distributed under the MIT license. See LICENSE.md file for details. #include "MouseCocoa.hpp" #include <type_traits> namespace Pomdog { namespace Detail { namespace Cocoa { //----------------------------------------------------------------------- MouseCocoa::MouseCocoa() : scrollWheel(0) {} //----------------------------------------------------------------------- MouseState MouseCocoa::GetState() const { return state; } //----------------------------------------------------------------------- void MouseCocoa::Position(Point2D const& position) { state.Position = position; } //----------------------------------------------------------------------- void MouseCocoa::WheelDelta(double wheelDelta) { scrollWheel += wheelDelta; static_assert(std::is_same<double, decltype(scrollWheel)>::value, ""); static_assert(std::is_same<std::int32_t, decltype(state.ScrollWheel)>::value, ""); state.ScrollWheel = this->scrollWheel; } //----------------------------------------------------------------------- void MouseCocoa::LeftButton(ButtonState buttonState) { state.LeftButton = buttonState; } //----------------------------------------------------------------------- void MouseCocoa::RightButton(ButtonState buttonState) { state.RightButton = buttonState; } //----------------------------------------------------------------------- void MouseCocoa::MiddleButton(ButtonState buttonState) { state.MiddleButton = buttonState; } //----------------------------------------------------------------------- void MouseCocoa::XButton1(ButtonState buttonState) { state.XButton1 = buttonState; } //----------------------------------------------------------------------- void MouseCocoa::XButton2(ButtonState buttonState) { state.XButton2 = buttonState; } //----------------------------------------------------------------------- } // namespace Cocoa } // namespace Detail } // namespace Pomdog
32.180328
86
0.464086
bis83
77953649de1f1064d89f8c61642717fe310407f2
11,224
cpp
C++
engine/cl_splitscreen.cpp
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
252
2020-12-16T15:34:43.000Z
2022-03-31T23:21:37.000Z
cstrike15_src/engine/cl_splitscreen.cpp
bahadiraraz/Counter-Strike-Global-Offensive
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
[ "MIT" ]
23
2020-12-20T18:02:54.000Z
2022-03-28T16:58:32.000Z
cstrike15_src/engine/cl_splitscreen.cpp
bahadiraraz/Counter-Strike-Global-Offensive
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
[ "MIT" ]
42
2020-12-19T04:32:33.000Z
2022-03-30T06:00:28.000Z
#include "client_pch.h" #include "cl_splitscreen.h" #if defined( _PS3 ) #include "tls_ps3.h" #define m_SplitSlot reinterpret_cast< SplitSlot_t *& >(GetTLSGlobals()->pEngineSplitSlot) #endif // _PS3 // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" class CSplitScreen : public ISplitScreen { public: CSplitScreen(); virtual bool Init(); virtual void Shutdown(); virtual bool AddSplitScreenUser( int nSlot, int nPlayerIndex ); virtual bool AddBaseUser( int nSlot, int nPlayerIndex ); virtual bool RemoveSplitScreenUser( int nSlot, int nPlayerIndex ); virtual int GetActiveSplitScreenPlayerSlot(); virtual int SetActiveSplitScreenPlayerSlot( int slot ); virtual bool IsValidSplitScreenSlot( int nSlot ); virtual int FirstValidSplitScreenSlot(); // -1 == invalid virtual int NextValidSplitScreenSlot( int nPreviousSlot ); // -1 == invalid virtual int GetNumSplitScreenPlayers(); virtual int GetSplitScreenPlayerEntity( int nSlot ); virtual INetChannel *GetSplitScreenPlayerNetChan( int nSlot ); virtual bool IsDisconnecting( int nSlot ); virtual void SetDisconnecting( int nSlot, bool bState ); virtual bool SetLocalPlayerIsResolvable( char const *pchContext, int nLine, bool bResolvable ); virtual bool IsLocalPlayerResolvable(); CClientState &GetLocalPlayer( int nSlot = -1 ); struct SplitSlot_t { SplitSlot_t() : m_nActiveSplitScreenPlayer( 0 ), m_bLocalPlayerResolvable( false ), m_bMainThread( false ) { } short m_nActiveSplitScreenPlayer; // Can a call to C_BasePlayer::GetLocalPlayer be resolved in client .dll (inside a setactivesplitscreenuser scope?) unsigned short m_bLocalPlayerResolvable : 1; unsigned short m_bMainThread : 1; unsigned short pad : 14; }; private: int FindSplitPlayerSlot( int nPlayerEntityIndex ); struct SplitPlayer_t { SplitPlayer_t() : m_bActive( false ) { } bool m_bActive; CClientState m_Client; }; SplitPlayer_t *m_SplitScreenPlayers[ MAX_SPLITSCREEN_CLIENTS ]; int m_nActiveSplitScreenUserCount; #if defined( _PS3 ) #elif !defined( _X360 ) // Each thread (mainly an issue in the client .dll) can have it's own "active" context. The per thread data is allocated as needed #else // xbox uses 12 bit thread id key to do direct lookup SplitSlot_t m_SplitSlotTable[0x1000]; #endif SplitSlot_t *GetSplitSlot(); bool m_bInitialized; }; static CTHREADLOCALPTR( CSplitScreen::SplitSlot_t ) s_SplitSlot; static CSplitScreen g_SplitScreenMgr; ISplitScreen *splitscreen = &g_SplitScreenMgr; CSplitScreen::CSplitScreen() { m_bInitialized = false; } #if defined( _X360 ) inline int BucketForThreadId() { DWORD id = GetCurrentThreadId(); // e.g.: 0xF9000028 -- or's the 9 and the 28 to give 12 bits (slot array is 0x1000 in size), the first nibble is(appears to be) always F so is masked off (0x0F00) return ( ( id >> 16 ) & 0x00000F00 ) | ( id & 0x000000FF ); } #endif CSplitScreen::SplitSlot_t *CSplitScreen::GetSplitSlot() { #if defined( _X360 ) // pix shows this function to be enormously expensive due to high frequency of inner loop calls // avoid conditionals and TLS, use a direct lookup instead return &m_SplitSlotTable[ BucketForThreadId() ]; #else if ( !s_SplitSlot ) { s_SplitSlot = new SplitSlot_t(); } return s_SplitSlot; #endif } bool CSplitScreen::Init() { m_bInitialized = true; Assert( ThreadInMainThread() ); SplitSlot_t *pSlot = GetSplitSlot(); pSlot->m_bLocalPlayerResolvable = false; pSlot->m_nActiveSplitScreenPlayer = 0; pSlot->m_bMainThread = true; m_nActiveSplitScreenUserCount = 1; for ( int i = 0 ; i < MAX_SPLITSCREEN_CLIENTS; ++i ) { MEM_ALLOC_CREDIT(); m_SplitScreenPlayers[ i ] = new SplitPlayer_t(); SplitPlayer_t *sp = m_SplitScreenPlayers[ i ]; sp->m_bActive = ( i == 0 ) ? true : false; sp->m_Client.m_bSplitScreenUser = ( i != 0 ) ? true : false; } return true; } void CSplitScreen::Shutdown() { Assert( ThreadInMainThread() ); for ( int i = 0; i < MAX_SPLITSCREEN_CLIENTS; ++i ) { delete m_SplitScreenPlayers[ i ]; m_SplitScreenPlayers[ i ] = NULL; } } bool CSplitScreen::AddBaseUser( int nSlot, int nPlayerIndex ) { Assert( ThreadInMainThread() ); SplitPlayer_t *sp = m_SplitScreenPlayers[ nSlot ]; sp->m_bActive = true; sp->m_Client.m_nSplitScreenSlot = nSlot; return true; } bool CSplitScreen::AddSplitScreenUser( int nSlot, int nPlayerEntityIndex ) { Assert( ThreadInMainThread() ); SplitPlayer_t *sp = m_SplitScreenPlayers[ nSlot ]; if ( sp->m_bActive == true ) { Assert( sp->m_Client.m_nSplitScreenSlot == nSlot ); Assert( sp->m_Client.m_nPlayerSlot == nPlayerEntityIndex - 1 ); return true; } // Msg( "Attached %d to slot %d\n", nPlayerEntityIndex, nSlot ); // 0.0.0.0:0 signifies a bot. It'll plumb all the way down to winsock calls but it won't make them. ns_address adr; adr.SetAddrType( NSAT_NETADR ); adr.m_adr.SetIPAndPort( 0, 0 ); char szName[ 256 ]; Q_snprintf( szName, sizeof( szName), "SPLIT%d", nSlot ); sp->m_bActive = true; sp->m_Client.Clear(); sp->m_Client.m_nPlayerSlot = nPlayerEntityIndex - 1; sp->m_Client.m_nSplitScreenSlot = nSlot; sp->m_Client.m_NetChannel = NET_CreateNetChannel( NS_CLIENT, &adr, szName, &sp->m_Client, NULL, true ); GetBaseLocalClient().m_NetChannel->AttachSplitPlayer( nSlot, sp->m_Client.m_NetChannel ); sp->m_Client.m_nViewEntity = nPlayerEntityIndex; ++m_nActiveSplitScreenUserCount; SetDisconnecting( nSlot, false ); ClientDLL_OnSplitScreenStateChanged(); return true; } bool CSplitScreen::RemoveSplitScreenUser( int nSlot, int nPlayerIndex ) { Assert( ThreadInMainThread() ); // Msg( "Detached %d from slot %d\n", nPlayerIndex, nSlot ); int idx = FindSplitPlayerSlot( nPlayerIndex ); if ( idx != -1 ) { SplitPlayer_t *sp = m_SplitScreenPlayers[ idx ]; if ( sp->m_Client.m_NetChannel ) { GetBaseLocalClient().m_NetChannel->DetachSplitPlayer( idx ); sp->m_Client.m_NetChannel->Shutdown( "RemoveSplitScreenUser" ); sp->m_Client.m_NetChannel = NULL; } sp->m_Client.m_nPlayerSlot = -1; sp->m_bActive = false; SetDisconnecting( nSlot, true ); --m_nActiveSplitScreenUserCount; ClientDLL_OnSplitScreenStateChanged(); } return true; } int CSplitScreen::GetActiveSplitScreenPlayerSlot() { #if !defined( SPLIT_SCREEN_STUBS ) SplitSlot_t *pSlot = GetSplitSlot(); int nSlot = pSlot->m_nActiveSplitScreenPlayer; #if defined( _DEBUG ) if ( nSlot >= host_state.max_splitscreen_players_clientdll ) { static bool warned = false; if ( !warned ) { warned = true; Warning( "GetActiveSplitScreenPlayerSlot() returning bogus slot #%d\n", nSlot ); } } #endif return nSlot; #else return 0; #endif } int CSplitScreen::SetActiveSplitScreenPlayerSlot( int slot ) { #if !defined( SPLIT_SCREEN_STUBS ) Assert( m_bInitialized ); slot = clamp( slot, 0, host_state.max_splitscreen_players_clientdll - 1 ); SplitSlot_t *pSlot = GetSplitSlot(); Assert( pSlot ); int old = pSlot->m_nActiveSplitScreenPlayer; if ( slot == old ) return slot; pSlot->m_nActiveSplitScreenPlayer = slot; // Only change netchannel in main thread and only change vgui message context id in main thread (for now) if ( pSlot->m_bMainThread ) { if ( m_SplitScreenPlayers[ slot ] && m_SplitScreenPlayers[ 0 ] ) { INetChannel *nc = m_SplitScreenPlayers[ slot ]->m_Client.m_NetChannel; CBaseClientState &bcs = m_SplitScreenPlayers[ 0 ]->m_Client; if ( bcs.m_NetChannel && nc ) { bcs.m_NetChannel->SetActiveChannel( nc ); } } } return old; #else return 0; #endif } int CSplitScreen::GetNumSplitScreenPlayers() { return m_nActiveSplitScreenUserCount; } int CSplitScreen::GetSplitScreenPlayerEntity( int nSlot ) { Assert( nSlot >= 0 && nSlot < host_state.max_splitscreen_players ); Assert( host_state.max_splitscreen_players <= MAX_SPLITSCREEN_CLIENTS ); if ( nSlot < 0 || nSlot >= host_state.max_splitscreen_players ) return -1; if ( !m_SplitScreenPlayers[ nSlot ]->m_bActive ) return -1; return m_SplitScreenPlayers[ nSlot ]->m_Client.m_nPlayerSlot + 1; } INetChannel *CSplitScreen::GetSplitScreenPlayerNetChan( int nSlot ) { Assert( nSlot >= 0 && nSlot < host_state.max_splitscreen_players ); Assert( host_state.max_splitscreen_players <= MAX_SPLITSCREEN_CLIENTS ); if ( nSlot < 0 || nSlot >= host_state.max_splitscreen_players ) return NULL; if ( !m_SplitScreenPlayers[ nSlot ]->m_bActive ) return NULL; return m_SplitScreenPlayers[ nSlot ]->m_Client.m_NetChannel; } bool CSplitScreen::IsValidSplitScreenSlot( int nSlot ) { Assert( host_state.max_splitscreen_players <= MAX_SPLITSCREEN_CLIENTS ); if ( nSlot < 0 || nSlot >= host_state.max_splitscreen_players ) return false; return m_SplitScreenPlayers[ nSlot ]->m_bActive; } int CSplitScreen::FirstValidSplitScreenSlot() { return 0; } int CSplitScreen::NextValidSplitScreenSlot( int nPreviousSlot ) { for ( ;; ) { ++nPreviousSlot; if ( nPreviousSlot >= host_state.max_splitscreen_players ) { return -1; } if ( m_SplitScreenPlayers[ nPreviousSlot ]->m_bActive ) { break; } } return nPreviousSlot; } int CSplitScreen::FindSplitPlayerSlot( int nPlayerEntityIndex ) { int nPlayerSlot = nPlayerEntityIndex - 1; Assert( host_state.max_splitscreen_players <= MAX_SPLITSCREEN_CLIENTS ); for ( int i = 1 ; i < host_state.max_splitscreen_players ; ++i ) { if ( m_SplitScreenPlayers[ i ]->m_Client.m_nPlayerSlot == nPlayerSlot ) { return i; } } return -1; } bool CSplitScreen::IsDisconnecting( int nSlot ) { Assert( nSlot >= 0 && nSlot < host_state.max_splitscreen_players ); Assert( host_state.max_splitscreen_players <= MAX_SPLITSCREEN_CLIENTS ); if ( nSlot < 0 || nSlot >= host_state.max_splitscreen_players ) return false; return ( m_SplitScreenPlayers[ nSlot ]->m_Client.m_nSignonState == SIGNONSTATE_NONE ) ? true : false; } void CSplitScreen::SetDisconnecting( int nSlot, bool bState ) { Assert( nSlot >= 0 && nSlot < host_state.max_splitscreen_players ); Assert( host_state.max_splitscreen_players <= MAX_SPLITSCREEN_CLIENTS ); if ( nSlot < 0 || nSlot >= host_state.max_splitscreen_players ) return; Assert( nSlot != 0 ); m_SplitScreenPlayers[ nSlot ]->m_Client.m_nSignonState = bState ? SIGNONSTATE_NONE : SIGNONSTATE_FULL; } CClientState &CSplitScreen::GetLocalPlayer( int nSlot /*= -1*/ ) { if ( nSlot == -1 ) { Assert( IsLocalPlayerResolvable() ); return m_SplitScreenPlayers[ GetActiveSplitScreenPlayerSlot() ]->m_Client; } return m_SplitScreenPlayers[ nSlot ]->m_Client; } bool CSplitScreen::SetLocalPlayerIsResolvable( char const *pchContext, int line, bool bResolvable ) { SplitSlot_t *pSlot = GetSplitSlot(); Assert( pSlot ); bool bPrev = pSlot->m_bLocalPlayerResolvable; pSlot->m_bLocalPlayerResolvable = bResolvable; return bPrev; } bool CSplitScreen::IsLocalPlayerResolvable() { #if defined( SPLIT_SCREEN_STUBS ) return true; #else SplitSlot_t *pSlot = GetSplitSlot(); return pSlot->m_bLocalPlayerResolvable; #endif } // Singleton client state CClientState &GetLocalClient( int nSlot /*= -1*/ ) { return g_SplitScreenMgr.GetLocalPlayer( nSlot ); } CClientState &GetBaseLocalClient() { return g_SplitScreenMgr.GetLocalPlayer( 0 ); }
26.787589
164
0.733428
DannyParker0001
7797a2841cc2e2f774a2a6567c322c089c125f9e
937
cpp
C++
basic/math/find_missing_numbers.cpp
sanjosh/smallprogs
8acf7a357080b9154b55565be7c7667db0d4049b
[ "Apache-2.0" ]
7
2017-02-28T06:33:43.000Z
2021-12-17T04:58:19.000Z
basic/math/find_missing_numbers.cpp
sanjosh/smallprogs
8acf7a357080b9154b55565be7c7667db0d4049b
[ "Apache-2.0" ]
null
null
null
basic/math/find_missing_numbers.cpp
sanjosh/smallprogs
8acf7a357080b9154b55565be7c7667db0d4049b
[ "Apache-2.0" ]
3
2017-02-28T06:33:30.000Z
2021-02-25T09:42:31.000Z
/* Missing numbers ------------------ # One missing Approach 1 : sum approach 2 : XOR Assume a1 ^ a2 ^ a3 ^ …^ an = A and a1 ^ a2 ^ a3 ^ …^ an-1 = B Then A ^ B = an Approach 3 : a[a[i]] = 1 ------------------ # Two missing Approach 1 sum and avg (statistical) sum of array, avg of array - compare with sum and avg of (1..n) one missing will be less than avg Approach 2 XOR XOR of all elem with (1..n) Bit is set in result only if corresponding bits are different https://www.geeksforgeeks.org/find-two-missing-numbers-set-2-xor-based-solution/?ref=rp https://www.geeksforgeeks.org/find-two-missing-numbers-set-1-an-interesting-linear-time-solution/ ------------------ # Four missing indicator array use combinatiorial design (sum of any k = find missing sum) https://www.geeksforgeeks.org/find-four-missing-numbers-array-containing-elements-1-n/?ref=rp compute newton sums Muthukrishnan : data streams and algo */
18.74
97
0.67556
sanjosh
7798421161971d4c29008ced6e9b718cfc0ff5ca
679
cpp
C++
day06/part2.cpp
Moremar/advent_of_code_2016
dea264671fc2c31baa42b1282751dfd1ae071a7d
[ "Apache-2.0" ]
null
null
null
day06/part2.cpp
Moremar/advent_of_code_2016
dea264671fc2c31baa42b1282751dfd1ae071a7d
[ "Apache-2.0" ]
null
null
null
day06/part2.cpp
Moremar/advent_of_code_2016
dea264671fc2c31baa42b1282751dfd1ae071a7d
[ "Apache-2.0" ]
null
null
null
#include "part1.hpp" #include "part2.hpp" using namespace std; string Part2::solve(const vector<string> &signals) { vector<map<char, int>> freqs = Part1::getFreqs(signals); // pick the least popular letter for each position string corrected = ""; for (const auto freq : freqs) { vector<pair<char, int>> toSort(freq.cbegin(), freq.cend()); // sort in the opposite order from part 1 sort(toSort.begin(), toSort.end(), [](pair<char, int> v1, pair<char, int> v2) { return (v1.second < v2.second) || (v1.second == v2.second && v1.first > v2.first); }); corrected += toSort[0].first; } return corrected; }
32.333333
94
0.60972
Moremar
7799a55d53c8ef71110728812322ddeb84cd0ec8
1,910
hpp
C++
SpaceWars2/skills/Laser.hpp
su8ru/SpaceWars2
1aa9ecd7ab8217ae5df8c6499597c8cbc7ab9f40
[ "Apache-2.0" ]
2
2020-02-01T08:47:10.000Z
2020-02-01T08:51:05.000Z
SpaceWars2/skills/Laser.hpp
subaru2003/SpaceWars2
1aa9ecd7ab8217ae5df8c6499597c8cbc7ab9f40
[ "Apache-2.0" ]
44
2019-06-03T11:46:56.000Z
2019-08-06T16:20:15.000Z
SpaceWars2/skills/Laser.hpp
su8ru/SpaceWars2
1aa9ecd7ab8217ae5df8c6499597c8cbc7ab9f40
[ "Apache-2.0" ]
3
2019-06-13T17:42:12.000Z
2019-06-14T23:36:45.000Z
#pragma once #include <Siv3D.hpp> #include "Bullet.hpp" #include "../Scenes/Game.hpp" class Laser final : public Bullet { private: bool isCharging = true; int energy = 1; Vec2 myPos; bool isLeft; bool isLInvalid = false; bool isRInvalid = false; static bool isLShooting; static bool isRShooting; static Optional<Sound> chargeSound[2]; static Optional<Sound> laserSound[2]; const static int CHARGE_TIME_LIMIT = 1000; // charge時間の上限 const static int WAITING_TIME = 100; // 実行までにかかるwaiting時間 const static int COOLDOWN_TIME = 1000; // 実行後のクールダウン時間(要検討) RectF getShapeShotten(){ if(isLeft) return RectF(myPos - Vec2(0, energy), Config::WIDTH, energy * 2); else return RectF(myPos - Vec2(Config::WIDTH, energy), Config::WIDTH, energy * 2); } Circle getShapeCharging(){ if(isLeft) return Circle(myPos + Vec2( 25 + energy, 0), energy); else return Circle(myPos + Vec2(-25 - energy, 0), energy); } public: Laser(Vec2 _pos, bool _isLeft) : Bullet(_pos, _isLeft) { isLeft = _isLeft; if (isLeft ? isLShooting : isRShooting) { // if another instance is already created and still alive... (isLeft ? isLInvalid : isRInvalid) = true; // this laser is disabled } else { (isLeft ? isLShooting : isRShooting) = true; ++(isLeft ? Data::LPlayer : Data::RPlayer).mainSkillCnt; if (!chargeSound[0]) { for (int i = 0; i < 2; i++ ) { chargeSound[i].emplace(L"/8203"); laserSound[i].emplace(L"/8204"); } } chargeSound[isLeft]->setVolume(Config::MASTER_VOLUME * Config::CURSOR_VOLUME); chargeSound[isLeft]->play(); } } ~Laser() override { if (!(isLeft ? isLInvalid : isRInvalid)) (isLeft ? isLShooting : isRShooting) = false; laserSound[isLeft]->stop(1s); }; bool update(Vec2 _myPos, Vec2 _oppPos) override; void draw() override; bool isVisible() override; int getDamage(Circle _circle) override; const static int bulletSpeed = 10; };
28.507463
104
0.68534
su8ru
779a7d4470804b9abcde7bb29dd24179ad47b79d
1,112
hpp
C++
contrib/autoboost/autoboost/context/fcontext.hpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
87
2015-01-18T00:43:06.000Z
2022-02-11T17:40:50.000Z
contrib/autoboost/autoboost/context/fcontext.hpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
274
2015-01-03T04:50:49.000Z
2021-03-08T09:01:09.000Z
contrib/autoboost/autoboost/context/fcontext.hpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
15
2015-09-30T20:58:43.000Z
2020-12-19T21:24:56.000Z
// Copyright Oliver Kowalke 2009. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef AUTOBOOST_CONTEXT_FCONTEXT_H #define AUTOBOOST_CONTEXT_FCONTEXT_H #if defined(__PGI) #include <stdint.h> #endif #if defined(_WIN32_WCE) typedef int intptr_t; #endif #include <autoboost/config.hpp> #include <autoboost/cstdint.hpp> #include <autoboost/context/detail/config.hpp> #ifdef AUTOBOOST_HAS_ABI_HEADERS # include AUTOBOOST_ABI_PREFIX #endif namespace autoboost { namespace context { typedef void* fcontext_t; extern "C" AUTOBOOST_CONTEXT_DECL intptr_t AUTOBOOST_CONTEXT_CALLDECL jump_fcontext( fcontext_t * ofc, fcontext_t nfc, intptr_t vp, bool preserve_fpu = true); extern "C" AUTOBOOST_CONTEXT_DECL fcontext_t AUTOBOOST_CONTEXT_CALLDECL make_fcontext( void * sp, std::size_t size, void (* fn)( intptr_t) ); }} #ifdef AUTOBOOST_HAS_ABI_HEADERS # include AUTOBOOST_ABI_SUFFIX #endif #endif // AUTOBOOST_CONTEXT_FCONTEXT_H
24.173913
107
0.747302
CaseyCarter
779affb1bcfd059a3db12a0761b89a2d0e0b41e6
298
cpp
C++
src/swimport/tests/49_arrays/src.cpp
talos-gis/swimport
e8f0fcf02b0c9751b199f750f1f8bc57c8ff54b3
[ "MIT" ]
1
2019-03-07T20:43:42.000Z
2019-03-07T20:43:42.000Z
src/swimport/tests/49_arrays/src.cpp
talos-gis/swimport
e8f0fcf02b0c9751b199f750f1f8bc57c8ff54b3
[ "MIT" ]
null
null
null
src/swimport/tests/49_arrays/src.cpp
talos-gis/swimport
e8f0fcf02b0c9751b199f750f1f8bc57c8ff54b3
[ "MIT" ]
null
null
null
#include "src.h" std::array<int,10> primes(){ return {2,3,5,7,11,13,17,19,23,29}; } std::array<std::pair<int,int>, 3> zip(std::array<int,3> a, std::array<int,3> b){ return { std::make_pair(a[0], b[0]), std::make_pair(a[1], b[1]), std::make_pair(a[2], b[2]) }; }
24.833333
80
0.526846
talos-gis
77a0048f0fe674428e66ebd07ce03d67b0051e93
970
hpp
C++
src/afk/renderer/Model.hpp
christocs/ModelAnimation
d32941dec8f2ef54e96086319a00ca5cf783e2fa
[ "0BSD" ]
null
null
null
src/afk/renderer/Model.hpp
christocs/ModelAnimation
d32941dec8f2ef54e96086319a00ca5cf783e2fa
[ "0BSD" ]
null
null
null
src/afk/renderer/Model.hpp
christocs/ModelAnimation
d32941dec8f2ef54e96086319a00ca5cf783e2fa
[ "0BSD" ]
null
null
null
#pragma once #include <filesystem> #include <glob.h> #include <vector> #include <assimp/scene.h> #include "afk/renderer/Animation.hpp" #include "afk/renderer/Bone.hpp" #include "afk/renderer/Mesh.hpp" #include "afk/renderer/ModelNode.hpp" #include "afk/renderer/Texture.hpp" namespace Afk { struct Model { using Meshes = std::vector<Mesh>; using Nodes = std::vector<ModelNode>; using NodeMap = std::unordered_map<std::string, unsigned int>; using Animations = std::unordered_map<std::string, Animation>; Nodes nodes = {}; NodeMap node_map = {}; Animations animations = {}; Meshes meshes = {}; Bones bones = {}; BoneStringMap bone_map = {}; glm::mat4 global_inverse; size_t root_node_index = 0; std::filesystem::path file_path = {}; std::filesystem::path file_dir = {}; Model() = default; Model(const std::filesystem::path &_file_path); }; }
23.658537
69
0.630928
christocs
77a095bceba23eb22b7c337086cacc6130a19a8d
2,177
cc
C++
history_gtest.cc
doj/few
cdaa53b08f73a901cd07022b92e20f02e9b7b91b
[ "MIT" ]
2
2015-04-05T20:15:31.000Z
2021-07-14T19:36:03.000Z
history_gtest.cc
doj/few
cdaa53b08f73a901cd07022b92e20f02e9b7b91b
[ "MIT" ]
null
null
null
history_gtest.cc
doj/few
cdaa53b08f73a901cd07022b92e20f02e9b7b91b
[ "MIT" ]
null
null
null
/* -*- mode: C++; c-basic-offset: 4; tab-width: 8; -*- * vi: set shiftwidth=4 tabstop=8: * :indentSize=4:tabSize=8: */ #include "gtest/gtest.h" #include "history.h" #if defined(_WIN32) #include <io.h> #include <stdio.h> namespace { int unlink(const std::string& fn) { return _unlink(fn.c_str()); } int unlink(const std::wstring& fn) { return _wunlink(fn.c_str()); } } #else #include <unistd.h> #endif TEST(History, can_cycle_through_history) { auto h = std::make_shared<History>(); const std::string eins = "1"; h->add(eins); const std::string zwei = "2"; h->add(zwei); const std::string drei = "3"; h->add(drei); const std::string c = "c"; auto i = h->begin(c); ASSERT_TRUE(i->atEnd()); ASSERT_EQ(c, i->next()); ASSERT_EQ(c, i->next()); ASSERT_TRUE(i->atEnd()); ASSERT_EQ(drei, i->prev()); ASSERT_FALSE(i->atEnd()); ASSERT_EQ(zwei, i->prev()); ASSERT_EQ(eins, i->prev()); ASSERT_EQ(eins, i->prev()); ASSERT_EQ(eins, i->prev()); ASSERT_FALSE(i->atEnd()); ASSERT_EQ(zwei, i->next()); ASSERT_EQ(drei, i->next()); ASSERT_EQ(c, i->next()); ASSERT_TRUE(i->atEnd()); ASSERT_EQ(c, i->next()); ASSERT_TRUE(i->atEnd()); } TEST(History, can_save_and_load) { const std::string filename = "history.test"; unlink(filename.c_str()); auto h = std::make_shared<History>(filename); const std::string eins = "1"; h->add(eins); const std::string zwei = "2"; h->add(zwei); const std::string drei = "3"; h->add(drei); h = nullptr; h = std::make_shared<History>(filename); auto i = h->begin(""); ASSERT_EQ(drei, i->prev()); ASSERT_EQ(zwei, i->prev()); ASSERT_EQ(eins, i->prev()); auto fn = h->filename(); h = nullptr; i = nullptr; ASSERT_EQ(0, unlink(fn.c_str())); } TEST(History, empty_history_only_returns_initial_iterator_value) { auto h = std::make_shared<History>(); const std::string s = "s"; auto i = h->begin(s); ASSERT_EQ(s, i->prev()); ASSERT_EQ(s, i->prev()); ASSERT_EQ(s, i->next()); ASSERT_EQ(s, i->prev()); ASSERT_TRUE(i->atEnd()); }
22.915789
64
0.582912
doj
77a2348dafc26ce71fc4ba976e5697322317c65e
2,067
cpp
C++
src/draw/ArcProgress.cpp
charanyaarvind/StratifyAPI
adfd1bc8354489378d53c6acd77ebedad5790b4f
[ "BSD-3-Clause" ]
null
null
null
src/draw/ArcProgress.cpp
charanyaarvind/StratifyAPI
adfd1bc8354489378d53c6acd77ebedad5790b4f
[ "BSD-3-Clause" ]
null
null
null
src/draw/ArcProgress.cpp
charanyaarvind/StratifyAPI
adfd1bc8354489378d53c6acd77ebedad5790b4f
[ "BSD-3-Clause" ]
null
null
null
/*! \file */ //Copyright 2011-2018 Tyler Gilbert; All Rights Reserved #include <cmath> #include "sgfx.hpp" #include "draw/ArcProgress.hpp" using namespace draw; ArcProgress::ArcProgress() { m_offset = 0; m_direction = 1; } void ArcProgress::draw_to_scale(const DrawingScaledAttr & attr){ //draw the progress bar on the bitmap with x, y at the top left corner sg_point_t p = attr.point(); Dim d = attr.dim(); sg_region_t bounds; s8 dir; float xf, yf; float xf_inner, yf_inner; Point center(p.x + d.width()/2, p.y + d.height()/2); sg_size_t rx = d.width()/2; sg_size_t ry = d.height()/2; sg_size_t rx_inner = rx*2/3; sg_size_t ry_inner = ry*2/3; Point arc; Point arc_inner; Point first_point; u32 i; sg_int_t x_max; u32 progress; u32 points = 4 * (d.width() + d.height())/2; float two_pi = 2.0 * M_PI; float half_pi = M_PI / 2.0; float theta; float offset = m_offset * two_pi / 360; progress = (points * value()) / max(); if( progress > points ){ progress = points; } if( m_direction > 0 ){ dir = 1; } else { dir = -1; } x_max = 0; i = 0; do { theta = (two_pi * i*dir / points - half_pi) + offset; xf = rx * cosf(theta); yf = ry * sinf(theta); xf_inner = rx_inner * cosf(theta); yf_inner = ry_inner * sinf(theta); arc.set(xf, yf); arc = arc + center; if( arc.x() > x_max ){ x_max = arc.x(); } arc_inner.set(xf_inner, yf_inner); arc_inner = arc_inner + center; if( i == 0 ){ attr.bitmap().draw_line(arc_inner, arc); } if( i == 1 ){ first_point = arc; } attr.bitmap().draw_pixel(arc); attr.bitmap().draw_pixel(arc_inner); i++; } while( i < progress ); attr.bitmap().draw_line(arc_inner, arc); if( progress > 0 && (attr.bitmap().pen_flags() & Pen::FLAG_IS_FILL) ){ theta = (two_pi * progress / (2*points) - half_pi) + offset; xf = ((rx + rx_inner)/2) * cosf(theta); yf = ((ry + ry_inner)/2)* sinf(theta); arc.set(xf, yf); arc = arc + center; bounds = attr.region(); //attr.bitmap().draw_pixel(arc); attr.bitmap().draw_pour(arc, bounds); } }
19.5
71
0.62119
charanyaarvind
77aa54d0679caf80d7343fbd65cd3b94af1a8b13
3,063
cpp
C++
src/oems/oems_sorter.cpp
ref2401/oems
00a295d01280211c3298ddacda0e0937471917ab
[ "MIT" ]
3
2019-12-10T05:53:40.000Z
2021-09-13T17:54:30.000Z
src/oems/oems_sorter.cpp
ref2401/oems
00a295d01280211c3298ddacda0e0937471917ab
[ "MIT" ]
1
2017-10-23T12:12:22.000Z
2017-10-23T12:12:22.000Z
src/oems/oems_sorter.cpp
ref2401/oems
00a295d01280211c3298ddacda0e0937471917ab
[ "MIT" ]
null
null
null
#include "oems/oems_sorter.h" #include <cassert> namespace { using namespace oems; void copy_data_from_gpu(ID3D11Device* p_device, ID3D11DeviceContext* p_ctx, ID3D11Buffer* p_buffer_src, float* p_dest, size_t byte_count) { assert(p_device); assert(p_ctx); assert(p_buffer_src); assert(p_dest); assert(byte_count > 0); const UINT bc = UINT(byte_count); assert(size_t(bc) == byte_count); // create stagint buffer and fill it with p_buffer_src's contents --- com_ptr<ID3D11Buffer >p_buffer_staging = make_buffer(p_device, bc, D3D11_USAGE_STAGING, 0, D3D11_CPU_ACCESS_READ); p_ctx->CopyResource(p_buffer_staging, p_buffer_src); // fill p_dest using the staging buffer --- D3D11_MAPPED_SUBRESOURCE map; HRESULT hr = p_ctx->Map(p_buffer_staging, 0, D3D11_MAP_READ, 0, &map); THROW_IF_DX_DEVICE_ERROR(hr, p_device); std::memcpy(p_dest, map.pData, byte_count); p_ctx->Unmap(p_buffer_staging, 0); } com_ptr<ID3D11Buffer> copy_data_to_gpu(ID3D11Device* p_device, const float* p_list, size_t byte_count) { assert(p_device); assert(p_list); assert(byte_count > 0); const UINT bc = UINT(byte_count); assert(size_t(bc) == byte_count); const D3D11_SUBRESOURCE_DATA data = { p_list, 0, 0 }; return make_buffer(p_device, &data, bc, D3D11_USAGE_DEFAULT, D3D11_BIND_UNORDERED_ACCESS); } } // namespace namespace oems { // ---- oems_sorter ---- oems_sorter::oems_sorter(ID3D11Device* p_device, ID3D11DeviceContext* p_ctx, ID3D11Debug* p_debug) : p_device_(p_device), p_ctx_(p_ctx), p_debug_(p_debug) { assert(p_device); assert(p_ctx); assert(p_debug); // p_debug == nullptr in Release mode. oems_shader_ = hlsl_compute(p_device, "../../data/oems.compute.hlsl"); } void oems_sorter::sort(std::vector<float>& list) { assert(list.size() > 4); const size_t byte_count = sizeof(float) * list.size(); const UINT item_count = UINT(list.size()); // copy list to the gpu & set uav --- com_ptr<ID3D11Buffer> p_buffer = copy_data_to_gpu(p_device_, list.data(), byte_count); com_ptr<ID3D11UnorderedAccessView> p_buffer_uav; D3D11_UNORDERED_ACCESS_VIEW_DESC uav_desc = {}; uav_desc.Format = DXGI_FORMAT_R32_FLOAT; uav_desc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER; uav_desc.Buffer.FirstElement = 0; uav_desc.Buffer.NumElements = item_count; HRESULT hr = p_device_->CreateUnorderedAccessView(p_buffer.ptr, &uav_desc, &p_buffer_uav.ptr); THROW_IF_DX_ERROR(hr); // (sort) setup compute pipeline & dispatch work --- p_ctx_->CSSetShader(oems_shader_.p_shader, nullptr, 0); p_ctx_->CSSetUnorderedAccessViews(0, 1, &p_buffer_uav.ptr, nullptr); #ifdef OEMS_DEBUG hr = p_debug_->ValidateContextForDispatch(p_ctx_); THROW_IF_DX_ERROR(hr); #endif p_ctx_->Dispatch(1, 1, 1); ID3D11UnorderedAccessView* uav_list[1] = { nullptr }; p_ctx_->CSSetUnorderedAccessViews(0, 1, uav_list, nullptr); // copy list from the gpu --- copy_data_from_gpu(p_device_, p_ctx_, p_buffer, list.data(), byte_count); } } // namespace oems
29.737864
103
0.726086
ref2401
77aab3eb1a087416cb39ea09c17f09dddb587c5e
993
cpp
C++
CCO/CCO_96_P5_All_Roads_Lead_Where.cpp
Togohogo1/pg
ee3c36acde47769c66ee13a227762ee677591375
[ "MIT" ]
null
null
null
CCO/CCO_96_P5_All_Roads_Lead_Where.cpp
Togohogo1/pg
ee3c36acde47769c66ee13a227762ee677591375
[ "MIT" ]
1
2021-10-14T18:26:56.000Z
2021-10-14T18:26:56.000Z
CCO/CCO_96_P5_All_Roads_Lead_Where.cpp
Togohogo1/pg
ee3c36acde47769c66ee13a227762ee677591375
[ "MIT" ]
1
2021-08-06T03:39:55.000Z
2021-08-06T03:39:55.000Z
#include <bits/stdc++.h> using namespace std; const int M = 1002; int n, m, a, b, vis[M], pre[M]; string A, B; vector<int> adj[M]; void dfs(int st) { vis[st] = true; for (int i : adj[st]) { if (!vis[i]) { pre[i] = st; dfs(i); } } } string find(int st, int ed) { int tmp = st; string path = ""; path += (char)tmp; while (tmp != ed) { int ntmp = pre[tmp]; path += (char)ntmp; tmp = ntmp; } return path; } int main() { ios::sync_with_stdio(0); cin.tie(0), cout.tie(0); cin >> m >> n; for (int i = 0; i < m; i++) { cin >> A >> B; int a = A.front(); int b = B.front(); adj[a].push_back(b); adj[b].push_back(a); } for (int i = 0; i < n; i++) { cin >> A >> B; int a = A.front(); int b = B.front(); dfs(b); cout << find(a, b) << '\n'; memset(vis, 0, sizeof(vis)); } }
15.515625
36
0.414904
Togohogo1
77acf87696718a89aa33813c79f6336f94a157d4
508
hpp
C++
src/ir/nodes.hpp
traplol/malang
3c02f4f483b7580a557841c31a65bf190fd1228f
[ "MIT" ]
4
2017-10-31T14:01:58.000Z
2019-07-16T04:53:32.000Z
src/ir/nodes.hpp
traplol/malang
3c02f4f483b7580a557841c31a65bf190fd1228f
[ "MIT" ]
null
null
null
src/ir/nodes.hpp
traplol/malang
3c02f4f483b7580a557841c31a65bf190fd1228f
[ "MIT" ]
2
2018-01-23T12:59:07.000Z
2019-07-16T04:53:39.000Z
#ifndef MALANG_IR_NODES_HPP #define MALANG_IR_NODES_HPP #include "ir.hpp" #include "ir_noop.hpp" #include "ir_block.hpp" #include "ir_assignment.hpp" #include "ir_binary_ops.hpp" #include "ir_branch.hpp" #include "ir_call.hpp" #include "ir_label.hpp" #include "ir_memory.hpp" #include "ir_primitives.hpp" #include "ir_return.hpp" #include "ir_symbol.hpp" #include "ir_unary_ops.hpp" #include "ir_values.hpp" #include "ir_discard_result.hpp" #include "ir_member_access.hpp" #endif /* MALANG_IR_NODES_HPP */
23.090909
32
0.777559
traplol
77bee52477c3f9529bafa7fafcfe5311d8d08699
5,391
cpp
C++
tests/unit/offload/OffloadFreeListTest.cpp
gjerecze/daqdb
ebab10f3ef2a64d541043b7378a951af294d44cb
[ "Apache-2.0" ]
22
2019-02-08T17:23:12.000Z
2021-10-12T06:35:37.000Z
tests/unit/offload/OffloadFreeListTest.cpp
gjerecze/daqdb
ebab10f3ef2a64d541043b7378a951af294d44cb
[ "Apache-2.0" ]
8
2019-02-11T06:30:47.000Z
2020-04-22T09:49:44.000Z
tests/unit/offload/OffloadFreeListTest.cpp
gjerecze/daqdb
ebab10f3ef2a64d541043b7378a951af294d44cb
[ "Apache-2.0" ]
10
2019-02-11T10:26:52.000Z
2019-09-16T20:49:25.000Z
/** * Copyright (c) 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cstdint> #include "../../lib/offload/OffloadFreeList.cpp" #include "../../lib/pmem/RTree.h" #define BOOST_TEST_MAIN #include <boost/filesystem.hpp> #include <boost/test/unit_test.hpp> #include <fakeit.hpp> namespace ut = boost::unit_test; using namespace fakeit; #define BOOST_TEST_DETECT_MEMORY_LEAK 1 #define TEST_POOL_FREELIST_FILENAME "test_file.pm" #define TEST_POOL_FREELIST_SIZE 10ULL * 1024 * 1024 #define LAYOUT "queue" #define CREATE_MODE_RW (S_IWUSR | S_IRUSR) #define FREELIST_MAX_LBA 512 pool<DaqDB::OffloadFreeList> *g_offloadFreeList = nullptr; bool txAbortPred(const pmem::manual_tx_abort &ex) { return true; } struct OffloadFreeListGlobalFixture { OffloadFreeListGlobalFixture() { if (boost::filesystem::exists(TEST_POOL_FREELIST_FILENAME)) boost::filesystem::remove(TEST_POOL_FREELIST_FILENAME); offloadFreeList = pool<DaqDB::OffloadFreeList>::create( TEST_POOL_FREELIST_FILENAME, LAYOUT, TEST_POOL_FREELIST_SIZE, CREATE_MODE_RW); g_offloadFreeList = &offloadFreeList; } ~OffloadFreeListGlobalFixture() { if (boost::filesystem::exists(TEST_POOL_FREELIST_FILENAME)) boost::filesystem::remove(TEST_POOL_FREELIST_FILENAME); } pool<DaqDB::OffloadFreeList> offloadFreeList; }; BOOST_GLOBAL_FIXTURE(OffloadFreeListGlobalFixture); struct OffloadFreeListTestFixture { OffloadFreeListTestFixture() { freeLbaList = g_offloadFreeList->get_root().get(); } ~OffloadFreeListTestFixture() { if (freeLbaList != nullptr) freeLbaList->clear(*g_offloadFreeList); freeLbaList->maxLba = 0; } DaqDB::OffloadFreeList *freeLbaList = nullptr; }; BOOST_FIXTURE_TEST_CASE(GetLbaInit, OffloadFreeListTestFixture) { freeLbaList->push(*g_offloadFreeList, -1); freeLbaList->maxLba = FREELIST_MAX_LBA; auto firstLBA = freeLbaList->get(*g_offloadFreeList); BOOST_CHECK_EQUAL(firstLBA, 1); } BOOST_FIXTURE_TEST_CASE(GetLbaInitPhase, OffloadFreeListTestFixture) { freeLbaList->push(*g_offloadFreeList, -1); freeLbaList->maxLba = FREELIST_MAX_LBA; const int lbaCount = 100; uint8_t index; long lba = 0; for (index = 0; index < lbaCount; index++) lba = freeLbaList->get(*g_offloadFreeList); BOOST_CHECK_EQUAL(lba, lbaCount); } BOOST_FIXTURE_TEST_CASE(GetLbaAfterInit_MaxLba_NotSet, OffloadFreeListTestFixture) { freeLbaList->push(*g_offloadFreeList, -1); BOOST_CHECK_EXCEPTION(freeLbaList->get(*g_offloadFreeList), pmem::manual_tx_abort, txAbortPred); } BOOST_FIXTURE_TEST_CASE(GetLastInitLba, OffloadFreeListTestFixture) { freeLbaList->push(*g_offloadFreeList, -1); freeLbaList->maxLba = FREELIST_MAX_LBA; long lba = 0; unsigned int index; for (index = 0; index < FREELIST_MAX_LBA - 1; index++) lba = freeLbaList->get(*g_offloadFreeList); BOOST_CHECK_EQUAL(lba, index); } BOOST_FIXTURE_TEST_CASE(GetLbaAfterInit_FirstLba, OffloadFreeListTestFixture) { freeLbaList->push(*g_offloadFreeList, -1); freeLbaList->maxLba = FREELIST_MAX_LBA; long lba = 0; unsigned int index; for (index = 0; index < FREELIST_MAX_LBA; index++) lba = freeLbaList->get(*g_offloadFreeList); BOOST_CHECK_EQUAL(lba, 0); } BOOST_FIXTURE_TEST_CASE(GetLbaAfterInit_CheckRemoved, OffloadFreeListTestFixture) { freeLbaList->push(*g_offloadFreeList, -1); freeLbaList->maxLba = FREELIST_MAX_LBA; const long freeElementLba = 100; long lba = 0; unsigned int index; for (index = 0; index < FREELIST_MAX_LBA; index++) lba = freeLbaList->get(*g_offloadFreeList); freeLbaList->push(*g_offloadFreeList, freeElementLba); lba = freeLbaList->get(*g_offloadFreeList); BOOST_CHECK_EQUAL(lba, freeElementLba); freeLbaList->push(*g_offloadFreeList, freeElementLba + 1); lba = freeLbaList->get(*g_offloadFreeList); BOOST_CHECK_EQUAL(lba, freeElementLba + 1); freeLbaList->push(*g_offloadFreeList, freeElementLba); freeLbaList->push(*g_offloadFreeList, freeElementLba + 1); lba = freeLbaList->get(*g_offloadFreeList); BOOST_CHECK_EQUAL(lba, freeElementLba); lba = freeLbaList->get(*g_offloadFreeList); BOOST_CHECK_EQUAL(lba, freeElementLba + 1); } BOOST_FIXTURE_TEST_CASE(GetLbaAfterInit_FullDisk, OffloadFreeListTestFixture) { freeLbaList->push(*g_offloadFreeList, -1); freeLbaList->maxLba = FREELIST_MAX_LBA; unsigned int index; for (index = 0; index < FREELIST_MAX_LBA; index++) freeLbaList->get(*g_offloadFreeList); BOOST_CHECK_EXCEPTION(freeLbaList->get(*g_offloadFreeList), pmem::manual_tx_abort, txAbortPred); }
32.089286
79
0.717863
gjerecze
77c45786ebad0c4226a9b75c4b4b03d15bb5af98
8,572
cpp
C++
TerrainEffects/RoadEffect.cpp
GuMiner/agow
b8665d5879f43a6bcb6e878827b3b25af9cc1b1d
[ "MIT" ]
null
null
null
TerrainEffects/RoadEffect.cpp
GuMiner/agow
b8665d5879f43a6bcb6e878827b3b25af9cc1b1d
[ "MIT" ]
null
null
null
TerrainEffects/RoadEffect.cpp
GuMiner/agow
b8665d5879f43a6bcb6e878827b3b25af9cc1b1d
[ "MIT" ]
null
null
null
#include <glm\mat4x4.hpp> #include <glm\gtc\random.hpp> #include <SFML\System.hpp> #include <algorithm> #include "Generators\ColorGenerator.h" #include "logging\Logger.h" #include "RoadEffect.h" RoadStats RoadEffect::stats = RoadStats(); RoadEffect::RoadEffect() { } bool RoadEffect::LoadBasics(ShaderFactory* shaderManager) { if (!shaderManager->CreateShaderProgram("roadRender", &programId)) { Logger::LogError("Failed to load the road rendering shader; cannot continue."); return false; } projMatrixLocation = glGetUniformLocation(programId, "projMatrix"); mvMatrixLocation = glGetUniformLocation(programId, "mvMatrix"); return true; } bool RoadEffect::LoadEffect(glm::ivec2 subtileId, void** effectData, SubTile* tile) { bool hasRoadEffect = false; RoadEffectData* roadEffect = nullptr; // Scan the image for road pixels. int roadCounter = 1; const long ROAD_SUBCOUNT = 10; for (int i = 0; i < TerrainTile::SubtileSize; i++) { for (int j = 0; j < TerrainTile::SubtileSize; j++) { int pixelId = tile->GetPixelId(glm::ivec2(i, j)); if (tile->type[pixelId] == TerrainTypes::ROADS) { ++roadCounter; if (roadCounter % ROAD_SUBCOUNT == 0) { if (!hasRoadEffect) { hasRoadEffect = true; roadEffect = new RoadEffectData(tile); } float height = tile->heightmap[pixelId]; // TODO configurable glm::vec3 bottomColor = ColorGenerator::GetTravellerColor(); glm::vec3 topColor = ColorGenerator::GetTravellerColor() * 1.10f; glm::vec3 position = glm::vec3((float)i, (float)j, height + 0.1f); glm::vec2 velocity = glm::vec2(glm::linearRand(-1.0f, 1.0f), glm::linearRand(-1.0f, 1.0f)) * 1.0f; glm::vec3 endPosition = position + glm::normalize(glm::vec3(velocity.x, velocity.y, 0.0f)); // Add road travelers roadEffect->travellers.positions.push_back(position); roadEffect->travellers.positions.push_back(endPosition); roadEffect->travellers.colors.push_back(bottomColor); roadEffect->travellers.colors.push_back(topColor); roadEffect->positions.push_back(glm::vec2(position.x, position.y)); roadEffect->velocities.push_back(velocity); } } } } if (hasRoadEffect) { glGenVertexArrays(1, &roadEffect->vao); glBindVertexArray(roadEffect->vao); glGenBuffers(1, &roadEffect->positionBuffer); glGenBuffers(1, &roadEffect->colorBuffer); Logger::Log("Parsed ", roadEffect->travellers.positions.size() / 2, " road travellers."); roadEffect->travellers.TransferPositionToOpenGl(roadEffect->positionBuffer); roadEffect->travellers.TransferStaticColorToOpenGl(roadEffect->colorBuffer); *effectData = roadEffect; } return hasRoadEffect; } void RoadEffect::UnloadEffect(void* effectData) { RoadEffectData* roadEffect = (RoadEffectData*)effectData; glDeleteVertexArrays(1, &roadEffect->vao); glDeleteBuffers(1, &roadEffect->positionBuffer); glDeleteBuffers(1, &roadEffect->colorBuffer); delete roadEffect; } float RoadEffect::MoveTraveller(const glm::ivec2 subtileId, RoadEffectData* roadEffect, int i, float elapsedSeconds) { roadEffect->positions[i] += (roadEffect->velocities[i] * elapsedSeconds); // This logic causes a slight pause when a boundary is hit, which looks logical. bool hitEdgeBoundary = false; glm::ivec2 subTilePos = glm::ivec2(roadEffect->positions[i].x, roadEffect->positions[i].y); if (subTilePos.x < 0 || subTilePos.x >= TerrainTile::SubtileSize) { roadEffect->positions[i] -= (roadEffect->velocities[i] * elapsedSeconds); roadEffect->velocities[i].x *= -1.0f; hitEdgeBoundary = true; } if (subTilePos.y < 0 || subTilePos.y >= TerrainTile::SubtileSize) { roadEffect->positions[i] -= (roadEffect->velocities[i] * elapsedSeconds); roadEffect->velocities[i].y *= -1.0f; hitEdgeBoundary = true; } // Ensure we're within bounds. subTilePos = glm::ivec2(roadEffect->positions[i].x, roadEffect->positions[i].y); subTilePos.x = std::max(std::min(subTilePos.x, TerrainTile::SubtileSize - 1), 0); subTilePos.y = std::max(std::min(subTilePos.y, TerrainTile::SubtileSize - 1), 0); if (!hitEdgeBoundary) { // See if we went off a road. If so, correct. int pixelId = roadEffect->tile->GetPixelId(subTilePos); if (roadEffect->tile->type[pixelId] != TerrainTypes::ROADS) { glm::ivec2 offRoad = subTilePos; roadEffect->positions[i] -= (roadEffect->velocities[i] * elapsedSeconds); // Whichever coordinates were different, we bounce. This isn't strictly correct, as if we went through a corner of a pixel, we shouldn't bounce one axis. // However, the subsequent step (angular distortion) is very incorrect (or correct, depending on your viewpoint) bool angleXDistortion = false; subTilePos = glm::ivec2(roadEffect->positions[i].x, roadEffect->positions[i].y); if (subTilePos.x != offRoad.x) { roadEffect->velocities[i].x *= -1.0f; angleXDistortion = true; } bool angleYDistortion = false; if (subTilePos.y != offRoad.y) { roadEffect->velocities[i].y *= -1.0f; angleYDistortion = true; } // TODO configurable // Distort axis (to promote moving *away* and prevent collisions) but keep the speed the same. // Do nothing if both distortions are requested. float factor = 1.5f; if (angleXDistortion) { float length = glm::length(roadEffect->velocities[i]); roadEffect->velocities[i].y *= factor; roadEffect->velocities[i] = glm::normalize(roadEffect->velocities[i]) * length; } else if (angleYDistortion) { float length = glm::length(roadEffect->velocities[i]); roadEffect->velocities[i].x *= factor; roadEffect->velocities[i] = glm::normalize(roadEffect->velocities[i]) * length; } } } return roadEffect->tile->heightmap[roadEffect->tile->GetPixelId(subTilePos)]; } void RoadEffect::Simulate(const glm::ivec2 subtileId, void* effectData, float elapsedSeconds) { RoadEffectData* roadEffect = (RoadEffectData*)effectData; auto& travellers = roadEffect->travellers.positions; for (unsigned int i = 0; i < travellers.size() / 2; i++) { float height = MoveTraveller(subtileId, roadEffect, i, elapsedSeconds); glm::vec3 position = glm::vec3(roadEffect->positions[i].x, roadEffect->positions[i].y, height + 0.f); glm::vec3 endPosition = position + glm::normalize(glm::vec3(roadEffect->velocities[i].x, roadEffect->velocities[i].y, 0.0f)); travellers[i * 2] = position; travellers[i * 2 + 1] = endPosition; } glBindVertexArray(roadEffect->vao); roadEffect->travellers.TransferUpdatePositionToOpenGl(roadEffect->positionBuffer); } void RoadEffect::Render(void* effectData, const glm::mat4& perspectiveMatrix, const glm::mat4& viewMatrix, const glm::mat4& modelMatrix) { sf::Clock clock; // TODO configurable glLineWidth(3.0f); RoadEffectData* roadEffect = (RoadEffectData*)effectData; glUseProgram(programId); glBindVertexArray(roadEffect->vao); glUniformMatrix4fv(projMatrixLocation, 1, GL_FALSE, &perspectiveMatrix[0][0]); glUniformMatrix4fv(mvMatrixLocation, 1, GL_FALSE, &(viewMatrix * modelMatrix)[0][0]); glDrawArrays(GL_LINES, 0, roadEffect->travellers.positions.size()); glLineWidth(1.0f); stats.usRenderTime += clock.getElapsedTime().asMicroseconds(); stats.travellersRendered += roadEffect->positions.size(); stats.tilesRendered++; } void RoadEffect::LogStats() { Logger::Log("Road Rendering: ", stats.usRenderTime, " us, ", stats.travellersRendered, " travellers, ", stats.tilesRendered, " tiles."); stats.Reset(); }
38.78733
165
0.623425
GuMiner
77cbbdd518320c2ccef95b126826213b3f82d59e
14,526
cpp
C++
src/terrain/sources/proland/dem/ResidualProducer.cpp
stormbirds/Proland-4.0
fdff3642e36c56af8ec5f9299166a3d4bf36d33a
[ "Unlicense" ]
99
2015-01-14T21:18:20.000Z
2021-12-01T09:42:15.000Z
src/terrain/sources/proland/dem/ResidualProducer.cpp
stormbirds/Proland-4.0
fdff3642e36c56af8ec5f9299166a3d4bf36d33a
[ "Unlicense" ]
null
null
null
src/terrain/sources/proland/dem/ResidualProducer.cpp
stormbirds/Proland-4.0
fdff3642e36c56af8ec5f9299166a3d4bf36d33a
[ "Unlicense" ]
46
2015-04-03T12:38:31.000Z
2021-09-26T02:38:56.000Z
/* * Proland: a procedural landscape rendering library. * Copyright (c) 2008-2011 INRIA * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Proland is distributed under a dual-license scheme. * You can obtain a specific license from Inria: proland-licensing@inria.fr. */ /* * Authors: Eric Bruneton, Antoine Begault, Guillaume Piolat. */ #include "proland/dem/ResidualProducer.h" #include <fstream> #include <sstream> #include "tiffio.h" #include "ork/core/Logger.h" #include "ork/resource/ResourceTemplate.h" #include "proland/producer/CPUTileStorage.h" #include "proland/util/mfs.h" #include <pthread.h> #include <cstring> using namespace std; using namespace ork; namespace proland { //#define SINGLE_FILE #define MAX_TILE_SIZE 256 void *ResidualProducer::key = NULL; void residualDelete(void* data) { delete[] (unsigned char*) data; } ResidualProducer::ResidualProducer(ptr<TileCache> cache, const char *name, int deltaLevel, float zscale) : TileProducer("ResidualProducer", "CreateResidualTile") { init(cache, name, deltaLevel, zscale); } ResidualProducer::ResidualProducer() : TileProducer("ResidualProducer", "CreateResidualTile") { } void ResidualProducer::init(ptr<TileCache> cache, const char *name, int deltaLevel, float zscale) { TileProducer::init(cache, false); this->name = name; if (strlen(name) == 0) { this->tileFile = NULL; this->minLevel = 0; this->maxLevel = 32; this->rootLevel = 0; this->deltaLevel = 0; this->rootTx = 0; this->rootTy = 0; this->scale = 1.0; } else { fopen(&tileFile, name, "rb"); if (tileFile == NULL) { if (Logger::ERROR_LOGGER != NULL) { Logger::ERROR_LOGGER->log("DEM", "Cannot open file '" + string(name) + "'"); } maxLevel = -1; scale = 1.0; } else { fread(&minLevel, sizeof(int), 1, tileFile); fread(&maxLevel, sizeof(int), 1, tileFile); fread(&tileSize, sizeof(int), 1, tileFile); fread(&rootLevel, sizeof(int), 1, tileFile); fread(&rootTx, sizeof(int), 1, tileFile); fread(&rootTy, sizeof(int), 1, tileFile); fread(&scale, sizeof(float), 1, tileFile); } this->deltaLevel = rootLevel == 0 ? deltaLevel : 0; scale = scale * zscale; int ntiles = minLevel + ((1 << (max(maxLevel - minLevel, 0) * 2 + 2)) - 1) / 3; header = sizeof(float) + sizeof(int) * (6 + ntiles * 2); offsets = new unsigned int[ntiles * 2]; if (tileFile != NULL) { fread(offsets, sizeof(unsigned int) * ntiles * 2, 1, tileFile); #ifndef SINGLE_FILE fclose(tileFile); tileFile = NULL; #endif } if (key == NULL) { key = new pthread_key_t; pthread_key_create((pthread_key_t*) key, residualDelete); } assert(tileSize + 5 < MAX_TILE_SIZE); assert(deltaLevel <= minLevel); #ifdef SINGLE_FILE mutex = new pthread_mutex_t; pthread_mutex_init((pthread_mutex_t*) mutex, NULL); #endif } } ResidualProducer::~ResidualProducer() { #ifdef SINGLE_FILE fclose(tileFile); pthread_mutex_destroy((pthread_mutex_t*) mutex); delete (pthread_mutex_t*) mutex; #endif delete[] offsets; } int ResidualProducer::getBorder() { return 2; } int ResidualProducer::getMinLevel() { return minLevel; } int ResidualProducer::getDeltaLevel() { return deltaLevel; } void ResidualProducer::addProducer(ptr<ResidualProducer> p) { producers.push_back(p); } bool ResidualProducer::hasTile(int level, int tx, int ty) { int l = level + deltaLevel - rootLevel; if (l >= 0 && (tx >> l) == rootTx && (ty >> l) == rootTy) { if (l <= maxLevel) { return true; } for (unsigned int i = 0; i < producers.size(); ++i) { if (producers[i]->hasTile(level + deltaLevel, tx, ty)) { return true; } } } return false; } bool ResidualProducer::doCreateTile(int level, int tx, int ty, TileStorage::Slot *data) { int l = level + deltaLevel - rootLevel; if (l >= 0 && (tx >> l) == rootTx && (ty >> l) == rootTy) { if (l > maxLevel) { for (unsigned int i = 0; i < producers.size(); ++i) { producers[i]->doCreateTile(level + deltaLevel, tx, ty, data); } return true; } } else { return true; } if (Logger::DEBUG_LOGGER != NULL) { ostringstream oss; oss << "Residual tile " << getId() << " " << level << " " << tx << " " << ty; Logger::DEBUG_LOGGER->log("DEM", oss.str()); } level = l; tx = tx - (rootTx << level); ty = ty - (rootTy << level); CPUTileStorage<float>::CPUSlot *cpuData = dynamic_cast<CPUTileStorage<float>::CPUSlot*>(data); assert(cpuData != NULL); assert(dynamic_cast<CPUTileStorage<float>*>(cpuData->getOwner())->getChannels() == 1); if ((int) name.size() == 0) { tileSize = cpuData->getOwner()->getTileSize() - 5; readTile(level, tx, ty, NULL, NULL, NULL, cpuData->data); } else { assert(cpuData->getOwner()->getTileSize() == tileSize + 5); unsigned char *tsData = (unsigned char*) pthread_getspecific(*((pthread_key_t*) key)); if (tsData == NULL) { tsData = new unsigned char[MAX_TILE_SIZE * MAX_TILE_SIZE * 4]; pthread_setspecific(*((pthread_key_t*) key), tsData); } unsigned char *compressedData = tsData; unsigned char *uncompressedData = tsData + MAX_TILE_SIZE * MAX_TILE_SIZE * 2; if (deltaLevel > 0 && level == deltaLevel) { float *tmp = new float[(tileSize + 5) * (tileSize + 5)]; readTile(0, 0, 0, compressedData, uncompressedData, NULL, cpuData->data); for (int i = 1; i <= deltaLevel; ++i) { upsample(i, 0, 0, cpuData->data, tmp); readTile(i, 0, 0, compressedData, uncompressedData, tmp, cpuData->data); } delete[] tmp; } else { readTile(level, tx, ty, compressedData, uncompressedData, NULL, cpuData->data); } } return true; } void ResidualProducer::swap(ptr<ResidualProducer> p) { TileProducer::swap(p); std::swap(name, p->name); std::swap(tileSize, p->tileSize); std::swap(rootLevel, p->rootLevel); std::swap(deltaLevel, p->deltaLevel); std::swap(rootTx, p->rootTx); std::swap(rootTy, p->rootTy); std::swap(minLevel, p->minLevel); std::swap(maxLevel, p->maxLevel); std::swap(scale, p->scale); std::swap(header, p->header); std::swap(offsets, p->offsets); std::swap(mutex, p->mutex); std::swap(tileFile, p->tileFile); std::swap(producers, p->producers); } int ResidualProducer::getTileSize(int level) { return level < minLevel ? tileSize >> (minLevel - level) : tileSize; } int ResidualProducer::getTileId(int level, int tx, int ty) { if (level < minLevel) { return level; } else { int l = max(level - minLevel, 0); return minLevel + tx + ty * (1 << l) + ((1 << (2 * l)) - 1) / 3; } } void ResidualProducer::readTile(int level, int tx, int ty, unsigned char* compressedData, unsigned char *uncompressedData, float *tile, float *result) { int tilesize = getTileSize(level) + 5; if ((int) name.size() == 0) { if (tile != NULL) { for (int j = 0; j < tilesize; ++j) { for (int i = 0; i < tilesize; ++i) { result[i + j * (tileSize + 5)] = tile[i + j * (tileSize + 5)]; } } } else { for (int j = 0; j < tilesize; ++j) { for (int i = 0; i < tilesize; ++i) { result[i + j * (tileSize + 5)] = 0.f; } } } } else { int tileid = getTileId(level, tx, ty); int fsize = offsets[2 * tileid + 1] - offsets[2 * tileid]; assert(fsize < (tileSize + 5) * (tileSize + 5) * 2); #ifdef SINGLE_FILE pthread_mutex_lock((pthread_mutex_t*) mutex); fseek64(tileFile, header + offsets[2 * tileid], SEEK_SET); fread(compressedData, fsize, 1, tileFile); pthread_mutex_unlock((pthread_mutex_t*) mutex); #else FILE *file; fopen(&file, name.c_str(), "rb"); fseek64(file, header + offsets[2 * tileid], SEEK_SET); fread(compressedData, fsize, 1, file); fclose(file); #endif /*ifstream fs(name.c_str(), ios::binary); fs.seekg(header + offsets[2 * tileid], ios::beg); fs.read((char*) compressedData, fsize); fs.close();*/ // TODO compare perfs FILE vs ifstream vs mmap mfs_file fd; mfs_open(compressedData, fsize, (char *)"r", &fd); TIFF* tf = TIFFClientOpen("name", "r", &fd, (TIFFReadWriteProc) mfs_read, (TIFFReadWriteProc) mfs_write, (TIFFSeekProc) mfs_lseek, (TIFFCloseProc) mfs_close, (TIFFSizeProc) mfs_size, (TIFFMapFileProc) mfs_map, (TIFFUnmapFileProc) mfs_unmap); TIFFReadEncodedStrip(tf, 0, uncompressedData, (tsize_t) -1); TIFFClose(tf); if (tile != NULL) { for (int j = 0; j < tilesize; ++j) { for (int i = 0; i < tilesize; ++i) { int off = 2 * (i + j * tilesize); int toff = i + j * (tileSize + 5); short z = short(uncompressedData[off + 1]) << 8 | short(uncompressedData[off]); result[toff] = tile[toff] + z * scale; } } } else { for (int j = 0; j < tilesize; ++j) { for (int i = 0; i < tilesize; ++i) { int off = 2 * (i + j * tilesize); short z = short(uncompressedData[off + 1]) << 8 | short(uncompressedData[off]); result[i + j * (tileSize + 5)] = z * scale; } } } } } void ResidualProducer::upsample(int level, int tx, int ty, float *parentTile, float *result) { int n = tileSize + 5; int tilesize = getTileSize(level); int px = 1 + (tx % 2) * tilesize / 2; int py = 1 + (ty % 2) * tilesize / 2; for (int j = 0; j <= tilesize + 4; ++j) { for (int i = 0; i <= tilesize + 4; ++i) { float z; if (j%2 == 0) { if (i%2 == 0) { z = parentTile[i/2+px + (j/2+py)*n]; } else { float z0 = parentTile[i/2+px-1 + (j/2+py)*n]; float z1 = parentTile[i/2+px + (j/2+py)*n]; float z2 = parentTile[i/2+px+1 + (j/2+py)*n]; float z3 = parentTile[i/2+px+2 + (j/2+py)*n]; z = ((z1+z2)*9-(z0+z3))/16; } } else { if (i%2 == 0) { float z0 = parentTile[i/2+px + (j/2-1+py)*n]; float z1 = parentTile[i/2+px + (j/2+py)*n]; float z2 = parentTile[i/2+px + (j/2+1+py)*n]; float z3 = parentTile[i/2+px + (j/2+2+py)*n]; z = ((z1+z2)*9-(z0+z3))/16; } else { int di, dj; z = 0.0; for (dj = -1; dj <= 2; ++dj) { float f = dj == -1 || dj == 2 ? -1/16.0f : 9/16.0f; for (di = -1; di <= 2; ++di) { float g = di == -1 || di == 2 ? -1/16.0f : 9/16.0f; z += f*g*parentTile[i/2+di+px + (j/2+dj+py)*n]; } } } } int off = i + j * n; result[off] = z; } } } void ResidualProducer::init(ptr<ResourceManager> manager, Resource *r, const string &name, ptr<ResourceDescriptor> desc, const TiXmlElement *e) { e = e == NULL ? desc->descriptor : e; ptr<TileCache> cache; string file; int deltaLevel = 0; float zscale = 1.0; cache = manager->loadResource(r->getParameter(desc, e, "cache")).cast<TileCache>(); if (e->Attribute("file") != NULL) { file = r->getParameter(desc, e, "file"); file = manager->getLoader()->findResource(file); } if (e->Attribute("scale") != NULL) { r->getFloatParameter(desc, e, "scale", &zscale); } if (e->Attribute("delta") != NULL) { r->getIntParameter(desc, e, "delta", &deltaLevel); } init(cache, file.c_str(), deltaLevel, zscale); const TiXmlNode *n = e->FirstChild(); while (n != NULL) { const TiXmlElement *f = n->ToElement(); if (f != NULL) { if (strncmp(f->Value(), "residualProducer", 16) == 0) { addProducer(ResourceFactory::getInstance()->create(manager, f->Value(), desc, f).cast<ResidualProducer>()); } else { if (Logger::ERROR_LOGGER != NULL) { Resource::log(Logger::ERROR_LOGGER, desc, f, "Invalid subelement"); } throw exception(); } } n = n->NextSibling(); } } class ResidualProducerResource : public ResourceTemplate<2, ResidualProducer> { public: ResidualProducerResource(ptr<ResourceManager> manager, const string &name, ptr<ResourceDescriptor> desc, const TiXmlElement *e = NULL) : ResourceTemplate<2, ResidualProducer>(manager, name, desc) { e = e == NULL ? desc->descriptor : e; checkParameters(desc, e, "name,cache,file,delta,scale,"); init(manager, this, name, desc, e); } }; extern const char residualProducer[] = "residualProducer"; static ResourceFactory::Type<residualProducer, ResidualProducerResource> ResidualProducerType; }
33.088838
143
0.547226
stormbirds
77ce9a852fad73496c9f54211e14f188a0d6d031
702
cpp
C++
chingjun/39-recover-rotated-sorted-array.cpp
joshua-jin/algorithm-campus
8f60cd63542f4f5778a992179c3e767fbc023338
[ "MIT" ]
8
2016-05-10T12:59:36.000Z
2020-09-16T19:47:44.000Z
chingjun/39-recover-rotated-sorted-array.cpp
joshua-jin/algorithm-campus
8f60cd63542f4f5778a992179c3e767fbc023338
[ "MIT" ]
null
null
null
chingjun/39-recover-rotated-sorted-array.cpp
joshua-jin/algorithm-campus
8f60cd63542f4f5778a992179c3e767fbc023338
[ "MIT" ]
2
2016-12-22T09:28:54.000Z
2020-01-22T17:56:02.000Z
class Solution { public: void reverse(vector<int> &nums, int startIndex, int endIndex) { while (startIndex < endIndex) { int temp = nums[startIndex]; nums[startIndex] = nums[endIndex]; nums[endIndex] = temp; startIndex++; endIndex--; } } void recoverRotatedSortedArray(vector<int> &nums) { // write your code here int size = nums.size(); for (int i = 1; i < size; i++) { if (nums[i] < nums[i-1]) { reverse(nums, 0, i-1); reverse(nums, i, size-1); reverse(nums, 0, size-1); return; } } } };
28.08
67
0.464387
joshua-jin
77d413c3e92109973099b4dd060302a7b5cece06
1,366
cpp
C++
Src/Source/GoToLineWindow.cpp
Sylvain78/BeTeX
4624602987dd0f2790280c69f380661a03a03180
[ "MIT" ]
null
null
null
Src/Source/GoToLineWindow.cpp
Sylvain78/BeTeX
4624602987dd0f2790280c69f380661a03a03180
[ "MIT" ]
null
null
null
Src/Source/GoToLineWindow.cpp
Sylvain78/BeTeX
4624602987dd0f2790280c69f380661a03a03180
[ "MIT" ]
null
null
null
#include "GoToLineWindow.h" using namespace InterfaceConstants; GoToLineWindow::GoToLineWindow(BRect r,BMessenger* messenger) : BWindow(r,"Go To Line...",B_FLOATING_WINDOW,B_NOT_ZOOMABLE|B_NOT_RESIZABLE) { SetFeel(B_NORMAL_WINDOW_FEEL); parent = new BView(Bounds(),"parent",B_FOLLOW_ALL_SIDES,B_WILL_DRAW); parent->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); AddChild(parent); msgr = messenger; r = Bounds(); num = new BTextControl(BRect(5,10,40,30),"num",NULL,NULL,NULL); parent->AddChild(num); num->MakeFocus(true); go = new BButton(BRect(55,8,95,28),"gogogadgetbutton","Go",new BMessage(K_GTL_WINDOW_GO)); parent->AddChild(go); go->MakeDefault(true); } GoToLineWindow::~GoToLineWindow() { delete msgr; } void GoToLineWindow::MessageReceived(BMessage* msg) { switch(msg->what) { case K_GTL_WINDOW_GO: { BMessage* linemsg = new BMessage(K_GTL_WINDOW_GO); BString text; text << num->Text(); bool IsNumeric=true; for(int i=0;i<text.Length();i++) { if(!isdigit(text[i])) { IsNumeric = false; } } if(IsNumeric && linemsg->AddInt32("line",atoi(text.String())-1) == B_OK) { msgr->SendMessage(linemsg); Quit(); } }break; default: BWindow::MessageReceived(msg); } } void GoToLineWindow::Quit() { msgr->SendMessage(new BMessage(K_GTL_WINDOW_QUIT)); BWindow::Quit(); }
22.032258
139
0.691069
Sylvain78
77d5cd25afa0df4941a3ec889ba98beb669636ed
17,235
cpp
C++
external/sbml/sbml/test/TestReadFromFile7.cpp
dchandran/evolvenetworks
072f9e1292552f691a86457ffd16a5743724fb5e
[ "BSD-3-Clause" ]
1
2019-08-22T17:17:41.000Z
2019-08-22T17:17:41.000Z
external/sbml/sbml/test/TestReadFromFile7.cpp
dchandran/evolvenetworks
072f9e1292552f691a86457ffd16a5743724fb5e
[ "BSD-3-Clause" ]
null
null
null
external/sbml/sbml/test/TestReadFromFile7.cpp
dchandran/evolvenetworks
072f9e1292552f691a86457ffd16a5743724fb5e
[ "BSD-3-Clause" ]
null
null
null
/** * \file TestReadFromFile7.cpp * \brief Reads test-data/l2v3-all.xml into memory and tests it. * \author Sarah Keating * * $Id: TestReadFromFile7.cpp 10129 2009-08-28 12:23:22Z sarahkeating $ * $HeadURL: https://sbml.svn.sourceforge.net/svnroot/sbml/trunk/libsbml/src/sbml/test/TestReadFromFile7.cpp $ */ /* Copyright 2004 California Institute of Technology and * Japan Science and Technology Corporation. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2.1 of the License, or * any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. The software and * documentation provided hereunder is on an "as is" basis, and the * California Institute of Technology and Japan Science and Technology * Corporation have no obligations to provide maintenance, support, * updates, enhancements or modifications. In no event shall the * California Institute of Technology or the Japan Science and Technology * Corporation be liable to any party for direct, indirect, special, * incidental or consequential damages, including lost profits, arising * out of the use of this software and its documentation, even if the * California Institute of Technology and/or Japan Science and Technology * Corporation have been advised of the possibility of such damage. See * the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * The original code contained here was initially developed by: * * Ben Bornstein * The Systems Biology Markup Language Development Group * ERATO Kitano Symbiotic Systems Project * Control and Dynamical Systems, MC 107-81 * California Institute of Technology * Pasadena, CA, 91125, USA * * http://www.cds.caltech.edu/erato * mailto:sbml-team@caltech.edu * * Contributor(s): */ #include <sbml/common/common.h> #include <sbml/SBMLReader.h> #include <sbml/SBMLWriter.h> #include <sbml/SBMLTypes.h> #include <string> #include <check.h> LIBSBML_CPP_NAMESPACE_USE BEGIN_C_DECLS extern char *TestDataDirectory; START_TEST (test_read_l2v3_all) { SBMLReader reader; SBMLDocument* d; Model* m; Compartment* c; CompartmentType* ct; Species* s; Parameter* p; AssignmentRule* ar; Reaction* r; SpeciesReference* sr; KineticLaw* kl; UnitDefinition* ud; Constraint* con; Event* e; Delay* delay; Trigger* trigger; EventAssignment* ea; FunctionDefinition* fd; InitialAssignment* ia; AlgebraicRule* alg; RateRule* rr; SpeciesType* st; StoichiometryMath* stoich; Unit* u; ListOfEvents *loe; Event *e1; ListOfEventAssignments *loea; EventAssignment *ea1; ListOfFunctionDefinitions *lofd; FunctionDefinition * fd1; ListOfParameters *lop; Parameter *p1; ListOfSpeciesTypes *lost; SpeciesType *st1; ListOfUnitDefinitions *loud; UnitDefinition *ud1; ListOfUnits *lou; Unit * u1; const ASTNode* ast; std::string filename(TestDataDirectory); filename += "l2v3-all.xml"; d = reader.readSBML(filename); if (d == NULL) { fail("readSBML(\"l2v3-all.xml\") returned a NULL pointer."); } // // <sbml level="2" version="3" ...> // fail_unless( d->getLevel () == 2, NULL ); fail_unless( d->getVersion() == 3, NULL ); // // <model id="l2v3_all"> // m = d->getModel(); fail_unless( m != NULL, NULL ); fail_unless(m->getId() == "l2v3_all", NULL); //<listOfCompartments> // <compartment id="a" size="2.3" compartmentType="hh" sboTerm="SBO:0000236"/> //</listOfCompartments> fail_unless( m->getNumCompartments() == 1, NULL ); c = m->getCompartment(0); fail_unless( c != NULL , NULL ); fail_unless( c->getId() == "a", NULL ); fail_unless( c->getCompartmentType() == "hh", NULL ); fail_unless( c->getSBOTerm() == 236, NULL ); fail_unless( c->getSBOTermID() == "SBO:0000236", NULL ); fail_unless( c->getSize() == 2.3, NULL ); //<listOfCompartmentTypes> // <compartmentType id="hh" sboTerm="SBO:0000236"/> //</listOfCompartmentTypes> fail_unless( m->getNumCompartmentTypes() == 1, NULL ); ct = m->getCompartmentType(0); fail_unless( ct != NULL , NULL ); fail_unless( ct->getId() == "hh", NULL ); fail_unless( ct->getSBOTerm() == 236, NULL ); fail_unless( ct->getSBOTermID() == "SBO:0000236", NULL ); //<listOfSpeciesTypes> // <speciesType id="gg" name="dd" sboTerm="SBO:0000236"/> //</listOfSpeciesTypes> fail_unless( m->getNumSpeciesTypes() == 1, NULL ); st = m->getSpeciesType(0); fail_unless( st != NULL , NULL ); fail_unless( st->getId() == "gg", NULL ); fail_unless( st->getName() == "dd", NULL ); fail_unless( st->getSBOTerm() == 236, NULL ); fail_unless( st->getSBOTermID() == "SBO:0000236", NULL ); lost = m->getListOfSpeciesTypes(); st1 = lost->get(0); fail_unless( st1 == st); st1 = lost->get("gg"); fail_unless( st1 == st); //<listOfConstraints> // <constraint> // <math xmlns="http://www.w3.org/1998/Math/MathML"> // <apply> // <lt/> // <ci> x </ci> // <cn type="integer"> 3 </cn> // </apply> // </math> // </constraint> //</listOfConstraints> fail_unless( m->getNumConstraints() == 1, NULL ); con = m->getConstraint(0); fail_unless( con != NULL , NULL ); ast = con->getMath(); fail_unless(!strcmp(SBML_formulaToString(ast), "lt(x, 3)"), NULL); //<event id="e1" sboTerm="SBO:0000231"> // <trigger sboTerm="SBO:0000231"> // <math xmlns="http://www.w3.org/1998/Math/MathML"> // <apply> // <lt/> // <ci> x </ci> // <cn type="integer"> 3 </cn> // </apply> // </math> // </trigger> // <delay sboTerm="SBO:0000064"> // <math xmlns="http://www.w3.org/1998/Math/MathML"> // <apply> // <plus/> // <ci> x </ci> // <cn type="integer"> 3 </cn> // </apply> // </math> // </delay> // <listOfEventAssignments> // <eventAssignment variable="a" sboTerm="SBO:0000064"> // <math xmlns="http://www.w3.org/1998/Math/MathML"> // <apply> // <times/> // <ci> x </ci> // <ci> p3 </ci> // </apply> // </math> // </eventAssignment> // </listOfEventAssignments> //</event> fail_unless( m->getNumEvents() == 1, NULL ); e = m->getEvent(0); fail_unless(e != NULL, NULL); fail_unless(e->getId() == "e1", NULL); fail_unless(e->getSBOTerm() == 231, NULL); fail_unless(e->getSBOTermID() == "SBO:0000231"); fail_unless(e->isSetDelay(), NULL); delay = e->getDelay(); fail_unless(delay != NULL, NULL); fail_unless(delay->getSBOTerm() == 64, NULL); fail_unless(delay->getSBOTermID() == "SBO:0000064"); ast = delay->getMath(); fail_unless(!strcmp(SBML_formulaToString(ast), "p + 3"), NULL); fail_unless(e->isSetTrigger(), NULL); trigger = e->getTrigger(); fail_unless(trigger != NULL, NULL); fail_unless(trigger->getSBOTerm() == 64, NULL); fail_unless(trigger->getSBOTermID() == "SBO:0000064"); ast = trigger->getMath(); fail_unless(!strcmp(SBML_formulaToString(ast), "lt(x, 3)"), NULL); loe = m->getListOfEvents(); e1 = loe->get(0); fail_unless( e1 == e); e1 = loe->get("e1"); fail_unless( e1 == e); fail_unless( e->getNumEventAssignments() == 1, NULL ); ea = e->getEventAssignment(0); fail_unless(ea != NULL, NULL); fail_unless(ea->getVariable() == "a", NULL); fail_unless(ea->getSBOTerm() == 64, NULL); fail_unless(ea->getSBOTermID() == "SBO:0000064"); ast = ea->getMath(); fail_unless(!strcmp(SBML_formulaToString(ast), "x * p3"), NULL); loea = e->getListOfEventAssignments(); ea1 = loea->get(0); fail_unless( ea1 == ea); ea1 = loea->get("a"); fail_unless( ea1 == ea); //<listOfFunctionDefinitions> // <functionDefinition id="fd" sboTerm="SBO:0000064"> // <math xmlns="http://www.w3.org/1998/Math/MathML"> // <lambda> // <bvar> // <ci> x </ci> // </bvar> // <apply> // <power/> // <ci> x </ci> // <cn type="integer"> 3 </cn> // </apply> // </lambda> // </math> // </functionDefinition> //</listOfFunctionDefinitions> fail_unless( m->getNumFunctionDefinitions() == 1, NULL ); fd = m->getFunctionDefinition(0); fail_unless(fd != NULL, NULL); fail_unless(fd->getId() == "fd", NULL); fail_unless(fd->getSBOTerm() == 64, NULL); fail_unless(fd->getSBOTermID() == "SBO:0000064"); ast = fd->getMath(); fail_unless(!strcmp(SBML_formulaToString(ast), "lambda(x, pow(x, 3))"), NULL); lofd = m->getListOfFunctionDefinitions(); fd1 = lofd->get(0); fail_unless( fd1 == fd); fd1 = lofd->get("fd"); fail_unless( fd1 == fd); //<listOfInitialAssignments> // <initialAssignment symbol="p1"> // <math xmlns="http://www.w3.org/1998/Math/MathML"> // <apply> // <times/> // <ci> x </ci> // <ci> p3 </ci> // </apply> // </math> // </initialAssignment> //</listOfInitialAssignments> fail_unless( m->getNumInitialAssignments() == 1, NULL ); ia = m->getInitialAssignment(0); fail_unless( ia != NULL , NULL ); fail_unless(ia->getSymbol() == "p1", NULL); ast = ia->getMath(); fail_unless(!strcmp(SBML_formulaToString(ast), "x * p3"), NULL); //<listOfRules> fail_unless( m->getNumRules() == 3, NULL ); // <algebraicRule sboTerm="SBO:0000064"> // <math xmlns="http://www.w3.org/1998/Math/MathML"> // <apply> // <power/> // <ci> x </ci> // <cn type="integer"> 3 </cn> // </apply> // </math> // </algebraicRule> alg = static_cast<AlgebraicRule*>( m->getRule(0)); fail_unless( alg != NULL , NULL ); fail_unless(alg->getSBOTerm() == 64, NULL); fail_unless(alg->getSBOTermID() == "SBO:0000064"); ast = alg->getMath(); fail_unless(!strcmp(SBML_formulaToString(ast), "pow(x, 3)"), NULL); // <assignmentRule variable="p2" sboTerm="SBO:0000064"> // <math xmlns="http://www.w3.org/1998/Math/MathML"> // <apply> // <times/> // <ci> x </ci> // <ci> p3 </ci> // </apply> // </math> // </assignmentRule> ar = static_cast <AssignmentRule*>(m->getRule(1)); fail_unless( ar != NULL , NULL ); fail_unless( ar->getVariable() == "p2", NULL); fail_unless(ar->getSBOTerm() == 64, NULL); fail_unless(ar->getSBOTermID() == "SBO:0000064"); ast = ar->getMath(); fail_unless(!strcmp(SBML_formulaToString(ast), "x * p3"), NULL); // <rateRule variable="p3" sboTerm="SBO:0000064"> // <math xmlns="http://www.w3.org/1998/Math/MathML"> // <apply> // <divide/> // <ci> p1 </ci> // <ci> p </ci> // </apply> // </math> // </rateRule> rr = static_cast<RateRule*> (m->getRule(2)); fail_unless( rr != NULL , NULL ); fail_unless( rr->getVariable() == "p3", NULL); fail_unless(rr->getSBOTerm() == 64, NULL); fail_unless(rr->getSBOTermID() == "SBO:0000064"); ast = rr->getMath(); fail_unless(!strcmp(SBML_formulaToString(ast), "p1 / p"), NULL); //<listOfSpecies> // <species id="s" compartment="a" initialAmount="0" speciesType="gg" sboTerm="SBO:000236"/> //</listOfSpecies> fail_unless( m->getNumSpecies() == 1, NULL ); s = m->getSpecies(0); fail_unless( s != NULL , NULL ); fail_unless( s->getId() == "s", NULL ); fail_unless( s->getSpeciesType() == "gg", NULL ); fail_unless( s->getCompartment() == "a", NULL ); fail_unless(s->getSBOTerm() == 236, NULL); fail_unless(s->getSBOTermID() == "SBO:0000236"); fail_unless(s->isSetInitialAmount(), NULL); fail_unless(!s->isSetInitialConcentration(), NULL); fail_unless(s->getInitialAmount() == 0, NULL); //<listOfReactions> // <reaction id="r" fast="true" reversible="false"> // <listOfReactants> // <speciesReference species="s" sboTerm="SBO:0000011"> // <stoichiometryMath sboTerm="SBO:0000064"> // <math xmlns="http://www.w3.org/1998/Math/MathML"> // <apply> // <times/> // <ci> s </ci> // <ci> p </ci> // </apply> // </math> // </stoichiometryMath> // </speciesReference> // </listOfReactants> // <kineticLaw> // <math xmlns="http://www.w3.org/1998/Math/MathML"> // <apply> // <divide/> // <apply> // <times/> // <ci> s </ci> // <ci> k </ci> // </apply> // <ci> p </ci> // </apply> // </math> // <listOfParameters> // <parameter id="k" value="9" units="litre"/> // </listOfParameters> // </kineticLaw> // </reaction> //</listOfReactions> fail_unless( m->getNumReactions() == 1, NULL ); r = m->getReaction(0); fail_unless( r != NULL , NULL ); fail_unless(r->getId() == "r", NULL); fail_unless(!r->getReversible(), NULL); fail_unless(r->getFast(), NULL); fail_unless(r->isSetKineticLaw(), NULL); kl = r->getKineticLaw(); fail_unless( kl != NULL , NULL ); fail_unless(kl->isSetMath(), NULL); ast = kl->getMath(); fail_unless(!strcmp(SBML_formulaToString(ast), "s * k / p"), NULL); fail_unless(kl->getNumParameters() == 2, NULL); p = kl->getParameter(0); fail_unless( p != NULL , NULL ); fail_unless(p->getId() == "k", NULL); fail_unless(p->getUnits() == "litre", NULL); fail_unless(p->getValue() == 9, NULL); ud = p->getDerivedUnitDefinition(); fail_unless (ud->getNumUnits() == 1, NULL); fail_unless( ud->getUnit(0)->getKind() == UNIT_KIND_LITRE, NULL ); fail_unless( ud->getUnit(0)->getExponent() == 1, NULL ); lop = kl->getListOfParameters(); p1 = lop->get(0); fail_unless( p1 == p); p1 = lop->get("k"); fail_unless( p1 == p); p = kl->getParameter(1); fail_unless( p != NULL , NULL ); fail_unless(p->getId() == "k1", NULL); fail_unless(p->getUnits() == "ud1", NULL); fail_unless(p->getValue() == 9, NULL); ud = p->getDerivedUnitDefinition(); fail_unless (ud->getNumUnits() == 1, NULL); fail_unless( ud->getUnit(0)->getKind() == UNIT_KIND_MOLE, NULL ); fail_unless( ud->getUnit(0)->getExponent() == 1, NULL ); fail_unless(r->getNumReactants() == 1, NULL); fail_unless(r->getNumProducts() == 0, NULL); fail_unless(r->getNumModifiers() == 0, NULL); sr = r->getReactant(0); fail_unless( sr != NULL , NULL ); fail_unless(sr->getSpecies() == "s", NULL); fail_unless(sr->getSBOTerm() == 11, NULL); fail_unless(sr->getSBOTermID() == "SBO:0000011", NULL); stoich = sr->getStoichiometryMath(); fail_unless( stoich != NULL , NULL ); fail_unless(stoich->getSBOTerm() == 64, NULL); fail_unless(stoich->getSBOTermID() == "SBO:0000064", NULL); ast = stoich->getMath(); fail_unless(!strcmp(SBML_formulaToString(ast), "s * p"), NULL); //<listOfUnitDefinitions> // <unitDefinition id="ud1"> // <listOfUnits> // <unit kind="mole"/> // </listOfUnits> // </unitDefinition> //</listOfUnitDefinitions> fail_unless(m->getNumUnitDefinitions() == 1, NULL); ud = m->getUnitDefinition(0); fail_unless( ud != NULL , NULL ); fail_unless( ud->getId() == "ud1", NULL ); loud = m->getListOfUnitDefinitions(); ud1 = loud->get(0); fail_unless (ud1 == ud); ud1 = loud->get("ud1"); fail_unless ( ud1 == ud); fail_unless(ud->getNumUnits() == 1, NULL); u = ud->getUnit(0); fail_unless( u != NULL , NULL ); fail_unless( u->getKind() == UNIT_KIND_MOLE, NULL ); lou = ud->getListOfUnits(); u1 = lou->get(0); fail_unless (u1 == u); delete d; } END_TEST Suite * create_suite_TestReadFromFile7 (void) { Suite *suite = suite_create("test-data/l2v3-all.xml"); TCase *tcase = tcase_create("test-data/l2v3-all.xml"); tcase_add_test(tcase, test_read_l2v3_all); suite_add_tcase(suite, tcase); return suite; } END_C_DECLS
29.715517
111
0.577778
dchandran
77d6b3536812d99301b4c7618c41a759ea9defee
1,017
cpp
C++
src/readraw.cpp
gmke/zernike
0880b0ae43cbb051afb54aa5decc246252467a8d
[ "MIT" ]
4
2019-05-15T09:28:48.000Z
2021-06-16T17:28:29.000Z
src/readraw.cpp
gmke/zernike
0880b0ae43cbb051afb54aa5decc246252467a8d
[ "MIT" ]
null
null
null
src/readraw.cpp
gmke/zernike
0880b0ae43cbb051afb54aa5decc246252467a8d
[ "MIT" ]
1
2019-01-17T13:30:49.000Z
2019-01-17T13:30:49.000Z
# include <libraw/libraw.h> # include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] NumericMatrix readraw(CharacterVector fname, NumericVector channels) { LibRaw rawimage; int ret=0; int i, j; std::string fn = as<std::string>(fname); ret=rawimage.open_file(fn.c_str()); if (ret != 0) stop("LibRaw returned error"); ret = rawimage.unpack(); ret = rawimage.subtract_black(); int h = rawimage.imgdata.sizes.height; int w = rawimage.imgdata.sizes.width; // set gamma slopes to 1 and color space to raw rawimage.imgdata.params.gamm[0] = 1.0; rawimage.imgdata.params.gamm[1] = 1.0; rawimage.imgdata.params.output_color = 0; ret = rawimage.dcraw_process(); if (ret != 0) stop("LibRaw returned error"); NumericMatrix img(w, h); channels = channels/sum(channels); for (int k=0; k<h*w; k++) { i = k % w; j = k / w; img(i, j) = 0; for (int l=0; l<3; l++) { img(i, j) += channels(l) * (double) rawimage.imgdata.image[k][l]; } } return img; }
25.425
71
0.629302
gmke
77e16fa3fbc6dc6a3613b94a4ec0268a7bd40243
1,519
cc
C++
base/error.cc
ifwe/tagged_test
02b5a9373962b4c857b6f73b8d0efe847d0e9799
[ "Apache-2.0" ]
null
null
null
base/error.cc
ifwe/tagged_test
02b5a9373962b4c857b6f73b8d0efe847d0e9799
[ "Apache-2.0" ]
null
null
null
base/error.cc
ifwe/tagged_test
02b5a9373962b4c857b6f73b8d0efe847d0e9799
[ "Apache-2.0" ]
null
null
null
/* This file is licensed under the terms of the Apache License, Version 2.0 * Please see the file COPYING for the full text of this license * * Copyright 2010-2011 Tagged */ /* <base/error.cc> Implements <base/error.h>. */ #include <base/error.h> #include <cstdlib> #include <iostream> #include <sstream> #include <base/code_location.h> using namespace std; using namespace Base; void TError::Abort(const TCodeLocation &code_location) { cerr << "aborting at " << code_location << endl; abort(); } TError::TError() : WhatBuffer(0), WhatPtr("PostCtor() was not called") {} void TError::PostCtor(const TCodeLocation &code_location, const char *details) { assert(this); assert(&code_location); try { CodeLocation = code_location; stringstream out_strm; out_strm << CodeLocation << ", " << GetClassName(); if (details) { out_strm << ", " << details; } WhatBuffer = out_strm.str(); WhatPtr = WhatBuffer.c_str(); } catch (...) { Abort(HERE); } } void TError::PostCtor(const TCodeLocation &code_location, const char *details_start, const char* details_end) { assert(this); assert(&code_location); try { CodeLocation = code_location; stringstream out_strm; out_strm << CodeLocation << ", " << GetClassName(); if (details_start) { out_strm << ", "; out_strm.write(details_start, details_end - details_start); } WhatBuffer = out_strm.str(); WhatPtr = WhatBuffer.c_str(); } catch (...) { Abort(HERE); } }
23.369231
111
0.65767
ifwe
77e18c4760e88a5beeacc54db569ee874a580847
1,501
cpp
C++
leetcode/Array Pair Sum Divisibility Problem.cpp
vkashkumar/Competitive-Programming
c457e745208c0ca3e45b1ffce254a21504533f51
[ "MIT" ]
2
2019-01-30T12:45:18.000Z
2021-05-06T19:02:51.000Z
leetcode/Array Pair Sum Divisibility Problem.cpp
vkashkumar/Competitive-Programming
c457e745208c0ca3e45b1ffce254a21504533f51
[ "MIT" ]
null
null
null
leetcode/Array Pair Sum Divisibility Problem.cpp
vkashkumar/Competitive-Programming
c457e745208c0ca3e45b1ffce254a21504533f51
[ "MIT" ]
3
2020-10-02T15:42:04.000Z
2022-03-27T15:14:16.000Z
// https://practice.geeksforgeeks.org/problems/array-pair-sum-divisibility-problem/0 #include<bits/stdc++.h> using namespace std; #define fast ios::sync_with_stdio(false);cin.tie(0) #define pb push_back #define digit(x) floor(log10(x))+1 #define mod 1000000007 #define endl "\n" #define int long long #define matrix vector<vector<int> > #define vi vector<int> #define pii pair<int,int> #define vs vector<string> #define vp vector<pii> #define test() int t;cin>>t;while(t--) #define all(x) x.begin(),x.end() #define debug(x) cerr << #x << " is " << x << endl; int dx[] = {0, 0, 1, -1}; int dy[] = {1, -1, 0, 0}; const int sz = 100005; void showArr(int *arr, int n){for(int i=0;i<n;i++) cout<<arr[i]<<" ";} //=================================================================// int32_t main(){ fast; test() { int n; cin>>n; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; int k; cin>>k; for(int i=0;i<n;i++) a[i]%=k; unordered_map<int,int> hm; for(int i=0;i<n;i++) hm[a[i]]++; int cnt = 0, ans = 0; for(int i=0;i<n;i++) { if(a[i]==0) { ans++; continue; } if(hm[k-a[i]]>0) { cnt++; hm[a[i]]--; hm[k-a[i]]--; } } cnt+=(ans/2); if(n&1) cout<<"False"<<endl; else if(cnt==n/2) cout<<"True"<<endl; else cout<<"False"<<endl; } return 0; }
26.803571
84
0.471019
vkashkumar
77ee7f92982342419476201213006b887b3e1014
1,536
cpp
C++
Online Judges/URI/2519/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
64
2019-03-17T08:56:28.000Z
2022-01-14T02:31:21.000Z
Online Judges/URI/2519/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
1
2020-12-24T07:16:30.000Z
2021-03-23T20:51:05.000Z
Online Judges/URI/2519/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
19
2019-05-25T10:48:16.000Z
2022-01-07T10:07:46.000Z
#include <iostream> #include <vector> using namespace std; vector<vector<int> > fk; int n, m; int query(int x, int y) { int sum = 0; for (int i = x; i > 0; i-=(i&(-i))) { for (int j = y; j > 0; j-=(j&(-j))) { sum+=fk[i][j]; } } return sum; } int query(int x1, int y1, int x2, int y2) { return (query(x2, y2) - query(x2, y1 - 1) - query(x1 - 1, y2) + query(x1 - 1, y1 - 1)); } void update(int x, int y, int value, int previous) { for (int i = x; i < n+1; i+=(i&(-i))) { for (int j = y; j < m+1; j+=(j&(-j))) { fk[i][j]-=previous; fk[i][j]+=value; } } } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int r, q, x1, y1, x2, y2; vector<vector<int> > v; while(cin >> n >> m) { v.assign(n, vector<int>(m, 0)); fk.assign(n + 1, vector<int>(m + 1, 0)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> v[i][j]; } } // constructing FK 2d for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { update(i + 1, j + 1, v[i][j], 0); } } cin >> q; while(q--) { cin >> r >> x1 >> y1 >> x2 >> y2; if (r == 0) { update(x1, y1, 0, 1); update(x2, y2, 1, 0); } else { cout << query(x1, y1, x2, y2) << endl; } } } return 0; }
21.633803
91
0.378906
AnneLivia
77eeb386d98a76d27a7d0f3e4f754033926db7a4
1,703
cpp
C++
ae5b2.cpp
ohmyjons/SPOJ-1
870ae3b072a3fbc89149b35fe5649a74512a8f60
[ "Unlicense" ]
264
2015-01-08T10:07:01.000Z
2022-03-26T04:11:51.000Z
ae5b2.cpp
ohmyjons/SPOJ-1
870ae3b072a3fbc89149b35fe5649a74512a8f60
[ "Unlicense" ]
17
2016-04-15T03:38:07.000Z
2020-10-30T00:33:57.000Z
ae5b2.cpp
ohmyjons/SPOJ-1
870ae3b072a3fbc89149b35fe5649a74512a8f60
[ "Unlicense" ]
127
2015-01-08T04:56:44.000Z
2022-02-25T18:40:37.000Z
// 2009-12-30 //Dynamic max prefix sum query with segment tree. O((n+m) lg n) #include <iostream> #include <algorithm> #include <functional> using namespace std; static int sum[1000000]; static int max_psum[1000000]; void recalc(int root) { sum[root]=sum[root<<1]+sum[1+(root<<1)]; max_psum[root]=max(max_psum[root<<1], sum[root<<1]+max_psum[1+(root<<1)]); } void atomic_upd(int root,int val) { sum[root]=val; max_psum[root]=val>0?val:0; } template<class RAI> void upd(int root,RAI begin,RAI end,RAI pos,int val) { if (end-begin==1) atomic_upd(root,val); else { RAI mid=begin+(end-begin)/2; if (pos<mid) upd(root<<1,begin,mid,pos,val); else upd(1+(root<<1),mid,end,pos,val); recalc(root); } } template<class RAI> void build_tree(int root,RAI begin,RAI end) { if (end-begin==1) atomic_upd(root,*begin); else { RAI mid=begin+(end-begin)/2; build_tree(root<<1,begin,mid); build_tree(1+(root<<1),mid,end); recalc(root); } } int in() { int res=0; char c; do c=getchar_unlocked(); while (c<=32); do { res=(res<<1)+(res<<3)+c-'0'; c=getchar_unlocked(); } while (c>32); return res; } int main() { int N,i,m,idx,val; static int a[200001],b[200001],c[200001],d[200001]; N=in(); for (i=1; i<=N; i++) b[i]=a[i]=in(); sort(b+1,b+N+1); c[0]=0; for (i=1; i<=N; i++) c[b[i]]=i; for (i=1; i<=N; i++) if (!c[i]) c[i]=c[i-1]; for (i=1; i<=N; i++) d[i]=c[i]-c[i-1]-1; build_tree(1,d,d+N+1); printf(max_psum[1]>0?"NIE\n":"TAK\n"); m=in(); while (m--) { idx=in(); val=in(); upd(1,d,d+N+1,d+val,d[val]+1); upd(1,d,d+N+1,d+a[idx],d[a[idx]]-1); d[val]++; d[a[idx]]--; a[idx]=val; printf(max_psum[1]>0?"NIE\n":"TAK\n"); } return 0; }
18.117021
63
0.590722
ohmyjons
77efb79e999805f6584f5ca06d8ee4d49512a27d
4,299
cpp
C++
TDD/tdd_instance_json.cpp
gxhblues/TDD
a1f0dce58a5caeb67e21cf79513df10879a7926a
[ "MIT" ]
null
null
null
TDD/tdd_instance_json.cpp
gxhblues/TDD
a1f0dce58a5caeb67e21cf79513df10879a7926a
[ "MIT" ]
null
null
null
TDD/tdd_instance_json.cpp
gxhblues/TDD
a1f0dce58a5caeb67e21cf79513df10879a7926a
[ "MIT" ]
null
null
null
#include "pch.h" #include "tdd_instance.h" #include "tdd_shape_box.h" #include "tdd_shape_connection.h" #include "tdd_shape_text.h" #include "tdd_shape_free.h" #include "tdd_shape_table.h" #include "tdd_shape_qrcode.h" #include "tdd_instance_action.h" using namespace std; namespace TDD { void to_json(json& j, const Instance& instance) { if (!instance.shapes.empty()) { json js; for (auto& s : instance.shapes) { json jj; s->to_json(jj); js.push_back(jj); } j["shapes"] = js; } if (!instance.groups.empty()) { json jgs; for (auto& g : instance.groups) { json jg; for (auto& s : g) { jg.push_back(s->GetID()); } jgs.push_back(jg); } j["groups"] = jgs; } } void from_json(const json& j, Instance& instance) { if (!j.contains("shapes")) { return; } vector<json> lines; for (auto& sj : j.at("shapes")) { auto t = sj.at("type").get<string>(); if (t == "Line") { if (sj["from"].contains("id") || sj["to"].contains("id")) lines.emplace_back(sj); else { //standalone line do not have reference shape, so it can construct directly. auto s = make_shared<Shape::Connection>(); s->from_json(sj, instance); instance.AppendConnection(s, false); } } else { shared_ptr<Shape::Shape> s; if (t == "Box") { s = make_shared<Shape::Box>(); } else if (t == "Free") { s = make_shared<Shape::Free>(); } else if (t == "Table") { s = make_shared<Shape::Table>(); } else if (t == "Text") { s = make_shared<Shape::Text>(); } else if (t == "QRCode") { s = make_shared<Shape::QRCode>(); } if (s) { s->from_json(sj, instance); instance.AppendShape(s, false); } } } for (auto& sj : lines) { auto s = make_shared<Shape::Connection>(); s->from_json(sj, instance); instance.AppendConnection(s, false); } //load groups if (j.contains("groups")) { for (auto& jg : j.at("groups")) { std::unordered_set<std::shared_ptr<Shape::Shape>> sg; for (auto sid : jg) { if (sid.is_number_unsigned()) { auto id = sid.get<u32>(); auto s = instance.GetShapeFromID(id); if (s) { sg.insert(s); } } } if (sg.size() < 2) continue; //dummy group //find if any duplicate group bool is_duplicate = false; for (auto& g : instance.groups) { if (g == sg) { is_duplicate = true; break; } } if (!is_duplicate) instance.groups.emplace_back(move(sg)); } } instance.selected_shapes.clear(); instance.selected_shapes_extended.clear(); instance.BuildSelectionCache(); } json Instance::DumpSelectedShapes() { if (selected_shapes.empty()) return {}; auto tmp_instance = make_shared<TDD::Instance>(); for (auto& s : selected_shapes) { tmp_instance->shapes.push_back(s); } unordered_set<shared_ptr<Shape::Shape>> sss; sss.insert(selected_shapes.begin(), selected_shapes.end()); for (auto& g : groups) { bool hit_group = true; for (auto s : g) { if (!sss.count(s)) { hit_group = false; break; } } if (hit_group) { tmp_instance->groups.push_back(g); } } json j = *tmp_instance; return j; } }
23.883333
92
0.442661
gxhblues
77f07abc258021fb1166525aaa4eef7de6d406ca
453
hh
C++
cc/data-fix-guile.hh
acorg/acmacs-whocc
af508bd4651ffb565cd4cf771200540918b1b2bd
[ "MIT" ]
null
null
null
cc/data-fix-guile.hh
acorg/acmacs-whocc
af508bd4651ffb565cd4cf771200540918b1b2bd
[ "MIT" ]
null
null
null
cc/data-fix-guile.hh
acorg/acmacs-whocc
af508bd4651ffb565cd4cf771200540918b1b2bd
[ "MIT" ]
null
null
null
#pragma once #include "acmacs-base/guile.hh" // ---------------------------------------------------------------------- namespace acmacs::data_fix::inline v1 { // pass pointer to this function to guile::init() void guile_defines(); } // namespace acmacs::data_fix::inline v1 // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End:
25.166667
73
0.456954
acorg
77f375dc872dc2f4556b13a9381d538524984220
2,280
hpp
C++
tests/testServer/ServiceComplexTypeRpcs.hpp
hermannolafs/gWhisper
2c7efe80337fad6d7ebe65597d97b2e430ab4cb6
[ "Apache-2.0" ]
47
2019-03-07T18:49:09.000Z
2022-03-16T17:02:20.000Z
tests/testServer/ServiceComplexTypeRpcs.hpp
hermannolafs/gWhisper
2c7efe80337fad6d7ebe65597d97b2e430ab4cb6
[ "Apache-2.0" ]
97
2019-03-06T15:10:50.000Z
2022-03-16T16:30:18.000Z
tests/testServer/ServiceComplexTypeRpcs.hpp
hermannolafs/gWhisper
2c7efe80337fad6d7ebe65597d97b2e430ab4cb6
[ "Apache-2.0" ]
13
2019-03-07T18:49:13.000Z
2022-02-03T07:22:13.000Z
// Copyright 2019 IBM Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "examples.grpc.pb.h" class ServiceComplexTypeRpcs final : public examples::ComplexTypeRpcs::Service { virtual ::grpc::Status echoColorEnum( ::grpc::ServerContext* context, const ::examples::ColorEnum* request, ::examples::ColorEnum* response ) override; virtual ::grpc::Status getNumberOrStringOneOf( ::grpc::ServerContext* context, const ::examples::NumberOrStringChoice* request, ::examples::NumberOrStringOneOf* response ) override; virtual ::grpc::Status sendNumberOrStringOneOf( ::grpc::ServerContext* context, const ::examples::NumberOrStringOneOf* request, ::examples::NumberOrStringChoice* response ) override; virtual ::grpc::Status addAllNumbers( ::grpc::ServerContext* context, const ::examples::RepeatedNumbers* request, ::examples::Uint32* response ) override; virtual ::grpc::Status getLastColor( ::grpc::ServerContext* context, const ::examples::RepeatedColors* request, ::examples::ColorEnum* response ) override; virtual ::grpc::Status echoNumberAndStrings( ::grpc::ServerContext* context, const ::examples::RepeatedNumberAndString* request, ::examples::RepeatedNumberAndString* response ) override; virtual ::grpc::Status mapNumbersToString( ::grpc::ServerContext* context, const ::examples::RepeatedNumbers* request, ::examples::NumberMap* response ) override; };
36.190476
78
0.644298
hermannolafs
77f4a89af8b7d867e75c778ec1916caf14ee76a4
2,668
cc
C++
cefclient/browser/window_test_win.cc
githubzhaoliang/sdkdemoapp_windows
e267ea8ec91f7101f323a6b72ad32bedbb1f034b
[ "BSD-3-Clause" ]
27
2015-01-20T10:25:14.000Z
2018-11-30T08:42:13.000Z
cef/tests/cefclient/browser/window_test_win.cc
lovewitty/miniblink49
c8cb0b50636915d748235eea95a57e24805dc43e
[ "Apache-2.0" ]
2
2019-01-14T00:17:19.000Z
2019-02-03T08:18:49.000Z
cef/tests/cefclient/browser/window_test_win.cc
lovewitty/miniblink49
c8cb0b50636915d748235eea95a57e24805dc43e
[ "Apache-2.0" ]
23
2015-01-09T10:51:00.000Z
2021-01-06T13:06:20.000Z
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. #include "cefclient/browser/window_test.h" namespace client { namespace window_test { namespace { HWND GetRootHwnd(CefRefPtr<CefBrowser> browser) { return ::GetAncestor(browser->GetHost()->GetWindowHandle(), GA_ROOT); } // Toggles the current display state. void Toggle(HWND root_hwnd, UINT nCmdShow) { // Retrieve current window placement information. WINDOWPLACEMENT placement; ::GetWindowPlacement(root_hwnd, &placement); if (placement.showCmd == nCmdShow) ::ShowWindow(root_hwnd, SW_RESTORE); else ::ShowWindow(root_hwnd, nCmdShow); } } // namespace void SetPos(CefRefPtr<CefBrowser> browser, int x, int y, int width, int height) { HWND root_hwnd = GetRootHwnd(browser); // Retrieve current window placement information. WINDOWPLACEMENT placement; ::GetWindowPlacement(root_hwnd, &placement); // Retrieve information about the display that contains the window. HMONITOR monitor = MonitorFromRect(&placement.rcNormalPosition, MONITOR_DEFAULTTONEAREST); MONITORINFO info; info.cbSize = sizeof(info); GetMonitorInfo(monitor, &info); // Make sure the window is inside the display. CefRect display_rect( info.rcWork.left, info.rcWork.top, info.rcWork.right - info.rcWork.left, info.rcWork.bottom - info.rcWork.top); CefRect window_rect(x, y, width, height); ModifyBounds(display_rect, window_rect); if (placement.showCmd == SW_MINIMIZE || placement.showCmd == SW_MAXIMIZE) { // The window is currently minimized or maximized. Restore it to the desired // position. placement.rcNormalPosition.left = window_rect.x; placement.rcNormalPosition.right = window_rect.x + window_rect.width; placement.rcNormalPosition.top = window_rect.y; placement.rcNormalPosition.bottom = window_rect.y + window_rect.height; ::SetWindowPlacement(root_hwnd, &placement); ::ShowWindow(root_hwnd, SW_RESTORE); } else { // Set the window position. ::SetWindowPos(root_hwnd, NULL, window_rect.x, window_rect.y, window_rect.width, window_rect.height, SWP_NOZORDER); } } void Minimize(CefRefPtr<CefBrowser> browser) { Toggle(GetRootHwnd(browser), SW_MINIMIZE); } void Maximize(CefRefPtr<CefBrowser> browser) { Toggle(GetRootHwnd(browser), SW_MAXIMIZE); } void Restore(CefRefPtr<CefBrowser> browser) { ::ShowWindow(GetRootHwnd(browser), SW_RESTORE); } } // namespace window_test } // namespace client
31.761905
80
0.723763
githubzhaoliang
af7ef5a4b85779e17307f454021fbbd2538c491c
3,296
cpp
C++
DotNetExp/HeapTreeNode.cpp
CaledoniaProject/DotNetExp
891d74b08205b29c5daa1fa9ec0c00171ab65f84
[ "MIT" ]
32
2020-08-14T13:39:14.000Z
2022-03-15T03:59:46.000Z
DotNetExp/HeapTreeNode.cpp
CaledoniaProject/DotNetExp
891d74b08205b29c5daa1fa9ec0c00171ab65f84
[ "MIT" ]
2
2020-08-15T00:40:03.000Z
2022-02-07T23:40:57.000Z
DotNetExp/HeapTreeNode.cpp
isabella232/DotNetExp
73d82016c743ef28d703b88fc418804de48644f6
[ "MIT" ]
14
2020-08-15T00:41:03.000Z
2022-02-07T22:42:12.000Z
#include "pch.h" #include "HeapTreeNode.h" #include "SortHelper.h" #include "resource.h" #include "ObjectsTreeNode.h" static const struct { PCWSTR header; int width; int format = LVCFMT_LEFT; } columns[] = { { L"Type Name", 420 }, { L"Method Table", 120, LVCFMT_RIGHT }, { L"Object Count", 100, LVCFMT_RIGHT }, { L"Total Size", 80, LVCFMT_RIGHT }, }; HeapTreeNode::HeapTreeNode(CTreeItem item, DataTarget* dt, int heap) : TreeNodeBase(item), _dt(dt), _heap(heap) { } int HeapTreeNode::GetColumnCount() const { return _countof(columns); } CString HeapTreeNode::GetColumnInfo(int column, int& width, int& format) const { auto& info = columns[column]; width = info.width; format = info.format; return info.header; } int HeapTreeNode::GetRowCount() { return (int)_items.FilteredSize(); } CString HeapTreeNode::GetColumnText(int row, int col) const { auto& item = _items[row]; CString text; switch (col) { case 0: return item.TypeName; case 1: text.Format(L"0x%llX", item.MethodTable); break; case 2: text.Format(L"%u", item.ObjectCount); break; case 3: text.Format(L"%lld", item.TotalSize); break; } return text; } bool HeapTreeNode::InitList() { CWaitCursor wait; _items.Set(_dt->GetHeapStats(_heap)); ApplyFilter(m_CurrentFilter); return true; } void HeapTreeNode::TermList() { _items.clear(); } void HeapTreeNode::SortList(int col, bool asc) { _items.Sort([&](const auto& t1, const auto& t2) { switch (col) { case 0: return SortHelper::SortStrings(t1.TypeName, t2.TypeName, asc); case 1: return SortHelper::SortNumbers(t1.MethodTable, t2.MethodTable, asc); case 2: return SortHelper::SortNumbers(t1.ObjectCount, t2.ObjectCount, asc); case 3: return SortHelper::SortNumbers(t1.TotalSize, t2.TotalSize, asc); } return false; }); } int HeapTreeNode::GetRowIcon(int row) const { auto& item = _items[row]; switch (item.Type) { case OBJ_STRING: return 14; case OBJ_ARRAY: return 19; case OBJ_FREE: return 20; } if (_dt->GetMethodTableInfo(item.MethodTable).BaseName == L"System.ValueType") return 13; return 12; } IFilterBarCallback* HeapTreeNode::GetFilterBarCallback(IFilterBar* fb) { return this; } std::pair<UINT, int> HeapTreeNode::GetListItemContextMenu(int selectedItem, int column) { if (selectedItem >= 0) { _selected = selectedItem; return { IDR_CONTEXT, 0 }; } return { 0,0 }; } void HeapTreeNode::HandleCommand(UINT cmd) { switch (cmd) { case ID_TYPE_VIEWOBJECTS: auto& item = _items[_selected]; auto node = GetTreeItem().GetChild(); CString text; while (node) { node.GetText(text); if (text == item.TypeName) { node.Select(); return; } node = node.GetNext(TVGN_NEXT); } node = GetTreeItem().InsertAfter(item.TypeName, TVI_LAST, 16); node.SetData(reinterpret_cast<DWORD_PTR>(new ObjectsTreeNode(node, _dt, item.MethodTable))); GetTreeItem().SortChildren(FALSE); node.Select(); break; } } int HeapTreeNode::ApplyFilter(const CString& text) { m_CurrentFilter = text; if (text.IsEmpty()) _items.Filter(nullptr); else { CString ltext(text); ltext.MakeLower(); _items.Filter([&](auto& info) -> bool { CString copy(info.TypeName); copy.MakeLower(); return copy.Find(ltext) >= 0; }); } return (int)_items.FilteredSize(); }
24.414815
113
0.694175
CaledoniaProject
af90d3a5e6bbf5d6bb27288b8c1db00e0520d99f
143
cpp
C++
GoFish/Card.cpp
uaineteine/GoFish
8140428e8ebb4a2cdb07b65c4e2f90a2236b0cca
[ "MIT" ]
null
null
null
GoFish/Card.cpp
uaineteine/GoFish
8140428e8ebb4a2cdb07b65c4e2f90a2236b0cca
[ "MIT" ]
null
null
null
GoFish/Card.cpp
uaineteine/GoFish
8140428e8ebb4a2cdb07b65c4e2f90a2236b0cca
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Card.h" Card::Card(int value, int suit) { Num = value; Suit = suit; } Card::~Card() { } int Num; int Suit;
8.411765
31
0.601399
uaineteine
af90fcc67631fc6346ca4ef1f70c0e6b5d069d23
331
cpp
C++
Difficulty 3/alex_and_barb.cpp
BrynjarGeir/Kattis
a151972cbae3db04a8e6764d5fa468d0146c862b
[ "MIT" ]
null
null
null
Difficulty 3/alex_and_barb.cpp
BrynjarGeir/Kattis
a151972cbae3db04a8e6764d5fa468d0146c862b
[ "MIT" ]
null
null
null
Difficulty 3/alex_and_barb.cpp
BrynjarGeir/Kattis
a151972cbae3db04a8e6764d5fa468d0146c862b
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int k, m, n; bool alexs_turn = true; cin >> k >> m >> n; while(k) { if(k >= m + n) k -= m; else if(k > n) k -= n; else k = 0; alexs_turn = !alexs_turn; } if(!alexs_turn) cout << "Barb"; else cout << "Alex"; }
16.55
35
0.453172
BrynjarGeir
af91378bfcd5f32650d5f4059b9ca690e09952ca
2,094
hh
C++
src/input/Touchpad.hh
lutris/openmsx
91ed35400c7b4c8c460004710736af9abc4dde29
[ "Naumen", "Condor-1.1", "MS-PL" ]
5
2015-02-27T21:42:28.000Z
2021-10-10T23:36:08.000Z
src/input/Touchpad.hh
lutris/openmsx
91ed35400c7b4c8c460004710736af9abc4dde29
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/input/Touchpad.hh
lutris/openmsx
91ed35400c7b4c8c460004710736af9abc4dde29
[ "Naumen", "Condor-1.1", "MS-PL" ]
2
2015-06-15T09:57:56.000Z
2017-05-14T01:11:48.000Z
#ifndef TOUCHPAD_HH #define TOUCHPAD_HH #include "JoystickDevice.hh" #include "MSXEventListener.hh" #include "StateChangeListener.hh" #include <memory> namespace openmsx { class MSXEventDistributor; class StateChangeDistributor; class CommandController; class StringSetting; class TclObject; class Touchpad : public JoystickDevice, private MSXEventListener , private StateChangeListener { public: Touchpad(MSXEventDistributor& eventDistributor, StateChangeDistributor& stateChangeDistributor, CommandController& commandController); virtual ~Touchpad(); template<typename Archive> void serialize(Archive& ar, unsigned version); private: void createTouchpadStateChange(EmuTime::param time, byte x, byte y, bool touch, bool button); void parseTransformMatrix(const TclObject& value); void transformCoords(int& x, int& y); // Pluggable virtual const std::string& getName() const; virtual string_ref getDescription() const; virtual void plugHelper(Connector& connector, EmuTime::param time); virtual void unplugHelper(EmuTime::param time); // JoystickDevice virtual byte read(EmuTime::param time); virtual void write(byte value, EmuTime::param time); // MSXEventListener virtual void signalEvent(const std::shared_ptr<const Event>& event, EmuTime::param time); // StateChangeListener virtual void signalStateChange(const std::shared_ptr<StateChange>& event); virtual void stopReplay(EmuTime::param time); MSXEventDistributor& eventDistributor; StateChangeDistributor& stateChangeDistributor; std::unique_ptr<StringSetting> transformSetting; double m[2][3]; // transformation matrix EmuTime start; // last time when CS switched 0->1 int hostX, hostY; // host state byte hostButtons; // byte x, y; // msx state (different from host state bool touch, button; // during replay) byte shift; // shift register to both transmit and receive data byte channel; // [0..3] 0->x, 3->y, 1,2->not used byte last; // last written data, to detect transitions }; } // namespace openmsx #endif
29.492958
75
0.748329
lutris
af96a56d2b84496b743017abe3f9e85dd8052cd3
11,760
ipp
C++
include/External/stlib/packages/numerical/random/discrete/DiscreteGeneratorBinned.ipp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
include/External/stlib/packages/numerical/random/discrete/DiscreteGeneratorBinned.ipp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
include/External/stlib/packages/numerical/random/discrete/DiscreteGeneratorBinned.ipp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
// -*- C++ -*- #if !defined(__numerical_random_DiscreteGeneratorBinned_ipp__) #error This file is an implementation detail of DiscreteGeneratorBinned. #endif namespace numerical { template<class Generator> inline typename DiscreteGeneratorBinned<Generator>::result_type DiscreteGeneratorBinned<Generator>:: operator()() { const Number efficiency = computeEfficiency(); // If the efficiency is very low (it has fallen below the minimum allow // efficiency) or if the efficiency is low (below the target efficiency) // and it is time for a rebuild. if (efficiency < getMinimumEfficiency() || (efficiency < getTargetEfficiency() && _stepsUntilNextRebuild <= 0)) { rebuild(); } // If it is time for a repair. else if (_stepsUntilNextRepair <= 0) { repair(); } // Loop until the point is not rejected. for (;;) { unsigned random = (*_discreteUniformGenerator)(); // Use the first bits for indexing. unsigned index = random & IndexMask(); // Use the remaining bits for the height deviate. unsigned heightGenerator = random >> IndexBits(); Number height = heightGenerator * _heightUpperBound * MaxHeightInverse(); // If we have a hit for the PMF's in this bin. if (height < _binnedPmf[index]) { // Do a linear search to find the PMF that we hit. std::size_t pmfIndex = _deviateIndices[index]; for (; pmfIndex < _deviateIndices[index + 1] - 1; ++pmfIndex) { height -= _pmf[pmfIndex]; if (height <= 0) { break; } } return _permutation[pmfIndex]; } } } // Initialize the probability mass function. template<class Generator> template<typename ForwardIterator> inline void DiscreteGeneratorBinned<Generator>:: initialize(ForwardIterator begin, ForwardIterator end) { // Build the array for the PMF. _pmf.resize(std::distance(begin, end)); std::copy(begin, end, _pmf.begin()); _permutation.resize(_pmf.size()); _rank.resize(_pmf.size()); _binIndices.resize(_pmf.size() + 1); // Initialize so the efficiency appears to be zero. _pmfSum = 0; _heightUpperBound = 1; // Rebuild the data structure by sorting the PMF and packing them into bins. rebuild(); } // Rebuild the bins. template<class Generator> inline void DiscreteGeneratorBinned<Generator>:: rebuild() { _stepsUntilNextRebuild = _stepsBetweenRebuilds; // Rebuilding also repairs the data structure, so we reset that counter // as well. _stepsUntilNextRepair = _stepsBetweenRepairs; // // Sort the PMF array in descending order. // _pmfSum = sum(_pmf); for (std::size_t i = 0; i != _permutation.size(); ++i) { _permutation[i] = i; } // Sort in descending order. ads::sortTogether(_pmf.begin(), _pmf.end(), _permutation.begin(), _permutation.end(), std::greater<Number>()); // Compute the ranks. for (std::size_t i = 0; i != _permutation.size(); ++i) { _rank[_permutation[i]] = i; } packIntoBins(); _heightUpperBound = *std::max_element(_binnedPmf.begin(), _binnedPmf.end()); } // Set the probability mass function with the specified index. template<class Generator> inline void DiscreteGeneratorBinned<Generator>:: setPmf(const std::size_t index, const Number value) { // The index in the re-ordered PMF. const std::size_t i = _rank[index]; // If the value has not changed, do nothing. I need this check; otherwise // the following branch could be expensive. if (_pmf[i] == value) { return; } // If the PMF has become zero. (It was not zero before.) if (value == 0) { // Set the PMF to zero. _pmf[i] = 0; // Repair the data structure. This is necessary to ensure that the // binned PMF are correct. They must be exactly zero. Likewize, the // sum of the PMF may have become zero. repair(); return; } // The remainder of this function is the standard case. Update the data // structure using the difference between the new and old values. const Number difference = value - _pmf[i]; // Update the sum of the PMF. _pmfSum += difference; // Update the PMF array. _pmf[i] = value; // // Update the binned PMF. // const std::size_t binIndex = _binIndices[i]; _binnedPmf[binIndex] += difference; // Update the upper bound on the bin height. if (_binnedPmf[binIndex] > _heightUpperBound) { _heightUpperBound = _binnedPmf[binIndex]; } // Fix the bin if necessary. if (i < _splittingEnd && _binnedPmf[binIndex] < 0) { fixBin(binIndex); } --_stepsUntilNextRepair; --_stepsUntilNextRebuild; } // Update the data structure following calls to setPmfWithoutUpdating() . template<class Generator> inline void DiscreteGeneratorBinned<Generator>:: updatePmf() { // // Compute the binned PMF. // std::fill(_binnedPmf.begin(), _binnedPmf.end(), 0); // First do the PMF's that are split over multiple bins. for (std::size_t i = 0; i != _splittingEnd; ++i) { // Split the PMF over a number of bins. const Number height = _pmf[i] / (_binIndices[i + 1] - _binIndices[i]); for (std::size_t j = _binIndices[i]; j != _binIndices[i + 1]; ++j) { _binnedPmf[j] = height; } } // Then do the PMF's that sit in a single bin. for (std::size_t i = _splittingEnd; i != _pmf.size(); ++i) { _binnedPmf[_binIndices[i]] += _pmf[i]; } // Compute the sum of the PMF. // Choose the more efficient method. if (_pmf.size() < _binnedPmf.size()) { _pmfSum = std::accumulate(_pmf.begin(), _pmf.end(), 0.0); } else { // Sum over the bins. _pmfSum = std::accumulate(_binnedPmf.begin(), _binnedPmf.end(), 0.0); } // Compute the upper bound on the bin height. _heightUpperBound = *std::max_element(_binnedPmf.begin(), _binnedPmf.end()); } // Count the number of required bins for the given maximum height. template<typename T, typename ForwardIterator> inline std::size_t countBins(ForwardIterator begin, ForwardIterator end, const T height) { const T inverse = 1.0 / height; std::size_t count = 0; // Count the splitting bins. while (begin != end && *begin > height) { count += std::size_t(*begin * inverse) + 1; ++begin; } // Count the stacking bins. // The following loop is a little complicated because I must allow for the // possibility of blocks with zero height. T currentHeight = -1; while (begin != end) { // If we are starting a new bin. if (currentHeight == -1) { // Add the first block to the bin. currentHeight = *begin; // We are using a new bin. ++count; // Move to the next block. ++begin; } else { // Try adding a block to the current bin. currentHeight += *begin; // If we can fit it in the current bin. if (currentHeight <= height) { // Move to the next block. ++begin; } else { // Start a new bin. currentHeight = -1; } } } return count; } // Compute a bin height such that all the blocks will fit in the bins. template<typename T, typename ForwardIterator> inline T computeBinHeight(ForwardIterator begin, ForwardIterator end, const std::size_t NumberOfBins) { const T content = std::accumulate(begin, end, T(0)); T factor = 1; T height; do { factor += 0.1; height = factor * content / NumberOfBins; } while (countBins(begin, end, height) > NumberOfBins); return height; } // Pack the block into bins. template<class Generator> inline void DiscreteGeneratorBinned<Generator>:: packIntoBins() { const Number height = computeBinHeight<Number>(_pmf.begin(), _pmf.end(), NumberOfBins); const Number inverse = 1.0 / height; // Empty the bins. std::fill(_binnedPmf.begin(), _binnedPmf.end(), 0); std::fill(_deviateIndices.begin(), _deviateIndices.end(), _pmf.size()); // Pack the blocks that are split across multiple bins. std::size_t pmfIndex = 0, binIndex = 0; for (; pmfIndex != _pmf.size() && _pmf[pmfIndex] > height; ++pmfIndex) { _binIndices[pmfIndex] = binIndex; const std::size_t count = std::size_t(_pmf[pmfIndex] * inverse) + 1; const Number binHeight = _pmf[pmfIndex] / count; for (std::size_t i = 0; i != count; ++i) { _deviateIndices[binIndex] = pmfIndex; _binnedPmf[binIndex] = binHeight; ++binIndex; } } // Record the end of the PMF's that are split accross multiple bins. _splittingEnd = pmfIndex; // // Pack the stacking bins. // // If there are blocks left to stack. if (pmfIndex != _pmf.size()) { // Put a block in the current bin. _binIndices[pmfIndex] = binIndex; _deviateIndices[binIndex] = pmfIndex; _binnedPmf[binIndex] = _pmf[pmfIndex]; ++pmfIndex; // Pack the rest of the blocks. Number newHeight; while (pmfIndex != _pmf.size()) { // Try adding a block to the current bin. newHeight = _binnedPmf[binIndex] + _pmf[pmfIndex]; // If we can fit it in the current bin. if (newHeight <= height) { // Add the block to the bin. _binIndices[pmfIndex] = binIndex; _binnedPmf[binIndex] = newHeight; // Move to the next block. ++pmfIndex; } else { // Put the block in the next bin. ++binIndex; _binIndices[pmfIndex] = binIndex; _deviateIndices[binIndex] = pmfIndex; _binnedPmf[binIndex] = _pmf[pmfIndex]; ++pmfIndex; } } // Move to an empty bin. ++binIndex; } // The guard value. _binIndices[pmfIndex] = binIndex; } template<class Generator> inline void DiscreteGeneratorBinned<Generator>:: fixBin(const std::size_t binIndex) { for (std::size_t j = binIndex + 1; _deviateIndices[binIndex] == _deviateIndices[j] && _binnedPmf[binIndex] < 0; ++j) { _binnedPmf[binIndex] += _binnedPmf[j]; _binnedPmf[j] = 0; } } // Print information about the data structure. template<class Generator> inline void DiscreteGeneratorBinned<Generator>:: print(std::ostream& out) const { out << "Bin data:\n\n" << "Height upper bound = " << _heightUpperBound << "\n" << "Binned PMF = " << _binnedPmf << "\n" << "Deviate indices = " << _deviateIndices << "\n" << "\nPMF data:\n\n" << "PMF sum = " << _pmfSum << "\n" << "Splitting end = " << _splittingEnd << "\n" << "PMF = \n" << _pmf << '\n' << "Permutation = \n" << _permutation << '\n' << "Rank = \n" << _rank << '\n' << "Bin indices = " << _binIndices << '\n' << "Steps between repairs = " << _stepsBetweenRepairs << "\n" << "Steps until next repair = " << _stepsUntilNextRepair << "\n" << "Steps between rebuilds = " << _stepsBetweenRebuilds << "\n" << "Steps until next rebuild = " << _stepsUntilNextRebuild << "\n" << "Target efficiency = " << _targetEfficiency << "\n" << "Minimum efficiency = " << _minimumEfficiency << "\n"; } } // namespace numerical
31.36
80
0.597789
bxl295
af97bbd12365e535c1e9f5f1944b6c55bb3b4b92
1,375
cpp
C++
LeetCode/Problems/0145_Binary_Tree_Postorder_Traversal/binary_tree_postorder_traversal.cpp
jocodoma/coding-interview-prep
f7f06be0bc5687c376b753ba3fa46b07412eeb80
[ "MIT" ]
null
null
null
LeetCode/Problems/0145_Binary_Tree_Postorder_Traversal/binary_tree_postorder_traversal.cpp
jocodoma/coding-interview-prep
f7f06be0bc5687c376b753ba3fa46b07412eeb80
[ "MIT" ]
null
null
null
LeetCode/Problems/0145_Binary_Tree_Postorder_Traversal/binary_tree_postorder_traversal.cpp
jocodoma/coding-interview-prep
f7f06be0bc5687c376b753ba3fa46b07412eeb80
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode* root) { // return recursiveTraversal(root); return iterativeTraversal(root); } // time complexity: O(n) // space complexity: in average is O(log n), but the worst case is O(n) vector<int> recursiveTraversal(TreeNode* root){ recursiveHelper(root); return sol; } void recursiveHelper(TreeNode* node){ if(!node) return; recursiveHelper(node->left); recursiveHelper(node->right); sol.push_back(node->val); } // time complexity: O(2n) = O(n), space complexity: O(2n) = O(n) vector<int> iterativeTraversal(TreeNode* root){ if(!root) return {}; std::stack<TreeNode*> s1, s2; s1.push(root); while(!s1.empty()){ TreeNode *node = s1.top();s1.pop(); s2.push(node); if(node->left) s1.push(node->left); if(node->right) s1.push(node->right); } while(!s2.empty()){ TreeNode *node = s2.top();s2.pop(); sol.push_back(node->val); } return sol; } private: vector<int> sol; };
24.553571
75
0.550545
jocodoma
af9d4644c7ff69a1b9faee999a0e125238840882
5,951
hpp
C++
src/csalt/src/userfunutils/FunctionOutputData.hpp
IncompleteWorlds/GMAT_2020
624de54d00f43831a4d46b46703e069d5c8c92ff
[ "Apache-2.0" ]
null
null
null
src/csalt/src/userfunutils/FunctionOutputData.hpp
IncompleteWorlds/GMAT_2020
624de54d00f43831a4d46b46703e069d5c8c92ff
[ "Apache-2.0" ]
null
null
null
src/csalt/src/userfunutils/FunctionOutputData.hpp
IncompleteWorlds/GMAT_2020
624de54d00f43831a4d46b46703e069d5c8c92ff
[ "Apache-2.0" ]
null
null
null
//------------------------------------------------------------------------------ // FunctionOutputData //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2020 United States Government as represented by the // Administrator of The National Aeronautics and Space Administration. // All Other Rights Reserved. // // Author: Wendy Shoan / NASA // Created: 2015.07.13 // /** * From original MATLAB prototype: * Author: S. Hughes. steven.p.hughes@nasa.gov * * This class stores user function data for the optimal control * problem. This data includes the function values and Jacobians. * The data on this class is used to form NLP function values. * */ //------------------------------------------------------------------------------ #ifndef FunctionOutputData_hpp #define FunctionOutputData_hpp #include "csaltdefs.hpp" #include "Rvector.hpp" #include "Rmatrix.hpp" #include "UserFunction.hpp" class FunctionOutputData { public: // class methods FunctionOutputData(); FunctionOutputData(const FunctionOutputData &copy); FunctionOutputData& operator=(const FunctionOutputData &copy); virtual ~FunctionOutputData(); /// Sets the function descriptions virtual void SetFunctionNames(StringArray fNames); /// Sets number of functions and function values virtual void SetFunctionValues(Integer numFuncs, const Rvector &funcValues); /// Sets function values virtual void SetFunctions(const Rvector &funcValues); /// Sets the number of functions virtual void SetNumFunctions(Integer numFuncs); /// Sets initialization flag virtual void SetIsInitializing(bool isInit); /// Sets the upper bounds virtual bool SetUpperBounds(const Rvector &toUpper); /// Sets the lower bounds virtual bool SetLowerBounds(const Rvector &toLower); bool SetNLPData(Integer meshIdx, Integer stageIdx, const IntegerArray &stateIdxs, const IntegerArray &controlIdxs, const IntegerArray &staticIdxs); DEPRECATED(bool SetStateJacobian(const Rmatrix& sj)); DEPRECATED(bool SetControlJacobian(const Rmatrix& cj)); DEPRECATED(bool SetTimeJacobian(const Rmatrix& tj)); DEPRECATED(const Rmatrix& GetStateJacobian()); DEPRECATED(const Rmatrix& GetControlJacobian()); DEPRECATED(const Rmatrix& GetTimeJacobian()); DEPRECATED(bool HasUserStateJacobian()); DEPRECATED(bool HasUserControlJacobian()); DEPRECATED(bool HasUserTimeJacobian()); bool SetJacobian(UserFunction::JacobianType jacType, const Rmatrix& j); const Rmatrix& GetJacobian(UserFunction::JacobianType jacType); bool HasUserJacobian(UserFunction::JacobianType jacType); std::vector<bool> HasUserJacobian(); const IntegerArray& GetStateIdxs(); const IntegerArray& GetControlIdxs(); // YK mod static vars const IntegerArray& GetStaticIdxs(); Integer GetMeshIdx(); Integer GetStageIdx(); /// Does it have a user function? virtual bool HasUserFunction() const; /// Returns the number of functions virtual Integer GetNumFunctions() const; /// returns the function descriptions virtual const StringArray& GetFunctionNames() const; /// returns array of function values virtual const Rvector& GetFunctionValues() const; /// Returns the array of upper bounds virtual const Rvector& GetUpperBounds(); /// Returns the array of lower bounds virtual const Rvector& GetLowerBounds(); /// Have the bounds been set? virtual bool BoundsSet(); /// Is it initializing? virtual bool IsInitializing() const; protected: /// indicates if the user has defined data of this type bool hasUserFunction; /// indicates of the user has provided state Jacobian //bool hasUserStateJacobian; /// indicates of the user has provided control Jacobian //bool hasUserControlJacobian; /// indicates of the user has provided time Jacobian //bool hasUserTimeJacobian; std::vector<bool> hasJacobian; /// mesh index Integer meshIndex; /// stage index Integer stageIndex; /// state indeces in phase decision vector IntegerArray stateIndexes; /// control indeces in phase decision vector IntegerArray controlIndexes; /// static var indices in phase decision vector; YK mod static vars IntegerArray staticIndexes; /// Jacobian of the function wrt state //Rmatrix stateJacobian; /// Jacobian of the function wrt control //Rmatrix controlJacobian; /// Jacobian of the function wrt time //Rmatrix timeJacobian; std::map<UserFunction::JacobianType, Rmatrix> jacobian; /// indicates if it is initializing or not. Note, /// some data can optionally be set by the user, and if not provided by user /// the system must fill it in. What is/is not provided by user is /// determined during intialization and flags are set accordingly at /// that time. bool isInitializing; /// the function values Rvector functionValues; /// number of functions Integer numFunctions; /// upper bounds on function values Rvector upperBounds; /// lower bounds on function values Rvector lowerBounds; /// String description of function values StringArray functionNames; /// Have the bounds on the function values been set? bool boundsSet; }; #endif // FunctionOutputData_hpp
36.286585
89
0.631995
IncompleteWorlds
af9e5c8a0b386c5ed63691799377fca378e9db67
4,648
cpp
C++
src/prod/src/Management/healthmanager/IHealthJobItem.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/Management/healthmanager/IHealthJobItem.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/Management/healthmanager/IHealthJobItem.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace Common; using namespace Federation; using namespace std; using namespace Store; using namespace Management::HealthManager; IHealthJobItem::IHealthJobItem(HealthEntityKind::Enum entityKind) : entityKind_(entityKind) , state_(EntityJobItemState::NotStarted) , pendingAsyncOperation_() , sequenceNumber_(0) { } IHealthJobItem::~IHealthJobItem() { } bool IHealthJobItem::operator > (IHealthJobItem const & other) const { // ReadOnly jobs have already written their info to store, so they should be quick to complete. // Give read only job items priority. if (this->CanExecuteOnStoreThrottled != other.CanExecuteOnStoreThrottled) { return other.CanExecuteOnStoreThrottled; } if (this->JobPriority < other.JobPriority) { return true; } else if (this->JobPriority == other.JobPriority) { return this->SequenceNumber > other.SequenceNumber; } else { return false; } } void IHealthJobItem::ProcessCompleteResult(Common::ErrorCode const & error) { this->OnComplete(error); } // Called when work is done, either sync or async void IHealthJobItem::OnWorkComplete() { ASSERT_IF( state_ == EntityJobItemState::NotStarted || state_ == EntityJobItemState::Completed, "{0}: OnWorkComplete can't be called in this state", *this); state_ = EntityJobItemState::Completed; // The pending async operation keeps the job item alive. // Release the reference to it here to avoid creating a circular reference. pendingAsyncOperation_.reset(); } AsyncOperationSPtr IHealthJobItem::OnWorkCanceled() { state_ = EntityJobItemState::Completed; AsyncOperationSPtr temp; pendingAsyncOperation_.swap(temp); return temp; } void IHealthJobItem::OnAsyncWorkStarted() { ASSERT_IF( state_ == EntityJobItemState::NotStarted, "{0}: OnAsyncWorkStarted can't be called in this state", *this); // Mark that async work is started and return // When the work is done, the entity will call OnAsyncWorkComplete if (state_ == EntityJobItemState::Started) { state_ = EntityJobItemState::AsyncPending; } } void IHealthJobItem::OnAsyncWorkReadyToComplete( Common::AsyncOperationSPtr const & operation) { // Accepted states: AsyncPending and Started (in rare situations, // when the callback is executed quickly and raises method before the async is started) ASSERT_IF( state_ == EntityJobItemState::NotStarted || state_ == EntityJobItemState::Completed, "{0}: OnAsyncWorkReadyToComplete can't be called in this state", *this); // Remember the operation that completed to be executed on post-processing pendingAsyncOperation_ = operation; if (state_ == EntityJobItemState::Started) { state_ = EntityJobItemState::AsyncPending; } } bool IHealthJobItem::ProcessJob(IHealthJobItemSPtr const & thisSPtr, HealthManagerReplica & root) { UNREFERENCED_PARAMETER(root); switch (state_) { case EntityJobItemState::NotStarted: { // Start actual processing, done in derived classes state_ = EntityJobItemState::Started; this->ProcessInternal(thisSPtr); break; } case EntityJobItemState::AsyncPending: { // The result error is already set this->FinishAsyncWork(); break; } default: Assert::CodingError("{0}: ProcessJob can't be called in this state", *this); } return true; } std::wstring IHealthJobItem::ToString() const { return wformatString(*this); } void IHealthJobItem::WriteTo(__in Common::TextWriter & w, Common::FormatOptions const &) const { w.Write( "{0}({1},id={2},{3},JI lsn={4},priority={5})", this->TypeString, this->ReplicaActivityId.TraceId, this->JobId, this->State, this->SequenceNumber, this->JobPriority); } void IHealthJobItem::WriteToEtw(uint16 contextSequenceId) const { HMCommonEvents::Trace->JobItemTrace( contextSequenceId, this->TypeString, this->ReplicaActivityId.TraceId, this->JobId, this->State, this->SequenceNumber, this->JobPriority); }
28.169697
99
0.655336
vishnuk007
afa2e52436d604e6dc03ea87d6e467a6820e18ef
799
cpp
C++
luogu/codes/P1051.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
1
2021-02-22T03:39:24.000Z
2021-02-22T03:39:24.000Z
luogu/codes/P1051.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
null
null
null
luogu/codes/P1051.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; struct node { string xm; int qm, bj; char bgb, xb; int lw; int ans; int sum; }a[101]; int n, tot = 0; bool cmp(node x, node y) { if(x.ans == y.ans) return x.sum < y.sum; else return x.ans > y.ans; } int main() { scanf("%d",&n); for (int i = 1; i <= n; i++) { cin>>a[i].xm>>a[i].qm>>a[i].bj>>a[i].bgb>>a[i].xb>>a[i].lw; if(a[i].qm>80&&a[i].lw>=1)a[i].ans+=8000; if(a[i].qm>85&&a[i].bj>80)a[i].ans+=4000; if(a[i].qm>90)a[i].ans+=2000; if(a[i].xb=='Y'&&a[i].qm>85)a[i].ans+=1000; if(a[i].bj>80&&a[i].bgb=='Y')a[i].ans+=850; a[i].sum=i; tot+=a[i].ans; } sort(a+1,a+n+1,cmp); cout<<a[1].xm<<endl<<a[1].ans<<endl<<tot; return 0; }
19.975
67
0.46433
Tony031218
afa3698dec43b47e99d645417f0d5c99f8f353e9
3,989
hpp
C++
src/core/lib/core_reflection/metadata/meta_expose.hpp
wgsyd/wgtf
d8cacb43e2c5d40080d33c18a8c2f5bd27d21bed
[ "BSD-3-Clause" ]
28
2016-06-03T05:28:25.000Z
2019-02-14T12:04:31.000Z
src/core/lib/core_reflection/metadata/meta_expose.hpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
null
null
null
src/core/lib/core_reflection/metadata/meta_expose.hpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
14
2016-06-03T05:52:27.000Z
2019-03-21T09:56:03.000Z
#pragma once #include "core_reflection/metadata/meta_impl.hpp" #include "core_reflection/reflection_macros.hpp" #include "core_reflection/metadata/meta_types.hpp" #include "core_reflection/utilities/reflection_function_utilities.hpp" namespace wgt { BEGIN_EXPOSE(MetaBase, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaNoneObj, MetaBase, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaComponentObj, MetaBase, MetaNone()) EXPOSE("componentName", componentName_) END_EXPOSE() BEGIN_EXPOSE(MetaAngleObj, MetaComponentObj, MetaNone()) EXPOSE("convertToRadians", convertToRadians_) END_EXPOSE() BEGIN_EXPOSE(MetaTimeObj, MetaComponentObj, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaSignalObj, MetaBase, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaInvalidatesObjectObj, MetaBase, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaCallbackObj, MetaBase, MetaNone()) EXPOSE_METHOD("invoke", exposedInvoke) END_EXPOSE() BEGIN_EXPOSE(MetaMinMaxObj, MetaBase, MetaNone()) EXPOSE("min", getMin) EXPOSE("max", getMax) END_EXPOSE() BEGIN_EXPOSE(MetaStepSizeObj, MetaBase, MetaNone()) EXPOSE("stepSize", getStepSize) END_EXPOSE() BEGIN_EXPOSE(MetaDecimalsObj, MetaBase, MetaNone()) EXPOSE("decimals", getDecimals) END_EXPOSE() BEGIN_EXPOSE(MetaEnumObj, MetaBase, MetaNone()) EXPOSE("enumString", getEnumString) EXPOSE_METHOD("generateEnum", generateEnum) END_EXPOSE() BEGIN_EXPOSE(MetaSliderObj, MetaBase, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaDisplayNameObj, MetaBase, MetaNone()) EXPOSE("displayName", displayName_) END_EXPOSE() BEGIN_EXPOSE(MetaAttributeDisplayNameObj, MetaBase, MetaNone()) EXPOSE("attributeName", getAttributeName) END_EXPOSE() BEGIN_EXPOSE(MetaDisplayNameCallbackObj, MetaDisplayNameObj, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaDescriptionObj, MetaBase, MetaNone()) EXPOSE("description", getDescription) END_EXPOSE() BEGIN_EXPOSE(MetaPanelLayoutObj, MetaBase, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaNoNullObj, MetaBase, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaColorObj, MetaBase, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaHiddenObj, MetaBase, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaThumbnailObj, MetaBase, MetaNone()) EXPOSE("width", getWidth) EXPOSE("height", getHeight) END_EXPOSE() BEGIN_EXPOSE(MetaInPlaceObj, MetaBase, MetaNone()) EXPOSE("propName", getPropName) END_EXPOSE() BEGIN_EXPOSE(MetaSelectedObj, MetaBase, MetaNone()) EXPOSE("propName", getPropName) END_EXPOSE() BEGIN_EXPOSE(MetaHDRColorReinhardTonemapObj, MetaHDRColorObj, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaGroupObj, MetaBase, MetaAttributeDisplayName("groupName")) EXPOSE("groupName", groupName_) END_EXPOSE() BEGIN_EXPOSE(MetaGroupCallbackObj, MetaGroupObj, MetaAttributeDisplayName("groupName")) END_EXPOSE() BEGIN_EXPOSE(MetaUrlObj, MetaBase, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaPasswordObj, MetaBase, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaMultilineObj, MetaBase, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaDirectInvokeObj, MetaBase, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaInPlacePropertyNameObj, MetaBase, MetaNone()) EXPOSE("propertyName", getPropertyName) END_EXPOSE() BEGIN_EXPOSE(MetaReadOnlyObj, MetaBase, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaUniqueIdObj, MetaBase, MetaNone()) EXPOSE("id", getId) END_EXPOSE() BEGIN_EXPOSE(MetaCommandObj, MetaBase, MetaNone()) EXPOSE("commandName", getCommandName) END_EXPOSE() BEGIN_EXPOSE(MetaActionObj, MetaBase, MetaNone()) EXPOSE("actionName", getActionName) EXPOSE_METHOD("execute", execute) END_EXPOSE() BEGIN_EXPOSE(MetaNoSerializationObj, MetaBase, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaOnStackObj, MetaBase, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaHDRColorObj, MetaBase, MetaNone()) EXPOSE_METHOD("tonemap", tonemap, MetaDirectInvoke()) EXPOSE("shouldUpdate", shouldUpdate, MetaSignalFunc(shouldUpdateSignal)) END_EXPOSE() BEGIN_EXPOSE(MetaDisplayPathNameCallbackObj, MetaNone()) END_EXPOSE() BEGIN_EXPOSE(MetaCollectionItemMetaObj, MetaBase, MetaNone()) END_EXPOSE() } // end namespace wgt
25.246835
87
0.810228
wgsyd
afa4ab28c45c8aeeaaafca429fff5b40960c5361
4,595
cpp
C++
src/asset-archiver/asset-archiver.cpp
scp-studios/scp-game-framework
17ffb68a50d834e490d387028f05add9f5391ea5
[ "MIT" ]
1
2022-01-31T22:20:01.000Z
2022-01-31T22:20:01.000Z
src/asset-archiver/asset-archiver.cpp
scp-studios/scp-game-framework
17ffb68a50d834e490d387028f05add9f5391ea5
[ "MIT" ]
null
null
null
src/asset-archiver/asset-archiver.cpp
scp-studios/scp-game-framework
17ffb68a50d834e490d387028f05add9f5391ea5
[ "MIT" ]
null
null
null
#include <fstream> #include <iostream> #include <vector> #include <string> #include <filesystem> #include <sstream> // Hello. This is a simple command line utility for packaging assets into a si- // ngle file. It works recursively. namespace stdfs = std::filesystem; // Unused argument suppressor #define UNUSED_ARG(x) (void)x // Simple function to put all of the command line arguments into a single vect- // or of strings, which is easier to work with. #if 0 static std::vector<std::string> preprocessCommandLineArguments(int argc, char** argv) { std::vector<std::string> result(argc); for (uint32_t i = 0; i < argc; i++) { result[i] = argv[i]; } return result; } #endif static std::vector<std::string> splitString(std::string_view host, std::string_view separator) { std::vector<std::string> result; size_t start = 0; size_t end = host.find(separator, start); while (end != std::string::npos) { result.push_back(std::string(host.substr(start, end - start))); start = end + separator.length(); end = host.find(separator, start); } result.push_back(std::string(host.substr(start))); return result; } // Obtain the files within the target directory. static std::vector<std::string> getFiles(std::string_view directory, bool recursive) { std::vector<std::string> files; for (const auto& file: stdfs::directory_iterator(directory)) { #ifdef _WIN32 files.push_back(file.path().string()); #else files.push_back(file.path()); #endif if (recursive && file.is_directory()) { #ifdef _WIN32 std::vector<std::string> subdirectoryFiles = getFiles(file.path().string(), recursive); #else std::vector<std::string> subdirectoryFiles = getFiles(file.path().c_str(), recursive); #endif files.insert(files.end(), subdirectoryFiles.begin(), subdirectoryFiles.end()); } } return files; } int main(int argc, char** argv) { // We are not using these arguments yet. UNUSED_ARG(argc); UNUSED_ARG(argv); // I'll use command line arguments later. For now, they are just constants. const std::string targetDir = "./assets"; const std::string contentOutput = "mardikar.jay"; const std::string configOutput = "neng.li"; // Obtain all of the files within the asset directory. std::vector<std::string> assetFiles = getFiles(targetDir, true); // This file is the file in which we output the content of the assets into. // They will be linked together into a single binary file. std::ofstream contentOutputFile(contentOutput, std::ofstream::binary); if (!contentOutputFile) { std::cerr << "[FATAL ERROR]: Failed to open " << contentOutput << " for writing.\n"; return -1; } // This is the file in which we output the configuration file. It is where // the reader can then lookup the location of the assets within the content // file. std::ofstream configOutputFile(configOutput); if (!configOutputFile) { std::cerr << "[FATAL ERROR]: Failed to open " << configOutput << "for writing.\n"; return -2; } // We need to keep track of where the file is. uint32_t startingMarker = 0; uint32_t endingMarker = 0; // We iterate through all of the assets. for (const auto& asset: assetFiles) { // At the start of each iteration, the starting marker is set to the p- // oint in which the last file ends. startingMarker = endingMarker; // We open the asset file for reading in binary mode. std::ifstream file(asset, std::ifstream::binary); if (!file) { std::cerr << "[WARNING]: Skipping " << asset << " due to an error in opening the file.\n"; continue; } // Next, we iterate through the whole file. while (file) { // Read a character char character; file.read(&character, 1); // Push that character to the content file. contentOutputFile.write(&character, 1); // Increase the ending marker. endingMarker++; } // Finally, we add an entry in the configuration file configOutputFile << asset << ":" << startingMarker << ":" << endingMarker << "\n"; } // Okay, now we're done. return 0; }
30.838926
102
0.605658
scp-studios
afae263cd3a9e957a7500eb9a1e18a3b3adea3f3
2,053
cpp
C++
tests/swats_test.cpp
ElianeBriand/ensmallen
0f634056d054d100b2a70cb8f15ea9fa38680d10
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
tests/swats_test.cpp
ElianeBriand/ensmallen
0f634056d054d100b2a70cb8f15ea9fa38680d10
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
tests/swats_test.cpp
ElianeBriand/ensmallen
0f634056d054d100b2a70cb8f15ea9fa38680d10
[ "BSL-1.0", "BSD-3-Clause" ]
1
2019-01-16T16:21:59.000Z
2019-01-16T16:21:59.000Z
/** * @file swats_test.cpp * @author Marcus Edel * * Test file for the SWATS optimizer. * * ensmallen is free software; you may redistribute it and/or modify it under * the terms of the 3-clause BSD license. You should have received a copy of * the 3-clause BSD license along with ensmallen. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #include <ensmallen.hpp> #include "catch.hpp" #include "test_function_tools.hpp" using namespace ens; using namespace ens::test; /** * Run SWATS on logistic regression and make sure the results are acceptable. */ TEST_CASE("SWATSLogisticRegressionTestFunction", "[SWATSTest]") { SWATS optimizer(1e-3, 10, 0.9, 0.999, 1e-6, 600000, 1e-9, true); // We allow a few trials in case of poor convergence. LogisticRegressionFunctionTest(optimizer, 0.003, 0.006, 5); } /** * Test the SWATS optimizer on the Sphere function. */ TEST_CASE("SWATSSphereFunctionTest", "[SWATSTest]") { SWATS optimizer(1e-3, 2, 0.9, 0.999, 1e-6, 500000, 1e-9, true); FunctionTest<SphereFunction>(optimizer, 1.0, 0.1); } /** * Test the SWATS optimizer on the Styblinski-Tang function. */ TEST_CASE("SWATSStyblinskiTangFunctionTest", "[SWATSTest]") { SWATS optimizer(1e-3, 2, 0.9, 0.999, 1e-6, 500000, 1e-9, true); FunctionTest<StyblinskiTangFunction>(optimizer, 0.3, 0.03); } /** * Test the SWATS optimizer on the Styblinski-Tang function. Use arma::fmat. */ TEST_CASE("SWATSStyblinskiTangFunctionFMatTest", "[SWATSTest]") { SWATS optimizer(1e-3, 2, 0.9, 0.999, 1e-6, 500000, 1e-9, true); FunctionTest<StyblinskiTangFunction, arma::fmat>(optimizer, 3.0, 0.3); } #if ARMA_VERSION_MAJOR > 9 ||\ (ARMA_VERSION_MAJOR == 9 && ARMA_VERSION_MINOR >= 400) /** * Test the SWATS optimizer on the Styblinski-Tang function. Use arma::sp_mat. */ TEST_CASE("SWATSStyblinskiTangFunctionSpMatTest", "[SWATSTest]") { SWATS optimizer(1e-3, 2, 0.9, 0.999, 1e-6, 500000, 1e-9, true); FunctionTest<StyblinskiTangFunction, arma::sp_mat>(optimizer, 0.3, 0.03); } #endif
29.328571
79
0.71018
ElianeBriand
afaf0c9404b2416edabec68fd000ac66b7a25362
6,375
cpp
C++
src/test/feature/ManagementTool/test_hawq_register_rollback.cpp
YangHao666666/hawq
10cff8350f1ba806c6fec64eb67e0e6f6f24786c
[ "Artistic-1.0-Perl", "ISC", "bzip2-1.0.5", "TCL", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "PostgreSQL", "BSD-3-Clause" ]
450
2015-09-05T09:12:51.000Z
2018-08-30T01:45:36.000Z
src/test/feature/ManagementTool/test_hawq_register_rollback.cpp
YangHao666666/hawq
10cff8350f1ba806c6fec64eb67e0e6f6f24786c
[ "Artistic-1.0-Perl", "ISC", "bzip2-1.0.5", "TCL", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "PostgreSQL", "BSD-3-Clause" ]
1,274
2015-09-22T20:06:16.000Z
2018-08-31T22:14:00.000Z
src/test/feature/ManagementTool/test_hawq_register_rollback.cpp
YangHao666666/hawq
10cff8350f1ba806c6fec64eb67e0e6f6f24786c
[ "Artistic-1.0-Perl", "ISC", "bzip2-1.0.5", "TCL", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "PostgreSQL", "BSD-3-Clause" ]
278
2015-09-21T19:15:06.000Z
2018-08-31T00:36:51.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <string> #include "lib/command.h" #include "lib/sql_util.h" #include "lib/string_util.h" #include "lib/hdfs_config.h" #include "lib/file_replace.h" #include "test_hawq_register.h" #include "gtest/gtest.h" using std::string; using hawq::test::SQLUtility; using hawq::test::Command; using hawq::test::HdfsConfig; TEST_F(TestHawqRegister, TestRollbackErrorSchema) { SQLUtility util; string test_root(util.getTestRootPath()); util.execute("drop table if exists t;"); util.execute("drop table if exists nt;"); util.execute("create table t(i int) with (appendonly=true, orientation=row) distributed randomly;"); util.execute("insert into t select generate_series(1, 100);"); util.query("select * from t;", 100); util.execute("create table nt(i int) with (appendonly=true, orientation=row) distributed by (i);"); util.execute("insert into nt select generate_series(1, 100);"); util.query("select * from nt;", 100); string t_yml(hawq::test::stringFormat("%s/ManagementTool/rollback/error_schema.yml", test_root.c_str())); string t_yml_tpl(hawq::test::stringFormat("%s/ManagementTool/rollback/error_schema.yml", test_root.c_str())); hawq::test::FileReplace frep; std::unordered_map<std::string, std::string> strs_src_dst; strs_src_dst["@DATABASE_OID@"]= getDatabaseOid(); strs_src_dst["@TABLE_OID@"]= getTableOid("t", "testhawqregister_testrollbackerrorschema"); string hdfs_prefix; hawq::test::HdfsConfig hc; hc.getNamenodeHost(hdfs_prefix); strs_src_dst["@PORT@"]= hdfs_prefix; frep.replace(t_yml_tpl, t_yml, strs_src_dst); EXPECT_EQ(1, Command::getCommandStatus(hawq::test::stringFormat("hawq register -d %s -c %s testhawqregister_testrollbackerrorschema.nt", HAWQ_DB, t_yml.c_str()))); util.query("select * from t;", 100); util.query("select * from nt;", 100); EXPECT_EQ(0, Command::getCommandStatus(hawq::test::stringFormat("rm -rf %s", t_yml.c_str()))); util.execute("drop table t;"); util.execute("drop table nt;"); } TEST_F(TestHawqRegister, TestRollbackErrorHDFSFileSize) { SQLUtility util; string test_root(util.getTestRootPath()); util.execute("drop table if exists t;"); util.execute("drop table if exists nt;"); util.execute("create table t(i int) with (appendonly=true, orientation=row) distributed randomly;"); util.execute("insert into t select generate_series(1, 100);"); util.query("select * from t;", 100); util.execute("create table nt(i int) with (appendonly=true, orientation=row) distributed by (i);"); util.execute("insert into nt select generate_series(1, 100);"); util.query("select * from nt;", 100); string t_yml(hawq::test::stringFormat("%s/ManagementTool/rollback/error_schema.yml", test_root.c_str())); string t_yml_tpl(hawq::test::stringFormat("%s/ManagementTool/rollback/error_schema.yml", test_root.c_str())); hawq::test::FileReplace frep; std::unordered_map<std::string, std::string> strs_src_dst; strs_src_dst["@DATABASE_OID@"]= getDatabaseOid(); strs_src_dst["@TABLE_OID@"]= getTableOid("t", "testhawqregister_testrollbackerrorhdfsfilesize"); string hdfs_prefix; hawq::test::HdfsConfig hc; hc.getNamenodeHost(hdfs_prefix); strs_src_dst["@PORT@"]= hdfs_prefix; frep.replace(t_yml_tpl, t_yml, strs_src_dst); EXPECT_EQ(1, Command::getCommandStatus(hawq::test::stringFormat("hawq register -d %s -c %s testhawqregister_testrollbackerrorhdfsfilesize.nt", HAWQ_DB, t_yml.c_str()))); util.query("select * from t;", 100); util.query("select * from nt;", 100); EXPECT_EQ(0, Command::getCommandStatus(hawq::test::stringFormat("rm -rf %s", t_yml.c_str()))); util.execute("drop table t;"); util.execute("drop table nt;"); } TEST_F(TestHawqRegister, TestRollBackHDFSFilePathContainErrorSymbol) { SQLUtility util; string test_root(util.getTestRootPath()); util.execute("drop table if exists t;"); util.execute("drop table if exists nt;"); util.execute("create table t(i int) with (appendonly=true, orientation=row) distributed randomly;"); util.execute("insert into t select generate_series(1, 100);"); util.query("select * from t;", 100); util.execute("create table nt(i int) with (appendonly=true, orientation=row) distributed by (i);"); util.execute("insert into nt select generate_series(1, 100);"); util.query("select * from nt;", 100); string t_yml(hawq::test::stringFormat("%s/ManagementTool/rollback/error_schema.yml", test_root.c_str())); string t_yml_tpl(hawq::test::stringFormat("%s/ManagementTool/rollback/error_schema.yml", test_root.c_str())); hawq::test::FileReplace frep; std::unordered_map<std::string, std::string> strs_src_dst; strs_src_dst["@DATABASE_OID@"]= getDatabaseOid(); strs_src_dst["@TABLE_OID@"]= getTableOid("t", "testhawqregister_testrollbackhdfsfilepathcontainerrorsymbol"); string hdfs_prefix; hawq::test::HdfsConfig hc; hc.getNamenodeHost(hdfs_prefix); strs_src_dst["@PORT@"]= hdfs_prefix; frep.replace(t_yml_tpl, t_yml, strs_src_dst); EXPECT_EQ(1, Command::getCommandStatus(hawq::test::stringFormat("hawq register -d %s -c %s testhawqregister_testrollbackhdfsfilepathcontainerrorsymbol.nt", HAWQ_DB, t_yml.c_str()))); util.query("select * from t;", 100); util.query("select * from nt;", 100); EXPECT_EQ(0, Command::getCommandStatus(hawq::test::stringFormat("rm -rf %s", t_yml.c_str()))); util.execute("drop table t;"); util.execute("drop table nt;"); }
49.038462
186
0.714667
YangHao666666
afafe01bc52f52d0237b360d94f7692b8943bb7d
1,233
cpp
C++
src/bounce/Bounce.cpp
Gigi1237/Bounce
6e674dd7babda0192b930cc532f692c75219d1fd
[ "MIT" ]
null
null
null
src/bounce/Bounce.cpp
Gigi1237/Bounce
6e674dd7babda0192b930cc532f692c75219d1fd
[ "MIT" ]
2
2015-02-11T02:46:15.000Z
2015-02-26T14:41:30.000Z
src/bounce/Bounce.cpp
Gigi1237/Bounce
6e674dd7babda0192b930cc532f692c75219d1fd
[ "MIT" ]
null
null
null
#include "Bounce.h" #include <iostream> //#include <intrin.h> - Not needed on linux World *world; void ClearScreen() { std::cout << std::string(100, '\n'); } void handleUp(int action) { //if (action == 1){ ClearScreen(); World::setGravity(World::getGravity() + 0.5f); std::cout << World::getGravity(); //} } void handleDown(int action) { //if (action == 1){ ClearScreen(); World::setGravity(World::getGravity() - 0.5f); std::cout << World::getGravity(); //} } void handleSpace(int action) { if (action == 1){ world->loadFromXml(XML_PATH"world.xml", TEXTURE_PATH); } } int main() { ClearScreen(); IFade2D *graphics = new_IFade2d(1280, 720, "Bounce!"); world = new World(graphics); World::setGravity(9.81f); world->loadFromXml(XML_PATH"world.xml", TEXTURE_PATH); graphics->setKeyPressHandler(up, &handleUp); graphics->setKeyPressHandler(down, &handleDown); graphics->setKeyPressHandler(space, &handleSpace); world->initClock(); while (graphics->windowShouldClose()){ graphics->prepareScene(); world->update(); world->draw(); graphics->swapBuffer(); } delete graphics; delete world; return 0; }
20.55
62
0.622871
Gigi1237
afb142fff97a1c2d73ccad2dabee4c031dd69a8f
991
cpp
C++
luogu/codes/P1311.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
1
2021-02-22T03:39:24.000Z
2021-02-22T03:39:24.000Z
luogu/codes/P1311.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
null
null
null
luogu/codes/P1311.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
null
null
null
/************************************************************* * > File Name : P1311.cpp * > Author : Tony * > Created Time : 2019/10/20 19:31:08 * > Algorithm : **************************************************************/ #include <bits/stdc++.h> using namespace std; inline int read() { int x = 0; int f = 1; char ch = getchar(); while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();} while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();} return x * f; } const int maxn = 200010; int n, k, p, las[maxn], sum[maxn], vis[maxn]; int main() { n = read(); k = read(); p = read(); int now = 0, ans = 0; for (int i = 1; i <= n; ++i) { int col = read(), pri = read(); if (pri <= p) { now = i; } if (now >= las[col]) { sum[col] = vis[col]; } las[col] = i; vis[col]++; ans += sum[col]; } printf("%d\n", ans); return 0; }
26.078947
65
0.379415
Tony031218
afb258add685e6ea7e2995fbc57674ba17d6b48f
677
hpp
C++
TheMachine/include/TheMachine/utils.hpp
adepierre/TheMachine
96df7775a4a6745802ab76649a63a4d16641a54b
[ "MIT" ]
1
2021-09-24T10:05:52.000Z
2021-09-24T10:05:52.000Z
TheMachine/include/TheMachine/utils.hpp
adepierre/TheMachine
96df7775a4a6745802ab76649a63a4d16641a54b
[ "MIT" ]
null
null
null
TheMachine/include/TheMachine/utils.hpp
adepierre/TheMachine
96df7775a4a6745802ab76649a63a4d16641a54b
[ "MIT" ]
null
null
null
#pragma once #include <opencv2/core.hpp> struct Detection { float x1, y1, x2, y2; float score; int cls; }; void DrawRectangle(cv::Mat& img, const Detection& d, const cv::Scalar& color); void DrawDetection(cv::Mat& img, const Detection& d, const cv::Scalar& color); void DrawPerson(cv::Mat& img, const Detection& d, const cv::Scalar& color); void DrawCar(cv::Mat& img, const Detection& d, const cv::Scalar& color); cv::Point2f RotatePoint(const cv::Point2f& inPoint, const cv::Point2f& center, const float& angDeg); void DrawTrain(cv::Mat& img, const Detection& d, const cv::Scalar& color); void DrawPlane(cv::Mat& img, const Detection& d, const cv::Scalar& color);
27.08
100
0.713442
adepierre
afb855da368616917984a559264b3171bcc4e44e
1,454
cpp
C++
POJ/POJ2417.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
18
2019-01-01T13:16:59.000Z
2022-02-28T04:51:50.000Z
POJ/POJ2417.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
null
null
null
POJ/POJ2417.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
5
2019-09-13T08:48:17.000Z
2022-02-19T06:59:03.000Z
#include <cmath> #include <cstdio> #include <cstring> #define HMOD 1000007LL using namespace std; struct hash_link { long long ori; long long val; int nxt; }; hash_link e[HMOD << 2]; int edge_num[HMOD], cnt; long long a, b, MOD; inline void add(long long x, long long y) { long long ori = x; x %= HMOD; for (int i = edge_num[x]; ~i; i = e[i].nxt) if (e[i].ori == ori) return ; e[cnt] = (hash_link) { ori, y, edge_num[x] }; edge_num[x] = cnt++; return ; } inline long long query(long long x) { long long ori = x; x %= HMOD; for (int i = edge_num[x]; ~i; i = e[i].nxt) if (e[i].ori == ori) return e[i].val; return -1LL; } void exgcd(long long a, long long b, long long &x, long long &y) { if (!b) { x = 1; y = 0; return ; } exgcd(b, a % b, x, y); long long t = x; x = y; y = t - (a / b) * y; return ; } long long exBSGS(long long a, long long b, long long MOD) { memset(edge_num, -1, sizeof edge_num); cnt = 0; long long M = ceil(sqrt(MOD)); long long t = 1LL, r = 1LL, x, y; for (long long i = 0; i < M; i++, t = t * a % MOD) add(t, i); for (long long i = 0; i <= M; i++, r = r * t % MOD) { exgcd(r, MOD, x, y); x = (x * b % MOD + MOD) % MOD; int res = query(x); if (res != -1) return i * M + res; } return -1LL; } int main() { while (~scanf("%lld %lld %lld", &MOD, &a, &b)) { long long ans = exBSGS(a, b, MOD); if (!~ans) puts("no solution"); else printf("%lld\n", ans); } return 0; }
17.518072
64
0.552957
HeRaNO
afbd8af7b78eee23bb4ad7a5ebc12380299cde0e
1,877
cpp
C++
cpp/src/torch_tensorrt.cpp
narendasan/TRTorch
badcc696891596925def4a260a8f58ade24f2296
[ "BSD-3-Clause" ]
null
null
null
cpp/src/torch_tensorrt.cpp
narendasan/TRTorch
badcc696891596925def4a260a8f58ade24f2296
[ "BSD-3-Clause" ]
null
null
null
cpp/src/torch_tensorrt.cpp
narendasan/TRTorch
badcc696891596925def4a260a8f58ade24f2296
[ "BSD-3-Clause" ]
null
null
null
#include "torch/csrc/jit/api/module.h" #include "core/compiler.h" #include "core/util/prelude.h" #include "torch_tensorrt/torch_tensorrt.h" namespace torch_tensorrt { // Defined in types.cpp trtorch::core::runtime::CudaDevice to_internal_cuda_device(Device device); namespace torchscript { // Defined in compile_spec.cpp trtorch::core::CompileSpec to_internal_compile_spec(CompileSpec external); bool CheckMethodOperatorSupport(const torch::jit::script::Module& module, std::string method_name) { return trtorch::core::CheckMethodOperatorSupport(module, method_name); } std::string ConvertGraphToTRTEngine( const torch::jit::script::Module& module, std::string method_name, CompileSpec info) { LOG_DEBUG(get_build_info()); // Want to export a much simpler (non TRT header dependent) API so doing the // type conversion here return trtorch::core::ConvertGraphToTRTEngine(module, method_name, to_internal_compile_spec(info)); } torch::jit::script::Module CompileGraph(const torch::jit::script::Module& module, CompileSpec info) { LOG_DEBUG(get_build_info()); // Want to export a much simpler (non TRT header dependent) API so doing the // type conversion here return trtorch::core::CompileGraph(module, to_internal_compile_spec(info)); } torch::jit::Module EmbedEngineInNewModule(const std::string& engine, Device device) { return trtorch::core::EmbedEngineInNewModule(engine, to_internal_cuda_device(device)); } } //namespace ts std::string get_build_info() { auto info = trtorch::core::util::get_build_info(); return std::string("TRTorch Version: ") + TORCH_TENSORRT_VERSION + '\n' + info; } void dump_build_info() { std::cout << get_build_info() << std::endl; } void set_device(const int gpu_id) { // Want to export a much simpler (non CUDA header dependent) API trtorch::core::set_device(gpu_id); } } // namespace trtorch
33.517857
101
0.755994
narendasan
afbeb2766cd84485a0e217549e064cb65b22fda5
109
hpp
C++
inc/receive_msg.hpp
os-chat/Chat
71d4750030a285fe5dab466d52f6d18f8f70ef07
[ "MIT" ]
null
null
null
inc/receive_msg.hpp
os-chat/Chat
71d4750030a285fe5dab466d52f6d18f8f70ef07
[ "MIT" ]
null
null
null
inc/receive_msg.hpp
os-chat/Chat
71d4750030a285fe5dab466d52f6d18f8f70ef07
[ "MIT" ]
null
null
null
#ifndef RECEIVE_MSG_HPP #define RECEIVE_MSG_HPP #include "common.hpp" void *receive_msg(void *ptr); #endif
13.625
29
0.779817
os-chat
afc0d98a7d0cbb89cdb834e40f8505129adeb8d5
4,137
tpp
C++
base/serialization.tpp
BowenforGit/Grasper
268468d6eb0a56e9a4815c0c1d7660b06bf8a1f7
[ "Apache-2.0" ]
29
2019-11-18T14:25:05.000Z
2022-02-10T07:21:48.000Z
base/serialization.tpp
BowenforGit/Grasper
268468d6eb0a56e9a4815c0c1d7660b06bf8a1f7
[ "Apache-2.0" ]
2
2021-03-17T03:17:38.000Z
2021-04-11T04:06:23.000Z
base/serialization.tpp
BowenforGit/Grasper
268468d6eb0a56e9a4815c0c1d7660b06bf8a1f7
[ "Apache-2.0" ]
6
2019-11-21T18:04:15.000Z
2022-03-01T02:48:50.000Z
/* Copyright 2019 Husky Data Lab, CUHK Authors: Created by Hongzhi Chen (hzchen@cse.cuhk.edu.hk) */ template <class T> ibinstream& operator<<(ibinstream& m, const T* p) { return m << *p; } template <class T> ibinstream& operator<<(ibinstream& m, const vector<T>& v) { m << v.size(); for (typename vector<T>::const_iterator it = v.begin(); it != v.end(); ++it) { m << *it; } return m; } template <class T> ibinstream& operator<<(ibinstream& m, const list<T>& v) { m << v.size(); for (typename list<T>::const_iterator it = v.begin(); it != v.end(); ++it) { m << *it; } return m; } template <class T> ibinstream& operator<<(ibinstream& m, const set<T>& v) { m << v.size(); for (typename set<T>::const_iterator it = v.begin(); it != v.end(); ++it) { m << *it; } return m; } template <class T1, class T2> ibinstream& operator<<(ibinstream& m, const pair<T1, T2>& v) { m << v.first; m << v.second; return m; } template <class KeyT, class ValT> ibinstream& operator<<(ibinstream& m, const map<KeyT, ValT>& v) { m << v.size(); for (typename map<KeyT, ValT>::const_iterator it = v.begin(); it != v.end(); ++it) { m << it->first; m << it->second; } return m; } template <class KeyT, class ValT> ibinstream& operator<<(ibinstream& m, const hash_map<KeyT, ValT>& v) { m << v.size(); for (typename hash_map<KeyT, ValT>::const_iterator it = v.begin(); it != v.end(); ++it) { m << it->first; m << it->second; } return m; } template <class T> ibinstream& operator<<(ibinstream& m, const hash_set<T>& v) { m << v.size(); for (typename hash_set<T>::const_iterator it = v.begin(); it != v.end(); ++it) { m << *it; } return m; } template <class T, class _HashFcn, class _EqualKey > ibinstream& operator<<(ibinstream& m, const hash_set<T, _HashFcn, _EqualKey>& v) { m << v.size(); for (typename hash_set<T, _HashFcn, _EqualKey>::const_iterator it = v.begin(); it != v.end(); ++it) { m << *it; } return m; } template <class T> obinstream& operator>>(obinstream& m, T*& p) { p = new T; return m >> (*p); } template <class T> obinstream& operator>>(obinstream& m, vector<T>& v) { size_t size; m >> size; v.resize(size); for (typename vector<T>::iterator it = v.begin(); it != v.end(); ++it) { m >> *it; } return m; } template <class T> obinstream& operator>>(obinstream& m, list<T>& v) { v.clear(); size_t size; m >> size; for (size_t i = 0; i < size; i++) { T tmp; m >> tmp; v.push_back(tmp); } return m; } template <class T> obinstream& operator>>(obinstream& m, set<T>& v) { v.clear(); size_t size; m >> size; for (size_t i = 0; i < size; i++) { T tmp; m >> tmp; v.insert(v.end(), tmp); } return m; } template <class T1, class T2> obinstream& operator>>(obinstream& m, pair<T1, T2>& v) { m >> v.first; m >> v.second; return m; } template <class KeyT, class ValT> obinstream& operator>>(obinstream& m, map<KeyT, ValT>& v) { v.clear(); size_t size; m >> size; for (size_t i = 0; i < size; i++) { KeyT key; m >> key; m >> v[key]; } return m; } template <class KeyT, class ValT> obinstream& operator>>(obinstream& m, hash_map<KeyT, ValT>& v) { v.clear(); size_t size; m >> size; for (size_t i = 0; i < size; i++) { KeyT key; m >> key; m >> v[key]; } return m; } template <class T> obinstream& operator>>(obinstream& m, hash_set<T>& v) { v.clear(); size_t size; m >> size; for (size_t i = 0; i < size; i++) { T key; m >> key; v.insert(key); } return m; } template <class T, class _HashFcn, class _EqualKey > obinstream& operator>>(obinstream& m, hash_set<T, _HashFcn, _EqualKey>& v) { v.clear(); size_t size; m >> size; for (size_t i = 0; i < size; i++) { T key; m >> key; v.insert(key); } return m; }
22.483696
105
0.539521
BowenforGit
afc26b1c39f8e3183c2e2400230efa5e674a8b13
10,914
cpp
C++
sources/VS/ThirdParty/wxWidgets/samples/archive/archive.cpp
Sasha7b9Work/S8-53M2
fdc9cb5e3feb8055fd3f7885a6f6362f62ff6b6e
[ "MIT" ]
15
2019-05-19T23:10:41.000Z
2021-08-06T14:02:09.000Z
sources/VS/ThirdParty/wxWidgets/samples/archive/archive.cpp
Sasha7b9Work/S8-53M2
fdc9cb5e3feb8055fd3f7885a6f6362f62ff6b6e
[ "MIT" ]
3
2019-12-05T08:08:50.000Z
2020-05-14T20:31:39.000Z
sources/VS/ThirdParty/wxWidgets/samples/archive/archive.cpp
Sasha7b9Work/S8-53M2
fdc9cb5e3feb8055fd3f7885a6f6362f62ff6b6e
[ "MIT" ]
4
2020-02-27T00:57:21.000Z
2021-08-06T14:02:11.000Z
///////////////////////////////////////////////////////////////////////////// // Name: samples/archive/archive.cpp // Purpose: A sample application to manipulate archives // Author: Tobias Taschner // Created: 2018-02-07 // Copyright: (c) 2018 wxWidgets development team // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "wx/archive.h" #include "wx/app.h" #include "wx/cmdline.h" #include "wx/filename.h" #include "wx/scopedptr.h" #include "wx/vector.h" #include "wx/wfstream.h" #include "wx/zipstrm.h" class ArchiveApp: public wxAppConsole { public: ArchiveApp() { m_forceZip64 = false; m_archiveClassFactory = NULL; m_filterClassFactory = NULL; } virtual void OnInitCmdLine(wxCmdLineParser& parser) wxOVERRIDE; virtual bool OnCmdLineParsed(wxCmdLineParser& parser) wxOVERRIDE; virtual int OnRun() wxOVERRIDE; private: enum ArchiveCommandType { CMD_CREATE, CMD_LIST, CMD_EXTRACT, CMD_NONE }; struct ArchiveCommandDesc { ArchiveCommandType type; const char* id; const char* desc; }; static const ArchiveCommandDesc s_cmdDesc[]; ArchiveCommandType m_command; wxString m_archiveFileName; wxVector<wxString> m_fileNames; bool m_forceZip64; // At most one of these pointers is non-NULL. const wxArchiveClassFactory* m_archiveClassFactory; const wxFilterClassFactory* m_filterClassFactory; int DoCreate(); int DoList(); int DoExtract(); bool CopyStreamData(wxInputStream& inputStream, wxOutputStream& outputStream, wxFileOffset size); }; const ArchiveApp::ArchiveCommandDesc ArchiveApp::s_cmdDesc[] = { {CMD_CREATE, "c", "create"}, {CMD_LIST, "l", "list"}, {CMD_EXTRACT, "x", "extract"}, {CMD_NONE, 0, 0} }; // Helper function iterating over all factories of the given type (assumed to // derive from wxFilterClassFactoryBase) and returning a string containing all // comma-separated values returned from their GetProtocols() called with the // given protocol type. template <typename T> void AppendAllSupportedOfType(wxString& all, wxStreamProtocolType type) { for (const T* factory = T::GetFirst(); factory; factory = factory->GetNext()) { const wxChar* const* exts = factory->GetProtocols(type); while (*exts) { if (!all.empty()) all+= ", "; all += *exts++; } } } // Returns all supported protocols or extensions (depending on the type // parameter value) for both archive and filter factories. wxString GetAllSupported(wxStreamProtocolType type) { wxString all; AppendAllSupportedOfType<wxArchiveClassFactory>(all, type); AppendAllSupportedOfType<wxFilterClassFactory>(all, type); return all; } void ArchiveApp::OnInitCmdLine(wxCmdLineParser& parser) { wxAppConsole::OnInitCmdLine(parser); parser.AddParam("command"); parser.AddParam("archive_name"); parser.AddParam("file_names", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_MULTIPLE | wxCMD_LINE_PARAM_OPTIONAL); parser.AddSwitch("", "force-zip64", "Force ZIP64 format when creating ZIP archives"); parser.AddUsageText("\ncommand:"); for (const ArchiveCommandDesc* cmdDesc = s_cmdDesc; cmdDesc->type != CMD_NONE; cmdDesc++) parser.AddUsageText(wxString::Format(" %s: %s", cmdDesc->id, cmdDesc->desc)); parser.AddUsageText("\nsupported formats: " + GetAllSupported(wxSTREAM_PROTOCOL)); } bool ArchiveApp::OnCmdLineParsed(wxCmdLineParser& parser) { m_command = CMD_NONE; wxString command = parser.GetParam(); for (const ArchiveCommandDesc* cmdDesc = s_cmdDesc; cmdDesc->type != CMD_NONE; cmdDesc++) { if (cmdDesc->id == command) m_command = cmdDesc->type; } if(m_command == CMD_NONE) { wxLogError("Invalid command: %s", command); return false; } m_archiveFileName = parser.GetParam(1); for (size_t i = 2; i < parser.GetParamCount(); i++) m_fileNames.push_back(parser.GetParam(i)); m_forceZip64 = parser.FoundSwitch("force-zip64") == wxCMD_SWITCH_ON; return wxAppConsole::OnCmdLineParsed(parser); } bool ArchiveApp::CopyStreamData(wxInputStream& inputStream, wxOutputStream& outputStream, wxFileOffset size) { wxChar buf[128 * 1024]; int readSize = 128 * 1024; wxFileOffset copiedData = 0; for (;;) { if (size != -1 && copiedData + readSize > size) readSize = size - copiedData; inputStream.Read(buf, readSize); size_t actuallyRead = inputStream.LastRead(); outputStream.Write(buf, actuallyRead); if (outputStream.LastWrite() != actuallyRead) { wxLogError("Failed to output data"); return false; } if (size == -1) { if (inputStream.Eof()) break; } else { copiedData += actuallyRead; if (copiedData >= size) break; } } return true; } int ArchiveApp::DoCreate() { if (m_fileNames.empty()) { wxLogError("Need at least one file to add to archive"); return -1; } wxTempFileOutputStream fileOutputStream(m_archiveFileName); if (m_archiveClassFactory) { wxScopedPtr<wxArchiveOutputStream> archiveOutputStream(m_archiveClassFactory->NewStream(fileOutputStream)); if (m_archiveClassFactory->GetProtocol().IsSameAs("zip", false) && m_forceZip64) reinterpret_cast<wxZipOutputStream*>(archiveOutputStream.get())->SetFormat(wxZIP_FORMAT_ZIP64); for(wxVector<wxString>::iterator fileName = m_fileNames.begin(); fileName != m_fileNames.end(); fileName++) { wxFileName inputFileName(*fileName); wxPrintf("Adding %s...\n", inputFileName.GetFullName()); wxFileInputStream inputFileStream(*fileName); if (!inputFileStream.IsOk()) { wxLogError("Could not open file"); return 1; } if (!archiveOutputStream->PutNextEntry(inputFileName.GetFullName(), wxDateTime::Now(), inputFileStream.GetLength())) break; if (!CopyStreamData(inputFileStream, *archiveOutputStream, inputFileStream.GetLength())) return 1; } if (!archiveOutputStream->Close()) return 1; } else // use m_filterClassFactory { if (m_fileNames.size() != 1) { wxLogError("Filter-based formats only support archives consisting of a single file"); return -1; } wxScopedPtr<wxFilterOutputStream> filterOutputStream(m_filterClassFactory->NewStream(fileOutputStream)); wxFileInputStream inputFileStream(*m_fileNames.begin()); if (!inputFileStream.IsOk()) { wxLogError("Could not open file"); return 1; } if (!CopyStreamData(inputFileStream, *filterOutputStream, inputFileStream.GetLength())) return 1; } fileOutputStream.Commit(); wxPrintf("Created archive\n"); return 0; } int ArchiveApp::DoList() { wxFileInputStream fileInputStream(m_archiveFileName); if (!fileInputStream.IsOk()) return 1; if (m_archiveClassFactory) { wxScopedPtr<wxArchiveInputStream> archiveStream(m_archiveClassFactory->NewStream(fileInputStream)); wxPrintf("Archive: %s\n", m_archiveFileName); wxPrintf("Length Date Time Name\n"); wxPrintf("---------- ---------- -------- ----\n"); wxFileOffset combinedSize = 0; int entryCount = 0; for (wxArchiveEntry* entry = archiveStream->GetNextEntry(); entry; entry = archiveStream->GetNextEntry()) { combinedSize += entry->GetSize(); entryCount++; wxPrintf("%10lld %s %s %s\n", entry->GetSize(), entry->GetDateTime().FormatISODate(), entry->GetDateTime().FormatISOTime(), entry->GetName()); } wxPrintf("---------- -------\n"); wxPrintf("%10lld %d files\n", combinedSize, entryCount); } else { wxPrintf("Archive \"%s\" contains a single file named \"%s\"\n", m_archiveFileName, wxFileName(m_archiveFileName).GetName()); } return 0; } int ArchiveApp::DoExtract() { wxFileInputStream fileInputStream(m_archiveFileName); if (!fileInputStream.IsOk()) return 1; if (m_archiveClassFactory) { wxScopedPtr<wxArchiveInputStream> archiveStream(m_archiveClassFactory->NewStream(fileInputStream)); wxPrintf("Extracting from: %s\n", m_archiveFileName); for (wxArchiveEntry* entry = archiveStream->GetNextEntry(); entry; entry = archiveStream->GetNextEntry()) { wxPrintf("Extracting: %s...\n", entry->GetName()); wxTempFileOutputStream outputFileStream(entry->GetName()); if (!CopyStreamData(*archiveStream, outputFileStream, entry->GetSize())) return 1; outputFileStream.Commit(); } wxPrintf("Extracted all files\n"); } else { wxScopedPtr<wxFilterInputStream> filterStream(m_filterClassFactory->NewStream(fileInputStream)); wxPrintf("Extracting single file from: %s\n", m_archiveFileName); wxTempFileOutputStream outputFileStream(wxFileName(m_archiveFileName).GetName()); if (!CopyStreamData(*filterStream, outputFileStream, -1)) return 1; outputFileStream.Commit(); wxPrintf("Extracted successfully\n"); } return 0; } int ArchiveApp::OnRun() { m_archiveClassFactory = wxArchiveClassFactory::Find(m_archiveFileName, wxSTREAM_FILEEXT); if (!m_archiveClassFactory) { m_filterClassFactory = wxFilterClassFactory::Find(m_archiveFileName, wxSTREAM_FILEEXT); if (!m_filterClassFactory) { wxLogError("File \"%s\" has unsupported extension, supported ones are: %s", m_archiveFileName, GetAllSupported(wxSTREAM_FILEEXT)); return -1; } } int result = -1; switch (m_command) { case CMD_CREATE: result = DoCreate(); break; case CMD_LIST: result = DoList(); break; case CMD_EXTRACT: result = DoExtract(); break; default: break; } return result; } wxIMPLEMENT_APP(ArchiveApp);
30.830508
128
0.616822
Sasha7b9Work
afc86f98606a6be02eecf6dc0f15664affe8a493
841
cc
C++
libmat/test/src/test_cr_cColItr_all.cc
stiegerc/winterface
b6d501df1d0c015f2cd7126ac6b4e746d541c80c
[ "BSD-2-Clause" ]
2
2020-10-06T09:14:23.000Z
2020-11-25T06:08:54.000Z
libmat/test/src/test_cr_cColItr_all.cc
stiegerc/Winterface
b6d501df1d0c015f2cd7126ac6b4e746d541c80c
[ "BSD-2-Clause" ]
1
2020-12-23T04:20:33.000Z
2020-12-23T04:20:33.000Z
libmat/test/src/test_cr_cColItr_all.cc
stiegerc/Winterface
b6d501df1d0c015f2cd7126ac6b4e746d541c80c
[ "BSD-2-Clause" ]
1
2020-07-14T13:53:32.000Z
2020-07-14T13:53:32.000Z
// 2014-2019, ETH Zurich, Integrated Systems Laboratory // Authors: Christian Stieger #include "testTools.h" #include "test_cr_tVecItr_all.h" #include "test_cr_tVecItr_all.cc" template<> void test_cr_tVecItr_all<CPX__,RE__,CPX__,lm_tCol<CPX__,RE__,CPX__>>::test_dereference() { const size_t M = genRndST(); const size_t N = genRndST(); const auto tMat1 = rnd<cMat>(M,N); cr_tVecItr tItr1(&tMat1,N-1); for (size_t n=0; n!=tMat1.N(); ++n) CPPUNIT_ASSERT(tMat1.cAt(N-1-n)==tItr1[n]); for (size_t n=0; n!=tMat1.N(); ++n,++tItr1) CPPUNIT_ASSERT(tMat1.cAt(N-1-n)==*tItr1); } // test id template<> const char* test_cr_tVecItr_all<CPX__,RE__,CPX__,lm_tCol<CPX__,RE__,CPX__>>::test_id() noexcept { return "test_cr_cColItr_all"; } // instantiation template class test_cr_tVecItr_all<CPX__,RE__,CPX__,lm_tCol<CPX__,RE__,CPX__>>;
24.735294
97
0.72176
stiegerc
afca3e293acc406f7c6dc97e7fbc547718455d00
1,088
cpp
C++
ECE264/Labs/Lab#3/lab3_GradeBook.cpp
Reiuiji/UmassdPortfolio
959d852a91825326fd777c1883cdfac39d8dd3dd
[ "MIT" ]
3
2017-04-23T00:53:11.000Z
2019-03-11T23:47:20.000Z
ECE264/Labs/Lab#3/lab3_GradeBook.cpp
Reiuiji/UmassdPortfolio
959d852a91825326fd777c1883cdfac39d8dd3dd
[ "MIT" ]
null
null
null
ECE264/Labs/Lab#3/lab3_GradeBook.cpp
Reiuiji/UmassdPortfolio
959d852a91825326fd777c1883cdfac39d8dd3dd
[ "MIT" ]
null
null
null
//Lab 3 lab3_GradeBook.cpp #include <iostream> using namespace std; #include "lab3_GradeBook.h" //set the gradebook with a course and a instructor tag GradeBook::GradeBook(string course, string Instructor) { setCourseName(course); setInstructorName(Instructor); } //set the course name void GradeBook::setCourseName(string name) { courseName = name; } //return the course name string GradeBook::getCourseName() { return courseName; } //set the instructor name void GradeBook::setInstructorName(string name) { InstructorName = name; } //this will change the instructor to a new one void GradeBook::changeInstructorName(string name) { InstructorName = name; cout << "Changing Instructor name to " << name << endl; cout << "\n"; } //return the instructor name string GradeBook::getInstructorName() { return InstructorName; } //output the course and intrurctor name neatly void GradeBook::displayMessage() { cout << "Welcome to the grade book for\n" << getCourseName() << "!" << endl; cout << "This Course is presented by: " << getInstructorName() << endl; cout << "\n"; }
20.923077
77
0.729779
Reiuiji
afcc23ae27949774542c6cb63d9a826e503cce32
7,678
cpp
C++
2/second-lab/second-lab/app.cpp
i582/HLProgramming
4d2da80c69f8e1014cbf7be9087bdec6b2c05d45
[ "MIT" ]
null
null
null
2/second-lab/second-lab/app.cpp
i582/HLProgramming
4d2da80c69f8e1014cbf7be9087bdec6b2c05d45
[ "MIT" ]
null
null
null
2/second-lab/second-lab/app.cpp
i582/HLProgramming
4d2da80c69f8e1014cbf7be9087bdec6b2c05d45
[ "MIT" ]
null
null
null
#include "app.h" App::App() { this->window = nullptr; this->renderer = nullptr; this->e = {}; this->running = true; } App::~App() { SDL_RemoveTimer(repeatOnceFunctionTimer); SDL_RemoveTimer(customEventFunctionTimer); SDL_Log("Старт разрушения окна"); SDL_DestroyWindow(window); SDL_Log("разрушение окна успешно завершено"); SDL_Quit(); } bool App::init() { SDL_Log("Начало создания окна"); this->window = SDL_CreateWindow("SDL2: Магические события", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 480, 640, SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_RESIZABLE); if (window == nullptr) { SDL_Log("Ошибка создания окна: %s\n", SDL_GetError()); return false; } this->renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (renderer == nullptr) { SDL_Log("Ошибка создания renderer! SDL Error: %s\n", SDL_GetError()); return false; } SDL_SetEventFilter(eventFilter, nullptr); createTimers(); return true; } void App::setup() { } void App::update() { } void App::on_event() { SDL_WaitEvent(nullptr); } void App::quit() { running = false; } int App::run() { if (!init()) return -1; setup(); update(); on_event(); return 0; } bool App::createTimers() { customEventFunctionTimer = SDL_AddTimer(2000 /* 2 sec */, customEventFunction, window); if (customEventFunctionTimer == 0) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Ошибка", "Невозможно создать кастомный событийный таймер. Расширенная информация в лог-файле.", window); SDL_LogCritical(SDL_LOG_CATEGORY_APPLICATION, "Невозможно создать кастомный событийный таймер, ошибка: %s", SDL_GetError()); return false; } repeatOnceFunctionTimer = SDL_AddTimer(10000 /* 10 sec */, repeatOnceFunction, window); if (repeatOnceFunctionTimer == 0) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Ошибка", "Невозможно создать кастомный одноразовый таймер. Расширенная информация в лог-файле.", window); SDL_LogCritical(SDL_LOG_CATEGORY_APPLICATION, "Невозможно создать кастомный одноразовый таймер, ошибка: %s", SDL_GetError()); return false; } return true; } void App::clearScreen(SDL_Window* window) { SDL_Surface* screen = SDL_GetWindowSurface(window); SDL_FillRect(screen, nullptr, SDL_MapRGB(screen->format, rand() % 255, rand() % 255, rand() % 255)); SDL_UpdateWindowSurface(window); } Uint32 App::repeatOnceFunction(Uint32 interval, void* param) { SDL_Event exitEvent = { SDL_QUIT }; SDL_Log("Таймер работает с следующим интервалом %d мс", interval); if (asmFunction() != 0) { SDL_HideWindow((SDL_Window*)param); SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Что-то пошло не так", "Найди меня! Я потерялся!", nullptr); SDL_Delay(15000); /* 15 sec */ SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Ты не нашел меня! Я расстроен тобою... я ухожу."); SDL_PushEvent(&exitEvent); } return 0; } Uint32 App::customEventFunction(Uint32 interval, void* param) { SDL_Event event = { SDL_WINDOWEVENT }; SDL_Log("Таймер работает с следующим интервалом %d мс", interval); event.window.windowID = SDL_GetWindowID((SDL_Window*)param); event.window.event = SDL_WINDOWEVENT_EXPOSED; SDL_PushEvent(&event); return interval; } int App::asmFunction() { static int internalValue = 1; #ifdef __GNUC__ __asm__("movl %0, %%eax\n\t" "add %%eax, %0" : "=r" (internalValue) : "r" (internalValue)); #elif _MSC_VER _asm { mov eax, internalValue add internalValue, eax }; #endif return internalValue; } int App::eventFilter(void* userdata, SDL_Event* event) { switch (event->type) { case SDL_KEYDOWN: if (event->key.keysym.sym == SDLK_q && event->key.keysym.mod == KMOD_CTRL) { SDL_Event exitEvent = { SDL_QUIT }; SDL_PushEvent(&exitEvent); } SDL_Log("нажатие кнопки %d", event->key.keysym.sym); break; case SDL_KEYUP: SDL_Log("отжатие кнопки %d", event->key.keysym.sym); break; case SDL_TEXTEDITING: SDL_Log("Клавиатурное исправление (композиция). Композия: '%s', курсор начал с %d и выбрал длину в %d", event->edit.text, event->edit.start, event->edit.length); break; case SDL_TEXTINPUT: SDL_Log("Клавиатурный ввод. Текст: '%s'", event->text.text); break; case SDL_FINGERMOTION: SDL_Log("Пальчик водится: %lld, x: %f, y: %f", event->tfinger.fingerId, event->tfinger.x, event->tfinger.y); break; case SDL_FINGERDOWN: SDL_Log("Пальчик: %lld вниз - x: %f, y: %f", event->tfinger.fingerId, event->tfinger.x, event->tfinger.y); return 1; case SDL_FINGERUP: SDL_Log("Пальчик: %lld вверх - x: %f, y: %f", event->tfinger.fingerId, event->tfinger.x, event->tfinger.y); break; case SDL_MULTIGESTURE: SDL_Log("Мульти тач: x = %f, y = %f, dAng = %f, dR = %f", event->mgesture.x, event->mgesture.y, event->mgesture.dTheta, event->mgesture.dDist); SDL_Log("Мульти тач: нажатие пальца = %i", event->mgesture.numFingers); break; case SDL_DOLLARGESTURE: SDL_Log("Записываемый %lld получен, ошибка: %f", event->dgesture.gestureId, event->dgesture.error); break; case SDL_DOLLARRECORD: SDL_Log("Записываемый черт: %lld", event->dgesture.gestureId); break; case SDL_MOUSEMOTION: SDL_Log("Мышинный сдвиг. X=%d, Y=%d, ИзмененияX=%d, ИзмененияY=%d", event->motion.x, event->motion.y, event->motion.xrel, event->motion.yrel); break; case SDL_MOUSEBUTTONDOWN: if (event->button.button == SDL_BUTTON_LEFT) asmFunction(); SDL_Log("Мышинный Кнопка Вниз %u", event->button.button); break; case SDL_MOUSEBUTTONUP: SDL_Log("Мышинный Кнопка Вверх %u", event->button.button); break; case SDL_MOUSEWHEEL: SDL_Log("Мышинный Колесо X=%d, Y=%d", event->wheel.x, event->wheel.y); break; case SDL_QUIT: SDL_Log("Пользовательский выход"); return 1; case SDL_WINDOWEVENT: switch (event->window.event) { case SDL_WINDOWEVENT_SHOWN: SDL_Log("Окно %d показано", event->window.windowID); break; case SDL_WINDOWEVENT_HIDDEN: SDL_Log("Окно %d скрыто", event->window.windowID); break; case SDL_WINDOWEVENT_EXPOSED: clearScreen(SDL_GetWindowFromID(event->window.windowID)); SDL_Log("Окно %d сдвинуто", event->window.windowID); break; case SDL_WINDOWEVENT_MOVED: SDL_Log("Окно %d перемещенно в %d,%d", event->window.windowID, event->window.data1, event->window.data2); break; case SDL_WINDOWEVENT_RESIZED: SDL_Log("Окно %d изменено до %dx%d", event->window.windowID, event->window.data1, event->window.data2); break; case SDL_WINDOWEVENT_SIZE_CHANGED: SDL_Log("Окно %d изменила размер до %dx%d", event->window.windowID, event->window.data1, event->window.data2); break; case SDL_WINDOWEVENT_MINIMIZED: SDL_Log("Окно %d свернуто", event->window.windowID); break; case SDL_WINDOWEVENT_MAXIMIZED: SDL_Log("Окно %d развернуто", event->window.windowID); break; case SDL_WINDOWEVENT_RESTORED: SDL_Log("Окно %d восстановленно", event->window.windowID); break; case SDL_WINDOWEVENT_ENTER: SDL_Log("Мышь пришла к окну %d", event->window.windowID); break; case SDL_WINDOWEVENT_LEAVE: SDL_Log("Мышь покинула окна %d", event->window.windowID); break; case SDL_WINDOWEVENT_FOCUS_GAINED: SDL_Log("Окно %d получило фокус клавиатуры", event->window.windowID); break; case SDL_WINDOWEVENT_FOCUS_LOST: SDL_Log("Окно %d потеряла фокус клавиатуры", event->window.windowID); break; case SDL_WINDOWEVENT_CLOSE: SDL_Log("Окно %d закрыто", event->window.windowID); break; default: SDL_Log("Окно %d получило неизвестное событие %d", event->window.windowID, event->window.event); break; } break; default: SDL_Log("Получен неизвестное событие %d", event->type); break; } return 0; }
23.057057
163
0.711383
i582
afcd9013abc4b631e94dd5af638cb031c4873c53
27
cpp
C++
WitchEngine3/src/WE3/input/SourceHolder.cpp
jadnohra/World-Of-Football
fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc
[ "MIT" ]
3
2018-12-02T14:09:22.000Z
2021-11-22T07:14:05.000Z
WitchEngine3/src/WE3/input/SourceHolder.cpp
jadnohra/World-Of-Football
fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc
[ "MIT" ]
1
2018-12-03T22:54:38.000Z
2018-12-03T22:54:38.000Z
WitchEngine3/src/WE3/input/SourceHolder.cpp
jadnohra/World-Of-Football
fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc
[ "MIT" ]
2
2020-09-22T21:04:14.000Z
2021-05-24T09:43:28.000Z
#include "SourceHolder.h"
13.5
26
0.740741
jadnohra
afcdcc50e1f4f31417bb60aa43ec84ee85e55e0b
2,779
hpp
C++
src/CAghostnodes.hpp
streeve/ExaCA
f6bd298d9719edfe948ce629369f02ac7c18c65b
[ "MIT" ]
13
2021-06-04T14:50:33.000Z
2022-03-26T03:21:17.000Z
src/CAghostnodes.hpp
streeve/ExaCA
f6bd298d9719edfe948ce629369f02ac7c18c65b
[ "MIT" ]
30
2021-07-21T23:13:34.000Z
2022-03-29T18:37:19.000Z
src/CAghostnodes.hpp
streeve/ExaCA
f6bd298d9719edfe948ce629369f02ac7c18c65b
[ "MIT" ]
5
2021-07-21T23:36:12.000Z
2022-03-11T00:52:15.000Z
// Copyright 2021 Lawrence Livermore National Security, LLC and other ExaCA Project Developers. // See the top-level LICENSE file for details. // // SPDX-License-Identifier: MIT #ifndef EXACA_GHOST_HPP #define EXACA_GHOST_HPP #include "CAtypes.hpp" #include <Kokkos_Core.hpp> void GhostNodesInit(int, int, int DecompositionStrategy, int NeighborRank_North, int NeighborRank_South, int NeighborRank_East, int NeighborRank_West, int NeighborRank_NorthEast, int NeighborRank_NorthWest, int NeighborRank_SouthEast, int NeighborRank_SouthWest, int MyXSlices, int MyYSlices, int MyXOffset, int MyYOffset, int ZBound_Low, int nzActive, int LocalActiveDomainSize, int NGrainOrientations, ViewI NeighborX, ViewI NeighborY, ViewI NeighborZ, ViewF GrainUnitVector, ViewI GrainOrientation, ViewI GrainID, ViewI CellType, ViewF DOCenter, ViewF DiagonalLength, ViewF CritDiagonalLength); void GhostNodes2D(int, int, int NeighborRank_North, int NeighborRank_South, int NeighborRank_East, int NeighborRank_West, int NeighborRank_NorthEast, int NeighborRank_NorthWest, int NeighborRank_SouthEast, int NeighborRank_SouthWest, int MyXSlices, int MyYSlices, int MyXOffset, int MyYOffset, ViewI NeighborX, ViewI NeighborY, ViewI NeighborZ, ViewI CellType, ViewF DOCenter, ViewI GrainID, ViewF GrainUnitVector, ViewI GrainOrientation, ViewF DiagonalLength, ViewF CritDiagonalLength, int NGrainOrientations, Buffer2D BufferWestSend, Buffer2D BufferEastSend, Buffer2D BufferNorthSend, Buffer2D BufferSouthSend, Buffer2D BufferNorthEastSend, Buffer2D BufferNorthWestSend, Buffer2D BufferSouthEastSend, Buffer2D BufferSouthWestSend, Buffer2D BufferWestRecv, Buffer2D BufferEastRecv, Buffer2D BufferNorthRecv, Buffer2D BufferSouthRecv, Buffer2D BufferNorthEastRecv, Buffer2D BufferNorthWestRecv, Buffer2D BufferSouthEastRecv, Buffer2D BufferSouthWestRecv, int BufSizeX, int BufSizeY, int BufSizeZ, int ZBound_Low); void GhostNodes1D(int, int, int NeighborRank_North, int NeighborRank_South, int MyXSlices, int MyYSlices, int MyXOffset, int MyYOffset, ViewI NeighborX, ViewI NeighborY, ViewI NeighborZ, ViewI CellType, ViewF DOCenter, ViewI GrainID, ViewF GrainUnitVector, ViewI GrainOrientation, ViewF DiagonalLength, ViewF CritDiagonalLength, int NGrainOrientations, Buffer2D BufferNorthSend, Buffer2D BufferSouthSend, Buffer2D BufferNorthRecv, Buffer2D BufferSouthRecv, int BufSizeX, int, int BufSizeZ, int ZBound_Low); #endif
73.131579
120
0.732997
streeve
afd03638568c09eb7f19f3eaa4843bdc98beca12
10,745
hpp
C++
include/Library/Astrodynamics/Trajectory/Orbit/Models/Kepler.hpp
cowlicks/library-astrodynamics
aec161a1e5a1294820a90e1a74633b5a71d59a33
[ "Apache-2.0" ]
null
null
null
include/Library/Astrodynamics/Trajectory/Orbit/Models/Kepler.hpp
cowlicks/library-astrodynamics
aec161a1e5a1294820a90e1a74633b5a71d59a33
[ "Apache-2.0" ]
null
null
null
include/Library/Astrodynamics/Trajectory/Orbit/Models/Kepler.hpp
cowlicks/library-astrodynamics
aec161a1e5a1294820a90e1a74633b5a71d59a33
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @project Library/Astrodynamics /// @file Library/Astrodynamics/Trajectory/Orbit/Models/Kepler.hpp /// @author Lucas Brémond <lucas@loftorbital.com> /// @license Apache License 2.0 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef __Library_Astrodynamics_Trajectory_Orbit_Models_Kepler__ #define __Library_Astrodynamics_Trajectory_Orbit_Models_Kepler__ #include <Library/Astrodynamics/Trajectory/Orbit/Models/Kepler/COE.hpp> #include <Library/Astrodynamics/Trajectory/Orbit/Model.hpp> #include <Library/Astrodynamics/Trajectory/State.hpp> #include <Library/Physics/Environment/Objects/Celestial.hpp> #include <Library/Physics/Units/Derived.hpp> #include <Library/Physics/Units/Length.hpp> #include <Library/Physics/Time/Instant.hpp> #include <Library/Core/Types/String.hpp> #include <Library/Core/Types/Real.hpp> #include <Library/Core/Types/Integer.hpp> //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace library { namespace astro { namespace trajectory { namespace orbit { namespace models { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using library::core::types::Integer ; using library::core::types::Real ; using library::core::types::String ; using library::physics::time::Instant ; using library::physics::units::Length ; using library::physics::units::Derived ; using library::physics::env::obj::Celestial ; using library::astro::trajectory::State ; using library::astro::trajectory::orbit::models::kepler::COE ; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class Kepler : public library::astro::trajectory::orbit::Model { public: enum class PerturbationType { None, J2 } ; Kepler ( const COE& aClassicalOrbitalElementSet, const Instant& anEpoch, const Derived& aGravitationalParameter, const Length& anEquatorialRadius, const Real& aJ2, const Kepler::PerturbationType& aPerturbationType ) ; Kepler ( const COE& aClassicalOrbitalElementSet, const Instant& anEpoch, const Celestial& aCelestialObject, const Kepler::PerturbationType& aPerturbationType, const bool inFixedFrame = false ) ; virtual Kepler* clone ( ) const override ; bool operator == ( const Kepler& aKeplerianModel ) const ; bool operator != ( const Kepler& aKeplerianModel ) const ; friend std::ostream& operator << ( std::ostream& anOutputStream, const Kepler& aKeplerianModel ) ; virtual bool isDefined ( ) const override ; COE getClassicalOrbitalElements ( ) const ; virtual Instant getEpoch ( ) const override ; virtual Integer getRevolutionNumberAtEpoch ( ) const override ; Derived getGravitationalParameter ( ) const ; Length getEquatorialRadius ( ) const ; Real getJ2 ( ) const ; Kepler::PerturbationType getPerturbationType ( ) const ; virtual State calculateStateAt ( const Instant& anInstant ) const override ; virtual Integer calculateRevolutionNumberAt ( const Instant& anInstant ) const override ; // [TBR] ? virtual void print ( std::ostream& anOutputStream, bool displayDecorator = true ) const override ; static String StringFromPerturbationType ( const Kepler::PerturbationType& aPerturbationType ) ; protected: virtual bool operator == ( const trajectory::Model& aModel ) const override ; virtual bool operator != ( const trajectory::Model& aModel ) const override ; private: COE coe_ ; Instant epoch_ ; Derived gravitationalParameter_ ; Length equatorialRadius_ ; Real j2_ ; Kepler::PerturbationType perturbationType_ ; static COE InertialCoeFromFixedCoe ( const COE& aClassicalOrbitalElementSet, const Instant& anEpoch, const Celestial& aCelestialObject ) ; static State CalculateNoneStateAt ( const COE& aClassicalOrbitalElementSet, const Instant& anEpoch, const Derived& aGravitationalParameter, const Instant& anInstant ) ; static Integer CalculateNoneRevolutionNumberAt ( const COE& aClassicalOrbitalElementSet, const Instant& anEpoch, const Derived& aGravitationalParameter, const Instant& anInstant ) ; static State CalculateJ2StateAt ( const COE& aClassicalOrbitalElementSet, const Instant& anEpoch, const Derived& aGravitationalParameter, const Instant& anInstant, const Length& anEquatorialRadius, const Real& aJ2 ) ; static Integer CalculateJ2RevolutionNumberAt ( const COE& aClassicalOrbitalElementSet, const Instant& anEpoch, const Derived& aGravitationalParameter, const Instant& anInstant, const Length& anEquatorialRadius, const Real& aJ2 ) ; } ; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } } } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
62.47093
189
0.304514
cowlicks
afd146c0ac57d6534ef3fe0cfe39762f126d39fb
6,793
cpp
C++
frameworks/lua/libs/kernel/dmzLuaKernelHandle.cpp
ashok/dmz
2f8d4bced646f25abf2e98bdc0d378dafb4b32ed
[ "MIT" ]
1
2015-11-05T03:03:31.000Z
2015-11-05T03:03:31.000Z
frameworks/lua/libs/kernel/dmzLuaKernelHandle.cpp
ashok/dmz
2f8d4bced646f25abf2e98bdc0d378dafb4b32ed
[ "MIT" ]
null
null
null
frameworks/lua/libs/kernel/dmzLuaKernelHandle.cpp
ashok/dmz
2f8d4bced646f25abf2e98bdc0d378dafb4b32ed
[ "MIT" ]
null
null
null
#include <dmzLuaKernel.h> #include "dmzLuaKernelPrivate.h" #include <dmzLuaKernelValidate.h> #include <dmzRuntimeDefinitions.h> #include <dmzSystem.h> #include <dmzTypesHashTableHandleTemplate.h> #include <dmzTypesString.h> #include <luacpp.h> using namespace dmz; namespace { static const char HandleName[] = "dmz.types.handle"; static const char HandleTableName[] = "dmz.types.handle.table"; static const char HandleTableKey = 'h'; static const char LuaHandleTableKey = 'l'; typedef HashTableHandleTemplate<int> HandleTable; static HandleTable * get_handle_table (lua_State *L) { lua_pushlightuserdata (L, (void *)&HandleTableKey); lua_rawget(L, LUA_REGISTRYINDEX); HandleTable **ptr = (HandleTable **)lua_touserdata (L, -1); lua_pop (L, 1); // pop user data return ptr ? *ptr : 0; } static int handle_table_delete (lua_State *L) { HandleTable **ptr = (HandleTable **)lua_touserdata (L, 1); if (ptr && *ptr) { delete (*ptr); *ptr = 0; } return 0; } inline Handle* handle_check (lua_State *L, int index) { LUA_START_VALIDATE (L); if (index < 0) { index = lua_gettop (L) + index + 1; } Handle *result (0); if (lua_isnumber (L, index)) { Handle value = (Handle)lua_tonumber (L, index); if (value) { result = lua_create_handle (L, value); lua_replace (L, index); // Replace string with handle } } else if (lua_isstring (L, index)) { String name = lua_tostring (L, index); if (name) { Definitions def (lua_get_runtime_context (L)); Handle value = def.create_named_handle (name); result = lua_create_handle (L, value); lua_replace (L, index); // Replace string with handle } else { lua_pushstring (L, "Empty string can not be converted to named handle"); lua_error (L); } } else { result = (Handle *)luaL_checkudata (L, index, HandleName); } LUA_END_VALIDATE (L, 0); return result; } static int handle_new (lua_State *L) { lua_pushvalue (L, 1); return handle_check (L, -1) ? 1 : 0; } static int handle_is_a (lua_State *L) { if (lua_to_handle (L, 1)) { lua_pushvalue (L, 1); } else { lua_pushnil (L); } return 1; } static const luaL_Reg arrayFunc [] = { {"new", handle_new}, {"is_a", handle_is_a}, {NULL, NULL}, }; static int handle_to_string (lua_State *L) { LUA_START_VALIDATE (L); int result (0); Handle *handle = handle_check (L, 1); if (handle) { String str; str << *handle; lua_pushstring (L, str.get_buffer ()); result = 1; } LUA_END_VALIDATE (L, result); return result; } static int handle_equal (lua_State *L) { int result (0); Handle *handle1 = handle_check (L, 1); Handle *handle2 = handle_check (L, 2); if (handle1 && handle2) { lua_pushboolean (L, (handle1 == handle2 ? 1 : 0)); result = 1; } return result; } static int handle_delete (lua_State *L) { LUA_START_VALIDATE (L); Handle *ptr = handle_check (L, 1); HandleTable *ht = get_handle_table (L); if (ptr && ht) { lua_pushlightuserdata (L, (void *)&LuaHandleTableKey); lua_rawget (L, LUA_REGISTRYINDEX); const int Table (lua_gettop (L)); if (lua_istable (L, Table)) { int *indexPtr = ht->lookup (*ptr); if (indexPtr) { lua_rawgeti (L, Table, *indexPtr); Handle *found = (Handle *)lua_touserdata (L, -1); if (!found) { if (ht->remove (*ptr)) { delete indexPtr; indexPtr = 0; } } lua_pop (L, 1); // pop Handle; } } lua_pop (L, 1); // pop Handle table } LUA_END_VALIDATE (L, 0); return 0; } static const luaL_Reg arrayMembers [] = { {"__tostring", handle_to_string}, {"__eq", handle_equal}, {"__gc", handle_delete}, {NULL, NULL}, }; }; //! \cond void dmz::open_lua_kernel_handle_lib (lua_State *L) { LUA_START_VALIDATE (L); lua_pushlightuserdata (L, (void *)&HandleTableKey); HandleTable **htPtr = (HandleTable **)lua_newuserdata (L, sizeof (HandleTable *)); if (htPtr) { lua_set_gc (L, -1, handle_table_delete); *htPtr = new HandleTable; lua_rawset (L, LUA_REGISTRYINDEX); } else { lua_pop (L, 1); } // pop light user data lua_pushlightuserdata (L, (void *)&LuaHandleTableKey); lua_newtable (L); lua_set_weak_table (L, -1, "v"); lua_rawset (L, LUA_REGISTRYINDEX); luaL_newmetatable (L, HandleName); luaL_register (L, NULL, arrayMembers); lua_pushvalue (L, -1); lua_setfield (L, -2, "__index"); lua_create_dmz_namespace (L, "handle"); luaL_register (L, NULL, arrayFunc); lua_make_readonly (L, -1); // make handle read only. lua_pop (L, 2); // pops meta table and dmz.handle table. LUA_END_VALIDATE (L, 0); } //! \endcond //! \addtogroup Lua //! @{ //! Creates a Handle on the Lua stack. dmz::Handle * dmz::lua_create_handle (lua_State *L, const Handle Value) { LUA_START_VALIDATE (L); Handle *result = 0; if (Value) { HandleTable *ht (get_handle_table (L)); lua_pushlightuserdata (L, (void *)&LuaHandleTableKey); lua_rawget (L, LUA_REGISTRYINDEX); const int Table (lua_gettop (L)); if (lua_istable (L, Table) && ht) { int *indexPtr = ht->lookup (Value); if (indexPtr) { lua_rawgeti (L, Table, *indexPtr); result = (Handle *)lua_touserdata (L, -1); if (!result) { lua_pop (L, 1); } else if (*result != Value) { lua_pop (L, 1); // pop invalid Handle; result = 0; } } if (!result) { if (indexPtr && ht->remove (Value)) { delete indexPtr; indexPtr = 0; } result = (Handle *)lua_newuserdata (L, sizeof (Handle)); if (result) { lua_pushvalue (L, -1); int index = luaL_ref (L, Table); indexPtr = new int (index); if (!ht->store (Value, indexPtr)) { delete indexPtr; indexPtr = 0; } *result = Value; luaL_getmetatable (L, HandleName); lua_setmetatable (L, -2); } } } lua_remove (L, Table); // Remove Table; } if (!result) { lua_pushnil (L); } LUA_END_VALIDATE (L, 1); return result; } //! Attempts to convert the specified object on the Lua stack to a Handle. dmz::Handle * dmz::lua_to_handle (lua_State *L, int narg) { return (Handle *) lua_is_object (L, narg, HandleName); } //! Raises and error if the specified object on the stack is not a Handle. dmz::Handle * dmz::lua_check_handle (lua_State *L, int narg) { return handle_check (L, narg); } //! @}
20.901538
85
0.596055
ashok
afd61686a999ca676966fe471358861c772f1deb
8,902
cc
C++
ns-allinone-3.30/ns-3.30/src/internet/model/tcp-ledbat.cc
NEWPLAN/ns3_v3.30
c931036574ee1efd58dad6df3f6d8365b4948bcd
[ "Apache-2.0" ]
null
null
null
ns-allinone-3.30/ns-3.30/src/internet/model/tcp-ledbat.cc
NEWPLAN/ns3_v3.30
c931036574ee1efd58dad6df3f6d8365b4948bcd
[ "Apache-2.0" ]
null
null
null
ns-allinone-3.30/ns-3.30/src/internet/model/tcp-ledbat.cc
NEWPLAN/ns3_v3.30
c931036574ee1efd58dad6df3f6d8365b4948bcd
[ "Apache-2.0" ]
1
2019-10-23T15:15:27.000Z
2019-10-23T15:15:27.000Z
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2016 NITK Surathkal * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Ankit Deepak <adadeepak8@gmail.com> * */ #include "tcp-ledbat.h" #include "ns3/log.h" #include "ns3/simulator.h" namespace ns3 { NS_LOG_COMPONENT_DEFINE("TcpLedbat"); NS_OBJECT_ENSURE_REGISTERED(TcpLedbat); TypeId TcpLedbat::GetTypeId(void) { static TypeId tid = TypeId("ns3::TcpLedbat") .SetParent<TcpNewReno>() .AddConstructor<TcpLedbat>() .SetGroupName("Internet") .AddAttribute("TargetDelay", "Targeted Queue Delay", TimeValue(MilliSeconds(100)), MakeTimeAccessor(&TcpLedbat::m_target), MakeTimeChecker()) .AddAttribute("BaseHistoryLen", "Number of Base delay samples", UintegerValue(10), MakeUintegerAccessor(&TcpLedbat::m_baseHistoLen), MakeUintegerChecker<uint32_t>()) .AddAttribute("NoiseFilterLen", "Number of Current delay samples", UintegerValue(4), MakeUintegerAccessor(&TcpLedbat::m_noiseFilterLen), MakeUintegerChecker<uint32_t>()) .AddAttribute("Gain", "Offset Gain", DoubleValue(1.0), MakeDoubleAccessor(&TcpLedbat::m_gain), MakeDoubleChecker<double>()) .AddAttribute("SSParam", "Possibility of Slow Start", EnumValue(DO_SLOWSTART), MakeEnumAccessor(&TcpLedbat::SetDoSs), MakeEnumChecker(DO_SLOWSTART, "yes", DO_NOT_SLOWSTART, "no")) .AddAttribute("MinCwnd", "Minimum cWnd for Ledbat", UintegerValue(2), MakeUintegerAccessor(&TcpLedbat::m_minCwnd), MakeUintegerChecker<uint32_t>()); return tid; } void TcpLedbat::SetDoSs(SlowStartType doSS) { NS_LOG_FUNCTION(this << doSS); m_doSs = doSS; if (m_doSs) { m_flag |= LEDBAT_CAN_SS; } else { m_flag &= ~LEDBAT_CAN_SS; } } TcpLedbat::TcpLedbat(void) : TcpNewReno() { NS_LOG_FUNCTION(this); m_target = MilliSeconds(100); m_gain = 1; m_doSs = DO_SLOWSTART; m_baseHistoLen = 10; m_noiseFilterLen = 4; InitCircBuf(m_baseHistory); InitCircBuf(m_noiseFilter); m_lastRollover = 0; m_sndCwndCnt = 0; m_flag = LEDBAT_CAN_SS; m_minCwnd = 2; }; void TcpLedbat::InitCircBuf(struct OwdCircBuf &buffer) { NS_LOG_FUNCTION(this); buffer.buffer.clear(); buffer.min = 0; } TcpLedbat::TcpLedbat(const TcpLedbat &sock) : TcpNewReno(sock) { NS_LOG_FUNCTION(this); m_target = sock.m_target; m_gain = sock.m_gain; m_doSs = sock.m_doSs; m_baseHistoLen = sock.m_baseHistoLen; m_noiseFilterLen = sock.m_noiseFilterLen; m_baseHistory = sock.m_baseHistory; m_noiseFilter = sock.m_noiseFilter; m_lastRollover = sock.m_lastRollover; m_sndCwndCnt = sock.m_sndCwndCnt; m_flag = sock.m_flag; m_minCwnd = sock.m_minCwnd; } TcpLedbat::~TcpLedbat(void) { NS_LOG_FUNCTION(this); } Ptr<TcpCongestionOps> TcpLedbat::Fork(void) { return CopyObject<TcpLedbat>(this); } std::string TcpLedbat::GetName() const { return "TcpLedbat"; } uint32_t TcpLedbat::MinCircBuf(struct OwdCircBuf &b) { NS_LOG_FUNCTION_NOARGS(); if (b.buffer.size() == 0) { return ~0U; } else { return b.buffer[b.min]; } } uint32_t TcpLedbat::CurrentDelay(FilterFunction filter) { NS_LOG_FUNCTION(this); return filter(m_noiseFilter); } uint32_t TcpLedbat::BaseDelay() { NS_LOG_FUNCTION(this); return MinCircBuf(m_baseHistory); } void TcpLedbat::IncreaseWindow(Ptr<TcpSocketState> tcb, uint32_t segmentsAcked) { NS_LOG_FUNCTION(this << tcb << segmentsAcked); if (tcb->m_cWnd.Get() <= tcb->m_segmentSize) { m_flag |= LEDBAT_CAN_SS; } if (m_doSs == DO_SLOWSTART && tcb->m_cWnd <= tcb->m_ssThresh && (m_flag & LEDBAT_CAN_SS)) { SlowStart(tcb, segmentsAcked); } else { m_flag &= ~LEDBAT_CAN_SS; CongestionAvoidance(tcb, segmentsAcked); } } void TcpLedbat::CongestionAvoidance(Ptr<TcpSocketState> tcb, uint32_t segmentsAcked) { NS_LOG_FUNCTION(this << tcb << segmentsAcked); if ((m_flag & LEDBAT_VALID_OWD) == 0) { TcpNewReno::CongestionAvoidance(tcb, segmentsAcked); //letting it fall to TCP behaviour if no timestamps return; } int64_t queue_delay; double offset; uint32_t cwnd = (tcb->m_cWnd.Get()); uint32_t max_cwnd; uint64_t current_delay = CurrentDelay(&TcpLedbat::MinCircBuf); uint64_t base_delay = BaseDelay(); if (current_delay > base_delay) { queue_delay = static_cast<int64_t>(current_delay - base_delay); offset = m_target.GetMilliSeconds() - queue_delay; } else { queue_delay = static_cast<int64_t>(base_delay - current_delay); offset = m_target.GetMilliSeconds() + queue_delay; } offset *= m_gain; m_sndCwndCnt = static_cast<int32_t>(offset * segmentsAcked * tcb->m_segmentSize); double inc = (m_sndCwndCnt * 1.0) / (m_target.GetMilliSeconds() * tcb->m_cWnd.Get()); cwnd += (inc * tcb->m_segmentSize); max_cwnd = static_cast<uint32_t>(tcb->m_highTxMark.Get() - tcb->m_lastAckedSeq) + segmentsAcked * tcb->m_segmentSize; cwnd = std::min(cwnd, max_cwnd); cwnd = std::max(cwnd, m_minCwnd * tcb->m_segmentSize); tcb->m_cWnd = cwnd; if (tcb->m_cWnd <= tcb->m_ssThresh) { tcb->m_ssThresh = tcb->m_cWnd - 1; } } void TcpLedbat::AddDelay(struct OwdCircBuf &cb, uint32_t owd, uint32_t maxlen) { NS_LOG_FUNCTION(this << owd << maxlen << cb.buffer.size()); if (cb.buffer.size() == 0) { NS_LOG_LOGIC("First Value for queue"); cb.buffer.push_back(owd); cb.min = 0; return; } cb.buffer.push_back(owd); if (cb.buffer[cb.min] > owd) { cb.min = static_cast<uint32_t>(cb.buffer.size() - 1); } if (cb.buffer.size() >= maxlen) { NS_LOG_LOGIC("Queue full" << maxlen); cb.buffer.erase(cb.buffer.begin()); cb.min = 0; NS_LOG_LOGIC("Current min element" << cb.buffer[cb.min]); for (uint32_t i = 1; i < maxlen - 1; i++) { if (cb.buffer[i] < cb.buffer[cb.min]) { cb.min = i; } } } } void TcpLedbat::UpdateBaseDelay(uint32_t owd) { NS_LOG_FUNCTION(this << owd); if (m_baseHistory.buffer.size() == 0) { AddDelay(m_baseHistory, owd, m_baseHistoLen); return; } uint64_t timestamp = static_cast<uint64_t>(Simulator::Now().GetSeconds()); if (timestamp - m_lastRollover > 60) { m_lastRollover = timestamp; AddDelay(m_baseHistory, owd, m_baseHistoLen); } else { uint32_t last = static_cast<uint32_t>(m_baseHistory.buffer.size() - 1); if (owd < m_baseHistory.buffer[last]) { m_baseHistory.buffer[last] = owd; if (owd < m_baseHistory.buffer[m_baseHistory.min]) { m_baseHistory.min = last; } } } } void TcpLedbat::PktsAcked(Ptr<TcpSocketState> tcb, uint32_t segmentsAcked, const Time &rtt) { NS_LOG_FUNCTION(this << tcb << segmentsAcked << rtt); if (tcb->m_rcvTimestampValue == 0 || tcb->m_rcvTimestampEchoReply == 0) { m_flag &= ~LEDBAT_VALID_OWD; } else { m_flag |= LEDBAT_VALID_OWD; } if (rtt.IsPositive()) { AddDelay(m_noiseFilter, tcb->m_rcvTimestampValue - tcb->m_rcvTimestampEchoReply, m_noiseFilterLen); UpdateBaseDelay(tcb->m_rcvTimestampValue - tcb->m_rcvTimestampEchoReply); } } } // namespace ns3
28.809061
119
0.599416
NEWPLAN
afdafc445a97e97903270769867114615ec67fd1
268
cpp
C++
timus/2100.cpp
y-wan/OJ
5dea140dbaaec98e440ad4b1c10fa5072f1ceea7
[ "MIT" ]
null
null
null
timus/2100.cpp
y-wan/OJ
5dea140dbaaec98e440ad4b1c10fa5072f1ceea7
[ "MIT" ]
null
null
null
timus/2100.cpp
y-wan/OJ
5dea140dbaaec98e440ad4b1c10fa5072f1ceea7
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main() { int n; string s; cin >> n; int sum = n + 2; for (int i = 0; i < n; i++) { cin >> s; if (s[s.size() - 4] == '+') sum++; } if (sum == 13) sum++; cout << 100 * sum << endl; return 0; }
14.888889
36
0.496269
y-wan
afdc73c0e5a987e35e16416b60dd714a5847b7ee
1,657
cpp
C++
test/src/MISC/Common/LongRunningOperation.cpp
theoremprover/cpp-parser
543cd50acc9e08aadf278b9c970d4db6c332887a
[ "BSD-3-Clause" ]
18
2018-05-10T18:50:06.000Z
2022-01-11T17:11:34.000Z
test/src/MISC/Common/LongRunningOperation.cpp
theoremprover/cpp-parser
543cd50acc9e08aadf278b9c970d4db6c332887a
[ "BSD-3-Clause" ]
24
2018-06-14T17:54:17.000Z
2022-03-11T23:21:29.000Z
test/src/MISC/Common/LongRunningOperation.cpp
theoremprover/cpp-parser
543cd50acc9e08aadf278b9c970d4db6c332887a
[ "BSD-3-Clause" ]
4
2019-04-02T16:04:34.000Z
2022-01-10T11:44:43.000Z
// This file is part of Notepad++ project // Copyright (C)2003 Don HO <don.h@free.fr> // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // Note that the GPL places important restrictions on "derived works", yet // it does not provide a detailed definition of that term. To avoid // misunderstandings, we consider an application to constitute a // "derivative work" for the purpose of this license if it does any of the // following: // 1. Integrates source code from Notepad++. // 2. Integrates/includes/aggregates Notepad++ into a proprietary executable // installer, such as those produced by InstallShield. // 3. Links to a library or executes a program that does any of the above. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #include "LongRunningOperation.h" #include "mutex.h" using namespace Yuni; LongRunningOperation::LongRunningOperation() { Mutex::ClassLevelLockable<LongRunningOperation>::mutex.lock(); } LongRunningOperation::~LongRunningOperation() { Mutex::ClassLevelLockable<LongRunningOperation>::mutex.unlock(); }
33.816327
76
0.754375
theoremprover
afe2e3508b335766c62fc986f31dba7fb2f00ecf
911
cpp
C++
cppPrime/cppBrowse_c02/test_10.cpp
ilvcr/cpplgproject
d3dc492b37c3754e35669eee2dd96d83de63ead4
[ "Apache-2.0" ]
null
null
null
cppPrime/cppBrowse_c02/test_10.cpp
ilvcr/cpplgproject
d3dc492b37c3754e35669eee2dd96d83de63ead4
[ "Apache-2.0" ]
null
null
null
cppPrime/cppBrowse_c02/test_10.cpp
ilvcr/cpplgproject
d3dc492b37c3754e35669eee2dd96d83de63ead4
[ "Apache-2.0" ]
null
null
null
/************************************************************************* > File Name: test_10.cpp > Author: @Yoghourt->ilvcr, Cn,Sx,Ty > Mail: ilvcr@outlook.com || liyaoliu@foxmail.com > Created Time: 2018年06月21日 星期四 23时30分40秒 > Description: 将泛型算法应用到vector类对象上 ************************************************************************/ #include<iostream> #include<algorithm> #include<vector> using namespace std; int ia[10] = {51, 23, 7, 88, 41, 98, 12, 103, 37, 6}; int main() { vector<int> vec(ia, ia+10); //排序数组 sort(vec.begin(), vec.end()); //获取值 int search_value; cin >> search_value; //搜索元素 vector<int>::iterator found; found = find(vec.begin(), vec.end(), search_value); if(found != vec.end()) cout << "search_value found!\n"; else cout << "search_value not found!\n"; //反转数组 reverse(vec.begin(), vec.end()); return 0; }
23.358974
74
0.512623
ilvcr
afe9b85bc1688b517c46b98ca8f2066909a22edb
2,036
cc
C++
PTA/PAT_A/Cpp11/A1075_AC.cc
StrayDragon/OJ-Solutions
b31b11c01507544aded2302923da080b39cf2ba8
[ "MIT" ]
1
2019-05-13T10:09:55.000Z
2019-05-13T10:09:55.000Z
PTA/PAT_A/Cpp11/A1075_AC.cc
StrayDragon/OJ-Solutions
b31b11c01507544aded2302923da080b39cf2ba8
[ "MIT" ]
null
null
null
PTA/PAT_A/Cpp11/A1075_AC.cc
StrayDragon/OJ-Solutions
b31b11c01507544aded2302923da080b39cf2ba8
[ "MIT" ]
null
null
null
// --- // id : 1075 // title : PAT Judge // difficulty : Medium // score : 25 // tag : Primary Algorithm // keyword : sort // status : AC // from : PAT (Advanced Level) Practice // --- #include <algorithm> #include <iostream> #include <vector> using namespace std; struct User { int rank, id, total = 0; vector<int> scores; int perfect_cnt = 0; bool at_least_pass_one = false; }; int main() { int n, k, m; scanf("%d %d %d", &n, &k, &m); vector<User> v(n + 1); for (int i = 1; i <= n; i++) v[i].scores.resize(k + 1, -1); vector<int> fullscores(k + 1); for (int i = 1; i <= k; i++) scanf("%d", &fullscores[i]); for (int id, si, score, i = 0; i < m; i++) { scanf("%d %d %d", &id, &si, &score); v[id].id = id; v[id].scores[si] = std::max(v[id].scores[si], score); if (score != -1) v[id].at_least_pass_one = true; else if (v[id].scores[si] == -1) v[id].scores[si] = -2; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= k; j++) { if (v[i].scores[j] != -1 && v[i].scores[j] != -2) v[i].total += v[i].scores[j]; if (v[i].scores[j] == fullscores[j]) v[i].perfect_cnt++; } } std::sort(v.begin() + 1, v.end(), [](const User& lhs, const User& rhs) { if (lhs.total != rhs.total) return lhs.total > rhs.total; else if (lhs.perfect_cnt != rhs.perfect_cnt) return lhs.perfect_cnt > rhs.perfect_cnt; else return lhs.id < rhs.id; }); for (int i = 1; i <= n; i++) { v[i].rank = i; if (i != 1 && v[i].total == v[i - 1].total) v[i].rank = v[i - 1].rank; } for (int i = 1; i <= n; i++) { if (v[i].at_least_pass_one) { printf("%d %05d %d", v[i].rank, v[i].id, v[i].total); for (int j = 1; j <= k; j++) { if (v[i].scores[j] != -1 && v[i].scores[j] != -2) printf(" %d", v[i].scores[j]); else if (v[i].scores[j] == -1) printf(" -"); else printf(" 0"); } printf("\n"); } } return 0; }
25.135802
74
0.478389
StrayDragon
afedea283c5bfd25ca1256f4f676b4c187dc5e08
7,233
cpp
C++
src/lz4mt_result.cpp
1shekhar/lz4mt-cpp
a01631c2a5496c8d6335801d270b3d8688da078d
[ "BSD-2-Clause" ]
140
2015-01-08T03:42:50.000Z
2022-02-15T13:08:27.000Z
src/lz4mt_result.cpp
1shekhar/lz4mt-cpp
a01631c2a5496c8d6335801d270b3d8688da078d
[ "BSD-2-Clause" ]
15
2015-01-29T21:00:39.000Z
2021-11-25T14:20:12.000Z
src/lz4mt_result.cpp
1shekhar/lz4mt-cpp
a01631c2a5496c8d6335801d270b3d8688da078d
[ "BSD-2-Clause" ]
40
2015-01-13T07:19:05.000Z
2022-01-12T18:24:30.000Z
#include "lz4mt.h" extern "C" const char* lz4mtResultToString(Lz4MtResult result) { const char* s = "???"; switch(result) { case LZ4MT_RESULT_OK: s = "OK"; break; case LZ4MT_RESULT_ERROR: s = "ERROR"; break; case LZ4MT_RESULT_INVALID_MAGIC_NUMBER: s = "INVALID_MAGIC_NUMBER"; break; case LZ4MT_RESULT_INVALID_HEADER: s = "INVALID_HEADER"; break; case LZ4MT_RESULT_PRESET_DICTIONARY_IS_NOT_SUPPORTED_YET: s = "PRESET_DICTIONARY_IS_NOT_SUPPORTED_YET"; break; case LZ4MT_RESULT_BLOCK_DEPENDENCE_IS_NOT_SUPPORTED_YET: s = "BLOCK_DEPENDENCE_IS_NOT_SUPPORTED_YET"; break; case LZ4MT_RESULT_INVALID_VERSION: s = "INVALID_VERSION"; break; case LZ4MT_RESULT_INVALID_HEADER_CHECKSUM: s = "INVALID_HEADER_CHECKSUM"; break; case LZ4MT_RESULT_INVALID_BLOCK_MAXIMUM_SIZE: s = "INVALID_BLOCK_MAXIMUM_SIZE"; break; case LZ4MT_RESULT_CANNOT_WRITE_HEADER: s = "CANNOT_WRITE_HEADER"; break; case LZ4MT_RESULT_CANNOT_WRITE_EOS: s = "CANNOT_WRITE_EOS"; break; case LZ4MT_RESULT_CANNOT_WRITE_STREAM_CHECKSUM: s = "CANNOT_WRITE_STREAM_CHECKSUM"; break; case LZ4MT_RESULT_CANNOT_READ_BLOCK_SIZE: s = "CANNOT_READ_BLOCK_SIZE"; break; case LZ4MT_RESULT_CANNOT_READ_BLOCK_DATA: s = "CANNOT_READ_BLOCK_DATA"; break; case LZ4MT_RESULT_CANNOT_READ_BLOCK_CHECKSUM: s = "CANNOT_READ_BLOCK_CHECKSUM"; break; case LZ4MT_RESULT_CANNOT_READ_STREAM_CHECKSUM: s = "CANNOT_READ_STREAM_CHECKSUM"; break; case LZ4MT_RESULT_STREAM_CHECKSUM_MISMATCH: s = "STREAM_CHECKSUM_MISMATCH"; break; case LZ4MT_RESULT_DECOMPRESS_FAIL: s = "DECOMPRESS_FAIL"; break; case LZ4MT_RESULT_BAD_ARG: s = "BAD_ARG"; break; case LZ4MT_RESULT_INVALID_BLOCK_SIZE: s = "INVALID_BLOCK_SIZE"; break; case LZ4MT_RESULT_INVALID_HEADER_RESERVED1: s = "INVALID_HEADER_RESERVED1"; break; case LZ4MT_RESULT_INVALID_HEADER_RESERVED2: s = "INVALID_HEADER_RESERVED2"; break; case LZ4MT_RESULT_INVALID_HEADER_RESERVED3: s = "INVALID_HEADER_RESERVED3"; break; case LZ4MT_RESULT_CANNOT_WRITE_DATA_BLOCK: s = "CANNOT_WRITE_DATA_BLOCK"; break; case LZ4MT_RESULT_CANNOT_WRITE_DECODED_BLOCK: s = "CANNOT_WRITE_DECODED_BLOCK"; break; default: s = "Unknown code"; break; } return s; } extern "C" int lz4mtResultToLz4cExitCode(Lz4MtResult result) { int e = 1; switch(result) { case LZ4MT_RESULT_OK: e = 0; break; case LZ4MT_RESULT_ERROR: e = 1; break; case LZ4MT_RESULT_INVALID_MAGIC_NUMBER: // selectDecoder() // if (ftell(finput) == MAGICNUMBER_SIZE) EXM_THROW(44,"Unrecognized header : file cannot be decoded"); // Wrong magic number at the beginning of 1st stream e = 44; break; case LZ4MT_RESULT_INVALID_HEADER_SKIPPABLE_SIZE_UNREADABLE: // selectDecoder() // if (nbReadBytes != 4) EXM_THROW(42, "Stream error : skippable size unreadable"); e = 42; break; case LZ4MT_RESULT_INVALID_HEADER_CANNOT_SKIP_SKIPPABLE_AREA: // selectDecoder() // if (errorNb != 0) EXM_THROW(43, "Stream error : cannot skip skippable area"); e = 43; break; case LZ4MT_RESULT_BLOCK_DEPENDENCE_IS_NOT_SUPPORTED_YET: e = 1; break; case LZ4MT_RESULT_CANNOT_WRITE_HEADER: // compress_file_blockDependency() // LZ4IO_compressFilename() // if (sizeCheck!=header_size) EXM_THROW(32, "Write error : cannot write header"); // e = 32; break; case LZ4MT_RESULT_CANNOT_WRITE_EOS: // compress_file_blockDependency() // LZ4IO_compressFilename() // if (sizeCheck!=(size_t)(4)) EXM_THROW(37, "Write error : cannot write end of stream"); // e = 37; break; case LZ4MT_RESULT_CANNOT_WRITE_STREAM_CHECKSUM: // compress_file_blockDependency() // LZ4IO_compressFilename() // if (sizeCheck!=(size_t)(4)) EXM_THROW(37, "Write error : cannot write stream checksum"); e = 37; break; case LZ4MT_RESULT_INVALID_HEADER: // decodeLZ4S() // if (nbReadBytes != 3) EXM_THROW(61, "Unreadable header"); e = 61; break; case LZ4MT_RESULT_INVALID_VERSION: //decodeLZ4S() // if (version != 1) EXM_THROW(62, "Wrong version number"); e = 62; break; case LZ4MT_RESULT_INVALID_HEADER_RESERVED1: //decodeLZ4S() // if (reserved1 != 0) EXM_THROW(65, "Wrong value for reserved bits"); e = 65; break; case LZ4MT_RESULT_PRESET_DICTIONARY_IS_NOT_SUPPORTED_YET: // decodeLZ4S() // if (dictionary == 1) EXM_THROW(66, "Does not support dictionary"); e = 66; break; case LZ4MT_RESULT_INVALID_HEADER_RESERVED2: //decodeLZ4S() // if (reserved2 != 0) EXM_THROW(67, "Wrong value for reserved bits"); e = 67; break; case LZ4MT_RESULT_INVALID_HEADER_RESERVED3: //decodeLZ4S() // if (reserved3 != 0) EXM_THROW(67, "Wrong value for reserved bits"); e = 67; break; case LZ4MT_RESULT_INVALID_BLOCK_MAXIMUM_SIZE: // decodeLZ4S() // if (blockSizeId < 4) EXM_THROW(68, "Unsupported block size"); e = 68; break; case LZ4MT_RESULT_INVALID_HEADER_CHECKSUM: // decodeLZ4S() // if (checkBits != checkBits_xxh32) EXM_THROW(69, "Stream descriptor error detected"); e = 69; break; case LZ4MT_RESULT_CANNOT_READ_BLOCK_SIZE: // decodeLZ4S() // if( nbReadBytes != 4 ) EXM_THROW(71, "Read error : cannot read next block size"); e = 71; break; case LZ4MT_RESULT_INVALID_BLOCK_SIZE: // decodeLZ4S() // if (blockSize > maxBlockSize) EXM_THROW(72, "Error : invalid block size"); e = 72; break; case LZ4MT_RESULT_CANNOT_READ_BLOCK_DATA: // decodeLZ4S() // if( nbReadBytes != blockSize ) EXM_THROW(73, "Read error : cannot read data block" ); e = 73; break; case LZ4MT_RESULT_CANNOT_READ_BLOCK_CHECKSUM: // decodeLZ4S() // if( sizeCheck != 4 ) EXM_THROW(74, "Read error : cannot read next block size"); e = 74; break; case LZ4MT_RESULT_BLOCK_CHECKSUM_MISMATCH: // decodeLZ4S() // if (checksum != readChecksum) EXM_THROW(75, "Error : invalid block checksum detected"); e = 75; break; case LZ4MT_RESULT_CANNOT_READ_STREAM_CHECKSUM: // decodeLZ4S() // if (sizeCheck != 4) EXM_THROW(74, "Read error : cannot read stream checksum"); e = 74; break; case LZ4MT_RESULT_STREAM_CHECKSUM_MISMATCH: // decodeLZ4S() // if (checksum != readChecksum) EXM_THROW(75, "Error : invalid stream checksum detected"); e = 75; break; case LZ4MT_RESULT_CANNOT_WRITE_DATA_BLOCK: // cannot write incompressible block // decodeLZ4S() // if (sizeCheck != (size_t)blockSize) EXM_THROW(76, "Write error : cannot write data block"); e = 76; break; case LZ4MT_RESULT_DECOMPRESS_FAIL: // decodeLZ4S() // if (decodedBytes < 0) EXM_THROW(77, "Decoding Failed ! Corrupted input detected !"); e = 77; break; case LZ4MT_RESULT_CANNOT_WRITE_DECODED_BLOCK: // decodeLZ4S() // if (sizeCheck != (size_t)decodedBytes) EXM_THROW(78, "Write error : cannot write decoded block\n"); e = 78; break; default: // LZ4IO_compressFilename_Legacy() // if (!in_buff || !out_buff) EXM_THROW(21, "Allocation error : not enough memory"); // if (sizeCheck!=MAGICNUMBER_SIZE) EXM_THROW(22, "Write error : cannot write header"); // // decodeLZ4S() // if (streamSize == 1) EXM_THROW(64, "Does not support stream size"); // NOTE : lz4mt support the streamSize header flag. e = 1; break; } return e; }
26.690037
161
0.718651
1shekhar
aff3322e251c03dea97c9a0bedf81187344ccea0
475
cc
C++
actions.cc
amadio/g4run
05dbfd0ec30567d0a60513d3002994094cd51af3
[ "BSD-2-Clause" ]
2
2020-08-18T12:22:13.000Z
2022-03-12T17:01:05.000Z
actions.cc
amadio/g4run
05dbfd0ec30567d0a60513d3002994094cd51af3
[ "BSD-2-Clause" ]
null
null
null
actions.cc
amadio/g4run
05dbfd0ec30567d0a60513d3002994094cd51af3
[ "BSD-2-Clause" ]
null
null
null
#include "actions.h" G4Run* RunAction::GenerateRun() { return nullptr; } void RunAction::BeginOfRunAction(const G4Run*) { } void RunAction::EndOfRunAction(const G4Run*) { } void EventAction::BeginOfEventAction(const G4Event*) { } void EventAction::EndOfEventAction(const G4Event*) { } void TrackingAction::PreUserTrackingAction(const G4Track*) { } void TrackingAction::PostUserTrackingAction(const G4Track*) { } void SteppingAction::UserSteppingAction(const G4Step*) { }
33.928571
63
0.772632
amadio
aff434f15dd46c9df3ed72ad489bfa072dcf1e37
3,332
cpp
C++
src/poll.cpp
TheClonerx/cppnet
1d282824d227542a3b130c37ef068ebddb212fa5
[ "MIT" ]
7
2019-03-03T05:43:52.000Z
2021-08-28T01:24:44.000Z
src/poll.cpp
TheClonerx/cppnet
1d282824d227542a3b130c37ef068ebddb212fa5
[ "MIT" ]
null
null
null
src/poll.cpp
TheClonerx/cppnet
1d282824d227542a3b130c37ef068ebddb212fa5
[ "MIT" ]
1
2020-01-02T05:47:12.000Z
2020-01-02T05:47:12.000Z
#include <cppnet/poll.hpp> #include <algorithm> bool net::poll::add(socket::native_handle_type fd, int eventmask) { if (fd < 0) return false; auto it = std::find_if(fds.begin(), fds.end(), [fd](const pollfd& p) { return p.fd == fd; }); if (it != fds.end()) return false; fds.push_back(pollfd { fd, static_cast<short>(eventmask), 0 }); return true; } bool net::poll::modify(socket::native_handle_type fd, int eventmask) { if (fd < 0) return false; auto it = std::find_if(fds.begin(), fds.end(), [fd](const pollfd& p) { return p.fd == fd; }); if (it == fds.end()) return false; it->events = eventmask; return true; } bool net::poll::remove(socket::native_handle_type fd) { if (fd < 0) return false; auto it = std::find_if(fds.begin(), fds.end(), [fd](const pollfd& p) { return p.fd == fd; }); if (it == fds.end()) return false; fds.erase(it); return true; } size_t net::poll::execute(std::optional<std::chrono::milliseconds> timeout) { for (pollfd& fd : fds) fd.revents = 0; #ifdef _WIN32 int ret = ::WSAPoll(fds.data(), static_cast<ULONG>(fds.size()), static_cast<INT>(timeout ? timeout->count() : -1)); if (ret < 0) throw std::system_error(WSAGetLastError(), std::system_category()); #else int ret = ::poll(fds.data(), fds.size(), timeout ? timeout->count() : -1); if (ret < 0) throw std::system_error(errno, std::system_category()); #endif return ret; } size_t net::poll::execute(std::optional<std::chrono::milliseconds> timeout, std::error_code& e) noexcept { for (pollfd& fd : fds) fd.revents = 0; #ifdef _WIN32 int ret = ::WSAPoll(fds.data(), static_cast<ULONG>(fds.size()), static_cast<INT>(timeout ? timeout->count() : -1)); if (ret < 0) e.assign(WSAGetLastError(), std::system_category()); #else int ret = ::poll(fds.data(), fds.size(), timeout ? timeout->count() : -1); if (ret < 0) e.assign(errno, std::system_category()); #endif return ret; } #ifdef _GNU_SOURCE size_t net::poll::execute(std::optional<std::chrono::nanoseconds> timeout, const sigset_t& sigmask) { timespec tm; if (timeout) { tm.tv_sec = std::chrono::duration_cast<std::chrono::seconds>(*timeout).count(); tm.tv_nsec = timeout->count() % std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::seconds(1)).count(); } for (pollfd& fd : fds) fd.revents = 0; int ret = ::ppoll(fds.data(), fds.size(), timeout ? &tm : nullptr, &sigmask); if (ret < 0) throw std::system_error(errno, std::system_category()); return ret; } size_t net::poll::execute(std::optional<std::chrono::nanoseconds> timeout, const sigset_t& sigmask, std::error_code& e) noexcept { timespec tm; if (timeout) { tm.tv_sec = std::chrono::duration_cast<std::chrono::seconds>(*timeout).count(); tm.tv_nsec = timeout->count() % std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::seconds(1)).count(); } for (pollfd& fd : fds) fd.revents = 0; int ret = ::ppoll(fds.data(), fds.size(), timeout ? &tm : nullptr, &sigmask); if (ret < 0) e.assign(errno, std::system_category()); return ret; } #endif
28.724138
128
0.604142
TheClonerx
aff5a97359496a813dfb2ec91f1506e5a4b269e0
537
hpp
C++
src/Enclave/binary/logic.hpp
dove-project/dove-backend
e9f4f6211181ccc9072416816d65793dc137444b
[ "MIT" ]
null
null
null
src/Enclave/binary/logic.hpp
dove-project/dove-backend
e9f4f6211181ccc9072416816d65793dc137444b
[ "MIT" ]
null
null
null
src/Enclave/binary/logic.hpp
dove-project/dove-backend
e9f4f6211181ccc9072416816d65793dc137444b
[ "MIT" ]
null
null
null
#ifndef _LOGIC_HPP #define _LOGIC_HPP #include "../binary_op.hpp" #ifdef LIB_FTFP class BitwiseAndOp: public BinaryOp { void call(fixed scalar1, fixed scalar2, fixed *result); }; class BitwiseOrOp: public BinaryOp { void call(fixed scalar1, fixed scalar2, fixed *result); }; #else class BitwiseAndOp: public BinaryOp { void call(double scalar1, double scalar2, double *result); }; class BitwiseOrOp: public BinaryOp { void call(double scalar1, double scalar2, double *result); }; #endif /* LIB_FTFP */ #endif /* _LOGIC_HPP */
23.347826
60
0.73743
dove-project
aff66757a237a9cc4ba9c0d79d3c7b310a77a916
557
cpp
C++
UVa Online Judge/10976 - Fractions Again.cpp
SamanKhamesian/ACM-ICPC-Problems
c68c04bee4de9ba9f30e665cd108484e0fcae4d7
[ "Apache-2.0" ]
2
2019-03-19T23:59:48.000Z
2019-03-21T20:13:12.000Z
UVa Online Judge/10976 - Fractions Again.cpp
SamanKhamesian/ACM-ICPC-Problems
c68c04bee4de9ba9f30e665cd108484e0fcae4d7
[ "Apache-2.0" ]
null
null
null
UVa Online Judge/10976 - Fractions Again.cpp
SamanKhamesian/ACM-ICPC-Problems
c68c04bee4de9ba9f30e665cd108484e0fcae4d7
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <algorithm> #include <cmath> #include <set> #include <vector> using namespace std; int main() { int k; vector <pair <int, int>> ans; while (cin >> k) { ans.clear(); for (int y = k + 1; y <= 2 * k; y++) { int x = ((k * y) / (y - k)); if ((k * y) % (y - k) == 0) { ans.push_back(make_pair(x, y)); } } cout << (int)ans.size() << endl; for (int i = 0; i < (int)ans.size(); i++) { printf("1/%d = 1/%d + 1/%d\n", k, ans[i].first, ans[i].second); } } }
15.472222
67
0.452424
SamanKhamesian
aff78f49864e880352a13d5671ccc2629f72f429
742
hpp
C++
TypeTraits/IsMemberPointer.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
2
2021-06-09T00:38:46.000Z
2021-09-04T21:55:33.000Z
TypeTraits/IsMemberPointer.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
null
null
null
TypeTraits/IsMemberPointer.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
1
2021-08-30T00:46:12.000Z
2021-08-30T00:46:12.000Z
// // Created by phoenixflower on 10/12/19. // #ifndef LANDESSDEVDATASTRUCTURES_ISMEMBERPOINTER_H #define LANDESSDEVDATASTRUCTURES_ISMEMBERPOINTER_H //#include "Definitions/Common.hpp" namespace LD { namespace Detail { template< class T > struct is_member_pointer_helper : LD::FalseType{}; template< class T, class U > struct is_member_pointer_helper<T U::*> : LD::TrueType {}; template< class T > struct is_member_pointer : is_member_pointer_helper<typename LD::Detail::RemoveCV<T>::type> {}; } template<typename T> constexpr bool IsMemberPointer = LD::Detail::is_member_pointer<T>::value; } #endif //LANDESSDEVDATASTRUCTURES_ISMEMBERPOINTER_H
26.5
84
0.685984
jlandess
aff897b6d20f05945ace3db06260645217b01119
1,798
cc
C++
src/factory-py.cc
florent-lamiraux/dynamic-graph-python
3adadf9e64585dfc623726af9f87f363da99284a
[ "BSD-2-Clause" ]
null
null
null
src/factory-py.cc
florent-lamiraux/dynamic-graph-python
3adadf9e64585dfc623726af9f87f363da99284a
[ "BSD-2-Clause" ]
null
null
null
src/factory-py.cc
florent-lamiraux/dynamic-graph-python
3adadf9e64585dfc623726af9f87f363da99284a
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2010, Florent Lamiraux, Thomas Moulard, LAAS-CNRS. // // This file is part of dynamic-graph-python. // dynamic-graph-python is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either // version 3 of the License, or (at your option) any later version. // // dynamic-graph-python is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Lesser Public License for more details. You should // have received a copy of the GNU Lesser General Public License along // with dynamic-graph. If not, see <http://www.gnu.org/licenses/>. #include <Python.h> #include <iostream> #include <dynamic-graph/factory.h> using dynamicgraph::Entity; using dynamicgraph::ExceptionAbstract; namespace dynamicgraph { namespace python { namespace factory { /** \brief Get name of entity */ PyObject* getEntityClassList(PyObject* /*self*/, PyObject* args) { if (!PyArg_ParseTuple(args, "")) return NULL; std::vector <std::string> classNames; dynamicgraph::FactoryStorage::getInstance() ->listEntities(classNames); Py_ssize_t classNumber = classNames.size(); // Build a tuple object PyObject* classTuple = PyTuple_New(classNumber); for (Py_ssize_t iEntity = 0; iEntity < (Py_ssize_t)classNames.size(); ++iEntity) { PyObject* className = Py_BuildValue("s", classNames[iEntity].c_str()); PyTuple_SetItem(classTuple, iEntity, className); } return Py_BuildValue("O", classTuple); } } // namespace factory } // namespace python } // namespace dynamicgraph
30.474576
70
0.713571
florent-lamiraux
affad5f7b825cc3df186ffecf55dc0b8ae2b88d8
1,513
cpp
C++
arduino-libs/Pacman/src/AmbushState.cpp
taylorsmithatnominet/BSidesCBR-2021-Badge
df3f13d780d6fb1b6d03d08e9bdd72f507f69aa6
[ "MIT" ]
null
null
null
arduino-libs/Pacman/src/AmbushState.cpp
taylorsmithatnominet/BSidesCBR-2021-Badge
df3f13d780d6fb1b6d03d08e9bdd72f507f69aa6
[ "MIT" ]
null
null
null
arduino-libs/Pacman/src/AmbushState.cpp
taylorsmithatnominet/BSidesCBR-2021-Badge
df3f13d780d6fb1b6d03d08e9bdd72f507f69aa6
[ "MIT" ]
null
null
null
#include "AmbushState.h" #include "Level.h" #include "MovementModule.h" #include "Player.h" #include "PathFinderModule.h" #include "Config.h" namespace pacman { Vect2 AmbushState::GetNextTarget() { Vect2 next = *m_playerwPtr->GetPos(); m_datawPtr->m_levelwPtr->NextIntersection(next, m_playerwPtr->GetDirection()); // if ghost is on target it will stop, so it sets the target to the player if (next == m_datawPtr->m_pos->Round()) { return m_playerwPtr->GetPos()->Round(); } return next; } void AmbushState::UpdatePath() { m_currentTarget = GetNextTarget(); m_pathfinder->UpdatePath(m_currentTarget, *m_playerwPtr->GetPos()); } AmbushState::AmbushState(GameObjectData* p_data, Player* p_player) : IGhostState(p_data), m_playerwPtr(p_player) { m_pathfinder = new PathFinderModule(m_datawPtr->m_levelwPtr); UpdatePath(); } AmbushState::~AmbushState() { delete m_pathfinder; m_pathfinder = nullptr; } bool AmbushState::Update(float p_delta) { Vect2* pos = m_datawPtr->m_pos; Vect2 nextDir = Vect2::ZERO; if (m_datawPtr->m_movement->SteppedOnTile()) { Vect2 currentDir = m_datawPtr->m_movement->GetDirection(); Vect2 back = Vect2(-currentDir.x, -currentDir.y); nextDir = m_pathfinder->GetNextDir(*pos, back); } m_datawPtr->m_movement->Update(p_delta, nextDir, float(Config::MOVEMENT_SPEED), false); if (m_pathfinder->ReachedGoal(*m_datawPtr->m_pos)) { UpdatePath(); return false; } return true; } void AmbushState::Enter() { UpdatePath(); } }; // namespace pacman
20.445946
88
0.727693
taylorsmithatnominet
affb2458f5b7d83a31f0e74be076cbaf4cb652fa
3,405
cpp
C++
Source/DemoScene/DX9Vector3.cpp
ookumaneko/PC-Psp-Cross-Platform-Demoscene
0c192f9ecf5a4fd9db3c9a2c9998b365bf480c1e
[ "MIT" ]
null
null
null
Source/DemoScene/DX9Vector3.cpp
ookumaneko/PC-Psp-Cross-Platform-Demoscene
0c192f9ecf5a4fd9db3c9a2c9998b365bf480c1e
[ "MIT" ]
null
null
null
Source/DemoScene/DX9Vector3.cpp
ookumaneko/PC-Psp-Cross-Platform-Demoscene
0c192f9ecf5a4fd9db3c9a2c9998b365bf480c1e
[ "MIT" ]
null
null
null
#ifndef _PSP_VER #include "Vector3.h" Vector3& Vector3::operator =(const Vector3 &rhs) { _vec = rhs._vec; return *this; } Vector3 Vector3::operator +(const Vector3& rhs) const { Vector3 ret; D3DXVec3Add( &ret._vec, &_vec, &rhs._vec ); return ret; } Vector3 Vector3::operator- (const Vector3& rhs) const { Vector3 ret; D3DXVec3Subtract( &ret._vec, &_vec, &rhs._vec ); return ret; } Vector3 Vector3::operator* (const float scalar) const { Vector3 ret; D3DXVec3Scale( &ret._vec, &_vec, scalar ); return ret; } Vector3& Vector3::operator+= (const Vector3& rhs) { D3DXVec3Add( &_vec, &_vec, &rhs._vec ); return *this; } Vector3& Vector3::operator-= (const Vector3& rhs) { D3DXVec3Subtract( &_vec, &_vec, &rhs._vec ); return *this; } Vector3& Vector3::operator*= (const float scalar) { D3DXVec3Scale( &_vec, &_vec, scalar ); return *this; } bool Vector3::operator== (const Vector3& rhs) { if ( _vec == rhs._vec ) return true; else return false; } bool Vector3::operator!= (const Vector3& rhs) { return !( *this == rhs ); } void Vector3::Add(const Vector3& rhs) { _vec += rhs._vec; } void Vector3::Add(const Vector3& vec1, const Vector3& vec2, Vector3& out) { D3DXVec3Add( &out._vec, &vec1._vec, &vec2._vec ); } void Vector3::Subtract(const Vector3& rhs) { _vec = _vec - rhs._vec; } void Vector3::Subtract(const Vector3& vec1, const Vector3& vec2, Vector3& out) { D3DXVec3Subtract( &out._vec, &vec1._vec, &vec2._vec ); } void Vector3::Multiply(const Vector3& rhs) { _vec.x *= rhs._vec.x; _vec.y *= rhs._vec.y; _vec.z *= rhs._vec.z; } void Vector3::Multiply(float scalar) { _vec *= scalar; } void Vector3::Multiply(const Vector3& vec1, const Vector3& vec2, Vector3& out) { out._vec.x = vec1._vec.x * vec2._vec.x; out._vec.y = vec1._vec.y * vec2._vec.y; out._vec.z = vec1._vec.z * vec2._vec.z; } void Vector3::Multiply(float scalar, Vector3& in, Vector3& out) { out._vec = in._vec * scalar; } void Vector3::Divide(const Vector3& rhs) { _vec.x /= rhs._vec.x; _vec.y /= rhs._vec.y; _vec.z /= rhs._vec.z; } void Vector3::Divide(const Vector3& vec1, const Vector3& vec2, Vector3& out) { out._vec.x = vec1._vec.x / vec2._vec.x; out._vec.y = vec1._vec.y / vec2._vec.y; out._vec.z = vec1._vec.z / vec2._vec.z; } void Vector3::Normalize() { D3DXVec3Normalize( &_vec, &_vec ); } void Vector3::Normalize(const Vector3& in, Vector3& out) { D3DXVec3Normalize( &out._vec, &in._vec ); } float Vector3::MagnitudeSquare(void) { return D3DXVec3LengthSq( &_vec ); } float Vector3::MagnitudeSquare(const Vector3& rhs) { return D3DXVec3LengthSq( &rhs._vec ); } Vector3 Vector3::Lerp(Vector3 &start, Vector3 &end, float amount) { Vector3 ret; D3DXVec3Lerp( &ret._vec, &start._vec, &end._vec, amount ); return ret; } void Vector3::Lerp(Vector3 &start, Vector3 &end, float amount, Vector3 &out) { D3DXVec3Lerp( &out._vec, &start._vec, &end._vec, amount ); } float Vector3::DotProduct(const Vector3& rhs) { return D3DXVec3Dot( &_vec, &rhs._vec ); } float Vector3::DotProduct(const Vector3& vec1, const Vector3& vec2) { return D3DXVec3Dot( &vec1._vec, &vec2._vec ); } Vector3 Vector3::CrossProduct(const Vector3& rhs, const Vector3& rhs2) { D3DXVec3Cross( &_vec, &rhs._vec, &rhs2._vec ); return *this; } void Vector3::CrossProduct(const Vector3& vec1, const Vector3& vec2, Vector3& out) { D3DXVec3Cross( &out._vec, &vec1._vec, &vec2._vec ); } #endif
19.346591
82
0.684288
ookumaneko
9b7c242e21a2a00dc1e56060aba426bdbd26aa2f
884
cpp
C++
src/npf/layout/rows.cpp
yeSpud/Tumblr-cpp
0f69846abf47495384077488fda49a2b17dfc439
[ "MIT" ]
1
2021-07-16T04:25:02.000Z
2021-07-16T04:25:02.000Z
src/npf/layout/rows.cpp
yeSpud/Tumblr-cpp
0f69846abf47495384077488fda49a2b17dfc439
[ "MIT" ]
4
2021-09-16T08:46:40.000Z
2022-03-12T05:12:20.000Z
src/npf/layout/rows.cpp
yeSpud/Tumblr-cpp
0f69846abf47495384077488fda49a2b17dfc439
[ "MIT" ]
null
null
null
// // Created by Spud on 7/16/21. // #include "npf/layout/rows.hpp" void Rows::populateBlocks(const JSON_ARRAY &array) { // TODO Comments display = std::vector<std::vector<int>>(array.Size()); for (JSON_ARRAY_ENTRY &entry : array) { if (entry.IsObject()) { JSON_OBJECT object = entry.GetObj(); POPULATE_ARRAY(object, "blocks", JSON_ARRAY intArray = object["blocks"].GetArray(); std::vector<int> block = std::vector<int>(intArray.Size()); for (JSON_ARRAY_ENTRY &blockEntry : intArray) { if (blockEntry.IsInt()) { block.push_back(blockEntry.GetInt()); } } display.push_back(block);) } } } void Rows::populateNPF(JSON_OBJECT entry) { // TODO Comments POPULATE_ARRAY(entry, "display", populateBlocks(entry["display"].GetArray());) objectHasValue(entry, "truncate_after", truncate_after); // TODO Mode (when implemented) }
23.891892
86
0.670814
yeSpud
9b805aa696c8ec98cb29950c14711a0a32d847bd
433
cpp
C++
competitive_programming/programming_contests/uri/handball.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
205
2018-12-01T17:49:49.000Z
2021-12-22T07:02:27.000Z
competitive_programming/programming_contests/uri/handball.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
2
2020-01-01T16:34:29.000Z
2020-04-26T19:11:13.000Z
competitive_programming/programming_contests/uri/handball.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
50
2018-11-28T20:51:36.000Z
2021-11-29T04:08:25.000Z
// https://www.urionlinejudge.com.br/judge/en/problems/view/1715 #include <iostream> using namespace std; int main() { int players, matches, p; while (cin >> players >> matches) { int counter = 0; for (int i = 0; i < players; i++) { bool scored = true; for (int j = 0; j < matches; j++) { cin >> p; if (p == 0) scored = false; } if (scored) counter++; } cout << counter << endl; } return 0; }
16.037037
64
0.56351
LeandroTk
9b8245efdb7e9da180d5eab0976e5c7db2a2d9b3
1,903
cpp
C++
example-Sprite/src/CustomSpriteA.cpp
selflash/ofxSelflash
087a263b2d4de970edd75ecab2c2a48b7b58e62d
[ "MIT" ]
19
2015-05-14T09:57:38.000Z
2022-01-10T23:32:28.000Z
example-Sprite/src/CustomSpriteA.cpp
selflash/ofxSelflash
087a263b2d4de970edd75ecab2c2a48b7b58e62d
[ "MIT" ]
3
2015-08-04T09:07:26.000Z
2018-01-18T07:14:35.000Z
example-Sprite/src/CustomSpriteA.cpp
selflash/ofxSelflash
087a263b2d4de970edd75ecab2c2a48b7b58e62d
[ "MIT" ]
1
2015-08-04T09:05:22.000Z
2015-08-04T09:05:22.000Z
#include "CustomSpriteA.h" //============================================================== // Constructor / Destructor //============================================================== //-------------------------------------------------------------- CustomSpriteA::CustomSpriteA() { ofLog() << "[CustomSpriteA]CustomSpriteA()"; _target = this; buttonMode(true); // visible(false); //-------------------------------------- flGraphics* g; g = graphics(); g->clear(); g->lineStyle(1, 0xff0000); g->beginFill(0xffffff); g->drawRect(0, 0, 100, 100); g->endFill(); //-------------------------------------- } //-------------------------------------------------------------- CustomSpriteA::~CustomSpriteA() { ofLog() << "[CustomSpriteA]~CustomSpriteA()"; } //============================================================== // Setup / Update / Draw //============================================================== //-------------------------------------------------------------- void CustomSpriteA::_setup() { // ofLog() << "[CustomSpriteA]_setup()"; } //-------------------------------------------------------------- void CustomSpriteA::_update() { // ofLog() << "[CustomSpriteA]_update()"; } //-------------------------------------------------------------- void CustomSpriteA::_draw() { // ofLog() << "[CustomSpriteA]_draw()"; } //============================================================== // Public Method //============================================================== //============================================================== // Protected / Private Method //============================================================== //============================================================== // Private Event Handler //==============================================================
29.276923
64
0.257488
selflash
9b85c208fc178f98f0861559d9f07fda788d569f
702
cpp
C++
TriviallyCopyable.cpp
haxpor/cpp_st
43d1492266c6e01e6e243c834fba26eedf1ab9f3
[ "MIT" ]
2
2021-06-10T22:05:01.000Z
2021-09-17T08:21:20.000Z
TriviallyCopyable.cpp
haxpor/cpp_st
43d1492266c6e01e6e243c834fba26eedf1ab9f3
[ "MIT" ]
null
null
null
TriviallyCopyable.cpp
haxpor/cpp_st
43d1492266c6e01e6e243c834fba26eedf1ab9f3
[ "MIT" ]
1
2020-02-25T04:26:52.000Z
2020-02-25T04:26:52.000Z
/** * Testbed on checking whether std::vector<scalar-type> is trivially copyable or not via * type traits. * * Read more about trivially copyable at Notes section in https://en.cppreference.com/w/cpp/types/is_trivially_copyable */ #include <type_traits> #include <iostream> #include <vector> std::vector<unsigned int> vec; int main() { unsigned int arr[10]; // std::vector is not trivially copyable std::cout << std::boolalpha << std::is_trivially_copyable<std::vector<unsigned int>>::value << std::endl; // arr is a pointer, and pointer is trivially copyable std::cout << std::boolalpha << std::is_trivially_copyable<unsigned int[10]>::value << std::endl; return 0; }
30.521739
119
0.702279
haxpor
9b8833ba7e7bdfcedd0db0682b215621dc48e04b
14,489
cpp
C++
src/gtirb_pprinter/AArch64PrettyPrinter.cpp
binrats/gtirb-pprinter
864640a62fe41068a80e0ef295da9d0522402aab
[ "MIT" ]
null
null
null
src/gtirb_pprinter/AArch64PrettyPrinter.cpp
binrats/gtirb-pprinter
864640a62fe41068a80e0ef295da9d0522402aab
[ "MIT" ]
null
null
null
src/gtirb_pprinter/AArch64PrettyPrinter.cpp
binrats/gtirb-pprinter
864640a62fe41068a80e0ef295da9d0522402aab
[ "MIT" ]
null
null
null
//===- AArch64PrettyPrinter.cpp ---------------------------------*- C++ -*-===// // // Copyright (c) 2020, The Binrat Developers. // // This code is licensed under the GNU Affero General Public License // as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. See the // LICENSE.txt file in the project root for license terms or visit // https://www.gnu.org/licenses/agpl.txt. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // //===----------------------------------------------------------------------===// #include "AArch64PrettyPrinter.hpp" #include "AuxDataSchema.hpp" #include <capstone/capstone.h> namespace gtirb_pprint { AArch64PrettyPrinter::AArch64PrettyPrinter(gtirb::Context& context_, gtirb::Module& module_, const ElfSyntax& syntax_, const PrintingPolicy& policy_) : ElfPrettyPrinter(context_, module_, syntax_, policy_, CS_ARCH_ARM64, CS_MODE_ARM) {} void AArch64PrettyPrinter::printHeader(std::ostream& os) { this->printBar(os); // header this->printBar(os); os << '\n'; for (int i = 0; i < 8; i++) { os << syntax.nop() << '\n'; } } std::string AArch64PrettyPrinter::getRegisterName(unsigned int reg) const { return reg == ARM64_REG_INVALID ? "" : cs_reg_name(this->csHandle, reg); } void AArch64PrettyPrinter::printOperandList(std::ostream& os, const cs_insn& inst) { cs_arm64& detail = inst.detail->arm64; uint8_t opCount = detail.op_count; for (int i = 0; i < opCount; i++) { if (i != 0) { os << ','; } printOperand(os, inst, i); } } void AArch64PrettyPrinter::printOperand(std::ostream& os, const cs_insn& inst, uint64_t index) { gtirb::Addr ea(inst.address); const cs_arm64_op& op = inst.detail->arm64.operands[index]; const gtirb::SymbolicExpression* symbolic = nullptr; bool finalOp = (index + 1 == inst.detail->arm64.op_count); switch (op.type) { case ARM64_OP_REG: printOpRegdirect(os, inst, op.reg); // add extender if needed if (op.ext != ARM64_EXT_INVALID) { os << ", "; printExtender(os, op.ext, op.shift.type, op.shift.value); } return; case ARM64_OP_IMM: if (finalOp) { auto pos = module.findSymbolicExpressionsAt(ea); if (!pos.empty()) { symbolic = &pos.begin()->getSymbolicExpression(); } } printOpImmediate(os, symbolic, inst, index); return; case ARM64_OP_MEM: if (finalOp) { auto pos = module.findSymbolicExpressionsAt(ea); if (!pos.empty()) { symbolic = &pos.begin()->getSymbolicExpression(); } } printOpIndirect(os, symbolic, inst, index); return; case ARM64_OP_FP: os << "#" << op.fp; return; case ARM64_OP_CIMM: case ARM64_OP_REG_MRS: case ARM64_OP_REG_MSR: case ARM64_OP_PSTATE: case ARM64_OP_SYS: // print the operand directly printOpRawValue(os, inst, index); return; case ARM64_OP_PREFETCH: printOpPrefetch(os, op.prefetch); return; case ARM64_OP_BARRIER: printOpBarrier(os, op.barrier); return; case ARM64_OP_INVALID: default: std::cerr << "invalid operand\n"; exit(1); } } void AArch64PrettyPrinter::printPrefix(std::ostream& os, const cs_insn& inst, uint64_t index) { auto* symbolicOperandInfo = module.getAuxData<gtirb::schema::SymbolicOperandInfoAD>(); for (const auto& pair : *symbolicOperandInfo) { const auto& symbolInfo = pair.second; if (pair.first == gtirb::Addr(inst.address) && index == std::get<0>(symbolInfo)) { os << std::get<1>(symbolInfo); } } } void AArch64PrettyPrinter::printOpRegdirect(std::ostream& os, const cs_insn& /* inst */, unsigned int reg) { os << getRegisterName(reg); } void AArch64PrettyPrinter::printOpImmediate(std::ostream& os, const gtirb::SymbolicExpression* symbolic, const cs_insn& inst, uint64_t index) { const cs_arm64_op& op = inst.detail->arm64.operands[index]; assert(op.type == ARM64_OP_IMM && "printOpImmediate called without an immediate operand"); bool is_jump = cs_insn_group(this->csHandle, &inst, ARM64_GRP_JUMP); if (const gtirb::SymAddrConst* s = this->getSymbolicImmediate(symbolic)) { if (!is_jump) { os << ' '; } printPrefix(os, inst, index); this->printSymbolicExpression(os, s, !is_jump); } else { os << "#" << op.imm; if (op.shift.type != ARM64_SFT_INVALID && op.shift.value != 0) { os << ","; printShift(os, op.shift.type, op.shift.value); } } } void AArch64PrettyPrinter::printOpIndirect(std::ostream& os, const gtirb::SymbolicExpression* symbolic, const cs_insn& inst, uint64_t index) { const cs_arm64& detail = inst.detail->arm64; const cs_arm64_op& op = detail.operands[index]; assert(op.type == ARM64_OP_MEM && "printOpIndirect called without a memory operand"); bool first = true; os << "["; // base register if (op.mem.base != ARM64_REG_INVALID) { first = false; os << getRegisterName(op.mem.base); } // displacement (constant) if (op.mem.disp != 0) { if (!first) { os << ","; } if (const auto* s = std::get_if<gtirb::SymAddrConst>(symbolic)) { printPrefix(os, inst, index); printSymbolicExpression(os, s, false); } else { os << "#" << op.mem.disp; } first = false; } // index register if (op.mem.index != ARM64_REG_INVALID) { if (!first) { os << ","; } first = false; os << getRegisterName(op.mem.index); } // add shift if (op.shift.type != ARM64_SFT_INVALID && op.shift.value != 0) { os << ","; assert(!first && "unexpected shift operator"); printShift(os, op.shift.type, op.shift.value); } os << "]"; if (detail.writeback && index + 1 == detail.op_count) { os << "!"; } } void AArch64PrettyPrinter::printOpRawValue(std::ostream& os, const cs_insn& inst, uint64_t index) { // grab the full operand string const char* opStr = inst.op_str; // flick through to the start of the operand unsigned int currOperand = 0; bool inBlock = false; const char* pos; for (pos = opStr; *pos != '\0' && currOperand != index; pos++) { char cur = *pos; if (cur == '[') { // entering an indirect memory access assert(!inBlock && "nested blocks should not be possible"); inBlock = true; } else if (cur == ']') { // exiting an indirect memory access assert(inBlock && "Closing unopened memory access"); inBlock = false; } else if (!inBlock && cur == ',') { // hit a new operand currOperand++; } } assert(currOperand == index && "unexpected end of operands"); const char* operandStart = pos; // find the end of the operand while (*pos != '\0') { char cur = *pos; if (cur == '[') { inBlock = true; } else if (cur == ']') { inBlock = false; } else if (!inBlock && cur == ',') { // found end of operand break; } pos++; } const char* operandEnd = pos; // skip leading whitespace while (isspace(*operandStart)) operandStart++; // print every character in the operand for (const char* cur = operandStart; cur < operandEnd; cur++) { os << *cur; } } void AArch64PrettyPrinter::printOpBarrier(std::ostream& os, const arm64_barrier_op barrier) { switch (barrier) { case ARM64_BARRIER_OSHLD: os << "oshld"; return; case ARM64_BARRIER_OSHST: os << "oshst"; return; case ARM64_BARRIER_OSH: os << "osh"; return; case ARM64_BARRIER_NSHLD: os << "nshld"; return; case ARM64_BARRIER_NSHST: os << "nshst"; return; case ARM64_BARRIER_NSH: os << "nsh"; return; case ARM64_BARRIER_ISHLD: os << "ishld"; return; case ARM64_BARRIER_ISHST: os << "ishst"; return; case ARM64_BARRIER_ISH: os << "ish"; return; case ARM64_BARRIER_LD: os << "ld"; return; case ARM64_BARRIER_ST: os << "st"; return; case ARM64_BARRIER_SY: os << "sy"; return; case ARM64_BARRIER_INVALID: default: std::cerr << "invalid operand\n"; exit(1); } } void AArch64PrettyPrinter::printOpPrefetch(std::ostream& os, const arm64_prefetch_op prefetch) { switch (prefetch) { case ARM64_PRFM_PLDL1KEEP: os << "pldl1keep"; return; case ARM64_PRFM_PLDL1STRM: os << "pldl1strm"; return; case ARM64_PRFM_PLDL2KEEP: os << "pldl2keep"; return; case ARM64_PRFM_PLDL2STRM: os << "pldl2strm"; return; case ARM64_PRFM_PLDL3KEEP: os << "pldl3keep"; return; case ARM64_PRFM_PLDL3STRM: os << "pldl3strm"; return; case ARM64_PRFM_PLIL1KEEP: os << "plil1keep"; return; case ARM64_PRFM_PLIL1STRM: os << "plil1strm"; return; case ARM64_PRFM_PLIL2KEEP: os << "plil2keep"; return; case ARM64_PRFM_PLIL2STRM: os << "plil2strm"; return; case ARM64_PRFM_PLIL3KEEP: os << "plil3keep"; return; case ARM64_PRFM_PLIL3STRM: os << "plil3strm"; return; case ARM64_PRFM_PSTL1KEEP: os << "pstl1keep"; return; case ARM64_PRFM_PSTL1STRM: os << "pstl1strm"; return; case ARM64_PRFM_PSTL2KEEP: os << "pstl2keep"; return; case ARM64_PRFM_PSTL2STRM: os << "pstl2strm"; return; case ARM64_PRFM_PSTL3KEEP: os << "pstl3keep"; return; case ARM64_PRFM_PSTL3STRM: os << "pstl3strm"; return; case ARM64_PRFM_INVALID: default: std::cerr << "invalid operand\n"; exit(1); } } void AArch64PrettyPrinter::printShift(std::ostream& os, const arm64_shifter type, unsigned int value) { switch (type) { case ARM64_SFT_LSL: os << "lsl"; break; case ARM64_SFT_MSL: os << "msl"; break; case ARM64_SFT_LSR: os << "lsr"; break; case ARM64_SFT_ASR: os << "asr"; break; case ARM64_SFT_ROR: os << "ror"; break; default: assert(false && "unexpected case"); } os << " #" << value; } void AArch64PrettyPrinter::printExtender(std::ostream& os, const arm64_extender& ext, const arm64_shifter shiftType, uint64_t shiftValue) { switch (ext) { case ARM64_EXT_UXTB: os << "uxtb"; break; case ARM64_EXT_UXTH: os << "uxth"; break; case ARM64_EXT_UXTW: os << "uxtw"; break; case ARM64_EXT_UXTX: os << "uxtx"; break; case ARM64_EXT_SXTB: os << "sxtb"; break; case ARM64_EXT_SXTH: os << "sxth"; break; case ARM64_EXT_SXTW: os << "sxtw"; break; case ARM64_EXT_SXTX: os << "sxtx"; break; default: assert(false && "unexpected case"); } if (shiftType != ARM64_SFT_INVALID) { assert(shiftType == ARM64_SFT_LSL && "unexpected shift type in extender"); os << " #" << shiftValue; } } std::optional<std::string> AArch64PrettyPrinter::getForwardedSymbolName(const gtirb::Symbol* symbol, bool /* inData */) const { const auto* symbolForwarding = module.getAuxData<gtirb::schema::SymbolForwarding>(); if (symbolForwarding) { auto found = symbolForwarding->find(symbol->getUUID()); if (found != symbolForwarding->end()) { gtirb::Node* destSymbol = gtirb::Node::getByUUID(context, found->second); return cast<gtirb::Symbol>(destSymbol)->getName(); } } return {}; } const PrintingPolicy& AArch64PrettyPrinterFactory::defaultPrintingPolicy() const { static PrintingPolicy DefaultPolicy{ /// Sections to avoid printing. {".comment", ".plt", ".init", ".fini", ".got", ".plt.got", ".got.plt", ".plt.sec", ".eh_frame_hdr"}, /// Functions to avoid printing. {"_start", "deregister_tm_clones", "register_tm_clones", "__do_global_dtors_aux", "frame_dummy", "__libc_csu_fini", "__libc_csu_init", "_dl_relocate_static_pie", "call_weak_fn"}, /// Sections with possible data object exclusion. {".init_array", ".fini_array"}, }; return DefaultPolicy; } std::unique_ptr<PrettyPrinterBase> AArch64PrettyPrinterFactory::create(gtirb::Context& gtirb_context, gtirb::Module& module, const PrintingPolicy& policy) { static const ElfSyntax syntax{}; return std::make_unique<AArch64PrettyPrinter>(gtirb_context, module, syntax, policy); } volatile bool AArch64PrettyPrinter::registered = registerPrinter( {"elf"}, {"aarch64"}, std::make_shared<AArch64PrettyPrinterFactory>(), true); }
30.697034
139
0.549934
binrats
9b8a17ad719aea690882161969571456622fe051
864
cpp
C++
microsoft/15.cpp
19yetnoob/-6Companies30days
93f8dc6370cae7a8907d02b3ac8de610b73b8d9f
[ "MIT" ]
null
null
null
microsoft/15.cpp
19yetnoob/-6Companies30days
93f8dc6370cae7a8907d02b3ac8de610b73b8d9f
[ "MIT" ]
null
null
null
microsoft/15.cpp
19yetnoob/-6Companies30days
93f8dc6370cae7a8907d02b3ac8de610b73b8d9f
[ "MIT" ]
null
null
null
void dfs(int node,set<int>s[],vector<int>&visit,string &ans){ visit[node]=1; for(auto a:s[node]){ if(visit[a]==-1) dfs(a,s,visit,ans); } ans=(char)('a'+node)+ans; } string findOrder(string dict[], int N, int K) { set<int>v[26]; for(int i=0;i<N-1;i++){ string a=dict[i]; string b=dict[i+1]; int m=min(a.size(),b.size()); for(int j=0;j<m;j++){ if(a[j]!=b[j]) { v[a[j]-'a'].insert(b[j]-'a'); break; } } } string ans=""; vector<int>visit(26,-1); for(int i=0;i<26;i++){ if(visit[i]==-1&&v[i].size()>0){ dfs(i,v,visit,ans); } } return ans; }
27.870968
62
0.359954
19yetnoob
9b8b881113ff6ca95474e985ffbb0bc2d3d5d058
11,401
cpp
C++
software/arduino-1.8.13/portable/sketchbook/libraries/UArmForArduino/src/uArmController.cpp
abstractguy/TSO_project
1130e6fb081d1486ff15339a9757c46a927a2965
[ "BSD-2-Clause" ]
1
2021-06-06T14:12:32.000Z
2021-06-06T14:12:32.000Z
software/arduino-1.8.13/portable/sketchbook/libraries/UArmForArduino/src/uArmController.cpp
abstractguy/TSO_project
1130e6fb081d1486ff15339a9757c46a927a2965
[ "BSD-2-Clause" ]
6
2021-04-06T12:35:34.000Z
2022-03-12T00:58:16.000Z
software/arduino-1.8.13/portable/sketchbook/libraries/UArmForArduino/src/uArmController.cpp
abstractguy/TSO_project
1130e6fb081d1486ff15339a9757c46a927a2965
[ "BSD-2-Clause" ]
2
2020-03-05T00:09:48.000Z
2021-06-03T20:06:03.000Z
/** ****************************************************************************** * @file uArmController.cpp * @author David.Long * @email xiaokun.long@ufactory.cc * @date 2016-09-28 * @license GNU * copyright(c) 2016 UFactory Team. All right reserved * @modified Samuel Duclos ****************************************************************************** */ #include <assert.h> #include "uArmController.h" uArmController controller; uArmController::uArmController() {mServoSpeed = 255;} void uArmController::init() { #ifdef DEVICE_ESP32 ESP32PWM::allocateTimer(0); // Allocate one timer. ESP32PWM::allocateTimer(1); // Allocate one timer. ESP32PWM::allocateTimer(2); // Allocate one timer. ESP32PWM::allocateTimer(3); // Allocate one timer. mServo[SERVO_ROT_NUM].setPeriodHertz(50); // Standard 50hz servo. mServo[SERVO_LEFT_NUM].setPeriodHertz(50); // Standard 50hz servo. mServo[SERVO_RIGHT_NUM].setPeriodHertz(50); // Standard 50hz servo. // TODO: merge <ESP32Servo.h> with <Servo.h>. mServo[SERVO_ROT_NUM].attach(SERVO_ROT_NUM, 500, 2500); mServo[SERVO_LEFT_NUM].attach(SERVO_LEFT_NUM, 500, 2500); mServo[SERVO_RIGHT_NUM].attach(SERVO_RIGHT_NUM, 500, 2500); #ifndef SAVE_PINS mServo[SERVO_HAND_ROT_NUM].setPeriodHertz(50); // Standard 50hz servo. mServo[SERVO_HAND_ROT_NUM].attach(SERVO_HAND_ROT_NUM, 600, 2400); #endif #else mServo[SERVO_ROT_NUM].setPulseWidthRange(500, 2500); mServo[SERVO_LEFT_NUM].setPulseWidthRange(500, 2500); mServo[SERVO_RIGHT_NUM].setPulseWidthRange(500, 2500); #ifndef SAVE_PINS mServo[SERVO_HAND_ROT_NUM].setPulseWidthRange(600, 2400); #endif attachAllServo(); #endif bool withOffset = true; #ifdef DISABLE_SERVO_OFFSET withOffset = false; #endif mCurAngle[0] = readServoAngle(SERVO_ROT_NUM, withOffset); mCurAngle[1] = readServoAngle(SERVO_LEFT_NUM, withOffset); mCurAngle[2] = readServoAngle(SERVO_RIGHT_NUM, withOffset); mCurAngle[3] = readServoAngle(SERVO_HAND_ROT_NUM, withOffset); } void uArmController::attachAllServo() { for (int i = SERVO_ROT_NUM; i < SERVO_COUNT; i++) mServo[i].attach(SERVO_CONTROL_PIN[i]); } void uArmController::attachServo(byte servoNum) { mServo[servoNum].attach(SERVO_CONTROL_PIN[servoNum]); } void uArmController::detachServo(byte servoNum) { mServo[servoNum].detach(); } void uArmController::detachAllServo() { for (int i = SERVO_ROT_NUM; i < SERVO_COUNT; i++) detachServo(i); } void uArmController::writeServoAngle(double servoRotAngle, double servoLeftAngle, double servoRightAngle) { writeServoAngle(SERVO_ROT_NUM, servoRotAngle); writeServoAngle(SERVO_LEFT_NUM, servoLeftAngle); writeServoAngle(SERVO_RIGHT_NUM, servoRightAngle); } double uArmController::getReverseServoAngle(byte servoNum, double servoAngle) {return servoAngle;} void uArmController::writeServoAngle(byte servoNum, double servoAngle, boolean writeWithOffset) { #ifdef DISABLE_SERVO_OFFSET writeWithOffset = false; #endif servoAngle = constrain(servoAngle, 0.00, 180.00); mCurAngle[servoNum] = servoAngle; servoAngle = writeWithOffset ? (servoAngle + mServoAngleOffset[servoNum]) : servoAngle; #ifdef DISABLE_SERVO_SPEED mServo[servoNum].write(servoAngle); #else mServo[servoNum].write(servoAngle, mServoSpeed); #endif } double uArmController::readServoAngle(byte servoNum, boolean withOffset) { double angle; #ifdef DISABLE_SERVO_OFFSET withOffset = false; #endif if (servoNum == SERVO_HAND_ROT_NUM) angle = map(getServoAnalogData(SERVO_HAND_ROT_ANALOG_PIN), SERVO_9G_MIN, SERVO_9G_MAX, 0, 180); else angle = analogToAngle(servoNum, getServoAnalogData(servoNum)); if (withOffset) angle -= mServoAngleOffset[servoNum]; angle = constrain(angle, 0.00, 180.00); return angle; } double uArmController::readServoAngles(double& servoRotAngle, double& servoLeftAngle, double& servoRightAngle, boolean withOffset) { #ifdef DISABLE_SERVO_OFFSET withOffset = false; #endif servoRotAngle = readServoAngle(SERVO_ROT_NUM, withOffset); servoLeftAngle = readServoAngle(SERVO_LEFT_NUM, withOffset); servoRightAngle = readServoAngle(SERVO_RIGHT_NUM, withOffset); } double uArmController::getServoAngles(double& servoRotAngle, double& servoLeftAngle, double& servoRightAngle) { servoRotAngle = mCurAngle[SERVO_ROT_NUM]; servoLeftAngle = mCurAngle[SERVO_LEFT_NUM]; servoRightAngle = mCurAngle[SERVO_RIGHT_NUM]; } double uArmController::getServoAngle(byte servoNum) { return mCurAngle[servoNum]; } void uArmController::updateAllServoAngle(boolean withOffset) { #ifdef DISABLE_SERVO_OFFSET withOffset = false; #endif for (unsigned char servoNum = SERVO_ROT_NUM; servoNum < SERVO_COUNT; servoNum++) { mCurAngle[servoNum] = readServoAngle(servoNum, withOffset); } } unsigned char uArmController::getCurrentXYZ(double& x, double& y, double& z) { double stretch = MATH_LOWER_ARM * cos(mCurAngle[SERVO_LEFT_NUM] / MATH_TRANS) + MATH_UPPER_ARM * cos(mCurAngle[SERVO_RIGHT_NUM] / MATH_TRANS) + MATH_L2 + MATH_FRONT_HEADER; double height = MATH_LOWER_ARM * sin(mCurAngle[SERVO_LEFT_NUM] / MATH_TRANS) - MATH_UPPER_ARM * sin(mCurAngle[SERVO_RIGHT_NUM] / MATH_TRANS) + MATH_L1; x = stretch * cos(mCurAngle[SERVO_ROT_NUM] / MATH_TRANS); y = stretch * sin(mCurAngle[SERVO_ROT_NUM] / MATH_TRANS); z = height; return IN_RANGE; } unsigned char uArmController::getXYZFromAngle(double& x, double& y, double& z, double rot, double left, double right) { double stretch = MATH_LOWER_ARM * cos(left / MATH_TRANS) + MATH_UPPER_ARM * cos(right / MATH_TRANS) + MATH_L2 + MATH_FRONT_HEADER; double height = MATH_LOWER_ARM * sin(left / MATH_TRANS) - MATH_UPPER_ARM * sin(right / MATH_TRANS) + MATH_L1; x = stretch * cos(rot / MATH_TRANS); y = stretch * sin(rot / MATH_TRANS); z = height; return IN_RANGE; } unsigned char uArmController::xyzToAngle(double x, double y, double z, double& angleRot, double& angleLeft, double& angleRight, boolean allowApproximate) { double xIn = 0.0; double zIn = 0.0; double rightAll = 0.0; double sqrtZX = 0.0; double phi = 0.0; x = constrain(x, -3276, 3276); y = constrain(y, -3276, 3276); z = constrain(z, -3276, 3276); x = (double)((int)(x * 10) / 10.0); y = (double)((int)(y * 10) / 10.0); z = (double)((int)(z * 10) / 10.0); if (z > MAX_Z || z < MIN_Z) return OUT_OF_RANGE_NO_SOLUTION; zIn = (z - MATH_L1) / MATH_LOWER_ARM; if (!allowApproximate) { // If need the move to closest point we have to jump over the return function. if (y < 0) return OUT_OF_RANGE_NO_SOLUTION; // Check the range of x. } // Calculate value of theta 1: the rotation angle. if (x == 0) angleRot = 90; else { if (x > 0) angleRot = atan(y / x) * MATH_TRANS; // Angle tranfer 0-180 CCW. if (x < 0) angleRot = 180 + atan(y / x) * MATH_TRANS; // Angle tranfer 0-180 CCW. } // Calculate value of theta 3. if (angleRot != 90) // xIn is the stretch. xIn = (x / cos(angleRot / MATH_TRANS) - MATH_L2 - MATH_FRONT_HEADER) / MATH_LOWER_ARM; else xIn = (y - MATH_L2 - MATH_FRONT_HEADER) / MATH_LOWER_ARM; phi = atan(zIn / xIn) * MATH_TRANS; // phi is the angle of line (from joint 2 to joint 4) with the horizon. sqrtZX = sqrt(zIn * zIn + xIn * xIn); rightAll = (sqrtZX * sqrtZX + MATH_UPPER_LOWER * MATH_UPPER_LOWER - 1) / (2 * MATH_UPPER_LOWER * sqrtZX); // Cosine law. angleRight = acos(rightAll) * MATH_TRANS; // Cosine law. // Calculate value of theta 2. rightAll = (sqrtZX * sqrtZX + 1 - MATH_UPPER_LOWER * MATH_UPPER_LOWER ) / (2 * sqrtZX); // Cosine law. angleLeft = acos(rightAll) * MATH_TRANS; // Cosine law. angleLeft = angleLeft + phi; angleRight = angleRight - phi; // Determine if the angle can be reached. return limitRange(angleRot, angleLeft, angleRight); } unsigned char uArmController::limitRange(double& angleRot, double& angleLeft, double& angleRight) { unsigned char result = IN_RANGE; // Determine if the angle can be reached. if (isnan(angleRot) || isnan(angleLeft) || isnan(angleRight)) result = OUT_OF_RANGE_NO_SOLUTION; else if (((angleLeft + mServoAngleOffset[SERVO_LEFT_NUM]) < LOWER_ARM_MIN_ANGLE) || ((angleLeft + mServoAngleOffset[SERVO_LEFT_NUM]) > LOWER_ARM_MAX_ANGLE)) // Check the right in range. result = OUT_OF_RANGE; else if (((angleRight + mServoAngleOffset[SERVO_RIGHT_NUM]) < UPPER_ARM_MIN_ANGLE) || ((angleRight + mServoAngleOffset[SERVO_RIGHT_NUM]) > UPPER_ARM_MAX_ANGLE)) // Check the left in range. result = OUT_OF_RANGE; else if (((180 - angleLeft - angleRight) > LOWER_UPPER_MAX_ANGLE) || ((180 - angleLeft - angleRight) < LOWER_UPPER_MIN_ANGLE)) // Check the angle of upper arm and lowe arm in range. result = OUT_OF_RANGE; angleRot = constrain(angleRot, 0.00, 180.00); angleLeft = constrain(angleLeft, 0.00, 180.00); angleRight = constrain(angleRight, 0.00, 180.00); return result; } double uArmController::analogToAngle(byte servoNum, int inputAnalog) { double intercept = 0.0f; double slope = 0.0f; switch (servoNum) { case 0: intercept = SERVO_0_INTERCEPT; slope = SERVO_0_SLOPE; break; case 1: intercept = SERVO_1_INTERCEPT; slope = SERVO_1_SLOPE; break; case 2: intercept = SERVO_2_INTERCEPT; slope = SERVO_2_SLOPE; break; case 3: intercept = SERVO_3_INTERCEPT; slope = SERVO_3_SLOPE; break; default: assert(0); break; } double angle = intercept + slope * inputAnalog; return angle; } unsigned int uArmController::getServoAnalogData(byte servoNum) { return getAnalogPinValue(SERVO_ANALOG_PIN[servoNum]); } static void _sort(unsigned int array[], unsigned int len) { unsigned int temp = 0; for (unsigned char i = 0; i < len; i++) { for (unsigned char j = 0; i + j < (len - 1); j++) { if (array[j] > array[j + 1]) { temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } } /*! \brief get gripper status \return STOP if gripper is not working \return WORKING if gripper is working but not catched sth \return GRABBING if gripper got sth */ unsigned char uArmController::getGripperStatus() { #ifdef DEVICE_ESP32 return STOP; #else if (digitalRead(GRIPPER) == HIGH) return STOP; else { if (getAnalogPinValue(GRIPPER_FEEDBACK) > 600) return WORKING; else return GRABBING; } #endif } /*! \brief get pin value \param pin of arduino \return HIGH or LOW */ int uArmController::getDigitalPinValue(unsigned int pin) { return digitalRead(pin); } /*! \brief set pin value \param pin of arduino \param value: HIGH or LOW */ void uArmController::setDigitalPinValue(unsigned int pin, unsigned char value) { if (value) digitalWrite(pin, HIGH); else digitalWrite(pin, LOW); } /*! \brief get analog value of pin \param pin of arduino \return value of analog data */ int uArmController::getAnalogPinValue(unsigned int pin) { unsigned int dat[8], result; for (int i = 0; i < 8; i++) dat[i] = analogRead(pin); _sort(dat, 8); result = (dat[2] + dat[3] + dat[4] + dat[5]) / 4; return result; } unsigned char uArmController::setServoSpeed(byte servoNum, unsigned char speed) { #ifndef DISABLE_SERVO_SPEED mServoSpeed = speed; #endif } unsigned char uArmController::setServoSpeed(unsigned char speed) { #ifndef DISABLE_SERVO_SPEED setServoSpeed(SERVO_ROT_NUM, speed); setServoSpeed(SERVO_LEFT_NUM, speed); setServoSpeed(SERVO_RIGHT_NUM, speed); //setServoSpeed(SERVO_HAND_ROT_NUM, true); #endif }
31.321429
189
0.716165
abstractguy
9b8d1d760d9debbb2924fe84ff2422e54e6024c1
10,417
cpp
C++
app/src/main/cpp/Polyhedrons/TestCube.cpp
er-gv/ad-GLES-screensaver-suit
0cf20431187db0c5601cfecf782b86559c91d167
[ "Apache-2.0" ]
null
null
null
app/src/main/cpp/Polyhedrons/TestCube.cpp
er-gv/ad-GLES-screensaver-suit
0cf20431187db0c5601cfecf782b86559c91d167
[ "Apache-2.0" ]
null
null
null
app/src/main/cpp/Polyhedrons/TestCube.cpp
er-gv/ad-GLES-screensaver-suit
0cf20431187db0c5601cfecf782b86559c91d167
[ "Apache-2.0" ]
null
null
null
// // Created by Erez on 15/05/20. // #include "TestCube.h" #include "../graphics/GLUtils.h" #include <glm/glm.hpp> #include <glm/vec3.hpp> #include <glm/mat4x4.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <android/log.h> #include <GLES3/gl3.h> #define LOG_TAG "TesterCubs" #define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, fmt, ##args) #define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, fmt, ##args) #define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, fmt, ##args) static GLint POSITION_DATA_SIZE = 3; const static glm::vec3 CUBE_VERTICE[] = { // Front vertices glm::vec3(-1,-1,1), //front bottom left glm::vec3(-1,+1,1), //front top left glm::vec3(+1,+1,1), //front top right glm::vec3(+1,-1,1), //front bottom right glm::vec3(-1,-1,-1), //back bottom left glm::vec3(-1,+1,-1), //back top left glm::vec3(+1,+1,-1), //back top right glm::vec3(+1,-1,-1) //back bottom right }; static const glm::vec3 CUBE_COLORS[] = { // R, G, B glm::vec3(1.0f, 0.0f, 0.0f), // Front face (red) glm::vec3(0.0f, 1.0f, 0.0f), // Right face (green) glm::vec3(0.0f, 0.0f, 1.0f), // Back face (blue) glm::vec3(1.0f, 1.0f, 0.0f), // Left face (yellow) glm::vec3(0.0f, 1.0f, 1.0f), // Top face (cyan) glm::vec3(1.0f, 0.0f, 1.0f) // Bottom face (magenta) }; static const glm::vec3 CUBE_NORMALS[] = { // X, Y, Z glm::vec3(0.0f, 0.0f, 1.0f), // Front face glm::vec3(1.0f, 0.0f, 0.0f), // Right face glm::vec3(0.0f, 0.0f, -1.0f), // Back face glm::vec3(-1.0f, 0.0f, 0.0f), // Left face glm::vec3(0.0f, 1.0f, 0.0f), // Top face glm::vec3(0.0f, -1.0f, 0.0f) // Bottom face }; TestCube::TestCube() { nVertices = 8; mLightPosHandle = 0; mPositionHandle = 0; mColorHandle = 0; mNormalHandle = 0; mUniColorMaterial = nullptr; mUniColorVBO = nullptr; //mPerVertexProgramHandle = 0; //mPointProgramHandle = 0; //mLightPosInModelSpace = glm::vec4(0, 0, 0, 1); //mLightPosInWorldSpace = glm::vec4(0); //mLightPosInEyeSpace = glm::vec4(0); LOGD("Create TestCube instance successful"); } //bool loadModel(char* const path); //virtual void postUpdate() = 0; // call this for post rendering update. bool TestCube::init() { LOGD("TestCube create"); return initBuffers() && initShaders(); } void TestCube::update(long time) { LOGD("TestCube change"); //float angleInDegrees = (360.0f / 10000.0f) * ((int) time); radians = glm::radians((360.0f / 10000.0f) * ((int) time)); } void TestCube::render(const glm::mat4& view, const glm::mat4& perspective) { // Set the OpenGL viewport to same size as the surface. // Do a compile rotation every 10 seconds; // Set out pre-vertex lighting program. //mUniColorMaterial->activate(); // Set piewrogram handle for cube drawing. mMVPMatrixHandle = mUniColorMaterial->getUniform("u_MVPMatrix"); mMVMatrixHandle = mUniColorMaterial->getUniform("u_MVMatrix"); mLightPosHandle = mUniColorMaterial->getUniform("u_LightPos"); mPositionHandle = mUniColorMaterial->getAttrib("a_Position"); mColorHandle = mUniColorMaterial->getAttrib("a_Color"); mNormalHandle = mUniColorMaterial->getAttrib("a_Normal"); // Calculate mPosition of the light // Rotate and then push into the distance. //mLightModelMatrix = glm::mat4(); //mLightPosInEyeSpace = view* mLightPosInModelSpace; // right resetTransform(); translate(4.0f, 0.0f, -7.0f); rotate(radians, 1.0f, 0.0f, 0.0f); drawCubeIBO(view, perspective); // left //resetTransform(); //translate(-4.0f, 0.0f, -7.0f); //rotate(radians, 0.0f, 1.0f, 0.0f); //drawCubeIBO(view, perspective); // top resetTransform(); translate(0.0f, 4.0f, -7.0f); rotate(radians, 0.0f, 1.0f, 0.0f); drawCubeIBO(view, perspective); // bottom resetTransform(); translate(0.0f, -4.0f, -7.0f); rotate(radians, 0.0f, 1.0f, 0.0f); drawCubeIBO(view, perspective); //mUniColorMaterial->deactivate(); // center /*resetTransform(); translate(0.0f, 0.0f, -5.0f); rotate(radians, 1.0f, 1.0f, 1.0f); drawCubeIBO(view, perspective);*/ } void TestCube::destroy() { } TestCube::~TestCube() { destroy(); } void TestCube::drawCubeIBO(const glm::mat4& view, const glm::mat4& perspective) { //activate the shader mUniColorVBO->activate(); glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); //bind attribs GLuint positionAttr = mUniColorVBO->getAttrib("a_Position"); glEnableVertexAttribArray(positionAttr); glVertexAttribPointer(positionAttr, 3, GL_FLOAT, GL_FALSE, 0, 0); GLuint u_mvp = mUniColorVBO->getUniform("u_MVPMatrix"); glUniformMatrix4fv(u_mvp, 1, GL_FALSE, glm::value_ptr(perspective *view* activeTransform)); GLuint u_mv = mUniColorVBO->getUniform("u_mvMat"); glUniformMatrix4fv(u_mv, 1, GL_FALSE, glm::value_ptr(view* activeTransform)); GLuint u_LightPos = mUniColorVBO->getUniform("u_LightPos"); glUniform3fv(u_LightPos, 3, glm::value_ptr(mLightPosInEyeSpace)); GLuint u_Color = mUniColorVBO->getUniform("u_Color"); GLuint u_FaceNormal = mUniColorVBO->getUniform("u_FaceNormal"); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo[0]); for(unsigned short i=0; i<6; ++i) { glUniform3fv(u_Color, 1, glm::value_ptr(CUBE_COLORS[i])); glUniform3fv(u_FaceNormal, 1, glm::value_ptr(CUBE_NORMALS[i])); glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_SHORT, reinterpret_cast<const void *>(4*i*sizeof(unsigned short))); } /*glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo[1]); glUniform3f(u_Color, 1.84f, 1.984f, 1.984f); for(unsigned short i=0; i<4; ++i) { glUniform3fv(u_FaceNormal, 3, glm::value_ptr(CUBE_NORMALS[i])); glDrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_SHORT, reinterpret_cast<const void *>(4*i*sizeof(unsigned short))); }*/ //deactivate current shader glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); mUniColorVBO->deactivate(); } bool TestCube::initVertices(){ //here we should lode vertices data from a file return true; } bool TestCube::initFaces(){ Polyhedron::Polygon** faces; nFaces=6; return true; } bool TestCube::initBuffers(){ nVbos=1; nIbos=2; vbo = new GLuint[nVbos]; ibo = new GLuint[nIbos]; bool result = false; unsigned short constexpr trianglesStripBuffer[] ={0,3, 1,2, 3,7,2,6, 7,4,6,5, 4,0,5,1,// 1,2,5,6, 4,7,0,3}; unsigned short constexpr wireFrameLinesIndexBuffer[] = { 0,1, 2,3, 2,3,7,6, 4, 5, 6, 7, 0,1,5,4, 1,2,6,5, 4,7,3,0 }; vertexDataBuffer = new GLfloat[nVertices*POSITION_DATA_SIZE]; char buffer[1000]; for(int i=0; i< nVertices; i++){ //CUBE_NORMALS CUBE_COLORS sprintf(buffer, "spatial[%d] = (%f, %f, %f).", i, CUBE_VERTICE[i].x, CUBE_VERTICE[i].y, CUBE_VERTICE[i].z); __android_log_print(ANDROID_LOG_INFO, LOG_TAG, "%s", buffer); vertexDataBuffer[i*3] = CUBE_VERTICE[i].x; vertexDataBuffer[i*3+1] = CUBE_VERTICE[i].y; vertexDataBuffer[i*3+2] = CUBE_VERTICE[i].z; sprintf(buffer, "vertexDataBuffer[%d] = (%f, %f, %f ).\n", i, vertexDataBuffer[i*POSITION_DATA_SIZE], vertexDataBuffer[i*3+1], vertexDataBuffer[i*3+2] ); __android_log_print(ANDROID_LOG_INFO, LOG_TAG, "%s", buffer); } glGenBuffers(1, vbo); glGenBuffers(2, ibo); if (vbo[0]>0 && ibo[0]>0 && ibo[1]>0) { glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); glBufferData(GL_ARRAY_BUFFER, nVertices*POSITION_DATA_SIZE*sizeof(GLfloat), vertexDataBuffer, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo[0]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(trianglesStripBuffer), trianglesStripBuffer, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo[1]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(wireFrameLinesIndexBuffer), wireFrameLinesIndexBuffer, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); result = true; } delete vertexDataBuffer; return result; } bool TestCube::addMaterials(){ return setupCubeMaterial() && setupCubeIBOMaterial(); } bool TestCube::setupCubeMaterial(){ const char vertex_shader[] = "shaders/vertex/per_pixel_vertex_shader_no_tex.glsl"; const char fragment_shader[] = "shaders/fragment/per_pixel_fragment_shader_no_tex.glsl"; mUniColorMaterial = Material::makeMaterial( vertex_shader, fragment_shader, (const char*[]){"a_Position", "a_Color", "a_Normal"}, 3, (const char*[]){"u_MVMatrix", "u_MVPMatrix", "u_LightPos"}, 3); return (nullptr != mUniColorMaterial); } bool TestCube::setupCubeIBOMaterial(){ const char vertex_shader[] = "shaders/vertex/monochrome_face_vertex.glsl"; const char fragment_shader[] = "shaders/fragment/monochrome_face_fragment.glsl"; mUniColorVBO = Material::makeMaterial( vertex_shader, fragment_shader, nullptr, 0, nullptr, 0); return (nullptr != mUniColorVBO); } bool TestCube::initShaders(){ if(addMaterials()){ //mLightMaterial-> return (mUniColorMaterial->isInitilized() && mUniColorVBO->isInitilized()); } return false; } ///======= //static TestCube *TestCube; static void printGLString(const char *name, GLenum s) { const char *v = (const char *) glGetString(s); LOGI("GL %s = %s \n", name, v); } static void checkGlError(const char *op) { for (GLint error = glGetError(); error; error = glGetError()) { LOGI("after %s() glError (0x%x)\n", op, error); } }
30.548387
119
0.623116
er-gv
9b8fe593b7c252f51a2afe8fca6f8835d8851af0
9,551
cpp
C++
src/Task.cpp
tehilinski/MTBMPI
5d8fa590c6708c6ef412c6d2959f04e125f2d9e0
[ "Apache-2.0" ]
null
null
null
src/Task.cpp
tehilinski/MTBMPI
5d8fa590c6708c6ef412c6d2959f04e125f2d9e0
[ "Apache-2.0" ]
null
null
null
src/Task.cpp
tehilinski/MTBMPI
5d8fa590c6708c6ef412c6d2959f04e125f2d9e0
[ "Apache-2.0" ]
null
null
null
/*------------------------------------------------------------------------------------------------------------ file Task.cpp class mtbmpi::Task brief Class to control a single concurrent task. details Tasks are created by the TaskFactory and owns a work task object as a TaskAdapter. The work tasks are derived from TaskAdapterBase. The task knows its state, and can perform these actions: Initialize, Start, Stop, Pause, Resume, AcceptData. A task has its own arc, argv pair, so that the task can be an adapter to a command-line application. In this implementation, the master will initialize a task with command-line arguments for its job as though that particular task were run from the command-line. project Master-Task-Blackboard MPI Framework author Thomas E. Hilinski <https://github.com/tehilinski> copyright Copyright 2020 Thomas E. Hilinski. All rights reserved. This software library, including source code and documentation, is licensed under the Apache License version 2.0. See "LICENSE.md" for more information. ------------------------------------------------------------------------------------------------------------*/ #include "Task.h" #include "Master.h" #include "MsgTags.h" #include "UtilitiesMPI.h" // define the following to write diagnostics to std::cout // #define DBG_MPI_TASK #ifdef DBG_MPI_TASK #include <iostream> using std::cout; using std::endl; #endif namespace mtbmpi { Task::Task ( Master & useParent, // parent of task std::string const & taskName, // name of this task IDNum const myID, // task mpi task rank IDNum const controllerID, // controller task rank IDNum const blackBoardID, // blackboard task rank TaskFactoryPtr pTaskFactory, // task factory ArgPair args) : SendsMsgsToLog (myID, blackBoardID), parent (useParent), name ( taskName ), idController (controllerID), argPair (args), state (State_Unknown), action (NoAction) { // string with Tracker index: 1-based idStr = ToString ( myID - parent.GetFirstTaskID() + 1 ); bufferState[0] = myID; // constant #ifdef DBG_MPI_TASK cout << "Tracker ID " << idStr << ": " << "constructor" << endl; #endif // get cmd-line args StrVec cmdLineArgs ( GetArgs().second, GetArgs().second + GetArgs().first ); // create and start task pTaskAdapter = pTaskFactory->Create (*this, name, cmdLineArgs); SetState( State_Created ); // Master decides when to activate this class // so that derived Task class can do things after this constructor // Activate (); } Task::~Task () { #ifdef DBG_MPI_TASK cout << "Tracker ID " << idStr << ": ~Task" << endl; #endif SetState( State_Terminated ); } void Task::Activate () { #ifdef DBG_MPI_TASK cout << "Tracker ID " << idStr << ": " << "Activate: enter" << endl; #endif // Handle messages while ( !( IsCompleted(state) || IsTerminated(state) || IsError(state) ) ) { #ifdef DBG_MPI_TASK cout << "Tracker ID " << idStr << ": " << "Activate: PI::COMM_WORLD.Probe: start" << ": state = " << AsString(state) << endl; #endif // Wait for messages MPI::Status status; mtbmpi::comm.Probe ( idController, MPI_ANY_TAG, status ); #ifdef DBG_MPI_TASK cout << "Tracker ID " << idStr << ": " << "Activate: PI::COMM_WORLD.Probe: done" << endl; static int probeCount = 0; if ( !IsMsgTagValid( status.Get_tag() ) ) { if ( probeCount < 10 ) { std::ostringstream os; os << "Task::Activate: Probe error." << " Error: " << status.Get_error() << " Tag: " << status.Get_tag() << " Source: " << status.Get_source() << " MPI::ERRORS_RETURN: " << MPI::ERRORS_RETURN; Log().Error( os.str() ); cout << os.str() << endl; ++probeCount; } } #endif action = ProcessMessage (status); #ifdef DBG_MPI_TASK if ( IsMsgTagValid( status.Get_tag() ) ) { cout << "Tracker ID " << idStr << ": " << "Activate: ProcessMessage: " << " Tag: " << status.Get_tag() << " Source: " << status.Get_source() << " Action = " << action << endl; } #endif switch (action) { case ActionInitialize: DoActionInitialize (); break; case ActionStart: DoActionStart (); break; case ActionStop: DoActionStop (); break; case ActionPause: DoActionPause (); break; case ActionResume: DoActionResume (); break; case ActionAcceptData: DoActionAcceptData(); break; case NoAction: default: break; } } // while #ifdef DBG_MPI_TASK cout << "Tracker ID " << idStr << ": " << "Activate: done" << endl; #endif } /// @cond SKIP_PRIVATE void Task::DoActionInitialize () { #ifdef DBG_MPI_TASK cout << "Tracker ID " << idStr << ": " << "Activate: ActionInitialize" << endl; #endif if ( IsError(state) ) { LogState(); return; } SetState( pTaskAdapter->InitializeTask () ); LogState(); } void Task::DoActionStart () { #ifdef DBG_MPI_TASK cout << "Tracker ID " << idStr << ": " << "Activate: ActionStart: enter" << endl; #endif if ( IsError(state) ) { LogState(); return; } if ( !IsInitialized(state) ) { // handle failed initialization SendMsgToLog ("initialization failed"); SetState( State_Error ); LogState(); return; } SetState( pTaskAdapter->StartTask() ); // returns state after start LogState(); #ifdef DBG_MPI_TASK cout << "Task " << idStr << ": " << "Activate: ActionStart: done" << endl; #endif } void Task::DoActionStop () { #ifdef DBG_MPI_TASK cout << "Tracker ID " << idStr << ": " << "Activate: ActionStop: enter" << endl; #endif SetState( pTaskAdapter->StopTask() ); if ( !IsCompleted(state) && !IsTerminated(state) ) // not stopped? { // force stop - ouch! pTaskAdapter.reset(); SetState( State_Terminated ); } else // if ( IsCompleted(state) || IsTerminated(state) ) { action = NoAction; } LogState(); // check for and discard any remaining msgs short count = 0; while ( count < 10 ) // number of checks { if ( mtbmpi::comm.Iprobe ( idController, MPI_ANY_TAG ) ) { // cout << "Task " << idStr << ": discarding msg" << endl; mtbmpi::comm.Recv ( 0, 0, MPI::BYTE, idController, MPI_ANY_TAG ); } else // wait a bit { Sleep(); } ++count; } #ifdef DBG_MPI_TASK cout << "Tracker ID " << idStr << ": " << "Activate: ActionStop: done" << endl; #endif } void Task::DoActionPause () { SetState( pTaskAdapter->PauseTask() ); LogState(); if ( IsPaused(state) ) action = NoAction; // wait for resume msg } void Task::DoActionResume () { if ( IsError(state) ) { LogState(); return; } SetState( pTaskAdapter->ResumeTask() ); LogState(); if ( IsRunning(state) || IsCompleted(state) ) action = NoAction; } void Task::DoActionAcceptData () { if ( IsError(state) ) { LogState(); return; } /// @todo DoActionAcceptData } void Task::SendStateToController () { #ifdef DBG_MPI_TASK cout << "Tracker ID " << idStr << ": " << "SendStateToController: " << "state = " << AsString(state) << endl; #endif // bufferState[0] = GetID(); // always bufferState[1] = static_cast<int>(state); mtbmpi::comm.Send ( &bufferState, // [0] = ID, [2] = enum State 2, // size of bufferState MPI::INT, // data type idController, // destination Tag_State ); // msg type } void Task::LogState () { std::string msg = "Tracker ID "; msg += idStr; msg += ": state = "; msg += AsString(state); Log().Message( msg ); } Task::ActionNeeded Task::ProcessMessage ( MPI::Status const & status) { ActionNeeded newAction = NoAction; switch ( status.Get_tag() ) { case Tag_InitializeTask: { mtbmpi::comm.Recv ( 0, 0, MPI::BYTE, idController, Tag_InitializeTask ); newAction = ActionInitialize; break; } case Tag_StartTask: { mtbmpi::comm.Recv ( 0, 0, MPI::BYTE, idController, Tag_StartTask ); newAction = ActionStart; break; } case Tag_RequestStopTask: { mtbmpi::comm.Recv ( 0, 0, MPI::BYTE, idController, Tag_RequestStopTask ); newAction = ActionStop; break; } case Tag_RequestStop: { mtbmpi::comm.Recv ( 0, 0, MPI::BYTE, idController, Tag_RequestStop ); newAction = ActionStop; break; } case Tag_RequestPauseTask: { mtbmpi::comm.Recv ( &bufferState, 2, MPI::INT, idController, Tag_RequestPauseTask ); newAction = ActionPause; break; } case Tag_RequestResumeTask: { mtbmpi::comm.Recv ( &bufferState, 2, MPI::INT, idController, Tag_RequestResumeTask ); newAction = ActionResume; break; } case Tag_Data: { /// @todo Tag_Data newAction = ActionAcceptData; break; } default: { // unknown message - mark as received but discard // mtbmpi::comm.Recv ( 0, 0, MPI::BYTE, idController, MPI_ANY_TAG ); break; } } return newAction; } /// @endcond void Task::SetState (State const newState) { state = newState; SendStateToController (); } void Task::SendMsgToLog ( std::string const & logMsg ) { Log().Message( logMsg, idStr ); } void Task::SendMsgToLog ( char const * const logMsg ) { Log().Message( logMsg, idStr ); } } // namespace mtbmpi
23.8775
110
0.597424
tehilinski
9b91494bfc8e3d744f2c88529dcbe3779ce83d77
4,158
cpp
C++
ChangeJournal/VolumeOptions.cpp
ambray/Ntfs
c610315b007d0d0d1666d878e4f9c955deb86077
[ "MIT" ]
20
2016-02-04T12:23:39.000Z
2021-12-30T04:17:49.000Z
ChangeJournal/VolumeOptions.cpp
c3358/Ntfs
c610315b007d0d0d1666d878e4f9c955deb86077
[ "MIT" ]
null
null
null
ChangeJournal/VolumeOptions.cpp
c3358/Ntfs
c610315b007d0d0d1666d878e4f9c955deb86077
[ "MIT" ]
6
2015-07-15T04:29:07.000Z
2020-12-21T22:35:17.000Z
#include "VolumeOptions.hpp" ntfs::VolOps::VolOps(std::shared_ptr<void> volHandle) : vhandle(volHandle) { } void ntfs::VolOps::setVolHandle(std::shared_ptr<void> vh) { if(vhandle) vhandle.reset(); vhandle = vh; } std::shared_ptr<void> ntfs::VolOps::getVolHandle() { return vhandle; } std::tuple<std::string, std::string, unsigned long> ntfs::VolOps::getVolInfo() { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> conv; wchar_t volNameBuf[MAX_PATH + 1] = { 0 }; wchar_t fsNameBuf[MAX_PATH + 1] = { 0 }; std::string volName; std::string fsName; unsigned long maxCompLen = 0; unsigned long serial = 0; unsigned long fsFlags = 0; if (!GetVolumeInformationByHandleW(vhandle.get(), volNameBuf, MAX_PATH, &serial, &maxCompLen, &fsFlags, fsNameBuf, MAX_PATH)) { throw VOL_API_INTERACTION_LASTERROR("Unable to query volume information!"); } volName = conv.to_bytes(volNameBuf); fsName = conv.to_bytes(fsNameBuf); return std::make_tuple(volName, fsName, maxCompLen); } std::unique_ptr<NTFS_VOLUME_DATA_BUFFER> ntfs::VolOps::getVolData() { unsigned long bytesRead = 0; auto tmp = std::unique_ptr<NTFS_VOLUME_DATA_BUFFER>(reinterpret_cast<PNTFS_VOLUME_DATA_BUFFER>(new unsigned char [vol_data_size])); if (!DeviceIoControl(vhandle.get(), FSCTL_GET_NTFS_VOLUME_DATA, nullptr, 0, tmp.get(), vol_data_size, &bytesRead, nullptr)) { throw VOL_API_INTERACTION_LASTERROR("Failed to get volume data!"); } return tmp; } unsigned long ntfs::VolOps::getDriveType() { std::string volname; std::tie(volname, std::ignore, std::ignore) = getVolInfo(); return GetDriveTypeA(volname.c_str()); } uint64_t ntfs::VolOps::getFileCount() { uint64_t bytesPerSeg = 0; auto data = getVolData(); if (!data) throw VOL_API_INTERACTION_ERROR("Bad data pointer returned!", ERROR_INVALID_PARAMETER); bytesPerSeg = data->BytesPerFileRecordSegment; if (0 == bytesPerSeg) throw VOL_API_INTERACTION_ERROR("Bad data returned... bytes per segment is 0!", ERROR_BUFFER_ALL_ZEROS); return uint64_t(data->MftValidDataLength.QuadPart / bytesPerSeg); } std::vector<uint8_t> ntfs::VolOps::getMftRecord(uint64_t recNum) { NTFS_FILE_RECORD_INPUT_BUFFER inBuf = { 0 }; std::vector<uint8_t> vec; size_t recSize = sizeof(NTFS_FILE_RECORD_OUTPUT_BUFFER); unsigned long bytesReturned = 0; auto data = getVolData(); if (!data) throw VOL_API_INTERACTION_ERROR("Bad data pointer returned when querying MFT record!", ERROR_INVALID_PARAMETER); recSize += data->BytesPerFileRecordSegment; auto tmpbuf = std::unique_ptr<NTFS_FILE_RECORD_OUTPUT_BUFFER>(reinterpret_cast<PNTFS_FILE_RECORD_OUTPUT_BUFFER>(new unsigned char[recSize])); inBuf.FileReferenceNumber.QuadPart = recNum; if (!DeviceIoControl(vhandle.get(), FSCTL_GET_NTFS_FILE_RECORD, &inBuf, sizeof(inBuf), tmpbuf.get(), recSize, &bytesReturned, nullptr)) { throw VOL_API_INTERACTION_LASTERROR("Unable to retrieve file record!"); } vec.resize(tmpbuf->FileRecordLength); memcpy(vec.data(), tmpbuf->FileRecordBuffer, tmpbuf->FileRecordLength); return vec; } std::vector<uint8_t> ntfs::VolOps::processMftAttributes(uint64_t recNum, std::function<void(NTFS_ATTRIBUTE*)> func) { std::vector<uint8_t> vec; try { vec = getMftRecord(recNum); processMftAttributes(vec, func); } catch (const std::exception& e) { throw std::runtime_error(std::string("[VolOps] An exception occurred while processing the requested MFT record! Error: ") + e.what()); } return vec; } void ntfs::VolOps::processMftAttributes(std::vector<uint8_t>& record, std::function<void(NTFS_ATTRIBUTE*)> func) { NTFS_FILE_RECORD_HEADER* header = reinterpret_cast<NTFS_FILE_RECORD_HEADER*>(record.data()); NTFS_ATTRIBUTE* current = nullptr; unsigned long frecSize = 0; if (!record.size() || !func) throw VOL_API_INTERACTION_ERROR("Unable to process MFT record! Bad parameters provided.", ERROR_INVALID_PARAMETER); for (current = (NTFS_ATTRIBUTE*)((unsigned char*)header + header->AttributeOffset); current->AttributeType != NtfsAttributeType::AttributeEndOfRecord; current = (NTFS_ATTRIBUTE*)((unsigned char*)current + current->Length)) { func(current); } }
30.573529
142
0.746994
ambray
9b9527084fade5933b613150bacd7da8f99aed7b
949
hpp
C++
include/actl/operation/scalar/comparison/less.hpp
AlCash07/ACTL
15de4e2783d8e39dbd8e10cd635aaab328ca4f5b
[ "BSL-1.0" ]
17
2018-08-22T06:48:20.000Z
2022-02-22T21:20:09.000Z
include/actl/operation/scalar/comparison/less.hpp
AlCash07/ACTL
15de4e2783d8e39dbd8e10cd635aaab328ca4f5b
[ "BSL-1.0" ]
null
null
null
include/actl/operation/scalar/comparison/less.hpp
AlCash07/ACTL
15de4e2783d8e39dbd8e10cd635aaab328ca4f5b
[ "BSL-1.0" ]
null
null
null
// Copyright 2020 Oleksandr Bacherikov. // // Distributed under the Boost Software License, Version 1.0 // (see accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). #pragma once #include <actl/operation/scalar/scalar_operation.hpp> namespace ac { namespace scalar { struct less_f : scalar_operation<less_f, 2> { using category = ordering_operation_tag; using argument_category = scalar_tag; template <class T, class U> static constexpr bool eval_scalar(T lhs, U rhs) { return lhs < rhs; } }; inline constexpr less_f less; } // namespace scalar struct less_f : operation<less_f> { using category = ordering_operation_tag; static constexpr auto formula = scalar::less; }; inline constexpr less_f less; template <class T, class U, enable_operators<T, U> = 0> constexpr auto operator<(T&& lhs, U&& rhs) { return less(pass<T>(lhs), pass<U>(rhs)); } } // namespace ac
21.088889
60
0.702845
AlCash07
9b9717d14bc6673e4d7bb284cfc1bba887fae73b
751
cpp
C++
examples/cpp/operator/integer.cpp
airgiser/ucb
d03e62a17f35a9183ed36662352f603f0f673194
[ "MIT" ]
1
2022-01-08T14:59:44.000Z
2022-01-08T14:59:44.000Z
examples/cpp/operator/integer.cpp
airgiser/just-for-fun
d03e62a17f35a9183ed36662352f603f0f673194
[ "MIT" ]
null
null
null
examples/cpp/operator/integer.cpp
airgiser/just-for-fun
d03e62a17f35a9183ed36662352f603f0f673194
[ "MIT" ]
null
null
null
/* * Copyright (c) airfox 2012. * * \brief Overload operators */ #include "integer.h" Integer::Integer(int val) : m_val(val) { } const Integer &operator+(const Integer &i) { return i; } const Integer operator-(const Integer &i) { return Integer(-i.m_val); } const Integer operator~(const Integer &i) { return Integer(~i.m_val); } int operator!(const Integer &i) { return !i.m_val; } const Integer &operator++(Integer &i) { i.m_val++; return i; } const Integer operator++(Integer &i, int) { Integer prev(i.m_val); i.m_val++; return prev; } const Integer &operator--(Integer &i) { i.m_val--; } const Integer operator--(Integer &i, int) { Integer prev(i.m_val); i.m_val--; return prev; }
13.175439
42
0.623169
airgiser
9b9a11328c68287403d1e94cdd736ba46ee725d6
457
hh
C++
userFiles/ctrl/body/articulations/specific_art/Roll_Shoulder_Art.hh
mharding01/augmented-neuromuscular-RT-running
7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834
[ "MIT" ]
null
null
null
userFiles/ctrl/body/articulations/specific_art/Roll_Shoulder_Art.hh
mharding01/augmented-neuromuscular-RT-running
7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834
[ "MIT" ]
null
null
null
userFiles/ctrl/body/articulations/specific_art/Roll_Shoulder_Art.hh
mharding01/augmented-neuromuscular-RT-running
7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834
[ "MIT" ]
null
null
null
/*! * \author Nicolas Van der Noot * \file Roll_Shoulder_Art.hh * \brief Roll_Shoulder_Art class */ #ifndef _ROLL_SHOULDER_ART_HH_ #define _ROLL_SHOULDER_ART_HH_ #include "Articulation.hh" /*! \brief Roll foot articulation */ class Roll_Shoulder_Art : public Articulation { public: Roll_Shoulder_Art(CtrlInputs *inputs, MotorCtrlIndex *ctrl_index, int body_part_id); virtual ~Roll_Shoulder_Art(); virtual void add_Qq_soft_lim(); }; #endif
19.041667
86
0.761488
mharding01
9b9ad6d38e874528617dd5edf39aeb0e92fe366b
4,443
cxx
C++
ITS/ITSbase/AliITSdigitSSD.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
ITS/ITSbase/AliITSdigitSSD.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
ITS/ITSbase/AliITSdigitSSD.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 2004-2006, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ #include <AliITSdigitSSD.h> #include <TArrayI.h> #include <iostream> /////////////////////////////////////////////////////////////////// // // // Class defining the digit object // for SSD // Inherits from AliITSdigit // // /////////////////////////////////////////////////////////////////// ClassImp(AliITSdigitSSD) //______________________________________________________________________ AliITSdigitSSD::AliITSdigitSSD():AliITSdigit(){ // default constructor Int_t i; for(i=0; i<fgkSize; i++) fTracks[i] = -3; for(i=0; i<fgkSize; i++) fHits[i] = -1; } //__________________________________________________________________________ AliITSdigitSSD::AliITSdigitSSD(const Int_t *digits):AliITSdigit(digits){ // Creates a real SSD digit object } //_____________________________________________________________________________ AliITSdigitSSD::AliITSdigitSSD(const Int_t *digits,const Int_t *tracks, const Int_t *hits):AliITSdigit(digits){ // Creates a simulated SSD digit object for(Int_t i=0; i<fgkSize; i++) { fTracks[i] = tracks[i]; fHits[i] = hits[i]; } // end for i } //______________________________________________________________________ Int_t AliITSdigitSSD::GetListOfTracks(TArrayI &t){ // Fills the TArrayI t with the tracks found in fTracks removing // duplicated tracks, but otherwise in the same order. It will return // the number of tracks and fill the remaining elements to the array // t with -1. // Inputs: // TArrayI &t Reference to a TArrayI to contain the list of // nonduplicated track numbers. // Output: // TArrayI &t The input array filled with the nonduplicated track // numbers. // Return: // Int_t The number of none -1 entries in the TArrayI t. Int_t nt = t.GetSize(); Int_t nth = this->GetNTracks(); Int_t n = 0,i,j; Bool_t inlist = kFALSE; t.Reset(-1); // -1 array. for(i=0;i<nth;i++) { if(this->GetTrack(i) == -1) continue; inlist = kFALSE; for(j=0;j<n;j++)if(this->GetTrack(i) == t.At(j)) inlist = kTRUE; if(!inlist){ // add to end of list t.AddAt(this->GetTrack(i),n); if(n<nt) n++; } // end if } // end for i return n; } //______________________________________________________________________ void AliITSdigitSSD::Print(ostream *os){ //Standard output format for this class Int_t i; AliITSdigit::Print(os); for(i=0; i<fgkSize; i++) *os <<","<< fTracks[i]; for(i=0; i<fgkSize; i++) *os <<","<< fHits[i]; } //______________________________________________________________________ void AliITSdigitSSD::Read(istream *os){ //Standard input for this class Int_t i; AliITSdigit::Read(os); for(i=0; i<fgkSize; i++) *os >> fTracks[i]; for(i=0; i<fgkSize; i++) *os >> fHits[i]; } //______________________________________________________________________ ostream &operator<<(ostream &os,AliITSdigitSSD &source){ // Standard output streaming function. source.Print(&os); return os; } //______________________________________________________________________ istream &operator>>(istream &os,AliITSdigitSSD &source){ // Standard output streaming function. source.Read(&os); return os; }
38.634783
79
0.597569
AllaMaevskaya
9b9afd88d914d2cadc0eb9f5808fba8bf1ca90af
7,892
cpp
C++
libs/fastflow/tests/test_dotprod_parfor.cpp
GMAP/NPB-CPP
2f77a1bce83c4efda56c4bafb555bcf9abe85dd2
[ "MIT" ]
11
2020-12-16T22:44:08.000Z
2022-03-30T00:52:58.000Z
libs/fastflow/tests/test_dotprod_parfor.cpp
GMAP/NPB-CPP
2f77a1bce83c4efda56c4bafb555bcf9abe85dd2
[ "MIT" ]
1
2021-04-01T09:07:52.000Z
2021-07-21T22:10:07.000Z
libs/fastflow/tests/test_dotprod_parfor.cpp
GMAP/NPB-CPP
2f77a1bce83c4efda56c4bafb555bcf9abe85dd2
[ "MIT" ]
3
2020-12-21T18:47:43.000Z
2021-11-20T19:48:45.000Z
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* *************************************************************************** * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * As a special exception, you may use this file as part of a free software * library without restriction. Specifically, if other files instantiate * templates or use macros or inline functions from this file, or you compile * this file and link it with other files to produce an executable, this * file does not by itself cause the resulting executable to be covered by * the GNU General Public License. This exception does not however * invalidate any other reasons why the executable file might be covered by * the GNU General Public License. * **************************************************************************** */ /* Author: Massimo * Date : May 2013 * February 2014 */ /* * The program computes the dot-product of 2 arrays. * compile with -DUSE_OPENMP for the OpenMP version * compile with -DUSE_TBB for the TBB version * */ #if defined(TEST_PARFOR_PIPE_REDUCE) #if !defined(HAS_CXX11_VARIADIC_TEMPLATES) #define HAS_CXX11_VARIADIC_TEMPLATES 1 #endif #endif #include <ff/ff.hpp> #include <ff/parallel_for.hpp> #if defined(USE_TBB) #include <numeric> #include <tbb/parallel_for.h> #include <tbb/parallel_reduce.h> #include <tbb/blocked_range.h> #include <tbb/task_scheduler_init.h> #endif using namespace ff; int main(int argc, char * argv[]) { const double INITIAL_VALUE = 5.0; int arraySize= 10000000; int nworkers = 3; int NTIMES = 5; int CHUNKSIZE= (std::min)(10000, arraySize/nworkers); if (argc>1) { if (argc<3) { printf("use: %s arraysize nworkers [ntimes] [CHUNKSIZE]\n", argv[0]); return -1; } arraySize= atoi(argv[1]); nworkers = atoi(argv[2]); if (argc>=4) NTIMES = atoi(argv[3]); if (argc==5) CHUNKSIZE = atoi(argv[4]); } if (nworkers<=0) { printf("Wrong parameters values\n"); return -1; } //printf("CHUNKSIZE=%d\n", CHUNKSIZE); // creates the array double *A = new double[arraySize]; double *B = new double[arraySize]; double sum = INITIAL_VALUE; #if defined(USE_OPENMP) // init data #pragma omp parallel for schedule(runtime) num_threads(nworkers) for(long j=0;j<arraySize;++j) { A[j]=j*3.14; B[j]=2.1*j; } ff::ffTime(ff::START_TIME); for(int z=0;z<NTIMES;++z) { #pragma omp parallel for default(shared) \ schedule(runtime) \ reduction(+:sum) \ num_threads(nworkers) for(long i=0;i<arraySize;++i) sum += A[i]*B[i]; } // for z ffTime(STOP_TIME); printf("omp %d Time = %g ntimes=%d\n", nworkers, ffTime(GET_TIME), NTIMES); #elif defined(USE_TBB) tbb::task_scheduler_init init(nworkers); tbb::affinity_partitioner ap; // init data tbb::parallel_for(tbb::blocked_range<long>(0, arraySize, CHUNKSIZE), [&] (const tbb::blocked_range<long> &r) { for(long j=r.begin(); j!=r.end(); ++j) { A[j]=j*3.14; B[j]=2.1*j; } },ap); ff::ffTime(ff::START_TIME); for(int z=0;z<NTIMES;++z) { // do work sum += tbb::parallel_reduce(tbb::blocked_range<long>(0, arraySize, CHUNKSIZE), double(0), [=] (const tbb::blocked_range<long> &r, double in) { return std::inner_product(A+r.begin(), A+r.end(), B+r.begin(), in, std::plus<double>(), std::multiplies<double>()); }, std::plus<double>(), ap); } ffTime(STOP_TIME); printf("tbb %d Time = %g ntimes=%d\n", nworkers, ffTime(GET_TIME), NTIMES); #else #if 1 #if defined(TEST_PARFOR_PIPE_REDUCE) // yet another version (to test ParallelForPipeReduce) { parallel_for(0,arraySize,1,CHUNKSIZE, [&](const long j) { A[j]=j*3.14; B[j]=2.1*j;}); ParallelForPipeReduce<double*> pfr(nworkers, (nworkers < ff_numCores())); // spinwait is set to true if ... auto Map = [&](const long start, const long stop, const int thid, ff_buffernode &node) { if (start == stop) return; double localsum = 0.0; for(long i=start;i<stop;++i) localsum += A[i]*B[i]; node.put(new double(localsum)); }; auto Reduce = [&](const double* v) { sum +=*v; }; ff::ffTime(ff::START_TIME); for(int z=0;z<NTIMES;++z) { pfr.parallel_reduce_idx(0, arraySize,1,CHUNKSIZE, Map, Reduce); } ffTime(STOP_TIME); printf("ff %d Time = %g ntimes=%d\n", nworkers, ffTime(GET_TIME), NTIMES); } #else // TEST_PARFOR_PIPE_REDUCE // (default) FastFlow version { ParallelForReduce<double> pfr(nworkers, (nworkers < ff_numCores())); // spinwait is set to true if ... //pfr.parallel_for_static(0,arraySize,1,CHUNKSIZE, [&](const long j) { A[j]=j*3.14; B[j]=2.1*j;}); pfr.parallel_for(0,arraySize,1,CHUNKSIZE, [&](const long j) { A[j]=j*3.14; B[j]=2.1*j;}); auto Fsum = [](double& v, const double& elem) { v += elem; }; ff::ffTime(ff::START_TIME); for(int z=0;z<NTIMES;++z) { //pfr.parallel_reduce_static(sum, 0.0, pfr.parallel_reduce(sum, 0.0, 0, arraySize,1,CHUNKSIZE, [&](const long i, double& sum) {sum += A[i]*B[i];}, Fsum); // FIX: , std::min(nworkers, (z+1))); } ffTime(STOP_TIME); printf("ff %d Time = %g ntimes=%d\n", nworkers, ffTime(GET_TIME), NTIMES); } #endif #else // using macroes FF_PARFORREDUCE_INIT(dp, double, nworkers); // init data FF_PARFOR_BEGIN(init, j,0,arraySize,1, CHUNKSIZE, nworkers) { A[j]=j*3.14; B[j]=2.1*j; } FF_PARFOR_END(init); //auto Fsum = [](double& v, double elem) { v += elem; }; ff::ffTime(ff::START_TIME); for(int z=0;z<NTIMES;++z) { // do work FF_PARFORREDUCE_START(dp, sum, 0.0, i,0,arraySize,1, CHUNKSIZE, nworkers) { sum += A[i]*B[i]; //} FF_PARFORREDUCE_F_STOP(dp, sum, Fsum); // this is just a different form } FF_PARFORREDUCE_STOP(dp, sum, +); } ffTime(STOP_TIME); printf("ff %d Time = %g ntimes=%d\n", nworkers, ffTime(GET_TIME), NTIMES); FF_PARFORREDUCE_DONE(dp); #endif // if 1 #endif printf("Sum =%g\n", sum); return 0; }
36.368664
155
0.533198
GMAP
9b9b04e6df390c202915d081bc3ff390efa01033
2,072
cpp
C++
MPAGSCipher/CaesarCipher.cpp
tomlatham/mpags-day-3-JamesDownsLab
1bd5cddd53ec798440aec77978668f5056bd3d18
[ "MIT" ]
null
null
null
MPAGSCipher/CaesarCipher.cpp
tomlatham/mpags-day-3-JamesDownsLab
1bd5cddd53ec798440aec77978668f5056bd3d18
[ "MIT" ]
1
2019-11-06T14:17:01.000Z
2019-11-06T14:17:01.000Z
MPAGSCipher/CaesarCipher.cpp
tomlatham/mpags-day-3-JamesDownsLab
1bd5cddd53ec798440aec77978668f5056bd3d18
[ "MIT" ]
1
2019-11-06T11:39:22.000Z
2019-11-06T11:39:22.000Z
// // Created by james on 01/11/2019. // #include "CaesarCipher.hpp" #include <iostream> #include <string> #include <vector> CaesarCipher::CaesarCipher(const size_t key): key_{key} {} CaesarCipher::CaesarCipher(const std::string& key): key_{0} { // check to see whether string can be parsed as a number bool stringIsNumber{true}; for (const auto& elem: key){ if (! std::isdigit(elem)){ stringIsNumber=false; } } if (stringIsNumber) { key_ = std::stoul(key); } else{ std::cerr << "[error] problem converting Caesar cipher key, string cannot be parsed as integer, key will default to " << key_ << std::endl; } } std::string CaesarCipher::applyCipher(const std::string &inputText, const CipherMode cipherMode) const { // Create the output string std::string outputText {}; // Make sure that the key is in the range 0 - 25 const size_t truncatedKey { key_ % alphabetSize_}; // Loop over the input text char processedChar {'x'}; for ( const auto& origChar : inputText ) { // For each character in the input text, find the corresponding position in // the alphabet_ by using an indexed loop over the alphabet_ container for ( size_t i{0}; i < alphabetSize_; ++i ) { if (origChar == alphabet_[i] ) { // Apply the appropriate shift (depending on whether we're encrypting // or decrypting) and determine the new character // Can then break out of the loop over the alphabet_ if ( cipherMode == CipherMode::Encrypt ) { processedChar = alphabet_[(i + truncatedKey) % alphabetSize_ ]; } else { processedChar = alphabet_[(i + alphabetSize_ - truncatedKey) % alphabetSize_ ]; } break; } } // Add the new character to the output text outputText += processedChar; } return outputText; }
31.393939
151
0.585907
tomlatham
9b9d1a0a21a98b3890885c4c9c21988e2227b7dc
5,272
cpp
C++
mrvizifymain.cpp
dpai/Vizify
e10ea233fc923164f281777ceb4bcd528c617b8b
[ "Apache-2.0" ]
6
2020-05-19T07:41:59.000Z
2022-03-27T20:31:35.000Z
mrvizifymain.cpp
dpai/Vizify
e10ea233fc923164f281777ceb4bcd528c617b8b
[ "Apache-2.0" ]
null
null
null
mrvizifymain.cpp
dpai/Vizify
e10ea233fc923164f281777ceb4bcd528c617b8b
[ "Apache-2.0" ]
null
null
null
#include "mrvizifymain.h" #include "ui_mrvizifymain.h" #include "citk.h" #include "cvtkwidget.h" #include "cmrvizthreshold.h" #include "MrVizifyConfig.h" //#include "compareimageui.h" #ifdef USE_CIMGPROC #include "CImgProcWidget.h" #endif #ifdef USE_CIMGCONV #include "ConverterWidget.h" #endif #ifdef USE_CIMGSTAT #include "StatsWidget.h" #endif /** Qt Includes **/ #include <QMessageBox> #include <QStandardItemModel> #include <QStandardItem> MrVizifyMain::MrVizifyMain(QWidget *parent) : QMainWindow(parent), ui(new Ui::MrVizifyMain), m_viewLoaded(false) { ui->setupUi(this); // Composition Initializations m_itk = CITK::CreateNew(); m_vtkwidget = CVTKWidget::CreateNew(); m_vtkwidget->SetVTKWidget(ui->wGet_ViewWindow); LinkInputModels(ui->cBox_Volumes->model()); SetupModuleButtons(); /** Now All chosen modules can be attached one after one **/ #ifdef USE_CIMGPROC if (!RegisterModule((QWidget *) new CImgProcWidget(ui->cBox_Volumes->model(), this))) { std::cout << "Module Not Loaded" << std::endl; } #endif #ifdef USE_CIMGCONV if (!RegisterModule((QWidget *) new Widget(ui->cBox_Volumes->model(), this))) { std::cout << "Module Not Loaded" << std::endl; } #endif #ifdef USE_CIMGSTAT if (!RegisterModule((QWidget *) new StatWidget(ui->cBox_Volumes->model(), this))) { std::cout << "Module Not Loaded" << std::endl; } #endif } MrVizifyMain::~MrVizifyMain() { delete ui; //delete m_itk; delete m_vtkwidget; delete m_ThresholdWidget; } void MrVizifyMain::LinkInputModels(QAbstractItemModel *model) { m_itk->SetImageListModel(model); m_ThresholdWidget = new CMrVizThreshold(model, this); m_ThresholdWidget->setWindowFlags(Qt::Window); } void MrVizifyMain::SetupModuleButtons() { /** Make a Stack of all available buttons **/ m_ModuleBtns.push(ui->pushButton_6); m_ModuleBtns.push(ui->pushButton_5); m_ModuleBtns.push(ui->pushButton_4); //m_ModuleBtns.push(ui->pushButton_3); m_ModuleBtns.push(ui->pushButton_2); ui->pushButton_2->setProperty("Module",2); ui->pushButton_3->setProperty("Module",3); ui->pushButton_4->setProperty("Module",4); ui->pushButton_5->setProperty("Module",5); ui->pushButton_6->setProperty("Module",6); } bool MrVizifyMain::RegisterModule(QWidget *lWidget) { if (m_ModuleBtns.size() == 0) { std::cout << "No buttons available to load Module " << lWidget->objectName().toStdString() << std::endl; delete lWidget; return false; } QPushButton *pBtn = m_ModuleBtns.top(); pBtn->setText(lWidget->objectName()); m_ModuleBtns.pop(); m_Modules[pBtn->property("Module").toInt()] = lWidget; lWidget->setWindowFlags(Qt::Window); return true; } void MrVizifyMain::Display() { m_vtkwidget->SetInput( m_itk->GetVTKData<InputImageType>(m_itk->GetImage(ui->cBox_Volumes->currentText()) ) ); m_vtkwidget->SetXYImageOrientation(m_itk->GetXYImageOrientation()); m_vtkwidget->Render(); } void MrVizifyMain::on_pBtn_LoadDicom_clicked() { /** * Load DICOM MR into ITK Memory **/ m_itk->LoadDicom(); if (m_itk->isDataLoaded()) { ui->lEdit_Dicom->setText(m_itk->GetImageDirectory()); } else { QMessageBox msg; msg.setText("No Dicom Images Found."); msg.exec(); } /** If an old view is loaded . Refresh to the new image **/ if (m_viewLoaded) { Display(); } } void MrVizifyMain::on_pBtn_ViewImage_clicked() { /** Visualize the selected image (if loaded) in the vtkwidget **/ if (m_itk->isDataLoaded()) { /** Get the image as vtkImageData for visualization **/ Display(); m_viewLoaded = true; } } void MrVizifyMain::on_pBtn_Threshold_clicked() { /** Initialize the threshold module and show the widget in a new window **/ m_ThresholdWidget->Init(); m_ThresholdWidget->show(); } void MrVizifyMain::on_pBtn_LoadData_clicked() { /** * Load Data MR into ITK Memory **/ m_itk->LoadData(); if (m_itk->isDataLoaded()) { ui->lEdit_Dicom->setText(m_itk->GetImageDirectory()); } else { QMessageBox msg; msg.setText("File Not Selected"); msg.exec(); } /** If an old view is loaded . Refresh to the new image **/ if (m_viewLoaded) { Display(); } } void MrVizifyMain::on_pushButton_2_clicked() { /** Open the Module associated with the button **/ try { QWidget *widget = m_Modules.at(ui->pushButton_2->property("Module").toInt()); widget->show(); } catch (std::exception) // Accessing NULL objects is going to throw . We ignore that error . {} } void MrVizifyMain::on_pushButton_3_clicked() { // CompareImageUI *cImageCompare = new CompareImageUI(this); // cImageCompare->setWindowFlags(Qt::Window); // cImageCompare->Init(); // cImageCompare->show(); } void MrVizifyMain::on_pushButton_4_clicked() { /** Open the Module associated with the button **/ try { QWidget *widget = m_Modules.at(ui->pushButton_4->property("Module").toInt()); widget->show(); } catch (std::exception) // Accessing NULL objects is going to throw . We ignore that error . {} }
23.22467
112
0.662557
dpai
9b9e9d3e6bc01f9e16184354f5272b9a263ae466
1,065
hpp
C++
src/JSON/JSONSerialiser.hpp
ilyaskurikhin/beesim
f30a8fad0d784074400e48055d69823717cae623
[ "DOC" ]
null
null
null
src/JSON/JSONSerialiser.hpp
ilyaskurikhin/beesim
f30a8fad0d784074400e48055d69823717cae623
[ "DOC" ]
null
null
null
src/JSON/JSONSerialiser.hpp
ilyaskurikhin/beesim
f30a8fad0d784074400e48055d69823717cae623
[ "DOC" ]
null
null
null
/* * prjsv 2015, 2016 * 2014, 2016 * Marco Antognini */ #ifndef INFOSV_JSONSERIALISER_HPP #define INFOSV_JSONSERIALISER_HPP #include <JSON/JSON.hpp> #include <stdexcept> #include <string> namespace j { class BadPayload : public std::runtime_error { public: BadPayload(std::string const& msg); }; class NoSuchFile : public std::runtime_error { public: NoSuchFile(std::string const& msg); }; // Read a JSON value from a payload string // Throw a BadPayload when the format is invalid Value readFromString(std::string const& payload); // Like `readFromString` but the payload is read from the given file // Throw a BadPayload when the file's content has an invalid format // Throw a NoSuchFile when the file doesn't exist Value readFromFile(std::string const& filepath); // Convert a JSON value to the corresponding payload string std::string writeToString(Value const& value); // Like `writeToString` but write it to the given file void writeToFile(Value const& value, std::string const& fileapath); } // j #endif // INFOSV_JSONSERIALISER_HPP
22.1875
68
0.748357
ilyaskurikhin
9b9f91932f7933f31ad51495f9796c4c7e1a3c1a
1,538
cpp
C++
src/sound/load_music.cpp
Damdoshi/LibLapin
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
[ "BSD-3-Clause" ]
38
2016-07-30T09:35:19.000Z
2022-03-04T10:13:48.000Z
src/sound/load_music.cpp
Elania-Marvers/LibLapin
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
[ "BSD-3-Clause" ]
15
2017-02-12T19:20:52.000Z
2021-06-09T09:30:52.000Z
src/sound/load_music.cpp
Elania-Marvers/LibLapin
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
[ "BSD-3-Clause" ]
12
2016-10-06T09:06:59.000Z
2022-03-04T10:14:00.000Z
// Jason Brillante "Damdoshi" // Hanged Bunny Studio 2014-2018 // // Bibliotheque Lapin #include <string.h> #include "lapin_private.h" #define PATTERN "%s -> %p" t_bunny_music *bunny_read_music(t_bunny_configuration *cnf) { t_bunny_sound *pc = NULL; if (bunny_set_sound_attribute(NULL, &pc, &cnf, true) == false) return (NULL); return ((t_bunny_music*)pc); } t_bunny_music *bunny_load_music(const char *file) { struct bunny_music *mus; if (bunny_which_format(file) != BC_CUSTOM) { t_bunny_configuration *cnf; if ((cnf = bunny_open_configuration(file, NULL)) == NULL) return (NULL); mus = (struct bunny_music*)bunny_read_music(cnf); bunny_delete_configuration(cnf); return ((t_bunny_music*)mus); } if ((mus = new (std::nothrow) struct bunny_music) == NULL) goto Fail; if ((mus->music.openFromFile(file)) == false) goto FailStruct; mus->file = bunny_strdup(file); mus->type = MUSIC; mus->duration = mus->music.getDuration().asSeconds(); mus->volume = 50; mus->pitch = 1; mus->loop = true; mus->position[0] = 0; mus->position[1] = 0; mus->position[2] = 0; mus->attenuation = 5; mus->playing = false; mus->pause = false; mus->sound_manager = NULL; mus->sound_areas = NULL; mus->trap = NULL; scream_log_if(PATTERN, "ressource,sound", file, mus); return ((t_bunny_music*)mus); FailStruct: delete mus; Fail: scream_error_if(return (NULL), bunny_errno, PATTERN, "ressource,sound", file, (void*)NULL); return (NULL); }
23.30303
93
0.659948
Damdoshi
9ba04a333b68ffc1f035a2a6455d3a1c9e7b685c
1,500
cpp
C++
Source/PyramidMath/ExplorerMovementComponent.cpp
andriuchap/summer-ue4jam-2019
125a67cffe6b98d5d6a04b762a07e2c75256d86b
[ "Apache-2.0" ]
null
null
null
Source/PyramidMath/ExplorerMovementComponent.cpp
andriuchap/summer-ue4jam-2019
125a67cffe6b98d5d6a04b762a07e2c75256d86b
[ "Apache-2.0" ]
null
null
null
Source/PyramidMath/ExplorerMovementComponent.cpp
andriuchap/summer-ue4jam-2019
125a67cffe6b98d5d6a04b762a07e2c75256d86b
[ "Apache-2.0" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "ExplorerMovementComponent.h" #include "GameFramework/PhysicsVolume.h" UExplorerMovementComponent::UExplorerMovementComponent(const FObjectInitializer &ObjInitializer) { FallingGravityScale = 2.0F; FallingThreshold = 100.0F; } void UExplorerMovementComponent::OnMovementModeChanged(EMovementMode PreviousMovementMode, uint8 PreviousCustomMode) { Super::OnMovementModeChanged(PreviousMovementMode, PreviousCustomMode); } FVector UExplorerMovementComponent::NewFallVelocity(const FVector& InitialVelocity, const FVector& Gravity, float DeltaTime) const { FVector Result = InitialVelocity; if (DeltaTime > 0.f) { if (InitialVelocity.Z < FallingThreshold) { // Apply extra gravity when falling so the character doesn't feel as floaty. float Multiplier = 1 - (FMath::Clamp(InitialVelocity.Z, 0.0F, FallingThreshold) / FallingThreshold); Result += Gravity * DeltaTime * FallingGravityScale; } else { // Apply gravity. Result += Gravity * DeltaTime; } // Don't exceed terminal velocity. const float TerminalLimit = FMath::Abs(GetPhysicsVolume()->TerminalVelocity); if (Result.SizeSquared() > FMath::Square(TerminalLimit)) { const FVector GravityDir = Gravity.GetSafeNormal(); if ((Result | GravityDir) > TerminalLimit) { Result = FVector::PointPlaneProject(Result, FVector::ZeroVector, GravityDir) + GravityDir * TerminalLimit; } } } return Result; }
30.612245
130
0.76
andriuchap
9ba04e7228cd06789745eb3286b692d96b630416
281
cpp
C++
CSES-Problemset/sorting and searching/distinct_numbers.cpp
rranjan14/cp-solutions
9614508efbed1e4ee8b970b5eed535d782a5783f
[ "MIT" ]
null
null
null
CSES-Problemset/sorting and searching/distinct_numbers.cpp
rranjan14/cp-solutions
9614508efbed1e4ee8b970b5eed535d782a5783f
[ "MIT" ]
null
null
null
CSES-Problemset/sorting and searching/distinct_numbers.cpp
rranjan14/cp-solutions
9614508efbed1e4ee8b970b5eed535d782a5783f
[ "MIT" ]
null
null
null
#include <iostream> #include <set> #define lli long long int using namespace std; int main() { lli n, x; cin >> n; set<int, greater<int>> s; for (lli i = 0; i < n; i++) { cin >> x; s.insert(x); } cout << s.size() << "\n"; return 0; }
16.529412
31
0.480427
rranjan14
9ba227d5b892261ae49a495c23d4152e89d695a5
4,976
hpp
C++
core/boards/stm32l073xx/include/dma.hpp
azuwey/hexos
746901a86d664c44c03cd46bb2370975f6a11542
[ "MIT" ]
null
null
null
core/boards/stm32l073xx/include/dma.hpp
azuwey/hexos
746901a86d664c44c03cd46bb2370975f6a11542
[ "MIT" ]
null
null
null
core/boards/stm32l073xx/include/dma.hpp
azuwey/hexos
746901a86d664c44c03cd46bb2370975f6a11542
[ "MIT" ]
null
null
null
#ifndef __STM32L073XX_DMA #define __STM32L073XX_DMA #include "common_types.hpp" namespace DMA { namespace ADDRESSES { const inline t_uint32 BASE_ADDRESS = ((t_uint32)0x40020000U); } // namespace ADDRESSES namespace TYPEDEFS { typedef union { struct __attribute__((packed)) { __R t_uint32 GIF1 : 0x01U; __R t_uint32 TCIF1 : 0x01U; __R t_uint32 HTIF1 : 0x01U; __R t_uint32 TEIF1 : 0x01U; __R t_uint32 GIF2 : 0x01U; __R t_uint32 TCIF2 : 0x01U; __R t_uint32 HTIF2 : 0x01U; __R t_uint32 TEIF2 : 0x01U; __R t_uint32 GIF3 : 0x01U; __R t_uint32 TCIF3 : 0x01U; __R t_uint32 HTIF3 : 0x01U; __R t_uint32 TEIF3 : 0x01U; __R t_uint32 GIF4 : 0x01U; __R t_uint32 TCIF4 : 0x01U; __R t_uint32 HTIF4 : 0x01U; __R t_uint32 TEIF4 : 0x01U; __R t_uint32 GIF5 : 0x01U; __R t_uint32 TCIF5 : 0x01U; __R t_uint32 HTIF5 : 0x01U; __R t_uint32 TEIF5 : 0x01U; __R t_uint32 GIF6 : 0x01U; __R t_uint32 TCIF6 : 0x01U; __R t_uint32 HTIF6 : 0x01U; __R t_uint32 TEIF6 : 0x01U; __R t_uint32 GIF7 : 0x01U; __R t_uint32 TCIF7 : 0x01U; __R t_uint32 HTIF7 : 0x01U; __R t_uint32 TEIF7 : 0x01U; t_uint32 /* RESERVED */ : 0x04U; } BIT; __R t_uint32 WORD; } t_ISR; typedef union { struct __attribute__((packed)) { __W t_uint32 CGIF1 : 0x01U; __W t_uint32 CTCIF1 : 0x01U; __W t_uint32 CHTIF1 : 0x01U; __W t_uint32 CTEIF1 : 0x01U; __W t_uint32 CGIF2 : 0x01U; __W t_uint32 CTCIF2 : 0x01U; __W t_uint32 CHTIF2 : 0x01U; __W t_uint32 CTEIF2 : 0x01U; __W t_uint32 CGIF3 : 0x01U; __W t_uint32 CTCIF3 : 0x01U; __W t_uint32 CHTIF3 : 0x01U; __W t_uint32 CTEIF3 : 0x01U; __W t_uint32 CGIF4 : 0x01U; __W t_uint32 CTCIF4 : 0x01U; __W t_uint32 CHTIF4 : 0x01U; __W t_uint32 CTEIF4 : 0x01U; __W t_uint32 CGIF5 : 0x01U; __W t_uint32 CTCIF5 : 0x01U; __W t_uint32 CHTIF5 : 0x01U; __W t_uint32 CTEIF5 : 0x01U; __W t_uint32 CGIF6 : 0x01U; __W t_uint32 CTCIF6 : 0x01U; __W t_uint32 CHTIF6 : 0x01U; __W t_uint32 CTEIF6 : 0x01U; __W t_uint32 CGIF7 : 0x01U; __W t_uint32 CTCIF7 : 0x01U; __W t_uint32 CHTIF7 : 0x01U; __W t_uint32 CTEIF7 : 0x01U; t_uint32 /* RESERVED */ : 0x04U; } BIT; __W t_uint32 WORD; } t_IFCR; typedef union { struct __attribute__((packed)) { __RW t_uint32 EN : 0x01U; __RW t_uint32 TCIE : 0x01U; __RW t_uint32 HTIE : 0x01U; __RW t_uint32 TEIE : 0x01U; __RW t_uint32 DIR : 0x01U; __RW t_uint32 CIRC : 0x01U; __RW t_uint32 PINC : 0x01U; __RW t_uint32 MINC : 0x01U; __RW t_uint32 PSIZE : 0x02U; __RW t_uint32 MSIZE : 0x02U; __RW t_uint32 PL : 0x02U; __RW t_uint32 MEM2MEM : 0x01U; t_uint32 /* RESERVED */ : 0x11U; } BIT; __RW t_uint32 WORD; } t_CCR; typedef union { struct __attribute__((packed)) { __RW t_uint32 NDT : 0x10U; t_uint32 /* RESERVED */ : 0x10U; } BIT; __RW t_uint32 WORD; } t_CNDTR; typedef union { struct __attribute__((packed)) { __RW t_uint32 PA : 0x20U; } BIT; __RW t_uint32 WORD; } t_CPAR; typedef union { struct __attribute__((packed)) { __RW t_uint32 MA : 0x20U; } BIT; __RW t_uint32 WORD; } t_CMAR; typedef union { struct __attribute__((packed)) { __RW t_uint32 C1S : 0x04U; __RW t_uint32 C2S : 0x04U; __RW t_uint32 C3S : 0x04U; __RW t_uint32 C4S : 0x04U; __RW t_uint32 C5S : 0x04U; __RW t_uint32 C6S : 0x04U; __RW t_uint32 C7S : 0x04U; t_uint32 /* RESERVED */ : 0x04U; } BIT; __RW t_uint32 WORD; } t_CSELR; typedef struct __attribute__((packed)) { t_ISR ISR; t_IFCR IFCR; t_CCR CCR1; t_CNDTR CNDTR1; t_CPAR CPAR1; t_CMAR CMAR1; t_uint32 RESERVED0[1]; t_CCR CCR2; t_CNDTR CNDTR2; t_CPAR CPAR2; t_CMAR CMAR2; t_uint32 RESERVED1[1]; t_CCR CCR3; t_CNDTR CNDTR3; t_CPAR CPAR3; t_CMAR CMAR3; t_uint32 RESERVED2[1]; t_CCR CCR4; t_CNDTR CNDTR4; t_CPAR CPAR4; t_CMAR CMAR4; t_uint32 RESERVED3[1]; t_CCR CCR5; t_CNDTR CNDTR5; t_CPAR CPAR5; t_CMAR CMAR5; t_uint32 RESERVED4[1]; t_CCR CCR6; t_CNDTR CNDTR6; t_CPAR CPAR6; t_CMAR CMAR6; t_uint32 RESERVED5[1]; t_CCR CCR7; t_CNDTR CNDTR7; t_CPAR CPAR7; t_CMAR CMAR7; t_uint32 RESERVED6[6]; t_CSELR CSELR; } t_DMA; } // namespace TYPEDEFS namespace HAL {} // namespace HAL } // namespace DMA namespace REGISTERS { inline DMA::TYPEDEFS::t_DMA &r_DMA = *((DMA::TYPEDEFS::t_DMA *)DMA::ADDRESSES::BASE_ADDRESS); } // namespace REGISTERS #endif // __STM32L073XX_DMA
26.897297
93
0.610732
azuwey
9ba4986fe67d3ad1ea2b0c0559932474b9320384
2,125
cpp
C++
geode/value/Compute.cpp
jjqcat/geode
157cc904c113cc5e29a1ffe7c091a83b8ec2cf8e
[ "BSD-3-Clause" ]
75
2015-02-08T22:04:31.000Z
2022-02-26T14:31:43.000Z
geode/value/Compute.cpp
bantamtools/geode
d906f1230b14953b68af63aeec2f7b0418d5fdfd
[ "BSD-3-Clause" ]
15
2015-01-08T15:11:38.000Z
2021-09-05T13:27:22.000Z
geode/value/Compute.cpp
bantamtools/geode
d906f1230b14953b68af63aeec2f7b0418d5fdfd
[ "BSD-3-Clause" ]
22
2015-03-11T16:43:13.000Z
2021-02-15T09:37:51.000Z
#include <geode/value/Compute.h> #include <geode/python/from_python.h> #include <geode/python/Ptr.h> #include <geode/python/Class.h> #include <geode/utility/format.h> namespace geode { #ifdef GEODE_PYTHON static PyObject* empty_tuple = 0; namespace { class CachePython : public Value<Ptr<>>,public Action { public: GEODE_DECLARE_TYPE(GEODE_NO_EXPORT) typedef ValueBase Base; const Ref<> f; PyObject *_name; protected: CachePython(PyObject* f) : f(ref(*f)), _name(NULL) {} CachePython(PyObject* f, string const &name) : f(ref(*f)), _name(to_python(name)) {} public: void input_changed() const { this->set_dirty(); } void update() const { Executing e(*this); this->set_value(e.stop(steal_ref_check(PyObject_Call(&*f,empty_tuple,0)))); } void dump(int indent) const { printf("%*scache(%s)\n",2*indent,"",name().c_str()); Action::dump_dependencies(indent); } vector<Ref<const ValueBase>> dependencies() const { return Action::dependencies(); } string name() const { if (_name) return from_python<string>(_name); else return from_python<string>(python_field(f,"__name__")); } string repr() const { return format("cache(%s)",name()); } }; GEODE_DEFINE_TYPE(CachePython) } // We write a special version for python to allow easy introspection static Ref<ValueBase> cache_py(PyObject* f) { if (!PyCallable_Check(f)) throw TypeError("cache: argument is not callable"); return new_<CachePython>(f); } // this decorator takes a name instead of extracting it from the callable static Ref<ValueBase> cache_named_inner(PyObject* f, string const &name) { if (!PyCallable_Check(f)) throw TypeError("cache: argument is not callable"); return new_<CachePython>(f, name); } #endif } using namespace geode; void wrap_compute() { #ifdef GEODE_PYTHON empty_tuple = PyTuple_New(0); GEODE_ASSERT(empty_tuple); typedef CachePython Self; Class<Self>("Cache") .GEODE_FIELD(f) .GEODE_GET(name) .repr() ; GEODE_FUNCTION_2(cache,cache_py) GEODE_FUNCTION_2(cache_named_inner,cache_named_inner) #endif }
22.368421
79
0.696471
jjqcat
9ba729f79b09d9da86be71e67339b928a0abb3c9
10,229
cpp
C++
cVRP/Individual.cpp
Frown00/evolutionary-algorithm
1ae279d904910be70c473c0ec6a9b9dc1395190e
[ "MIT" ]
null
null
null
cVRP/Individual.cpp
Frown00/evolutionary-algorithm
1ae279d904910be70c473c0ec6a9b9dc1395190e
[ "MIT" ]
null
null
null
cVRP/Individual.cpp
Frown00/evolutionary-algorithm
1ae279d904910be70c473c0ec6a9b9dc1395190e
[ "MIT" ]
null
null
null
#include "Individual.h" #include "utils.cpp" Individual::Individual(int t_dimension) { m_dimension = t_dimension; m_fitness = -1; } Individual::Individual(Individual* other) { m_genotype = other->m_genotype; m_fitness = other->m_fitness; m_dimension = other->m_dimension; m_genotype_text = other->m_genotype_text; } Individual::~Individual() { std::cout << "\nINDIVIDUAL DEST\n"; } std::vector<int> Individual::getGenotype() { return m_genotype; } std::string Individual::getTextGenotype() { //std::string genotype = ""; /*for(int i = 0; i < m_genotype.size(); i++) { genotype += std::to_string(m_genotype[i]); genotype += " "; }*/ return m_genotype_text; } void Individual::setGenotype(std::vector<int> t_genotype) { m_genotype_text = ""; for(int i = 0; i < t_genotype.size(); i++) { m_genotype.push_back(t_genotype[i]); m_genotype_text += std::to_string(t_genotype[i]); } } std::vector<int> Individual::getIds(int t_dimension, int t_depot_id) { std::vector<int> left_location_ids; for(int i = 1; i <= t_dimension; i++) { if(i != t_depot_id) left_location_ids.push_back(i); } return left_location_ids; } void Individual::setRandomGenotype(Location* t_depot, std::vector<Location*> t_locations, int t_capacity) { int depot_id = t_depot->getId(); std::vector<int> left_location_ids = getIds(m_dimension, depot_id); m_genotype.push_back(t_depot->getId()); for(int i = 0; i < m_dimension - 1; i++) { int idx = rand() % left_location_ids.size(); m_genotype.push_back(left_location_ids[idx]); left_location_ids.erase(left_location_ids.begin() + idx); } m_genotype.push_back(t_depot->getId()); // fill with random returns to depot for(int i = 0; i < m_dimension; i++) { int idx = rand() % m_genotype.size(); m_genotype.insert(m_genotype.begin() + idx, t_depot->getId()); } fixGenotype(t_depot, t_locations, t_capacity); } double Individual::countFitness(Location* t_depot, std::vector<Location*> t_locations) { m_fitness = 0; const int genotype_size = m_genotype.size(); Location* first = getLocationById(t_locations, m_genotype[0]); int prev_last = genotype_size - 1; Location* last = getLocationById(t_locations, m_genotype[prev_last]); m_fitness += t_depot->countDistance(first->getCoords()); for(int i = 0; i < prev_last; i++) { Location* start_route = getLocationById(t_locations, m_genotype[i]); int next = i + 1; Location* end_route = getLocationById(t_locations, m_genotype[next]); m_fitness += start_route->countDistance(end_route->getCoords()); } m_fitness += t_depot->countDistance(last->getCoords()); return m_fitness; } double Individual::getFitness() { return m_fitness; } Location* Individual::getLocationById(std::vector<Location*> t_locations, int t_id) { for(int i = 0; i < t_locations.size(); i++) { if(t_locations[i]->getId() == t_id) return t_locations[i]; } } void Individual::mutate( MutationType t_type, Location* t_depot, std::vector<Location*> t_locations, int t_capacity ) { int gen1_pos = (rand() % (m_genotype.size() - 1)) + 1; int gen2_pos = (rand() % (m_genotype.size() - 1)) + 1; switch (t_type) { case MutationType::SWAP: { swapMutation(gen1_pos, gen2_pos); break; } case MutationType::INVERSION: { inversionMutation(gen1_pos, gen2_pos); break; } default: throw "Wrong mutation type"; } fixGenotype(t_depot, t_locations, t_capacity); } void Individual::fixGenotype(Location* t_depot, std::vector<Location*> t_locations, int t_capacity) { int depot_id = t_depot->getId(); if(m_genotype[0] != depot_id) m_genotype.insert(m_genotype.begin() + 0, depot_id); if(m_genotype[m_genotype.size() - 1] != depot_id) m_genotype.insert(m_genotype.begin() + m_genotype.size(), depot_id); // clear depot after depot for(int i = 0; i < m_genotype.size() - 1; i++) { if(m_genotype[i] == m_genotype[i + 1]) { m_genotype.erase(m_genotype.begin() + i); i--; } } int current_weight = 0; for(int i = 0; i < m_genotype.size(); i++) { if(m_genotype[i] == t_depot->getId()) { current_weight = 0; } else { Location* loc = getLocationById(t_locations, m_genotype[i]); current_weight += loc->getDemands(); if(current_weight > t_capacity) { m_genotype.insert(m_genotype.begin() + i, depot_id); current_weight = 0; } } } m_genotype_text = ""; for(int i = 0; i < m_genotype.size(); i++) { m_genotype_text += std::to_string(m_genotype[i]); } } std::vector<int> Individual::getPlainGenotype(Location* t_depot) { std::vector<int> plain_genotype; for(int i = 0; i < m_genotype.size(); i++) { if(m_genotype[i] != t_depot->getId()) { plain_genotype.push_back(m_genotype[i]); } } return plain_genotype; } void Individual::swapMutation(int t_gen1_pos, int t_gen2_pos) { int temp = m_genotype[t_gen1_pos]; m_genotype[t_gen1_pos] = m_genotype[t_gen2_pos]; m_genotype[t_gen2_pos] = temp; } void Individual::inversionMutation(int t_gen1_pos, int t_gen2_pos) { int swap_amount = (abs(t_gen1_pos - t_gen2_pos) + 1)/ 2; int left = t_gen1_pos; int right = t_gen2_pos; if(t_gen1_pos > t_gen2_pos) { left = t_gen2_pos; right = t_gen1_pos; } for(int i = 0; i <= swap_amount; i++) { swapMutation(left + i, right - i); } } std::vector<std::vector<int>> Individual::cycleCrossover(Individual* t_other_individual, Location* t_depot) { std::vector<int> cycle; std::vector<int> parent1 = getPlainGenotype(t_depot); std::vector<int> parent2 = t_other_individual->getPlainGenotype(t_depot); std::vector<int> child1_genotype, child2_genotype; int pos = 0; int first_in_cycle = parent1[0]; cycle.push_back(first_in_cycle); // first is a depot (start point) while(parent1.size() > pos) { int index = utils::findIndex(parent2, cycle[pos]); int gen = parent1[index]; if(gen == first_in_cycle) break; cycle.push_back(gen); pos++; } // crossover for(int i = 0; i < parent1.size(); i++) { if(utils::findIndex(cycle, parent1[i]) != -1) { child1_genotype.push_back(parent2[i]); child2_genotype.push_back(parent1[i]); } else { child1_genotype.push_back(parent1[i]); child2_genotype.push_back(parent2[i]); } } // set returns to depot according to their parents for(int i = 0; i < m_genotype.size(); i++) { if(m_genotype[i] == t_depot->getId()) { child1_genotype.insert(child1_genotype.begin() + i, m_genotype[i]); } } std::vector<int> partner_genotype = t_other_individual->getGenotype(); for(int i = 0; i < partner_genotype.size(); i++) { if(partner_genotype[i] == t_depot->getId()) { child2_genotype.insert(child2_genotype.begin() + i, partner_genotype[i]); } } return std::vector<std::vector<int>> { child1_genotype, child2_genotype }; } std::vector<std::vector<int>> Individual::orderedCrossover(Individual* t_other_individual, Location* t_depot) { std::vector<int> parent1 = getPlainGenotype(t_depot); std::vector<int> parent2 = t_other_individual->getPlainGenotype(t_depot); std::vector<int> child1_genotype, child2_genotype = std::vector<int>(); child1_genotype.resize(parent1.size()); child2_genotype.resize(parent2.size()); int cross_point1 = rand() % parent1.size(); int cross_point2 = rand() % parent1.size(); int min_constr = cross_point1; int max_constr = cross_point2; if(min_constr > max_constr) { int temp = min_constr; min_constr = max_constr; max_constr = min_constr; } std::vector<int> values_in_section; std::vector<int> values_out_section; for(int i = 0; i < parent1.size(); i++) { int gen = parent1[i]; if(i >= min_constr && i <= max_constr) { values_in_section.push_back(gen); } else { values_out_section.push_back(gen); } } int offset = 0; for(int i = 0; i < parent1.size(); i++) { if(i >= min_constr && i <= max_constr) { child1_genotype[i] = parent1[i]; } else { int local_offset = -1; for(int j = 0; j < parent2.size(); j++) { int found = utils::findIndex(values_in_section, parent2[j]); if(found == -1) { local_offset++; } if(offset == local_offset) { child1_genotype[i] = parent2[j]; offset++; break; } } } } for (int i = 0; i < parent2.size(); i++) { int gen = parent2[i]; int found = utils::findIndex(values_out_section, gen); if(found != -1) { child2_genotype[i] = values_out_section[0]; values_out_section.erase(values_out_section.begin()); } else { child2_genotype[i] = parent2[i]; } } return std::vector<std::vector<int>> { child1_genotype, child2_genotype }; } std::vector<Individual*> Individual::crossover( CrossoverType t_type, Location* t_depot, std::vector<Location*> t_locations, int t_capacity, Individual* t_other_individual ) { std::vector<std::vector<int>> child_genotypes; switch(t_type) { case CrossoverType::ORDERED: child_genotypes = orderedCrossover(t_other_individual, t_depot); case CrossoverType::CYCLE: child_genotypes = cycleCrossover(t_other_individual, t_depot); break; default: // error in config break; } Individual* child1 = new Individual(m_dimension); Individual* child2 = new Individual(m_dimension); child1->setGenotype(child_genotypes[0]); child1->fixGenotype(t_depot, t_locations, t_capacity); child2->setGenotype(child_genotypes[1]); child2->fixGenotype(t_depot, t_locations, t_capacity); return std::vector<Individual*> { child1, child2 }; } void Individual::printRouting(Location* t_depot) { int route = 1; std::cout << "\nDEPOT ID: " << t_depot->getId(); for(int i = 0; i < m_genotype.size() - 1; i++) { if(m_genotype[i] == t_depot->getId()) { std::cout << "\nROUTE " + std::to_string(route) + ": "; route++; } else { std::cout << m_genotype[i]; int next = i + 1; if(m_genotype[next] != t_depot->getId()) { std::cout << " -> "; } } } std::cout << '\n' << "FITNESS: " << getFitness(); }
30.810241
111
0.655196
Frown00
9ba7ebc605fc3a841bc949e22916bb82cca3a365
2,081
cpp
C++
tests/msg_feed_id/test.cpp
morgenm/PMC-Game
ae09b3df200bd1cf47bcf8888939112e5ac42d38
[ "MIT" ]
null
null
null
tests/msg_feed_id/test.cpp
morgenm/PMC-Game
ae09b3df200bd1cf47bcf8888939112e5ac42d38
[ "MIT" ]
null
null
null
tests/msg_feed_id/test.cpp
morgenm/PMC-Game
ae09b3df200bd1cf47bcf8888939112e5ac42d38
[ "MIT" ]
null
null
null
#include "msg_sys/msg_feed_id.h" #include <iostream> void TryEquals() { MessageFeedID lhs; MessageFeedID rhs; rhs.NewID(); if( lhs == rhs ) { std::cout << "MessageFeedID TryEquals Bad Test: FAILED!\n"; } else { std::cout << "MessageFeedID TryEquals Bad Test: Passed.\n"; } MessageFeedID newLHS; MessageFeedID newRHS; if( newLHS == newRHS ) { std::cout << "MessageFeedID TryEquals Good Test: Passed.\n"; } else { std::cout << "MessageFeedID TryEquals Good Test: FAILED!\n"; } } void TryLessThan() { MessageFeedID lhs; MessageFeedID rhs; if( lhs < rhs ) { std::cout << "MessageFeedID TryLessThan Bad Test: FAILED!\n"; } else { std::cout << "MessageFeedID TryLessThan Bad Test: Passed.\n"; } MessageFeedID newLHS; MessageFeedID newRHS; newRHS.NewID(); if( newLHS < newRHS ) { std::cout << "MessageFeedID TryLessThan Good Test: Passed.\n"; } else { std::cout << "MessageFeedID TryLessThan Good Test: FAILED!\n"; } } void TryGreaterThan() { MessageFeedID lhs; MessageFeedID rhs; if( lhs > rhs ) { std::cout << "MessageFeedID TryGreaterThan Bad Test: FAILED!\n"; } else { std::cout << "MessageFeedID TryLessThan Bad Test: Passed.\n"; } MessageFeedID newLHS; MessageFeedID newRHS; newRHS.NewID(); if( newRHS > newLHS ) { std::cout << "MessageFeedID TryGreaterThan Good Test: Passed.\n"; } else { std::cout << "MessageFeedID TryGreaterThan Good Test: FAILED!\n"; } } void TryNewID() { MessageFeedID oldID; MessageFeedID newID; newID.NewID(); oldID = newID; for(int i=0; i<1000; i++) { newID.NewID(); } if( newID > oldID ) { std::cout << "MessageFeedID TryNewID Many Test: Passed.\n"; } else { std::cout << "MessageFeedID TryNewID Many Test: FAILED!\n"; } } int main() { TryEquals(); TryLessThan(); TryGreaterThan(); TryNewID(); return 0; }
21.905263
73
0.583373
morgenm
9baa88af4a23983b1d79e18b1992c91ec4dc3c21
1,207
hh
C++
libs/core/include/singleton.hh
no111u3/laptop_control
92f25ef61511dfacd5edeff3dedf06f31a347a9f
[ "Apache-2.0" ]
1
2019-04-30T13:46:51.000Z
2019-04-30T13:46:51.000Z
libs/core/include/singleton.hh
no111u3/laptop_control
92f25ef61511dfacd5edeff3dedf06f31a347a9f
[ "Apache-2.0" ]
null
null
null
libs/core/include/singleton.hh
no111u3/laptop_control
92f25ef61511dfacd5edeff3dedf06f31a347a9f
[ "Apache-2.0" ]
null
null
null
/** Copyright 2019 Boris Vinogradov <no111u3@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. */ #pragma once #include <memory> #include <utility> namespace core { template <typename T> class Singleton { public: static T & get() { return *t_; } template <typename ...Args> static void create(Args ...args) { t_ = std::make_unique<T>(std::forward<Args>(args)...); } private: Singleton() = default; Singleton(const Singleton &) = default; Singleton(Singleton &&) noexcept = default; ~Singleton() = default; static inline std::unique_ptr<T> t_; }; } // namespace core
28.738095
75
0.651201
no111u3
9bb32ea99deda845c13b99b27305e1a56d6f0444
1,196
hxx
C++
ImageSharpOpenJpegNative/src/openjpeg.mct.hxx
cinderblocks/ImageSharp.OpenJpeg
bf5c976a6dbfa0d2666be566c845a7410440cea2
[ "Apache-2.0" ]
null
null
null
ImageSharpOpenJpegNative/src/openjpeg.mct.hxx
cinderblocks/ImageSharp.OpenJpeg
bf5c976a6dbfa0d2666be566c845a7410440cea2
[ "Apache-2.0" ]
null
null
null
ImageSharpOpenJpegNative/src/openjpeg.mct.hxx
cinderblocks/ImageSharp.OpenJpeg
bf5c976a6dbfa0d2666be566c845a7410440cea2
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2022 Sjofn LLC. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _ISOJ_OPENJPEG_OPENJP2_OPENJPEG_MCT_H_ #define _ISOJ_OPENJPEG_OPENJP2_OPENJPEG_MCT_H_ #include "ImageSharpOpenJpeg_Exports.hxx" #include "shared.hxx" IMAGESHARPOPENJPEG_EXPORT bool openjpeg_openjp2_opj_set_MCT(opj_cparameters_t* parameters, float* pEncodingMatrix, int32_t* p_dc_shift, const uint32_t pNbComp) { return ::opj_set_MCT(parameters, pEncodingMatrix, p_dc_shift, pNbComp); } #endif // _CPP_OPENJPEG_OPENJP2_OPENJPEG_MCT_H_
38.580645
90
0.698997
cinderblocks
9bb6ef5eb90e150ed1c7d1a90646c8202a54213e
14,412
cpp
C++
project/src/bytecode_vm/vm.cpp
Jeff-Mott-OR/cpplox
6b2b771c50fd3d0121283d1f2e54860e1d263bca
[ "MIT" ]
57
2018-04-18T11:06:31.000Z
2022-01-26T22:15:01.000Z
project/src/bytecode_vm/vm.cpp
Jeff-Mott-OR/cpplox
6b2b771c50fd3d0121283d1f2e54860e1d263bca
[ "MIT" ]
24
2018-04-20T04:24:39.000Z
2018-11-13T06:11:37.000Z
project/src/bytecode_vm/vm.cpp
Jeff-Mott-OR/cpplox
6b2b771c50fd3d0121283d1f2e54860e1d263bca
[ "MIT" ]
6
2018-04-19T03:25:35.000Z
2020-02-20T03:22:52.000Z
#include "vm.hpp" #include <chrono> #include <cstddef> #include <cstdint> #include <iostream> #include <utility> #include <gsl/gsl_util> #include "compiler.hpp" #include "debug.hpp" using std::chrono::duration_cast; using std::chrono::seconds; using std::chrono::system_clock; using std::cout; using std::move; using std::nullptr_t; using std::string; using std::to_string; using std::uint8_t; using std::uint16_t; using std::vector; using boost::apply_visitor; using boost::bad_get; using boost::get; using boost::static_visitor; using gsl::narrow; using namespace motts::lox; namespace { // Only false and nil are falsey, everything else is truthy struct Is_truthy_visitor : static_visitor<bool> { auto operator()(bool value) const { return value; } auto operator()(nullptr_t) const { return false; } template<typename T> auto operator()(const T&) const { return true; } }; struct Is_equal_visitor : static_visitor<bool> { // Different types automatically compare false template<typename T, typename U> auto operator()(const T&, const U&) const { return false; } // Same types use normal equality test template<typename T> auto operator()(const T& lhs, const T& rhs) const { return lhs == rhs; } }; struct Plus_visitor : static_visitor<Value> { auto operator()(const string& lhs, const string& rhs) const { return Value{lhs + rhs}; } auto operator()(double lhs, double rhs) const { return Value{lhs + rhs}; } // All other type combinations can't be '+'-ed together template<typename T, typename U> Value operator()(const T&, const U&) const { throw VM_error{"Operands must be two numbers or two strings."}; } }; struct Call_visitor : static_visitor<void> { // "Capture" variables, like a lamba but the long-winded way uint8_t& arg_count; vector<Call_frame>& frames_; vector<Value>& stack_; explicit Call_visitor( uint8_t& arg_count_capture, vector<Call_frame>& frames_capture, vector<Value>& stack_capture ) : arg_count {arg_count_capture}, frames_ {frames_capture}, stack_ {stack_capture} {} auto operator()(const Function* callee) const { if (arg_count != callee->arity) { throw VM_error{ "Expected " + to_string(callee->arity) + " arguments but got " + to_string(arg_count) + ".", frames_ }; } frames_.push_back(Call_frame{ *callee, callee->chunk.code.cbegin(), stack_.end() - 1 - arg_count }); } auto operator()(const Native_fn* callee) const { auto return_value = callee->fn(stack_.end() - arg_count, stack_.end()); stack_.erase(stack_.end() - 1 - arg_count, stack_.end()); stack_.push_back(return_value); } template<typename T> void operator()(const T&) const { throw VM_error{"Can only call functions and classes.", frames_}; } }; auto clock_native(vector<Value>::iterator /*args_begin*/, vector<Value>::iterator /*args_end*/) { return Value{narrow<double>(duration_cast<seconds>(system_clock::now().time_since_epoch()).count())}; } string stack_trace(const vector<Call_frame>& frames) { string trace; for (auto frame_iter = frames.crbegin(); frame_iter != frames.crend(); ++frame_iter) { const auto instruction_offset = frame_iter->ip - 1 - frame_iter->function.chunk.code.cbegin(); const auto line = frame_iter->function.chunk.lines.at(instruction_offset); trace += "[Line " + to_string(line) + "] in " + ( frame_iter->function.name.empty() ? "script" : frame_iter->function.name + "()" ) + "\n"; } return trace; } } namespace motts { namespace lox { void VM::interpret(const string& source) { // TODO: Allow dynamically-sized stack but without invalidating iterators. // Maybe deque? Or offsets instead of iterators? For now just pre-allocate. stack_.reserve(256); auto entry_point_function = compile(source); stack_.push_back(Value{&entry_point_function}); frames_.push_back(Call_frame{ entry_point_function, entry_point_function.chunk.code.cbegin(), stack_.begin() }); globals_["clock"] = Value{new Native_fn{clock_native}}; run(); } void VM::run() { for (;;) { #ifndef NDEBUG cout << " "; for (const auto value : stack_) { cout << "[ "; print_value(value); cout << " ]"; } cout << "\n"; disassemble_instruction(frames_.back().function.chunk, frames_.back().ip - frames_.back().function.chunk.code.cbegin()); #endif const auto instruction = static_cast<Op_code>(*frames_.back().ip++); switch (instruction) { case Op_code::constant: { const auto constant_offset = *frames_.back().ip++; const auto constant = frames_.back().function.chunk.constants.at(constant_offset); stack_.push_back(constant); break; } case Op_code::nil: { stack_.push_back(Value{nullptr}); break; } case Op_code::true_: { stack_.push_back(Value{true}); break; } case Op_code::false_: { stack_.push_back(Value{false}); break; } case Op_code::pop: { stack_.pop_back(); break; } case Op_code::get_local: { const auto local_offset = *frames_.back().ip++; stack_.push_back(*(frames_.back().stack_begin + local_offset)); break; } case Op_code::set_local: { const auto local_offset = *frames_.back().ip++; *(frames_.back().stack_begin + local_offset) = stack_.back(); break; } case Op_code::get_global: { const auto name_offset = *frames_.back().ip++; const auto name = get<string>(frames_.back().function.chunk.constants.at(name_offset).variant); const auto found_value = globals_.find(name); if (found_value == globals_.end()) { throw VM_error{"Undefined variable '" + name + "'", frames_}; } stack_.push_back(found_value->second); break; } case Op_code::set_global: { const auto name_offset = *frames_.back().ip++; const auto name = get<string>(frames_.back().function.chunk.constants.at(name_offset).variant); const auto found_value = globals_.find(name); if (found_value == globals_.end()) { throw VM_error{"Undefined variable '" + name + "'", frames_}; } found_value->second = stack_.back(); break; } case Op_code::define_global: { const auto name_offset = *frames_.back().ip++; const auto name = get<string>(frames_.back().function.chunk.constants.at(name_offset).variant); globals_[name] = stack_.back(); stack_.pop_back(); break; } case Op_code::equal: { const auto right_value = move(stack_.back()); stack_.pop_back(); const auto left_value = move(stack_.back()); stack_.pop_back(); stack_.push_back(Value{ apply_visitor(Is_equal_visitor{}, left_value.variant, right_value.variant) }); break; } case Op_code::greater: { const auto right_value = get<double>(stack_.back().variant); stack_.pop_back(); const auto left_value = get<double>(stack_.back().variant); stack_.pop_back(); stack_.push_back(Value{left_value > right_value}); break; } case Op_code::less: { const auto right_value = get<double>(stack_.back().variant); stack_.pop_back(); const auto left_value = get<double>(stack_.back().variant); stack_.pop_back(); stack_.push_back(Value{left_value < right_value}); break; } case Op_code::add: { const auto right_value = move(stack_.back()); stack_.pop_back(); const auto left_value = move(stack_.back()); stack_.pop_back(); stack_.push_back(apply_visitor(Plus_visitor{}, left_value.variant, right_value.variant)); break; } case Op_code::subtract: { const auto right_value = get<double>(stack_.back().variant); stack_.pop_back(); const auto left_value = get<double>(stack_.back().variant); stack_.pop_back(); stack_.push_back(Value{left_value - right_value}); break; } case Op_code::multiply: { const auto right_value = get<double>(stack_.back().variant); stack_.pop_back(); const auto left_value = get<double>(stack_.back().variant); stack_.pop_back(); stack_.push_back(Value{left_value * right_value}); break; } case Op_code::divide: { const auto right_value = get<double>(stack_.back().variant); stack_.pop_back(); const auto left_value = get<double>(stack_.back().variant); stack_.pop_back(); stack_.push_back(Value{left_value / right_value}); break; } case Op_code::not_: { const auto value = apply_visitor(Is_truthy_visitor{}, stack_.back().variant); stack_.pop_back(); stack_.push_back(Value{!value}); break; } case Op_code::negate: { // TODO Convert error: "Operand must be a number." const auto value = get<double>(stack_.back().variant); stack_.pop_back(); stack_.push_back(Value{-value}); break; } case Op_code::print: { print_value(stack_.back()); cout << "\n"; stack_.pop_back(); break; } case Op_code::jump: { // DANGER! Reinterpret cast: The two bytes following a jump_if_false instruction // are supposed to represent a single uint16 number const auto jump_length = reinterpret_cast<const uint16_t&>(*(frames_.back().ip)); frames_.back().ip += 2; frames_.back().ip += jump_length; break; } case Op_code::jump_if_false: { // DANGER! Reinterpret cast: The two bytes following a jump_if_false instruction // are supposed to represent a single uint16 number const auto jump_length = reinterpret_cast<const uint16_t&>(*(frames_.back().ip)); frames_.back().ip += 2; if (!apply_visitor(Is_truthy_visitor{}, stack_.back().variant)) { frames_.back().ip += jump_length; } break; } case Op_code::loop: { // DANGER! Reinterpret cast: The two bytes following a loop instruction // are supposed to represent a single uint16 number const auto jump_length = reinterpret_cast<const uint16_t&>(*(frames_.back().ip)); frames_.back().ip -= 1; frames_.back().ip -= jump_length; break; } case Op_code::call: { auto arg_count = *frames_.back().ip++; Call_visitor call_visitor {arg_count, frames_, stack_}; apply_visitor(call_visitor, (stack_.end() - 1 - arg_count)->variant); break; } case Op_code::return_: { const auto return_value = stack_.back(); stack_.erase(frames_.back().stack_begin, stack_.end()); frames_.pop_back(); if (frames_.empty()) { return; } stack_.push_back(return_value); break; } } } } VM_error::VM_error(const string& what, const vector<Call_frame>& frames) : VM_error{what + "\n" + stack_trace(frames)} {} }}
33.594406
136
0.490425
Jeff-Mott-OR
9bb8bc9b7e857f3e82af6939d8ca22a11a54b4d9
2,147
hpp
C++
search.hpp
dasapon/cappuccino
e198a495d8061b01ab34eb202415db2b28bce619
[ "MIT" ]
2
2018-02-14T15:10:41.000Z
2018-02-19T23:46:45.000Z
search.hpp
dasapon/cappuccino
e198a495d8061b01ab34eb202415db2b28bce619
[ "MIT" ]
null
null
null
search.hpp
dasapon/cappuccino
e198a495d8061b01ab34eb202415db2b28bce619
[ "MIT" ]
null
null
null
#pragma once #include "position.hpp" #include "state.hpp" #include "hash_table.hpp" #include "time.hpp" constexpr int max_ply = 128; using PV = sheena::Array<Move, max_ply>; enum { RPSDepth = 4 * depth_scale, }; class KillerMove : public sheena::Array<Move, 2>{ public: void update(Move m){ if((*this)[0] != m){ (*this)[1] = (*this)[0]; (*this)[0] = m; } } void clear(){ (*this)[1] = (*this)[0] = NullMove; } }; class MoveOrdering{ enum Status{ Hash, Important, All, }; Status status; int n_moves; int idx; sheena::Array<Move, MaxLegalMove> moves; sheena::Array<float, MaxLegalMove> scores; const State& state; Move hash_move; KillerMove killer; bool do_fp; void insertion_sort(int start, int end); public: MoveOrdering(const State& state, Move hash_move, const KillerMove& killer, bool rps, bool do_fp); MoveOrdering(const State& state, Move hash_move); Move next(float* score); }; class Searcher{ int search(State& state, int alpha, int beta, int depth, int ply); int qsearch(State& state, int alpha, int beta, int depth, int ply); int search_w(State& state, int alpha, int beta, int depth, int ply); std::thread main_thread, timer_thread; uint64_t nodes; HashTable hash_table; PV pv_table[max_ply]; KillerMove killer[max_ply + 2]; int think_with_timer(State& state, int max_depth, bool print); int think(State& state, int max_depth, PV& pv, bool print, bool wait_timer_stopping); public: ~Searcher(){ if(main_thread.joinable())main_thread.join(); } Searcher(){} void go(State& state, uint64_t time, uint64_t inc, bool ponder_or_infinite); int think(State& state, int max_depth, PV& pv, bool print); int think(State& state, int max_depth, bool print); void hash_size(size_t mb){hash_table.set_size(mb);} uint64_t node_searched()const{return nodes;} //time control private: volatile bool abort; volatile bool inf; Timer search_start; void timer_start(uint64_t, uint64_t, bool); public: void ponder_hit(){ inf = false; } void stop(){ inf = false; abort = true; if(main_thread.joinable())main_thread.join(); if(timer_thread.joinable())timer_thread.join(); } };
23.855556
98
0.704704
dasapon
9bbc054ea09ab3a7ff30d0248cdf6e577f52a1f9
15,964
hpp
C++
examples/example_utils.hpp
ROCmMathLibrariesBot/hipCUB
003a5b2b791dc01e88d0c0caaaf1de9ae53ad638
[ "BSD-3-Clause" ]
36
2019-05-14T09:27:57.000Z
2022-03-03T09:19:11.000Z
examples/example_utils.hpp
ROCmMathLibrariesBot/hipCUB
003a5b2b791dc01e88d0c0caaaf1de9ae53ad638
[ "BSD-3-Clause" ]
70
2019-05-06T23:07:53.000Z
2022-03-17T08:24:22.000Z
examples/example_utils.hpp
ROCmMathLibrariesBot/hipCUB
003a5b2b791dc01e88d0c0caaaf1de9ae53ad638
[ "BSD-3-Clause" ]
25
2019-05-03T19:45:13.000Z
2022-03-31T08:14:38.000Z
#ifndef EXAMPLES_EXAMPLE_UTILS_HPP #define EXAMPLES_EXAMPLE_UTILS_HPP #include "mersenne.h" #include <vector> #include <sstream> #include <iostream> #include <hipcub/util_type.hpp> #include <hipcub/util_allocator.hpp> #include <hipcub/iterator/discard_output_iterator.hpp> #define AssertEquals(a, b) if ((a) != (b)) { std::cerr << "\n(" << __FILE__ << ": " << __LINE__ << ")\n"; exit(1);} template <typename T> T CoutCast(T val) { return val; } int CoutCast(char val) { return val; } int CoutCast(unsigned char val) { return val; } int CoutCast(signed char val) { return val; } /****************************************************************************** * Command-line parsing functionality ******************************************************************************/ /** * Utility for parsing command line arguments */ struct CommandLineArgs { std::vector<std::string> keys; std::vector<std::string> values; std::vector<std::string> args; hipDeviceProp_t deviceProp; float device_giga_bandwidth; std::size_t device_free_physmem; std::size_t device_total_physmem; /** * Constructor */ CommandLineArgs(int argc, char **argv) : keys(10), values(10) { using namespace std; // Initialize mersenne generator unsigned int mersenne_init[4]= {0x123, 0x234, 0x345, 0x456}; mersenne::init_by_array(mersenne_init, 4); for (int i = 1; i < argc; i++) { string arg = argv[i]; if ((arg[0] != '-') || (arg[1] != '-')) { args.push_back(arg); continue; } string::size_type pos; string key, val; if ((pos = arg.find('=')) == string::npos) { key = string(arg, 2, arg.length() - 2); val = ""; } else { key = string(arg, 2, pos - 2); val = string(arg, pos + 1, arg.length() - 1); } keys.push_back(key); values.push_back(val); } } /** * Checks whether a flag "--<flag>" is present in the commandline */ bool CheckCmdLineFlag(const char* arg_name) { using namespace std; for (std::size_t i = 0; i < keys.size(); ++i) { if (keys[i] == string(arg_name)) return true; } return false; } /** * Returns number of naked (non-flag and non-key-value) commandline parameters */ template <typename T> int NumNakedArgs() { return args.size(); } /** * Returns the commandline parameter for a given index (not including flags) */ template <typename T> void GetCmdLineArgument(std::size_t index, T &val) { using namespace std; if (index < args.size()) { std::istringstream str_stream(args[index]); str_stream >> val; } } /** * Returns the value specified for a given commandline parameter --<flag>=<value> */ template <typename T> void GetCmdLineArgument(const char *arg_name, T &val) { using namespace std; for (std::size_t i = 0; i < keys.size(); ++i) { if (keys[i] == string(arg_name)) { std::istringstream str_stream(values[i]); str_stream >> val; } } } /** * Returns the values specified for a given commandline parameter --<flag>=<value>,<value>* */ template <typename T> void GetCmdLineArguments(const char *arg_name, std::vector<T> &vals) { using namespace std; if (CheckCmdLineFlag(arg_name)) { // Clear any default values vals.clear(); // Recover from multi-value string for (std::size_t i = 0; i < keys.size(); ++i) { if (keys[i] == string(arg_name)) { string val_string(values[i]); std::istringstream str_stream(val_string); string::size_type old_pos = 0; string::size_type new_pos = 0; // Iterate comma-separated values T val; while ((new_pos = val_string.find(',', old_pos)) != string::npos) { if (new_pos != old_pos) { str_stream.width(new_pos - old_pos); str_stream >> val; vals.push_back(val); } // skip over comma str_stream.ignore(1); old_pos = new_pos + 1; } // Read last value str_stream >> val; vals.push_back(val); } } } } /** * The number of pairs parsed */ int ParsedArgc() { return (int) keys.size(); } /** * Initialize device */ hipError_t DeviceInit(int dev = -1) { hipError_t error = hipSuccess; do { int deviceCount; error = hipGetDeviceCount(&deviceCount); if (error) break; if (deviceCount == 0) { fprintf(stderr, "No devices supporting CUDA.\n"); exit(1); } if (dev < 0) { GetCmdLineArgument("device", dev); } if ((dev > deviceCount - 1) || (dev < 0)) { dev = 0; } error = hipSetDevice(dev); if (error) break; hipMemGetInfo(&device_free_physmem, &device_total_physmem); // int ptx_version = 0; // error = hipcub::PtxVersion(ptx_version); // if (error) break; error = hipGetDeviceProperties(&deviceProp, dev); if (error) break; if (deviceProp.major < 1) { fprintf(stderr, "Device does not support Hip.\n"); exit(1); } device_giga_bandwidth = float(deviceProp.memoryBusWidth) * deviceProp.memoryClockRate * 2 / 8 / 1000 / 1000; if (!CheckCmdLineFlag("quiet")) { printf( "Using device %d: %s ( SM%d, %d SMs, " "%lld free / %lld total MB physmem, " "%.3f GB/s @ %d kHz mem clock, ECC %s)\n", dev, deviceProp.name, deviceProp.major * 100 + deviceProp.minor * 10, deviceProp.multiProcessorCount, (unsigned long long) device_free_physmem / 1024 / 1024, (unsigned long long) device_total_physmem / 1024 / 1024, device_giga_bandwidth, deviceProp.memoryClockRate, (deviceProp.ECCEnabled) ? "on" : "off"); fflush(stdout); } } while (0); return error; } }; /****************************************************************************** * Helper routines for list comparison and display ******************************************************************************/ /** * Compares the equivalence of two arrays */ template <typename S, typename T, typename OffsetT> int CompareResults(T* computed, S* reference, OffsetT len, bool verbose = true) { for (OffsetT i = 0; i < len; i++) { if (computed[i] != reference[i]) { if (verbose) std::cout << "INCORRECT: [" << i << "]: " << CoutCast(computed[i]) << " != " << CoutCast(reference[i]); return 1; } } return 0; } /** * Compares the equivalence of two arrays */ template <typename OffsetT> int CompareResults(float* computed, float* reference, OffsetT len, bool verbose = true) { for (OffsetT i = 0; i < len; i++) { if (computed[i] != reference[i]) { float difference = std::abs(computed[i]-reference[i]); float fraction = difference / std::abs(reference[i]); if (fraction > 0.0001) { if (verbose) std::cout << "INCORRECT: [" << i << "]: " << "(computed) " << CoutCast(computed[i]) << " != " << CoutCast(reference[i]) << " (difference:" << difference << ", fraction: " << fraction << ")"; return 1; } } } return 0; } /** * Compares the equivalence of two arrays */ // template <typename OffsetT> // int CompareResults(hipcub::NullType* computed, hipcub::NullType* reference, OffsetT len, bool verbose = true) // { // return 0; // } /** * Compares the equivalence of two arrays */ template <typename OffsetT> int CompareResults(double* computed, double* reference, OffsetT len, bool verbose = true) { for (OffsetT i = 0; i < len; i++) { if (computed[i] != reference[i]) { double difference = std::abs(computed[i]-reference[i]); double fraction = difference / std::abs(reference[i]); if (fraction > 0.0001) { if (verbose) std::cout << "INCORRECT: [" << i << "]: " << CoutCast(computed[i]) << " != " << CoutCast(reference[i]) << " (difference:" << difference << ", fraction: " << fraction << ")"; return 1; } } } return 0; } // /** // * Verify the contents of a device array match those // * of a host array // */ // int CompareDeviceResults( // hipcub::NullType */* h_reference */, // hipcub::NullType */* d_data */, // std::size_t /* num_items */, // bool /* verbose */ = true, // bool /* display_data */ = false) // { // return 0; // } /** * Verify the contents of a device array match those * of a host array */ // template <typename S, typename OffsetT> // int CompareDeviceResults( // S *h_reference, // hipcub::DiscardOutputIterator<OffsetT> d_data, // std::size_t num_items, // bool verbose = true, // bool display_data = false) // { // return 0; // } /** * Verify the contents of a device array match those * of a host array */ template <typename S, typename T> int CompareDeviceResults( S *h_reference, T *d_data, std::size_t num_items, bool verbose = true, bool display_data = false) { // Allocate array on host T *h_data = (T*) malloc(num_items * sizeof(T)); // Copy data back hipMemcpy(h_data, d_data, sizeof(T) * num_items, hipMemcpyDeviceToHost); // Display data if (display_data) { printf("Reference:\n"); for (std::size_t i = 0; i < num_items; i++) { std::cout << CoutCast(h_reference[i]) << ", "; } printf("\n\nComputed:\n"); for (std::size_t i = 0; i < num_items; i++) { std::cout << CoutCast(h_data[i]) << ", "; } printf("\n\n"); } // Check int retval = CompareResults(h_data, h_reference, num_items, verbose); // Cleanup if (h_data) free(h_data); return retval; } /** * Verify the contents of a device array match those * of a device array */ template <typename T> int CompareDeviceDeviceResults( T *d_reference, T *d_data, std::size_t num_items, bool verbose = true, bool display_data = false) { // Allocate array on host T *h_reference = (T*) malloc(num_items * sizeof(T)); T *h_data = (T*) malloc(num_items * sizeof(T)); // Copy data back hipMemcpy(h_reference, d_reference, sizeof(T) * num_items, hipMemcpyDeviceToHost); hipMemcpy(h_data, d_data, sizeof(T) * num_items, hipMemcpyDeviceToHost); // Display data if (display_data) { printf("Reference:\n"); for (std::size_t i = 0; i < num_items; i++) { std::cout << CoutCast(h_reference[i]) << ", "; } printf("\n\nComputed:\n"); for (std::size_t i = 0; i < num_items; i++) { std::cout << CoutCast(h_data[i]) << ", "; } printf("\n\n"); } // Check int retval = CompareResults(h_data, h_reference, num_items, verbose); // Cleanup if (h_reference) free(h_reference); if (h_data) free(h_data); return retval; } /** * Print the contents of a host array */ template <typename InputIteratorT> void DisplayResults( InputIteratorT h_data, std::size_t num_items) { // Display data for (std::size_t i = 0; i < num_items; i++) { std::cout << CoutCast(h_data[i]) << ", "; } printf("\n"); } int g_num_rand_samples = 0; /** * Generates random keys. * * We always take the second-order byte from rand() because the higher-order * bits returned by rand() are commonly considered more uniformly distributed * than the lower-order bits. * * We can decrease the entropy level of keys by adopting the technique * of Thearling and Smith in which keys are computed from the bitwise AND of * multiple random samples: * * entropy_reduction | Effectively-unique bits per key * ----------------------------------------------------- * -1 | 0 * 0 | 32 * 1 | 25.95 (81%) * 2 | 17.41 (54%) * 3 | 10.78 (34%) * 4 | 6.42 (20%) * ... | ... * */ template <typename K> void RandomBits( K &key, int entropy_reduction = 0, int begin_bit = 0, int end_bit = sizeof(K) * 8) { const int NUM_BYTES = sizeof(K); const int WORD_BYTES = sizeof(unsigned int); const int NUM_WORDS = (NUM_BYTES + WORD_BYTES - 1) / WORD_BYTES; unsigned int word_buff[NUM_WORDS]; if (entropy_reduction == -1) { memset((void *) &key, 0, sizeof(key)); return; } if (end_bit < 0) end_bit = sizeof(K) * 8; while (true) { // Generate random word_buff for (int j = 0; j < NUM_WORDS; j++) { int current_bit = j * WORD_BYTES * 8; unsigned int word = 0xffffffff; word &= 0xffffffff << std::max(0, begin_bit - current_bit); word &= 0xffffffff >> std::max(0, (current_bit + (WORD_BYTES * 8)) - end_bit); for (int i = 0; i <= entropy_reduction; i++) { // Grab some of the higher bits from rand (better entropy, supposedly) word &= mersenne::genrand_int32(); g_num_rand_samples++; } word_buff[j] = word; } memcpy(&key, word_buff, sizeof(K)); K copy = key; if (!std::isnan(copy)) break; // avoids NaNs when generating random floating point numbers } } /// Randomly select number between [0:max) template <typename T> T RandomValue(T max) { unsigned int bits; unsigned int max_int = (unsigned int) -1; do { RandomBits(bits); } while (bits == max_int); return (T) ((double(bits) / double(max_int)) * double(max)); } struct GpuTimer { hipEvent_t start; hipEvent_t stop; GpuTimer() { hipEventCreate(&start); hipEventCreate(&stop); } ~GpuTimer() { hipEventDestroy(start); hipEventDestroy(stop); } void Start() { hipEventRecord(start, 0); } void Stop() { hipEventRecord(stop, 0); } float ElapsedMillis() { float elapsed; hipEventSynchronize(stop); hipEventElapsedTime(&elapsed, start, stop); return elapsed; } }; #endif
26.343234
120
0.502255
ROCmMathLibrariesBot