Dataset Viewer (First 5GB)
Auto-converted to Parquet Duplicate
blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
591b796a77ece19db9ed1b2670d4160de7ababcb
98c9087c563688a690dda6d3f06b45edbb6650fc
/sem1/hw9/hw9.1/hw9.1/hashtable.h
fd9a3f473d4514fba6632e90af4c1de23986d530
[ "Apache-2.0" ]
permissive
Daria-Donina/spbu1stYear
0d80bed8ba4597bd65dcec76354a2d37df61c6fe
8853fb65c7a0ad62556a49d12908098af9caf7ed
refs/heads/master
2020-03-30T04:37:32.773000
2019-04-14T13:29:51
2019-04-14T13:29:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
648
h
hashtable.h
#pragma once #include <fstream> namespace hashTable { struct HashTable; //Create hash table HashTable *createHashtable(); //Print content of a hash table void printHashTable(HashTable *hashTable); //Delete hash table void deleteHashTable(HashTable *hashTable); //Load factor of a hash table float loadFactor(HashTable *hashTable); //Maximum length of a list in a hash table int maxListLength(HashTable *hashTable); //Average length of a list in a hash table float averageListLength(HashTable *hashTable); //Fill hash table void add(std::ifstream &inputData, HashTable *hashTable); } //Testing the program bool programTest();
732e725b6b9b240253cb31b4f757e02773216bcb
2ba220de6f1279bb7e52234149aa9da13f796c09
/src/actions/action.hpp
87880393ca0a52965fefd711719f9859011c8548
[]
no_license
marblefactory/Server
b19abfef8ecf179200996d13b393abf368723185
9d19db11e2ef8cb7727047a431ddfb1416eb50b1
refs/heads/master
2021-08-20T09:01:56.131000
2017-11-28T17:50:03
2017-11-28T17:50:03
112,361,812
0
0
null
null
null
null
UTF-8
C++
false
false
759
hpp
action.hpp
// // action.h // EngineCommandSet // // Created by Albie Baker-Smith on 14/11/2017. // Copyright © 2017 Albie Baker-Smith. All rights reserved. // #ifndef action_h #define action_h #include "action_visitor.hpp" #include "../objects/object.hpp" // Parent class for other actions, e.g. movement, interaction, etc class Action { public: virtual void accept(ActionVisitor &visitor) = 0; }; // Represents a move the spy can make. class Move: public Action { public: // The destination of the movement, i.e. where the spy will end up after // executing the movement. Object *dest; Move(Object *dest): dest(dest) { } void accept(ActionVisitor &visitor) override { visitor.visit(*this); } }; #endif /* action_h */
e7e3e7303e6d487b9511479ac2d4aed54235f0ef
0f41e546cf59b389e6e657980ea1019a811b1c54
/hdu/guess_number.cpp
8f15d504163d379621cc4fbf80d1eacc2de4eebb
[]
no_license
aim-for-better/acm
ef23964e02016361e9dd70cff2520cb86a57f3f4
6d4d939b811bb00b3f148b74f3d3b3720b61bf97
refs/heads/master
2020-07-18T03:53:15.455000
2017-10-30T14:26:52
2017-10-30T14:26:52
73,922,672
0
0
null
null
null
null
UTF-8
C++
false
false
1,813
cpp
guess_number.cpp
#include <iostream> #include<cstdio> #include<cstring> using namespace std; const int maxn=105; struct Node{ int a; int b; //the number of that a has equal with the dst number int c; //the number in the right position }; Node node[maxn]; int realNum[5]; int guessNum[5]; bool judge(int real,int j){ realNum[1]=real/1000; realNum[2]=(real%1000)/100; realNum[3]=(real%100)/10; realNum[4]=(real%10); guessNum[1]=node[j].a/1000; guessNum[2]=(node[j].a%1000)/100; guessNum[3]=(node[j].a%100)/10; guessNum[4]=(node[j].a%10); int cnt=0; for(int i=1;i<=4;i++){ if(realNum[i]==guessNum[i])cnt++; } if(cnt!=node[j].c) return false; bool mark[5]; for(int i=1;i<=4;i++) mark[i]=false; cnt=0; for(int i=1;i<=4;i++){ for(int j=1;j<=4;j++){ if(realNum[i]==guessNum[j]&&!mark[j]){ cnt++; mark[j]=true; break; // break to fine the next i } } } if(cnt!=node[j].b)return false; return true; } int main() { int n; bool flag=true; int cnt=0; int ans=0; while(scanf("%d",&n)!=EOF){ if(n==0)break; for(int i=1;i<=n;i++){ scanf("%d%d%d",&node[i].a,&node[i].b,&node[i].c); } cnt=0; ans=0; // mei ju for(int i=1000;i<=9999;i++){ flag=true; for(int j=1;j<=n;j++){ if(!judge(i,j)){ flag=false; break; } } if(flag){ cnt++; ans=i; } } if(cnt==1){ printf("%d\n",ans); }else{ printf("Not sure\n"); } } return 0; }
b5f9d75f4028469d045311662abb5c0433473786
3fa05bd3be30fe7d8b7b7df08e49bbb87403c30b
/src/site.h
b43632fe64a09c3cb724296f9a9b1dce55a84301
[]
no_license
joebradly/kMC
e50aaa3a4183e88c1600c59b9780040c6bd077c5
3e7b138fc07bb36c6242cde1059bb1fa6f96743c
refs/heads/master
2020-12-26T18:47:19.358000
2014-03-24T19:12:55
2014-03-24T19:12:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,646
h
site.h
#pragma once #include "particlestates.h" #include <vector> #include <set> #include <sys/types.h> #include <armadillo> #include <assert.h> #include <libconfig_utils/libconfig_utils.h> using namespace arma; namespace kMC { class KMCSolver; class Reaction; class DiffusionReaction; class Boundary; class Site { public: Site(uint _x, uint _y, uint _z); ~Site(); /* * Static non-trivial functions */ static void setMainSolver(KMCSolver* solver); static void loadConfig(const Setting & setting); static void initializeBoundaries(); static void updateBoundaries(); static void updateAffectedSites(); static void selectUpdateFlags(); /* * Misc static property functions */ static uint getLevel(uint i, uint j, uint k); static double getCurrentSolutionDensity(); static double getCurrentRelativeCrystalOccupancy(); static umat getCurrentCrystalBoxTopology(); /* * Init / Reset / clear static implementations */ static void setInitialNNeighborsLimit(const uint & nNeighborsLimit, bool check = true); static void setInitialBoundaries(const umat & boundaryMatrix); static void setInitialBoundaries(const int boundaryType); static void setInitialNNeighborsToCrystallize(const uint & nNeighborsToCrystallize); static void resetBoundariesTo(const umat & boundaryMatrix); static void resetBoundariesTo(const int boundaryType); static void resetNNeighborsLimitTo(const uint & nNeighborsLimit, bool check = true); static void resetNNeighborsToCrystallizeTo(const uint & nNeighborsToCrystallize); static void clearAll(); static void clearAffectedSites(); static void clearBoundaries(); static void finalizeBoundaries(); static void setZeroTotalEnergy(); /* * Non-trivial functions */ void setParticleState(int newState); bool isLegalToSpawn(); bool qualifiesAsCrystal(); bool qualifiesAsSurface(); void spawnAsFixedCrystal(); void spawnAsCrystal(); void blockCrystallizationOnSite(); void allowCrystallizationOnSite(); void crystallize(); void decrystallize(); void activate(); void deactivate(); void flipActive(); void flipDeactive(); void addReaction(Reaction* reaction) { m_reactions.push_back(reaction); } void calculateRates(); void initializeDiffusionReactions(); void introduceNeighborhood(); bool hasNeighboring(int state, int range) const; uint countNeighboring(int state, int range) const; void propagateToNeighbors(int reqOldState, int newState, int range); void informNeighborhoodOnChange(int change); void distanceTo(const Site * other, int &dx, int &dy, int &dz, bool absolutes = false) const; uint maxDistanceTo(const Site * other) const; double potentialBetween(const Site * other); void setNeighboringDirectUpdateFlags(); void queueAffectedSites(); void setZeroEnergy(); void reset(); void clearNeighborhood(); const string info(int xr = 0, int yr = 0, int zr = 0, string desc = "X") const; void forEachNeighborDo(function<void (Site *)> applyFunction) const; void forEachNeighborDo_sendIndices(function<void (Site *, uint, uint, uint)> applyFunction) const; void forEachActiveReactionDo(function<void (Reaction*)> applyFunction) const; void forEachActiveReactionDo_sendIndex(function<void (Reaction*, uint)> applyFunction) const; /* * Misc. trivial functions */ static const uint & nSurfaces() { return m_totalDeactiveParticles.memptr()[ParticleStates::surface]; } static uint nCrystals() { return m_totalActiveParticles(ParticleStates::crystal) + m_totalActiveParticles(ParticleStates::fixedCrystal); } static const uint & nSolutionParticles() { return m_totalActiveParticles.memptr()[ParticleStates::solution]; } static const uint &boundaryTypes(const uint i, const uint j = 0) { return m_boundaryTypes(i, j); } static const uint &nNeighborsToCrystallize() { return m_nNeighborsToCrystallize; } static const uint &nNeighborsLimit() { return m_nNeighborsLimit; } static const uint &neighborhoodLength() { return m_neighborhoodLength; } static const uint &levelMatrix(const uint i, const uint j, const uint k) { return m_levelMatrix(i, j, k); } static uint originTransformVector(const uint i) { return m_originTransformVector(i); } static const uint & totalActiveSites() { return m_totalActiveSites; } static const uvec4 & totalActiveParticlesVector() { return m_totalActiveParticles; } static const uvec4 & totalDeactiveParticlesVector() { return m_totalDeactiveParticles; } static const uint & totalActiveParticles(const uint i) { return m_totalActiveParticles(i); } static const uint & totalDeactiveParticles(const uint i) { return m_totalDeactiveParticles(i); } static const double & totalEnergy() { return m_totalEnergy; } static const Boundary * boundaries(const uint xyz, const uint loc) { return m_boundaries(xyz, loc); } static const field<Boundary*> & boundaryField() { return m_boundaries; } const int & particleState() const { return m_particleState; } string particleStateName() const { return ParticleStates::names.at(m_particleState); } string particleStateShortName() const { return ParticleStates::shortNames.at(m_particleState); } uint nNeighbors(uint level = 0) const { return m_nNeighbors(level); } uint nActiveReactions() const; uint nNeighborsSum() const; bool isCrystal() const { return ((m_particleState == ParticleStates::crystal) || (m_particleState == ParticleStates::fixedCrystal)); } bool isSurface() const { return m_particleState == ParticleStates::surface; } const bool & isActive() const { return m_active; } const uint & x() const { return m_x; } const uint & y() const { return m_y; } const uint & z() const { return m_z; } const uint & r(const uint i) const { return m_r(i); } const vector<Reaction*> & reactions() const { return m_reactions; } const static set<Site*> & affectedSites() { return m_affectedSites; } Site* neighborhood(const uint x, const uint y, const uint z) const { return m_neighborhood[x][y][z]; } double energy() const { return m_energy; } const bool & isFixedCrystalSeed() { return m_isFixedCrystalSeed; } const bool & cannotCrystallize() { return m_cannotCrystallize; } bool operator == (const Site & other) const { return this == &other; } const string str() const { stringstream s; s << "Site@(" << x() << ", " << y() << ", " << z() << ")"; return s.str(); } const static uint & NX(); const static uint & NY(); const static uint & NZ(); //should be in site.. all sites in sites and jazz jazz.. void clearAllReactions(); private: static field<Boundary*> m_boundaries; static field<const Setting*> m_boundaryConfigs; static umat m_boundaryTypes; static uint m_nNeighborsLimit; static uint m_neighborhoodLength; static uint m_nNeighborsToCrystallize; static ucube m_levelMatrix; static ivec m_originTransformVector; static uint m_totalActiveSites; static uvec4 m_totalActiveParticles; static uvec4 m_totalDeactiveParticles; static double m_totalEnergy; static set<Site*> m_affectedSites; static KMCSolver* m_solver; Site**** m_neighborhood; uvec m_nNeighbors; uint m_nNeighborsSum; bool m_active; bool m_isFixedCrystalSeed; bool m_cannotCrystallize; const uint m_x; const uint m_y; const uint m_z; const uvec3 m_r; double m_energy; int m_particleState = ParticleStates::solution; vector<Reaction*> m_reactions; DiffusionReaction* m_diffusionReactions[3][3][3]; void setNewParticleState(int newState); void deactivateFixedCrystal(); }; } ostream& operator<<(ostream& os, const kMC::Site& ss);
7c1f40cf9eb376f9293a37e8311a60e4ca800c3f
d96ebf4dac46404a46253afba5ba5fc985d5f6fc
/third_party/highway/hwy/tests/compress_test.cc
1ff457a46438f7cec7814de3acf9f61e939d24eb
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
marco-c/gecko-dev-wordified-and-comments-removed
f9de100d716661bd67a3e7e3d4578df48c87733d
74cb3d31740be3ea5aba5cb7b3f91244977ea350
refs/heads/master
2023-08-04T23:19:13.836000
2023-08-01T00:33:54
2023-08-01T00:33:54
211,297,165
1
0
null
null
null
null
UTF-8
C++
false
false
20,969
cc
compress_test.cc
# include < stdio . h > # include < string . h > # include < array > # undef HWY_TARGET_INCLUDE # define HWY_TARGET_INCLUDE " tests / compress_test . cc " # include " hwy / foreach_target . h " # include " hwy / highway . h " # include " hwy / tests / test_util - inl . h " HWY_BEFORE_NAMESPACE ( ) ; namespace hwy { namespace HWY_NAMESPACE { # define HWY_PRINT_TABLES 0 # if ! HWY_PRINT_TABLES | | HWY_IDE template < class D class DI typename T = TFromD < D > typename TI = TFromD < DI > > void CheckStored ( D d DI di const char * op size_t expected_pos size_t actual_pos size_t num_to_check const AlignedFreeUniquePtr < T [ ] > & in const AlignedFreeUniquePtr < TI [ ] > & mask_lanes const AlignedFreeUniquePtr < T [ ] > & expected const T * actual_u int line ) { if ( expected_pos ! = actual_pos ) { hwy : : Abort ( __FILE__ line " % s : size mismatch for % s : expected % d actual % d \ n " op TypeName ( T ( ) Lanes ( d ) ) . c_str ( ) static_cast < int > ( expected_pos ) static_cast < int > ( actual_pos ) ) ; } for ( size_t i = 0 ; i < num_to_check ; + + i ) { if ( ! IsEqual ( expected [ i ] actual_u [ i ] ) ) { const size_t N = Lanes ( d ) ; fprintf ( stderr " % s : mismatch at i = % d of % d line % d : \ n \ n " op static_cast < int > ( i ) static_cast < int > ( num_to_check ) line ) ; Print ( di " mask " Load ( di mask_lanes . get ( ) ) 0 N ) ; Print ( d " in " Load ( d in . get ( ) ) 0 N ) ; Print ( d " expect " Load ( d expected . get ( ) ) 0 num_to_check ) ; Print ( d " actual " Load ( d actual_u ) 0 num_to_check ) ; HWY_ASSERT ( false ) ; } } } struct TestCompress { template < class T class D > HWY_NOINLINE void operator ( ) ( T D d ) { RandomState rng ; using TI = MakeSigned < T > ; using TU = MakeUnsigned < T > ; const Rebind < TI D > di ; const size_t N = Lanes ( d ) ; const size_t bits_size = RoundUpTo ( ( N + 7 ) / 8 8 ) ; for ( int frac : { 0 2 3 } ) { const size_t misalign = static_cast < size_t > ( frac ) * N / 4 ; auto in_lanes = AllocateAligned < T > ( N ) ; auto mask_lanes = AllocateAligned < TI > ( N ) ; auto garbage = AllocateAligned < TU > ( N ) ; auto expected = AllocateAligned < T > ( N ) ; auto actual_a = AllocateAligned < T > ( misalign + N ) ; auto bits = AllocateAligned < uint8_t > ( bits_size ) ; HWY_ASSERT ( in_lanes & & mask_lanes & & garbage & & expected & & actual_a & & bits ) ; T * actual_u = actual_a . get ( ) + misalign ; memset ( bits . get ( ) 0 bits_size ) ; for ( size_t rep = 0 ; rep < AdjustedReps ( 200 ) ; + + rep ) { size_t expected_pos = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { const uint64_t r = Random32 ( & rng ) ; in_lanes [ i ] = T ( ) ; CopyBytes < sizeof ( T ) > ( & r & in_lanes [ i ] ) ; mask_lanes [ i ] = ( Random32 ( & rng ) & 1024 ) ? TI ( 1 ) : TI ( 0 ) ; if ( mask_lanes [ i ] > 0 ) { expected [ expected_pos + + ] = in_lanes [ i ] ; } garbage [ i ] = static_cast < TU > ( Random64 ( & rng ) ) ; } size_t num_to_check ; if ( CompressIsPartition < T > : : value ) { size_t extra = expected_pos ; for ( size_t i = 0 ; i < N ; + + i ) { if ( mask_lanes [ i ] = = 0 ) { expected [ extra + + ] = in_lanes [ i ] ; } } HWY_ASSERT ( extra = = N ) ; num_to_check = N ; } else { num_to_check = expected_pos ; } const auto in = Load ( d in_lanes . get ( ) ) ; const auto mask = RebindMask ( d Gt ( Load ( di mask_lanes . get ( ) ) Zero ( di ) ) ) ; StoreMaskBits ( d mask bits . get ( ) ) ; memset ( actual_u 0 N * sizeof ( T ) ) ; StoreU ( Compress ( in mask ) d actual_u ) ; CheckStored ( d di " Compress " expected_pos expected_pos num_to_check in_lanes mask_lanes expected actual_u __LINE__ ) ; memset ( actual_u 0 N * sizeof ( T ) ) ; StoreU ( CompressNot ( in Not ( mask ) ) d actual_u ) ; CheckStored ( d di " CompressNot " expected_pos expected_pos num_to_check in_lanes mask_lanes expected actual_u __LINE__ ) ; memset ( actual_u 0 N * sizeof ( T ) ) ; const size_t size1 = CompressStore ( in mask d actual_u ) ; CheckStored ( d di " CompressStore " expected_pos size1 expected_pos in_lanes mask_lanes expected actual_u __LINE__ ) ; memcpy ( actual_u garbage . get ( ) N * sizeof ( T ) ) ; const size_t size2 = CompressBlendedStore ( in mask d actual_u ) ; CheckStored ( d di " CompressBlendedStore " expected_pos size2 expected_pos in_lanes mask_lanes expected actual_u __LINE__ ) ; for ( size_t i = size2 ; i < N ; + + i ) { # if HWY_COMPILER_MSVC & & HWY_TARGET = = HWY_AVX2 # else HWY_ASSERT_EQ ( garbage [ i ] reinterpret_cast < TU * > ( actual_u ) [ i ] ) ; # endif } memset ( actual_u 0 N * sizeof ( T ) ) ; StoreU ( CompressBits ( in bits . get ( ) ) d actual_u ) ; CheckStored ( d di " CompressBits " expected_pos expected_pos num_to_check in_lanes mask_lanes expected actual_u __LINE__ ) ; memset ( actual_u 0 N * sizeof ( T ) ) ; const size_t size3 = CompressBitsStore ( in bits . get ( ) d actual_u ) ; CheckStored ( d di " CompressBitsStore " expected_pos size3 expected_pos in_lanes mask_lanes expected actual_u __LINE__ ) ; } } } } ; HWY_NOINLINE void TestAllCompress ( ) { ForAllTypes ( ForPartialVectors < TestCompress > ( ) ) ; } struct TestCompressBlocks { template < class T class D > HWY_NOINLINE void operator ( ) ( T D d ) { # if HWY_TARGET = = HWY_SCALAR ( void ) d ; # else static_assert ( sizeof ( T ) = = 8 & & ! IsSigned < T > ( ) " Should be u64 " ) ; RandomState rng ; using TI = MakeSigned < T > ; const Rebind < TI D > di ; const size_t N = Lanes ( d ) ; auto in_lanes = AllocateAligned < T > ( N ) ; auto mask_lanes = AllocateAligned < TI > ( N ) ; auto expected = AllocateAligned < T > ( N ) ; auto actual = AllocateAligned < T > ( N ) ; HWY_ASSERT ( in_lanes & & mask_lanes & & expected & & actual ) ; for ( size_t rep = 0 ; rep < AdjustedReps ( 200 ) ; + + rep ) { size_t expected_pos = 0 ; for ( size_t i = 0 ; i < N ; i + = 2 ) { const uint64_t bits = Random32 ( & rng ) ; in_lanes [ i + 1 ] = in_lanes [ i ] = T ( ) ; CopyBytes < sizeof ( T ) > ( & bits & in_lanes [ i ] ) ; CopyBytes < sizeof ( T ) > ( & bits & in_lanes [ i + 1 ] ) ; mask_lanes [ i + 1 ] = mask_lanes [ i ] = TI { ( Random32 ( & rng ) & 8 ) ? 1 : 0 } ; if ( mask_lanes [ i ] > 0 ) { expected [ expected_pos + + ] = in_lanes [ i ] ; expected [ expected_pos + + ] = in_lanes [ i + 1 ] ; } } size_t num_to_check ; if ( CompressIsPartition < T > : : value ) { size_t extra = expected_pos ; for ( size_t i = 0 ; i < N ; + + i ) { if ( mask_lanes [ i ] = = 0 ) { expected [ extra + + ] = in_lanes [ i ] ; } } HWY_ASSERT ( extra = = N ) ; num_to_check = N ; } else { num_to_check = expected_pos ; } const auto in = Load ( d in_lanes . get ( ) ) ; const auto mask = RebindMask ( d Gt ( Load ( di mask_lanes . get ( ) ) Zero ( di ) ) ) ; memset ( actual . get ( ) 0 N * sizeof ( T ) ) ; StoreU ( CompressBlocksNot ( in Not ( mask ) ) d actual . get ( ) ) ; CheckStored ( d di " CompressBlocksNot " expected_pos expected_pos num_to_check in_lanes mask_lanes expected actual . get ( ) __LINE__ ) ; } # endif } } ; HWY_NOINLINE void TestAllCompressBlocks ( ) { ForGE128Vectors < TestCompressBlocks > ( ) ( uint64_t ( ) ) ; } # endif # if HWY_PRINT_TABLES | | HWY_IDE namespace detail { void PrintCompress8x8Tables ( ) { printf ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 8x8 \ n " ) ; constexpr size_t N = 8 ; for ( uint64_t code = 0 ; code < ( 1ull < < N ) ; + + code ) { std : : array < uint8_t N > indices { 0 } ; size_t pos = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { if ( code & ( 1ull < < i ) ) { indices [ pos + + ] = i ; } } for ( size_t i = 0 ; i < N ; + + i ) { if ( ! ( code & ( 1ull < < i ) ) ) { indices [ pos + + ] = i ; } } HWY_ASSERT ( pos = = N ) ; for ( size_t i = 0 ; i < N ; + + i ) { printf ( " % d " indices [ i ] ) ; } printf ( code & 1 ? " / / \ n " : " / * * / " ) ; } printf ( " \ n " ) ; } void PrintCompress16x8Tables ( ) { printf ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 16x8 \ n " ) ; constexpr size_t N = 8 ; for ( uint64_t code = 0 ; code < ( 1ull < < N ) ; + + code ) { std : : array < uint8_t N > indices { 0 } ; size_t pos = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { if ( code & ( 1ull < < i ) ) { indices [ pos + + ] = i ; } } for ( size_t i = 0 ; i < N ; + + i ) { if ( ! ( code & ( 1ull < < i ) ) ) { indices [ pos + + ] = i ; } } HWY_ASSERT ( pos = = N ) ; for ( size_t i = 0 ; i < N ; + + i ) { printf ( " % d " 2 * indices [ i ] ) ; } printf ( code & 1 ? " / / \ n " : " / * * / " ) ; } printf ( " \ n " ) ; } void PrintCompressNot16x8Tables ( ) { printf ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = Not 16x8 \ n " ) ; constexpr size_t N = 8 ; for ( uint64_t not_code = 0 ; not_code < ( 1ull < < N ) ; + + not_code ) { const uint64_t code = ~ not_code ; std : : array < uint8_t N > indices { 0 } ; size_t pos = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { if ( code & ( 1ull < < i ) ) { indices [ pos + + ] = i ; } } for ( size_t i = 0 ; i < N ; + + i ) { if ( ! ( code & ( 1ull < < i ) ) ) { indices [ pos + + ] = i ; } } HWY_ASSERT ( pos = = N ) ; for ( size_t i = 0 ; i < N ; + + i ) { printf ( " % d " 2 * indices [ i ] ) ; } printf ( not_code & 1 ? " / / \ n " : " / * * / " ) ; } printf ( " \ n " ) ; } void PrintCompress32x8Tables ( ) { printf ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 32 / 64x8 \ n " ) ; constexpr size_t N = 8 ; for ( uint64_t code = 0 ; code < ( 1ull < < N ) ; + + code ) { const size_t count = PopCount ( code ) ; std : : array < uint32_t N > indices { 0 } ; size_t pos = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { if ( code & ( 1ull < < i ) ) { indices [ pos + + ] = i ; } } for ( size_t i = 0 ; i < N ; + + i ) { if ( ! ( code & ( 1ull < < i ) ) ) { indices [ pos + + ] = i ; } } HWY_ASSERT ( pos = = N ) ; uint64_t packed = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { HWY_ASSERT ( indices [ i ] < N ) ; if ( i < count ) { indices [ i ] | = N ; HWY_ASSERT ( indices [ i ] < 0x10 ) ; } packed + = indices [ i ] < < ( i * 4 ) ; } HWY_ASSERT ( packed < ( 1ull < < ( N * 4 ) ) ) ; printf ( " 0x % 08x " static_cast < uint32_t > ( packed ) ) ; } printf ( " \ n " ) ; } void PrintCompressNot32x8Tables ( ) { printf ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = Not 32 / 64x8 \ n " ) ; constexpr size_t N = 8 ; for ( uint64_t not_code = 0 ; not_code < ( 1ull < < N ) ; + + not_code ) { const uint64_t code = ~ not_code ; const size_t count = PopCount ( code ) ; std : : array < uint32_t N > indices { 0 } ; size_t pos = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { if ( code & ( 1ull < < i ) ) { indices [ pos + + ] = i ; } } for ( size_t i = 0 ; i < N ; + + i ) { if ( ! ( code & ( 1ull < < i ) ) ) { indices [ pos + + ] = i ; } } HWY_ASSERT ( pos = = N ) ; uint64_t packed = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { HWY_ASSERT ( indices [ i ] < N ) ; if ( i < count ) { indices [ i ] | = N ; HWY_ASSERT ( indices [ i ] < 0x10 ) ; } packed + = indices [ i ] < < ( i * 4 ) ; } HWY_ASSERT ( packed < ( 1ull < < ( N * 4 ) ) ) ; printf ( " 0x % 08x " static_cast < uint32_t > ( packed ) ) ; } printf ( " \ n " ) ; } void PrintCompress64x4NibbleTables ( ) { printf ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 64x4Nibble \ n " ) ; constexpr size_t N = 4 ; for ( uint64_t code = 0 ; code < ( 1ull < < N ) ; + + code ) { std : : array < uint32_t N > indices { 0 } ; size_t pos = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { if ( code & ( 1ull < < i ) ) { indices [ pos + + ] = i ; } } for ( size_t i = 0 ; i < N ; + + i ) { if ( ! ( code & ( 1ull < < i ) ) ) { indices [ pos + + ] = i ; } } HWY_ASSERT ( pos = = N ) ; uint64_t packed = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { HWY_ASSERT ( indices [ i ] < N ) ; packed + = indices [ i ] < < ( i * 4 ) ; } HWY_ASSERT ( packed < ( 1ull < < ( N * 4 ) ) ) ; printf ( " 0x % 08x " static_cast < uint32_t > ( packed ) ) ; } printf ( " \ n " ) ; } void PrintCompressNot64x4NibbleTables ( ) { printf ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = Not 64x4Nibble \ n " ) ; constexpr size_t N = 4 ; for ( uint64_t not_code = 0 ; not_code < ( 1ull < < N ) ; + + not_code ) { const uint64_t code = ~ not_code ; std : : array < uint32_t N > indices { 0 } ; size_t pos = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { if ( code & ( 1ull < < i ) ) { indices [ pos + + ] = i ; } } for ( size_t i = 0 ; i < N ; + + i ) { if ( ! ( code & ( 1ull < < i ) ) ) { indices [ pos + + ] = i ; } } HWY_ASSERT ( pos = = N ) ; uint64_t packed = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { HWY_ASSERT ( indices [ i ] < N ) ; packed + = indices [ i ] < < ( i * 4 ) ; } HWY_ASSERT ( packed < ( 1ull < < ( N * 4 ) ) ) ; printf ( " 0x % 08x " static_cast < uint32_t > ( packed ) ) ; } printf ( " \ n " ) ; } void PrintCompressNot64x2NibbleTables ( ) { printf ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = Not 64x2Nibble \ n " ) ; constexpr size_t N = 2 ; for ( uint64_t not_code = 0 ; not_code < ( 1ull < < N ) ; + + not_code ) { const uint64_t code = ~ not_code ; std : : array < uint32_t N > indices { 0 } ; size_t pos = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { if ( code & ( 1ull < < i ) ) { indices [ pos + + ] = i ; } } for ( size_t i = 0 ; i < N ; + + i ) { if ( ! ( code & ( 1ull < < i ) ) ) { indices [ pos + + ] = i ; } } HWY_ASSERT ( pos = = N ) ; uint64_t packed = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { HWY_ASSERT ( indices [ i ] < N ) ; packed + = indices [ i ] < < ( i * 4 ) ; } HWY_ASSERT ( packed < ( 1ull < < ( N * 4 ) ) ) ; printf ( " 0x % 08x " static_cast < uint32_t > ( packed ) ) ; } printf ( " \ n " ) ; } void PrintCompress64x4Tables ( ) { printf ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 64x4 uncompressed \ n " ) ; constexpr size_t N = 4 ; for ( uint64_t code = 0 ; code < ( 1ull < < N ) ; + + code ) { std : : array < size_t N > indices { 0 } ; size_t pos = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { if ( code & ( 1ull < < i ) ) { indices [ pos + + ] = i ; } } for ( size_t i = 0 ; i < N ; + + i ) { if ( ! ( code & ( 1ull < < i ) ) ) { indices [ pos + + ] = i ; } } HWY_ASSERT ( pos = = N ) ; for ( size_t i = 0 ; i < N ; + + i ) { printf ( " % d " static_cast < int > ( indices [ i ] ) ) ; } } printf ( " \ n " ) ; } void PrintCompressNot64x4Tables ( ) { printf ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = Not 64x4 uncompressed \ n " ) ; constexpr size_t N = 4 ; for ( uint64_t not_code = 0 ; not_code < ( 1ull < < N ) ; + + not_code ) { const uint64_t code = ~ not_code ; std : : array < size_t N > indices { 0 } ; size_t pos = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { if ( code & ( 1ull < < i ) ) { indices [ pos + + ] = i ; } } for ( size_t i = 0 ; i < N ; + + i ) { if ( ! ( code & ( 1ull < < i ) ) ) { indices [ pos + + ] = i ; } } HWY_ASSERT ( pos = = N ) ; for ( size_t i = 0 ; i < N ; + + i ) { printf ( " % d " static_cast < int > ( indices [ i ] ) ) ; } } printf ( " \ n " ) ; } void PrintCompress64x4PairTables ( ) { printf ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 64x4 u32 index \ n " ) ; constexpr size_t N = 4 ; for ( uint64_t code = 0 ; code < ( 1ull < < N ) ; + + code ) { const size_t count = PopCount ( code ) ; std : : array < size_t N > indices { 0 } ; size_t pos = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { if ( code & ( 1ull < < i ) ) { indices [ pos + + ] = i ; } } for ( size_t i = 0 ; i < N ; + + i ) { if ( ! ( code & ( 1ull < < i ) ) ) { indices [ pos + + ] = i ; } } HWY_ASSERT ( pos = = N ) ; for ( size_t i = 0 ; i < N ; + + i ) { const int first_n_bit = i < count ? 8 : 0 ; const int low = static_cast < int > ( 2 * indices [ i ] ) + first_n_bit ; HWY_ASSERT ( low < 0x10 ) ; printf ( " % d % d " low low + 1 ) ; } } printf ( " \ n " ) ; } void PrintCompressNot64x4PairTables ( ) { printf ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = Not 64x4 u32 index \ n " ) ; constexpr size_t N = 4 ; for ( uint64_t not_code = 0 ; not_code < ( 1ull < < N ) ; + + not_code ) { const uint64_t code = ~ not_code ; const size_t count = PopCount ( code ) ; std : : array < size_t N > indices { 0 } ; size_t pos = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { if ( code & ( 1ull < < i ) ) { indices [ pos + + ] = i ; } } for ( size_t i = 0 ; i < N ; + + i ) { if ( ! ( code & ( 1ull < < i ) ) ) { indices [ pos + + ] = i ; } } HWY_ASSERT ( pos = = N ) ; for ( size_t i = 0 ; i < N ; + + i ) { const int first_n_bit = i < count ? 8 : 0 ; const int low = static_cast < int > ( 2 * indices [ i ] ) + first_n_bit ; HWY_ASSERT ( low < 0x10 ) ; printf ( " % d % d " low low + 1 ) ; } } printf ( " \ n " ) ; } void PrintCompress32x4Tables ( ) { printf ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 32x4 \ n " ) ; using T = uint32_t ; constexpr size_t N = 4 ; for ( uint64_t code = 0 ; code < ( 1ull < < N ) ; + + code ) { std : : array < uint32_t N > indices { 0 } ; size_t pos = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { if ( code & ( 1ull < < i ) ) { indices [ pos + + ] = i ; } } for ( size_t i = 0 ; i < N ; + + i ) { if ( ! ( code & ( 1ull < < i ) ) ) { indices [ pos + + ] = i ; } } HWY_ASSERT ( pos = = N ) ; for ( size_t i = 0 ; i < N ; + + i ) { for ( size_t idx_byte = 0 ; idx_byte < sizeof ( T ) ; + + idx_byte ) { printf ( " % d " static_cast < int > ( sizeof ( T ) * indices [ i ] + idx_byte ) ) ; } } } printf ( " \ n " ) ; } void PrintCompressNot32x4Tables ( ) { printf ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = Not 32x4 \ n " ) ; using T = uint32_t ; constexpr size_t N = 4 ; for ( uint64_t not_code = 0 ; not_code < ( 1ull < < N ) ; + + not_code ) { const uint64_t code = ~ not_code ; std : : array < uint32_t N > indices { 0 } ; size_t pos = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { if ( code & ( 1ull < < i ) ) { indices [ pos + + ] = i ; } } for ( size_t i = 0 ; i < N ; + + i ) { if ( ! ( code & ( 1ull < < i ) ) ) { indices [ pos + + ] = i ; } } HWY_ASSERT ( pos = = N ) ; for ( size_t i = 0 ; i < N ; + + i ) { for ( size_t idx_byte = 0 ; idx_byte < sizeof ( T ) ; + + idx_byte ) { printf ( " % d " static_cast < int > ( sizeof ( T ) * indices [ i ] + idx_byte ) ) ; } } } printf ( " \ n " ) ; } void PrintCompress64x2Tables ( ) { printf ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 64x2 \ n " ) ; using T = uint64_t ; constexpr size_t N = 2 ; for ( uint64_t code = 0 ; code < ( 1ull < < N ) ; + + code ) { std : : array < uint32_t N > indices { 0 } ; size_t pos = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { if ( code & ( 1ull < < i ) ) { indices [ pos + + ] = i ; } } for ( size_t i = 0 ; i < N ; + + i ) { if ( ! ( code & ( 1ull < < i ) ) ) { indices [ pos + + ] = i ; } } HWY_ASSERT ( pos = = N ) ; for ( size_t i = 0 ; i < N ; + + i ) { for ( size_t idx_byte = 0 ; idx_byte < sizeof ( T ) ; + + idx_byte ) { printf ( " % d " static_cast < int > ( sizeof ( T ) * indices [ i ] + idx_byte ) ) ; } } } printf ( " \ n " ) ; } void PrintCompressNot64x2Tables ( ) { printf ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = Not 64x2 \ n " ) ; using T = uint64_t ; constexpr size_t N = 2 ; for ( uint64_t not_code = 0 ; not_code < ( 1ull < < N ) ; + + not_code ) { const uint64_t code = ~ not_code ; std : : array < uint32_t N > indices { 0 } ; size_t pos = 0 ; for ( size_t i = 0 ; i < N ; + + i ) { if ( code & ( 1ull < < i ) ) { indices [ pos + + ] = i ; } } for ( size_t i = 0 ; i < N ; + + i ) { if ( ! ( code & ( 1ull < < i ) ) ) { indices [ pos + + ] = i ; } } HWY_ASSERT ( pos = = N ) ; for ( size_t i = 0 ; i < N ; + + i ) { for ( size_t idx_byte = 0 ; idx_byte < sizeof ( T ) ; + + idx_byte ) { printf ( " % d " static_cast < int > ( sizeof ( T ) * indices [ i ] + idx_byte ) ) ; } } } printf ( " \ n " ) ; } } HWY_NOINLINE void PrintTables ( ) { # if HWY_TARGET = = HWY_STATIC_TARGET detail : : PrintCompress32x8Tables ( ) ; detail : : PrintCompressNot32x8Tables ( ) ; detail : : PrintCompress64x4NibbleTables ( ) ; detail : : PrintCompressNot64x4NibbleTables ( ) ; detail : : PrintCompressNot64x2NibbleTables ( ) ; detail : : PrintCompress64x4Tables ( ) ; detail : : PrintCompressNot64x4Tables ( ) ; detail : : PrintCompress32x4Tables ( ) ; detail : : PrintCompressNot32x4Tables ( ) ; detail : : PrintCompress64x2Tables ( ) ; detail : : PrintCompressNot64x2Tables ( ) ; detail : : PrintCompress64x4PairTables ( ) ; detail : : PrintCompressNot64x4PairTables ( ) ; detail : : PrintCompress16x8Tables ( ) ; detail : : PrintCompress8x8Tables ( ) ; detail : : PrintCompressNot16x8Tables ( ) ; # endif } # endif } } HWY_AFTER_NAMESPACE ( ) ; # if HWY_ONCE namespace hwy { HWY_BEFORE_TEST ( HwyCompressTest ) ; # if HWY_PRINT_TABLES HWY_EXPORT_AND_TEST_P ( HwyCompressTest PrintTables ) ; # else HWY_EXPORT_AND_TEST_P ( HwyCompressTest TestAllCompress ) ; HWY_EXPORT_AND_TEST_P ( HwyCompressTest TestAllCompressBlocks ) ; # endif } # endif
e68018f06b6d5ed5bca0da4be7839e84f88c7673
7dd7c2bc755c9b7a94d2c1deac5a121a58fedba6
/MazeTest/MazeTest/BombedWall.h
633134666318b829e6bc8958d7488594eb405482
[]
no_license
wizardeye/DP
2ada6afcd33bc2b7bfc929d84c5ee593e0bc027d
7584919e1724a529b557637a41e67c33b8f03d08
refs/heads/master
2021-09-14T05:55:51.793000
2018-05-09T00:34:53
2018-05-09T00:34:53
120,073,638
0
0
null
null
null
null
UTF-8
C++
false
false
544
h
BombedWall.h
// // BombedWall.h // MazeTest // // Created by air seok on 2018. 2. 5.. // Copyright © 2018년 seok ki. All rights reserved. // #ifndef BombedWall_h #define BombedWall_h #include "Wall.h" class BombedWall: public Wall { public: BombedWall(): Wall() {} BombedWall(const BombedWall& other): Wall(other) { _bomb = other._bomb; } virtual Wall* Clone() const; bool hasBomb(); private: bool _bomb; }; Wall* BombedWall::Clone() const { return new BombedWall(*this); } #endif /* BombedWall_h */
4933a45d1480b3240b158e88c463216d1d86d184
15d4bc5b838d54f42e43367da1cf8ad484370ef0
/include/yarrr/inventory.hpp
65cad501bc31f77e84d85332556c5ad7ef89c0f6
[]
no_license
PeterHajdu/libyarrr
f5e9324704b03f156cb445cc8d6729f536044edc
4625b4f784da4b2dfdb036ed91d3b7c300be3890
refs/heads/master
2021-05-04T12:52:47.940000
2015-05-19T09:23:10
2015-05-19T09:23:10
120,302,008
0
0
null
null
null
null
UTF-8
C++
false
false
491
hpp
inventory.hpp
#pragma once #include <yarrr/object.hpp> #include <yarrr/item.hpp> #include <vector> namespace yarrr { class Inventory : public ObjectBehavior { public: add_polymorphic_ctci( "yarrr_inventory" ); Inventory(); Inventory( const Id& id ); virtual Pointer clone() const override; void register_item( Item& ); typedef std::vector< std::reference_wrapper< Item > > ItemContainer; const ItemContainer& items() const; private: ItemContainer m_items; }; }
067b232ac57028c7b073137127f4aee1f9d7e78c
0ad1ae62f8c58d52436c10754551a5e6166aab8e
/src/driver/base/client.hpp
92e4ddd12d5943ffd47fcac94db69fe836790362
[ "Apache-2.0" ]
permissive
shrayolacrayon/mongo-cxx-driver
2145e42d7edc4e4ae7884d065523fa16b6705603
16762309288814f287dc12e96a587279e79c84f3
refs/heads/master
2021-05-28T10:47:41.236000
2014-12-08T15:16:08
2014-12-08T15:16:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,441
hpp
client.hpp
// Copyright 2014 MongoDB Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "driver/config/prelude.hpp" #include <memory> #include "driver/base/database.hpp" #include "driver/base/read_preference.hpp" #include "driver/base/uri.hpp" #include "driver/base/write_concern.hpp" #include "driver/options/client.hpp" namespace mongo { namespace driver { class settings; /// The client class is the entry point into the MongoDB driver. It acts as a logical gateway for /// accessing the databases of MongoDB clusters. Databases that are accessed via a client inherit /// all of the options specified on the client. class LIBMONGOCXX_EXPORT client { // TODO: iterable for databases on the server // TODO: add + implement client api methods public: client( const uri& mongodb_uri = uri(), const options::client& options = options::client() ); client(client&& rhs) noexcept; client& operator=(client&& rhs) noexcept; ~client(); // TODO: document that modifications at this level do not affect existing clients + databases void read_preference(class read_preference rp); class read_preference read_preference() const; // TODO: document that modifications at this level do not affect existing clients + databases void write_concern(class write_concern wc); const class write_concern& write_concern() const; class database database(const std::string& name) const &; class database database(const std::string& name) const && = delete; inline class database operator[](const std::string& name) const; private: friend class database; friend class collection; class impl; std::unique_ptr<impl> _impl; }; // class client inline class database client::operator[](const std::string& name) const { return database(name); } } // namespace driver } // namespace mongo #include "driver/config/postlude.hpp"
3e9390b6c53bfd01755ccfbda78bfcb61b66816a
2eaf198cab76506045fcc4d312abd12afc9fc713
/src/ripple/app/tx/impl/AMMCreate.cpp
0c6874953a34c1f5fce882030ddf9ec5e3464579
[ "LicenseRef-scancode-free-unknown", "ISC" ]
permissive
XRPLF/rippled
26c378a72f65dde2ee9427a8a106505a60a3303d
300b7e078a4bc511f30b74509d416e5081ec3650
refs/heads/develop
2023-08-31T00:07:03.935000
2023-08-21T23:22:59
2023-08-21T23:23:06
2,724,167
267
126
ISC
2023-09-14T21:57:05
2011-11-07T04:40:15
C++
UTF-8
C++
false
false
12,353
cpp
AMMCreate.cpp
//------------------------------------------------------------------------------ /* This file is part of rippled: https://github.com/ripple/rippled Copyright (c) 2023 Ripple Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #include <ripple/app/tx/impl/AMMCreate.h> #include <ripple/app/ledger/OrderBookDB.h> #include <ripple/app/misc/AMMHelpers.h> #include <ripple/app/misc/AMMUtils.h> #include <ripple/ledger/Sandbox.h> #include <ripple/ledger/View.h> #include <ripple/protocol/AMMCore.h> #include <ripple/protocol/Feature.h> #include <ripple/protocol/STAccount.h> #include <ripple/protocol/STIssue.h> #include <ripple/protocol/TxFlags.h> namespace ripple { NotTEC AMMCreate::preflight(PreflightContext const& ctx) { if (!ammEnabled(ctx.rules)) return temDISABLED; if (auto const ret = preflight1(ctx); !isTesSuccess(ret)) return ret; if (ctx.tx.getFlags() & tfUniversalMask) { JLOG(ctx.j.debug()) << "AMM Instance: invalid flags."; return temINVALID_FLAG; } auto const amount = ctx.tx[sfAmount]; auto const amount2 = ctx.tx[sfAmount2]; if (amount.issue() == amount2.issue()) { JLOG(ctx.j.debug()) << "AMM Instance: tokens can not have the same currency/issuer."; return temBAD_AMM_TOKENS; } if (auto const err = invalidAMMAmount(amount)) { JLOG(ctx.j.debug()) << "AMM Instance: invalid asset1 amount."; return err; } if (auto const err = invalidAMMAmount(amount2)) { JLOG(ctx.j.debug()) << "AMM Instance: invalid asset2 amount."; return err; } if (ctx.tx[sfTradingFee] > TRADING_FEE_THRESHOLD) { JLOG(ctx.j.debug()) << "AMM Instance: invalid trading fee."; return temBAD_FEE; } return preflight2(ctx); } XRPAmount AMMCreate::calculateBaseFee(ReadView const& view, STTx const& tx) { // The fee required for AMMCreate is one owner reserve. return view.fees().increment; } TER AMMCreate::preclaim(PreclaimContext const& ctx) { auto const accountID = ctx.tx[sfAccount]; auto const amount = ctx.tx[sfAmount]; auto const amount2 = ctx.tx[sfAmount2]; // Check if AMM already exists for the token pair if (auto const ammKeylet = keylet::amm(amount.issue(), amount2.issue()); ctx.view.read(ammKeylet)) { JLOG(ctx.j.debug()) << "AMM Instance: ltAMM already exists."; return tecDUPLICATE; } if (auto const ter = requireAuth(ctx.view, amount.issue(), accountID); ter != tesSUCCESS) { JLOG(ctx.j.debug()) << "AMM Instance: account is not authorized, " << amount.issue(); return ter; } if (auto const ter = requireAuth(ctx.view, amount2.issue(), accountID); ter != tesSUCCESS) { JLOG(ctx.j.debug()) << "AMM Instance: account is not authorized, " << amount2.issue(); return ter; } // Globally or individually frozen if (isFrozen(ctx.view, accountID, amount.issue()) || isFrozen(ctx.view, accountID, amount2.issue())) { JLOG(ctx.j.debug()) << "AMM Instance: involves frozen asset."; return tecFROZEN; } auto noDefaultRipple = [](ReadView const& view, Issue const& issue) { if (isXRP(issue)) return false; if (auto const issuerAccount = view.read(keylet::account(issue.account))) return (issuerAccount->getFlags() & lsfDefaultRipple) == 0; return false; }; if (noDefaultRipple(ctx.view, amount.issue()) || noDefaultRipple(ctx.view, amount2.issue())) { JLOG(ctx.j.debug()) << "AMM Instance: DefaultRipple not set"; return terNO_RIPPLE; } // Check the reserve for LPToken trustline STAmount const xrpBalance = xrpLiquid(ctx.view, accountID, 1, ctx.j); // Insufficient reserve if (xrpBalance <= beast::zero) { JLOG(ctx.j.debug()) << "AMM Instance: insufficient reserves"; return tecINSUF_RESERVE_LINE; } auto insufficientBalance = [&](STAmount const& asset) { if (isXRP(asset)) return xrpBalance < asset; return accountID != asset.issue().account && accountHolds( ctx.view, accountID, asset.issue(), FreezeHandling::fhZERO_IF_FROZEN, ctx.j) < asset; }; if (insufficientBalance(amount) || insufficientBalance(amount2)) { JLOG(ctx.j.debug()) << "AMM Instance: insufficient funds, " << amount << " " << amount2; return tecUNFUNDED_AMM; } auto isLPToken = [&](STAmount const& amount) -> bool { if (auto const sle = ctx.view.read(keylet::account(amount.issue().account))) return sle->isFieldPresent(sfAMMID); return false; }; if (isLPToken(amount) || isLPToken(amount2)) { JLOG(ctx.j.debug()) << "AMM Instance: can't create with LPTokens " << amount << " " << amount2; return tecAMM_INVALID_TOKENS; } // Disallow AMM if the issuer has clawback enabled auto clawbackDisabled = [&](Issue const& issue) -> TER { if (isXRP(issue)) return tesSUCCESS; if (auto const sle = ctx.view.read(keylet::account(issue.account)); !sle) return tecINTERNAL; else if (sle->getFlags() & lsfAllowTrustLineClawback) return tecNO_PERMISSION; return tesSUCCESS; }; if (auto const ter = clawbackDisabled(amount.issue()); ter != tesSUCCESS) return ter; return clawbackDisabled(amount2.issue()); } static std::pair<TER, bool> applyCreate( ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Journal j_) { auto const amount = ctx_.tx[sfAmount]; auto const amount2 = ctx_.tx[sfAmount2]; auto const ammKeylet = keylet::amm(amount.issue(), amount2.issue()); // Mitigate same account exists possibility auto const ammAccount = [&]() -> Expected<AccountID, TER> { std::uint16_t constexpr maxAccountAttempts = 256; for (auto p = 0; p < maxAccountAttempts; ++p) { auto const ammAccount = ammAccountID(p, sb.info().parentHash, ammKeylet.key); if (!sb.read(keylet::account(ammAccount))) return ammAccount; } return Unexpected(tecDUPLICATE); }(); // AMM account already exists (should not happen) if (!ammAccount) { JLOG(j_.error()) << "AMM Instance: AMM already exists."; return {ammAccount.error(), false}; } // LP Token already exists. (should not happen) auto const lptIss = ammLPTIssue( amount.issue().currency, amount2.issue().currency, *ammAccount); if (sb.read(keylet::line(*ammAccount, lptIss))) { JLOG(j_.error()) << "AMM Instance: LP Token already exists."; return {tecDUPLICATE, false}; } // Create AMM Root Account. auto sleAMMRoot = std::make_shared<SLE>(keylet::account(*ammAccount)); sleAMMRoot->setAccountID(sfAccount, *ammAccount); sleAMMRoot->setFieldAmount(sfBalance, STAmount{}); std::uint32_t const seqno{ ctx_.view().rules().enabled(featureDeletableAccounts) ? ctx_.view().seq() : 1}; sleAMMRoot->setFieldU32(sfSequence, seqno); // Ignore reserves requirement, disable the master key, allow default // rippling (AMM LPToken can be used as a token in another AMM, which must // support payments and offer crossing), and enable deposit authorization to // prevent payments into AMM. // Note, that the trustlines created by AMM have 0 credit limit. // This prevents shifting the balance between accounts via AMM, // or sending unsolicited LPTokens. This is a desired behavior. // A user can only receive LPTokens through affirmative action - // either an AMMDeposit, TrustSet, crossing an offer, etc. sleAMMRoot->setFieldU32( sfFlags, lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth); // Link the root account and AMM object sleAMMRoot->setFieldH256(sfAMMID, ammKeylet.key); sb.insert(sleAMMRoot); // Calculate initial LPT balance. auto const lpTokens = ammLPTokens(amount, amount2, lptIss); // Create ltAMM auto ammSle = std::make_shared<SLE>(ammKeylet); ammSle->setAccountID(sfAccount, *ammAccount); ammSle->setFieldAmount(sfLPTokenBalance, lpTokens); auto const& [issue1, issue2] = std::minmax(amount.issue(), amount2.issue()); ammSle->setFieldIssue(sfAsset, STIssue{sfAsset, issue1}); ammSle->setFieldIssue(sfAsset2, STIssue{sfAsset2, issue2}); // AMM creator gets the auction slot and the voting slot. initializeFeeAuctionVote( ctx_.view(), ammSle, account_, lptIss, ctx_.tx[sfTradingFee]); sb.insert(ammSle); // Send LPT to LP. auto res = accountSend(sb, *ammAccount, account_, lpTokens, ctx_.journal); if (res != tesSUCCESS) { JLOG(j_.debug()) << "AMM Instance: failed to send LPT " << lpTokens; return {res, false}; } auto sendAndTrustSet = [&](STAmount const& amount) -> TER { if (auto const res = accountSend( sb, account_, *ammAccount, amount, ctx_.journal, WaiveTransferFee::Yes)) return res; // Set AMM flag on AMM trustline if (!isXRP(amount)) { if (SLE::pointer sleRippleState = sb.peek(keylet::line(*ammAccount, amount.issue())); !sleRippleState) return tecINTERNAL; else { auto const flags = sleRippleState->getFlags(); sleRippleState->setFieldU32(sfFlags, flags | lsfAMMNode); sb.update(sleRippleState); } } return tesSUCCESS; }; // Send asset1. res = sendAndTrustSet(amount); if (res != tesSUCCESS) { JLOG(j_.debug()) << "AMM Instance: failed to send " << amount; return {res, false}; } // Send asset2. res = sendAndTrustSet(amount2); if (res != tesSUCCESS) { JLOG(j_.debug()) << "AMM Instance: failed to send " << amount2; return {res, false}; } JLOG(j_.debug()) << "AMM Instance: success " << *ammAccount << " " << ammKeylet.key << " " << lpTokens << " " << amount << " " << amount2; auto addOrderBook = [&](Issue const& issueIn, Issue const& issueOut, std::uint64_t uRate) { Book const book{issueIn, issueOut}; auto const dir = keylet::quality(keylet::book(book), uRate); if (auto const bookExisted = static_cast<bool>(sb.read(dir)); !bookExisted) ctx_.app.getOrderBookDB().addOrderBook(book); }; addOrderBook(amount.issue(), amount2.issue(), getRate(amount2, amount)); addOrderBook(amount2.issue(), amount.issue(), getRate(amount, amount2)); return {res, res == tesSUCCESS}; } TER AMMCreate::doApply() { // This is the ledger view that we work against. Transactions are applied // as we go on processing transactions. Sandbox sb(&ctx_.view()); auto const result = applyCreate(ctx_, sb, account_, j_); if (result.second) sb.apply(ctx_.rawView()); return result.first; } } // namespace ripple
1ad665b2f853805c09589a540e555ec0bdaad341
850da8bdc25f529e49264753242e0a94bf97eb2d
/TConfigFile.cpp
80b938cd61ff99cdffdaab936480411a080f3976
[]
no_license
marcoafo/SupportCPP
8d34bade585eefdde69bd42a1a5b0579a18ed263
9910b2107cafcfa41bd7ffda89ccf176b513ddb4
refs/heads/master
2021-01-23T17:30:28.162000
2015-04-02T00:02:30
2015-04-02T00:02:30
33,277,673
0
0
null
null
null
null
ISO-8859-2
C++
false
false
3,419
cpp
TConfigFile.cpp
#include <fstream> #include "TConfigFile.h" //--------------------------------------------------------------------------- /*! * \brief Remove escape characters (\r, \n e \t) from both sides of a string. * \param Expression String to be trimmed (from both sides). * \return Return the string without escape characters in both sides. * \sa Friends repository. */ std::string TConfigFile::Trim(const char* Expression) { std::string text = Expression; char const* delims = " \t\r\n"; // escape chars std::string::size_type corte = text.find_first_not_of(delims); text.erase(0,corte); corte = text.find_last_not_of(delims); text.erase(corte+1); return text; } //--------------------------------------------------------------------------- /*! * \brief Class constructor. */ TConfigFile::TConfigFile() { } /*! * \brief Class copy constructor. * \param Copy Reference of the origin object, from which the members properties will be copied to newly created object. */ TConfigFile::TConfigFile(const TConfigFile &Copy) { Parameters = Copy.Parameters; } /*! * \brief Class destructor. */ TConfigFile::~TConfigFile() { } //--------------------------------------------------------------------------- /*! * \brief Copy (assign) operator. * \param Copy Reference to the object from which the members properties will be copied. * \return Self-reference to the object, to allow child-inheritance. */ const TConfigFile& TConfigFile::operator = (const TConfigFile &Copy) { Parameters = Copy.Parameters; return *this; } //--------------------------------------------------------------------------- /*! * \brief Read a configuration file and parse the variables to this class, cleaning its container first. * \param ConfigFile File name (may include full pathname) to the configuration file to be parsed. * \return True if parsed the file successfully, false if it couldn't open the file (no error message will be thrown). */ bool TConfigFile::ReadFile(const char* ConfigFile) { std::fstream file; file.open(ConfigFile,std::fstream::in); if(!file.is_open()) return false; Parameters.clear(); while(!file.eof()) { std::string line; getline(file,line); line = Trim(line.c_str()); if(line.empty()) continue; // line em branco if(line.substr(0,1) == "#") continue; // comentário std::string::size_type pos = 0; if((pos = line.find("=",pos)) == std::string::npos) continue; // line inválida std::string param,val; param = Trim(line.substr(0,pos).c_str()); val = Trim(line.substr(pos+1).c_str()); Parameters.insert( std::pair<std::string,std::string>(param,val) ); } file.close(); return true; } /*! * \brief Write the parameters and their values in a standard way to a output file. * \param ConfigFile File name (may include full pathname) to the configuration file to be written. * \return True if wrote the configuration file, false if it couldn't open the file for output (no error message will be thrown). */ bool TConfigFile::WriteFile(const char* ConfigFile) { std::fstream file; file.open(ConfigFile,std::fstream::out); if(!file.is_open()) return false; for(std::multimap<std::string,std::string>::iterator it = Parameters.begin(); it != Parameters.end(); it++) { file << it->first << " = " << it->second << std::endl; } file.close(); return true; }
3f0227a0f456d05c92c84d6b7f7d634d9909f8b4
d508027427b9a11a6bab0722479ee8d7b7eda72b
/3rd/include/3dsmax2010sdk/IContainerManager.h
cced1ed7e6d9374d34e40b387b7fd546d24b7af1
[]
no_license
gaoyakun/atom3d
421bc029ee005f501e0adb6daed778662eb73bac
129adf3ceca175faa8acf715c05e3c8f099399fe
refs/heads/master
2021-01-10T18:28:50.562000
2019-12-06T13:17:00
2019-12-06T13:17:00
56,327,530
5
0
null
null
null
null
ISO-8859-1
C++
false
false
2,537
h
IContainerManager.h
/***************************************************************************** FILE: IContainerManager.h DESCRIPTION: Describes the interface for global container functionality. CREATED BY: Nicolas Léonard HISTORY: July 9th, 2008 Creation Copyright (c) 2008, All Rights Reserved. *****************************************************************************/ #ifndef __ICONTAINER_MANAGER__H #define __ICONTAINER_MANAGER__H #include "iFnPub.h" //! \brief The interface for global container functionality. /*! Operations on a specific container can be accessed through the container itself. \see IContainerObject */ class IContainerManager : public FPStaticInterface { public: //! \brief Create a container /*! \return the container node if successfully created */ /*! \remarks If created, the container node will be selected */ /*! \remarks The container node will be created at the average of the content nodes, or at the origin if the Tab is empty */ /*! \param[in] contentNodes - Nodes to be added as content of the container */ virtual INode* CreateContainer(INodeTab& contentNodes) = 0; //! \brief Inherit a container into the scene /*! \return the container node if a container was successfully inherited */ /*! \param[in] asset - The container asset representing the definition file to be used */ /*! \remarks If the asset is invalid, the user will be presented with a file dialog. */ virtual INode* CreateInheritedContainer(const MaxSDK::AssetManagement::AssetUser& asset) = 0; //! \brief Test if a node is in a container or not /*! \param[in] node - The node that we are testing to see if it is in a container */ /*! \return the container interface if the node is in a container */ virtual IContainerObject* IsInContainer(INode *node) = 0; //! \brief Test if a node is a container or not /*! \param[in] node - The node that we are testing to see if it is a container */ /*! \return the container interface if the node is a container */ virtual IContainerObject* IsContainerNode(INode *node) = 0; // Function IDs for function publishing enum { IMPORT_CONTAINER_ID, CREATE_CONTAINER_ID, IS_IN_CONTAINER_ID, IS_CONTAINER_NODE_ID, }; }; //! \brief IContainerManager interface ID #define IID_IContainerManager Interface_ID(0xD951AEE9, 0x5769E48B) //! \brief Returns the container manager interface inline IContainerManager* GetContainerManagerInterface() { return static_cast<IContainerManager*>(GetCOREInterface(IID_IContainerManager)); } #endif __ICONTAINER_MANAGER__H
0d3d554da08a931c084700464608070f96b434a1
d29af0b8935a3690c00dcb7d81c8dbfdb71ecef2
/src/ui/wxWidgets/ComparisonGridTable.h
cb8724d61f48ff29fafe107038aaa890239b45d1
[ "Artistic-2.0", "MIT" ]
permissive
pwsafe/pwsafe
fde24362cb54f1266feb83348e880f65a90b5ff9
0a4a8870b040eebed63907be6fbf2222fef096b3
refs/heads/master
2023-08-08T17:14:38.584000
2023-07-17T00:12:48
2023-08-07T09:32:17
40,989,540
713
197
NOASSERTION
2023-09-06T12:44:11
2015-08-18T18:16:11
C++
UTF-8
C++
false
false
4,984
h
ComparisonGridTable.h
/* * Copyright (c) 2003-2023 Rony Shapiro <ronys@pwsafe.org>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ /** \file ComparisonGridTable.h * */ #ifndef _COMPARISONGRIDTABLE_H_ #define _COMPARISONGRIDTABLE_H_ #include <wx/grid.h> #include "../../core/DBCompareData.h" #include "../../core/UIinterface.h" // #define CurrentBackgroundColor *wxWHITE #if wxVERSION_NUMBER >= 3103 #define CurrentBackgroundColor (wxSystemSettings::GetAppearance().IsUsingDarkBackground() ? wxColor(29, 30, 32) : *wxWHITE) #else #define CurrentBackgroundColor (*wxWHITE) #endif #define ComparisonBackgroundColor *wxWHITE struct SelectionCriteria; class PWScore; class ComparisonGrid : public wxGrid { public: ComparisonGrid(wxWindow* parent, wxWindowID id); wxPen GetRowGridLinePen(int row); bool IsRowSelected(int row) const; // Make sure the two rows holding corresponding items from current and comparison db are // always selected together void OnGridRangeSelect(wxGridRangeSelectEvent& evt); void OnAutoSelectGridRow(wxCommandEvent& evt); DECLARE_EVENT_TABLE() }; class ComparisonGridTable: public wxGridTableBase { public: ComparisonGridTable(SelectionCriteria* criteria); virtual ~ComparisonGridTable(); //virtual overrides int GetNumberCols(); void SetValue(int row, int col, const wxString& value); wxString GetColLabelValue(int col); //common to all derived classes void AutoSizeField(CItemData::FieldType ft); int FieldToColumn(CItemData::FieldType ft); CItemData::FieldType ColumnToField(int col); //derived classes must override these //should return wxNOT_FOUND on error virtual int GetItemRow(const pws_os::CUUID& uuid) const = 0; virtual pws_os::CUUID GetSelectedItemId(bool readOnly) = 0; virtual const st_CompareData& operator[](size_t index) const = 0; protected: SelectionCriteria* m_criteria; typedef bool (CItemData::*AvailableFunction)() const; typedef struct { CItemData::FieldType ft; AvailableFunction available; } ColumnData; ColumnData* m_colFields; //UIinterface overrides public: void RefreshRow(int row) const; }; /////////////////////////////////////////////////////////////// //UniSafeCompareGridTable // //Class to handle display of comparison results which only involve a single //safe (uses only a single core) class UniSafeCompareGridTable: public ComparisonGridTable { typedef pws_os::CUUID st_CompareData::*uuid_ptr; CompareData* m_compData; PWScore* m_core; wxGridCellAttr *m_gridAttr; uuid_ptr m_uuidptr; public: UniSafeCompareGridTable(SelectionCriteria* criteria, CompareData* data, PWScore* core, uuid_ptr pu, const wxColour& backgroundColour); virtual ~UniSafeCompareGridTable(); //virtual overrides int GetNumberRows(); bool IsEmptyCell(int row, int col); wxString GetValue(int row, int col); wxGridCellAttr* GetAttr(int row, int col, wxGridCellAttr::wxAttrKind kind); //virtual override from ComparisonGridTable int GetItemRow(const pws_os::CUUID& uuid) const; virtual pws_os::CUUID GetSelectedItemId(bool readOnly); virtual const st_CompareData& operator[](size_t index) const { return m_compData->at(index); } bool DeleteRows(size_t pos, size_t numRows); bool AppendRows(size_t numRows = 1); }; /////////////////////////////////////////////////////////////////// //MultiSafeCompareGridTable // //Class to handle display of comparison results which involve two //safes (uses both the cores in comparison result) class MultiSafeCompareGridTable: public ComparisonGridTable { CompareData* m_compData; PWScore* m_currentCore; PWScore* m_otherCore; wxGridCellAttr *m_currentAttr, *m_comparisonAttr; public: MultiSafeCompareGridTable(SelectionCriteria* criteria, CompareData* data, PWScore* current, PWScore* other); virtual ~MultiSafeCompareGridTable(); //virtual overrides int GetNumberRows(); bool IsEmptyCell(int row, int col); wxString GetValue(int row, int col); wxString GetRowLabelValue(int row); wxGridCellAttr* GetAttr(int row, int col, wxGridCellAttr::wxAttrKind kind); //virtual override from ComparisonGridTable int GetItemRow(const pws_os::CUUID& uuid) const; virtual pws_os::CUUID GetSelectedItemId(bool readOnly); virtual const st_CompareData& operator[](size_t index) const { return m_compData->at(index/2); } bool DeleteRows(size_t pos, size_t numRows); private: PWScore* GetRowCore(int row); }; #endif /* _COMPARISONGRIDTABLE_H_ */
ee3592f2807cc36259f459e12d02a37b1d95e9cf
32f5397d60e07cc75703ac3ebf40f251d7ef1614
/src/vulkan/VulkanContext.h
2033f842ebc764db0b3700f89dbc7f9d34a30bcf
[]
no_license
Denis-chen/OculusTest
17a4bd1d1fad4495ac855104617ab89fe3000da5
72eaf596f92d86caadb4179e21504dbd0dbc7684
refs/heads/master
2021-01-12T05:23:17.945000
2016-11-05T20:24:20
2016-11-05T20:24:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,148
h
VulkanContext.h
#pragma once #include <memory> #include "VulkanFwd.h" using namespace std; namespace vulkan { class VulkanContext //TODO: enumerate extensions, layers for device and instance { private: VkInstance instance; unique_ptr<VulkanDebug> debug; VkDevice device; VkPhysicalDevice physicalDevice; VkQueue queue; uint32_t queueFamilyIndex; VkCommandPool commandPool; void createInstance(); void createDevice(); VkPhysicalDevice getPhysicalDeviceFromVulkan(); uint32_t getQueueFamilyIndex(VkPhysicalDevice physicalDevice); uint32_t calculateMemoryTypeIndex(VkPhysicalDevice physicalDevice); public: VulkanContext(); void init(); VkInstance getInstance() { return instance; } VkDevice getDevice() { return device; } VkPhysicalDevice getPhysicalDevice() { return physicalDevice; } VkCommandPool getCommandPool() { return commandPool; } VkQueue getQueue() { return queue; } ~VulkanContext(); }; }
e9413307e1fca6741b622af5b43493692edacfda
2fd7255b5a0c34b00fc968bafd47fa46559cf24a
/VJUDGE/Daffodil Individual Rated Contest 2019-07-05/c.cpp
e3168fe8e134308a0812ab8d54891db1f3d69f2e
[]
no_license
bappi2097/ACM-Problem-Solving
61d7439ccead5f781aa209615f8abe4ef6cf5f43
c9d83dd0f0dbe9b5d666c932ead369287ac76651
refs/heads/master
2022-10-21T02:06:28.954000
2020-06-15T07:16:32
2020-06-15T07:16:32
271,226,280
3
0
null
null
null
null
UTF-8
C++
false
false
204
cpp
c.cpp
#include<bits/stdc++.h> using namespace std; int main() { int s,x; cin>>s>>x; int i=1; for(i=1;1;i++) { if(s/x==0)break; s/=x; } cout<<i<<endl; return 0; }
5c79fb870c3930a476d2e877c20aa1f18b323097
7bce4c933163d766c75099cbb90ae6b81158730a
/priority.cpp
85079233d356986466d0008b4cd9540677b99b01
[]
no_license
richaharish/everything
47debaaa354125462845bae6c285c89b45a08dd3
06c5b5ab92b2809eadcae58939b75736433ede93
refs/heads/master
2021-06-30T12:00:48.360000
2017-09-20T13:17:15
2017-09-20T13:17:15
104,182,134
1
0
null
null
null
null
UTF-8
C++
false
false
2,174
cpp
priority.cpp
#include<iostream> #include"schedule.h" //priority non preemptive using namespace std; int schedule::priority() { int index,index1; char stop='n' ; int i=0; while(stop == 'n') { cout<<"Enter the process id ,arrival time ,burst time and priority "<<endl; cin>>pid[i]; cin>>arrivaltime[i]; cin>>bursttime[i]; cin>>pri[i]; cout<<"Is this the last process y/n"<<endl; cin>>stop; i++; } int checker[i]={0}; //sorting the data for(int k=0;k<i-1;k++) { for(int j=0;j<i-1-k;j++) { if(arrivaltime[j]>arrivaltime[j+1]) { //for arrival time int temp= arrivaltime[j]; arrivaltime[j]=arrivaltime[j+1]; arrivaltime[j+1]=temp; //for burst time temp=bursttime[j]; bursttime[j]=bursttime[j+1]; bursttime[j+1]=temp; //for pid temp=pid[j]; pid[j]=pid[j+1]; pid[j+1]=temp; //for priority temp=pri[j]; pri[j]=pri[j+1]; pri[j+1]=temp; } } } for(int k=0;k<i;k++) { int min=100,max=0; for(int j=0;j<i;j++) { if((k==0)&&(checker[j]==0)&&(arrivaltime[j]<min)) { min=arrivaltime[j]; index1=j; } else if ((k!=0)&&(checker[j]==0)&&(pri[j]>max)) { max=pri[j]; index1=j; } } cout<<"max"<<max<<endl; cout<<"index"<<index1<<endl; checker[index1]=1; int CT; if(k==0) { completiontime[index1]=arrivaltime[index1]+bursttime[index1]; } else { completiontime[index1]=CT+bursttime[index1]; } TAT[index1]=completiontime[index1]-arrivaltime[index1]; waittime[index1]=TAT[index1]-bursttime[index1]; CT=completiontime[index1]; } return(i); }
0c030bcab2bbfe31d35292d7442f641020c98620
3e903c662c0237c9313f22b2760e9e4d71ac939c
/Ennemy.h
fa9b81579a489f03e0075552d5fca296d9977127
[]
no_license
amandaSalander/sylcraft
2998c449be8ba6abc35cf26977f67f0422e3b38e
e831c23d2247014d942ea54b303816821ac59100
refs/heads/master
2020-04-05T20:43:04.513000
2018-12-14T19:16:23
2018-12-14T19:16:23
157,192,717
0
0
null
null
null
null
UTF-8
C++
false
false
672
h
Ennemy.h
// // Created by amanda on 22/11/18. // #ifndef PROJECT_1_ENNEMY_H #define PROJECT_1_ENNEMY_H #include <fstream> #include "Element.h" class Ennemy : public Element{ private: int stamina; int attackEffect; int defenseEffect; int max_stamina; int margin_detection; int margin_attack; public: Ennemy(const std::string &type); int getStamina() const; int getAttackEffect() const; int getDefenseEffect() const; int getMax_stamina() const; void setStamina(int stamina); void setAttackEffect(int attackEffect); int getMargin_detection() const; int getMargin_attack() const; }; #endif //PROJECT_1_ENNEMY_H
22044fce7b82e448d527807702ef3865d3b8bfa3
9eab75ac8109b4cd6968718252cf949dd54ff8f4
/others/TLE1_1.cpp
6e48929312b4b8638c67d629993a593b41dbcee9
[]
no_license
tymefighter/CompetitiveProg
48131feca6498672c9d64787a27bea20597e5810
f867d53c6f1b307d8f2d323a315974b418abd48d
refs/heads/master
2021-06-09T14:09:16.186000
2021-05-17T14:17:14
2021-05-17T14:17:14
186,087,058
3
1
null
null
null
null
UTF-8
C++
false
false
2,560
cpp
TLE1_1.cpp
#include<iostream> #include<cstdio> #include<map> #include<vector> #include<string> #include<utility> using namespace std; class segmentTree { private: vector<int> seg, arr; int n; public: segmentTree(const vector<int> &a) { n = a.size(); arr = a; seg.resize(4*n); constructTree(a, 0, n-1, 0); } void constructTree(const vector<int> &a, int low, int high, int pos) { if(low == high) { seg[pos] = a[low]^1; return; } int mid = (low + high)/2; //cout<<low<<" "<<mid<<" "<<pos<<'\n'; constructTree(a, low, mid, 2*pos + 1); constructTree(a, mid+1, high, 2*pos + 2); seg[pos] = seg[2*pos+1]+seg[2*pos+2]; return; } int numZeros(const int &start,const int &end, int low, int high, int pos) { if(start > high || end < low) return 0; else if(start <= low && end >= high) return seg[pos]; else { int mid = (low + high)/2; return numZeros(start, end, low, mid, 2*pos + 1) + numZeros(start, end, mid+1, high, 2*pos + 2); } return 1; } void toggle(const int &p, int low, int high, int pos) { if(low == high) { //cout<<low<<" "<<p<<'\n'; arr[p] ^= 1; seg[pos] ^= 1; return; } int val, mid; mid = (low + high)/2; //cout<<low<<" "<<high<<'\n'; if(arr[p] == 0) seg[pos] -= 1; else seg[pos] += 1; if(p > mid) { toggle(p, mid+1, high, 2*pos+2); } else if(p <= mid) { toggle(p, low, mid, 2*pos+1); } return; } int occ(const int &k, int low, int high, int pos, int curr) { if(k > seg[0]) return -1; if(low == high) return low; //cout<<low<<" "<<high<<" "<<curr<<" "<<seg[2*pos+1]<<" "<<k<<'\n'; int mid = (low + high)/2; if(k > curr + seg[2*pos + 1]) return occ(k, mid+1, high, 2*pos+2, curr+seg[2*pos+1]); else return occ(k, low, mid, 2*pos+1, curr); } void printSegArray(void) { for(int i = 0;i < seg.size();i++) cout<<seg[i]<<" "; cout<<'\n'; } }; int main() { ios_base::sync_with_stdio(false); cout.tie(nullptr); cin.tie(nullptr); int n, q, i, p, k, start, end, type; vector<int> a; cin>>n>>q; a.resize(n); for(i = 0;i < n;i++) cin>>a[i]; segmentTree s(a); //s.printSegArray(); while(q--) { cin>>type; if(type == 1) { cin>>start>>end; cout<<s.numZeros(start, end, 0, n-1, 0)<<'\n'; } else if(type == 2) { cin>>p; s.toggle(p, 0, n-1, 0); //s.printSegArray(); } else if(type == 3) { cin>>k; cout<<s.occ(k, 0, n-1, 0, 0)<<'\n'; } } }
7ebc00a3ad9b2da54df14af7bb405cc47e1830a1
7e319798fef54d6e079948eee165feba883db5f0
/IOAble.h
34471f1e7cab4fabc0c20f1d3de00da3d835675f
[]
no_license
dharamoghariya/COVIDApplication
2a43cff47b6488ec40716803a17f4f368b8001c0
2ab6af1727d44418f1c681ed37b4e3cd023f2e24
refs/heads/master
2023-02-12T12:46:10.566000
2021-01-12T18:28:20
2021-01-12T18:28:20
328,865,986
0
0
null
null
null
null
UTF-8
C++
false
false
1,281
h
IOAble.h
/* Name: Dhara Moghariya Student Number: 161449194 Email: dmoghariya@myseneca.ca Section: NAA Date: November 15, 2020 ----------------------------------------------------------- Final Project Milestone 2 Module: IOAble Filename: IOAble.h Version 0.9 Revision History ----------------------------------------------------------- Date Reason 2020/11/15 Initial Implementation 2020/11/15 Testing and Debugging ----------------------------------------------------------- I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments. -----------------------------------------------------------*/ #ifndef SDDS_IOABLE_H_ #define SDDS_IOABLE_H_ #include <iostream> namespace sdds { class IOAble { public: // pure virtual functions virtual std::ostream& csvWrite(std::ostream& ostr) const = 0; virtual std::istream& csvRead(std::istream& istr) = 0; virtual std::ostream& write(std::ostream& ostr) const = 0; virtual std::istream& read(std::istream& istr) = 0; // an empty virtual destructor virtual ~IOAble() { } }; std::ostream& operator<<(std::ostream& ostr, const IOAble& IO); std::istream& operator>>(std::istream& istr, IOAble& IO); } #endif // !SDDS_IOABLE_H_
9019d2cc698aed3b33f87c9a02df41e1d10f500a
72bb6deb4a8657fc494777847e356c328fe8550d
/plane-ZJU-online/include/plane_segmentation.h
681940c92dbcb13ee207745afdda2928c879a3f8
[]
no_license
rising-turtle/study
daafeac486e274af47268e9c7d66feacd3476a44
76b414d0a47692f997539b34b356c34a3528f34d
refs/heads/master
2021-12-09T07:23:41.800000
2021-12-02T19:34:44
2021-12-02T19:34:44
90,572,871
2
0
null
null
null
null
GB18030
C++
false
false
1,550
h
plane_segmentation.h
# ifndef PLANE_SEGMENTATION_H_ #define PLANE_SEGMENTATION_H_ #include <vector> #include <Eigen/Dense> class PlaneSegmentation { private: public: PlaneSegmentation(); ~PlaneSegmentation(); inline void setAngularThreshold (double angularThreshold) { angularThreshold_ = angularThreshold; } inline void setDistanceThreshold (double distanceThreshold) { distanceThreshold_ = distanceThreshold; } inline void setPlaneThreshold (int minPlaneCount,double minPlaneArea) { minPlaneCount_ = minPlaneCount; minPlaneArea_ = minPlaneArea; } inline void setMaxVisDistance(double maxVisDistance) { maxVisDistance_=maxVisDistance; } //return the num of planes, classFlag sign the plane index the point belong to int segmentOrganized (float** cloud,float** normals,const int width,const int height,int classFlag[]); //get all planes' equition (a,b,c,d) a*x + b*y +c*z + d = 0 void gettPlaneModel(std::vector<double> modelEquition[4]); protected: double angularThreshold_; //拓展点与平面法向量夹角 double distanceThreshold_; //拓展点到平面的距离 int minPlaneCount_; //最少平面点数 double minPlaneArea_; //最小平面面积 double maxVisDistance_; //最远视距 //int downSample(double** dataIn,double** dataOut,const int width,const int height,const int downStep); struct PlaneModel { Eigen::Vector3d centroid; Eigen::Vector3d normal; }; std::vector<PlaneModel> planeVector_; }; #endif
9f4e104f6b8a4316ec044418ebf0530ebb913cff
de8315ca5cbc2afe96334134ef6de36dc5d8fe3d
/BA/BA.cpp
892165a79b38e6637ad0a8e3c76f3cd3249952eb
[]
no_license
toniortiz/RGBD-Mapping
ab071d335bdc44aeab3bf8cbbb92a3a545429a46
60206bebd4b1399210be0624e23e56320a24330c
refs/heads/master
2020-07-18T04:44:54.090000
2019-09-03T22:34:06
2019-09-03T22:34:06
206,177,899
1
0
null
null
null
null
UTF-8
C++
false
false
5,695
cpp
BA.cpp
#include "BA.h" #include "Core/Feature.h" #include "Core/Frame.h" #include "Core/PinholeCamera.h" #include <g2o/core/block_solver.h> #include <g2o/core/optimization_algorithm_levenberg.h> #include <g2o/core/robust_kernel_impl.h> #include <g2o/core/solver.h> #include <g2o/core/sparse_optimizer.h> #include <g2o/solvers/cholmod/linear_solver_cholmod.h> #include <g2o/solvers/csparse/linear_solver_csparse.h> #include <g2o/solvers/dense/linear_solver_dense.h> #include <g2o/solvers/structure_only/structure_only_solver.h> #include <g2o/types/sba/types_six_dof_expmap.h> using namespace std; void BA::twoFrameBA(FramePtr prevFrame, FramePtr curFrame, const vector<cv::DMatch>& matches, vector<cv::DMatch>& inlierMatches, SE3& T) { static const double deltaMono = sqrt(5.991); static const double deltaStereo = sqrt(7.815); double fx = prevFrame->_camera->fx(); double fy = prevFrame->_camera->fy(); double cx = prevFrame->_camera->cx(); double cy = prevFrame->_camera->cy(); double bf = prevFrame->_camera->baseLineFx(); g2o::SparseOptimizer optimizer; optimizer.setVerbose(false); // g2o::CameraParameters* cam_params = new g2o::CameraParameters(prevFrame->_camera->fx(), // Vec2(prevFrame->_camera->cx(), prevFrame->_camera->cy()), prevFrame->_camera->baseLine()); // cam_params->setId(0); // optimizer.addParameter(cam_params); g2o::BlockSolver_6_3::LinearSolverType* linearSolver; linearSolver = new g2o::LinearSolverCholmod<g2o::BlockSolver_6_3::PoseMatrixType>(); g2o::BlockSolver_6_3* solver_ptr = new g2o::BlockSolver_6_3(linearSolver); g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg(solver_ptr); optimizer.setAlgorithm(solver); g2o::VertexSE3Expmap* vSE3 = new g2o::VertexSE3Expmap(); vSE3->setEstimate(g2o::SE3Quat(Mat33::Identity(), Vec3::Zero())); vSE3->setFixed(false); vSE3->setId(0); optimizer.addVertex(vSE3); vector<bool> inliers(matches.size(), true); int good = 0; vector<g2o::EdgeSE3ProjectXYZOnlyPose*> edgesMono; edgesMono.reserve(matches.size()); vector<g2o::EdgeStereoSE3ProjectXYZOnlyPose*> edgesStereo; edgesStereo.reserve(matches.size()); for (size_t i = 0; i < matches.size(); i++) { const Vec3& prevXc = prevFrame->_features[matches[i].queryIdx]->_Xc; if (prevXc.isZero()) { inliers[i] = false; continue; } good++; FeaturePtr curFtr = curFrame->_features[matches[i].trainIdx]; if (curFtr->_right <= 0) { g2o::EdgeSE3ProjectXYZOnlyPose* edge = new g2o::EdgeSE3ProjectXYZOnlyPose(); edge->setVertex(0, dynamic_cast<g2o::OptimizableGraph::Vertex*>(optimizer.vertex(0))); edge->setMeasurement(curFtr->_uXi); double invSigma2 = curFrame->_invLevelSigma2[curFtr->_level]; edge->setInformation(Mat22::Identity() * invSigma2); edge->fx = fx; edge->fy = fy; edge->cx = cx; edge->cy = cy; edge->Xw = prevXc; g2o::RobustKernelHuber* kernel = new g2o::RobustKernelHuber(); kernel->setDelta(deltaMono); edge->setRobustKernel(kernel); optimizer.addEdge(edge); edge->setId(i); edgesMono.push_back(edge); } else { g2o::EdgeStereoSE3ProjectXYZOnlyPose* edge = new g2o::EdgeStereoSE3ProjectXYZOnlyPose(); edge->setVertex(0, dynamic_cast<g2o::OptimizableGraph::Vertex*>(optimizer.vertex(0))); Vec3 meas(curFtr->_uXi.x(), curFtr->_uXi.y(), curFtr->_right); edge->setMeasurement(meas); double invSigma2 = curFrame->_invLevelSigma2[curFtr->_level]; edge->setInformation(Mat33::Identity() * invSigma2); edge->fx = fx; edge->fy = fy; edge->cx = cx; edge->cy = cy; edge->bf = bf; edge->Xw = prevXc; g2o::RobustKernelHuber* kernel = new g2o::RobustKernelHuber(); kernel->setDelta(deltaStereo); edge->setRobustKernel(kernel); optimizer.addEdge(edge); edge->setId(i); edgesStereo.push_back(edge); } } for (size_t it = 0; it < 4; ++it) { optimizer.initializeOptimization(0); optimizer.optimize(10); for (g2o::EdgeSE3ProjectXYZOnlyPose* e : edgesMono) { if (!inliers[e->id()]) e->computeError(); if (e->chi2() > 5.991) { inliers[e->id()] = false; e->setLevel(1); good--; } else { inliers[e->id()] = true; e->setLevel(0); } if (it == 2) e->setRobustKernel(nullptr); } for (g2o::EdgeStereoSE3ProjectXYZOnlyPose* e : edgesStereo) { if (!inliers[e->id()]) e->computeError(); if (e->chi2() > 7.815) { inliers[e->id()] = false; e->setLevel(1); good--; } else { inliers[e->id()] = true; e->setLevel(0); } if (it == 2) e->setRobustKernel(nullptr); } if (good < 5) break; } for (size_t i = 0; i < inliers.size(); ++i) { if (inliers[i]) inlierMatches.push_back(matches[i]); } g2o::VertexSE3Expmap* recov = dynamic_cast<g2o::VertexSE3Expmap*>(optimizer.vertex(0)); g2o::SE3Quat q = recov->estimate(); T = SE3(q.rotation(), q.translation()); }
7da240b870e8ec4a21dc23fe637e5903e5694240
320e20dd92c0c9968f838c5ea201644598ff114c
/tools/lli/ChildTarget/Unix/ChildTarget.inc
67a24ece96526e23b8c1035ad34b208d0ce7e490
[ "NCSA" ]
permissive
big-tool-brewery/llvm
509262f3c97616844b7379105f2a66ccd70348bd
03b94a460d9cfd86e438cd88596d93c63fc3c3e0
refs/heads/master
2021-01-24T19:08:54.452000
2014-01-23T15:05:45
2014-01-23T15:05:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,366
inc
ChildTarget.inc
//===- ChildTarget.inc - Child process for external JIT execution for Unix -==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implementation of the Unix-specific parts of the ChildTarget class // which executes JITed code in a separate process from where it was built. // //===----------------------------------------------------------------------===// #include <stdio.h> #include <stdlib.h> #include <unistd.h> namespace { struct ConnectionData_t { int InputPipe; int OutputPipe; ConnectionData_t(int in, int out) : InputPipe(in), OutputPipe(out) {} }; } // namespace LLIChildTarget::~LLIChildTarget() { delete static_cast<ConnectionData_t *>(ConnectionData); } // OS-specific methods void LLIChildTarget::initializeConnection() { // Store the parent ends of the pipes ConnectionData = (void*)new ConnectionData_t(STDIN_FILENO, STDOUT_FILENO); } int LLIChildTarget::WriteBytes(const void *Data, size_t Size) { return write(((ConnectionData_t*)ConnectionData)->OutputPipe, Data, Size); } int LLIChildTarget::ReadBytes(void *Data, size_t Size) { return read(((ConnectionData_t*)ConnectionData)->InputPipe, Data, Size); }
a95f6b4dcbc1fdeed0eeaac7e4105b4c3aec2f58
50dd5445581091995ce4a5b7c1887a234e84393a
/fluffelwatch/mainwindow.cpp
f1e69be514f85321d286e5cbd587d1d3e688028e
[ "MIT" ]
permissive
Schallaven/fluffelwatch
5fe0e7f7d9a2148c9469bc0c4b757ba615067f69
3bbf909c9482d6f83281193aa858da3a0dc88bd6
refs/heads/main
2023-03-14T12:00:54.102000
2021-03-07T00:02:40
2021-03-07T00:02:40
308,924,940
0
0
null
null
null
null
UTF-8
C++
false
false
23,759
cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { /* Setup UI with a border less window and an action context menu */ ui->setupUi(this); setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); setupContextMenu(); setupGlobalShortcuts(); /* Read in settings from an conf-file */ settings = new QSettings("fluffelwatch.conf", QSettings::NativeFormat); readSettings(); /* Calculate the region and window size */ calculateRegionSizes(); /* Start timer every 10 msec (can do faster timers, but it costs CPU load!) */ timerID = startTimer(10, Qt::PreciseTimer); /* Start the thread for managing IPC to allow external programs to * change section number and iconstates */ ipcthread.start(); } MainWindow::~MainWindow() { /* Request exit of the thread and give it some time to exit */ ipcthread.requestInterruption(); QThread::msleep(ipcthread.timeout * 2); /* Kill the timer we started */ killTimer(timerID); /* Destroy everything */ delete ui; } void MainWindow::mousePressEvent(QMouseEvent* event) { /* Start moving the window with the left mouse button; this avoids accidently moving * the window when accesing the context menu. */ if (event->button() == Qt::LeftButton) { isMoving = true; movingStartPos = event->pos(); } } void MainWindow::mouseMoveEvent(QMouseEvent* event) { /* Moving the window: Calculating the difference between the current position of the * mouse and the starting position. Then add this to the window position (top-left) * corner to move the window the same distance/direction. */ if (isMoving) { QPoint diffPos = event->pos() - movingStartPos; window()->move(window()->pos() + diffPos); } } void MainWindow::mouseReleaseEvent(QMouseEvent* event) { Q_UNUSED(event) /* Stop moving in any case */ isMoving = false; } void MainWindow::paintEvent(QPaintEvent* event) { Q_UNUSED(event) QMainWindow::paintEvent(event); QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); painter.testRenderHint(QPainter::TextAntialiasing); /* Fill background and draw all elements */ painter.setBrush(backgroundBrush); painter.drawRect(this->rect()); paintAllElements(painter); } void MainWindow::timerEvent(QTimerEvent* event) { Q_UNUSED(event) /* Process new information from thread if available */ if (ipcthread.dataChanged()) { /* Get the newest data */ FluffelIPCThread::listenerData tempData = ipcthread.getData(); /* Send icon states to the icon manager */ icons.setStates(tempData.iconstates); qDebug("New state: section = %d, states = 0x%08X, timercontrol = %d", tempData.section, tempData.iconstates, tempData.timercontrol); /* If the timers are NOT running yet, then only react to the autostart signal and only if the user wants that */ if (autostartstop && !timeControl.areBothTimerValid() && tempData.timercontrol == FluffelIPCThread::timeControlStart) { qDebug("Got start signal, resetting and starting both timers."); timeControl.resetBothTimer(); timeControl.restartBothTimer(); } /* If the timers are running and the user wants it, react to the autostop signal */ else if (autostartstop && timeControl.isAnyTimerRunning() && tempData.timercontrol == FluffelIPCThread::timeControlStop) { qDebug("Got stop signal. Stopping both timers and do a split."); timeControl.pauseBothTimer(); displaySegments.clear(); int remains = data.split(timeControl.elapsedPreferredTime()); int segments = data.getCurrentSegments(displaySegments, segmentLines); qDebug("Got %d segments from data object. %d remaining segments.", segments, remains); } /* Autosplits enabled, so split if the section number changes */ if (autosplit && (tempData.section > data.getCurrentSection())) { qDebug("Do an autosplit to section %d", tempData.section); displaySegments.clear(); int remains = data.splitToSection(tempData.section, timeControl.elapsedPreferredTime()); int segments = data.getCurrentSegments(displaySegments, segmentLines); qDebug("Got %d segments from data object. %d remaining segments.", segments, remains); } /* Pause the ingame timer whenever requested */ if (timeControl.areBothTimerValid() && timeControl.isIngameTimerRunning() && tempData.timercontrol == FluffelIPCThread::timeControlPause) { qDebug("Pausing ingame timer."); timeControl.pauseIngameTimer(); } /* Resume ingame timer whenever requested */ else if (timeControl.areBothTimerValid() && !timeControl.isIngameTimerRunning() && tempData.timercontrol == FluffelIPCThread::timeControlNone) { qDebug("Continuing ingame timer"); timeControl.resumeIngameTimer(); } } /* Update the display */ update(); } void MainWindow::onSplit() { /* If timers are not started yet, start them */ if (!timeControl.areBothTimerValid()) { qDebug("Start"); timeControl.startBothTimer(); return; } /* Otherwise, split the time here */ qDebug("Split"); displaySegments.clear(); int remains = data.split(timeControl.elapsedPreferredTime()); int segments = data.getCurrentSegments(displaySegments, segmentLines); qDebug("Got %d segments from data object. %d remaining segments.", segments, remains); /* Stop the timer if that was the last split */ if (remains == 0) { timeControl.pauseBothTimer(); } } void MainWindow::onPause() { /* Doesn't do anything if there are no more splits to do */ if (!data.canSplit()) { qDebug("Cannot do any more splits"); return; } /* Check if paused or not */ qDebug("Toggle timer"); timeControl.toggleBothTimer(); } void MainWindow::onReset() { bool merge = false; /* Pause timer so they do not continue running */ timeControl.pauseBothTimer(); /* Check if there have been splits and ask user about data */ if (data.hasSplit()) { int ret = QMessageBox::warning(this, "Segment times changed", "Do you want to merge your times before reset?", QMessageBox::Save | QMessageBox::No, QMessageBox::Save); merge = (ret == QMessageBox::Save); } qDebug("Reset"); timeControl.resetBothTimer(); displaySegments.clear(); /* Reset data */ data.reset(merge); int segments = data.getCurrentSegments(displaySegments, segmentLines); qDebug("Got %d segments from data object", segments); } void MainWindow::onOpen() { qDebug("open"); /* Pause timer so they do not continue running */ timeControl.pauseBothTimer(); /* Check if there have been splits and ask user about data */ if (data.hasSplit()) { int ret = QMessageBox::warning(this, "Segment times changed", "Do you want to discard this data?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); if (ret == QMessageBox::No) { return; } } qDebug("open new file"); /* Let the user select a filename and try to open this file */ QString filename = QFileDialog::getOpenFileName(this, "Open file with data segments", "", "All files (*.*)"); if (filename.length() == 0) return; /* Load data */ data.loadData(filename); /* Set back timers, display, etc. */ timeControl.resetBothTimer(); displaySegments.clear(); data.getCurrentSegments(displaySegments, segmentLines); calculateRegionSizes(); } void MainWindow::onSave() { qDebug("save"); /* Pause timer so they do not continue running */ timeControl.pauseBothTimer(); /* Merging unsaved data */ data.reset(true); /* Check for filename */ if (data.getFilename().size() == 0) { onSaveAs(); } else { data.saveData(data.getFilename()); } } void MainWindow::onSaveAs() { qDebug("saveas"); /* Pause timer so they do not continue running */ timeControl.pauseBothTimer(); /* Let the user select a filename to save the segment data */ QString filename = QFileDialog::getSaveFileName(this, "Save segment data", data.getFilename(), "All files (*.*)"); if (filename.length() == 0) return; data.saveData(filename); } void MainWindow::onToggleAutosplit(bool enable) { if (enable) { qDebug("Enabled autosplit"); } else { qDebug("Disabled autosplit"); } autosplit = enable; } void MainWindow::onToggleAutosave(bool enable) { if (enable) { qDebug("Enabled autosave"); } else { qDebug("Disabled autosave"); } autosave = enable; } void MainWindow::onToggleAutostartstop(bool enable) { if (enable) { qDebug("Enabled autostart/stop"); } else { qDebug("Disabled autostart/stop"); } autostartstop = enable; } void MainWindow::onExit() { /* Whatever is in the split data, save it as a temporary file with a time stamp * and set it as last filename used. Of course, only if the split data changed * (i.e. has splits already). Set this file as the last split data file so that * it will be loaded next time Fluffelwatch is opened. */ if (autosave && data.hasSplit()) { QString filename = QDateTime::currentDateTime().toString("yyyy.MM.dd hh:mm:ss") + " " + data.getTitle() + ".conf"; data.reset(true); data.saveData(filename); settings->setValue("Data/segmentData", filename); } /* Destroy the settings here to sync it and write everything to the file. */ delete settings; /* Close the window */ this->close(); } void MainWindow::setupContextMenu() { QAction *separator1 = new QAction(this); QAction *separator2 = new QAction(this); separator1->setSeparator(true); separator2->setSeparator(true); this->addAction(ui->action_Start_Split); this->addAction(ui->action_Pause); this->addAction(ui->action_Reset); this->addAction(ui->actionAutosplit_between_missions); this->addAction(ui->actionAutostart_stop_the_timers); this->addAction(separator1); this->addAction(ui->action_Open); this->addAction(ui->actionS_ave); this->addAction(ui->actionSave_as); this->addAction(ui->actionAutosave_at_exit); this->addAction(separator2); this->addAction(ui->action_Exit); } void MainWindow::setupGlobalShortcuts() { /* Register global hotkeys for start, pause/resume, reset */ QxtGlobalShortcut* shortcutSplit = new QxtGlobalShortcut(this); shortcutSplit->setShortcut(QKeySequence("Ctrl+Shift+F1")); QxtGlobalShortcut* shortcutPause = new QxtGlobalShortcut(this); shortcutPause->setShortcut(QKeySequence("Ctrl+Shift+F2")); QxtGlobalShortcut* shortcutReset = new QxtGlobalShortcut(this); shortcutReset->setShortcut(QKeySequence("Ctrl+Shift+F3")); connect(shortcutSplit, &QxtGlobalShortcut::activated, this, &MainWindow::onSplit); connect(shortcutPause, &QxtGlobalShortcut::activated, this, &MainWindow::onPause); connect(shortcutReset, &QxtGlobalShortcut::activated, this, &MainWindow::onReset); } void MainWindow::readSettings() { /* Read font and color settings into maps for convenient access */ readSettingsFonts(); readSettingsColors(); backgroundBrush = QBrush(userColors["background"]); /* General settings */ marginSize = settings->value("marginSize", 0).toInt(); segmentLines = qMax(2, settings->value("segmentLines").toInt()); /* Autosplit, Autosave, Autostart/stop (will automatically set the boolean through the toggle slot) */ ui->actionAutosplit_between_missions->setChecked(settings->value("autosplit", false).toBool()); ui->actionAutosave_at_exit->setChecked(settings->value("autosave", false).toBool()); ui->actionAutostart_stop_the_timers->setChecked(settings->value("autostartstop", false).toBool()); /* Read the segment and food data if available */ readSettingsData(); } void MainWindow::readSettingsFonts() { /* Get all keys from the fonts group */ settings->beginGroup("Fonts"); QStringList keys = settings->allKeys(); /* Iterate over each key and create an entry in the map. The value is read into a string * and then converted to a QFont by fromString. */ for(int i = 0; i < keys.size(); ++i) { QFont value; if (value.fromString(settings->value(keys[i], QFont("Arial", 18, QFont::Bold).toString()).toString())) { userFonts.insert(keys[i], value); } } /* Reset the group */ settings->endGroup(); } void MainWindow::readSettingsColors() { /* Read the keys and settings from the colors group */ settings->beginGroup("Colors"); QStringList keys = settings->allKeys(); /* Iterate over each key and create an entry in the map. The value is read into a string * and then converted to QColor. */ for(int i = 0; i < keys.size(); ++i) { QColor value = QColor(settings->value(keys[i], "#fefefe").toString()); userColors.insert(keys[i], value); } /* Reset the group */ settings->endGroup(); } void MainWindow::readSettingsData() { /* Read the segment data as well as the current fluffelfood data in */ settings->beginGroup("Data"); QString segmentData = settings->value("segmentData").toString(); QString foodData = settings->value("foodData").toString(); /* Load segment data */ data.loadData(segmentData); int segments = data.getCurrentSegments(displaySegments, segmentLines); qDebug("Segment data loaded from... %s", segmentData.toStdString().c_str()); qDebug("Got %d segments from data object", segments); /* Load food data */ icons.loadFromFile(foodData); icons.showAllIcons(); qDebug("Food data loaded from... %s", foodData.toStdString().c_str()); settings->endGroup(); } void MainWindow::paintAllElements(QPainter& painter) { /* Main title (taken from split data file) */ paintText(painter, regionTitle, userFonts["mainTitle"], userColors["mainTitle"], data.getTitle(), Qt::AlignCenter); /* Separators */ paintSeparator(painter, regionTitle.bottomLeft(), regionTitle.bottomRight()); paintSeparator(painter, regionTimeList.bottomLeft(), regionTimeList.bottomRight()); /* Paint all segments (middle part) */ int lines = qMin(segmentLines, displaySegments.size()); for (int i = 0; i < lines; ++i) { paintSegmentLine(painter, QRect(marginSize, regionTimeList.top() + marginSize + i * segmentSize.height(), segmentSize.width(), segmentSize.height()), displaySegments[i]); } /* Status area: the icons + the ingame and real timer */ QRect rectReal = QRect(regionStatus.right() - mainTimerSize.width() - marginSize, regionStatus.top() + marginSize, mainTimerSize.width(), mainTimerSize.height()); QRect rectIngame = QRect(regionStatus.right() - adjustedTimerSize.width() - marginSize, regionStatus.bottom() - adjustedTimerSize.height() - marginSize, adjustedTimerSize.width(), adjustedTimerSize.height()); icons.paint(painter, regionStatus); paintText(painter, rectReal, userFonts["realTimer"], userColors["realTimer"], timeControl.elapsedRealTimeString(), Qt::AlignRight | Qt::AlignVCenter); paintText(painter, rectIngame, userFonts["ingameTimer"], userColors["ingameTimer"], timeControl.elapsedIngameTimeString(), Qt::AlignRight | Qt::AlignVCenter); } void MainWindow::paintText(QPainter& painter, const QRect& rect, const QFont& font, const QColor& color, const QString& text, int flags) { painter.setFont(font); painter.setPen(color); painter.drawText(rect, flags, text); } void MainWindow::paintSeparator(QPainter& painter, const QPoint& start, const QPoint& end) { painter.setPen(userColors["separatorLine"]); painter.drawLine(start, end); } void MainWindow::paintSegmentLine(QPainter& painter, const QRect& rect, SplitData::segment& segment) { /* Decide which state we want to draw: past segments, current segment (when timer are on), and * future segments. */ if (segment.ran) { paintSegmentLinePast(painter, rect, segment); } else if (segment.current && timeControl.areBothTimerValid()) { paintSegmentLineCurrent(painter, rect, segment); } else { paintSegmentLineFuture(painter, rect, segment); } } void MainWindow::paintSegmentLinePast(QPainter& painter, const QRect& rect, SplitData::segment& segment) { /* Draw a past/ran segment */ /* Segment title */ paintText(painter, rect, userFonts["segmentTitle"], userColors["segmentTitle"], segment.title, Qt::AlignLeft | Qt::AlignVCenter); /* Segment difference time; display only if the segment was ran or it is the current segment */ QRect rectDiff = QRect(rect.right() - segmentColumnSizes[2] - segmentColumnSizes[1] - marginSize * 2, rect.top(), segmentColumnSizes[1], rect.height()); QColor textColor = userColors["segmentTitle"]; if (segment.improtime < 0) { textColor = userColors["gainedTime"]; } else if (segment.improtime > 0 ) { textColor = userColors["lostTime"]; } paintText(painter, rectDiff, userFonts["segmentDiff"], textColor, TimeController::getStringFromTimeDiff(segment.totalimprotime), Qt::AlignRight | Qt::AlignVCenter); /* Segment time (lost or improvement) */ QRect rectTime = QRect(rect.right() - segmentColumnSizes[2] - marginSize * 2, rect.top(), segmentColumnSizes[2], rect.height()); textColor = userColors["segmentTime"]; if (segment.runtime < segment.besttime) { textColor = userColors["newRecord"]; } else if (segment.improtime > 0) { textColor = userColors["lostTime"]; } else if (segment.improtime < 0) { textColor = userColors["gainedTime"]; } paintText(painter, rectTime, userFonts["segmentTime"], textColor, TimeController::getStringFromTime(segment.totaltime), Qt::AlignRight | Qt::AlignVCenter); } void MainWindow::paintSegmentLineCurrent(QPainter& painter, const QRect& rect, SplitData::segment& segment) { /* Draw the current segment with the timers on */ /* Highlighted segment title */ paintText(painter, rect, userFonts["segmentTitle"], userColors["currentSegment"], segment.title, Qt::AlignLeft | Qt::AlignVCenter); /* Segment difference time; display only if the segment was ran or it is the current segment */ QRect rectDiff = QRect(rect.right() - segmentColumnSizes[2] - segmentColumnSizes[1] - marginSize * 2, rect.top(), segmentColumnSizes[1], rect.height()); qint64 improtime = timeControl.elapsedPreferredTime() - segment.totaltime; /* Display with normal text color */ paintText(painter, rectDiff, userFonts["segmentDiff"], userColors["segmentTitle"], TimeController::getStringFromTimeDiff(improtime), Qt::AlignRight | Qt::AlignVCenter); /* Segment time (or improvement) */ QRect rectTime = QRect(rect.right() - segmentColumnSizes[2] - marginSize * 2, rect.top(), segmentColumnSizes[2], rect.height()); QColor textcolor = userColors["currentSegment"]; if (improtime > 0) { textcolor = userColors["lostTime"]; } paintText(painter, rectTime, userFonts["segmentTime"], textcolor, TimeController::getStringFromTime(timeControl.elapsedPreferredTime()), Qt::AlignRight | Qt::AlignVCenter); } void MainWindow::paintSegmentLineFuture(QPainter& painter, const QRect& rect, SplitData::segment& segment) { /* Draw a future segment */ /* Segment title */ paintText(painter, rect, userFonts["segmentTitle"], userColors["segmentTitle"], segment.title, Qt::AlignLeft | Qt::AlignVCenter); /* Segment time */ QRect rectTime = QRect(rect.right() - segmentColumnSizes[2] - marginSize * 2, rect.top(), segmentColumnSizes[2], rect.height()); paintText(painter, rectTime, userFonts["segmentTime"], userColors["segmentTime"], TimeController::getStringFromTime(segment.totaltime), Qt::AlignRight | Qt::AlignVCenter); } void MainWindow::calculateRegionSizes() { /* Calculate title region */ QFontMetrics fm(userFonts["mainTitle"]); regionTitle = QRect(QPoint(0, 0), fm.size(Qt::TextSingleLine, data.getTitle())); regionTitle.adjust(0, 0, marginSize * 2, marginSize * 2); /* Calculate time list region */ QFontMetrics segTitle(userFonts["segmentTitle"]); QFontMetrics segDiff(userFonts["segmentDiff"]); QFontMetrics segTime(userFonts["segmentTime"]); QSize sizeTitle = segTitle.size(Qt::TextSingleLine, data.getLongestSegmentTitle()); segmentColumnSizes[0] = sizeTitle.width(); QSize sizeDiff = segDiff.size(Qt::TextSingleLine, " −00:00:00.00 "); segmentColumnSizes[1] = sizeDiff.width(); QSize sizeTime = segTime.size(Qt::TextSingleLine, " 00:00:00.00 "); segmentColumnSizes[2] = sizeTime.width(); segmentSize.setWidth(sizeTitle.width() + marginSize + sizeDiff.width() + marginSize + sizeTime.width()); segmentSize.setHeight(qMax(qMax(sizeTitle.height(), sizeDiff.height()), sizeTime.height())); regionTimeList = QRect(regionTitle.bottomLeft(), QSize(segmentSize.width(), segmentSize.height() * segmentLines)); regionTimeList.adjust(0, 0, marginSize * 2, marginSize * 2); /* Calculate status bar (with the two timers) */ QFontMetrics mtFm(userFonts["realTimer"]); mainTimerSize = mtFm.size(Qt::TextSingleLine, "00:00:00.00"); QFontMetrics atFm(userFonts["ingameTimer"]); adjustedTimerSize = atFm.size(Qt::TextSingleLine, "00:00:00.00"); QSize iconArea = adjustedTimerSize; regionStatus = QRect(regionTimeList.bottomLeft(), QSize(iconArea.width() + qMax(mainTimerSize.width(), adjustedTimerSize.width()), qMax(mainTimerSize.height() + adjustedTimerSize.height(), iconArea.height()))); regionStatus.adjust(0, 0, marginSize * 2, marginSize * 2); /* Calculate new window size: width is the max width of all regions and * height is simply the sum of all regions. */ int maxWidth = qMax(qMax(regionTitle.width(), regionTimeList.width()), regionStatus.width()); QSize windowSize; windowSize.setWidth(maxWidth); windowSize.setHeight(regionTitle.height() + regionTimeList.height() + regionStatus.height()); resize(windowSize); /* Update all regions to have the max width */ regionTitle.setWidth(maxWidth); regionTimeList.setWidth(maxWidth); segmentSize.setWidth(maxWidth); regionStatus.setWidth(maxWidth); }
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
4