hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
61d7d0a1bf3b9eeefeba28c620907ce9b3b43be5
1,533
cpp
C++
ParamedicCommander.cpp
AviNagosa/cpp_WarGame_Ex4
4d054a82efb6cd4468674be5062e8462c5b6dbe1
[ "MIT" ]
null
null
null
ParamedicCommander.cpp
AviNagosa/cpp_WarGame_Ex4
4d054a82efb6cd4468674be5062e8462c5b6dbe1
[ "MIT" ]
null
null
null
ParamedicCommander.cpp
AviNagosa/cpp_WarGame_Ex4
4d054a82efb6cd4468674be5062e8462c5b6dbe1
[ "MIT" ]
null
null
null
#include "ParamedicCommander.hpp" void ParamedicCommander::operation(std::vector<std::vector<Soldier*>> &board,std::pair<int,int> source){ int x1 = source.first; int y1 = source.second; Soldier* paramedicCommander = board[x1][y1]; std::stack<std::pair<int,int>> myPlatoon; // healAround(board,x1,y1); for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { //if the we have a soldier and the soldier are not this if (board[x1 + i][y1 + j] != nullptr && (i!=0 && j!=0)) { //if the other soldier belong to the same group if (board[x1 + i][y1 + j]->getPlayerNumber() == board[x1][y1]->getPlayerNumber()) { board[x1 + i][y1 + j]->setHP(board[x1 + i][y1 + j]->getMaxHP()); } } } } for(int i = 0 ; i < board.size() ; i++) { for(int j = 0 ; j < board[i].size() ; j++) { if(board[i][j] != nullptr) { if(board[i][j]->getPlayerNumber() == paramedicCommander->getPlayerNumber()) { if(board[i][j]->getType() == "P"){ myPlatoon.push({i,j}); } } } } } while(!myPlatoon.empty()){ std::pair<int,int> current = myPlatoon.top(); board[current.first][current.second]->operation(board,current); myPlatoon.pop(); } };
34.066667
104
0.452707
AviNagosa
61d7fcc28537064a96af419020956c602426eb51
32,220
cc
C++
client/clientservicer.cc
gorlak/P4
fa25916ef69fa77887bb493800b6ce12be3f469e
[ "BSD-2-Clause" ]
null
null
null
client/clientservicer.cc
gorlak/P4
fa25916ef69fa77887bb493800b6ce12be3f469e
[ "BSD-2-Clause" ]
null
null
null
client/clientservicer.cc
gorlak/P4
fa25916ef69fa77887bb493800b6ce12be3f469e
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 1995, 2001 Perforce Software. All rights reserved. * * This file is part of Perforce - the FAST SCM System. */ # ifdef USE_EBCDIC # define NEED_EBCDIC # endif # include <stdhdrs.h> # include <strbuf.h> # include <strdict.h> # include <strops.h> # include <strarray.h> # include <strtable.h> # include <error.h> # include <mapapi.h> # include <handler.h> # include <rpc.h> # include <i18napi.h> # include <charcvt.h> # include <transdict.h> # include <ignore.h> # include <debug.h> # include <tunable.h> # include <p4tags.h> # include <msgclient.h> # include <msgsupp.h> # include <filesys.h> # include <pathsys.h> # include <enviro.h> # include <readfile.h> # include <diffsp.h> # include <diffan.h> # include <diff.h> # include "clientuser.h" # include "client.h" # include "clientprog.h" # include "clientservice.h" /* * ReconcileHandle - handle reconcile's list of files to skip when adding */ class ReconcileHandle : public LastChance { public: ReconcileHandle() { pathArray = new StrArray; delCount = 0; } ~ReconcileHandle() { delete pathArray; } StrArray *pathArray; int delCount; } ; /* * SendDir - utility method used by clientTraverseShort to decide if a * filename should be output as a file or as a directory (status -s) */ int SendDir( PathSys *fileName, StrPtr *cwd, StrArray *dirs, int &idx, int skip ) { int isDir = 0; // Skip printing file in current directory and just report subdirectory if( skip ) { fileName->SetLocal( *cwd, StrRef( "..." ) ); return 1; } // If file is in the current directory: isDirs is unset so that our // caller will send back the original file. fileName->ToParent(); if( !fileName->SCompare( *cwd ) ) return isDir; // Set path to the directory under cwd containing this file. // 'dirs' is the list of dirs in cwd on workspace. for( ; idx < dirs->Count() && !isDir; idx++ ) { if( fileName->IsUnderRoot( *dirs->Get( idx ) ) ) { fileName->SetLocal( *dirs->Get(idx), StrRef( "..." )); ++isDir; } } return isDir; } void clientReconcileFlush( Client *client, Error *e ) { // Delete the client's reconcile handle StrRef skipAdd( "skipAdd" ); ReconcileHandle *recHandle = (ReconcileHandle *)client->handles.Get( &skipAdd ); if( recHandle ) delete recHandle; } /* * clientReconcileEdit() -- "inquire" about file, for 'p4 reconcile' * * This routine performs clientCheckFile's scenario 1 checking, but * also saves the list of files that are in the depot so they can be * compared to the list of files on the client when reconciling later for add. * */ void clientReconcileEdit( Client *client, Error *e ) { client->NewHandler(); StrPtr *clientType = client->GetVar( P4Tag::v_type ); StrPtr *digest = client->GetVar( P4Tag::v_digest ); StrPtr *digestType = client->GetVar( P4Tag::v_digestType ); StrPtr *confirm = client->GetVar( P4Tag::v_confirm, e ); StrPtr *fileSize = client->GetVar( P4Tag::v_fileSize ); StrPtr *submitTime = client->GetVar( P4Tag::v_time ); if( e->Test() && !e->IsFatal() ) { client->OutputError( e ); return; } const char *status = "exists"; const char *ntype = clientType ? clientType->Text() : "text"; // For adding files, checkSize is a maximum (or use alt type) // For flush, checkSize is an optimization check on binary files. offL_t checkSize = fileSize ? fileSize->Atoi64() : 0; /* * If we do know the type, we want to know if it's missing. * If it isn't missing and a digest is given, we want to know if * it is the same. */ FileSys *f = ClientSvc::File( client, e ); if( e->Test() || !f ) return; int statVal = f->Stat(); // Save the list of depot files. We'll diff it against the list of all // files on client to find files to add in clientReconcileAdd StrRef skipAdd( "skipAdd" ); ReconcileHandle *recHandle = (ReconcileHandle *)client->handles.Get( &skipAdd ); if( !recHandle ) { recHandle = new ReconcileHandle; client->handles.Install( &skipAdd, recHandle, e ); if( e->Test() ) return; } if( !( statVal & ( FSF_SYMLINK|FSF_EXISTS ) ) ) { status = "missing"; recHandle->delCount++; } else if ( ( !( statVal & FSF_SYMLINK ) && ( f->IsSymlink() ) ) || ( ( statVal & FSF_SYMLINK ) && !( f->IsSymlink() ) ) ) { recHandle->pathArray->Put()->Set( f->Name() ); } else if( digest ) { recHandle->pathArray->Put()->Set( f->Name() ); if( digestType ) { StrBuf localDigest; FileDigestType digType; if( !digestType->Compare( StrRef( P4Tag::v_digestTypeMD5 ) ) ) digType = FS_DIGEST_MD5; else if( !digestType->Compare( StrRef( P4Tag::v_digestTypeGitText ) ) ) digType = FS_DIGEST_GIT_TEXT_SHA1; else if( !digestType->Compare( StrRef( P4Tag::v_digestTypeGitBinary ) ) ) digType = FS_DIGEST_GIT_BINARY_SHA1; else if( !digestType->Compare( StrRef( P4Tag::v_digestTypeSHA256 ) ) ) digType = FS_DIGEST_SHA256; f->ComputeDigest( digType, &localDigest, e ); if( !e->Test() && !localDigest.XCompare( *digest ) ) status = "same"; } else if( !checkSize || checkSize == f->GetSize() ) { StrBuf localDigest; f->Translator( ClientSvc::XCharset( client, FromClient ) ); // Bypass expensive digest computation with -m unless the // local file's timestamp is different from the server's. if( !submitTime || ( submitTime && ( f->StatModTime() != submitTime->Atoi()) ) ) { f->Digest( &localDigest, e ); if( !e->Test() && !localDigest.XCompare( *digest ) ) status = "same"; } else if( submitTime ) status = "same"; } // If we can't read the file (for some reason -- wrong type?) // we consider the files different. e->Clear(); } delete f; // tell the server client->SetVar( P4Tag::v_type, ntype ); client->SetVar( P4Tag::v_status, status ); client->Confirm( confirm ); // Report non-fatal error and clear it. client->OutputError( e ); } int clientTraverseShort( Client *client, StrPtr *cwd, const char *dir, int traverse, int noIgnore, int initial, int skipCheck, int skipCurrent, MapApi *map, StrArray *files, StrArray *dirs, int &idx, StrArray *depotFiles, int &ddx, const char *config, Error *e ) { // Variant of clientTraverseDirs that computes the files to be // added during traversal of directories instead of at the end, // and returns directories and files rather than all files. // This is used by 'status -s'. // Scan the directory. FileSys *f = client->GetUi()->File( FST_BINARY ); f->SetContentCharSetPriv( client->content_charset ); f->Set( StrRef( dir ) ); int fstat = f->Stat(); Ignore *ignore = client->GetIgnore(); StrPtr ignored = client->GetIgnoreFile(); StrBuf from; StrBuf to; CharSetCvt *cvt = ( (TransDict *)client->transfname )->ToCvt(); const char *fileName; int found = 0; // Use server case-sensitivity rules to find files to add // from.SetCaseFolding( client->protocolNocase ); // With unicode server and client using character set, we need // to send files back as utf8. if( client != client->translated ) { fileName = cvt->FastCvt( f->Name(), strlen(f->Name()), 0 ); if( !fileName ) fileName = f->Name(); } else fileName = f->Name(); // If this is a file, not a directory, and not to be ignored, // save the filename if( !( fstat & FSF_DIRECTORY ) ) { if( ( fstat & FSF_EXISTS ) || ( fstat & FSF_SYMLINK ) ) { if( noIgnore || !ignore->Reject( StrRef(f->Name()), ignored, config ) ) { files->Put()->Set( fileName ); found = 1; } } delete f; return found; } // If this is a symlink to a directory, and not to be ignored, // return filename and quit if( ( fstat & FSF_SYMLINK ) && ( fstat & FSF_DIRECTORY ) ) { if( noIgnore || !ignore->Reject( StrRef(f->Name()), ignored, config ) ) { files->Put()->Set( fileName ); found = 1; } delete f; return found; } // This is a directory to be scanned. StrArray *ua = f->ScanDir( e ); if( e->Test() ) { // report error but keep moving delete f; client->OutputError( e ); return 0; } // PathSys for concatenating dir and local path, // to get full path PathSys *p = PathSys::Create(); p->SetCharSet( f->GetCharSetPriv() ); // Attach path delimiter to dirs so Sort() works correctly, and also to // save relevant Stat() information. StrArray *a = new StrArray(); StrBuf dirDelim; StrBuf symDelim; #ifdef OS_NT dirDelim.Set( "\\" ); symDelim.Set( "\\\\" ); #else dirDelim.Set( "/" ); symDelim.Set( "//" ); #endif // Now files & dirs at this level from ScanDir() will be sorted // in the same order as the depotFiles array. And delimiters tell us // the Stat() of those files. for( int i = 0; i < ua->Count(); i++ ) { p->SetLocal( StrRef( dir ), *ua->Get(i) ); f->Set( *p ); int stat = f->Stat(); StrBuf out; if( ( stat & FSF_DIRECTORY ) && !( stat & FSF_SYMLINK ) ) out << ua->Get( i ) << dirDelim; else if( ( stat & FSF_DIRECTORY ) && ( stat & FSF_SYMLINK ) ) out << ua->Get( i ) << symDelim; else if( ( stat & FSF_EXISTS ) || ( stat & FSF_SYMLINK ) ) out << ua->Get(i); else continue; a->Put()->Set( out ); } a->Sort( !StrBuf::CaseUsage() ); delete ua; // If directory is unknown to p4, we don't need to check that files // are in depot (they aren't), so just return after the first file // is found and bypass checking. int doSkipCheck = skipCheck; int dddx = 0; int matched; StrArray *depotDirs = new StrArray(); // First time through we save depot dirs if( initial ) { StrPtr *ddir; for( int j=0; ddir=client->GetVar( StrRef("depotDirs"), j); j++) { StrBuf dirD; dirD << ddir << dirDelim; depotDirs->Put()->Set( dirD ); } depotDirs->Sort( !StrBuf::CaseUsage() ); } // For each directory entry. for( int i = 0; i < a->Count(); i++ ) { // Strip delimiters and use the hints to determine stat int isDir = 0; int isSymDir = 0; StrBuf fName; if( a->Get(i)->EndsWith( symDelim.Text(), 2 ) ) { ++isDir; ++isSymDir; fName.Set( a->Get(i)->Text(), a->Get(i)->Length() - 2 ); } else if( a->Get(i)->EndsWith( dirDelim.Text(), 1 ) ) { ++isDir; fName.Set( a->Get(i)->Text(), a->Get(i)->Length() - 1 ); } else fName.Set( a->Get(i) ); // Check mapping, ignore files before sending file or symlink back p->SetLocal( StrRef( dir ), fName ); f->Set( *p ); int checkFile = 0; if( client != client->translated ) { fileName = cvt->FastCvt( f->Name(), strlen(f->Name()) ); if( !fileName ) fileName = f->Name(); } else fileName = f->Name(); if( isDir ) { if( isSymDir ) { from.Set( fileName ); from << "/"; if( client->protocolNocase != StrBuf::CaseUsage() ) { from.SetCaseFolding( client->protocolNocase ); matched = map->Translate( from, to, MapLeftRight ); from.SetCaseFolding( !client->protocolNocase ); } else matched = map->Translate( from, to, MapLeftRight ); if( !matched ) continue; if( noIgnore || !ignore->Reject( StrRef(f->Name()), ignored, config ) ) { if( doSkipCheck ) { p->Set( fileName ); (void)SendDir( p, cwd, dirs, idx, skipCurrent ); files->Put()->Set( p ); found = 1; break; } else ++checkFile; } } else if( traverse ) { if( initial ) { dirs->Put()->Set( fileName ); int foundOne = 0; int l; // If this directory is unknown to the depot, we don't // need to compare against depot files. for( ; dddx < depotDirs->Count() && !foundOne; dddx++) { StrBuf fName; fName << fileName << dirDelim; const StrPtr *ddir = depotDirs->Get( dddx ); p->SetLocal( *cwd, *ddir ); l = fName.SCompare( *p ); if( !l ) ++foundOne; else if( l < 0 ) break; } skipCheck = !foundOne ? 1 : 0; } found = clientTraverseShort( client, cwd, f->Name(), traverse, noIgnore, 0, skipCheck, skipCurrent, map, files, dirs, idx, depotFiles, ddx, config, e ); // Stop traversing directories when we have a file to // to add, unless we are at the top and need to check // for files in the current directory. if( found && !initial ) break; else if( found && initial && !skipCurrent ) found = 0; if( found ) break; } } else { from.Set( fileName ); if( client->protocolNocase != StrBuf::CaseUsage() ) { from.SetCaseFolding( client->protocolNocase ); matched = map->Translate( from, to, MapLeftRight ); from.SetCaseFolding( !client->protocolNocase ); } else matched = map->Translate( from, to, MapLeftRight ); if( !matched ) continue; if( noIgnore || !ignore->Reject( StrRef(f->Name()), ignored, config ) ) { if( doSkipCheck ) { p->Set( fileName ); (void)SendDir( p, cwd, dirs, idx, skipCurrent ); files->Put()->Set( p ); found = 1; break; } else ++checkFile; } } // See if file is in depot and if not, either set the file // or directory to be reported back to the server. if( checkFile ) { int l = 0; int finished = 0; while ( !finished ) { if( ddx >= depotFiles->Count()) l = -1; else l = StrRef( fileName ).SCompare( *depotFiles->Get(ddx)); if( !l ) { ++ddx; ++finished; } else if( l < 0 ) { p->Set( fileName ); if( initial && skipCurrent ) { p->ToParent(); p->SetLocal( *p, StrRef("...") ); files->Put()->Set( p ); } else if( SendDir( p, cwd, dirs, idx, skipCurrent ) ) files->Put()->Set( p ); else files->Put()->Set( fileName ); found = 1; break; } else ++ddx; } if( ( !initial || skipCurrent ) && found ) break; } } delete p; delete a; delete f; delete depotDirs; return found; } void clientTraverseDirs( Client *client, const char *dir, int traverse, int noIgnore, int getDigests, MapApi *map, StrArray *files, StrArray *sizes, StrArray *digests, int &hasIndex, StrArray *hasList, const char *config, Error *e ) { // Return all files in dir, and optionally traverse dirs in dir, // while checking each file against map before returning it // Scan the directory. FileSys *f = client->GetUi()->File( FST_BINARY ); f->SetContentCharSetPriv( client->content_charset ); f->Set( StrRef( dir ) ); int fstat = f->Stat(); Ignore *ignore = client->GetIgnore(); StrPtr ignored = client->GetIgnoreFile(); StrBuf from; StrBuf to; CharSetCvt *cvt = ( (TransDict *)client->transfname )->ToCvt(); const char *fileName; StrBuf localDigest; // With unicode server and client using character set, we need // to send files back as utf8. if( client != client->translated ) { fileName = cvt->FastCvt( f->Name(), strlen(f->Name()), 0 ); if( !fileName ) fileName = f->Name(); } else fileName = f->Name(); // If this is a file, not a directory, and not to be ignored, // save the filename if( !( fstat & FSF_DIRECTORY ) ) { if( ( fstat & FSF_EXISTS ) || ( fstat & FSF_SYMLINK ) ) { if( noIgnore || !ignore->Reject( StrRef(f->Name()), ignored, config ) ) { files->Put()->Set( fileName ); sizes->Put()->Set( StrNum( f->GetSize() ) ); if( getDigests ) { f->Translator( ClientSvc::XCharset(client,FromClient)); f->Digest( &localDigest, e ); digests->Put()->Set( localDigest ); } } } delete f; return; } // If this is a symlink to a directory, and not to be ignored, // return filename and quit if( ( fstat & FSF_SYMLINK ) && ( fstat & FSF_DIRECTORY ) ) { if( noIgnore || !ignore->Reject( StrRef(f->Name()), ignored, config ) ) { files->Put()->Set( fileName ); sizes->Put()->Set( StrNum( f->GetSize() ) ); if( getDigests ) { f->Translator( ClientSvc::XCharset(client,FromClient)); f->Digest( &localDigest, e ); digests->Put()->Set( localDigest ); } } delete f; return; } // Directory might be ignored, bail if( !noIgnore && ignore->RejectDir( StrRef( f->Name() ), ignored, config ) ) { delete f; return; } // This is a directory to be scanned. StrArray *a = f->ScanDir( e ); if( e->Test() ) { // report error but keep moving delete f; client->OutputError( e ); return; } // Sort in case sensitivity of client a->Sort( !StrBuf::CaseUsage() ); // PathSys for concatenating dir and local path, // to get full path PathSys *p = PathSys::Create(); p->SetCharSet( f->GetCharSetPriv() ); int matched; // For each directory entry. for( int i = 0; i < a->Count(); i++ ) { // Check mapping, ignore files before sending file or symlink back p->SetLocal( StrRef( dir ), *a->Get(i) ); f->Set( *p ); if( client != client->translated ) { fileName = cvt->FastCvt( f->Name(), strlen(f->Name()) ); if( !fileName ) fileName = f->Name(); } else fileName = f->Name(); // Do compare with array list (skip files if possible) int cmp = -1; while( hasList && hasIndex < hasList->Count() ) { cmp = f->Path()->SCompare( *hasList->Get( hasIndex ) ); if( cmp < 0 ) break; hasIndex++; if( cmp == 0 ) break; } // Don't stat if we matched a file from the edit list if( cmp == 0 ) continue; int stat = f->Stat(); if( stat & FSF_DIRECTORY ) { if( stat & FSF_SYMLINK ) { from.Set( fileName ); from << "/"; if( client->protocolNocase != StrBuf::CaseUsage() ) { from.SetCaseFolding( client->protocolNocase ); matched = map->Translate( from, to, MapLeftRight ); from.SetCaseFolding( !client->protocolNocase ); } else matched = map->Translate( from, to, MapLeftRight ); if( !matched ) continue; if( noIgnore || !ignore->Reject( StrRef(f->Name()), ignored, config ) ) { files->Put()->Set( fileName ); sizes->Put()->Set( StrNum( f->GetSize() ) ); if( getDigests ) { f->Translator( ClientSvc::XCharset(client,FromClient)); f->Digest( &localDigest, e ); digests->Put()->Set( localDigest ); } } } else if( traverse ) clientTraverseDirs( client, f->Name(), traverse, noIgnore, getDigests, map, files, sizes, digests, hasIndex, hasList, config, e ); } else if( ( stat & FSF_EXISTS ) || ( stat & FSF_SYMLINK ) ) { from.Set( fileName ); if( client->protocolNocase != StrBuf::CaseUsage() ) { from.SetCaseFolding( client->protocolNocase ); matched = map->Translate( from, to, MapLeftRight ); from.SetCaseFolding( !client->protocolNocase ); } else matched = map->Translate( from, to, MapLeftRight ); if( !matched ) continue; if( noIgnore || !ignore->Reject( StrRef(f->Name()), ignored, config ) ) { files->Put()->Set( fileName ); sizes->Put()->Set( StrNum( f->GetSize() ) ); if( getDigests ) { f->Translator( ClientSvc::XCharset(client,FromClient)); f->Digest( &localDigest, e ); digests->Put()->Set( localDigest ); } } } } delete p; delete a; delete f; } void clientReconcileAdd( Client *client, Error *e ) { /* * Reconcile add confirm * * Scans the directory (local syntax) and returns * files in the directory using the full path. This * differs from clientScanDir in that it returns full * paths, supports traversing subdirectories, and checks * against a mapTable. */ client->NewHandler(); StrPtr *dir = client->transfname->GetVar( P4Tag::v_dir, e ); StrPtr *confirm = client->GetVar( P4Tag::v_confirm, e ); StrPtr *traverse = client->GetVar( "traverse" ); StrPtr *summary = client->GetVar( "summary" ); StrPtr *skipIgnore = client->GetVar( "skipIgnore" ); StrPtr *skipCurrent = client->GetVar( "skipCurrent" ); StrPtr *sendDigest = client->GetVar( "sendDigest" ); StrPtr *mapItem; if( e->Test() ) return; MapApi *map = new MapApi; StrArray *files = new StrArray(); StrArray *sizes = new StrArray(); StrArray *dirs = new StrArray(); StrArray *depotFiles = new StrArray(); StrArray *digests = new StrArray(); // Construct a MapTable object from the strings passed in by server for( int i = 0; mapItem = client->GetVar( StrRef("mapTable"), i ); i++) { MapType m; int j; char *c = mapItem->Text(); switch( *c ) { case '-': m = MapExclude; j = 1; break; case '+': m = MapOverlay; j = 1; break; default: m = MapInclude; j = 0; break; } map->Insert( StrRef( c+j ), StrRef( c+j ), m ); } // If we have a list of files we know are in the depot already, // filter them out of our list of files to add. For -s option, // we need to have this list of depot files for computing files // and directories to add (even if it is an empty list). StrRef skipAdd( "skipAdd" ); ReconcileHandle *recHandle = (ReconcileHandle *)client->handles.Get( &skipAdd ); if( recHandle ) { recHandle->pathArray->Sort( !StrBuf::CaseUsage() ); } else if( !recHandle && summary != 0 ) { recHandle = new ReconcileHandle; client->handles.Install( &skipAdd, recHandle, e ); if( e->Test() ) { delete files; delete sizes; delete dirs; delete depotFiles; delete digests; delete map; return; } } // status -s also needs the list of files opened for add appended // to the list of depot files. if( summary != 0 ) { const StrPtr *dfile; for( int j=0; dfile=client->GetVar( StrRef("depotFiles"), j); j++) depotFiles->Put()->Set( dfile ); for( int j=0; dfile=recHandle->pathArray->Get(j); j++ ) depotFiles->Put()->Set( dfile ); depotFiles->Sort( !StrBuf::CaseUsage() ); } // status -s will output files in the current directory and paths // rather than all of the files individually. Compare against depot // files early so we can abort traversal early if we can. int hasIndex = 0; const char *config = client->GetEnviro()->Get( "P4CONFIG" ); if( summary != 0 ) { int idx = 0; int ddx = 0; (void)clientTraverseShort( client, dir, dir->Text(), traverse != 0, skipIgnore != 0, 1, 0, skipCurrent != 0, map, files, dirs, idx, depotFiles, ddx, config, e ); } else clientTraverseDirs( client, dir->Text(), traverse != 0, skipIgnore != 0, sendDigest != 0, map, files, sizes, digests, hasIndex, recHandle ? recHandle->pathArray : 0, config, e ); delete map; // Compare list of files on client with list of files in the depot // if we have this list from ReconcileEdit. Skip this comparison // if summary because it was done already. if( recHandle && !summary ) { int i1 = 0, i2 = 0, i0 = 0, l = 0; while( i1 < files->Count() ) { if( i2 >= recHandle->pathArray->Count()) l = -1; else l = files->Get( i1 )->SCompare( *recHandle->pathArray->Get( i2 ) ); if( !l ) { ++i1; ++i2; } else if( l < 0 ) { client->SetVar( P4Tag::v_file, i0, *files->Get( i1 ) ); if( !sendDigest && recHandle->delCount ) { // Deleted files? Send filesize info so the // server can try to pair up moves. client->SetVar( P4Tag::v_fileSize, i0, *sizes->Get( i1 ) ); } if( sendDigest ) client->SetVar( P4Tag::v_digest, i0, *digests->Get(i1)); ++i0; ++i1; } else { ++i2; } } } else { for( int j = 0; j < files->Count(); j++ ) { client->SetVar( P4Tag::v_file, j, *files->Get(j) ); if( sendDigest ) client->SetVar( P4Tag::v_digest, j, *digests->Get(j) ); } } client->Confirm( confirm ); delete files; delete sizes; delete dirs; delete depotFiles; delete digests; } void clientExactMatch( Client *client, Error *e ) { // Compare existing digest to list of // new client files, return match, or not. // Args: // type = existing file type (clientpart) // digest = existing file digest // fileSize = existing file size // charSet = existing file charset // toFileN = new file local path // indexN = new file index // confirm = return callback // // Return: // toFile = exact match // index = exact match client->NewHandler(); StrPtr *digest = client->GetVar( P4Tag::v_digest ); StrPtr *confirm = client->GetVar( P4Tag::v_confirm, e ); if( e->Test() ) return; StrPtr *matchFile = 0; StrPtr *matchIndex = 0; FileSys *f = 0; for( int i = 0 ; client->GetVar( StrRef( P4Tag::v_toFile ), i ) ; i++ ) { delete f; StrVarName path = StrVarName( StrRef( P4Tag::v_toFile ), i ); f = ClientSvc::FileFromPath( client, path.Text(), e ); // If we encounter a problem with a file, we just don't return // it as a match. No need to blat out lots of errors. if( e->Test() || !f ) { e->Clear(); continue; } int statVal = f->Stat(); // Skip files that are symlinks when we // aren't looking for symlinks. if( ( !( statVal & ( FSF_SYMLINK|FSF_EXISTS ) ) ) || ( !( statVal & FSF_SYMLINK ) && ( f->IsSymlink() ) ) || ( ( statVal & FSF_SYMLINK ) && !( f->IsSymlink() ) ) ) continue; if( !digest ) continue; StrBuf localDigest; f->Translator( ClientSvc::XCharset( client, FromClient ) ); f->Digest( &localDigest, e ); if( e->Test() ) { e->Clear(); continue; } if( !localDigest.XCompare( *digest ) ) { matchFile = client->GetVar( StrRef(P4Tag::v_toFile), i ); matchIndex = client->GetVar( StrRef(P4Tag::v_index), i ); break; // doesn't get any better } } delete f; if( matchFile && matchIndex ) { client->SetVar( P4Tag::v_toFile, matchFile ); client->SetVar( P4Tag::v_index, matchIndex ); } client->Confirm( confirm ); } void clientOpenMatch( Client *client, ClientFile *f, Error *e ) { // Follow on from clientOpenFile, not called by server directly. // Grab RPC vars and attach them to the file handle so that // clientCloseMatch can use them for N-way diffing. StrPtr *fromFile = client->GetVar( P4Tag::v_fromFile, e ); StrPtr *key = client->GetVar( P4Tag::v_key, e ); StrPtr *flags = client->GetVar( P4Tag::v_diffFlags ); if( e->Test() ) return; f->matchDict = new StrBufDict; f->matchDict->SetVar( P4Tag::v_fromFile, fromFile ); f->matchDict->SetVar( P4Tag::v_key, key ); if( flags ) f->matchDict->SetVar( P4Tag::v_diffFlags, flags ); for( int i = 0 ; ; i++ ) { StrPtr *index = client->GetVar( StrRef( P4Tag::v_index ), i ); StrPtr *file = client->GetVar( StrRef( P4Tag::v_toFile ), i ); if( !index || !file ) break; f->matchDict->SetVar( StrRef( P4Tag::v_index ), i, *index ); f->matchDict->SetVar( StrRef( P4Tag::v_toFile ), i, *file ); } } void clientCloseMatch( Client *client, ClientFile *f1, Error *e ) { // Follow on from clientCloseFile, not called by server directly. // Compare temp file to existing client files. Figure out the // best match, along with a quantitative measure of how good // the match was (lines matched vs total lines). Stash it // in the handle so clientAckMatch can report it back. if( !f1->matchDict ) { e->Set( MsgSupp::NoParm ) << "clientCloseMatch"; return; } StrPtr *fname; FileSys *f2 = 0; DiffFlags flags; if( StrPtr* diffFlags = f1->matchDict->GetVar( P4Tag::v_diffFlags ) ) flags.Init( diffFlags ); int bestNum = 0; int bestSame = 0; int totalLines = 0; for( int i = 0 ; fname = f1->matchDict->GetVar( StrRef( P4Tag::v_toFile ), i ) ; i++ ) { delete f2; f2 = client->GetUi()->File( f1->file->GetType() ); f2->SetContentCharSetPriv( f1->file->GetContentCharSetPriv() ); f2->Set( *fname ); if( e->Test() || !f2 ) { // don't care e->Clear(); continue; } Sequence s1( f1->file, flags, e ); Sequence s2( f2, flags, e ); if ( e->Test() ) { // still don't care e->Clear(); continue; } DiffAnalyze diff( &s1, &s2 ); int same = 0; for( Snake *s = diff.GetSnake() ; s ; s = s->next ) { same += ( s->u - s->x ); if( s->u > totalLines ) totalLines = s->u; } if( same > bestSame ) { bestNum = i; bestSame = same; } } delete f2; f1->file->Close( e ); totalLines++; // snake lines start at zero if( bestSame ) { f1->matchDict->SetVar( P4Tag::v_index, f1->matchDict->GetVar( StrRef( P4Tag::v_index ), bestNum ) ); f1->matchDict->SetVar( P4Tag::v_toFile, f1->matchDict->GetVar( StrRef( P4Tag::v_toFile ), bestNum ) ); f1->matchDict->SetVar( P4Tag::v_lower, bestSame ); f1->matchDict->SetVar( P4Tag::v_upper, totalLines ); } // clientAckMatch will send this back } void clientAckMatch( Client *client, Error *e ) { StrPtr *handle = client->GetVar( P4Tag::v_handle, e ); StrPtr *confirm = client->GetVar( P4Tag::v_confirm, e ); if( e->Test() ) return; // Get handle. ClientFile *f = (ClientFile *)client->handles.Get( handle, e ); if( e->Test() ) return; // Fire everything back. StrPtr *fromFile = f->matchDict->GetVar( P4Tag::v_fromFile ); StrPtr *key = f->matchDict->GetVar( P4Tag::v_key ); StrPtr *toFile = f->matchDict->GetVar( P4Tag::v_toFile ); StrPtr *index = f->matchDict->GetVar( P4Tag::v_index ); StrPtr *lower = f->matchDict->GetVar( P4Tag::v_lower ); StrPtr *upper = f->matchDict->GetVar( P4Tag::v_upper ); if( fromFile && key ) { client->SetVar( P4Tag::v_fromFile, fromFile ); client->SetVar( P4Tag::v_key, key ); } else { e->Set( MsgSupp::NoParm ) << "fromFile/key"; return; } if( toFile && index && lower && upper ) { client->SetVar( P4Tag::v_toFile, toFile ); client->SetVar( P4Tag::v_index, index ); client->SetVar( P4Tag::v_lower, lower ); client->SetVar( P4Tag::v_upper, upper ); } client->Confirm( confirm ); delete f; }
25.211268
81
0.565053
gorlak
61d831db7ee8f53dd38f550ca9bb4112a528b20b
9,689
cc
C++
src/theia/vision/sfm/triangulation/triangulation_test.cc
nuernber/Theia
4bac771b09458a46c44619afa89498a13cd39999
[ "BSD-3-Clause" ]
1
2021-02-02T13:30:52.000Z
2021-02-02T13:30:52.000Z
src/theia/vision/sfm/triangulation/triangulation_test.cc
nuernber/Theia
4bac771b09458a46c44619afa89498a13cd39999
[ "BSD-3-Clause" ]
null
null
null
src/theia/vision/sfm/triangulation/triangulation_test.cc
nuernber/Theia
4bac771b09458a46c44619afa89498a13cd39999
[ "BSD-3-Clause" ]
1
2020-09-28T08:43:13.000Z
2020-09-28T08:43:13.000Z
// Copyright (C) 2013 The Regents of the University of California (Regents) // and Google, Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // * Neither the name of The Regents or University of California, Google, // nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Please contact the author of this library if you have any questions. // Author: Chris Sweeney (cmsweeney@cs.ucsb.edu), John Flynn (jflynn@google.com) #include <Eigen/Core> #include <Eigen/Geometry> #include <glog/logging.h> #include <vector> #include "gtest/gtest.h" #include "theia/math/util.h" #include "theia/test/benchmark.h" #include "theia/util/random.h" #include "theia/util/util.h" #include "theia/vision/sfm/triangulation/triangulation.h" #include "theia/vision/sfm/pose/util.h" namespace theia { using Eigen::MatrixXd; using Eigen::Matrix3d; using Eigen::Quaterniond; using Eigen::Vector2d; using Eigen::Vector3d; using Eigen::Vector4d; double ReprojectionError(const TransformationMatrix& pose, const Vector3d& world_point, const Vector2d& image_point) { const Vector2d reprojected_point = (pose * world_point).hnormalized(); const double sq_reproj_error = (reprojected_point - image_point).squaredNorm(); return sq_reproj_error; } void TestTriangulationBasic(const Vector3d& point_3d, const Quaterniond& rel_rotation, const Vector3d& rel_translation, const double projection_noise, const double max_reprojection_error) { InitRandomGenerator(); TransformationMatrix pose_left = TransformationMatrix::Identity(); TransformationMatrix pose_right = TransformationMatrixFromRt( rel_rotation.toRotationMatrix(), rel_translation); // Reproject point into both image 2, assume image 1 is identity rotation at // the origin. Vector2d image_point_1 = (pose_left * point_3d).hnormalized(); Vector2d image_point_2 = (pose_right * point_3d).hnormalized(); // Add projection noise if required. if (projection_noise) { AddNoiseToProjection(projection_noise, &image_point_1); AddNoiseToProjection(projection_noise, &image_point_2); } // Triangulate. Vector3d triangulated_point; EXPECT_TRUE(Triangulate(pose_left.matrix(), pose_right.matrix(), image_point_1, image_point_2, &triangulated_point)); // Check the reprojection error. EXPECT_LE( ReprojectionError(pose_left, triangulated_point, image_point_1), max_reprojection_error); EXPECT_LE( ReprojectionError(pose_right, triangulated_point, image_point_2), max_reprojection_error); } void TestTriangulationManyPoints(const double projection_noise, const double max_reprojection_error) { using Eigen::AngleAxisd; static const int num_views = 8; // Sets some test rotations and translations. static const Quaterniond kRotations[num_views] = { Quaterniond(AngleAxisd(Radians(7.0), Vector3d(0.0, 0.0, 1.0).normalized())), Quaterniond( AngleAxisd(Radians(12.0), Vector3d(0.0, 1.0, 0.0).normalized())), Quaterniond( AngleAxisd(Radians(15.0), Vector3d(1.0, 0.0, 0.0).normalized())), Quaterniond( AngleAxisd(Radians(20.0), Vector3d(1.0, 0.0, 1.0).normalized())), Quaterniond( AngleAxisd(Radians(11.0), Vector3d(0.0, 1.0, 1.0).normalized())), Quaterniond(AngleAxisd(Radians(0.0), Vector3d(1.0, 1.0, 1.0).normalized())), Quaterniond(AngleAxisd(Radians(5.0), Vector3d(0.0, 1.0, 1.0).normalized())), Quaterniond(AngleAxisd(Radians(0.0), Vector3d(1.0, 1.0, 1.0).normalized())) }; static const Vector3d kTranslations[num_views] = { Vector3d(1.0, 1.0, 1.0), Vector3d(3.0, 2.0, 13.0), Vector3d(4.0, 5.0, 11.0), Vector3d(1.0, 2.0, 15.0), Vector3d(3.0, 1.5, 91.0), Vector3d(1.0, 7.0, 11.0), Vector3d(0.0, 0.0, 0.0), // Tests no translation. Vector3d(0.0, 0.0, 0.0) // Tests no translation and no rotation. }; // Set up model points. static const double kTestPoints[][3] = { { -1.62, -2.99, 6.12 }, { 4.42, -1.53, 9.83 }, { 1.45, -0.59, 5.29 }, { 1.89, -1.10, 8.22 }, { -0.21, 2.38, 5.63 }, { 0.61, -0.97, 7.49 }, { 0.48, 0.70, 8.94 }, { 1.65, -2.56, 8.63 }, { 2.44, -0.20, 7.78 }, { 2.84, -2.58, 7.35 }, { -1.35, -2.84, 7.33 }, { -0.42, 1.54, 8.86 }, { 2.56, 1.72, 7.86 }, { 1.75, -1.39, 5.73 }, { 2.08, -3.91, 8.37 }, { -0.91, 1.36, 9.16 }, { 2.84, 1.54, 8.74 }, { -1.01, 3.02, 8.18 }, { -3.73, -0.62, 7.81 }, { -2.98, -1.88, 6.23 }, { 2.39, -0.19, 6.47 }, { -0.63, -1.05, 7.11 }, { -1.76, -0.55, 5.18 }, { -3.19, 3.27, 8.18 }, { 0.31, -2.77, 7.54 }, { 0.54, -3.77, 9.77 }, }; // Set up pose matrices. std::vector<ProjectionMatrix> poses(num_views); for (int i = 0; i < num_views; i++) { poses[i] = TransformationMatrixFromRt(kRotations[i].toRotationMatrix(), kTranslations[i]).matrix(); } for (int j = 0; j < ARRAYSIZE(kTestPoints); j++) { // Reproject model point into the images. std::vector<Vector2d> image_points(num_views); const Vector3d model_point(kTestPoints[j][0], kTestPoints[j][1], kTestPoints[j][2]); for (int i = 0; i < num_views; i++) { image_points[i] = (poses[i] * model_point.homogeneous()).eval().hnormalized(); } // Add projection noise if required. if (projection_noise) { for (int i = 0; i < num_views; i++) { AddNoiseToProjection(projection_noise, &image_points[i]); } } Vector3d triangulated_point; ASSERT_TRUE(TriangulateNView(poses, image_points, &triangulated_point)); // Check the reprojection error. for (int i = 0; i < num_views; i++) { EXPECT_LE(ReprojectionError(TransformationMatrix(poses[i]), triangulated_point, image_points[i]), max_reprojection_error); } } } TEST(Triangluation, BasicTest) { static const double kProjectionNoise = 0.0; static const double kReprojectionTolerance = 1e-12; // Set up model points. const Vector3d points_3d[2] = { Vector3d(5.0, 20.0, 23.0), Vector3d(-6.0, 16.0, 33.0) }; // Set up rotations. const Quaterniond kRotation(Eigen::AngleAxisd(0.15, Vector3d(0.0, 1.0, 0.0))); // Set up translations. const Vector3d kTranslation(-3.0, 1.5, 11.0); // Run the test. for (int i = 0; i < 2; i++) { TestTriangulationBasic(points_3d[i], kRotation, kTranslation, kProjectionNoise, kReprojectionTolerance); } } TEST(Triangluation, NoiseTest) { static const double kProjectionNoise = 1.0 / 512.0; static const double kReprojectionTolerance = 1e-5; // Set up model points. const Vector3d points_3d[2] = { Vector3d(5.0, 20.0, 23.0), Vector3d(-6.0, 16.0, 33.0) }; // Set up rotations. const Quaterniond kRotation(Eigen::AngleAxisd(0.15, Vector3d(0.0, 1.0, 0.0))); // Set up translations. const Vector3d kTranslation(-3.0, 1.5, 11.0); // Run the test. for (int i = 0; i < 2; i++) { TestTriangulationBasic(points_3d[i], kRotation, kTranslation, kProjectionNoise, kReprojectionTolerance); } } TEST(TriangluationNView, BasicTest) { static const double kProjectionNoise = 0.0; static const double kReprojectionTolerance = 1e-12; // Run the test. TestTriangulationManyPoints(kProjectionNoise, kReprojectionTolerance); } TEST(TriangluationNView, NoiseTest) { static const double kProjectionNoise = 1.0 / 512.0; static const double kReprojectionTolerance = 5e-4; // Run the test. TestTriangulationManyPoints(kProjectionNoise, kReprojectionTolerance); } BENCHMARK(TriangulationNView, Benchmark, 100, 1000) { static const double kProjectionNoise = 0.0; static const double kReprojectionTolerance = 1e-12; // Run the test. TestTriangulationManyPoints(kProjectionNoise, kReprojectionTolerance); } } // namespace theia
37.554264
80
0.647745
nuernber
61d893f82a7bea7717d41b3c2b90fb8f05a81c68
2,882
cpp
C++
source/editor/gui/Player/PInventory.cpp
Slattz/NLTK
b4e687c329ac4820a02fd45ce13d8afdddd26ef3
[ "MIT" ]
19
2018-07-26T10:41:16.000Z
2021-12-31T00:09:40.000Z
source/editor/gui/Player/PInventory.cpp
Slattz/NLTK
b4e687c329ac4820a02fd45ce13d8afdddd26ef3
[ "MIT" ]
4
2019-03-29T04:12:38.000Z
2019-05-16T18:57:25.000Z
source/editor/gui/Player/PInventory.cpp
Slattz/NLTK
b4e687c329ac4820a02fd45ce13d8afdddd26ef3
[ "MIT" ]
5
2018-07-14T21:43:56.000Z
2020-12-11T19:46:49.000Z
#include <3ds.h> #include <string> #include <citro2d.h> #include "CTRFont.hpp" #include "gfx.h" #include "save.h" #include "item.h" #include "e_utils.h" #include "utils.h" #include "InputManager.h" #include "menus.h" #include "gui/PlayerMenu.hpp" static std::vector<std::pair<std::string, s32>> inventoryData; // TODO: I dislike this. Find someother way of doing. Perhaps an item container class? static void Draw_PlayerMenu_Inventory(void) { int x = 42; int y = 63; Editor::Player::Draw_PlayerMenuTop(); C2D_SceneBegin(bottom); for (int i = 0; i < 16; ++i) { if (i == 2) { x += 38 * 2; } if (i > 0 && (i == 4 || i % 10 == 0)) { y += 38; x = 42; } Item item = Save::Instance()->players[PlayerConfig.SelectedPlayer]->Pockets[i]; DrawSprite(Common_ss, ITEM_HOLE, x - 16, y - 16); if (inventoryData[i].second > -1) { DrawSprite(Items_ss, inventoryData[i].second, x, y); } x += 38; } InputManager::Instance()->DrawCursor(); C3D_FrameEnd(0); } void Editor::Player::Spawn_PlayerMenu_Inventory() { if (PlayerConfig.DrawingSubmenu) return; PlayerConfig.DrawingSubmenu = true; inventoryData = load_player_invitems(PlayerConfig.SelectedPlayer); while (aptMainLoop()) { checkIfCardInserted(); Draw_PlayerMenu_Inventory(); InputManager::Instance()->RefreshInput(); PlayerConfig.LColor = PlayerConfig.RColor = COLOR_GREY; if (InputManager::Instance()->IsButtonDown(KEY_B)) break; if (InputManager::Instance()->IsButtonHeld(KEY_R)) PlayerConfig.RColor = COLOR_WHITE; if (InputManager::Instance()->IsButtonHeld(KEY_L)) PlayerConfig.LColor = COLOR_WHITE; if (InputManager::Instance()->IsButtonDown(KEY_R)) { while (true) { PlayerConfig.SelectedPlayer++; if (PlayerConfig.SelectedPlayer > 3) PlayerConfig.SelectedPlayer = 0; if (Save::Instance()->players[PlayerConfig.SelectedPlayer]->Exists()) { break; } } inventoryData = load_player_invitems(PlayerConfig.SelectedPlayer); } if (InputManager::Instance()->IsButtonDown(KEY_L)) { while (true) { PlayerConfig.SelectedPlayer--; if (PlayerConfig.SelectedPlayer < 0) PlayerConfig.SelectedPlayer = 3; if (Save::Instance()->players[PlayerConfig.SelectedPlayer]->Exists()) { break; } } inventoryData = load_player_invitems(PlayerConfig.SelectedPlayer); } } PlayerConfig.DrawingSubmenu = false; }
26.2
149
0.568008
Slattz
61d905fc66d11a428214bb4eac8d911568cfc420
4,873
cc
C++
node_modules/opencv4nodejs/cc/modules/features2d/detectors/MSERDetector.cc
osman-demirci/digital-guard-app-ipcamera
397a105d34194e2ce1ab7a31f34d03631a316b44
[ "Apache-2.0" ]
1
2020-12-01T10:15:31.000Z
2020-12-01T10:15:31.000Z
node_modules/opencv4nodejs/cc/modules/features2d/detectors/MSERDetector.cc
osman-demirci/digital-guard-app-ipcamera
397a105d34194e2ce1ab7a31f34d03631a316b44
[ "Apache-2.0" ]
null
null
null
node_modules/opencv4nodejs/cc/modules/features2d/detectors/MSERDetector.cc
osman-demirci/digital-guard-app-ipcamera
397a105d34194e2ce1ab7a31f34d03631a316b44
[ "Apache-2.0" ]
null
null
null
#include "MSERDetector.h" #include "Rect.h" #include "Point.h" Nan::Persistent<v8::FunctionTemplate> MSERDetector::constructor; NAN_MODULE_INIT(MSERDetector::Init) { v8::Local<v8::FunctionTemplate> ctor = Nan::New<v8::FunctionTemplate>(MSERDetector::New); v8::Local<v8::ObjectTemplate> instanceTemplate = ctor->InstanceTemplate(); FeatureDetector::Init(ctor); constructor.Reset(ctor); ctor->SetClassName(Nan::New("MSERDetector").ToLocalChecked()); instanceTemplate->SetInternalFieldCount(1); Nan::SetPrototypeMethod(ctor, "detectRegions", MSERDetector::DetectRegions); Nan::SetPrototypeMethod(ctor, "detectRegionsAsync", MSERDetector::DetectRegionsAsync); Nan::SetAccessor(instanceTemplate, Nan::New("delta").ToLocalChecked(), MSERDetector::GetDelta); Nan::SetAccessor(instanceTemplate, Nan::New("minArea").ToLocalChecked(), MSERDetector::GetMinArea); Nan::SetAccessor(instanceTemplate, Nan::New("maxArea").ToLocalChecked(), MSERDetector::GetMaxArea); Nan::SetAccessor(instanceTemplate, Nan::New("maxVariation").ToLocalChecked(), MSERDetector::GetMaxVariation); Nan::SetAccessor(instanceTemplate, Nan::New("minDiversity").ToLocalChecked(), MSERDetector::GetMinDiversity); Nan::SetAccessor(instanceTemplate, Nan::New("maxEvolution").ToLocalChecked(), MSERDetector::GetMaxEvolution); Nan::SetAccessor(instanceTemplate, Nan::New("areaThreshold").ToLocalChecked(), MSERDetector::GetAreaThreshold); Nan::SetAccessor(instanceTemplate, Nan::New("minMargin").ToLocalChecked(), MSERDetector::GetMinMargin); Nan::SetAccessor(instanceTemplate, Nan::New("edgeBlurSize").ToLocalChecked(), MSERDetector::GetEdgeBlurSize); target->Set(Nan::New("MSERDetector").ToLocalChecked(), ctor->GetFunction()); }; NAN_METHOD(MSERDetector::New) { FF_ASSERT_CONSTRUCT_CALL(MSERDetector); FF_METHOD_CONTEXT("MSERDetector::New"); MSERDetector* self = new MSERDetector(); // optional args bool hasOptArgsObj = FF_HAS_ARG(0) && info[0]->IsObject(); FF_OBJ optArgs = hasOptArgsObj ? info[0]->ToObject(Nan::GetCurrentContext()).ToLocalChecked() : FF_NEW_OBJ(); FF_GET_INT_IFDEF(optArgs, self->delta, "delta", 5); FF_GET_INT_IFDEF(optArgs, self->minArea, "minArea", 60); FF_GET_INT_IFDEF(optArgs, self->maxArea, "maxArea", 14400); FF_GET_NUMBER_IFDEF(optArgs, self->maxVariation, "maxVariation", 0.25); FF_GET_NUMBER_IFDEF(optArgs, self->minDiversity, "minDiversity", 0.2); FF_GET_INT_IFDEF(optArgs, self->maxEvolution, "maxEvolution", 200); FF_GET_NUMBER_IFDEF(optArgs, self->areaThreshold, "areaThreshold", 1.01); FF_GET_NUMBER_IFDEF(optArgs, self->minMargin, "minMargin", 0.003); FF_GET_INT_IFDEF(optArgs, self->edgeBlurSize, "edgeBlurSize", 5); if (!hasOptArgsObj) { FF_ARG_INT_IFDEF(0, self->delta, self->delta); FF_ARG_INT_IFDEF(1, self->minArea, self->minArea); FF_ARG_INT_IFDEF(2, self->maxArea, self->maxArea); FF_ARG_NUMBER_IFDEF(3, self->maxVariation, self->maxVariation); FF_ARG_NUMBER_IFDEF(4, self->minDiversity, self->minDiversity); FF_ARG_INT_IFDEF(5, self->maxEvolution, self->maxEvolution); FF_ARG_NUMBER_IFDEF(6, self->areaThreshold, self->areaThreshold); FF_ARG_NUMBER_IFDEF(7, self->minMargin, self->minMargin); FF_ARG_INT_IFDEF(8, self->edgeBlurSize, self->edgeBlurSize); } self->Wrap(info.Holder()); self->detector = cv::MSER::create(self->delta, self->minArea, self->maxArea, self->maxVariation, self->minDiversity, self->maxEvolution, self->areaThreshold, self->minMargin, self->edgeBlurSize); FF_RETURN(info.Holder()); } struct DetectRegionsWorker : public CatchCvExceptionWorker { public: cv::Ptr<cv::MSER> det; DetectRegionsWorker( MSERDetector *mser){ this->det = mser->getMSERDetector(); } cv::Mat img; std::vector<std::vector<cv::Point> > regions; std::vector<cv::Rect> mser_bbox; std::string executeCatchCvExceptionWorker() { det->detectRegions(img, regions, mser_bbox); return ""; } bool unwrapRequiredArgs(Nan::NAN_METHOD_ARGS_TYPE info) { // we only need input image return Mat::Converter::arg(0, &img, info); } FF_VAL getReturnValue() { FF_OBJ ret = FF_NEW_OBJ(); Nan::Set(ret, FF_NEW_STRING("msers"), ObjectArrayOfArraysConverter<Point2, cv::Point>::wrap(regions)); Nan::Set(ret, FF_NEW_STRING("bboxes"), ObjectArrayConverter<Rect, cv::Rect>::wrap(mser_bbox)); return ret; } }; NAN_METHOD(MSERDetector::DetectRegions) { FF::SyncBinding( std::make_shared<DetectRegionsWorker>(FF_UNWRAP(info.This(), MSERDetector)), "MSERDetector::DetectRegions", info ); } NAN_METHOD(MSERDetector::DetectRegionsAsync) { FF::AsyncBinding( std::make_shared<DetectRegionsWorker>(FF_UNWRAP(info.This(), MSERDetector)), "MSERDetector::DetectRegionsAsync", info ); }
42.373913
113
0.725631
osman-demirci
61dc979c2a7355b7c9faefe9d9e47a9137a1fe9a
18,005
cpp
C++
src/tag.cpp
sarthon/herbstluftwm
b6925946bed73b7b9a74d84e5ed47209ee669eca
[ "BSD-2-Clause-FreeBSD" ]
4
2019-07-30T22:32:38.000Z
2019-11-12T04:30:11.000Z
src/tag.cpp
calvinhenderson/herbstluftwm
b6925946bed73b7b9a74d84e5ed47209ee669eca
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/tag.cpp
calvinhenderson/herbstluftwm
b6925946bed73b7b9a74d84e5ed47209ee669eca
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
/** Copyright 2011-2013 Thorsten Wißmann. All rights reserved. * * This software is licensed under the "Simplified BSD License". * See LICENSE for details */ #include <assert.h> #include <string.h> #include <stdio.h> #include "tag.h" #include "globals.h" #include "clientlist.h" #include "ipc-protocol.h" #include "utils.h" #include "hook.h" #include "layout.h" #include "stack.h" #include "ewmh.h" #include "monitor.h" #include "settings.h" static GArray* g_tags; // Array of HSTag* static bool g_tag_flags_dirty = true; static HSObject* g_tag_object; static HSObject* g_tag_by_name; static int* g_raise_on_focus_temporarily; static int tag_rename(HSTag* tag, char* name, GString* output); void tag_init() { g_tags = g_array_new(false, false, sizeof(HSTag*)); g_raise_on_focus_temporarily = &(settings_find("raise_on_focus_temporarily") ->value.i); g_tag_object = hsobject_create_and_link(hsobject_root(), "tags"); HSAttribute attributes[] = { ATTRIBUTE("count", g_tags->len, ATTR_READ_ONLY), ATTRIBUTE_LAST, }; hsobject_set_attributes(g_tag_object, attributes); g_tag_by_name = hsobject_create_and_link(g_tag_object, "by-name"); } static void tag_free(HSTag* tag) { if (tag->frame) { HSClient** buf; size_t count; frame_destroy(tag->frame, &buf, &count); if (count) { g_free(buf); } } stack_destroy(tag->stack); hsobject_unlink_and_destroy(g_tag_by_name, tag->object); g_string_free(tag->name, true); g_string_free(tag->display_name, true); g_free(tag); } void tag_destroy() { int i; for (i = 0; i < g_tags->len; i++) { HSTag* tag = g_array_index(g_tags, HSTag*, i); tag_free(tag); } g_array_free(g_tags, true); hsobject_unlink_and_destroy(g_tag_object, g_tag_by_name); hsobject_unlink_and_destroy(hsobject_root(), g_tag_object); } int tag_get_count() { return g_tags->len; } HSTag* find_tag(const char* name) { int i; for (i = 0; i < g_tags->len; i++) { if (!strcmp(g_array_index(g_tags, HSTag*, i)->name->str, name)) { return g_array_index(g_tags, HSTag*, i); } } return NULL; } int tag_index_of(HSTag* tag) { for (int i = 0; i < g_tags->len; i++) { if (g_array_index(g_tags, HSTag*, i) == tag) { return i; } } return -1; } HSTag* get_tag_by_index(int index) { if (index < 0 || index >= g_tags->len) { return NULL; } return g_array_index(g_tags, HSTag*, index); } HSTag* get_tag_by_index_str(char* index_str, bool skip_visible_tags) { int index = atoi(index_str); // index must be treated relative, if it's first char is + or - bool is_relative = array_find("+-", 2, sizeof(char), &index_str[0]) >= 0; HSMonitor* monitor = get_current_monitor(); if (is_relative) { int current = tag_index_of(monitor->tag); int delta = index; index = delta + current; // ensure index is valid index = MOD(index, g_tags->len); if (skip_visible_tags) { HSTag* tag = g_array_index(g_tags, HSTag*, index); for (int i = 0; find_monitor_with_tag(tag); i++) { if (i >= g_tags->len) { // if we tried each tag then there is no invisible tag return NULL; } index += delta; index = MOD(index, g_tags->len); tag = g_array_index(g_tags, HSTag*, index); } } } else { // if it is absolute, then check index if (index < 0 || index >= g_tags->len) { HSDebug("invalid tag index %d\n", index); return NULL; } } return g_array_index(g_tags, HSTag*, index); } HSTag* find_unused_tag() { for (int i = 0; i < g_tags->len; i++) { if (!find_monitor_with_tag(g_array_index(g_tags, HSTag*, i))) { return g_array_index(g_tags, HSTag*, i); } } return NULL; } static GString* tag_attr_floating(HSAttribute* attr) { HSTag* tag = container_of(attr->value.b, HSTag, floating); HSMonitor* m = find_monitor_with_tag(tag); if (m != NULL) { monitor_apply_layout(m); } return NULL; } static GString* tag_attr_name(HSAttribute* attr) { HSTag* tag = container_of(attr->value.str, HSTag, display_name); GString* error = g_string_new(""); int status = tag_rename(tag, tag->display_name->str, error); if (status == 0) { g_string_free(error, true); return NULL; } else { return error; } } static void sum_up_clientframes(HSFrame* frame, void* data) { if (frame->type == TYPE_CLIENTS) { (*(int*)data)++; } } static int tag_attr_frame_count(void* data) { HSTag* tag = (HSTag*) data; int i = 0; frame_do_recursive_data(tag->frame, sum_up_clientframes, 0, &i); return i; } static void sum_up_clients(HSFrame* frame, void* data) { if (frame->type == TYPE_CLIENTS) { *(int*)data += frame->content.clients.count; } } static int tag_attr_client_count(void* data) { HSTag* tag = (HSTag*) data; int i = 0; frame_do_recursive_data(tag->frame, sum_up_clients, 0, &i); return i; } static int tag_attr_curframe_windex(void* data) { HSTag* tag = (HSTag*) data; HSFrame* frame = frame_current_selection_below(tag->frame); return frame->content.clients.selection; } static int tag_attr_curframe_wcount(void* data) { HSTag* tag = (HSTag*) data; HSFrame* frame = frame_current_selection_below(tag->frame); return frame->content.clients.count; } static int tag_attr_index(void* data) { HSTag* tag = (HSTag*) data; return tag_index_of(tag); } static void tag_unlink_id_object(HSTag* tag, void* data) { (void)data; hsobject_unlink(g_tag_object, tag->object); } static void tag_link_id_object(HSTag* tag, void* data) { (void)data; GString* index_str = g_string_new(""); int index = tag_index_of(tag); g_string_printf(index_str, "%d", index); hsobject_link(g_tag_object, tag->object, index_str->str); g_string_free(index_str, true); } HSTag* add_tag(const char* name) { HSTag* find_result = find_tag(name); if (find_result) { // nothing to do return find_result; } HSTag* tag = g_new0(HSTag, 1); tag->stack = stack_create(); tag->frame = frame_create_empty(NULL, tag); tag->name = g_string_new(name); tag->display_name = g_string_new(name); tag->floating = false; g_array_append_val(g_tags, tag); // create object tag->object = hsobject_create_and_link(g_tag_by_name, name); tag->object->data = tag; HSAttribute attributes[] = { ATTRIBUTE_STRING("name", tag->display_name, tag_attr_name), ATTRIBUTE_BOOL( "floating", tag->floating, tag_attr_floating), ATTRIBUTE_CUSTOM_INT("index", tag_attr_index, ATTR_READ_ONLY), ATTRIBUTE_CUSTOM_INT("frame_count", tag_attr_frame_count, ATTR_READ_ONLY), ATTRIBUTE_CUSTOM_INT("client_count", tag_attr_client_count, ATTR_READ_ONLY), ATTRIBUTE_CUSTOM_INT("curframe_windex",tag_attr_curframe_windex, ATTR_READ_ONLY), ATTRIBUTE_CUSTOM_INT("curframe_wcount",tag_attr_curframe_wcount, ATTR_READ_ONLY), ATTRIBUTE_LAST, }; hsobject_set_attributes(tag->object, attributes); tag_link_id_object(tag, NULL); ewmh_update_desktops(); ewmh_update_desktop_names(); tag_set_flags_dirty(); return tag; } int tag_add_command(int argc, char** argv, GString* output) { if (argc < 2) { return HERBST_NEED_MORE_ARGS; } if (!strcmp("", argv[1])) { g_string_append_printf(output, "%s: An empty tag name is not permitted\n", argv[0]); return HERBST_INVALID_ARGUMENT; } HSTag* tag = add_tag(argv[1]); hook_emit_list("tag_added", tag->name->str, NULL); return 0; } static int tag_rename(HSTag* tag, char* name, GString* output) { if (find_tag(name)) { g_string_append_printf(output, "Error: Tag \"%s\" already exists\n", name); return HERBST_TAG_IN_USE; } hsobject_link_rename(g_tag_by_name, tag->name->str, name); g_string_assign(tag->name, name); g_string_assign(tag->display_name, name); ewmh_update_desktop_names(); hook_emit_list("tag_renamed", tag->name->str, NULL); return 0; } int tag_rename_command(int argc, char** argv, GString* output) { if (argc < 3) { return HERBST_NEED_MORE_ARGS; } if (!strcmp("", argv[2])) { g_string_append_printf(output, "%s: An empty tag name is not permitted\n", argv[0]); return HERBST_INVALID_ARGUMENT; } HSTag* tag = find_tag(argv[1]); if (!tag) { g_string_append_printf(output, "%s: Tag \"%s\" not found\n", argv[0], argv[1]); return HERBST_INVALID_ARGUMENT; } return tag_rename(tag, argv[2], output); } static void client_update_tag(void* key, void* client_void, void* data) { (void) key; (void) data; HSClient* client = (HSClient*)client_void; if (client) { ewmh_window_update_tag(client->window, client->tag); } } int tag_remove_command(int argc, char** argv, GString* output) { // usage: remove TAG [TARGET] // it removes an TAG and moves all its wins to TARGET // if no TARGET is given, current tag is used if (argc < 2) { return HERBST_NEED_MORE_ARGS; } HSTag* tag = find_tag(argv[1]); HSTag* target = (argc >= 3) ? find_tag(argv[2]) : get_current_monitor()->tag; if (!tag) { g_string_append_printf(output, "%s: Tag \"%s\" not found\n", argv[0], argv[1]); return HERBST_INVALID_ARGUMENT; } else if (!target) { g_string_append_printf(output, "%s: Tag \"%s\" not found\n", argv[0], argv[2]); return HERBST_INVALID_ARGUMENT; } else if (tag == target) { g_string_append_printf(output, "%s: Cannot merge tag \"%s\" into itself\n", argv[0], argv[1]); return HERBST_INVALID_ARGUMENT; } if (find_monitor_with_tag(tag)) { g_string_append_printf(output, "%s: Cannot merge the currently viewed tag\n", argv[0]); return HERBST_TAG_IN_USE; } // prevent dangling tag_previous pointers all_monitors_replace_previous_tag(tag, target); // save all these windows HSClient** buf; size_t count; frame_destroy(tag->frame, &buf, &count); tag->frame = NULL; int i; for (i = 0; i < count; i++) { HSClient* client = buf[i]; stack_remove_slice(client->tag->stack, client->slice); client->tag = target; stack_insert_slice(client->tag->stack, client->slice); ewmh_window_update_tag(client->window, client->tag); frame_insert_client(target->frame, buf[i]); } HSMonitor* monitor_target = find_monitor_with_tag(target); if (monitor_target) { // if target monitor is viewed, then show windows monitor_apply_layout(monitor_target); for (i = 0; i < count; i++) { client_set_visible(buf[i], true); } } g_free(buf); tag_foreach(tag_unlink_id_object, NULL); // remove tag char* oldname = g_strdup(tag->name->str); tag_free(tag); for (i = 0; i < g_tags->len; i++) { if (g_array_index(g_tags, HSTag*, i) == tag) { g_array_remove_index(g_tags, i); break; } } ewmh_update_current_desktop(); ewmh_update_desktops(); ewmh_update_desktop_names(); clientlist_foreach(client_update_tag, NULL); tag_update_focus_objects(); tag_set_flags_dirty(); hook_emit_list("tag_removed", oldname, target->name->str, NULL); g_free(oldname); tag_foreach(tag_link_id_object, NULL); return 0; } int tag_set_floating_command(int argc, char** argv, GString* output) { // usage: floating [[tag] on|off|toggle] HSTag* tag = get_current_monitor()->tag; const char* action = (argc > 1) ? argv[1] : "toggle"; if (argc >= 3) { // if a tag is specified tag = find_tag(argv[1]); action = argv[2]; if (!tag) { g_string_append_printf(output, "%s: Tag \"%s\" not found\n", argv[0], argv[1]); return HERBST_INVALID_ARGUMENT; } } bool new_value = string_to_bool(action, tag->floating); if (!strcmp(action, "status")) { // just print status g_string_append(output, tag->floating ? "on" : "off"); } else { // assign new value and rearrange if needed tag->floating = new_value; HSMonitor* m = find_monitor_with_tag(tag); HSDebug("setting tag:%s->floating to %s\n", tag->name->str, tag->floating ? "on" : "off"); if (m != NULL) { monitor_apply_layout(m); } } return 0; } static void client_update_tag_flags(void* key, void* client_void, void* data) { (void) key; (void) data; HSClient* client = (HSClient*)client_void; if (client) { TAG_SET_FLAG(client->tag, TAG_FLAG_USED); if (client->urgent) { TAG_SET_FLAG(client->tag, TAG_FLAG_URGENT); } } } void tag_force_update_flags() { g_tag_flags_dirty = false; // unset all tags for (int i = 0; i < g_tags->len; i++) { g_array_index(g_tags, HSTag*, i)->flags = 0; } // update flags clientlist_foreach(client_update_tag_flags, NULL); } void tag_update_flags() { if (g_tag_flags_dirty) { tag_force_update_flags(); } } void tag_set_flags_dirty() { g_tag_flags_dirty = true; hook_emit_list("tag_flags", NULL); } void ensure_tags_are_available() { if (g_tags->len > 0) { // nothing to do return; } add_tag("default"); } HSTag* find_tag_with_toplevel_frame(HSFrame* frame) { int i; for (i = 0; i < g_tags->len; i++) { HSTag* m = g_array_index(g_tags, HSTag*, i); if (m->frame == frame) { return m; } } return NULL; } int tag_move_window_command(int argc, char** argv, GString* output) { if (argc < 2) { return HERBST_NEED_MORE_ARGS; } HSTag* target = find_tag(argv[1]); if (!target) { g_string_append_printf(output, "%s: Tag \"%s\" not found\n", argv[0], argv[1]); return HERBST_INVALID_ARGUMENT; } tag_move_focused_client(target); return 0; } int tag_move_window_by_index_command(int argc, char** argv, GString* output) { if (argc < 2) { return HERBST_NEED_MORE_ARGS; } bool skip_visible = false; if (argc >= 3 && !strcmp(argv[2], "--skip-visible")) { skip_visible = true; } HSTag* tag = get_tag_by_index_str(argv[1], skip_visible); if (!tag) { g_string_append_printf(output, "%s: Invalid index \"%s\"\n", argv[0], argv[1]); return HERBST_INVALID_ARGUMENT; } tag_move_focused_client(tag); return 0; } void tag_move_focused_client(HSTag* target) { HSClient* client = frame_focused_client(get_current_monitor()->tag->frame); if (client == 0) { // nothing to do return; } tag_move_client(client, target); } void tag_move_client(HSClient* client, HSTag* target) { HSTag* tag_source = client->tag; HSMonitor* monitor_source = find_monitor_with_tag(tag_source); if (tag_source == target) { // nothing to do return; } HSMonitor* monitor_target = find_monitor_with_tag(target); frame_remove_client(tag_source->frame, client); // insert window into target frame_insert_client(target->frame, client); // enfoce it to be focused on the target tag frame_focus_client(target->frame, client); stack_remove_slice(client->tag->stack, client->slice); client->tag = target; stack_insert_slice(client->tag->stack, client->slice); ewmh_window_update_tag(client->window, client->tag); // refresh things, hide things, layout it, and then show it if needed if (monitor_source && !monitor_target) { // window is moved to invisible tag // so hide it client_set_visible(client, false); } monitor_apply_layout(monitor_source); monitor_apply_layout(monitor_target); if (!monitor_source && monitor_target) { client_set_visible(client, true); } if (monitor_target == get_current_monitor()) { frame_focus_recursive(monitor_target->tag->frame); } else if (monitor_source == get_current_monitor()) { frame_focus_recursive(monitor_source->tag->frame); } tag_set_flags_dirty(); } void tag_update_focus_layer(HSTag* tag) { HSClient* focus = frame_focused_client(tag->frame); stack_clear_layer(tag->stack, LAYER_FOCUS); if (focus) { // enforce raise_on_focus_temporarily if there is at least one // fullscreen window or if the tag is in tiling mode if (!stack_is_layer_empty(tag->stack, LAYER_FULLSCREEN) || *g_raise_on_focus_temporarily || focus->tag->floating == false) { stack_slice_add_layer(tag->stack, focus->slice, LAYER_FOCUS); } } HSMonitor* monitor = find_monitor_with_tag(tag); if (monitor) { monitor_restack(monitor); } } void tag_foreach(void (*action)(HSTag*,void*), void* data) { for (int i = 0; i < g_tags->len; i++) { HSTag* tag = g_array_index(g_tags, HSTag*, i); action(tag, data); } } static void tag_update_focus_layer_helper(HSTag* tag, void* data) { (void) data; tag_update_focus_layer(tag); } void tag_update_each_focus_layer() { tag_foreach(tag_update_focus_layer_helper, NULL); } void tag_update_focus_objects() { hsobject_link(g_tag_object, get_current_monitor()->tag->object, "focus"); }
30.620748
98
0.624049
sarthon
61de8541ecc67347ddaddda0963e571c17e6c70c
133
cpp
C++
ProjectResolver.cpp
MCModMachine/Client
d52f47d30e9a46645697dae639a8c2eb85b6be5e
[ "MIT" ]
1
2016-08-17T10:17:09.000Z
2016-08-17T10:17:09.000Z
ProjectResolver.cpp
MCModMachine/Client
d52f47d30e9a46645697dae639a8c2eb85b6be5e
[ "MIT" ]
null
null
null
ProjectResolver.cpp
MCModMachine/Client
d52f47d30e9a46645697dae639a8c2eb85b6be5e
[ "MIT" ]
null
null
null
// // ProjectResolver.cpp // mcubed-client // // Created by Gaelan Bright Steele on 7/3/16. // // #include "ProjectResolver.hpp"
13.3
46
0.661654
MCModMachine
61e07c9646651fb073e527891cb89661f6f5ab11
2,809
cpp
C++
src/RenderProcessHandler.cpp
GPBeta/nc.js
859ab391930d3ac13f69312074ac2ecc65b8594a
[ "MIT" ]
105
2016-05-31T15:57:47.000Z
2022-03-04T07:08:45.000Z
src/RenderProcessHandler.cpp
GPBeta/nc.js
859ab391930d3ac13f69312074ac2ecc65b8594a
[ "MIT" ]
6
2016-06-23T02:36:17.000Z
2020-02-27T02:56:49.000Z
src/RenderProcessHandler.cpp
GPBeta/nc.js
859ab391930d3ac13f69312074ac2ecc65b8594a
[ "MIT" ]
32
2016-07-09T12:51:35.000Z
2022-01-11T07:41:12.000Z
/*************************************************************** * Name: RenderProcessHandler.cpp * Purpose: Codes for Node-CEF Render Process Handler Class * Author: Joshua GPBeta (studiocghibli@gmail.com) * Created: 2016-05-22 * Copyright: Studio GPBeta (www.gpbeta.com) * License: **************************************************************/ /// ============================================================================ /// declarations /// ============================================================================ /// ---------------------------------------------------------------------------- /// Headers /// ---------------------------------------------------------------------------- #include "ncjs/RenderProcessHandler.h" #include "ncjs/Core.h" #include "ncjs/Environment.h" #include "ncjs/constants.h" #include <include/cef_command_line.h> namespace ncjs { /// ---------------------------------------------------------------------------- /// variables /// ---------------------------------------------------------------------------- /// ============================================================================ /// implementation /// ============================================================================ void RenderProcessHandler::OnRenderThreadCreated(CefRefPtr<CefListValue> extra_info) { CefRefPtr<CefCommandLine> args = CefCommandLine::CreateCommandLine(); // retrieve application path args->SetProgram(CefCommandLine::GetGlobalCommandLine()->GetProgram()); OnNodeCefCreated(*args.get()); m_core.Initialize(args); } void RenderProcessHandler::OnWebKitInitialized() { Core::RegisterExtension(); } void RenderProcessHandler::OnContextReleased(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context) { // may also destroy environment object Environment::InvalidateContext(context); } void RenderProcessHandler::OnUncaughtException(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context, CefRefPtr<CefV8Exception> exception, CefRefPtr<CefV8StackTrace> stackTrace) { // works only if CefSettings::uncaught_exception_stack_size > 0 if (Environment* env = Environment::Get(context)) { CefRefPtr<CefV8Value> process = env->GetObject().process; CefRefPtr<CefV8Value> emit = process->GetValue(consts::str_emit); if (emit.get()) { CefV8ValueList args; args.push_back(CefV8Value::CreateString(consts::str_uncaught_except)); args.push_back(CefV8Value::CreateString(exception->GetMessage())); emit->ExecuteFunction(process, args); } } } } // ncjs
33.440476
85
0.49733
GPBeta
61eac8aa131cc6d476c979b93e162c0c1c23cdf4
513
hxx
C++
include/pqxx/internal/gates/connection-errorhandler.hxx
ash-j-f/libpqxx
0f0941c4fb04c56703ccacd567a27160a8a74b93
[ "BSD-3-Clause" ]
null
null
null
include/pqxx/internal/gates/connection-errorhandler.hxx
ash-j-f/libpqxx
0f0941c4fb04c56703ccacd567a27160a8a74b93
[ "BSD-3-Clause" ]
null
null
null
include/pqxx/internal/gates/connection-errorhandler.hxx
ash-j-f/libpqxx
0f0941c4fb04c56703ccacd567a27160a8a74b93
[ "BSD-3-Clause" ]
null
null
null
#include <pqxx/internal/callgate.hxx> namespace pqxx { class connection; class errorhandler; } namespace pqxx::internal::gate { class PQXX_PRIVATE connection_errorhandler : callgate<connection> { friend class pqxx::errorhandler; connection_errorhandler(reference x) : super(x) {} void register_errorhandler(errorhandler *h) { home().register_errorhandler(h); } void unregister_errorhandler(errorhandler *h) { home().unregister_errorhandler(h); } }; } // namespace pqxx::internal::gate
22.304348
65
0.74269
ash-j-f
61eb60da6bb7bdbeff7e85ee49cc68c93a27edb8
1,099
cpp
C++
test/2020.10.06/b/b.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
test/2020.10.06/b/b.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
test/2020.10.06/b/b.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <vector> const int N = 2e5 + 1e4; struct node { int id; int country, score; }; bool vis[N]; node a[N]; int main() { #ifdef woshiluo freopen( "b.in", "r", stdin ); freopen( "b.out", "w", stdout ); #endif int n; scanf( "%d", &n ); for( int i = 1; i <= n; i ++ ) { a[i].id = i; scanf( "%d%d", &a[i].country, &a[i].score ); } int p1 = 1, ans = 0; std::vector<node> coun[N]; for( int j = 1; j <= n; j ++ ) { node cur; cur.id = 0; scanf( "%d%d", &cur.country, &cur.score ); while( p1 <= n && a[p1].score <= cur.score ) { coun[0].push_back( a[p1] ); coun[ a[p1].country ].push_back( a[p1] ); p1 ++; } while( coun[ cur.country ].size() > 0 && vis[ coun[ cur.country ].back().id ] ) { coun[ cur.country ].pop_back(); } if( coun[ cur.country ].size() != 0 ) { vis[ coun[ cur.country ].back().id ] = true; coun[ cur.country ].pop_back(); } else { ans ++; // while( vis[ coun[0].back().id ] ) // coun[0].pop_back(); // vis[ coun[0].back().id ] = true; // coun[0].pop_back(); } } printf( "%d\n", ans ); }
19.981818
83
0.509554
woshiluo
61ebb0342ec7940dcfc768a68d71ff287df55500
6,192
cpp
C++
AssignmentProject/Player.cpp
VasilStamatov/GraphicsLearning
8cf5dc57fedd809066472e96c8182153a1fa54d9
[ "MIT" ]
null
null
null
AssignmentProject/Player.cpp
VasilStamatov/GraphicsLearning
8cf5dc57fedd809066472e96c8182153a1fa54d9
[ "MIT" ]
null
null
null
AssignmentProject/Player.cpp
VasilStamatov/GraphicsLearning
8cf5dc57fedd809066472e96c8182153a1fa54d9
[ "MIT" ]
null
null
null
#include "Player.h" #include "Box.h" #include <GameEngine/ResourceManager.h> #include <GameEngine\GameEngineErrors.h> #include <SDL/SDL.h> void Player::Init(b2World* _world, const glm::vec2& _position, const glm::vec2& _drawDims, glm::vec2& _collisionDims, GameEngine::ColorRGBA8 _color) { //set the member variables and initialize the capsule and texture GameEngine::GLTexture texture = GameEngine::ResourceManager::GetTexture("Assets/Char2/IDLE.png"); m_color = _color; m_drawDims = _drawDims; m_collisionDims = _collisionDims; m_capsule.Init(_world, _position, _collisionDims, 1.0f, 0.1f, true); m_texture.Init(texture, glm::ivec2(10, 1)); //hardcode some damage so it's not the default m_attackDamage = 0.50f; } void Player::Draw(GameEngine::SpriteBatch& _spriteBatch) { glm::vec4 destRect; //set the player destination rectangle b2Body* body = m_capsule.GetBody(); destRect.x = body->GetPosition().x - m_drawDims.x / 2.0f; destRect.y = body->GetPosition().y - m_capsule.GetDimensions().y / 2.0f; destRect.z = m_drawDims.x; destRect.w = m_drawDims.y; int tileIndex; int numTiles; float animSpeed = 0.2f; glm::vec2 velocity; velocity.x = body->GetLinearVelocity().x; velocity.y = body->GetLinearVelocity().y; //Calculate animation if (m_healthPoints <= 0.0f) { //dying GameEngine::GLTexture texture = GameEngine::ResourceManager::GetTexture("Assets/Char2/DYING.png"); m_texture.Init(texture, glm::ivec2(10, 1)); numTiles = 10; tileIndex = 0; if (m_moveState != PlayerMoveState::DYING) { m_moveState = PlayerMoveState::DYING; m_animTime = 0.0f; } } else { if (m_onGround) { if (abs(velocity.x) > 1.0f && ((velocity.x > 0 && m_direction > 0) || (velocity.x < 0 && m_direction < 0))) { //// is moving GameEngine::GLTexture texture = GameEngine::ResourceManager::GetTexture("Assets/Char2/RUN.png"); m_texture.Init(texture, glm::ivec2(8, 1)); numTiles = 8; tileIndex = 0; animSpeed = abs(velocity.x * 0.025f); if (m_moveState != PlayerMoveState::RUNNING) { m_moveState = PlayerMoveState::RUNNING; m_animTime = 0.0f; } } else { //standing GameEngine::GLTexture texture = GameEngine::ResourceManager::GetTexture("Assets/Char2/IDLE.png"); m_texture.Init(texture, glm::ivec2(10, 1)); numTiles = 10; tileIndex = 0; m_moveState = PlayerMoveState::STANDING; } } else { //jumping GameEngine::GLTexture texture = GameEngine::ResourceManager::GetTexture("Assets/Char2/JUMP.png"); m_texture.Init(texture, glm::ivec2(10, 1)); if (velocity.y < 0.0f) { //falling numTiles = 1; tileIndex = 7; m_moveState = PlayerMoveState::JUMPING; } else { //rising numTiles = 1; tileIndex = 2; m_moveState = PlayerMoveState::JUMPING; } } } //increment animation time m_animTime += animSpeed; // check for death if (m_animTime > numTiles && m_moveState == PlayerMoveState::DYING) { m_isDead = true; } //apply animation tileIndex = tileIndex + (int)m_animTime % numTiles; //get the uv coordinates from the tile index glm::vec4 uvRect = m_texture.GetUVs(tileIndex); //check direction if (m_direction == -1) { uvRect.x += 1.0f / m_texture.dims.x; uvRect.z *= -1; } //Draw the sprite _spriteBatch.Draw(destRect, uvRect, m_texture.texture.id, 1.0f, m_color, body->GetAngle()); } void Player::Update(GameEngine::InputManager& _inputManager) { //check if the player is alive if (m_healthPoints > 0.0f) { b2Body* body = m_capsule.GetBody(); if (_inputManager.IsKeyPressed(SDLK_SPACE) && m_maxShots > 0) { //player shoot m_playerShot = true; m_maxShots--; //shooting sound GameEngine::SoundEffect soundEffect = m_audio.LoadSoundEffect("Sound/Laser_Shoot6.ogg"); soundEffect.Play(); } if (_inputManager.IsKeyDown(SDLK_a)) { //walking left body->ApplyForceToCenter(b2Vec2(-100.0f, 0.0f), true); m_direction = -1; } else if (_inputManager.IsKeyDown(SDLK_d)) { //walking right body->ApplyForceToCenter(b2Vec2(100.0f, 0.0f), true); m_direction = 1; } else { //drifting body->SetLinearVelocity(b2Vec2(body->GetLinearVelocity().x * 0.95f, body->GetLinearVelocity().y)); } //Control the max possible speed const float MAX_SPEED = 10.0f; if (body->GetLinearVelocity().x < -MAX_SPEED) { body->SetLinearVelocity(b2Vec2(-MAX_SPEED, body->GetLinearVelocity().y)); } else if (body->GetLinearVelocity().x > MAX_SPEED) { body->SetLinearVelocity(b2Vec2(MAX_SPEED, body->GetLinearVelocity().y)); } //loop through all contact points m_onGround = false; for (b2ContactEdge* ce = body->GetContactList(); ce != nullptr; ce = ce->next) { b2Contact* c = ce->contact; if (c->IsTouching()) { b2WorldManifold manifold; c->GetWorldManifold(&manifold); //check if the points are below bool below = false; for (int i = 0; i < b2_maxManifoldPoints; i++) { if (manifold.points[i].y < body->GetPosition().y - m_capsule.GetDimensions().y / 2.0f + m_capsule.GetDimensions().x / 2.0f + 0.01f) { below = true; break; } } if (below) { m_onGround = true; //player can jump if (_inputManager.IsKeyPressed(SDLK_w)) { GameEngine::SoundEffect soundEffect = m_audio.LoadSoundEffect("Sound/Jump17.ogg"); soundEffect.Play(); body->ApplyLinearImpulse(b2Vec2(0.0f, 30.0f), b2Vec2(0.0f, 0.0f), true); break; } } } } } }
29.207547
142
0.593992
VasilStamatov
61ec0f4d60a9fc41e720319c1ce0ce72a3114fdb
1,335
hpp
C++
supervisor/src/network/websocket/ManagerVisitor.hpp
mdziekon/eiti-tin-ftp-stattr
c8b8c119f6731045f90281d607b98d7a5ffb3bd2
[ "MIT" ]
1
2018-11-12T02:48:46.000Z
2018-11-12T02:48:46.000Z
supervisor/src/network/websocket/ManagerVisitor.hpp
mdziekon/eiti-tin-ftp-stattr
c8b8c119f6731045f90281d607b98d7a5ffb3bd2
[ "MIT" ]
null
null
null
supervisor/src/network/websocket/ManagerVisitor.hpp
mdziekon/eiti-tin-ftp-stattr
c8b8c119f6731045f90281d607b98d7a5ffb3bd2
[ "MIT" ]
null
null
null
#ifndef TIN_NETWORK_WEBSOCKET_MANAGERVISITOR_HPP #define TIN_NETWORK_WEBSOCKET_MANAGERVISITOR_HPP namespace tin { namespace network { namespace websocket { class Manager; namespace events { struct TerminateNetworkManager; struct NewServerConnection; struct ServerConnectionClosed; struct MessageReceived; struct MessageSendRequest; struct MessageSendMultiRequest; struct MessageBroadcastRequest; } class ManagerVisitor { friend class tin::network::websocket::Manager; public: void visit(tin::network::websocket::events::TerminateNetworkManager& evt); void visit(tin::network::websocket::events::NewServerConnection& evt); void visit(tin::network::websocket::events::ServerConnectionClosed& evt); void visit(tin::network::websocket::events::MessageReceived& evt); void visit(tin::network::websocket::events::MessageSendRequest& evt); void visit(tin::network::websocket::events::MessageSendMultiRequest& evt); void visit(tin::network::websocket::events::MessageBroadcastRequest& evt); private: tin::network::websocket::Manager& manager; ManagerVisitor(tin::network::websocket::Manager& manager); }; }}} #endif /* TIN_NETWORK_WEBSOCKET_MANAGERVISITOR_HPP */
32.560976
82
0.708614
mdziekon
61ed8cf47b6d9db480d424b5df3b496fc0964cb5
7,952
cpp
C++
tests/benchmarks/benchmark_tensor.cpp
roman-ellerbrock/QuTree
28c5b4eddf20e41cd015a03d33f31693eff17839
[ "MIT" ]
6
2020-04-24T09:58:23.000Z
2022-02-06T03:40:55.000Z
tests/benchmarks/benchmark_tensor.cpp
roman-ellerbrock/QuTree
28c5b4eddf20e41cd015a03d33f31693eff17839
[ "MIT" ]
1
2020-06-18T11:33:14.000Z
2020-06-18T11:35:23.000Z
tests/benchmarks/benchmark_tensor.cpp
roman-ellerbrock/QuTree
28c5b4eddf20e41cd015a03d33f31693eff17839
[ "MIT" ]
1
2020-12-26T15:23:21.000Z
2020-12-26T15:23:21.000Z
// // Created by Roman Ellerbrock on 2/3/20. // #include <iomanip> #include "benchmark_tensor.h" #include "benchmark_helper.h" #include "benchmark_tree.h" namespace benchmark { TensorShape make_TensorDim(size_t order, size_t dim) { assert(order > 1); assert(dim > 0); vector<size_t> dims; for (size_t i = 0; i < order; ++i) { dims.emplace_back(dim); } return TensorShape(dims); } auto vector_hole_product_sample(Matrixcd& S, const vector<Tensorcd>& A, const vector<Tensorcd>& B, const vector<Matrixcd>& Su, size_t nsample, size_t bef, size_t act, size_t aft) { vector<Tensorcd> sAs; vector<Matrixcd> Ss; for (size_t k = 0; k < A.size(); ++k) { sAs.push_back(A[k]); Ss.push_back(S); } vector<chrono::microseconds> duration_vec; for (size_t n = 0; n < nsample; ++n) { std::chrono::time_point<std::chrono::system_clock> start, end; start = std::chrono::system_clock::now(); for (size_t k = 0; k < A.size(); ++k) { multStateArTB(sAs[k], Su[k], A[k]); contraction(Ss[k], sAs[k], B[k], bef, act, act, aft); } end = std::chrono::system_clock::now(); duration_vec.emplace_back(chrono::duration_cast<chrono::microseconds>(end - start).count()); } return statistic_helper(duration_vec); } auto vector_hole_product(mt19937& gen, size_t dim, size_t order, size_t mode, size_t nsample, ostream& os) { /// Initialize memory auto tdim = make_TensorDim(order, dim); vector<Tensorcd> As; vector<Tensorcd> Bs; vector<Matrixcd> Sus; size_t chunk = pow(2, 21); for (size_t k = 0; k < chunk; ++k) { Tensorcd A(tdim, false); Tensorcd B(tdim, false); Matrixcd Su(dim, dim); Tensor_Extension::generate(A, gen); Tensor_Extension::generate(B, gen); Tensor_Extension::generate(Su, gen); As.emplace_back(A); Bs.emplace_back(B); Sus.emplace_back(Su); } Matrixcd S(dim, dim); size_t aft = tdim.after(mode); size_t act = tdim[mode]; size_t bef = tdim.before(mode); /// Run hole-product return vector_hole_product_sample(S, As, Bs, Sus, nsample, bef, act, aft); } auto hole_product_sample(Matrixcd& S, const Tensorcd& A, const Tensorcd& B, size_t nsample, size_t bef, size_t act, size_t aft) { vector<chrono::microseconds> duration_vec; size_t chunk = pow(2, 20); for (size_t n = 0; n < nsample; ++n) { std::chrono::time_point<std::chrono::system_clock> start, end; start = std::chrono::system_clock::now(); for (size_t k = 0; k < chunk; ++k) { contraction(S, A, B, bef, act, act, aft); } end = std::chrono::system_clock::now(); duration_vec.emplace_back(chrono::duration_cast<chrono::microseconds>(end - start).count()); } return statistic_helper(duration_vec); } auto hole_product(mt19937& gen, size_t dim, size_t order, size_t mode, size_t nsample, ostream& os) { /// Initialize memory auto tdim = make_TensorDim(order, dim); Tensorcd A(tdim, false); Tensorcd B(tdim, false); Tensor_Extension::generate(A, gen); Tensor_Extension::generate(B, gen); Matrixcd S(dim, dim); size_t aft = tdim.after(mode); size_t act = tdim[mode]; size_t bef = tdim.before(mode); /// Run hole-product return hole_product_sample(S, A, B, nsample, bef, act, aft); } auto matrix_tensor_sample(Tensorcd& B, const Matrixcd& S, const Tensorcd& A, size_t nsample, size_t bef, size_t act, size_t aft) { vector<chrono::microseconds> duration_vec; for (size_t n = 0; n < nsample; ++n) { std::chrono::time_point<std::chrono::system_clock> start, end; start = std::chrono::system_clock::now(); matrixTensor(B, S, A, bef, act, act, aft, true); end = std::chrono::system_clock::now(); duration_vec.emplace_back(chrono::duration_cast<chrono::microseconds>(end - start).count()); } return statistic_helper(duration_vec); } auto matrix_tensor(mt19937& gen, size_t dim, size_t order, size_t mode, size_t nsample, ostream& os) { /// Initialize memory std::chrono::time_point<std::chrono::system_clock> allocate_start, allocate_end; auto tdim = make_TensorDim(order, dim); Tensorcd A(tdim, false); Matrixcd S(dim, dim); Tensor_Extension::generate(A, gen); Tensor_Extension::generate(S, gen); Tensorcd B(tdim, true); size_t aft = tdim.after(mode); size_t act = tdim[mode]; size_t bef = tdim.before(mode); return matrix_tensor_sample(B, S, A, nsample, bef, act, aft); } void screen_order(mt19937& gen, ostream& os, size_t nsample) { /// Screen order of tensor size_t dim = 2; size_t max_order = 29; os << "# Matrix tensor\n"; for (size_t order = 3; order <= max_order; order += 2) { size_t mode = order / 2 + 1; os << std::setprecision(6); os << dim << "\t" << order; auto stat = matrix_tensor(gen, dim, order, mode, nsample, cout); os << "\t" << stat.first / 1000. << "\t" << stat.second / 1000. << endl; } os << "# tensor hole product\n"; for (size_t order = 3; order <= max_order; order += 2) { size_t mode = order / 2 + 1; os << std::setprecision(6); os << dim << "\t" << order; auto stat = hole_product(gen, dim, order, mode, nsample, cout); os << "\t" << stat.first / 1000. << "\t" << stat.second / 1000. << endl; } max_order = 3; os << "# tree-simulated tensor hole product\n"; for (size_t order = 3; order <= max_order; order += 2) { size_t mode = order / 2 + 1; os << std::setprecision(6); os << dim << "\t" << order; auto stat = vector_hole_product(gen, dim, order, mode, nsample, cout); os << "\t" << stat.first / 1000. << "\t" << stat.second / 1000. << endl; } } void screen_dim(mt19937& gen, ostream& os, size_t nsample) { /// Screen dim of tensor size_t order = 3; size_t min_dim = 50; size_t max_dim = 250; size_t step_dim = 20; os << "# matrix tensor product\n"; for (size_t dim = min_dim; dim <= max_dim; dim += step_dim) { size_t mode = order / 2 + 1; os << std::setprecision(6); os << dim << "\t" << order; auto stat = matrix_tensor(gen, dim, order, mode, nsample, cout); os << "\t" << stat.first / 1000. << "\t" << stat.second / 1000. << endl; } os << "# tensor hole product\n"; for (size_t dim = min_dim; dim <= max_dim; dim += step_dim) { size_t mode = order / 2 + 1; os << std::setprecision(6); os << dim << "\t" << order; auto stat = hole_product(gen, dim, order, mode, nsample, cout); os << "\t" << stat.first / 1000. << "\t" << stat.second / 1000. << endl; } } void screen_nleaves(mt19937& gen, ostream& os, size_t nsample) { /// Screen dim of nleaves os << "# hole-matrix tree\n"; size_t dim = 2; auto max_order = (size_t) pow(2, 20); size_t min_order = 4; /* for (size_t order = min_order; order <= max_order; order *= 2) { size_t mode = order / 2 + 1; os << std::setprecision(6); os << dim << "\t" << order; auto stat = benchmark::holematrixtree(gen, dim, order, nsample, os); os << "\t" << stat.first / 1000. << "\t" << stat.second / 1000. << endl; } */ os << "# Factor-matrix tree\n"; for (size_t order = min_order; order <= max_order; order *= 2) { size_t mode = order / 2 + 1; os << dim << "\t" << order; auto stat = benchmark::factormatrixtree(gen, dim, order, nsample, os); os << "\t" << stat.first / 1000. << "\t" << stat.second / 1000. << endl; } /* os << "# Sparse factor matrix tree\n"; for (size_t order = min_order; order <= max_order; order *= 2) { size_t mode = order / 2 + 1; os << dim << "\t" << order; auto stat = benchmark::sparse_factormatrixtree(gen, dim, order, 100 * nsample, os); os << "\t" << stat.first / 1000. << "\t" << stat.second / 1000. << endl; } */ /* os << "# Sparse hole matrix tree\n"; for (size_t order = min_order; order <= max_order; order *= 2) { size_t mode = order / 2 + 1; os << dim << "\t" << order; auto stat = benchmark::sparse_holematrixtree(gen, dim, order, 100 * nsample, os); os << "\t" << stat.first / 1000. << "\t" << stat.second / 1000. << endl; }*/ } }
33.552743
110
0.628521
roman-ellerbrock
61ef8dfe9a000a64aa08d78e1d78fbe96d7ca168
9,144
cpp
C++
example/processing_room/processing_app.cpp
GeniusVentures/SuperGenius
ae43304f4a2475498ef56c971296175acb88d0ee
[ "MIT" ]
1
2021-07-10T21:25:03.000Z
2021-07-10T21:25:03.000Z
example/processing_room/processing_app.cpp
GeniusVentures/SuperGenius
ae43304f4a2475498ef56c971296175acb88d0ee
[ "MIT" ]
null
null
null
example/processing_room/processing_app.cpp
GeniusVentures/SuperGenius
ae43304f4a2475498ef56c971296175acb88d0ee
[ "MIT" ]
null
null
null
#include "processing/processing_service.hpp" #include <iostream> #include <boost/program_options.hpp> #include <boost/format.hpp> #include <libp2p/multi/multibase_codec/multibase_codec_impl.hpp> #include <libp2p/log/configurator.hpp> #include <libp2p/log/logger.hpp> using namespace sgns::processing; namespace { class ProcessingCoreImpl : public ProcessingCore { public: ProcessingCoreImpl(size_t nSubtasks, size_t subTaskProcessingTime) : m_nSubtasks(nSubtasks) , m_subTaskProcessingTime(subTaskProcessingTime) { } void SplitTask(const SGProcessing::Task& task, SubTaskList& subTasks) override { for (size_t i = 0; i < m_nSubtasks; ++i) { auto subtask = std::make_unique<SGProcessing::SubTask>(); subtask->set_ipfsblock(task.ipfs_block_id()); subtask->set_results_channel((boost::format("%s_subtask_%d") % task.results_channel() % i).str()); subTasks.push_back(std::move(subtask)); } } void ProcessSubTask( const SGProcessing::SubTask& subTask, SGProcessing::SubTaskResult& result, uint32_t initialHashCode) override { std::cout << "SubTask processing started. " << subTask.results_channel() << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(m_subTaskProcessingTime)); std::cout << "SubTask processed. " << subTask.results_channel() << std::endl; result.set_ipfs_results_data_id((boost::format("%s_%s") % "RESULT_IPFS" % subTask.results_channel()).str()); } private: size_t m_nSubtasks; size_t m_subTaskProcessingTime; }; class ProcessingTaskQueueImpl : public ProcessingTaskQueue { public: ProcessingTaskQueueImpl(const std::list<SGProcessing::Task>& tasks) : m_tasks(tasks) { } bool GrabTask(std::string& taskKey, SGProcessing::Task& task) override { if (m_tasks.empty()) { return false; } task = std::move(m_tasks.back()); m_tasks.pop_back(); taskKey = (boost::format("TASK_%d") % m_tasks.size()).str(); return true; }; bool CompleteTask(const std::string& taskKey, const SGProcessing::TaskResult& task) override { return false; } private: std::list<SGProcessing::Task> m_tasks; }; // cmd line options struct Options { size_t serviceIndex = 0; size_t subTaskProcessingTime = 0; // ms size_t roomSize = 0; size_t disconnect = 0; size_t nSubTasks = 5; size_t channelListRequestTimeout = 5000; // optional remote peer to connect to std::optional<std::string> remote; }; boost::optional<Options> parseCommandLine(int argc, char** argv) { namespace po = boost::program_options; try { Options o; std::string remote; po::options_description desc("processing service options"); desc.add_options()("help,h", "print usage message") ("remote,r", po::value(&remote), "remote service multiaddress to connect to") ("processingtime,p", po::value(&o.subTaskProcessingTime), "subtask processing time (ms)") ("roomsize,s", po::value(&o.roomSize), "subtask processing time (ms)") ("disconnect,d", po::value(&o.disconnect), "disconnect after (ms)") ("nsubtasks,n", po::value(&o.nSubTasks), "number of subtasks that task is split to") ("channellisttimeout,t", po::value(&o.channelListRequestTimeout), "chnnel list request timeout (ms)") ("serviceindex,i", po::value(&o.serviceIndex), "index of the service in computational grid (has to be a unique value)"); po::variables_map vm; po::store(parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help") != 0 || argc == 1) { std::cerr << desc << "\n"; return boost::none; } if (o.serviceIndex == 0) { std::cerr << "Service index should be > 0\n"; return boost::none; } if (o.subTaskProcessingTime == 0) { std::cerr << "SubTask processing time should be > 0\n"; return boost::none; } if (o.roomSize == 0) { std::cerr << "Processing room size should be > 0\n"; return boost::none; } if (!remote.empty()) { o.remote = remote; } return o; } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } return boost::none; } } int main(int argc, char* argv[]) { auto options = parseCommandLine(argc, argv); if (!options) { return 1; } auto loggerPubSub = sgns::base::createLogger("GossipPubSub"); //loggerPubSub->set_level(spdlog::level::trace); auto loggerProcessingEngine = sgns::base::createLogger("ProcessingEngine"); loggerProcessingEngine->set_level(spdlog::level::trace); auto loggerProcessingService = sgns::base::createLogger("ProcessingService"); loggerProcessingService->set_level(spdlog::level::trace); auto loggerProcessingQueue = sgns::base::createLogger("ProcessingSubTaskQueue"); loggerProcessingQueue->set_level(spdlog::level::debug); const std::string processingGridChannel = "GRID_CHANNEL_ID"; const std::string logger_config(R"( # ---------------- sinks: - name: console type: console color: true groups: - name: processing_app sink: console level: info children: - name: libp2p - name: Gossip # ---------------- )"); // prepare log system auto logging_system = std::make_shared<soralog::LoggingSystem>( std::make_shared<soralog::ConfiguratorFromYAML>( // Original LibP2P logging config std::make_shared<libp2p::log::Configurator>(), // Additional logging config for application logger_config)); logging_system->configure(); libp2p::log::setLoggingSystem(logging_system); auto pubs = std::make_shared<sgns::ipfs_pubsub::GossipPubSub>(); if (options->serviceIndex == 1) { std::string publicKey = "z5b3BTS9wEgJxi9E8NHH6DT8Pj9xTmxBRgTaRUpBVox9a"; std::string privateKey = "zGRXH26ag4k9jxTGXp2cg8n31CEkR2HN1SbHaKjaHnFTu"; libp2p::crypto::KeyPair keyPair; auto codec = libp2p::multi::MultibaseCodecImpl(); keyPair.publicKey = { libp2p::crypto::PublicKey::Type::Ed25519, codec.decode(publicKey).value() }; keyPair.privateKey = { libp2p::crypto::PublicKey::Type::Ed25519, codec.decode(privateKey).value() }; pubs = std::make_shared<sgns::ipfs_pubsub::GossipPubSub>(keyPair); } if (options->remote) { pubs->Start(40001, { *options->remote }); } else { pubs->Start(40001, {}); } const size_t maximalNodesCount = 1; std::list<SGProcessing::Task> tasks; // Only a service with index equal to 1 has a locked task (job) if (options->serviceIndex == 1) { SGProcessing::Task task; task.set_ipfs_block_id("IPFS_BLOCK_ID_1"); task.set_block_len(1000); task.set_block_line_stride(2); task.set_block_stride(4); task.set_random_seed(0); task.set_results_channel("RESULT_CHANNEL_ID_1"); tasks.push_back(std::move(task)); } boost::asio::deadline_timer timerToDisconnect(*pubs->GetAsioContext()); if (options->disconnect > 0) { timerToDisconnect.expires_from_now(boost::posix_time::milliseconds(options->disconnect)); timerToDisconnect.async_wait([pubs, &timerToDisconnect](const boost::system::error_code& error) { timerToDisconnect.expires_at(boost::posix_time::pos_infin); pubs->Stop(); }); } auto taskQueue = std::make_shared<ProcessingTaskQueueImpl>(tasks); auto processingCore = std::make_shared<ProcessingCoreImpl>(options->nSubTasks, options->subTaskProcessingTime); ProcessingServiceImpl processingService(pubs, maximalNodesCount, options->roomSize, taskQueue, processingCore); processingService.Listen(processingGridChannel); processingService.SetChannelListRequestTimeout(boost::posix_time::milliseconds(options->channelListRequestTimeout)); processingService.SendChannelListRequest(); // Gracefully shutdown on signal boost::asio::signal_set signals(*pubs->GetAsioContext(), SIGINT, SIGTERM); signals.async_wait( [&pubs](const boost::system::error_code&, int) { pubs->Stop(); }); pubs->Wait(); return 0; }
32.892086
136
0.600612
GeniusVentures
61f15eed8fbfa60be522860a3e181667181f8228
2,785
cc
C++
Sources/Traits/Observable.cc
twistedflick/Yuka
c1601a7314ccbdb1de2f4b7c69f4e2eb3f749b35
[ "Apache-2.0" ]
null
null
null
Sources/Traits/Observable.cc
twistedflick/Yuka
c1601a7314ccbdb1de2f4b7c69f4e2eb3f749b35
[ "Apache-2.0" ]
null
null
null
Sources/Traits/Observable.cc
twistedflick/Yuka
c1601a7314ccbdb1de2f4b7c69f4e2eb3f749b35
[ "Apache-2.0" ]
null
null
null
/* Copyright 2018 Mo McRoberts. * * 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. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "p_YukaTraits.hh" /* Observable trait constructor */ Observable::Observable(): Trait::Trait() { m_traits |= Traits::ObservableTrait; } /* Protected destructor */ Observable::~Observable() { delete m_observable; } /* Construct our private ObservableData */ void Observable::initObservable() { if(m_observable) { return; } m_observable = new ObservableData(this); } /* Attach a listener to a specific event */ void Observable::on(Yuka::Events::EventKind what, Listening *listener) { ListenerVector *vec; initObservable(); vec = m_observable->vectorFor(what, true); vec->push_back(listener); } /* Deliver an event to all listeners registered for it */ bool Observable::emit(Yuka::Events::Event *ev) { ListenerVector *vec; /* If <this> also has the Flexible trait, deliver the event to all of * our attached behaviours */ initObservable(); if(m_observable->flex) { Behaviours::Behaviour *p, *next; /* Our behaviours are always listeners for events we emit */ for(p = m_observable->flex->m_behaviours.first; p; p = next) { next = p->next(); if(!p->enabled()) { continue; } /* For the moment, ignore the result - in future this may, depending * upon the event flags, allow the event to be canceled conditionally. */ deliver(ev, p); } } /* Next, send the event to all of our registered listeners */ if((vec = m_observable->vectorFor(ev->eventKind()))) { ListenerVector::iterator i; for(i = vec->begin(); i != vec->end(); ++i) { deliver(ev, *i); } } return true; } bool Observable::emit(Yuka::Events::Event &ev) { return emit(&ev); } bool Observable::deliver(Yuka::Events::Event *ev, Listening *listener) { return listener->process(ev); } /* ObservableData implementation */ ObservableData::ObservableData(Observable *owner): flex(dynamic_cast<Flexible *>(owner)), map() { } ListenerVector * ObservableData::vectorFor(Events::EventKind what, bool shouldCreate) { ListenerMap::iterator i; if(shouldCreate) { return &(map[what]); } i = map.find(what); if(i == map.end()) { return NULL; } return &(i->second); }
20.477941
76
0.687612
twistedflick
61f7ef867b0b2b66c2df5584ecdc8c811b6f037e
24
cpp
C++
src/rp2_common/pico_standard_link/new_delete.cpp
asynts/pico-sdk
3a9052bc7b5f59cdbf0096ebee954db5af7babe7
[ "BSD-3-Clause" ]
null
null
null
src/rp2_common/pico_standard_link/new_delete.cpp
asynts/pico-sdk
3a9052bc7b5f59cdbf0096ebee954db5af7babe7
[ "BSD-3-Clause" ]
null
null
null
src/rp2_common/pico_standard_link/new_delete.cpp
asynts/pico-sdk
3a9052bc7b5f59cdbf0096ebee954db5af7babe7
[ "BSD-3-Clause" ]
null
null
null
// Moved to my codebase
12
23
0.708333
asynts
61f8ef9b7ac54cdab280ffea4ef63c702710ff67
7,071
cpp
C++
Dump (complete other files)/MATLAB/control.cpp
Mauvai/Quadcopter-FYP-legacy
161f2842d06d30aad06895efa198dc0ee28a27c2
[ "MIT" ]
null
null
null
Dump (complete other files)/MATLAB/control.cpp
Mauvai/Quadcopter-FYP-legacy
161f2842d06d30aad06895efa198dc0ee28a27c2
[ "MIT" ]
null
null
null
Dump (complete other files)/MATLAB/control.cpp
Mauvai/Quadcopter-FYP-legacy
161f2842d06d30aad06895efa198dc0ee28a27c2
[ "MIT" ]
null
null
null
/* See Ross' Logbook, semester 2 week 3 for control difference equations. * Gains are DILIBERATELY ENTERED AS FLOATS, AND NOT A FLOAT ARRAY - faster, no referencing overhead. *Channel 1, u1 is Height *Channel 2, u2 is Roll *Channel 3, u3 is Pitch *Channel 4, u4 is Yaw *Motor 1 PWM input is summed +u1 -u3+u4 *Motor 2 PWM input summed +u1-u2 -u4 *Motor 3 PWM input is summed +u1 +u3+u4 *Motor 4 PWM input summed +u1+u2 -u4 */ #include <stdio.h> // Recommended over iostream for saving space #include <propeller.h> // Propeller-specific functions #include "simpletools.h" //controller gains (1-9 for 4 controllers) const float kh1 = 1.00000000; const float kh2 = 1.94143434; const float kh3 = -2.05856566; const float kh4 = 2.45649993; const float kh5 = -2.33936861; const float kh6 = 0.65588425; const float kh7 = -0.65588425; const float kh8 = 0.59261116; const float kh9 = -0.59261116; const float kr1 = 1.00000000; const float kr2 = 0.06995984; const float kr3 = -0.18004016; const float kr4 = 1.67745556; const float kr5 = -1.56737523; const float kr6 = 0.32608685; const float kr7 = -0.32608685; const float kr8 = 0.83837179; const float kr9 = -0.83837179; const float kp1 = 1.00000000; const float kp2 = 0.06995984; const float kp3 = -0.18004016; const float kp4 = 1.67745556; const float kp5 = -1.56737523; const float kp6 = 0.32608685; const float kp7 = -0.32608685; const float kp8 = 0.83837179; const float kp9 = -0.838371579; const float ky1 = 1.00000000; const float ky2 = -0.00394348; const float ky3 = -0.00394348; const float ky4 = 0.37474411; const float ky5 = -0.36685716; const float ky6 = 0.45170301; const float ky7 = -0.45170301; const float ky8 = 0.11704666; const float ky9 = -0.11704666; //The height observer gains are: // Fn1 Fn2 Fn3 Gn1 const float Fh11 = -1.06012243; const float Fh12 = 0.03000000; const float Fh13 = 0.00658443; const float Gh14 = 2.06012243; const float Fh21 = -38.4669769; const float Fh22 = 1.00000000; const float Fh23 = 0.40978132; const float Gh24 = 38.46697692; const float Fh31 = -9.37529529; const float Fh32 = 0.00000000; const float Fh33 = 0.65143906; const float Gh34 = 9.37529529; //The roll observer gains are: // Fn1 Fn2 Fn3 Gn1 Gn2 const float Fr11 = 0.50291653; const float Fr12 = -0.00243995; const float Fr13 = 0.02059603; const float Gr14 = 0.49708347; const float Gr15 = 0.03243995; const float Fr21 = 0.12765187; const float Fr22 = 0.34837765; const float Fr23 = 1.28179111; const float Gr24 = -0.12765187; const float Gr25 = 0.65162235; const float Fr31 = 0.01464762; const float Fr32 = -0.01783035; const float Fr33 = 0.65143906; const float Gr34 = -0.01464762; const float Gr35 = 0.01783035; //The pitch observer gains are: // Fn1 Fn2 Fn3 Gn1 Gn2 const float Fp11 = 0.50291653; const float Fp12 = -0.00243995; const float Fp13 = 0.02059603; const float Gp14 = 0.49708347; const float Gp15 = 0.03243995; const float Fp21 = 0.12765187; const float Fp22 = 0.34837765; const float Fp23 = 1.28179111; const float Gp24 = -0.12765187; const float Gp25 = 0.65162235; const float Fp31 = 0.01464762; const float Fp32 = -0.01783035; const float Fp33 = 0.65143906; const float Gp34 = -0.01464762; const float Gp35 = 0.01783035; //The yaw observer gains are: // Fn1 Fn2 Fn3 Gn1 Gn2 const float Fy11 = 0.50291653; const float Fy12 = -0.00243995; const float Fy13 = 0.02059603; const float Gy14 = 0.19050553; const float Gy15 = 0.02745124; const float Fy21 = 0.12765187; const float Fy22 = 0.34837765; const float Fy23 = 1.28179111; const float Gy24 = -0.00549183; const float Gy25 = 0.03271282; const float Fy31 = 0.01464762; const float Fy32 = -0.01783035; const float Fy33 = 0.65143906; const float Gy34 = 0.00913020; const float Gy35 = 0.25971804; float x1hat_h_k 0; float x1hat_h_k_minus_1 0; float x2hat_h_k 0; float x2hat_h_k_minus_1 0; float x3hat_h_k 0; float x3hat_h_k_minus_1 0; float x1hat_r_k 0; float x1hat_r_k_minus_1 0; float x2hat_r_k 0; float x2hat_r_k_minus_1 0; float x3hat_r_k 0; float x3hat_r_k_minus_1 0; float x1hat_p_k 0; float x1hat_p_k_minus_1 0; float x2hat_p_k 0; float x2hat_p_k_minus_1 0; float x3hat_p_k 0; float x3hat_p_k_minus_1 0; float x1hat_y_k 0; float x1hat_y_k_minus_1 0; float x2hat_y_k 0; float x2hat_y_k_minus_1 0; float x3hat_y_k 0; float x3hat_y_k_minus_1 0; float setPoint_h_k = 0; float setPoint_h_k_minus_1 = 0; float setPoint_r_k = 0; float setPoint_r_k_minus_1 = 0; float setPoint_p_k = 0; float setPoint_p_k_minus_1 = 0; float setPoint_y_k = 0; float setPoint_y_k_minus_1 = 0; float u_h_k = 0; float u_h_k_minus_1 = 0; float u_r_k = 0; float u_r_k_minus_1 = 0; float u_p_k = 0; float u_p_k_minus_1 = 0; float u_y_k = 0; float u_y_k_minus_1 = 0; float control_pitch(float theta, float gyr_x) { _pitch_observer(float theta, float gyr_x); u_h_k = k21*u_h_k_minus_1+ k22*setPoint_h_k + k23*setPoint_h_k_minus_1 + k24*x1hat_h_k + k15*x1hat_h_k_minus_1 + k16*x2hat_h_k + k17*x2hat_h_k_minus_1 + k18*x3hat_h_k + k19*x3hat_h_k_minus_1; } float _pitch_observer(float theta, float gyr_x) //this should not be called other than inside control_pitch() { x1hat_h_k = Fh11*x1hat_h_k_minus_1+ Fh12*x2hat_h_k_minus_1 + Fh13*x3hat_h_k_minus_1 + Gh11*theta + Gh12*gyr_x; x2hat_h_k = Fh21*x1hat_h_k_minus_1+ Fh22*x2hat_h_k_minus_1 + Fh23*x3hat_h_k_minus_1 + Gh21*theta + Gh22*gyr_x; x3hat_h_k = Fh31*x1hat_h_k_minus_1+ Fh32*x2hat_h_k_minus_1 + Fh33*x3hat_h_k_minus_1 + Gh31*theta + Gh32*gyr_x; } float control_roll(float phi, float gyr_y) { _roll_observer(float phi, float gyr_y); u_r_k = k11*u_r_k_minus_1+ k12*setPoint_r_k + k13*setPoint_r_k_minus_1 + k14*x1hat_r_k + k15*x1hat_r_k_minus_1 + k16*x2hat_r_k + k17*x2hat_r_k_minus_1 + k18*x3hat_r_k + k19*x3hat_r_k_minus_1; } float _roll_observer(float phi, float gyr_y) //this should not be called other than inside control_pitch() { x1hat_r_k = Fh11*x1hat_r_k_minus_1+ Fh12*x2hat_r_k_minus_1 + Fh13*x3hat_r_k_minus_1 + Gh11*phi + Gh12*gyr_y; x2hat_r_k = Fh21*x1hat_r_k_minus_1+ Fh22*x2hat_r_k_minus_1 + Fh23*x3hat_r_k_minus_1 + Gh21*phi + Gh22*gyr_y; x3hat_r_k = Fh31*x1hat_r_k_minus_1+ Fh32*x2hat_r_k_minus_1 + Fh33*x3hat_r_k_minus_1 + Gh31*phi + Gh32*gyr_y; } u(k)= K1*u(k-1)+ K2*r(k) + K3*r(k-1) + K4*x1hat(k) + K5*x1hat(k-1) + K6*x2hat(k) + K7*x2hat(k-1) + K8*x3hat(k) + K9*x3hat(k-1) x1hat(k+1)= F11*x1hat(k)+ F12*x2hat(k) + F13*x3hat(k) + G11*y1(k) + G12*y2(k) x2hat(k+1)= F21*x1hat(k)+ F22*x2hat(k) + F23*x3hat(k) + G21*y1(k) + G22*y2(k) x3hat(k+1)= F31*x1hat(k)+ F32*x2hat(k) + F33*x3hat(k) + G31*y1(k) + G32*y2(k)
51.613139
156
0.682506
Mauvai
61fa755ffc416f277da7e0de904ebcbaed9b80af
43
hpp
C++
src/boost_spirit_include_qi_int.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_spirit_include_qi_int.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_spirit_include_qi_int.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/spirit/include/qi_int.hpp>
21.5
42
0.790698
miathedev
110305308784e6e667bd787d44a294464fee708d
2,646
hpp
C++
inc/net/async.hpp
douderg/https-client
e169fe4297aaad76098637d02361c611e79001bc
[ "BSL-1.0" ]
1
2022-02-20T22:19:55.000Z
2022-02-20T22:19:55.000Z
inc/net/async.hpp
douderg/https-client
e169fe4297aaad76098637d02361c611e79001bc
[ "BSL-1.0" ]
null
null
null
inc/net/async.hpp
douderg/https-client
e169fe4297aaad76098637d02361c611e79001bc
[ "BSL-1.0" ]
1
2022-02-22T00:08:02.000Z
2022-02-22T00:08:02.000Z
#pragma once #include <boost/beast.hpp> #include <boost/beast/core/bind_handler.hpp> #include <boost/beast/core/flat_buffer.hpp> #include <boost/beast/core/stream_traits.hpp> #include <boost/beast/http/dynamic_body.hpp> #include <boost/beast/http/message.hpp> #include <boost/beast/http/read.hpp> #include <boost/beast/http/string_body.hpp> #include <boost/beast/http/write.hpp> #include <exception> #include <future> #include <memory> #include <stdexcept> #include <utility> #include <functional> namespace async { struct reader { boost::beast::flat_buffer buffer; std::promise<std::string> result; void on_read(boost::beast::error_code ec, size_t bytes); }; struct writer { std::promise<void> result; void on_write(boost::beast::error_code ec, size_t bytes); }; template <class StreamT, class RequestT, class ResponseT> class request_handler : public std::enable_shared_from_this<request_handler<StreamT, RequestT, ResponseT>> { public: request_handler(StreamT& stream, std::function<ResponseT(const RequestT&)> func): stream_(stream), handler_(func) { } std::future<void> handle_next() { request_ = {}; boost::beast::http::async_read( stream_, buffer_, request_, boost::beast::bind_front_handler(&request_handler<StreamT, RequestT, ResponseT>::on_read, this->shared_from_this()) ); return result_.get_future(); } private: void on_read(boost::beast::error_code ec, size_t bytes) { if (ec) { result_.set_exception(std::make_exception_ptr(std::runtime_error(ec.message()))); } else { response_ = handler_(request_); boost::beast::http::async_write( stream_, response_, boost::beast::bind_front_handler(&request_handler<StreamT, RequestT, ResponseT>::on_write, this->shared_from_this(), request_.need_eof()) ); } } void on_write(bool close, boost::beast::error_code ec, size_t bytes) { if (ec) { result_.set_exception(std::make_exception_ptr(std::runtime_error(ec.message()))); } else { if (close) { boost::beast::error_code ec; boost::beast::get_lowest_layer(stream_).socket().shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec); } result_.set_value(); } } StreamT& stream_; std::function<ResponseT(const RequestT&)> handler_; boost::beast::flat_buffer buffer_; std::promise<void> result_; RequestT request_; ResponseT response_; }; }
30.767442
153
0.645881
douderg
11059480300d6c513449ad09c59545265395b6fd
6,398
cpp
C++
FormulaEngine/ScriptWorld.cpp
apoch/formula-engine
594190bb5602a7362f09e4ed080c68224390a231
[ "BSD-3-Clause" ]
30
2015-10-13T05:11:48.000Z
2021-07-16T06:24:18.000Z
FormulaEngine/ScriptWorld.cpp
apoch/formula-engine
594190bb5602a7362f09e4ed080c68224390a231
[ "BSD-3-Clause" ]
null
null
null
FormulaEngine/ScriptWorld.cpp
apoch/formula-engine
594190bb5602a7362f09e4ed080c68224390a231
[ "BSD-3-Clause" ]
3
2016-06-03T03:01:43.000Z
2021-07-16T06:24:31.000Z
#include "Pch.h" #include "Interfaces.h" #include "Formula.h" #include "Actions.h" #include "TokenPool.h" #include "PropertyBag.h" #include "EventHandler.h" #include "Scriptable.h" #include "ScriptWorld.h" ScriptWorld::ScriptWorld (TokenPool * pool, IEngineBinder * binder) : m_binder(binder), m_tokens(pool) { assert(m_tokens != nullptr); if (pool) { m_magicTokenEvent = pool->AddToken("event"); m_magicTokenOther = pool->AddToken("other"); } } ScriptWorld::~ScriptWorld () { for (auto & instance : m_instances) delete instance; } void ScriptWorld::AddArchetype (const std::string & name, Scriptable && archetype) { unsigned token = m_tokens->AddToken(name); assert(m_archetypes.find(token) == m_archetypes.end()); m_archetypes.emplace(token, std::move(archetype)); } void ScriptWorld::AddScriptable (const std::string & name, Scriptable && scriptable) { unsigned token = m_tokens->AddToken(name); assert(m_scriptables.find(token) == m_scriptables.end()); m_scriptables.emplace(token, std::move(scriptable)); } void ScriptWorld::AddMagicBag (unsigned token) { m_magicBags.emplace_back(token, TextPropertyBag(token)); } void ScriptWorld::DispatchEvent (Scriptable * target, unsigned eventToken, const IFormulaPropertyBag * paramBag) { // TODO - this is a giant HACK target->GetScopes().SetWorld(this); target->GetEvents()->TriggerHandlers(this, eventToken, target, paramBag); } bool ScriptWorld::DispatchEvents () { bool dispatched = false; TransferTimedEvents(); while (!m_eventQueue.empty()) { dispatched = true; std::vector<Event> tempqueue = std::move(m_eventQueue); for (Event & e : tempqueue) { if (e.targetToken) { Scriptable * scriptable = GetScriptable(e.targetToken); if (scriptable) DispatchEvent(scriptable, e.nameToken, e.parameterBag); } else if (e.directTarget) { DispatchEvent(e.directTarget, e.nameToken, e.parameterBag); } else { for (auto & pair : m_scriptables) { DispatchEvent(&pair.second, e.nameToken, e.parameterBag); } for (auto * scriptable : m_instances) { DispatchEvent(scriptable, e.nameToken, e.parameterBag); } } delete e.parameterBag; } } return dispatched; } void ScriptWorld::DumpOverview () const { std::cout << "----- Scripting world " << this << " -----\n"; std::cout << "Contains " << m_scriptables.size() << " objects and " << m_archetypes.size() << " archetypes\n"; std::cout << "Instantiated " << m_instances.size() << " objects\n"; std::cout << "----- End world -----" << std::endl; } Scriptable * ScriptWorld::GetArchetype (unsigned token) { auto iter = m_archetypes.find(token); if (iter == m_archetypes.end()) return nullptr; return &iter->second; } Scriptable * ScriptWorld::GetScriptable (unsigned token) { auto iter = m_scriptables.find(token); if (iter == m_scriptables.end()) return nullptr; return &iter->second; } TextPropertyBag * ScriptWorld::GetMagicBag (unsigned token) { for (auto & pair : m_magicBags) { if (pair.first == token) return &pair.second; } return nullptr; } Scriptable * ScriptWorld::InstantiateArchetype (unsigned token, IFormulaPropertyBag * paramBag) { Scriptable * archetype = GetArchetype(token); if (!archetype) return nullptr; Scriptable * instance = archetype->Instantiate(); m_instances.push_back(instance); instance->BindAll(m_binder, this); QueueEvent(instance, m_tokens->AddToken("OnCreate"), paramBag); return instance; } Scriptable * ScriptWorld::InstantiateArchetype (unsigned nameOfInstance, unsigned token, IFormulaPropertyBag * paramBag) { Scriptable * archetype = GetArchetype(token); if (!archetype) return nullptr; Scriptable * instance = archetype->Instantiate(); assert(m_scriptables.find(nameOfInstance) == m_scriptables.end()); instance->BindAll(m_binder, this); m_scriptables.emplace(nameOfInstance, std::move(*instance)); delete instance; QueueEvent(GetScriptable(nameOfInstance), m_tokens->AddToken("OnCreate"), paramBag); return GetScriptable(nameOfInstance); } void ScriptWorld::QueueBroadcastEvent (const std::string & eventName) { QueueEvent(0, eventName); } void ScriptWorld::QueueEvent (unsigned targetToken, const std::string & eventName) { Event e; e.nameToken = m_tokens->AddToken(eventName); e.targetToken = targetToken; e.directTarget = nullptr; e.parameterBag = nullptr; m_eventQueue.push_back(e); } void ScriptWorld::QueueEvent (Scriptable * target, unsigned eventToken, IFormulaPropertyBag * bag) { Event e; e.nameToken = eventToken; e.targetToken = 0; e.directTarget = target; e.parameterBag = bag; m_eventQueue.push_back(e); } void ScriptWorld::QueueDelayedEvent (unsigned targetToken, unsigned eventToken, IFormulaPropertyBag * paramBag, ValueT delaySeconds) { Event e; e.nameToken = eventToken; e.targetToken = targetToken; e.directTarget = nullptr; e.parameterBag = paramBag; e.timestamp = std::chrono::system_clock::now(); e.timestamp += std::chrono::milliseconds(long long(delaySeconds * 1000.0)); m_eventQueueTimed.push_back(e); } void ScriptWorld::QueueDelayedEvent (Scriptable * target, unsigned eventToken, IFormulaPropertyBag * paramBag, ValueT delaySeconds) { Event e; e.nameToken = eventToken; e.targetToken = 0; e.directTarget = target; e.parameterBag = paramBag; e.timestamp = std::chrono::system_clock::now(); e.timestamp += std::chrono::milliseconds(long long(delaySeconds * 1000.0)); m_eventQueueTimed.push_back(e); } void ScriptWorld::TransferTimedEvents () { auto iter = std::stable_partition(m_eventQueueTimed.begin(), m_eventQueueTimed.end(), [](const Event & e) { return (e.timestamp > std::chrono::system_clock::now()); }); m_eventQueue.insert(m_eventQueue.end(), iter, m_eventQueueTimed.end()); std::stable_sort(m_eventQueue.begin(), m_eventQueue.end(), [](const Event & a, const Event & b) { return a.timestamp < b.timestamp; }); m_eventQueueTimed.erase(iter, m_eventQueueTimed.end()); } unsigned ScriptWorld::PeekTimeUntilNextEvent () const { long long timeUntilEvent = 0xffffffff; auto now(std::chrono::system_clock::now()); for (const auto & timedEvent : m_eventQueueTimed) { auto delta = timedEvent.timestamp - now; auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(delta); if (ms.count() < timeUntilEvent) timeUntilEvent = ms.count(); } return unsigned(timeUntilEvent); }
26.114286
134
0.719912
apoch
110a718c4b17363fe841bd825867a9651ae30f6f
2,217
cpp
C++
tests/src/experimental/tests_DynArray.cpp
Mike-Bal/mart-common
0b52654c6f756e8e86689e56d24849c97079229c
[ "MIT" ]
null
null
null
tests/src/experimental/tests_DynArray.cpp
Mike-Bal/mart-common
0b52654c6f756e8e86689e56d24849c97079229c
[ "MIT" ]
null
null
null
tests/src/experimental/tests_DynArray.cpp
Mike-Bal/mart-common
0b52654c6f756e8e86689e56d24849c97079229c
[ "MIT" ]
null
null
null
#include <mart-common/experimental/DynArray.h> #include <catch2/catch.hpp> #if __cpp_lib_span #include <span> #endif TEST_CASE( "experimental_DynArrayTrivial_has_correct_size", "[experimental][dynarray]" ) { mart::DynArrayTriv<int> arr1; CHECK( arr1.size() == 0 ); mart::DynArrayTriv<int> arr2( 5 ); CHECK( arr2.size() == 5 ); mart::DynArrayTriv<int> arr3{ 5 }; CHECK( arr3.size() == 1 ); int carr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; #if __cpp_lib_span mart::DynArrayTriv<int> arr4{ std::span<int>( carr ) }; CHECK( arr4.size() == 10 ); for( std::size_t i = 0; i < 10; ++i ) { CHECK( arr4[i] == i ); } #endif mart::DynArrayTriv<int> arr5( std::begin( carr ), std::end( carr ) ); CHECK( arr5.size() == 10 ); for( std::size_t i = 0; i < 10; ++i ) { CHECK( arr5[i] == i ); } } TEST_CASE( "experimental_DynArrayTrivial_copy", "[experimental][dynarray]" ) { mart::DynArrayTriv<int> arr1( 5 ); CHECK( arr1.size() == 5 ); std::iota( arr1.begin(), arr1.end(), 0 ); for( std::size_t i = 0; i < 5; ++i ) { CHECK( arr1[i] == i ); } mart::DynArrayTriv<int> arr2 = arr1; for( std::size_t i = 0; i < 5; ++i ) { CHECK( arr2[i] == i ); } } TEST_CASE( "experimental_DynArrayTrivial_append", "[experimental][dynarray]" ) { mart::DynArrayTriv<int> arr1{ 1, 2, 3, 4, 5, 6 }; auto arr2 = arr1.append( 7 ); CHECK( arr2.back() == 7 ); } namespace { template<class T, std::size_t S = 10> struct AllocT { using value_type =T; static T* allocate( std::size_t n ) { auto cnt = S > n ? S : n; return new T[cnt]; } static void deallocate( T* t, std::size_t ) { delete t; } static T* reallocate( T* t, std::size_t n ) { if( n <= S ) { return t; } else { return nullptr; } } }; using Alloc = AllocT<int,100>; #if __cpp_concepts static_assert( mart::detail::AllocWithRealloc<Alloc> ); #endif } // namespace TEST_CASE( "experimental_DynArrayTrivial_append_move", "[experimental][dynarray]" ) { mart::DynArrayTriv<int, Alloc> arr2; { mart::DynArrayTriv<int, Alloc> arr1{ 1, 2, 3, 4, 5, 6 }; arr2 = std::move( arr1 ).append( 7 ); #ifdef __cpp_concepts CHECK( arr1.size() == 0 ); #else CHECK( arr1.size() == 6 ); #endif } CHECK( arr2.back() == 7 ); }
19.794643
88
0.606676
Mike-Bal
1110807be62f625c87aa59d67b4759d31e1ab28b
17,841
cpp
C++
jlp_andor/jlp_Atmcd32d_linux.cpp
jlprieur/PiscoSpeck2
f6018b362feb67b71c920c3272a44fed35cad844
[ "MIT" ]
1
2020-03-28T14:45:16.000Z
2020-03-28T14:45:16.000Z
jlp_andor/jlp_Atmcd32d_linux.cpp
jlprieur/PiscoSpeck2
f6018b362feb67b71c920c3272a44fed35cad844
[ "MIT" ]
null
null
null
jlp_andor/jlp_Atmcd32d_linux.cpp
jlprieur/PiscoSpeck2
f6018b362feb67b71c920c3272a44fed35cad844
[ "MIT" ]
1
2020-07-09T00:20:38.000Z
2020-07-09T00:20:38.000Z
/**************************************************************************** * jlp_Atmcd32d_linux.cpp * Dummy Andor library to replace Windows one * * JLP * Version 28/08/2015 *****************************************************************************/ #include "asp2_typedef.h" // BYTE #include "jlp_Atmcd32d_linux.h" unsigned int AbortAcquisition(void){return(0);} unsigned int CancelWait(void){return(0);} unsigned int CoolerOFF(void){return(0);} unsigned int CoolerON(void){return(0);} unsigned int DemosaicImage(WORD* _input, WORD* _red, WORD* _green, WORD* _blue, ColorDemosaicInfo* _info){return(0);} unsigned int EnableKeepCleans(int iMode){return(0);} unsigned int FreeInternalMemory(void){return(0);} unsigned int GetAcquiredData(at_32 * array, unsigned long size){return(0);} unsigned int GetAcquiredData16(WORD* array, unsigned long size){return(0);} unsigned int GetAcquiredFloatData(float* array, unsigned long size){return(0);} unsigned int GetAcquisitionProgress(long* acc, long* series){return(0);} unsigned int GetAcquisitionTimings(float* exposure, float* accumulate, float* kinetic){return(0);} unsigned int GetAdjustedRingExposureTimes(int _inumTimes, float *_fptimes){return(0);} unsigned int GetAllDMAData(at_32* array, unsigned long size){return(0);} unsigned int GetAmpDesc(int index, char* name, int len){return(0);} unsigned int GetAmpMaxSpeed(int index, float* speed){return(0);} unsigned int GetAvailableCameras(long* totalCameras){return(0);} unsigned int GetBackground(at_32* array, unsigned long size){return(0);} unsigned int GetBitDepth(int channel, int* depth){return(0);} unsigned int GetCameraEventStatus(DWORD *cam_status){return(0);} unsigned int GetCameraHandle(long cameraIndex, long* cameraHandle){return(0);} unsigned int GetCameraInformation(int index, long *information){return(0);} unsigned int GetCameraSerialNumber(int* number){return(0);} unsigned int GetCapabilities(AndorCapabilities* caps){return(0);} unsigned int GetControllerCardModel(char* controllerCardModel){return(0);} unsigned int GetCurrentCamera(long* cameraHandle){return(0);} unsigned int GetCYMGShift(int * _iXshift, int * _iYshift){return(0);} unsigned int GetDDGIOCFrequency(double* frequency){return(0);} unsigned int GetDDGIOCNumber(unsigned long* number_pulses){return(0);} unsigned int GetDDGIOCPulses(int* pulses){return(0);} // DDG Lite functions unsigned int GetDDGLiteGlobalControlByte(unsigned char * _byte){return(0);} unsigned int GetDDGLiteControlByte(AT_DDGLiteChannelId _channel, unsigned char * _byte){return(0);} unsigned int GetDDGLiteInitialDelay(AT_DDGLiteChannelId _channel, float * _f_delay){return(0);} unsigned int GetDDGLitePulseWidth(AT_DDGLiteChannelId _channel, float * _f_width){return(0);} unsigned int GetDDGLiteInterPulseDelay(AT_DDGLiteChannelId _channel, float * _f_delay){return(0);} unsigned int GetDDGLitePulsesPerExposure(AT_DDGLiteChannelId _channel, at_u32 * _ui32_pulses){return(0);} unsigned int GetDDGPulse(double width, double resolution, double* Delay, double *Width){return(0);} unsigned int GetDetector(int* xpixels, int* ypixels){return(0);} unsigned int GetDICameraInfo(void *info){return(0);} unsigned int GetEMCCDGain(int* gain){return(0);} unsigned int GetEMGainRange(int* low, int* high){return(0);} unsigned int GetFastestRecommendedVSSpeed(int *index, float* speed){return(0);} unsigned int GetFIFOUsage(int* FIFOusage){return(0);} unsigned int GetFilterMode(int* mode){return(0);} unsigned int GetFKExposureTime(float* time){return(0);} unsigned int GetFKVShiftSpeed(int index, int* speed){return(0);} unsigned int GetFKVShiftSpeedF(int index, float* speed){return(0);} unsigned int GetHardwareVersion(unsigned int* PCB, unsigned int* Decode, unsigned int* dummy1, unsigned int* dummy2, unsigned int* CameraFirmwareVersion, unsigned int* CameraFirmwareBuild){return(0);} unsigned int GetHeadModel(char* name){return(0);} unsigned int GetHorizontalSpeed(int index, int* speed){return(0);} unsigned int GetHSSpeed(int channel, int type, int index, float* speed){return(0);} unsigned int GetHVflag(int *bFlag){return(0);} unsigned int GetID(int devNum, int* id){return(0);} unsigned int GetImageFlip(int* iHFlip, int* iVFlip){return(0);} unsigned int GetImageRotate(int* iRotate){return(0);} unsigned int GetImages (long first, long last, at_32* array, unsigned long size, long* validfirst, long* validlast){return(0);} unsigned int GetImages16 (long first, long last, WORD* array, unsigned long size, long* validfirst, long* validlast){return(0);} unsigned int GetImagesPerDMA(unsigned long* images){return(0);} unsigned int GetIRQ(int* IRQ){return(0);} unsigned int GetKeepCleanTime(float *KeepCleanTime){return(0);} unsigned int GetMaximumBinning(int ReadMode, int HorzVert, int* MaxBinning){return(0);} unsigned int GetMaximumExposure(float* MaxExp){return(0);} unsigned int GetMCPGain(int iNum, int *iGain, float *fPhotoepc){return(0);} unsigned int GetMCPGainRange(int * _i_low, int * _i_high){return(0);} unsigned int GetMCPVoltage(int *iVoltage){return(0);} unsigned int GetMinimumImageLength(int* MinImageLength){return(0);} unsigned int GetMostRecentColorImage16 (unsigned long size, int algorithm, WORD* red, WORD* green, WORD* blue){return(0);} unsigned int GetMostRecentImage (at_32* array, unsigned long size){return(0);} unsigned int GetMostRecentImage16 (WORD* array, unsigned long size){return(0);} unsigned int GetMSTimingsData(SYSTEMTIME *TimeOfStart,float *_pfDifferences, int _inoOfimages){return(0);} unsigned int GetMSTimingsEnabled(void){return(0);} unsigned int GetNewData(at_32* array, unsigned long size){return(0);} unsigned int GetNewData16(WORD* array, unsigned long size){return(0);} unsigned int GetNewData8(unsigned char* array, unsigned long size){return(0);} unsigned int GetNewFloatData(float* array, unsigned long size){return(0);} unsigned int GetNumberADChannels(int* channels){return(0);} unsigned int GetNumberAmp(int* amp){return(0);} unsigned int GetNumberAvailableImages (at_32* first, at_32* last){return(0);} unsigned int GetNumberDevices(int* numDevs){return(0);} unsigned int GetNumberFKVShiftSpeeds(int* number){return(0);} unsigned int GetNumberHorizontalSpeeds(int* number){return(0);} unsigned int GetNumberHSSpeeds(int channel, int type, int* speeds){return(0);} unsigned int GetNumberNewImages (long* first, long* last){return(0);} unsigned int GetNumberPreAmpGains(int* noGains){return(0);} unsigned int GetNumberRingExposureTimes(int *_ipnumTimes){return(0);} unsigned int GetNumberVerticalSpeeds(int* number){return(0);} unsigned int GetNumberVSAmplitudes(int* number){return(0);} unsigned int GetNumberVSSpeeds(int* speeds){return(0);} unsigned int GetOldestImage (at_32* array, unsigned long size){return(0);} unsigned int GetOldestImage16 (WORD* array, unsigned long size){return(0);} unsigned int GetPhysicalDMAAddress(unsigned long* Address1, unsigned long* Address2){return(0);} unsigned int GetPixelSize(float* xSize, float* ySize){return(0);} unsigned int GetPreAmpGain(int index, float* gain){return(0);} unsigned int GetReadOutTime(float *ReadoutTime){return(0);} unsigned int GetRegisterDump(int* mode){return(0);} unsigned int GetRingExposureRange(float *_fpMin, float *_fpMax){return(0);} unsigned int GetSizeOfCircularBuffer (long* index){return(0);} unsigned int GetSlotBusDeviceFunction(DWORD *dwSlot, DWORD *dwBus, DWORD *dwDevice, DWORD *dwFunction){return(0);} unsigned int GetSoftwareVersion(unsigned int* eprom, unsigned int* coffile, unsigned int* vxdrev, unsigned int* vxdver, unsigned int* dllrev, unsigned int* dllver){return(0);} unsigned int GetSpoolProgress(long* index){return(0);} unsigned int GetStatus(int* status){return(0);} unsigned int GetTemperature(int* temperature){return(0);} unsigned int GetTemperatureF(float* temperature){return(0);} unsigned int GetTemperatureRange(int* mintemp,int* maxtemp){return(0);} unsigned int GetTemperatureStatus(float *SensorTemp, float *TargetTemp, float *AmbientTemp, float *CoolerVolts){return(0);} unsigned int GetTotalNumberImagesAcquired (long* index){return(0);} unsigned int GetVersionInfo(AT_VersionInfoId _id, char * _sz_versionInfo, at_u32 _ui32_bufferLen){return(0);} unsigned int GetVerticalSpeed(int index, int* speed){return(0);} unsigned int GetVirtualDMAAddress(void** Address1, void** Address2){return(0);} unsigned int GetVSSpeed(int index, float* speed){return(0);} unsigned int GPIBReceive(int id, short address, char* text, int size){return(0);} unsigned int GPIBSend(int id, short address, char* text){return(0);} unsigned int I2CBurstRead(BYTE i2cAddress, long nBytes, BYTE* data){return(0);} unsigned int I2CBurstWrite(BYTE i2cAddress, long nBytes, BYTE* data){return(0);} unsigned int I2CRead(BYTE deviceID, BYTE intAddress, BYTE* pdata){return(0);} unsigned int I2CReset(void){return(0);} unsigned int I2CWrite(BYTE deviceID, BYTE intAddress, BYTE data){return(0);} unsigned int IdAndorDll(void){return(0);} unsigned int InAuxPort(int port, int* state){return(0);} unsigned int Initialize(char * dir){return(0);} // read ini file to get head and card unsigned int InitializeDevice(char * dir){return(0);} unsigned int IsCoolerOn(int * _iCoolerStatus){return(0);} unsigned int IsInternalMechanicalShutter(int *InternalShutter){return(0);} unsigned int IsPreAmpGainAvailable(int channel, int amplifier, int index, int pa, int* status){return(0);} unsigned int IsTriggerModeAvailable(int _itriggerMode){return(0);} unsigned int Merge(const at_32* array, long nOrder, long nPoint, long nPixel, float* coeff, long fit, long hbin, at_32* output, float* start, float* step){return(0);} unsigned int OutAuxPort(int port, int state){return(0);} unsigned int PrepareAcquisition(void){return(0);} unsigned int SaveAsBmp(char* path, char* palette, long ymin, long ymax){return(0);} unsigned int SaveAsCommentedSif(char* path, char* comment){return(0);} unsigned int SaveAsEDF(char* _szPath, int _iMode){return(0);} unsigned int SaveAsFITS(char* szFileTitle, int type){return(0);} unsigned int SaveAsRaw(char* szFileTitle, int type){return(0);} unsigned int SaveAsSif(char* path){return(0);} unsigned int SaveAsSPC(char* path){return(0);} unsigned int SaveAsTiff(char* path, char* palette, int position, int type){return(0);} unsigned int SaveAsTiffEx(char* path, char* palette, int position, int type, int _mode){return(0);} unsigned int SaveEEPROMToFile(char *cFileName){return(0);} unsigned int SaveToClipBoard(char* palette){return(0);} unsigned int SelectDevice(int devNum){return(0);} unsigned int SendSoftwareTrigger(void){return(0);} unsigned int SetAccumulationCycleTime(float time){return(0);} unsigned int SetAcqStatusEvent(HANDLE event){return(0);} unsigned int SetAcquisitionMode(int mode){return(0);} unsigned int SetAcquisitionType(int type){return(0);} unsigned int SetADChannel(int channel){return(0);} unsigned int SetAdvancedTriggerModeState(int _istate){return(0);} unsigned int SetBackground(at_32* array, unsigned long size){return(0);} unsigned int SetBaselineClamp(int state){return(0);} unsigned int SetBaselineOffset(int offset){return(0);} unsigned int SetCameraStatusEnable(DWORD Enable){return(0);} unsigned int SetComplexImage(int numAreas, int* areas){return(0);} unsigned int SetCoolerMode(int mode){return(0);} unsigned int SetCropMode(int active, int cropheight, int reserved){return(0);} unsigned int SetCurrentCamera(long cameraHandle){return(0);} unsigned int SetCustomTrackHBin(int bin){return(0);} unsigned int SetDataType(int type){return(0);} unsigned int SetDDGAddress(BYTE t0, BYTE t1, BYTE t2, BYTE tt, BYTE address){return(0);} unsigned int SetDDGGain(int gain){return(0);} unsigned int SetDDGGateStep(double step){return(0);} unsigned int SetDDGInsertionDelay(int state){return(0);} unsigned int SetDDGIntelligate(int state){return(0);} unsigned int SetDDGIOC(int state){return(0);} unsigned int SetDDGIOCFrequency(double frequency){return(0);} unsigned int SetDDGIOCNumber(unsigned long number_pulses){return(0);} // DDG Lite functions unsigned int SetDDGLiteGlobalControlByte(unsigned char _byte){return(0);} unsigned int SetDDGLiteControlByte(AT_DDGLiteChannelId _channel, unsigned char _byte){return(0);} unsigned int SetDDGLiteInitialDelay(AT_DDGLiteChannelId _channel, float _f_delay){return(0);} unsigned int SetDDGLitePulseWidth(AT_DDGLiteChannelId _channel, float _f_width){return(0);} unsigned int SetDDGLiteInterPulseDelay(AT_DDGLiteChannelId _channel, float _f_delay){return(0);} unsigned int SetDDGLitePulsesPerExposure(AT_DDGLiteChannelId _channel, at_u32 _ui32_pulses){return(0);} unsigned int SetDDGTimes(double t0, double t1, double t2){return(0);} unsigned int SetDDGTriggerMode(int mode){return(0);} unsigned int SetDDGVariableGateStep(int mode, double p1, double p2){return(0);} unsigned int SetDelayGenerator(int board, short address, int type){return(0);} unsigned int SetDMAParameters(int MaxImagesPerDMA, float SecondsPerDMA){return(0);} unsigned int SetDriverEvent(HANDLE event){return(0);} unsigned int SetEMAdvanced(int state){return(0);} unsigned int SetEMCCDGain(int gain){return(0);} unsigned int SetEMClockCompensation(int EMClockCompensationFlag){return(0);} unsigned int SetEMGainMode(int mode){return(0);} unsigned int SetExposureTime(float time){return(0);} unsigned int SetFanMode(int mode){return(0);} unsigned int SetFastExtTrigger(int mode){return(0);} unsigned int SetFastKinetics(int exposedRows, int seriesLength, float time, int mode, int hbin, int vbin){return(0);} unsigned int SetFastKineticsEx(int exposedRows, int seriesLength, float time, int mode, int hbin, int vbin, int offset){return(0);} unsigned int SetFilterMode(int mode){return(0);} unsigned int SetFilterParameters(int width, float sensitivity, int range, float accept, int smooth, int noise){return(0);} unsigned int SetFKVShiftSpeed(int index){return(0);} unsigned int SetFPDP(int state){return(0);} unsigned int SetFrameTransferMode(int mode){return(0);} unsigned int SetFullImage(int hbin, int vbin){return(0);} unsigned int SetFVBHBin(int bin){return(0);} unsigned int SetGain(int gain){return(0);} unsigned int SetGate(float delay, float width, float step){return(0);} unsigned int SetGateMode(int gatemode){return(0);} unsigned int SetHighCapacity(int state){return(0);} unsigned int SetHorizontalSpeed(int index){return(0);} unsigned int SetHSSpeed(int type, int index){return(0);} unsigned int SetImage(int hbin, int vbin, int hstart, int hend, int vstart, int vend){return(0);} unsigned int SetImageFlip(int iHFlip, int iVFlip){return(0);} unsigned int SetImageRotate(int iRotate){return(0);} unsigned int SetIsolatedCropMode (int active, int cropheight, int cropwidth, int vbin, int hbin){return(0);} unsigned int SetKineticCycleTime(float time){return(0);} unsigned int SetMCPGain(int gain){return(0);} unsigned int SetMCPGating(int gating){return(0);} unsigned int SetMessageWindow(HWND wnd){return(0);} unsigned int SetMultiTrack(int number, int height, int offset,int* bottom,int* gap){return(0);} unsigned int SetMultiTrackHBin(int bin){return(0);} unsigned int SetMultiTrackHRange(int _iStart, int _iEnd){return(0);} unsigned int SetNextAddress(at_32* data, long lowAdd, long highAdd, long len, long physical){return(0);} unsigned int SetNextAddress16(at_32* data, long lowAdd, long highAdd, long len, long physical){return(0);} unsigned int SetNumberAccumulations(int number){return(0);} unsigned int SetNumberKinetics(int number){return(0);} unsigned int SetNumberPrescans(int _i_number){return(0);} unsigned int SetOutputAmplifier(int type){return(0);} unsigned int SetPCIMode(int mode,int value){return(0);} unsigned int SetPhotonCounting(int state){return(0);} unsigned int SetPhotonCountingThreshold(long min, long max){return(0);} unsigned int SetPixelMode(int bitdepth, int colormode){return(0);} unsigned int SetPreAmpGain(int index){return(0);} unsigned int SetRandomTracks(int numTracks, int* areas){return(0);} unsigned int SetReadMode(int mode){return(0);} unsigned int SetRegisterDump(int mode){return(0);} unsigned int SetRingExposureTimes(int numTimes, float *times){return(0);} unsigned int SetSaturationEvent(HANDLE event){return(0);} unsigned int SetShutter(int type, int mode, int closingtime, int openingtime){return(0);} unsigned int SetShutterEx(int type, int mode, int closingtime, int openingtime, int ext_mode){return(0);} unsigned int SetShutters(int type, int mode, int closingtime, int openingtime, int ext_type, int ext_mode, int dummy1, int dummy2){return(0);} unsigned int SetSifComment(char* comment){return(0);} unsigned int SetSingleTrack(int centre, int height){return(0);} unsigned int SetSingleTrackHBin(int bin){return(0);} unsigned int SetSpool(int active, int method, char* path, int framebuffersize){return(0);} unsigned int SetStorageMode(long mode){return(0);} unsigned int SetTemperature(int temperature){return(0);} unsigned int SetTriggerMode(int mode){return(0);} unsigned int SetUserEvent(HANDLE event){return(0);} unsigned int SetUSGenomics(long width, long height){return(0);} unsigned int SetVerticalRowBuffer(int rows){return(0);} unsigned int SetVerticalSpeed(int index){return(0);} unsigned int SetVirtualChip(int state){return(0);} unsigned int SetVSAmplitude(int index){return(0);} unsigned int SetVSSpeed(int index){return(0);} unsigned int ShutDown(void){return(0);} unsigned int StartAcquisition(void){return(0);} unsigned int UnMapPhysicalAddress(void){return(0);} unsigned int WaitForAcquisition(void){return(0);} unsigned int WaitForAcquisitionByHandle(long cameraHandle){return(0);} unsigned int WaitForAcquisitionByHandleTimeOut(long cameraHandle, int _iTimeOutMs){return(0);} unsigned int WaitForAcquisitionTimeOut(int _iTimeOutMs){return(0);} unsigned int WhiteBalance(WORD* _wRed, WORD* _wGreen, WORD* _wBlue, float *_fRelR, float *_fRelB, WhiteBalanceInfo *_info){return(0);}
66.32342
200
0.779553
jlprieur
1110fab520e853673a70ebe0815b8879209eb52c
3,121
cpp
C++
inference-engine/src/vpu/graph_transformer/src/middleend/passes/propagate_dynamism_to_outputs.cpp
mpenkows/openvino
438c69411a16f58f279f444582eec892916d5a8c
[ "Apache-2.0" ]
null
null
null
inference-engine/src/vpu/graph_transformer/src/middleend/passes/propagate_dynamism_to_outputs.cpp
mpenkows/openvino
438c69411a16f58f279f444582eec892916d5a8c
[ "Apache-2.0" ]
null
null
null
inference-engine/src/vpu/graph_transformer/src/middleend/passes/propagate_dynamism_to_outputs.cpp
mpenkows/openvino
438c69411a16f58f279f444582eec892916d5a8c
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "vpu/middleend/pass_manager.hpp" #include <set> #include <memory> namespace vpu { namespace { class PassImpl final : public Pass { public: explicit PassImpl(StageBuilder::Ptr stageBuilder) : _stageBuilder(std::move(stageBuilder)) {} void run(const Model& model) override { for (const auto& data : model->datas()) { if (data->usage() != DataUsage::Output || data->parentDataToShapeEdge() != nullptr) { continue; } const auto& producer = data->producer(); VPU_THROW_UNLESS(producer, "Output data must have a producer, but {} doesn't have", data->name()); if (producer->type() != StageType::Convert) { continue; } VPU_THROW_UNLESS(producer->numInputs() == 1, "Only single input producers are supported, but {} has {} inputs", producer->name(), producer->numInputs()); const auto& input = producer->input(0); const auto& parentDataToShapeEdge = input->parentDataToShapeEdge(); if (parentDataToShapeEdge == nullptr) { continue; } const auto parent = parentDataToShapeEdge->parent(); const auto& parentAttrs = parent->attrs(); VPU_THROW_UNLESS(parentAttrs.getOrDefault("converted-notation", false), "All shape parent data object must be already converted to MDK notation, but {} is in IE notation", parent->name()); const auto& parentInIENotation = parent->producer()->input(0); const auto& parentInIENotationAttrs = parentInIENotation->attrs(); VPU_THROW_UNLESS(parentInIENotationAttrs.getOrDefault("IE-notation", false), "Data object {} is expected to be shape in IE notation, but is not marked as it", parentInIENotation->name()); VPU_THROW_UNLESS(parentInIENotation->usage() == DataUsage::Intermediate, "Shape data object in IE notation {} is expected to be an {} data object, but it has usage {}", parentInIENotation->name(), DataUsage::Intermediate, parentInIENotation->usage()); model->connectDataWithShape(parent, data); // MyriadInferRequest::GetResult assumes that dynamic data object has shape data object // with the same name + suffix "@shape" const auto shapeName = data->name() + "@shape"; const auto& shapeOutput = model->addOutputData(shapeName, parentInIENotation->desc()); _stageBuilder->addCopyStage( model, "copy-for-dynamic-output", nullptr, parentInIENotation, shapeOutput, "PropagateDynamismToOutput"); } } private: StageBuilder::Ptr _stageBuilder; }; } // namespace Pass::Ptr PassManager::propagateDynamismToOutputs() { return std::make_shared<PassImpl>(_stageBuilder); } } // namespace vpu
36.717647
115
0.604614
mpenkows
111225b73f892dfdc834d3596a2d948bbbdd37a2
1,026
hpp
C++
libs/systems/include/sge/systems/window.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/systems/include/sge/systems/window.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/systems/include/sge/systems/window.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_SYSTEMS_WINDOW_HPP_INCLUDED #define SGE_SYSTEMS_WINDOW_HPP_INCLUDED #include <sge/systems/window_fwd.hpp> #include <sge/systems/window_source.hpp> #include <sge/systems/detail/symbol.hpp> namespace sge::systems { class window { public: SGE_SYSTEMS_DETAIL_SYMBOL explicit window(sge::systems::window_source &&); [[nodiscard]] SGE_SYSTEMS_DETAIL_SYMBOL sge::systems::window dont_show() &&; [[nodiscard]] SGE_SYSTEMS_DETAIL_SYMBOL sge::systems::window dont_quit() &&; [[nodiscard]] SGE_SYSTEMS_DETAIL_SYMBOL sge::systems::window hide_cursor() &&; [[nodiscard]] sge::systems::window_source const &source() const; [[nodiscard]] bool show() const; [[nodiscard]] bool quit() const; private: sge::systems::window_source source_; bool show_; bool quit_; }; } #endif
22.8
80
0.72807
cpreh
11145c3a1ad05f911c8547ab86977a5962be7502
1,262
cpp
C++
src/PSV_Utils.cpp
MSeys/PSV_2DCore_samples
3942c75391aeda9172dfed75165e80b5628a7a60
[ "MIT" ]
null
null
null
src/PSV_Utils.cpp
MSeys/PSV_2DCore_samples
3942c75391aeda9172dfed75165e80b5628a7a60
[ "MIT" ]
null
null
null
src/PSV_Utils.cpp
MSeys/PSV_2DCore_samples
3942c75391aeda9172dfed75165e80b5628a7a60
[ "MIT" ]
null
null
null
#include "PSV_Utils.h" PSV_TouchSamplingMode PSV_TSMode{ PSV_TOUCH_MOTION }; // 0 is reserved for drawing when there is no transformation int PSV_CT{ 0 }; std::vector<Vector2f> PSV_Translations{ Vector2f{ 0, 0 } }; std::vector<Scale2f> PSV_Scales{ Scale2f{ 1, 1 } }; bool PSV_Allowed{ false }; void PSV_SetTouchSamplingMode(const PSV_TouchSamplingMode& psvTouchSamplingMode) { PSV_TSMode = psvTouchSamplingMode; } void PSV_Begin() { if (PSV_CT == 0) { PSV_Allowed = true; } PSV_CT++; Scale2f scales{ 1, 1 }; Vector2f translations{ 0, 0 }; for(int i{ 1 }; i < PSV_CT; i++) { scales.x *= PSV_Scales[i].x; scales.y *= PSV_Scales[i].y; translations.x += PSV_Translations[i].x; translations.y += PSV_Translations[i].y; } PSV_Scales.push_back(scales); PSV_Translations.push_back(translations); } void PSV_Translate(float x, float y) { if(!PSV_Allowed) { return; } PSV_Translations[PSV_CT].x += x; PSV_Translations[PSV_CT].y += y; } void PSV_Scale(float x, float y) { if (!PSV_Allowed) { return; } PSV_Scales[PSV_CT].x *= x; PSV_Scales[PSV_CT].y *= y; } void PSV_End() { if(PSV_CT > 0) { PSV_CT--; PSV_Scales.pop_back(); PSV_Translations.pop_back(); } if (PSV_CT == 0) { PSV_Allowed = false; } }
15.775
80
0.674326
MSeys
11191d13042be879ca1b85e70c0a49aa5fdf32c8
113
cpp
C++
src/asn1/Asn1Sequence.cpp
LabSEC/libcryptosec
e53030ec32b52b6abeaa973a9f0bfba0eb2c2440
[ "BSD-3-Clause" ]
22
2015-08-26T16:40:59.000Z
2022-02-22T19:52:55.000Z
src/asn1/Asn1Sequence.cpp
LabSEC/Libcryptosec
e53030ec32b52b6abeaa973a9f0bfba0eb2c2440
[ "BSD-3-Clause" ]
14
2015-09-01T00:39:22.000Z
2018-12-17T16:24:28.000Z
src/asn1/Asn1Sequence.cpp
LabSEC/Libcryptosec
e53030ec32b52b6abeaa973a9f0bfba0eb2c2440
[ "BSD-3-Clause" ]
22
2015-08-31T19:17:37.000Z
2021-01-04T13:38:35.000Z
#include <libcryptosec/asn1/Asn1Sequence.h> Asn1Sequence::Asn1Sequence() { } Asn1Sequence::~Asn1Sequence() { }
11.3
43
0.743363
LabSEC
1119f16640fa86183026819b3f5d8c4f5b025ee1
145
hpp
C++
Source/Tools/alive_api/AEJsonUpgrader.hpp
THEONLYDarkShadow/alive_reversing
680d87088023f2d5f2a40c42d6543809281374fb
[ "MIT" ]
1
2021-04-11T23:44:43.000Z
2021-04-11T23:44:43.000Z
Source/Tools/alive_api/AEJsonUpgrader.hpp
THEONLYDarkShadow/alive_reversing
680d87088023f2d5f2a40c42d6543809281374fb
[ "MIT" ]
null
null
null
Source/Tools/alive_api/AEJsonUpgrader.hpp
THEONLYDarkShadow/alive_reversing
680d87088023f2d5f2a40c42d6543809281374fb
[ "MIT" ]
null
null
null
#pragma once #include "JsonUpgrader.hpp" class AEJsonUpgrader : public BaseJsonUpgrader { public: virtual void AddUpgraders() override; };
14.5
46
0.758621
THEONLYDarkShadow
111c303a55d067f1ab1ec11f263587d516e1cd6e
2,618
cpp
C++
example/main.cpp
Megaxela/CodeExecutor
4d4f4e6ffb298e250e04edb23a29bf90c3e0d43a
[ "MIT" ]
3
2020-05-22T09:24:30.000Z
2020-11-06T15:16:04.000Z
example/main.cpp
Megaxela/CodeExecutor
4d4f4e6ffb298e250e04edb23a29bf90c3e0d43a
[ "MIT" ]
null
null
null
example/main.cpp
Megaxela/CodeExecutor
4d4f4e6ffb298e250e04edb23a29bf90c3e0d43a
[ "MIT" ]
2
2020-05-12T03:28:11.000Z
2020-11-18T09:48:27.000Z
#include <iostream> #include <CodeExecutor/Builder.hpp> #include <CodeExecutor/Process.hpp> #include <CodeExecutor/CommonCompiler.hpp> #include <CodeExecutor/CommonLinker.hpp> static const char* source1Example = "#include <iostream>\n" "extern \"C\" int func(int a, int b)" "{" " std::cout << a + b << std::endl;" "}"; static const char* source2Example = "extern \"C\" int func2(int a, int b, int c)" "{" " return a + b + c;" "}"; int main(int argc, char** argv) { CodeExecutor::Builder builder; // Setting compiler instance builder.setCompiler( std::make_shared<CodeExecutor::CommonCompiler>( "/usr/bin/gcc" ) ); // Setting linker instance builder.setLinker( std::make_shared<CodeExecutor::CommonLinker>( "/usr/bin/gcc" ) ); // Adding build target builder.addTarget( // Creating source object from actual source CodeExecutor::Source::createFromSource(source1Example) ); // Building library CodeExecutor::LibraryPtr result; try { result = builder.build(); } catch (std::runtime_error &e) { // Catching compilation or linkage errors std::cerr << "Can't build sources. Error: " << e.what() << std::endl; return -1; } // Resolving function from built library auto func = result->resolveFunction<int(int, int)>("func"); // Checking resolving result if (func == nullptr) { std::cerr << "Can't resolve function: " << result->errorString() << std::endl; return 1; } // Clearing targets builder.clearTargets(); // Adding new target builder.addTarget( // Catching compilation or linkage errors CodeExecutor::Source::createFromSource(source2Example) ); // Building second library CodeExecutor::LibraryPtr result2; try { result2 = builder.build(); } catch (std::runtime_error &e) { // Catching compilation or linkage errors std::cerr << "Can't build sources. Error: " << e.what() << std::endl; return -1; } // Resolving second function auto func2 = result2->resolveFunction<int(int, int, int)>("func2"); // Checking resolve result if (func2 == nullptr) { std::cerr << result2->errorString() << std::endl; return 1; } // Running resolved functions std::cout << "Executing func(12, 13): "; func(12, 13); std::cout << "Executing func2(1, 2, 3): " << func2(1, 2, 3) << std::endl; return 0; }
23.585586
86
0.585943
Megaxela
111c635e4c628c2a19ad779ec3b5d4367200a25f
983
hpp
C++
src/ParallelAlgorithms/Events/Factory.hpp
isha1810/spectre
fc22b6cc9c64d7ebc7f6ffef3252056358673558
[ "MIT" ]
null
null
null
src/ParallelAlgorithms/Events/Factory.hpp
isha1810/spectre
fc22b6cc9c64d7ebc7f6ffef3252056358673558
[ "MIT" ]
null
null
null
src/ParallelAlgorithms/Events/Factory.hpp
isha1810/spectre
fc22b6cc9c64d7ebc7f6ffef3252056358673558
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include <cstddef> #include <type_traits> #include "ParallelAlgorithms/Events/ObserveErrorNorms.hpp" #include "ParallelAlgorithms/Events/ObserveFields.hpp" #include "ParallelAlgorithms/Events/ObserveTimeStep.hpp" #include "Time/Actions/ChangeSlabSize.hpp" #include "Utilities/TMPL.hpp" namespace dg::Events { template <size_t VolumeDim, typename TimeTag, typename Fields, typename SolutionFields> using field_observations = tmpl::flatten<tmpl::list< ObserveFields<VolumeDim, TimeTag, Fields, SolutionFields>, tmpl::conditional_t<std::is_same_v<SolutionFields, tmpl::list<>>, tmpl::list<>, ObserveErrorNorms<TimeTag, SolutionFields>>>>; } // namespace dg::Events namespace Events { template <typename Metavars> using time_events = tmpl::list<Events::ObserveTimeStep<Metavars>, Events::ChangeSlabSize>; } // namespace Events
32.766667
74
0.734486
isha1810
111fa1fff1f3ff3fb6f6c4d8df923964b5c3175d
2,996
cpp
C++
query_optimizer/LogicalGenerator.cpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
82
2016-04-18T03:59:06.000Z
2019-02-04T11:46:08.000Z
query_optimizer/LogicalGenerator.cpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
265
2016-04-19T17:52:43.000Z
2018-10-11T17:55:08.000Z
query_optimizer/LogicalGenerator.cpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
68
2016-04-18T05:00:34.000Z
2018-10-30T12:41:02.000Z
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ #include "query_optimizer/LogicalGenerator.hpp" #include <memory> #include <vector> #include "parser/ParseStatement.hpp" #include "query_optimizer/OptimizerContext.hpp" #include "query_optimizer/Validator.hpp" #include "query_optimizer/logical/Logical.hpp" #include "query_optimizer/resolver/Resolver.hpp" #include "query_optimizer/rules/CollapseProject.hpp" #include "query_optimizer/rules/GenerateJoins.hpp" #include "query_optimizer/rules/PushDownFilter.hpp" #include "query_optimizer/rules/PushDownSemiAntiJoin.hpp" #include "query_optimizer/rules/Rule.hpp" #include "query_optimizer/rules/UnnestSubqueries.hpp" #include "glog/logging.h" namespace quickstep { namespace optimizer { namespace L = ::quickstep::optimizer::logical; LogicalGenerator::LogicalGenerator(OptimizerContext *optimizer_context) : optimizer_context_(optimizer_context) {} LogicalGenerator::~LogicalGenerator() {} L::LogicalPtr LogicalGenerator::generatePlan( const CatalogDatabase &catalog_database, const ParseStatement &parse_statement) { resolver::Resolver resolver(catalog_database, optimizer_context_); DVLOG(4) << "Parse tree:\n" << parse_statement.toString(); logical_plan_ = resolver.resolve(parse_statement); DVLOG(4) << "Initial logical plan:\n" << logical_plan_->toString(); optimizePlan(); DVLOG(4) << "Optimized logical plan:\n" << logical_plan_->toString(); return logical_plan_; } void LogicalGenerator::optimizePlan() { std::vector<std::unique_ptr<Rule<L::Logical>>> rules; if (optimizer_context_->has_nested_queries()) { rules.emplace_back(new UnnestSubqueries(optimizer_context_)); } rules.emplace_back(new PushDownSemiAntiJoin()); rules.emplace_back(new PushDownFilter()); rules.emplace_back(new GenerateJoins()); rules.emplace_back(new PushDownFilter()); rules.emplace_back(new CollapseProject()); for (std::unique_ptr<Rule<L::Logical>> &rule : rules) { logical_plan_ = rule->apply(logical_plan_); DVLOG(5) << "After applying rule " << rule->getName() << ":\n" << logical_plan_->toString(); } #ifdef QUICKSTEP_DEBUG Validate(logical_plan_); #endif } } // namespace optimizer } // namespace quickstep
34.436782
71
0.756342
Hacker0912
11247b0a46266ea1827ed45e5ec5498869d38f80
1,035
cpp
C++
helperlib/fourier.cpp
Ben1980/fourier
7edd8e7004a528d574584cba08d8c653edc5ee41
[ "MIT" ]
null
null
null
helperlib/fourier.cpp
Ben1980/fourier
7edd8e7004a528d574584cba08d8c653edc5ee41
[ "MIT" ]
null
null
null
helperlib/fourier.cpp
Ben1980/fourier
7edd8e7004a528d574584cba08d8c653edc5ee41
[ "MIT" ]
2
2020-03-25T15:54:40.000Z
2020-08-31T08:42:56.000Z
#include "fourier.h" #include <algorithm> #include <cmath> bool Fourier::Equal(const Coefficients& expected, const Coefficients& result) { if(!expected || !result) return false; if(expected().size() != result().size()) return false; const bool equal = std::equal(expected().begin(), expected().end(), result().begin(), [](const Coefficients::Coefficient& expected, const Coefficients::Coefficient& result) { const bool equalOrder = (expected.order - result.order) == 0; const bool equalA = Equal(expected.a, result.a); const bool equalB = Equal(expected.b, result.b); return equalOrder && equalA && equalB; }); return equal; } bool Fourier::Equal(double expected, double result, double maximumDelta) { if(expected > std::numeric_limits<double>::min()) { // Test case for values unequal to 0 return std::fabs(result/expected - 1) <= maximumDelta; } // Test case for values equal to 0 return std::fabs(result) <= std::numeric_limits<double>::min(); }
34.5
92
0.66087
Ben1980
1126843072c418bbb69d2c4511b0610d92d88e13
5,408
cpp
C++
tests/cthread/test_cthread_read_defined_3.cpp
hachetman/systemc-compiler
0cc81ace03336d752c0146340ff5763a20e3cefd
[ "Apache-2.0" ]
86
2020-10-23T15:59:47.000Z
2022-03-28T18:51:19.000Z
tests/cthread/test_cthread_read_defined_3.cpp
hachetman/systemc-compiler
0cc81ace03336d752c0146340ff5763a20e3cefd
[ "Apache-2.0" ]
18
2020-12-14T13:11:26.000Z
2022-03-14T05:34:20.000Z
tests/cthread/test_cthread_read_defined_3.cpp
hachetman/systemc-compiler
0cc81ace03336d752c0146340ff5763a20e3cefd
[ "Apache-2.0" ]
17
2020-10-29T16:19:43.000Z
2022-03-11T09:51:05.000Z
/****************************************************************************** * Copyright (c) 2020, Intel Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception. * *****************************************************************************/ // // Created by ripopov on 12/4/18. // #include "systemc.h" #include <sct_assert.h> // Channels and channel arrays defined and read tests class A : public sc_module { public: sc_signal<bool> clk{"clk"}; sc_signal<bool> nrst{"nrst"}; sc_signal<unsigned> s; SC_CTOR(A) { SC_CTHREAD(write_sig_thread, clk); async_reset_signal_is(nrst, false); SC_CTHREAD(read_sig_thread, clk); async_reset_signal_is(nrst, false); bsignal_ptr_arr[0] = new sc_signal<bool>("bsig_0"); bsignal_ptr_arr[1] = new sc_signal<bool>("bsig_1"); csignal_ptr_arr[0] = new sc_signal<bool>("csig_0"); csignal_ptr_arr[1] = new sc_signal<bool>("csig_1"); } sc_signal<bool> bsignal{"bsignal"}; sc_signal<bool> bsignal_array[2]; sc_signal<bool> bsignal_array2d[2][2]; sc_signal<bool> *bsignal_ptr = new sc_signal<bool>("bsignal_ptr"); sc_signal<bool> *bsignal_array_ptr = new sc_signal<bool>[2]; sc_signal<bool> *bsignal_ptr_arr[2]; sc_signal<bool> csignal{"csignal"}; sc_signal<bool> csignal_array[2]; sc_signal<bool> csignal_array2d[2][2]; sc_signal<bool> *csignal_ptr = new sc_signal<bool>("csignal_ptr"); sc_signal<bool> *csignal_array_ptr = new sc_signal<bool>[2]; sc_signal<bool> *csignal_ptr_arr[2]; void write_sig_thread() { bsignal = false; bsignal_array[s.read()] = false; bsignal_array2d[s.read()][1] = false; bsignal_ptr->write(false); bsignal_array_ptr[1] = false; bsignal_ptr_arr[0]->write(false); sct_assert_defined(bsignal); sct_assert_defined(*bsignal_ptr); sct_assert_array_defined(bsignal_array); sct_assert_array_defined(bsignal_array2d); sct_assert_array_defined(bsignal_array_ptr); sct_assert_array_defined(*bsignal_ptr_arr); wait(); while (1) { bsignal = true; bsignal_array[0] = bsignal; bsignal_array2d[1][s.read()] = true; bsignal_ptr->write(bsignal_array[s.read()]); bsignal_array_ptr[s.read()] = bsignal_ptr->read(); bsignal_ptr_arr[s.read()+1]->write(bsignal_array_ptr[0]); sct_assert_defined(bsignal); sct_assert_read(bsignal); sct_assert_array_defined(bsignal_array); sct_assert_read(bsignal_array); sct_assert_array_defined(bsignal_array2d); sct_assert_read(bsignal_array2d, false); sct_assert_array_defined(bsignal_array_ptr); sct_assert_read(bsignal_array_ptr); sct_assert_array_defined(bsignal_ptr_arr); sct_assert_read(bsignal_ptr_arr, false); wait(); } } void read_sig_thread() { csignal = false; if (s) { csignal_array[0] = false; } csignal_array2d[1][0] = false; csignal_ptr->write(false); csignal_array_ptr[1] = false; csignal_ptr_arr[0]->write(false); sct_assert_defined(csignal); sct_assert_defined(*csignal_ptr); sct_assert_array_defined(csignal_array); sct_assert_array_defined(csignal_array_ptr); sct_assert_read(csignal_array_ptr, false); wait(); while (1) { bool b = csignal; csignal = !csignal; sct_assert_defined(csignal); sct_assert_read(csignal); b = csignal_array[0]; csignal_array[0] = csignal_array[1]; csignal_array[1] = csignal_array[0]; sct_assert_array_defined(csignal_array); sct_assert_read(csignal_array); b = csignal_array2d[1][0]; csignal_array2d[1][0] = csignal; sct_assert_array_defined(csignal_array2d); sct_assert_read(csignal_array2d); wait(); b = csignal; sct_assert_register(csignal); sct_assert_defined(csignal, false); sct_assert_read(csignal); csignal_ptr->write(b); b = csignal_ptr->read(); sct_assert_register(*csignal_ptr, false); sct_assert_defined(*csignal_ptr); sct_assert_read(*csignal_ptr); if (s.read()) { b = csignal_array_ptr[s.read()]; csignal_array_ptr[s.read()] = !b; } sct_assert_array_defined(csignal_array_ptr); sct_assert_read(csignal_array_ptr); sct_assert_register(csignal_array_ptr); while (s.read()) { b = *csignal_ptr_arr[csignal_array_ptr[0]]; csignal_ptr_arr[csignal_array2d[0][s.read()]]->write(true); sct_assert_array_defined(csignal_ptr_arr); sct_assert_read(csignal_ptr_arr); wait(); } } } }; int sc_main(int argc, char* argv[]) { A a_mod{"b_mod"}; sc_start(); return 0; }
32
79
0.571006
hachetman
112a10fafc301bd5da5276252f09e35d75868bbf
1,016
cpp
C++
src/ConvexConcaveCollisionAlgorithm.cpp
yoshinoToylogic/bulletsharp
79558f9e78b68f1d218d64234645848661a54e01
[ "MIT" ]
null
null
null
src/ConvexConcaveCollisionAlgorithm.cpp
yoshinoToylogic/bulletsharp
79558f9e78b68f1d218d64234645848661a54e01
[ "MIT" ]
null
null
null
src/ConvexConcaveCollisionAlgorithm.cpp
yoshinoToylogic/bulletsharp
79558f9e78b68f1d218d64234645848661a54e01
[ "MIT" ]
null
null
null
#include "StdAfx.h" #ifndef DISABLE_COLLISION_ALGORITHMS #include "CollisionObject.h" #include "CollisionObjectWrapper.h" #include "ConvexConcaveCollisionAlgorithm.h" ConvexConcaveCollisionAlgorithm::CreateFunc::CreateFunc() : CollisionAlgorithmCreateFunc(new btConvexConcaveCollisionAlgorithm::CreateFunc()) { } ConvexConcaveCollisionAlgorithm::SwappedCreateFunc::SwappedCreateFunc() : CollisionAlgorithmCreateFunc(new btConvexConcaveCollisionAlgorithm::SwappedCreateFunc()) { } #define Native static_cast<btConvexConcaveCollisionAlgorithm*>(_native) ConvexConcaveCollisionAlgorithm::ConvexConcaveCollisionAlgorithm(CollisionAlgorithmConstructionInfo^ ci, CollisionObjectWrapper^ body0Wrap, CollisionObjectWrapper^ body1Wrap, bool isSwapped) : ActivatingCollisionAlgorithm(new btConvexConcaveCollisionAlgorithm(*ci->_native, body0Wrap->_native, body1Wrap->_native, isSwapped)) { } void ConvexConcaveCollisionAlgorithm::ClearCache() { Native->clearCache(); } #endif
29.028571
105
0.813976
yoshinoToylogic
112acc7bafbf886dea086b46cb7e491d34d8ec71
2,194
cc
C++
login.cc
DSNP/dsnpd
0670d60c80a407b8a399b7a456ce0b2c2d3ee6bd
[ "MIT" ]
null
null
null
login.cc
DSNP/dsnpd
0670d60c80a407b8a399b7a456ce0b2c2d3ee6bd
[ "MIT" ]
3
2021-02-04T00:26:22.000Z
2021-02-04T00:30:06.000Z
login.cc
DSNP/dsnpd
0670d60c80a407b8a399b7a456ce0b2c2d3ee6bd
[ "MIT" ]
null
null
null
/* * Copyright (c) 2009-2011, Adrian Thurston <thurston@complang.org> * * 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 "dsnp.h" #include "error.h" #include "keyagent.h" #include <string.h> #include <openssl/rand.h> void Server::login( const String &_user, const String &pass, const String &sessionId ) { const long lasts = LOGIN_TOKEN_LASTS; User user( mysql, _user ); /* Make a token first so we can pass it to the key agent. FIXME: need to * make sure it is unique. */ u_char tokenBin[TOKEN_SIZE]; RAND_bytes( tokenBin, TOKEN_SIZE ); String token = binToBase64( tokenBin, TOKEN_SIZE ); int check = keyAgent.checkPass( user.id(), pass, token ); if ( check == CHECK_PASS_OK ) { /* Record the token. */ DbQuery loginToken( mysql, "INSERT INTO login_token ( user_id, login_token, session_id, expires ) " "VALUES ( %L, %e, %e, date_add( now(), interval %l second ) )", user.id(), token(), sessionId(), lasts ); String idHash = makeIduriHash( user.iduri ); message("login of %s successful\n", user.iduri() ); bioWrap.returnOkLocal( idHash, token, lasts ); } else if ( check == CHECK_PASS_BAD_USER ) { /* The Reason should not be given away to the user. Just logged to the * logfile. */ throw InvalidLogin( user.iduri, pass, "bad user" ); } else if ( check == CHECK_PASS_BAD_PASS ) { throw InvalidLogin( user.iduri, pass, "bad pass" ); } else { /* Invalid result the key agent. */ throw InvalidLogin( user.iduri, pass, "unknown reason" ); } }
35.387097
86
0.707384
DSNP
112d8a47697576f7b2c6b8e9b86373b13629d8de
3,303
cpp
C++
Tests/substring.cpp
klassen-software-solutions/kssutil
985a80e96d648c448f2ac81d7dcbc48054e0c7aa
[ "MIT" ]
1
2019-05-08T16:45:02.000Z
2019-05-08T16:45:02.000Z
Tests/substring.cpp
klassen-software-solutions/kssutil
985a80e96d648c448f2ac81d7dcbc48054e0c7aa
[ "MIT" ]
14
2019-01-23T15:22:55.000Z
2021-08-27T23:23:42.000Z
Tests/substring.cpp
klassen-software-solutions/kssutil
985a80e96d648c448f2ac81d7dcbc48054e0c7aa
[ "MIT" ]
1
2022-02-05T09:04:53.000Z
2022-02-05T09:04:53.000Z
// // substring.cpp // kssutil // // Created by Steven W. Klassen on 2014-01-25. // Copyright (c) 2014 Klassen Software Solutions. All rights reserved. // #include <iostream> #include <kss/test/all.h> #include <kss/util/substring.hpp> using namespace std; using namespace kss::util; using namespace kss::util::strings; using namespace kss::test; namespace { template <class CHAR> class constants { public: static const CHAR* original_string; static const CHAR* is; static const CHAR* repl1; static const CHAR* after_first_write; static const CHAR* second_substr; static const CHAR a; static const CHAR* after_second_write; static const CHAR* after_third_write; }; template<> const char* constants<char>::original_string = "This is a test of the substring class."; template<> const wchar_t* constants<wchar_t>::original_string = L"This is a test of the substring class."; template<> const char* constants<char>::is = "is"; template<> const wchar_t* constants<wchar_t>::is = L"is"; template<> const char* constants<char>::repl1 = "XXXX"; template<> const wchar_t* constants<wchar_t>::repl1 = L"XXXX"; template<> const char* constants<char>::after_first_write = "This XXXX a test of the substring class."; template<> const wchar_t* constants<wchar_t>::after_first_write = L"This XXXX a test of the substring class."; template<> const char* constants<char>::second_substr = "is a test of the "; template<> const wchar_t* constants<wchar_t>::second_substr = L"is a test of the "; template<> const char constants<char>::a = 'A'; template<> const wchar_t constants<wchar_t>::a = L'A'; template<> const char* constants<char>::after_second_write = "This Asubstring class."; template<> const wchar_t* constants<wchar_t>::after_second_write = L"This Asubstring class."; template<> const char* constants<char>::after_third_write = "This XXXXsubstring class."; template<> const wchar_t* constants<wchar_t>::after_third_write = L"This XXXXsubstring class."; template <class CHAR> void substring_test_instance() { typedef basic_string<CHAR> str; typedef SubString<CHAR> substr; str s(constants<CHAR>::original_string); KSS_ASSERT(substr(s, 5, 2) == constants<CHAR>::is); KSS_ASSERT(substr(s, constants<CHAR>::is) == constants<CHAR>::is); substr(s, 5, 2) = constants<CHAR>::repl1; KSS_ASSERT(s == constants<CHAR>::after_first_write); substr(s, constants<CHAR>::repl1) = constants<CHAR>::is; KSS_ASSERT(s == constants<CHAR>::original_string); substr sub(s, 5, 17); KSS_ASSERT(sub == constants<CHAR>::second_substr); KSS_ASSERT(sub.size() == 17); KSS_ASSERT(!sub.empty()); sub = constants<CHAR>::a; KSS_ASSERT(sub.size() == 1); KSS_ASSERT(s == constants<CHAR>::after_second_write); sub = constants<CHAR>::repl1; KSS_ASSERT(sub.size() == 4); KSS_ASSERT(s == constants<CHAR>::after_third_write); } } static TestSuite ts("strings::substring", { make_pair("basic_substring<char>", substring_test_instance<char>), make_pair("basic_substring<wchar_t>", substring_test_instance<wchar_t>) });
38.406977
114
0.6703
klassen-software-solutions
112dc5e1ced9272942baca39a38edea5f4cd359e
728
cpp
C++
vm86/executeBytecodeOnHostMachine.cpp
Sainan/vm86
e9cf021c78bdfc03d250a0b10f55ff5213d1af89
[ "Unlicense" ]
1
2021-09-27T11:50:44.000Z
2021-09-27T11:50:44.000Z
vm86/executeBytecodeOnHostMachine.cpp
Sainan/vm86
e9cf021c78bdfc03d250a0b10f55ff5213d1af89
[ "Unlicense" ]
null
null
null
vm86/executeBytecodeOnHostMachine.cpp
Sainan/vm86
e9cf021c78bdfc03d250a0b10f55ff5213d1af89
[ "Unlicense" ]
null
null
null
#include "executeBytecodeOnHostMachine.hpp" #include <stdexcept> #include <windows.h> namespace vm86 { regvalue_t executeBytecodeOnHostMachine(const std::vector<uint8_t>& bytecode, regvalue_t reg_counter, regvalue_t reg_data) { void* const buffer = VirtualAlloc(nullptr, bytecode.size(), MEM_COMMIT, PAGE_READWRITE); if (buffer == nullptr) { throw std::runtime_error("VirtualAlloc failed"); } std::memcpy(buffer, bytecode.data(), bytecode.size()); DWORD old_protect; VirtualProtect(buffer, bytecode.size(), PAGE_EXECUTE_READ, &old_protect); const regvalue_t rax = ((regvalue_t(__fastcall*)(regvalue_t, regvalue_t))buffer)(reg_counter, reg_data); VirtualFree(buffer, 0, MEM_RELEASE); return rax; } }
30.333333
123
0.752747
Sainan
112e0c2bd4e0c9c1d0064ec2f4e6ff39a6e61bb9
4,368
cpp
C++
TestSrc/TestTokens.cpp
dirkcgrunwald/SAM
0478925c506ad38fd405954cc4415a3e96e77d90
[ "MIT" ]
null
null
null
TestSrc/TestTokens.cpp
dirkcgrunwald/SAM
0478925c506ad38fd405954cc4415a3e96e77d90
[ "MIT" ]
null
null
null
TestSrc/TestTokens.cpp
dirkcgrunwald/SAM
0478925c506ad38fd405954cc4415a3e96e77d90
[ "MIT" ]
null
null
null
#define BOOST_TEST_MAIN TestTokens #include <boost/test/unit_test.hpp> #include <stdexcept> #include <stack> #include <tuple> #include <sam/Tokens.hpp> #include <sam/VastNetflow.hpp> #include <sam/FeatureMap.hpp> using namespace sam; struct F { VastNetflow netflow; std::shared_ptr<FeatureMap> featureMap = std::make_shared<FeatureMap>(); std::stack<double> mystack; std::string key; F() { std::string s = "1,1,1365582756.384094,2013-04-10 08:32:36," "20130410083236.384094,17,UDP,172.20.2.18," "239.255.255.250,29986,1900,0,0,0,133,0,1,0,1,0,0"; netflow = makeNetflow(s); key = "key"; } ~F() { } }; BOOST_FIXTURE_TEST_CASE( test_number_token, F ) { NumberToken<VastNetflow> number(featureMap, DestIp); bool b = number.evaluate(mystack, key, netflow); BOOST_CHECK_EQUAL(b, true); BOOST_CHECK_EQUAL(mystack.top(), DestIp); } BOOST_FIXTURE_TEST_CASE( test_add_token, F ) { mystack.push(1.6); mystack.push(3.5); AddOperator<VastNetflow> addOper(featureMap); bool b = addOper.evaluate(mystack, key, netflow); BOOST_CHECK_EQUAL(b, true); BOOST_CHECK_EQUAL(mystack.top(), 5.1); b = addOper.evaluate(mystack, key, netflow); BOOST_CHECK_EQUAL(b, false); } BOOST_FIXTURE_TEST_CASE( test_sub_token, F ) { mystack.push(1.6); mystack.push(3.5); SubOperator<VastNetflow> subOper(featureMap); bool b = subOper.evaluate(mystack, key, netflow); BOOST_CHECK_EQUAL(b, true); BOOST_CHECK_EQUAL(mystack.top(), -1.9); b = subOper.evaluate(mystack, key, netflow); BOOST_CHECK_EQUAL(b, false); } BOOST_FIXTURE_TEST_CASE( test_mult_token, F ) { mystack.push(3); mystack.push(2); MultOperator<VastNetflow> multOper(featureMap); bool b = multOper.evaluate(mystack, key, netflow); BOOST_CHECK_EQUAL(b, true); BOOST_CHECK_EQUAL(mystack.top(), 6); b = multOper.evaluate(mystack, key, netflow); BOOST_CHECK_EQUAL(b, false); } BOOST_FIXTURE_TEST_CASE( test_field_token, F ) { FieldToken<TimeSeconds, VastNetflow> fieldToken(featureMap); bool b = fieldToken.evaluate(mystack, key, netflow); BOOST_CHECK_EQUAL(b, true); BOOST_CHECK_EQUAL(mystack.top(), 1365582756.384094); } BOOST_FIXTURE_TEST_CASE( test_func_token, F ) { std::string identifier = "top2"; std::string function = "value"; std::vector<double> parameters; parameters.push_back(1); auto func = [&function, &parameters](Feature const * feature)->double { auto topkFeature = static_cast<TopKFeature const *>(feature); if (function.compare(VALUE_FUNCTION) == 0) { if (parameters.size() != 1) { throw std::runtime_error("Expected there to be one parameter," " found " + boost::lexical_cast<std::string>(parameters.size())); } int index = boost::lexical_cast<int>(parameters[0]); return topkFeature->getFrequencies()[index]; } throw std::runtime_error("Evaluate with function " + function + " is not defined for class TopKFeature"); }; FuncToken<VastNetflow> funcToken(featureMap, func, identifier); // Nothing in featureMap, so should return false. bool b = funcToken.evaluate(mystack, key, netflow); BOOST_CHECK_EQUAL(b, false); std::vector<std::string> keys; std::vector<double> frequencies; keys.push_back("key1"); keys.push_back("key2"); frequencies.push_back(.4); frequencies.push_back(.3); TopKFeature feature(keys, frequencies); featureMap->updateInsert(key, identifier, feature); b = funcToken.evaluate(mystack, key, netflow); BOOST_CHECK_EQUAL(b, true); BOOST_CHECK_EQUAL(mystack.top(), .3); } BOOST_FIXTURE_TEST_CASE( test_prev_token, F ) { PrevToken<TimeSeconds, VastNetflow> prevToken1(featureMap); PrevToken<TimeSeconds, VastNetflow> prevToken2(featureMap); // We don't want the identifiers to be the same or that could cause problems. BOOST_CHECK(prevToken1.getIdentifier() != prevToken2.getIdentifier()); // First pass should have no previous value, so fails. bool b = prevToken1.evaluate(mystack, key, netflow); BOOST_CHECK_EQUAL(b, false); // Second pass should have previous value. b = prevToken1.evaluate(mystack, key, netflow); BOOST_CHECK_EQUAL(b, true); BOOST_CHECK_EQUAL(mystack.top(), 1365582756.384094); }
25.694118
79
0.688645
dirkcgrunwald
1131a29608fbbb76c124977c6e1437c9e2726135
335
cpp
C++
Codes/multiple_variables_declarations_&_constant.cpp
Felipe-Pereira-Barros/CPP
050add96024c8e5b0d01ebb6cab52452cbb6dff5
[ "MIT" ]
2
2020-05-21T14:44:36.000Z
2020-05-28T01:08:18.000Z
Codes/multiple_variables_declarations_&_constant.cpp
Felipe-Pereira-Barros/CPP
050add96024c8e5b0d01ebb6cab52452cbb6dff5
[ "MIT" ]
null
null
null
Codes/multiple_variables_declarations_&_constant.cpp
Felipe-Pereira-Barros/CPP
050add96024c8e5b0d01ebb6cab52452cbb6dff5
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; #define pi 3.1415 #define channel cout << "Felipe Pereira Barros\n\n"; int main(){ //int LIFE, AMMO, HEALTH; /*int LIFE; int AMMO; int HEALTH;*/ int LIFE=3; int AMMO=500; int HEALTH=100; cout << pi << "\n\n"; channel system("pause"); return 0; }
14.565217
52
0.576119
Felipe-Pereira-Barros
1134a720ba180c863b06ec264c436a5b9364aa46
501
cpp
C++
q/src/res/Impl/Free_Type_Font_Loader.cpp
jeanleflambeur/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
36
2015-03-09T16:47:14.000Z
2021-02-04T08:32:04.000Z
q/src/res/Impl/Free_Type_Font_Loader.cpp
jeanlemotan/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
42
2017-02-11T11:15:51.000Z
2019-12-28T16:00:44.000Z
q/src/res/Impl/Free_Type_Font_Loader.cpp
jeanleflambeur/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
5
2015-10-15T05:46:48.000Z
2020-05-11T17:40:36.000Z
#include "QStdAfx.h" #include "res/Resource.h" #include "text/Font.h" #include "Free_Type_Font_Loader.h" using namespace q; using namespace res; using namespace impl; using namespace data; using namespace text; bool Free_Type_Font_Loader::can_load_from_source(data::Source& /*source*/) const { return true; } void Free_Type_Font_Loader::load(Path const& /*path*/, data::Source& source, Font& font) const { font.unload(); source.seek(0); font.load_free_type(source); }
20.04
95
0.712575
jeanleflambeur
11368f5297c08c1bdcf850dd42ba2e324d86ecc4
496
cpp
C++
math_logics/factorial.cpp
sanathvernekar/Routine_codes
a898ca7e79cf39c289cb2fefaf764c9f8e0eb331
[ "MIT" ]
null
null
null
math_logics/factorial.cpp
sanathvernekar/Routine_codes
a898ca7e79cf39c289cb2fefaf764c9f8e0eb331
[ "MIT" ]
null
null
null
math_logics/factorial.cpp
sanathvernekar/Routine_codes
a898ca7e79cf39c289cb2fefaf764c9f8e0eb331
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define mod 1000000007 #define ll long long int ll factorial[2000000]; ll max_fact=1; ll fact(ll x){ ll i; if(x<=max_fact)return factorial[x]; else{ for(i=max_fact+1;i<=x;i++){ factorial[i]=(factorial[i-1]*i)%mod; } max_fact=x; return factorial[x]; } } int main() { factorial[0]=1; factorial[1]=1; ll t; cin>>t; while(t--){ ll n; cin>>n; cout<<fact(n)<<endl; } return 0; }
13.052632
48
0.560484
sanathvernekar
11395bed29ed905ef9ebbb97b267c6743d734db9
2,732
cpp
C++
MikaCL/main.cpp
acbarrentine/Mika
8d88f015360c1ab731da0fda1281a3327dcb9ec9
[ "Unlicense" ]
null
null
null
MikaCL/main.cpp
acbarrentine/Mika
8d88f015360c1ab731da0fda1281a3327dcb9ec9
[ "Unlicense" ]
null
null
null
MikaCL/main.cpp
acbarrentine/Mika
8d88f015360c1ab731da0fda1281a3327dcb9ec9
[ "Unlicense" ]
null
null
null
#include "stdafx.h" #include "../Compiler/Compiler.h" void Usage() { GCompiler.Message(MsgSeverity::kInfo, "Usage: MikaCL <glue_source_header_path> [-s <source_script_path>] [-o <output_file_path>] [-d <debug_file_path>]\n"); GCompiler.Message(MsgSeverity::kInfo, " Example: MikaCL TestScrits/MikaGlue.mikah -s TestScripts/FirstRun.mika -o TestScripts/Output/FirstRun.miko\n"); GCompiler.Message(MsgSeverity::kInfo, "Or, to generate glue:\n"); GCompiler.Message(MsgSeverity::kInfo, " MikaCL -glue <glue_source_header_path> <generated_native_glue_path>\n"); } void MakeGlue(const char* glueSource, const char* generatedGlue) { if (GCompiler.GetErrorCount() == 0) GCompiler.ReadGlueHeader(glueSource); if (GCompiler.GetErrorCount() == 0) GCompiler.ParseGlueHeader(); if (GCompiler.GetErrorCount() == 0) GCompiler.WriteGlueFile(generatedGlue); } int main(int argc, const char* argv[]) { if (argc < 2) { Usage(); return -1; } if (strncmp(argv[1], "-glue", 5) == 0) { if (argc < 4) { Usage(); return -1; } MakeGlue(argv[2], argv[3]); return 0; } std::string glueHeaderPath(argv[1]); std::string sourcePath; std::string objectPath; std::string debugPath; int argIndex = 2; while (argIndex < argc) { if ('-' == argv[argIndex][0]) { switch (argv[argIndex][1]) { case 's': sourcePath = argv[argIndex + 1]; argIndex += 2; break; case 'o': objectPath = argv[argIndex + 1]; argIndex += 2; break; case 'd': debugPath = argv[argIndex + 1]; argIndex += 2; break; default: ++argIndex; break; } } else { GCompiler.Message(MsgSeverity::kInfo, "Unknown command line option: '%s'\n", argv[argIndex]); Usage(); return -1; } } if (!glueHeaderPath.length() || (sourcePath.length() && !objectPath.length())) { Usage(); return -1; } if (GCompiler.GetErrorCount() == 0) GCompiler.ReadGlueHeader(glueHeaderPath.c_str()); if (GCompiler.GetErrorCount() == 0) GCompiler.ParseGlueHeader(); if (GCompiler.GetErrorCount() == 0) GCompiler.ReadScript(sourcePath.c_str()); if (GCompiler.GetErrorCount() == 0) GCompiler.ParseScript(); if (GCompiler.GetErrorCount() == 0) GCompiler.AnalyzeScript(); if (GCompiler.GetErrorCount() == 0) GCompiler.WriteObjectFile(objectPath.c_str(), debugPath.c_str()); return -GCompiler.GetErrorCount(); }
29.376344
160
0.577233
acbarrentine
113de64bfc72e1832c8714ad09ca78d608e0b49e
3,124
cpp
C++
tengine/game/entities/camera.cpp
BSVino/Digitanks
1bd1ed115493bce22001ae6684b70b8fcf135db0
[ "BSD-4-Clause" ]
5
2015-07-03T18:42:32.000Z
2017-08-25T10:28:12.000Z
tengine/game/entities/camera.cpp
BSVino/Digitanks
1bd1ed115493bce22001ae6684b70b8fcf135db0
[ "BSD-4-Clause" ]
null
null
null
tengine/game/entities/camera.cpp
BSVino/Digitanks
1bd1ed115493bce22001ae6684b70b8fcf135db0
[ "BSD-4-Clause" ]
null
null
null
#include "camera.h" #include <geometry.h> #include <game/cameramanager.h> REGISTER_ENTITY(CCamera); NETVAR_TABLE_BEGIN(CCamera); NETVAR_TABLE_END(); SAVEDATA_TABLE_BEGIN_EDITOR(CCamera); SAVEDATA_DEFINE_HANDLE_ENTITY(CSaveData::DATA_COPYTYPE, CEntityHandle<CBaseEntity>, m_hCameraTarget, "CameraTarget"); SAVEDATA_DEFINE_HANDLE_ENTITY(CSaveData::DATA_COPYTYPE, CEntityHandle<CBaseEntity>, m_hTrackStart, "TrackStart"); SAVEDATA_DEFINE_HANDLE_ENTITY(CSaveData::DATA_COPYTYPE, CEntityHandle<CBaseEntity>, m_hTrackEnd, "TrackEnd"); SAVEDATA_DEFINE_HANDLE_ENTITY(CSaveData::DATA_COPYTYPE, CEntityHandle<CBaseEntity>, m_hTargetStart, "TargetStart"); SAVEDATA_DEFINE_HANDLE_ENTITY(CSaveData::DATA_COPYTYPE, CEntityHandle<CBaseEntity>, m_hTargetEnd, "TargetEnd"); SAVEDATA_DEFINE_HANDLE_DEFAULT(CSaveData::DATA_COPYTYPE, float, m_flFOV, "FOV", 45); SAVEDATA_DEFINE_HANDLE_DEFAULT(CSaveData::DATA_COPYTYPE, float, m_flOrthoHeight, "OrthoHeight", 10); SAVEDATA_DEFINE_HANDLE_DEFAULT(CSaveData::DATA_COPYTYPE, bool, m_bOrtho, "Ortho", false); SAVEDATA_EDITOR_VARIABLE("Ortho"); SAVEDATA_EDITOR_VARIABLE("CameraTarget"); SAVEDATA_EDITOR_VARIABLE("TrackStart"); SAVEDATA_EDITOR_VARIABLE("TrackEnd"); SAVEDATA_EDITOR_VARIABLE("TargetStart"); SAVEDATA_EDITOR_VARIABLE("TargetEnd"); SAVEDATA_EDITOR_VARIABLE("FOV"); SAVEDATA_EDITOR_VARIABLE("OrthoHeight"); SAVEDATA_TABLE_END(); INPUTS_TABLE_BEGIN(CCamera); INPUTS_TABLE_END(); CCamera::~CCamera() { if (CameraManager()) CameraManager()->RemoveCamera(this); } void CCamera::Spawn() { TAssert(CameraManager()); CameraManager()->AddCamera(this); } void CCamera::CameraThink() { if (IsTracking()) { Vector vecTargetPosition = m_hCameraTarget->GetGlobalOrigin(); Vector vecTargetStart = m_hTargetStart->GetGlobalOrigin(); Vector vecTargetEnd = m_hTargetEnd->GetGlobalOrigin(); Vector vecClosestPoint; DistanceToLineSegment(vecTargetPosition, vecTargetStart, vecTargetEnd, &vecClosestPoint); float flTargetLength = (vecTargetEnd-vecTargetStart).Length(); TAssert(flTargetLength > 0); if (flTargetLength > 0) { float flLerp = (vecClosestPoint-vecTargetStart).Length()/flTargetLength; Vector vecTrackStart = m_hTrackStart->GetGlobalOrigin(); Vector vecTrackEnd = m_hTrackEnd->GetGlobalOrigin(); SetGlobalOrigin(vecTrackStart + (vecTrackEnd-vecTrackStart)*flLerp); Vector vecTrackStartDirection = (vecTargetStart-vecTrackStart).Normalized(); Vector vecTrackEndDirection = (vecTargetEnd-vecTrackEnd).Normalized(); SetGlobalAngles(VectorAngles(vecTrackStartDirection + (vecTrackEndDirection-vecTrackStartDirection)*flLerp)); } } } bool CCamera::IsTracking() { if (m_hCameraTarget && m_hTrackStart && m_hTrackEnd && m_hTargetStart && m_hTargetEnd) return true; return false; } void CCamera::OnActivated() { bool bSnap = false; if (s_sCurrentInput.length()) { tvector<tstring> asArgs; tstrtok(s_sCurrentInput, asArgs); for (size_t i = 1; i < asArgs.size(); i++) { if (asArgs[i].comparei("snap") == 0) { bSnap = true; break; } } } CameraManager()->SetActiveCamera(this, bSnap); }
29.752381
118
0.775288
BSVino
114492e420f2b0202b17594790b10c85305ce532
5,523
cpp
C++
libaln/src/alncalcconfidence.cpp
Bill-Armstrong/NANO
34356c2bcbc5e5b81383a0caf6da84dd0df03482
[ "MIT" ]
2
2020-10-05T21:48:53.000Z
2020-10-05T21:49:01.000Z
libaln/src/alncalcconfidence.cpp
Bill-Armstrong/NANO
34356c2bcbc5e5b81383a0caf6da84dd0df03482
[ "MIT" ]
1
2020-08-14T08:00:12.000Z
2020-08-14T08:00:12.000Z
libaln/src/alncalcconfidence.cpp
Bill-Armstrong/NANO
34356c2bcbc5e5b81383a0caf6da84dd0df03482
[ "MIT" ]
4
2020-07-22T23:07:02.000Z
2022-01-14T03:22:31.000Z
// ALN Library /* MIT License Copyright (c) 2020 William Ward Armstrong Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // alncalcconfidence.cpp #ifdef ALNDLL #define ALNIMP __declspec(dllexport) #endif #include <aln.h> #include "alnpriv.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif static int ALNAPI ValidateALNCalcConfidence(const ALN* pALN, ALNDATAINFO* pDataInfo, const ALNCALLBACKINFO* pCallbackInfo, ALNCONFIDENCE* pConfidence); #ifdef _DEBUG static void DebugValidateALNCalcConfidence(const ALN* pALN, ALNDATAINFO* pDataInfo, const ALNCALLBACKINFO* pCallbackInfo, ALNCONFIDENCE* pConfidence); #endif static int __cdecl CompareErrors(const void* pElem1, const void* pElem2) { float flt1 = *(float*)pElem1; float flt2 = *(float*)pElem2; if (flt1 < flt2) return -1; else if (flt1 > flt2) return 1; return 0; } // set ALN confidence intervals based on a data set // much of this is derived from theory documented in Master95 p302-323 // and Press et al p228-229 ALNIMP int ALNAPI ALNCalcConfidence(const ALN* pALN, ALNDATAINFO* pDataInfo, const ALNCALLBACKINFO* pCallbackInfo, ALNCONFIDENCE* pConfidence) { int nReturn = ValidateALNCalcConfidence(pALN, pDataInfo, pCallbackInfo, pConfidence); if (nReturn != ALN_NOERROR) return nReturn; #ifdef _DEBUG DebugValidateALNCalcConfidence(pALN, pDataInfo, pCallbackInfo, pConfidence); #endif // result array float* afltResult = NULL; try { // see how many points there are long nTRcurrSamples = pDataInfo->nTRcurrSamples; // allocate results array afltResult = new float[nTRcurrSamples]; // evaluate on data int nStart, nEnd; nReturn = EvalTree(pALN->pTree, pALN, pDataInfo, pCallbackInfo, afltResult, &nStart, &nEnd, TRUE); if (nReturn != ALN_NOERROR) { ThrowALNException(); } // set the number of errors and error vector int nErr = (nEnd - nStart + 1); float* afltErr = afltResult + nStart; if (nErr <= 0) { ThrowALNException(); // bad error count } // EvalTree returned the errors in afltResult... now we sort them! qsort(afltErr, nErr, sizeof(float), CompareErrors); // calculate upper an lower bound indexes by discarding np-1 from each end // (conservative approach.. see Masters95 p305) int nDiscard = (int)floor((float)nErr * pConfidence->fltP - 1); // if nErr * pConfidence->fltP is less than 1, then nDiscard will be less than 0 if (nDiscard < 0) nDiscard = 0; ASSERT(nDiscard >= 0 && nDiscard < nErr / 2); // set number of samples used pConfidence->nSamples = nErr; // set lower bound int nLower = nDiscard; ASSERT(nLower >= 0 && nLower < nErr); pConfidence->fltLowerBound = afltErr[nLower]; // set upper bound int nUpper = nErr - nDiscard - 1; ASSERT(nUpper >= 0 && nUpper < nErr); pConfidence->fltUpperBound = afltErr[nUpper]; } catch (CALNUserException* e) // user abort exception { nReturn = ALN_USERABORT; e->Delete(); } catch (CALNMemoryException* e) // memory specific exceptions { nReturn = ALN_OUTOFMEM; e->Delete(); } catch (CALNException* e) // anything other exception we recognize { nReturn = ALN_GENERIC; e->Delete(); } catch (...) // anything else, including FP errs { nReturn = ALN_GENERIC; } // deallocate mem delete[] afltResult; return nReturn; } // validate params static int ALNAPI ValidateALNCalcConfidence(const ALN* pALN, ALNDATAINFO* pDataInfo, const ALNCALLBACKINFO* pCallbackInfo, ALNCONFIDENCE* pConfidence) { int nReturn = ValidateALNDataInfo(pALN, pDataInfo, pCallbackInfo); if (nReturn != ALN_NOERROR) return nReturn; if (pConfidence->fltP <= 0.0 || pConfidence->fltP >= 0.5) return ALN_GENERIC; return ALN_NOERROR; } // debug version ASSERTS if bad params #ifdef _DEBUG static void DebugValidateALNCalcConfidence(const ALN* pALN, ALNDATAINFO* pDataInfo, const ALNCALLBACKINFO* pCallbackInfo, ALNCONFIDENCE* pConfidence) { DebugValidateALNDataInfo(pALN, pDataInfo, pCallbackInfo); ASSERT(pConfidence->fltP > 0.0 && pConfidence->fltP < 0.5); } #endif
29.222222
89
0.673728
Bill-Armstrong
1145033b0fe6d6dad1658b1922fb2387246a8e1f
214
cpp
C++
C++/o1-check-power-of-2.cpp
xenron/sandbox-dev-lintcode
114145723af43eafc84ff602ad3ac7b353a9fc38
[ "MIT" ]
695
2015-04-18T16:11:56.000Z
2022-03-11T13:28:44.000Z
C++/o1-check-power-of-2.cpp
Abd-Elrazek/LintCode
8f6ee0ff38cb7cf8bf9fca800243823931604155
[ "MIT" ]
4
2015-07-04T13:07:35.000Z
2020-08-11T11:32:29.000Z
C++/o1-check-power-of-2.cpp
Abd-Elrazek/LintCode
8f6ee0ff38cb7cf8bf9fca800243823931604155
[ "MIT" ]
338
2015-04-28T04:39:03.000Z
2022-03-16T03:00:15.000Z
// Time: O(1) // Space: O(1) class Solution { public: /* * @param n: An integer * @return: True or false */ bool checkPowerOf2(int n) { return n > 0 && (n & (n - 1)) == 0; } };
15.285714
43
0.453271
xenron
114a1b95175b42ec9a10955ba24cabc439c1284a
864
cpp
C++
cpp/sowcpp/src/ch09/prog9-13.cpp
newnix/Forge
6d18105460fabc20592ed3c29813173cdb57d512
[ "BSD-3-Clause-Clear" ]
null
null
null
cpp/sowcpp/src/ch09/prog9-13.cpp
newnix/Forge
6d18105460fabc20592ed3c29813173cdb57d512
[ "BSD-3-Clause-Clear" ]
null
null
null
cpp/sowcpp/src/ch09/prog9-13.cpp
newnix/Forge
6d18105460fabc20592ed3c29813173cdb57d512
[ "BSD-3-Clause-Clear" ]
null
null
null
// Practice Program 9-13 // Demonstrates a pointer to a const parameter #include <iostream> void displayValues(const int *, int); int main() { // Array sizes const int SIZE = 6; // Define an array of const ints const int array1[SIZE] = { 1, 2, 3, 4, 5, 6}; // Define an array of nonconst ints int array2[SIZE] = { 7, 8, 9, 10, 11, 12 }; // Display the contents of the const array displayValues(array1, SIZE); // Display the contents of the nonconst array displayValues(array2, SIZE); return 0; } // The display Values function uses a pointer to prarameter to display the contents of an array void displayValues(const int *numbers, int size) { // Display all the values for (int count = 0; count < size; count++) { std::cout << *(numbers + count) << " "; } std::cout << std::endl; }
22.153846
95
0.626157
newnix
114b7c156decc9542072cfaff1c9070b3f42f069
13,987
cpp
C++
export/windows/obj/src/lime/system/JNI.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
null
null
null
export/windows/obj/src/lime/system/JNI.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
null
null
null
export/windows/obj/src/lime/system/JNI.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
1
2021-07-16T22:57:01.000Z
2021-07-16T22:57:01.000Z
// Generated by Haxe 4.0.0-rc.2+77068e10c #include <hxcpp.h> #ifndef INCLUDED_Reflect #include <Reflect.h> #endif #ifndef INCLUDED_haxe_IMap #include <haxe/IMap.h> #endif #ifndef INCLUDED_haxe_Log #include <haxe/Log.h> #endif #ifndef INCLUDED_haxe_ds_StringMap #include <haxe/ds/StringMap.h> #endif #ifndef INCLUDED_lime_system_JNI #include <lime/system/JNI.h> #endif #ifndef INCLUDED_lime_system_JNIMemberField #include <lime/system/JNIMemberField.h> #endif #ifndef INCLUDED_lime_system_JNIStaticField #include <lime/system/JNIStaticField.h> #endif HX_LOCAL_STACK_FRAME(_hx_pos_d83344e4dbfeb65c_18_callMember,"lime.system.JNI","callMember",0x6d0f06e7,"lime.system.JNI.callMember","lime/system/JNI.hx",18,0x21970b7f) HX_LOCAL_STACK_FRAME(_hx_pos_d83344e4dbfeb65c_43_callStatic,"lime.system.JNI","callStatic",0x6e55013b,"lime.system.JNI.callStatic","lime/system/JNI.hx",43,0x21970b7f) HX_LOCAL_STACK_FRAME(_hx_pos_d83344e4dbfeb65c_67_createMemberField,"lime.system.JNI","createMemberField",0xd212c0f5,"lime.system.JNI.createMemberField","lime/system/JNI.hx",67,0x21970b7f) HX_LOCAL_STACK_FRAME(_hx_pos_d83344e4dbfeb65c_78_createMemberMethod,"lime.system.JNI","createMemberMethod",0x87227e46,"lime.system.JNI.createMemberMethod","lime/system/JNI.hx",78,0x21970b7f) HX_LOCAL_STACK_FRAME(_hx_pos_d83344e4dbfeb65c_103_createStaticField,"lime.system.JNI","createStaticField",0xe4dcd621,"lime.system.JNI.createStaticField","lime/system/JNI.hx",103,0x21970b7f) HX_LOCAL_STACK_FRAME(_hx_pos_d83344e4dbfeb65c_114_createStaticMethod,"lime.system.JNI","createStaticMethod",0xe52aef9a,"lime.system.JNI.createStaticMethod","lime/system/JNI.hx",114,0x21970b7f) HX_LOCAL_STACK_FRAME(_hx_pos_d83344e4dbfeb65c_139_getEnv,"lime.system.JNI","getEnv",0x2402f6c6,"lime.system.JNI.getEnv","lime/system/JNI.hx",139,0x21970b7f) HX_LOCAL_STACK_FRAME(_hx_pos_d83344e4dbfeb65c_151_init,"lime.system.JNI","init",0x6490931f,"lime.system.JNI.init","lime/system/JNI.hx",151,0x21970b7f) HX_LOCAL_STACK_FRAME(_hx_pos_d83344e4dbfeb65c_163_onCallback,"lime.system.JNI","onCallback",0x99e6bb53,"lime.system.JNI.onCallback","lime/system/JNI.hx",163,0x21970b7f) HX_LOCAL_STACK_FRAME(_hx_pos_d83344e4dbfeb65c_184_postUICallback,"lime.system.JNI","postUICallback",0x8d567168,"lime.system.JNI.postUICallback","lime/system/JNI.hx",184,0x21970b7f) HX_LOCAL_STACK_FRAME(_hx_pos_d83344e4dbfeb65c_13_boot,"lime.system.JNI","boot",0x5ff0dc41,"lime.system.JNI.boot","lime/system/JNI.hx",13,0x21970b7f) HX_LOCAL_STACK_FRAME(_hx_pos_d83344e4dbfeb65c_14_boot,"lime.system.JNI","boot",0x5ff0dc41,"lime.system.JNI.boot","lime/system/JNI.hx",14,0x21970b7f) namespace lime{ namespace _hx_system{ void JNI_obj::__construct() { } Dynamic JNI_obj::__CreateEmpty() { return new JNI_obj; } void *JNI_obj::_hx_vtable = 0; Dynamic JNI_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< JNI_obj > _hx_result = new JNI_obj(); _hx_result->__construct(); return _hx_result; } bool JNI_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x0e3c4b1d; } ::haxe::ds::StringMap JNI_obj::alreadyCreated; bool JNI_obj::initialized; ::Dynamic JNI_obj::callMember( ::Dynamic method, ::Dynamic jobject,::cpp::VirtualArray a){ HX_STACKFRAME(&_hx_pos_d83344e4dbfeb65c_18_callMember) HXDLIN( 18) switch((int)(a->get_length())){ case (int)0: { HXLINE( 21) return method(jobject); } break; case (int)1: { HXLINE( 23) return method(jobject,a->__get(0)); } break; case (int)2: { HXLINE( 25) return method(jobject,a->__get(0),a->__get(1)); } break; case (int)3: { HXLINE( 27) return method(jobject,a->__get(0),a->__get(1),a->__get(2)); } break; case (int)4: { HXLINE( 29) return method(jobject,a->__get(0),a->__get(1),a->__get(2),a->__get(3)); } break; case (int)5: { HXLINE( 31) return method(jobject,a->__get(0),a->__get(1),a->__get(2),a->__get(3),a->__get(4)); } break; case (int)6: { HXLINE( 33) return method(jobject,a->__get(0),a->__get(1),a->__get(2),a->__get(3),a->__get(4),a->__get(5)); } break; case (int)7: { HXLINE( 35) return method(jobject,a->__get(0),a->__get(1),a->__get(2),a->__get(3),a->__get(4),a->__get(5),a->__get(6)); } break; default:{ HXLINE( 37) return null(); } } HXLINE( 18) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC3(JNI_obj,callMember,return ) ::Dynamic JNI_obj::callStatic( ::Dynamic method,::cpp::VirtualArray a){ HX_STACKFRAME(&_hx_pos_d83344e4dbfeb65c_43_callStatic) HXDLIN( 43) switch((int)(a->get_length())){ case (int)0: { HXLINE( 46) return method(); } break; case (int)1: { HXLINE( 48) return method(a->__get(0)); } break; case (int)2: { HXLINE( 50) return method(a->__get(0),a->__get(1)); } break; case (int)3: { HXLINE( 52) return method(a->__get(0),a->__get(1),a->__get(2)); } break; case (int)4: { HXLINE( 54) return method(a->__get(0),a->__get(1),a->__get(2),a->__get(3)); } break; case (int)5: { HXLINE( 56) return method(a->__get(0),a->__get(1),a->__get(2),a->__get(3),a->__get(4)); } break; case (int)6: { HXLINE( 58) return method(a->__get(0),a->__get(1),a->__get(2),a->__get(3),a->__get(4),a->__get(5)); } break; case (int)7: { HXLINE( 60) return method(a->__get(0),a->__get(1),a->__get(2),a->__get(3),a->__get(4),a->__get(5),a->__get(6)); } break; default:{ HXLINE( 62) return null(); } } HXLINE( 43) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(JNI_obj,callStatic,return ) ::lime::_hx_system::JNIMemberField JNI_obj::createMemberField(::String className,::String memberName,::String signature){ HX_STACKFRAME(&_hx_pos_d83344e4dbfeb65c_67_createMemberField) HXLINE( 68) ::lime::_hx_system::JNI_obj::init(); HXLINE( 73) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC3(JNI_obj,createMemberField,return ) ::Dynamic JNI_obj::createMemberMethod(::String className,::String memberName,::String signature,hx::Null< bool > __o_useArray,hx::Null< bool > __o_quietFail){ bool useArray = __o_useArray.Default(false); bool quietFail = __o_quietFail.Default(false); HX_STACKFRAME(&_hx_pos_d83344e4dbfeb65c_78_createMemberMethod) HXLINE( 79) ::lime::_hx_system::JNI_obj::init(); HXLINE( 98) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC5(JNI_obj,createMemberMethod,return ) ::lime::_hx_system::JNIStaticField JNI_obj::createStaticField(::String className,::String memberName,::String signature){ HX_STACKFRAME(&_hx_pos_d83344e4dbfeb65c_103_createStaticField) HXLINE( 104) ::lime::_hx_system::JNI_obj::init(); HXLINE( 109) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC3(JNI_obj,createStaticField,return ) ::Dynamic JNI_obj::createStaticMethod(::String className,::String memberName,::String signature,hx::Null< bool > __o_useArray,hx::Null< bool > __o_quietFail){ bool useArray = __o_useArray.Default(false); bool quietFail = __o_quietFail.Default(false); HX_STACKFRAME(&_hx_pos_d83344e4dbfeb65c_114_createStaticMethod) HXLINE( 115) ::lime::_hx_system::JNI_obj::init(); HXLINE( 134) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC5(JNI_obj,createStaticMethod,return ) ::Dynamic JNI_obj::getEnv(){ HX_STACKFRAME(&_hx_pos_d83344e4dbfeb65c_139_getEnv) HXLINE( 140) ::lime::_hx_system::JNI_obj::init(); HXLINE( 145) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC0(JNI_obj,getEnv,return ) void JNI_obj::init(){ HX_STACKFRAME(&_hx_pos_d83344e4dbfeb65c_151_init) HXDLIN( 151) if (!(::lime::_hx_system::JNI_obj::initialized)) { HXLINE( 153) ::lime::_hx_system::JNI_obj::initialized = true; } } STATIC_HX_DEFINE_DYNAMIC_FUNC0(JNI_obj,init,(void)) ::Dynamic JNI_obj::onCallback( ::Dynamic object,::String method,::cpp::VirtualArray args){ HX_STACKFRAME(&_hx_pos_d83344e4dbfeb65c_163_onCallback) HXLINE( 164) ::Dynamic field = ::Reflect_obj::field(object,method); HXLINE( 166) if (hx::IsNotNull( field )) { HXLINE( 168) if (hx::IsNull( args )) { HXLINE( 168) args = ::cpp::VirtualArray_obj::__new(0); } HXLINE( 170) return ::Reflect_obj::callMethod(object,field,args); } HXLINE( 173) ::haxe::Log_obj::trace((HX_("onCallback - unknown field ",2b,28,2a,3c) + method),hx::SourceInfo(HX_("lime/system/JNI.hx",7f,0b,97,21),173,HX_("lime.system.JNI",bf,02,fc,60),HX_("onCallback",04,6e,bd,5c))); HXLINE( 174) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC3(JNI_obj,onCallback,return ) void JNI_obj::postUICallback( ::Dynamic callback){ HX_STACKFRAME(&_hx_pos_d83344e4dbfeb65c_184_postUICallback) HXDLIN( 184) callback(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(JNI_obj,postUICallback,(void)) JNI_obj::JNI_obj() { } bool JNI_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"init") ) { outValue = init_dyn(); return true; } break; case 6: if (HX_FIELD_EQ(inName,"getEnv") ) { outValue = getEnv_dyn(); return true; } break; case 10: if (HX_FIELD_EQ(inName,"callMember") ) { outValue = callMember_dyn(); return true; } if (HX_FIELD_EQ(inName,"callStatic") ) { outValue = callStatic_dyn(); return true; } if (HX_FIELD_EQ(inName,"onCallback") ) { outValue = onCallback_dyn(); return true; } break; case 11: if (HX_FIELD_EQ(inName,"initialized") ) { outValue = ( initialized ); return true; } break; case 14: if (HX_FIELD_EQ(inName,"alreadyCreated") ) { outValue = ( alreadyCreated ); return true; } if (HX_FIELD_EQ(inName,"postUICallback") ) { outValue = postUICallback_dyn(); return true; } break; case 17: if (HX_FIELD_EQ(inName,"createMemberField") ) { outValue = createMemberField_dyn(); return true; } if (HX_FIELD_EQ(inName,"createStaticField") ) { outValue = createStaticField_dyn(); return true; } break; case 18: if (HX_FIELD_EQ(inName,"createMemberMethod") ) { outValue = createMemberMethod_dyn(); return true; } if (HX_FIELD_EQ(inName,"createStaticMethod") ) { outValue = createStaticMethod_dyn(); return true; } } return false; } bool JNI_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 11: if (HX_FIELD_EQ(inName,"initialized") ) { initialized=ioValue.Cast< bool >(); return true; } break; case 14: if (HX_FIELD_EQ(inName,"alreadyCreated") ) { alreadyCreated=ioValue.Cast< ::haxe::ds::StringMap >(); return true; } } return false; } #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo *JNI_obj_sMemberStorageInfo = 0; static hx::StaticInfo JNI_obj_sStaticStorageInfo[] = { {hx::fsObject /* ::haxe::ds::StringMap */ ,(void *) &JNI_obj::alreadyCreated,HX_("alreadyCreated",30,e9,f8,79)}, {hx::fsBool,(void *) &JNI_obj::initialized,HX_("initialized",14,f5,0f,37)}, { hx::fsUnknown, 0, null()} }; #endif static void JNI_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(JNI_obj::alreadyCreated,"alreadyCreated"); HX_MARK_MEMBER_NAME(JNI_obj::initialized,"initialized"); }; #ifdef HXCPP_VISIT_ALLOCS static void JNI_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(JNI_obj::alreadyCreated,"alreadyCreated"); HX_VISIT_MEMBER_NAME(JNI_obj::initialized,"initialized"); }; #endif hx::Class JNI_obj::__mClass; static ::String JNI_obj_sStaticFields[] = { HX_("alreadyCreated",30,e9,f8,79), HX_("initialized",14,f5,0f,37), HX_("callMember",98,b9,e5,2f), HX_("callStatic",ec,b3,2b,31), HX_("createMemberField",64,36,37,55), HX_("createMemberMethod",f7,c9,e4,c3), HX_("createStaticField",90,4b,01,68), HX_("createStaticMethod",4b,3b,ed,21), HX_("getEnv",f7,3c,1c,a3), HX_("init",10,3b,bb,45), HX_("onCallback",04,6e,bd,5c), HX_("postUICallback",99,d0,5a,b0), ::String(null()) }; void JNI_obj::__register() { JNI_obj _hx_dummy; JNI_obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("lime.system.JNI",bf,02,fc,60); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &JNI_obj::__GetStatic; __mClass->mSetStaticField = &JNI_obj::__SetStatic; __mClass->mMarkFunc = JNI_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(JNI_obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = hx::TCanCast< JNI_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = JNI_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = JNI_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = JNI_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } void JNI_obj::__boot() { { HX_GC_STACKFRAME(&_hx_pos_d83344e4dbfeb65c_13_boot) HXDLIN( 13) alreadyCreated = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); } { HX_STACKFRAME(&_hx_pos_d83344e4dbfeb65c_14_boot) HXDLIN( 14) initialized = false; } } } // end namespace lime } // end namespace system
38.320548
219
0.679917
arturspon
114da60a83afbf61ee7e8b550c99eb501d9b97ca
6,220
cpp
C++
test/views/binding_view.cpp
shi27feng/mockturtle
032dcd590b57040c5ff10d80b515353ffe822671
[ "MIT" ]
null
null
null
test/views/binding_view.cpp
shi27feng/mockturtle
032dcd590b57040c5ff10d80b515353ffe822671
[ "MIT" ]
null
null
null
test/views/binding_view.cpp
shi27feng/mockturtle
032dcd590b57040c5ff10d80b515353ffe822671
[ "MIT" ]
null
null
null
#include <catch.hpp> #include <sstream> #include <lorina/genlib.hpp> #include <mockturtle/io/genlib_reader.hpp> #include <mockturtle/networks/klut.hpp> #include <mockturtle/views/binding_view.hpp> using namespace mockturtle; std::string const simple_library = "GATE zero 0 O=CONST0;\n" "GATE one 0 O=CONST1;\n" "GATE inverter 1 O=!a; PIN * INV 1 999 1.0 1.0 1.0 1.0\n" "GATE buffer 2 O=a; PIN * NONINV 1 999 1.0 1.0 1.0 1.0\n" "GATE and 5 O=a*b; PIN * NONINV 1 999 1.0 1.0 1.0 1.0\n" "GATE or 5 O=a+b; PIN * NONINV 1 999 1.0 1.0 1.0 1.0\n"; TEST_CASE( "Create binding view", "[binding_view]" ) { std::vector<gate> gates; std::istringstream in( simple_library ); auto result = lorina::read_genlib( in, genlib_reader( gates ) ); CHECK( result == lorina::return_code::success ); binding_view<klut_network> ntk( gates ); auto const a = ntk.create_pi(); auto const b = ntk.create_pi(); auto const c = ntk.create_pi(); auto const d = ntk.create_pi(); auto const c0 = ntk.get_constant( false ); auto const t1 = ntk.create_and( a, b ); auto const t2 = ntk.create_or( c, d ); auto const f = ntk.create_and( t1, t2 ); auto const g = ntk.create_not( a ); ntk.create_po( f ); ntk.create_po( g ); ntk.create_po( ntk.get_constant() ); ntk.add_binding( ntk.get_node( c0 ), 0 ); ntk.add_binding( ntk.get_node( t1 ), 4 ); ntk.add_binding( ntk.get_node( t2 ), 5 ); ntk.add_binding( ntk.get_node( f ), 4 ); ntk.add_binding( ntk.get_node( g ), 2 ); CHECK( ntk.has_binding( ntk.get_node( a ) ) == false ); CHECK( ntk.has_binding( ntk.get_node( b ) ) == false ); CHECK( ntk.has_binding( ntk.get_node( c ) ) == false ); CHECK( ntk.has_binding( ntk.get_node( d ) ) == false ); CHECK( ntk.has_binding( ntk.get_node( c0 ) ) == true ); CHECK( ntk.has_binding( ntk.get_node( t1 ) ) == true ); CHECK( ntk.has_binding( ntk.get_node( t2 ) ) == true ); CHECK( ntk.has_binding( ntk.get_node( f ) ) == true ); CHECK( ntk.has_binding( ntk.get_node( g ) ) == true ); CHECK( ntk.get_binding_index( ntk.get_node( c0 ) ) == 0 ); CHECK( ntk.get_binding_index( ntk.get_node( t1 ) ) == 4 ); CHECK( ntk.get_binding_index( ntk.get_node( t2 ) ) == 5 ); CHECK( ntk.get_binding_index( ntk.get_node( f ) ) == 4 ); CHECK( ntk.get_binding_index( ntk.get_node( g ) ) == 2 ); CHECK( ntk.get_binding( ntk.get_node( c0 ) ).name == "zero" ); CHECK( ntk.get_binding( ntk.get_node( t1 ) ).name == "and" ); CHECK( ntk.get_binding( ntk.get_node( t2 ) ).name == "or" ); CHECK( ntk.get_binding( ntk.get_node( f ) ).name == "and" ); CHECK( ntk.get_binding( ntk.get_node( g ) ).name == "inverter" ); CHECK( ntk.compute_area() == 16 ); CHECK( ntk.compute_worst_delay() == 2 ); std::stringstream report_stats; ntk.report_stats( report_stats ); CHECK( report_stats.str() == "[i] Report stats: area = 16.00; delay = 2.00;\n" ); std::stringstream report_gates; ntk.report_gates_usage( report_gates ); CHECK( report_gates.str() == "[i] Report gates usage:\n" "[i] zero \t Instance = 1\t Area = 0.00 0.00 %\n" "[i] inverter \t Instance = 1\t Area = 1.00 6.25 %\n" "[i] and \t Instance = 2\t Area = 10.00 62.50 %\n" "[i] or \t Instance = 1\t Area = 5.00 31.25 %\n" "[i] TOTAL \t Instance = 5\t Area = 16.00 100.00 %\n" ); } TEST_CASE( "Binding view on copy", "[binding_view]" ) { std::vector<gate> gates; std::istringstream in( simple_library ); auto result = lorina::read_genlib( in, genlib_reader( gates ) ); CHECK( result == lorina::return_code::success ); binding_view<klut_network> ntk( gates ); auto const a = ntk.create_pi(); auto const b = ntk.create_pi(); auto const c = ntk.create_pi(); auto const d = ntk.create_pi(); auto const c0 = ntk.get_constant( false ); auto const t1 = ntk.create_and( a, b ); auto const t2 = ntk.create_or( c, d ); auto const f = ntk.create_and( t1, t2 ); auto const g = ntk.create_not( a ); ntk.create_po( f ); ntk.create_po( g ); ntk.create_po( ntk.get_constant() ); ntk.add_binding( ntk.get_node( c0 ), 0 ); ntk.add_binding( ntk.get_node( t1 ), 4 ); ntk.add_binding( ntk.get_node( t2 ), 5 ); ntk.add_binding( ntk.get_node( f ), 4 ); ntk.add_binding( ntk.get_node( g ), 2 ); binding_view<klut_network> ntk_copy = ntk; CHECK( ntk_copy.has_binding( ntk_copy.get_node( a ) ) == false ); CHECK( ntk_copy.has_binding( ntk_copy.get_node( b ) ) == false ); CHECK( ntk_copy.has_binding( ntk_copy.get_node( c ) ) == false ); CHECK( ntk_copy.has_binding( ntk_copy.get_node( d ) ) == false ); CHECK( ntk_copy.has_binding( ntk_copy.get_node( c0 ) ) == true ); CHECK( ntk_copy.has_binding( ntk_copy.get_node( t1 ) ) == true ); CHECK( ntk_copy.has_binding( ntk_copy.get_node( t2 ) ) == true ); CHECK( ntk_copy.has_binding( ntk_copy.get_node( f ) ) == true ); CHECK( ntk_copy.has_binding( ntk_copy.get_node( g ) ) == true ); CHECK( ntk_copy.get_binding_index( ntk_copy.get_node( c0 ) ) == 0 ); CHECK( ntk_copy.get_binding_index( ntk_copy.get_node( t1 ) ) == 4 ); CHECK( ntk_copy.get_binding_index( ntk_copy.get_node( t2 ) ) == 5 ); CHECK( ntk_copy.get_binding_index( ntk_copy.get_node( f ) ) == 4 ); CHECK( ntk_copy.get_binding_index( ntk_copy.get_node( g ) ) == 2 ); CHECK( ntk_copy.get_binding( ntk_copy.get_node( c0 ) ).name == "zero" ); CHECK( ntk_copy.get_binding( ntk_copy.get_node( t1 ) ).name == "and" ); CHECK( ntk_copy.get_binding( ntk_copy.get_node( t2 ) ).name == "or" ); CHECK( ntk_copy.get_binding( ntk_copy.get_node( f ) ).name == "and" ); CHECK( ntk_copy.get_binding( ntk_copy.get_node( g ) ).name == "inverter" ); CHECK( ntk_copy.compute_area() == 16 ); CHECK( ntk_copy.compute_worst_delay() == 2 ); }
41.744966
124
0.595981
shi27feng
1150563ce1ba961345148e6969fb8447cf082339
697
cpp
C++
src/adc_sync.cpp
close2/alibvr-examples
a1d267670349aad23c0986ead59ebba6d279c130
[ "MIT" ]
null
null
null
src/adc_sync.cpp
close2/alibvr-examples
a1d267670349aad23c0986ead59ebba6d279c130
[ "MIT" ]
null
null
null
src/adc_sync.cpp
close2/alibvr-examples
a1d267670349aad23c0986ead59ebba6d279c130
[ "MIT" ]
null
null
null
#define F_CPU 8000000UL #include <util/delay.h> #include "ports.h" #include "adc.h" // First define the Adc. // We want a single conversion, whenever we start a conversion. // Use the internal 1.1V voltage as reference. typedef Adc<_adc::Ref::V1_1> AdcV1_1; typedef PIN_D6 Led; __attribute__ ((OS_main)) int main(void) { // put Led pin into output mode. Led::DDR = 1; for (;;) { // Measure the voltage on Pin ADC4. AdcV1_1::init<PIN_ADC4>(); auto adc4 = AdcV1_1::adc_8bit(); // We also want to measure the voltage on Pin ADC5 AdcV1_1::init<PIN_ADC5>(); auto adc5 = AdcV1_1::adc_8bit(); Led::PORT = (adc4 < adc5); _delay_ms(30); } return 0; }
21.78125
63
0.647059
close2
1152b7e84283053e94cac0b2cbca972a6d5d8832
9,301
cpp
C++
dawn/src/dawn/dawn-opt.cpp
PanicSheep/dawn
5ae233b1bff66dd9d7b53cde88ad3e957b4a5143
[ "MIT" ]
null
null
null
dawn/src/dawn/dawn-opt.cpp
PanicSheep/dawn
5ae233b1bff66dd9d7b53cde88ad3e957b4a5143
[ "MIT" ]
null
null
null
dawn/src/dawn/dawn-opt.cpp
PanicSheep/dawn
5ae233b1bff66dd9d7b53cde88ad3e957b4a5143
[ "MIT" ]
null
null
null
//===--------------------------------------------------------------------------------*- C++ -*-===// // _ // | | // __| | __ ___ ___ ___ // / _` |/ _` \ \ /\ / / '_ | // | (_| | (_| |\ V V /| | | | // \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain // // // This file is distributed under the MIT License (MIT). // See LICENSE.txt for details. // //===------------------------------------------------------------------------------------------===// #include "dawn/Compiler/Driver.h" #include "dawn/IIR/StencilInstantiation.h" #include "dawn/Optimizer/Driver.h" #include "dawn/SIR/SIR.h" #include "dawn/Serialization/IIRSerializer.h" #include "dawn/Serialization/SIRSerializer.h" #include "dawn/Support/FileSystem.h" #include "dawn/Support/Logger.h" #include <cxxopts.hpp> #include <fstream> #include <iostream> #include <string> #include <tuple> enum class SerializationFormat { Byte, Json }; enum class IRType { SIR, IIR }; // toString is used because #DEFAULT_VALUE in the options does not work consistently for both string // and non-string values template <typename T> std::string toString(const T& t) { return std::to_string(t); } std::string toString(const char* t) { return t; } std::string toString(const std::string& t) { return t; } dawn::PassGroup parsePassGroup(const std::string& passGroup) { if(passGroup == "SSA" || passGroup == "ssa") return dawn::PassGroup::SSA; else if(passGroup == "PrintStencilGraph" || passGroup == "print-stencil-graph") return dawn::PassGroup::PrintStencilGraph; else if(passGroup == "SetStageName" || passGroup == "set-stage-name") return dawn::PassGroup::SetStageName; else if(passGroup == "StageReordering" || passGroup == "stage-reordering") return dawn::PassGroup::StageReordering; else if(passGroup == "StageMerger" || passGroup == "stage-merger") return dawn::PassGroup::StageMerger; else if(passGroup == "TemporaryMerger" || passGroup == "temporary-merger" || passGroup == "tmp-merger") return dawn::PassGroup::TemporaryMerger; else if(passGroup == "Inlining" || passGroup == "inlining") return dawn::PassGroup::Inlining; else if(passGroup == "IntervalPartitioning" || passGroup == "interval-partitioning") return dawn::PassGroup::IntervalPartitioning; else if(passGroup == "TmpToStencilFunction" || passGroup == "tmp-to-stencil-function" || passGroup == "tmp-to-stencil-fcn" || passGroup == "tmp-to-function" || passGroup == "tmp-to-fcn") return dawn::PassGroup::TmpToStencilFunction; else if(passGroup == "SetNonTempCaches" || passGroup == "set-non-tmp-caches" || passGroup == "set-nontmp-caches") return dawn::PassGroup::SetNonTempCaches; else if(passGroup == "SetCaches" || passGroup == "set-caches") return dawn::PassGroup::SetCaches; else if(passGroup == "SetBlockSize" || passGroup == "set-block-size") return dawn::PassGroup::SetBlockSize; else if(passGroup == "DataLocalityMetric" || passGroup == "data-locality-metric") return dawn::PassGroup::DataLocalityMetric; else throw std::runtime_error(std::string("Unknown pass group: ") + passGroup); } std::tuple<std::shared_ptr<dawn::SIR>, std::shared_ptr<dawn::iir::StencilInstantiation>, SerializationFormat> deserializeInput(const std::string& input) { std::shared_ptr<dawn::SIR> stencilIR = nullptr; std::shared_ptr<dawn::iir::StencilInstantiation> internalIR = nullptr; SerializationFormat format = SerializationFormat::Byte; // Try SIR first IRType type = IRType::SIR; { try { stencilIR = dawn::SIRSerializer::deserializeFromString(input, dawn::SIRSerializer::Format::Byte); format = SerializationFormat::Byte; } catch(...) { stencilIR = nullptr; } } if(!stencilIR) { try { stencilIR = dawn::SIRSerializer::deserializeFromString(input, dawn::SIRSerializer::Format::Json); format = SerializationFormat::Json; } catch(...) { stencilIR = nullptr; } } // Then try IIR if(!stencilIR) { type = IRType::IIR; try { internalIR = dawn::IIRSerializer::deserializeFromString(input, dawn::IIRSerializer::Format::Byte); format = SerializationFormat::Byte; } catch(...) { internalIR = nullptr; } } if(!internalIR && !stencilIR) { try { internalIR = dawn::IIRSerializer::deserializeFromString(input, dawn::IIRSerializer::Format::Json); format = SerializationFormat::Json; } catch(...) { internalIR = nullptr; } } // Deserialize again, only this time do not catch exceptions switch(type) { case IRType::SIR: { if(format == SerializationFormat::Byte) { stencilIR = dawn::SIRSerializer::deserializeFromString(input, dawn::SIRSerializer::Format::Byte); } else { stencilIR = dawn::SIRSerializer::deserializeFromString(input, dawn::SIRSerializer::Format::Json); } break; } case IRType::IIR: { if(format == SerializationFormat::Byte) { internalIR = dawn::IIRSerializer::deserializeFromString(input, dawn::IIRSerializer::Format::Byte); } else { internalIR = dawn::IIRSerializer::deserializeFromString(input, dawn::IIRSerializer::Format::Json); } break; } } return {stencilIR, internalIR, format}; } int main(int argc, char* argv[]) { cxxopts::Options options("dawn-opt", "Optimizer for the Dawn DSL compiler toolchain"); options.positional_help("[SIR or IIR file. If unset, reads from stdin]"); // clang-format off options.add_options() ("input", "Input file. If unset, reads from stdin.", cxxopts::value<std::string>()) ("o,out", "Output IIR filename. If unset, writes IIR to stdout.", cxxopts::value<std::string>()) ("v,verbose", "Set verbosity level to info. If set, use -o or --out to redirect IIR.") ("default-opt", "Add default groups before those in --pass-groups.") ("p,pass-groups", "Comma-separated ordered list of pass groups to run. See dawn/Compiler/Driver.h for list. If unset and --default-opts is not passed, only lowers to IIR.", cxxopts::value<std::vector<std::string>>()->default_value({})) ("h,help", "Display usage."); options.add_options("Pass") #define OPT(TYPE, NAME, DEFAULT_VALUE, OPTION, OPTION_SHORT, HELP, VALUE_NAME, HAS_VALUE, F_GROUP) \ (OPTION, HELP, cxxopts::value<TYPE>()->default_value(toString(DEFAULT_VALUE))) #include "dawn/Optimizer/Options.inc" #undef OPT ; // clang-format on // This is how the positional argument is specified options.parse_positional({"input"}); const int numArgs = argc; auto result = options.parse(argc, argv); if(result.count("help")) { std::cout << options.help() << std::endl; return 0; } // Determine the list of pass groups to run std::list<dawn::PassGroup> passGroups; if(result.count("default-opt") > 0) { passGroups = dawn::defaultPassGroups(); } for(auto pg : result["pass-groups"].as<std::vector<std::string>>()) { passGroups.push_back(parsePassGroup(pg)); } // Until stencil functions are added to the IIR... passGroups.push_back(dawn::PassGroup::Inlining); // Get the input from file or stdin std::string input; if(result.count("input")) { std::ifstream t(result["input"].as<std::string>()); input.insert(input.begin(), (std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); } else { std::istreambuf_iterator<char> begin(std::cin), end; input.insert(input.begin(), begin, end); } auto [stencilIR, internalIR, format] = deserializeInput(input); // Create a dawn::Options struct for the driver dawn::Options optimizerOptions; #define OPT(TYPE, NAME, DEFAULT_VALUE, OPTION, OPTION_SHORT, HELP, VALUE_NAME, HAS_VALUE, F_GROUP) \ optimizerOptions.NAME = result[OPTION].as<TYPE>(); #include "dawn/Optimizer/Options.inc" #undef OPT // Call optimizer std::map<std::string, std::shared_ptr<dawn::iir::StencilInstantiation>> optimizedSIM; if(stencilIR) { optimizedSIM = dawn::run(stencilIR, passGroups, optimizerOptions); } else { std::map<std::string, std::shared_ptr<dawn::iir::StencilInstantiation>> stencilInstantiationMap{ {"restoredIIR", internalIR}}; optimizedSIM = dawn::run(stencilInstantiationMap, passGroups, optimizerOptions); } if(optimizedSIM.size() > 1) { DAWN_LOG(WARNING) << "More than one StencilInstantiation is not supported in IIR"; } for(auto& [name, instantiation] : optimizedSIM) { dawn::IIRSerializer::Format iirFormat = (format == SerializationFormat::Byte) ? dawn::IIRSerializer::Format::Byte : dawn::IIRSerializer::Format::Json; if(result.count("out")) dawn::IIRSerializer::serialize(result["out"].as<std::string>(), instantiation, iirFormat); else if(!optimizerOptions.DumpStencilInstantiation) { std::cout << dawn::IIRSerializer::serializeToString(instantiation, iirFormat); } else { DAWN_LOG(INFO) << "dump-si present. Skipping serialization."; } } return 0; }
37.353414
162
0.641329
PanicSheep
1154769f682578831f0622843a5ffdcf8cf129c7
21,007
cpp
C++
src/game/etj_save_system.cpp
Aciz/etjump
6215e86cf9aeef504dc4eb24a57ecdc797cb7a2e
[ "BSL-1.0", "MIT" ]
16
2019-09-07T18:08:08.000Z
2022-03-04T21:37:06.000Z
src/game/etj_save_system.cpp
Aciz/etjump
6215e86cf9aeef504dc4eb24a57ecdc797cb7a2e
[ "BSL-1.0", "MIT" ]
121
2019-09-07T19:30:39.000Z
2022-01-31T20:59:48.000Z
src/game/etj_save_system.cpp
etjump/etjump
8dcc3ca939e95063e630367d98cac7ffeec6d88c
[ "BSL-1.0", "MIT" ]
14
2019-09-07T17:20:40.000Z
2022-01-30T06:47:15.000Z
/* * MIT License * * Copyright (c) 2021 ETJump team <zero@etjump.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <string> #include <vector> using std::string; using std::vector; #include "etj_save_system.h" #include "utilities.hpp" #include "etj_session.h" ETJump::SaveSystem::Client::Client() { alliesBackupPositions = boost::circular_buffer<SavePosition>(MAX_BACKUP_POSITIONS); axisBackupPositions = boost::circular_buffer<SavePosition>(MAX_BACKUP_POSITIONS); for (int i = 0; i < MAX_SAVED_POSITIONS; i++) { alliesSavedPositions[i].isValid = false; axisSavedPositions[i].isValid = false; } for (int i = 0; i < MAX_BACKUP_POSITIONS; i++) { alliesBackupPositions.push_back(SavePosition()); alliesBackupPositions[i].isValid = false; axisBackupPositions.push_back(SavePosition()); axisBackupPositions[i].isValid = false; } alliesLastLoadPosition.isValid = false; axisLastLoadPosition.isValid = false; } ETJump::SaveSystem::DisconnectedClient::DisconnectedClient() { for (int i = 0; i < MAX_SAVED_POSITIONS; i++) { alliesSavedPositions[i].isValid = false; axisSavedPositions[i].isValid = false; progression = 0; } alliesLastLoadPosition.isValid = false; axisLastLoadPosition.isValid = false; } // Zero: required for saving saves to db std::string UserDatabase_Guid(gentity_t *ent); // Saves current position void ETJump::SaveSystem::save(gentity_t *ent) { auto *client = ent->client; if (!client) { return; } if (!g_save.integer) { CPTo(ent, "^3Save ^7is not enabled."); return; } if ((client->sess.deathrunFlags & static_cast<int>(DeathrunFlags::Active)) && (client->sess.deathrunFlags & static_cast<int>(DeathrunFlags::NoSave))) { CPTo(ent, "^3Save ^7is disabled for this death run."); return; } if (level.saveLoadRestrictions & static_cast<int>(SaveLoadRestrictions::Move)) { // comparing to zero vector if (!VectorCompare(client->ps.velocity, vec3_origin)) { CPTo(ent, "^3Save ^7is disabled while moving on this map."); return; } } // No saving while dead if it's disabled by map if (client->ps.pm_type == PM_DEAD && level.saveLoadRestrictions & static_cast<int>(SaveLoadRestrictions::Dead)) { CPTo(ent, "^3Save ^7is disabled while dead on this map."); return; } auto argv = GetArgs(); auto position = 0; if (argv->size() > 1) { ToInt((*argv)[1], position); if (position < 0 || position >= MAX_SAVED_POSITIONS) { CPTo(ent, "Invalid position."); return; } if (position > 0 && client->sess.timerunActive && client->sess.runSpawnflags & TIMERUN_DISABLE_BACKUPS) { CPTo(ent, "Save slots are disabled for this timerun."); return; } } if (!client->sess.saveAllowed) { CPTo(ent, "You are not allowed to save a position."); return; } if (client->sess.sessionTeam == TEAM_SPECTATOR) { CPTo(ent, "^7You can not ^3save^7 as a spectator."); return; } if (client->sess.timerunActive && client->sess.runSpawnflags & TIMERUN_DISABLE_SAVE) { CPTo(ent, "^3Save ^7is disabled for this timerun."); return; } trace_t trace; trap_TraceCapsule(&trace, client->ps.origin, ent->r.mins, ent->r.maxs, client->ps.origin, ent->s.number, CONTENTS_NOSAVE); if (level.noSave) { if ((!trace.fraction) != 1.0f) { CPTo(ent, "^7You can not ^3save ^7inside this area."); return; } } else { if (trace.fraction != 1.0f) { CPTo(ent, "^7You can not ^3save ^7inside this area."); return; } } if (client->pers.race.isRacing) { if (client->pers.race.saveLimit == 0) { CPTo(ent, "^5You've used all your saves."); return; } if (client->pers.race.saveLimit > 0) { client->pers.race.saveLimit--; } } else { fireteamData_t *ft; if (G_IsOnFireteam(ent - g_entities, &ft)) { if (ft->saveLimit < 0) { client->sess.saveLimit = 0; } if (ft->saveLimit) { if (client->sess.saveLimit) { client->sess.saveLimit--; } else { CPTo(ent, "^5You've used all your fireteam saves."); return; } } } } SavePosition *pos = nullptr; if (client->sess.sessionTeam == TEAM_ALLIES) { pos = _clients[ClientNum(ent)].alliesSavedPositions + position; } else { pos = _clients[ClientNum(ent)].axisSavedPositions + position; } saveBackupPosition(ent, pos); storePosition(client, pos); sendClientCommands(ent, position); } // Loads position void ETJump::SaveSystem::load(gentity_t *ent) { auto *client = ent->client; if (!client) { return; } if (!g_save.integer) { CPTo(ent, "^3Load ^7is not enabled."); return; } if (!client->sess.saveAllowed) { CPTo(ent, "You are not allowed to load a position."); return; } if ((client->sess.deathrunFlags & static_cast<int>(DeathrunFlags::Active)) && (client->sess.deathrunFlags & static_cast<int>(DeathrunFlags::NoSave))) { CPTo(ent, "^3Load ^7is disabled for this death run."); return; } if (client->ps.pm_type == PM_DEAD && level.saveLoadRestrictions & static_cast<int>(SaveLoadRestrictions::Dead)) { CPTo(ent, "^3Load ^7is disabled while dead on this map."); return; } auto argv = GetArgs(); auto slot = 0; if (argv->size() > 1) { ToInt((*argv)[1], slot); if (slot < 0 || slot >= MAX_SAVED_POSITIONS) { CPTo(ent, "^7Invalid save slot."); return; } if (slot > 0 && client->sess.timerunActive && client->sess.runSpawnflags & TIMERUN_DISABLE_BACKUPS) { CPTo(ent, "Save slots are disabled for this timerun."); return; } } if (client->sess.sessionTeam == TEAM_SPECTATOR) { CPTo(ent, "^7You can not ^3load ^7as a spectator."); return; } auto validSave = getValidTeamSaveForSlot(ent, client->sess.sessionTeam, slot); if (validSave) { saveLastLoadPos(ent); // store position for unload command restoreStanceFromSave(ent, validSave); if (client->sess.timerunActive && client->sess.runSpawnflags & TIMERUN_DISABLE_SAVE) { InterruptRun(ent); } teleportPlayer(ent, validSave); } else { CPTo(ent, "^7Use ^3save ^7first."); } } // Saves position, does not check for anything. Used for target_save void ETJump::SaveSystem::forceSave(gentity_t *location, gentity_t *ent) { SavePosition *pos = nullptr; auto *client = ent->client; if (!client || !location) { return; } if (client->sess.sessionTeam == TEAM_ALLIES) { pos = &_clients[ClientNum(ent)].alliesSavedPositions[0]; } else if (client->sess.sessionTeam == TEAM_AXIS) { pos = &_clients[ClientNum(ent)].axisSavedPositions[0]; } else { return; } saveBackupPosition(ent, pos); VectorCopy(location->s.origin, pos->origin); VectorCopy(location->s.angles, pos->vangles); pos->isValid = true; pos->stance = client->ps.eFlags & EF_CROUCHING ? Crouch : client->ps.eFlags & EF_PRONE ? Prone : Stand; trap_SendServerCommand(ent - g_entities, "savePrint"); } // Loads backup position void ETJump::SaveSystem::loadBackupPosition(gentity_t *ent) { auto *client = ent->client; if (!client) { return; } if (!g_save.integer) { CPTo(ent, "^3Load ^7is not enabled."); return; } if (!client->sess.saveAllowed) { CPTo(ent, "You are not allowed to load a position."); return; } if (client->sess.timerunActive && client->sess.runSpawnflags & TIMERUN_DISABLE_BACKUPS) { CPTo(ent, "Backup is disabled for this timerun."); return; } if ((client->sess.deathrunFlags & static_cast<int>(DeathrunFlags::Active)) && (client->sess.deathrunFlags & static_cast<int>(DeathrunFlags::NoSave))) { CPTo(ent, "^3Backup ^7is disabled for this death run."); return; } if (client->ps.pm_type == PM_DEAD && level.saveLoadRestrictions & static_cast<int>(SaveLoadRestrictions::Dead)) { CPTo(ent, "^3Backup ^7is disabled while dead on this map."); return; } auto argv = GetArgs(); auto slot = 0; if (argv->size() > 1) { ToInt(argv->at(1), slot); if (slot < 1 || slot > MAX_SAVED_POSITIONS) { CPTo(ent, "^7Invalid backup slot."); return; } if (slot > 0) { slot--; } } if (client->sess.sessionTeam == TEAM_SPECTATOR) { CPTo(ent, "^7You can not ^3load ^7as a spectator."); return; } SavePosition *pos = nullptr; if (client->sess.sessionTeam == TEAM_ALLIES) { pos = &_clients[ClientNum(ent)].alliesBackupPositions[slot]; } else { pos = &_clients[ClientNum(ent)].axisBackupPositions[slot]; } if (pos->isValid) { restoreStanceFromSave(ent, pos); if (client->sess.timerunActive && client->sess.runSpawnflags & TIMERUN_DISABLE_SAVE) { InterruptRun(ent); } teleportPlayer(ent, pos); } else { CPTo(ent, "^7Use ^3save ^7first."); } } // Undo last load command and teleport to last position client loaded from // Position validation is done here void ETJump::SaveSystem::unload(gentity_t* ent) { auto* client = ent->client; if (!client) { return; } if (!g_save.integer) { CPTo(ent, "^3Unload ^7is not enabled."); return; } if (!client->sess.saveAllowed) { CPTo(ent, "^7You are not allowed to ^3unload ^7a position."); return; } if ((client->sess.deathrunFlags & static_cast<int>(DeathrunFlags::Active)) && (client->sess.deathrunFlags & static_cast<int>(DeathrunFlags::NoSave))) { CPTo(ent, "^3unload ^7is disabled for this death run."); return; } if (client->ps.pm_type == PM_DEAD && level.saveLoadRestrictions & static_cast<int>(SaveLoadRestrictions::Dead)) { CPTo(ent, "^3unload ^7is disabled while dead on this map."); return; } if (client->sess.sessionTeam == TEAM_SPECTATOR) { CPTo(ent, "^7You can not ^3unload ^7as a spectator."); return; } if (client->sess.timerunActive) { CPTo(ent, "^3unload ^7is not available during timeruns."); return; } auto validPos = getValidTeamUnloadPos(ent, client->sess.sessionTeam); if (validPos) { // check for nosave areas only if we have valid pos trace_t trace; trap_TraceCapsule(&trace, validPos->origin, ent->r.mins, ent->r.maxs, validPos->origin, ent->s.number, CONTENTS_NOSAVE); if (level.noSave) { if ((!trace.fraction) != 1.0f) { CPTo(ent, "^7You can not ^3unload ^7to this area."); return; } } else { if (trace.fraction != 1.0f) { CPTo(ent, "^7You can not ^3unload ^7to this area."); return; } } restoreStanceFromSave(ent, validPos); teleportPlayer(ent, validPos); } else { CPTo(ent, "^7Use ^3load ^7first."); } } // Saves position client loaded from. Executed on every successful load command, // position validation is done later. This is to prevent unexpected behavior // where the last load position is not a valid position, and client is // teleported to a position that was valid before that. void ETJump::SaveSystem::saveLastLoadPos(gentity_t* ent) { SavePosition* pos = nullptr; auto *client = ent->client; if (client->sess.sessionTeam == TEAM_ALLIES) { pos = &_clients[ClientNum(ent)].alliesLastLoadPosition; } else if (client->sess.sessionTeam == TEAM_AXIS) { pos = &_clients[ClientNum(ent)].axisLastLoadPosition; } else { return; } storePosition(client, pos); } void ETJump::SaveSystem::reset() { for (int clientIndex = 0; clientIndex < level.numConnectedClients; clientIndex++) { int clientNum = level.sortedClients[clientIndex]; // TODO: reset saved positions here resetSavedPositions(g_entities + clientNum); } _savedPositions.clear(); } // Used to reset positions on map change/restart void ETJump::SaveSystem::resetSavedPositions(gentity_t *ent) { int clientNum = ClientNum(ent); for (int saveIndex = 0; saveIndex < MAX_SAVED_POSITIONS; saveIndex++) { _clients[clientNum].alliesSavedPositions[saveIndex].isValid = false; _clients[clientNum].axisSavedPositions[saveIndex].isValid = false; } for (int backupIndex = 0; backupIndex < MAX_BACKUP_POSITIONS; backupIndex++) { _clients[clientNum].alliesBackupPositions[backupIndex].isValid = false; _clients[clientNum].axisBackupPositions[backupIndex].isValid = false; } _clients[clientNum].quickDeployPositions[TEAM_ALLIES].isValid = false; _clients[clientNum].quickDeployPositions[TEAM_AXIS].isValid = false; _clients[clientNum].alliesLastLoadPosition.isValid = false; _clients[clientNum].axisLastLoadPosition.isValid = false; } // Called on client disconnect. Saves saves for future sessions void ETJump::SaveSystem::savePositionsToDatabase(gentity_t *ent) { if (!ent->client) { return; } string guid = _session->Guid(ent); DisconnectedClient client; for (int i = 0; i < MAX_SAVED_POSITIONS; i++) { // Allied VectorCopy(_clients[ClientNum(ent)].alliesSavedPositions[i].origin, client.alliesSavedPositions[i].origin); VectorCopy(_clients[ClientNum(ent)].alliesSavedPositions[i].vangles, client.alliesSavedPositions[i].vangles); client.alliesSavedPositions[i].isValid = _clients[ClientNum(ent)].alliesSavedPositions[i].isValid; // Axis VectorCopy(_clients[ClientNum(ent)].axisSavedPositions[i].origin, client.axisSavedPositions[i].origin); VectorCopy(_clients[ClientNum(ent)].axisSavedPositions[i].vangles, client.axisSavedPositions[i].vangles); client.axisSavedPositions[i].isValid = _clients[ClientNum(ent)].axisSavedPositions[i].isValid; } client.progression = ent->client->sess.clientMapProgression; ent->client->sess.loadPreviousSavedPositions = qfalse; std::map<string, DisconnectedClient>::iterator it = _savedPositions.find(guid); if (it != _savedPositions.end()) { it->second = client; } else { _savedPositions.insert(std::make_pair(guid, client)); } } // Called on client connect. Loads saves from previous session void ETJump::SaveSystem::loadPositionsFromDatabase(gentity_t *ent) { if (!ent->client) { return; } if (!ent->client->sess.loadPreviousSavedPositions) { return; } string guid = _session->Guid(ent); std::map<string, DisconnectedClient>::iterator it = _savedPositions.find(guid); if (it != _savedPositions.end()) { unsigned validPositionsCount = 0; for (int i = 0; i < MAX_SAVED_POSITIONS; i++) { // Allied VectorCopy(it->second.alliesSavedPositions[i].origin, _clients[ClientNum(ent)].alliesSavedPositions[i].origin); VectorCopy(it->second.alliesSavedPositions[i].vangles, _clients[ClientNum(ent)].alliesSavedPositions[i].vangles); _clients[ClientNum(ent)].alliesSavedPositions[i].isValid = it->second.alliesSavedPositions[i].isValid; if (it->second.alliesSavedPositions[i].isValid) { ++validPositionsCount; } // Axis VectorCopy(it->second.axisSavedPositions[i].origin, _clients[ClientNum(ent)].axisSavedPositions[i].origin); VectorCopy(it->second.axisSavedPositions[i].vangles, _clients[ClientNum(ent)].axisSavedPositions[i].vangles); _clients[ClientNum(ent)].axisSavedPositions[i].isValid = it->second.axisSavedPositions[i].isValid; if (it->second.axisSavedPositions[i].isValid) { ++validPositionsCount; } } ent->client->sess.loadPreviousSavedPositions = qfalse; ent->client->sess.clientMapProgression = it->second.progression; if (validPositionsCount) { ChatPrintTo(ent, "^<ETJump: ^7loaded saved positions from previous session."); } } } void ETJump::SaveSystem::storeTeamQuickDeployPosition(gentity_t *ent, team_t team) { auto lastValidSave = getValidTeamSaveForSlot(ent, team, 0); if (lastValidSave) { auto client = &_clients[ClientNum(ent)]; auto autoSave = &(client->quickDeployPositions[team]); *autoSave = *lastValidSave; } } void ETJump::SaveSystem::loadTeamQuickDeployPosition(gentity_t *ent, team_t team) { auto validSave = getValidTeamQuickDeploySave(ent, team); if (validSave) { restoreStanceFromSave(ent, validSave); teleportPlayer(ent, validSave); } } void ETJump::SaveSystem::loadOnceTeamQuickDeployPosition(gentity_t *ent, team_t team) { auto validSave = getValidTeamQuickDeploySave(ent, team); if (validSave) { restoreStanceFromSave(ent, validSave); teleportPlayer(ent, validSave); validSave->isValid = false; } } ETJump::SaveSystem::SavePosition* ETJump::SaveSystem::getValidTeamSaveForSlot(gentity_t *ent, team_t team, int slot) { if (!ent || !ent->client) { return nullptr; } if (team != TEAM_ALLIES && team != TEAM_AXIS) { return nullptr; } auto client = &_clients[ClientNum(ent)]; SavePosition *pos = nullptr; if (team == TEAM_ALLIES) { pos = &client->alliesSavedPositions[slot]; } else { pos = &client->axisSavedPositions[slot]; } if (!pos->isValid) { return nullptr; } return pos; } ETJump::SaveSystem::SavePosition* ETJump::SaveSystem::getValidTeamUnloadPos(gentity_t* ent, team_t team) { if (!ent || !ent->client) { return nullptr; } if (team != TEAM_ALLIES && team != TEAM_AXIS) { return nullptr; } auto client = &_clients[ClientNum(ent)]; SavePosition* pos = nullptr; if (team == TEAM_ALLIES) { pos = &client->alliesLastLoadPosition; } else { pos = &client->axisLastLoadPosition; } if (!pos->isValid) { return nullptr; } return pos; } ETJump::SaveSystem::SavePosition* ETJump::SaveSystem::getValidTeamQuickDeploySave(gentity_t *ent, team_t team) { if (!ent || !ent->client) { return nullptr; } if (team != TEAM_ALLIES && team != TEAM_AXIS) { return nullptr; } auto client = &_clients[ClientNum(ent)]; auto pos = &client->quickDeployPositions[team]; if (!pos->isValid) { return nullptr; } return pos; } void ETJump::SaveSystem::restoreStanceFromSave(gentity_t *ent, SavePosition *pos) { if (!ent || !ent->client) { return; } auto client = ent->client; if (pos->stance == Crouch) { client->ps.eFlags &= ~EF_PRONE; client->ps.eFlags &= ~EF_PRONE_MOVING; client->ps.pm_flags |= PMF_DUCKED; } else if (pos->stance == Prone) { client->ps.eFlags |= EF_PRONE; SetClientViewAngle(ent, pos->vangles); } else { client->ps.eFlags &= ~EF_PRONE; client->ps.eFlags &= ~EF_PRONE_MOVING; client->ps.pm_flags &= ~PMF_DUCKED; } } // Saves backup position void ETJump::SaveSystem::saveBackupPosition(gentity_t *ent, SavePosition *pos) { if (!ent->client) { return; } if (ent->client->sess.timerunActive && ent->client->sess.runSpawnflags & TIMERUN_DISABLE_BACKUPS) { return; } SavePosition backup; VectorCopy(pos->origin, backup.origin); VectorCopy(pos->vangles, backup.vangles); backup.isValid = pos->isValid; backup.stance = pos->stance; // Can never be spectator as this would not be called if (ent->client->sess.sessionTeam == TEAM_ALLIES) { _clients[ClientNum(ent)].alliesBackupPositions.push_front(backup); } else { _clients[ClientNum(ent)].axisBackupPositions.push_front(backup); } } void ETJump::SaveSystem::storePosition(gclient_s* client, SavePosition *pos) { VectorCopy(client->ps.origin, pos->origin); VectorCopy(client->ps.viewangles, pos->vangles); pos->isValid = true; if (client->ps.eFlags & EF_CROUCHING) { pos->stance = Crouch; } else if (client->ps.eFlags & EF_PRONE) { pos->stance = Prone; } else { pos->stance = Stand; } } void ETJump::SaveSystem::sendClientCommands(gentity_t* ent, int position) { auto client = ClientNum(ent); trap_SendServerCommand(client, "resetStrafeQuality\n"); trap_SendServerCommand(client, "resetJumpSpeeds\n"); trap_SendServerCommand(client, position == 0 ? "savePrint\n" : va("savePrint %d\n", position)); } void ETJump::SaveSystem::teleportPlayer(gentity_t* ent, SavePosition* pos) { auto *client = ent->client; client->ps.eFlags ^= EF_TELEPORT_BIT; G_AddEvent(ent, EV_LOAD_TELEPORT, 0); G_SetOrigin(ent, pos->origin); VectorClear(client->ps.velocity); if (client->pers.loadViewAngles) { SetClientViewAngle(ent, pos->vangles); } client->ps.pm_time = 1; // Crashland + instant load bug fix. } ETJump::SaveSystem::SaveSystem(const std::shared_ptr<Session> session) : _session(session) //:guidInterface_(guidInterface) { } ETJump::SaveSystem::~SaveSystem() { }
22.95847
150
0.691531
Aciz
115747e69ec6f2e22509d7426923f8bf7d1f2742
1,363
cpp
C++
Source/SphereObject.cpp
claytonkanderson/Sunburst
881363da513f138d57d6032b4d0d33bf85a4d096
[ "MIT" ]
null
null
null
Source/SphereObject.cpp
claytonkanderson/Sunburst
881363da513f138d57d6032b4d0d33bf85a4d096
[ "MIT" ]
null
null
null
Source/SphereObject.cpp
claytonkanderson/Sunburst
881363da513f138d57d6032b4d0d33bf85a4d096
[ "MIT" ]
null
null
null
// // SphereObj.cpp // CSE_168 // // Created by Clayton Anderson on 4/11/17. // Copyright © 2017 Clayton Anderson. All rights reserved. // #define GLM_ENABLE_EXPERIMENTAL #include "SphereObject.hpp" bool SphereObject::Intersect(const Ray &ray, Intersection &hit) { vec3 p, d, q, c; p = ray.Origin; d = ray.Direction; c = center; q = p - dot(p-c, d) * d; float qcSquared = dot(q-c,q-c); if (qcSquared > radius*radius) return false; float a = sqrt(radius*radius - qcSquared); float t = -dot(p-c, d); if (t - a >= 0) { vec3 q1 = p + (t - a) * d; float hitDist = distance(q1, p); if (hitDist < minHitDist) return false; if (hitDist < hit.HitDistance) { hit.Position = q1; hit.Normal = (q1 - c) / radius; hit.HitDistance = hitDist; } return true; } else if (t + a >= 0) { vec3 q2 = p + (t + a) * d; float hitDist = distance(q2, p); if (hitDist < minHitDist) return false; if (hitDist < hit.HitDistance) { hit.Position = q2; hit.Normal = (q2 - c) / radius; hit.HitDistance = hitDist; } return true; } return false; }
20.969231
63
0.486427
claytonkanderson
11606275a283f7c6a9eef32a7fd10f10bb80e42b
12,542
cpp
C++
lifecycle/src/lifecycle_talker.cpp
HATAEGON/demos
fb3ad7e7fc6548c30e77a6ed86a2bd108fce5d82
[ "Apache-2.0" ]
null
null
null
lifecycle/src/lifecycle_talker.cpp
HATAEGON/demos
fb3ad7e7fc6548c30e77a6ed86a2bd108fce5d82
[ "Apache-2.0" ]
null
null
null
lifecycle/src/lifecycle_talker.cpp
HATAEGON/demos
fb3ad7e7fc6548c30e77a6ed86a2bd108fce5d82
[ "Apache-2.0" ]
null
null
null
// Copyright 2016 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <chrono> #include <iostream> #include <memory> #include <string> #include <thread> #include <utility> #include "lifecycle_msgs/msg/transition.hpp" #include "rclcpp/rclcpp.hpp" #include "rclcpp/publisher.hpp" #include "rclcpp_lifecycle/lifecycle_node.hpp" #include "rclcpp_lifecycle/lifecycle_publisher.hpp" #include "rcutils/logging_macros.h" #include "std_msgs/msg/string.hpp" using namespace std::chrono_literals; /// LifecycleTalker inheriting from rclcpp_lifecycle::LifecycleNode /** * The lifecycle talker does not like the regular "talker" node * inherit from node, but rather from lifecyclenode. This brings * in a set of callbacks which are getting invoked depending on * the current state of the node. * Every lifecycle node has a set of services attached to it * which make it controllable from the outside and invoke state * changes. * Available Services as for Beta1: * - <node_name>__get_state * - <node_name>__change_state * - <node_name>__get_available_states * - <node_name>__get_available_transitions * Additionally, a publisher for state change notifications is * created: * - <node_name>__transition_event */ class LifecycleTalker : public rclcpp_lifecycle::LifecycleNode { public: /// LifecycleTalker constructor /** * The lifecycletalker/lifecyclenode constructor has the same * arguments a regular node. */ explicit LifecycleTalker(const std::string & node_name, bool intra_process_comms = false) : rclcpp_lifecycle::LifecycleNode(node_name, rclcpp::NodeOptions().use_intra_process_comms(intra_process_comms)) {} /// Callback for walltimer in order to publish the message. /** * Callback for walltimer. This function gets invoked by the timer * and executes the publishing. * For this demo, we ask the node for its current state. If the * lifecycle publisher is not activate, we still invoke publish, but * the communication is blocked so that no messages is actually transferred. */ void publish() { static size_t count = 0; auto msg = std::make_unique<std_msgs::msg::String>(); msg->data = "Lifecycle HelloWorld #" + std::to_string(++count); // Print the current state for demo purposes if (!pub_->is_activated()) { RCLCPP_INFO( get_logger(), "Lifecycle publisher is currently inactive. Messages are not published."); } else { RCLCPP_INFO( get_logger(), "Lifecycle publisher is active. Publishing: [%s]", msg->data.c_str()); } // We independently from the current state call publish on the lifecycle // publisher. // Only if the publisher is in an active state, the message transfer is // enabled and the message actually published. pub_->publish(std::move(msg)); } /// Transition callback for state configuring /** * on_configure callback is being called when the lifecycle node * enters the "configuring" state. * Depending on the return value of this function, the state machine * either invokes a transition to the "inactive" state or stays * in "unconfigured". * TRANSITION_CALLBACK_SUCCESS transitions to "inactive" * TRANSITION_CALLBACK_FAILURE transitions to "unconfigured" * TRANSITION_CALLBACK_ERROR or any uncaught exceptions to "errorprocessing" */ rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn on_configure(const rclcpp_lifecycle::State &) { // This callback is supposed to be used for initialization and // configuring purposes. // We thus initialize and configure our publishers and timers. // The lifecycle node API does return lifecycle components such as // lifecycle publishers. These entities obey the lifecycle and // can comply to the current state of the node. // As of the beta version, there is only a lifecycle publisher // available. pub_ = this->create_publisher<std_msgs::msg::String>("lifecycle_chatter", 10); timer_ = this->create_wall_timer( 1s, std::bind(&LifecycleTalker::publish, this)); RCLCPP_INFO(get_logger(), "on_configure() is called."); // We return a success and hence invoke the transition to the next // step: "inactive". // If we returned TRANSITION_CALLBACK_FAILURE instead, the state machine // would stay in the "unconfigured" state. // In case of TRANSITION_CALLBACK_ERROR or any thrown exception within // this callback, the state machine transitions to state "errorprocessing". return rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn::SUCCESS; } /// Transition callback for state activating /** * on_activate callback is being called when the lifecycle node * enters the "activating" state. * Depending on the return value of this function, the state machine * either invokes a transition to the "active" state or stays * in "inactive". * TRANSITION_CALLBACK_SUCCESS transitions to "active" * TRANSITION_CALLBACK_FAILURE transitions to "inactive" * TRANSITION_CALLBACK_ERROR or any uncaught exceptions to "errorprocessing" */ rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn on_activate(const rclcpp_lifecycle::State & state) { // The parent class method automatically transition on managed entities // (currently, LifecyclePublisher). // pub_->on_activate() could also be called manually here. // Overriding this method is optional, a lot of times the default is enough. LifecycleNode::on_activate(state); RCUTILS_LOG_INFO_NAMED(get_name(), "on_activate() is called."); // Let's sleep for 2 seconds. // We emulate we are doing important // work in the activating phase. std::this_thread::sleep_for(2s); // We return a success and hence invoke the transition to the next // step: "active". // If we returned TRANSITION_CALLBACK_FAILURE instead, the state machine // would stay in the "inactive" state. // In case of TRANSITION_CALLBACK_ERROR or any thrown exception within // this callback, the state machine transitions to state "errorprocessing". return rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn::SUCCESS; } /// Transition callback for state deactivating /** * on_deactivate callback is being called when the lifecycle node * enters the "deactivating" state. * Depending on the return value of this function, the state machine * either invokes a transition to the "inactive" state or stays * in "active". * TRANSITION_CALLBACK_SUCCESS transitions to "inactive" * TRANSITION_CALLBACK_FAILURE transitions to "active" * TRANSITION_CALLBACK_ERROR or any uncaught exceptions to "errorprocessing" */ rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn on_deactivate(const rclcpp_lifecycle::State & state) { // The parent class method automatically transition on managed entities // (currently, LifecyclePublisher). // pub_->on_deactivate() could also be called manually here. // Overriding this method is optional, a lot of times the default is enough. LifecycleNode::on_deactivate(state); RCUTILS_LOG_INFO_NAMED(get_name(), "on_deactivate() is called."); // We return a success and hence invoke the transition to the next // step: "inactive". // If we returned TRANSITION_CALLBACK_FAILURE instead, the state machine // would stay in the "active" state. // In case of TRANSITION_CALLBACK_ERROR or any thrown exception within // this callback, the state machine transitions to state "errorprocessing". return rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn::SUCCESS; } /// Transition callback for state cleaningup /** * on_cleanup callback is being called when the lifecycle node * enters the "cleaningup" state. * Depending on the return value of this function, the state machine * either invokes a transition to the "unconfigured" state or stays * in "inactive". * TRANSITION_CALLBACK_SUCCESS transitions to "unconfigured" * TRANSITION_CALLBACK_FAILURE transitions to "inactive" * TRANSITION_CALLBACK_ERROR or any uncaught exceptions to "errorprocessing" */ rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn on_cleanup(const rclcpp_lifecycle::State &) { // In our cleanup phase, we release the shared pointers to the // timer and publisher. These entities are no longer available // and our node is "clean". timer_.reset(); pub_.reset(); RCUTILS_LOG_INFO_NAMED(get_name(), "on cleanup is called."); // We return a success and hence invoke the transition to the next // step: "unconfigured". // If we returned TRANSITION_CALLBACK_FAILURE instead, the state machine // would stay in the "inactive" state. // In case of TRANSITION_CALLBACK_ERROR or any thrown exception within // this callback, the state machine transitions to state "errorprocessing". return rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn::SUCCESS; } /// Transition callback for state shutting down /** * on_shutdown callback is being called when the lifecycle node * enters the "shuttingdown" state. * Depending on the return value of this function, the state machine * either invokes a transition to the "finalized" state or stays * in its current state. * TRANSITION_CALLBACK_SUCCESS transitions to "finalized" * TRANSITION_CALLBACK_FAILURE transitions to current state * TRANSITION_CALLBACK_ERROR or any uncaught exceptions to "errorprocessing" */ rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn on_shutdown(const rclcpp_lifecycle::State & state) { // In our shutdown phase, we release the shared pointers to the // timer and publisher. These entities are no longer available // and our node is "clean". timer_.reset(); pub_.reset(); RCUTILS_LOG_INFO_NAMED( get_name(), "on shutdown is called from state %s.", state.label().c_str()); // We return a success and hence invoke the transition to the next // step: "finalized". // If we returned TRANSITION_CALLBACK_FAILURE instead, the state machine // would stay in the current state. // In case of TRANSITION_CALLBACK_ERROR or any thrown exception within // this callback, the state machine transitions to state "errorprocessing". return rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn::SUCCESS; } private: // We hold an instance of a lifecycle publisher. This lifecycle publisher // can be activated or deactivated regarding on which state the lifecycle node // is in. // By default, a lifecycle publisher is inactive by creation and has to be // activated to publish messages into the ROS world. std::shared_ptr<rclcpp_lifecycle::LifecyclePublisher<std_msgs::msg::String>> pub_; // We hold an instance of a timer which periodically triggers the publish function. // As for the beta version, this is a regular timer. In a future version, a // lifecycle timer will be created which obeys the same lifecycle management as the // lifecycle publisher. std::shared_ptr<rclcpp::TimerBase> timer_; }; /** * A lifecycle node has the same node API * as a regular node. This means we can spawn a * node, give it a name and add it to the executor. */ int main(int argc, char * argv[]) { // force flush of the stdout buffer. // this ensures a correct sync of all prints // even when executed simultaneously within the launch file. setvbuf(stdout, NULL, _IONBF, BUFSIZ); rclcpp::init(argc, argv); rclcpp::executors::SingleThreadedExecutor exe; std::shared_ptr<LifecycleTalker> lc_node = std::make_shared<LifecycleTalker>("lc_talker"); exe.add_node(lc_node->get_node_base_interface()); exe.spin(); rclcpp::shutdown(); return 0; }
40.588997
96
0.737123
HATAEGON
11618218922b6e1590c9d93f947d503eb08537d3
273
hpp
C++
src/info.hpp
jlangvand/jucipp
0a3102f13e62d78a329d488fb1eb8812181e448e
[ "MIT" ]
null
null
null
src/info.hpp
jlangvand/jucipp
0a3102f13e62d78a329d488fb1eb8812181e448e
[ "MIT" ]
null
null
null
src/info.hpp
jlangvand/jucipp
0a3102f13e62d78a329d488fb1eb8812181e448e
[ "MIT" ]
1
2019-12-05T00:56:32.000Z
2019-12-05T00:56:32.000Z
#pragma once #include <gtkmm.h> class Info : public Gtk::InfoBar { Info(); public: static Info &get() { static Info instance; return instance; } void print(const std::string &text); private: Gtk::Label label; sigc::connection timeout_connection; };
14.368421
38
0.666667
jlangvand
11678fedcabd0106b1d812718274714701f60a7a
9,433
cpp
C++
NYP_Framework_Week08_SOLUTION/Base/Source/SpatialPartition/Grid.cpp
KianMarvi/Assignment
8133acec4dd65bc49316aec8deb3961035bdef27
[ "MIT" ]
null
null
null
NYP_Framework_Week08_SOLUTION/Base/Source/SpatialPartition/Grid.cpp
KianMarvi/Assignment
8133acec4dd65bc49316aec8deb3961035bdef27
[ "MIT" ]
8
2019-12-29T17:17:00.000Z
2020-02-07T08:08:01.000Z
NYP_Framework_Week08_SOLUTION/Base/Source/SpatialPartition/Grid.cpp
KianMarvi/Assignment
8133acec4dd65bc49316aec8deb3961035bdef27
[ "MIT" ]
null
null
null
#include "Grid.h" #include "stdio.h" #include "MeshBuilder.h" #include "RenderHelper.h" #include "../GenericEntity.h" #include "../SceneGraph/SceneGraph.h" /******************************************************************************** Constructor ********************************************************************************/ CGrid::CGrid(void) : index(Vector3(-1, -1, -1)) , size(Vector3(-1, -1, -1)) , offset(Vector3(-1, -1, -1)) , min(Vector3(-1, -1, -1)) , max(Vector3(-1, -1, -1)) , theMesh(NULL) , ListOfObjects(NULL) , meshRenderMode(FILL) , theDetailLevel(CLevelOfDetails::NO_DETAILS) { } /******************************************************************************** Destructor ********************************************************************************/ CGrid::~CGrid(void) { if (theMesh) { // Do not delete the Mesh here as MeshBuilder will take care of them. //delete theMesh; theMesh = NULL; } Remove(); } /******************************************************************************** Initialise this grid ********************************************************************************/ void CGrid::Init( const int xIndex, const int zIndex, const int xGridSize, const int zGridSize, const float xOffset, const float zOffset) { index.Set((float)xIndex, 0.0f, (float)zIndex); size.Set((float)xGridSize, 0.0f, (float)zGridSize); offset.Set(xOffset, 0.0f, zOffset); min.Set(index.x * size.x - offset.x, 0.0f, index.z * size.z - offset.z); max.Set(index.x * size.x - offset.x + xGridSize, 0.0f, index.z * size.z - offset.z + zGridSize); } /******************************************************************************** Set a particular grid's Mesh ********************************************************************************/ void CGrid::SetMesh(const std::string& _meshName) { Mesh* modelMesh = MeshBuilder::GetInstance()->GetMesh(_meshName); if (modelMesh != nullptr) { theMesh = MeshBuilder::GetInstance()->GetMesh(_meshName); } } /******************************************************************************** Set Mesh's Render Mode ********************************************************************************/ void CGrid::SetMeshRenderMode(SMeshRenderMode meshRenderMode) { this->meshRenderMode = meshRenderMode; } /******************************************************************************** Get Mesh's Render Mode ********************************************************************************/ CGrid::SMeshRenderMode CGrid::GetMeshRenderMode(void) const { return meshRenderMode; } /******************************************************************************** Update the grid ********************************************************************************/ void CGrid::Update(vector<EntityBase*>* migrationList) { // Check each object to see if they are no longer in this grid std::vector<EntityBase*>::iterator it; it = ListOfObjects.begin(); while (it != ListOfObjects.end()) { Vector3 position = (*it)->GetPosition(); if (((min.x <= position.x) && (position.x < max.x)) && ((min.z <= position.z) && (position.z < max.z))) { // Move on otherwise ++it; } else { migrationList->push_back(*it); // Remove from this Grid it = ListOfObjects.erase(it); } } } /******************************************************************************** Render ********************************************************************************/ void CGrid::Render(void) { if (theMesh) { if (ListOfObjects.size() > 0) { // Set to wire render mode if wire render mode is required if (meshRenderMode == WIRE) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); RenderHelper::RenderMesh(theMesh); // Set back to fill render mode if wire render mode is required if (meshRenderMode == WIRE) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } } } /******************************************************************************** RenderObjects ********************************************************************************/ void CGrid::RenderObjects(const int RESOLUTION) { /* glPushAttrib(GL_ENABLE_BIT); // Draw the Grid and its list of objects for (int i=0; i<(int)ListOfObjects.size(); i++) { ListOfObjects[i]->Render(RESOLUTION); } glPopAttrib(); */ } /******************************************************************************** Add a new object to this grid ********************************************************************************/ void CGrid::Add(EntityBase* theObject) { for (int i = 0; i < (int)ListOfObjects.size(); ++i) { if (ListOfObjects[i] == theObject) return; } ListOfObjects.push_back( theObject ); ChangeGridColor(); } /******************************************************************************** Remove but not delete object from this grid ********************************************************************************/ void CGrid::Remove(void) { for (int i = 0; i < (int)ListOfObjects.size(); i++) { // We can delete the entities here. // If you delete them here, then do not delete in Scene Graph or SceneText delete ListOfObjects[i]; ListOfObjects[i] = NULL; ChangeGridColor(); } ListOfObjects.clear(); } /******************************************************************************** Remove but not delete an object from this grid ********************************************************************************/ bool CGrid::Remove(EntityBase* theObject) { // Clean up entities that are done std::vector<EntityBase*>::iterator it, end; it = ListOfObjects.begin(); end = ListOfObjects.end(); while (it != end) { if ((*it) == theObject) { it = ListOfObjects.erase(it); ChangeGridColor(); return true; } else { // Move on otherwise ++it; } } return false; } /******************************************************************************** Check if an object is in this grid ********************************************************************************/ bool CGrid::IsHere(EntityBase* theObject) const { for (int i = 0; i < (int)ListOfObjects.size(); ++i) { if (ListOfObjects[i] == theObject) return true; } return false; } /******************************************************************************** Get list of objects in this grid ********************************************************************************/ vector<EntityBase*> CGrid::GetListOfObject(Vector3 position, const float radius) { // if the radius of inclusion is not specified, or illegal value specified // then return all entities in this grid if (radius <= 0.0f) { return ListOfObjects; } vector<EntityBase*> theListOfObjects; for (int i = 0; i < (int)ListOfObjects.size(); ++i) { // Calculate the distance between the object and the supplied position // And check if it is within the radius if ((ListOfObjects[i]->GetPosition() - position).LengthSquared() < radius * radius) { theListOfObjects.push_back(ListOfObjects[i]); } } return theListOfObjects; } /******************************************************************************** Set the Level of Detail for objects in this CGrid ********************************************************************************/ void CGrid::SetDetailLevel(const CLevelOfDetails::DETAIL_LEVEL theDetailLevel) { this->theDetailLevel = theDetailLevel; // Update the objects in this grid to the specified level of detail GenericEntity* aGenericEntity = NULL; for (int i = 0; i < (int)ListOfObjects.size(); ++i) { aGenericEntity = (GenericEntity*)ListOfObjects[i]; if (aGenericEntity->GetLODStatus() == true) { aGenericEntity->SetDetailLevel(theDetailLevel); } } } // Get number of objects in this grid int CGrid::GetNumOfObject(void) const { return ListOfObjects.size(); } /******************************************************************************** PrintSelf ********************************************************************************/ void CGrid::PrintSelf(void) { if (ListOfObjects.size() > 0) { cout << "********************************************************************************" << endl; cout << "CGrid::PrintSelf()" << endl; cout << "\tIndex\t:\t" << index << "\t\tOffset\t:\t" << offset << endl; cout << "\tMin\t:\t" << min << "\tMax\t:\t" << max << endl; cout << "\tList of objects in this grid: (LOD:" << this->theDetailLevel << ")" << endl; cout << "\t------------------------------------------------------------------------" << endl; for (int i = 0; i < (int)ListOfObjects.size(); ++i) { cout << "\t" << i << "\t:\t" << ListOfObjects[i]->GetPosition() << endl; GenericEntity* aGenericEntity = (GenericEntity*)ListOfObjects[i]; cout << aGenericEntity->GetLODStatus() << endl; if (aGenericEntity->GetLODStatus() == true) { cout << "\t\t\t\t*** LOD Level: " << ((GenericEntity*)ListOfObjects[i])->GetDetailLevel() << endl; } } cout << "\t------------------------------------------------------------------------" << endl; cout << "********************************************************************************" << endl; } else { //cout << "\tThis grid has no entities." << endl; } } void CGrid::ChangeGridColor() { if (ListOfObjects.size() >= 1) { SetMesh("GRID_YELLOW"); } if (ListOfObjects.size() >= 3) { SetMesh("GRID_ORANGE"); } if (ListOfObjects.size() >= 5) { SetMesh("GRID_RED"); } }
30.33119
102
0.457225
KianMarvi
11693cdca03008dcf4f1d1c9d9d9e2cd55ab4853
2,017
cpp
C++
bin/lib/setuptools/main.cpp
TansuoTro/CPPS
cca35d8dc2128aba7fa4a40cb6d83487e265cf3f
[ "MIT" ]
null
null
null
bin/lib/setuptools/main.cpp
TansuoTro/CPPS
cca35d8dc2128aba7fa4a40cb6d83487e265cf3f
[ "MIT" ]
null
null
null
bin/lib/setuptools/main.cpp
TansuoTro/CPPS
cca35d8dc2128aba7fa4a40cb6d83487e265cf3f
[ "MIT" ]
null
null
null
#import "json" #import "compress" namespace setuptools{ //生成安装文件 var setup(var option){ io.mkdir("dist"); var filename = "{option["name"]}-{option["username"]}-{option["version"]}-{option["platfrom"]}"; var configname = "dist/{filename}.json"; print("build config json file..."); var jsonval = json.encode(option); io.remove(configname); var jsonfile = io.fopen(configname,"wb+"); if(jsonfile){ io.fwrites(jsonfile,jsonval); io.fclose(jsonfile); console.color(2); println("success!"); console.clearcolor(); } else{ console.color(1); println("faild!"); console.clearcolor(); return; } var targzname = "dist/{filename}.tar.gz"; io.remove(targzname); print("create tar.gz file..."); var file = tarfile.open(targzname,"x:gz"); if(!file){ console.color(1); println("faild!"); console.clearcolor(); return; } console.color(2); println("success!"); console.clearcolor(); var projectpath = "{option["name"]}/"; var count = option["packages"].size(); var idx = 1; foreach(var filename : option["packages"]){ var pos = string.find(filename,projectpath); var filename2 = filename; if(pos == 0){ filename2 = string.substr(filename,string.length(projectpath),string.npos); } console.color(4); print("[{idx}/{count}] "); idx++; console.clearcolor(); print("{filename} ..."); var fileinfo = file.gettarinfo(filename,filename2); if(fileinfo){ file.addfile(fileinfo); console.color(2); println("ok"); console.clearcolor(); } } print("saving compressed file..."); file.close(); console.color(2); println("success!"); console.clearcolor(); exit(0); } var find_packages(var projectname){ var ret = []; var b = io.file_exists("README.md"); if(b) ret.push_back("README.md"); var b = io.file_exists("LICENSE"); if(b) ret.push_back("LICENSE"); var list = io.walk(projectname); foreach(var filename:list){ ret.push_back(filename); } return ret; } }
23.183908
98
0.632127
TansuoTro
116c8dfd6129ad74f1dd6ae441a5bc1bb7a09067
65,211
cc
C++
src/paths/long/SupportedHyperBasevector6.cc
Amjadhpc/w2rap-contigger
221f6cabedd19743046ee5dec18e6feb85130218
[ "MIT" ]
48
2016-04-26T16:52:59.000Z
2022-01-15T09:18:17.000Z
src/paths/long/SupportedHyperBasevector6.cc
Amjadhpc/w2rap-contigger
221f6cabedd19743046ee5dec18e6feb85130218
[ "MIT" ]
45
2016-04-27T08:20:56.000Z
2022-02-14T07:47:11.000Z
src/paths/long/SupportedHyperBasevector6.cc
Amjadhpc/w2rap-contigger
221f6cabedd19743046ee5dec18e6feb85130218
[ "MIT" ]
15
2016-05-11T14:35:25.000Z
2022-01-15T09:18:45.000Z
/////////////////////////////////////////////////////////////////////////////// // SOFTWARE COPYRIGHT NOTICE AGREEMENT // // This software and its documentation are copyright (2014) by the // // Broad Institute. All rights are reserved. This software is supplied // // without any warranty or guaranteed support whatsoever. The Broad // // Institute is not responsible for its use, misuse, or functionality. // /////////////////////////////////////////////////////////////////////////////// /* * SupportedHyperBasevector6.cc * * Created on: Apr 3, 2013 * Author: tsharpe */ // MakeDepend: library OMP // MakeDepend: cflags OMP_FLAGS #include "Basevector.h" #include "CoreTools.h" #include "IteratorRange.h" #include "ParallelVecUtilities.h" #include "Qualvector.h" #include "paths/long/CreateGenome.h" //#include "paths/long/EvalByReads.h" #include "paths/long/KmerCount.h" #include "paths/long/SupportedHyperBasevector.h" #include "random/Bernoulli.h" #include "system/WorklistN.h" #include <algorithm> #include <set> namespace { // open anonymous namespace class BubbleProc { public: BubbleProc( SupportedHyperBasevector const& shbv, SupportedHyperBasevector::BubbleParams const& parms, SupportedHyperBasevector::BubbleAux const& aux, long_logging_control const& log_control, long_logging const& logc, vec< std::pair<int,vec<int> > >* pSubs, const long_heuristics& heur ) : mSHBV(shbv), mParms(parms), mAux(aux), mLogControl(log_control), mLogC(logc), mpSubs(pSubs), mheur(&heur) {} void operator()( size_t edgeId ) { vec<int> substPath; if ( mSHBV.IsPoppable(edgeId,mParms,mAux,mLogControl,mLogC,&substPath,*mheur) ) { SpinLocker lock(gLockedData); mpSubs->push(edgeId,substPath); } } private: SupportedHyperBasevector const& mSHBV; SupportedHyperBasevector::BubbleParams const& mParms; SupportedHyperBasevector::BubbleAux const& mAux; long_logging_control const& mLogControl; long_logging const& mLogC; vec< std::pair<int,vec<int> > >* mpSubs; static SpinLockedData gLockedData; const long_heuristics* mheur; }; SpinLockedData BubbleProc::gLockedData; } // close anonymous namespace void TruncateMe( vec<int>& p, Bool& del, int& start, int& stop, const vec<Bool>& used, const SupportedHyperBasevector& shb ) { del = False; vec< vec<int> > subs, subs_origin; vec<int> s, s_origin; for ( int j = 0; j <= p.isize( ); j++ ) { if ( j == p.isize( ) || ( p[j] >= 0 && !used[ p[j] ] ) ) { if ( s.nonempty( ) ) { if ( s.back( ) < 0 ) { s.pop_back( ); s_origin.pop_back( ); } subs.push_back(s); subs_origin.push_back(s_origin); } s.clear( ); s_origin.clear( ); } else { s.push_back( p[j] ); s_origin.push_back(j); } } vec<int> nkmers( subs.size( ), 0 ), ids( subs.size( ), vec<int>::IDENTITY ); for ( int j = 0; j < subs.isize( ); j++ ) { for ( int l = 0; l < subs[j].isize( ); l++ ) nkmers[j] += shb.EdgeLengthKmers( subs[j][l] ); } ReverseSortSync( nkmers, ids ); if ( nkmers.empty( ) || ( nkmers.size( ) >= 2 && nkmers[0] == nkmers[1] ) ) del = True; else { p = subs[ ids[0] ]; start = subs_origin[ ids[0] ].front( ); stop = subs_origin[ ids[0] ].back( ); } } void SupportedHyperBasevector::TruncatePaths( const long_logging& logc ) { double clock = WallClockTime( ); vec<Bool> used, to_delete( NPaths( ), False ); Used(used); for ( int i = 0; i < NPaths( ); i++ ) { Bool del; int start, stop; TruncateMe( PathMutable(i), del, start, stop, used, *this ); if (del) to_delete[i] = True; } EraseIf( PathsMutable( ), to_delete ); EraseIf( WeightsFwMutable( ), to_delete ); EraseIf( WeightsRcMutable( ), to_delete ); // Temporary if. if ( WeightsFwOrigin( ).size( ) == WeightsFw( ).size( ) ) { EraseIf( WeightsFwOriginMutable( ), to_delete ); EraseIf( WeightsRcOriginMutable( ), to_delete ); } to_delete.resize_and_set( NPairs( ), False ); for ( int i = 0; i < NPairs( ); i++ ) { Bool del1, del2; int start1, stop1, start2, stop2; vec<int> left = PairLeftMutable(i), right = PairRightMutable(i); TruncateMe( PairLeftMutable(i), del1, start1, stop1, used, *this ); TruncateMe( PairRightMutable(i), del2, start2, stop2, used, *this ); if ( del1 || del2 ) to_delete[i] = True; else { int sub = 0; for ( int k = stop1; k < left.isize( ); k++ ) sub += EdgeLengthKmers( left[k] ); for ( int k = 0; k < start2; k++ ) sub += EdgeLengthKmers( right[k] ); AddTrim( i, -sub ); } } EraseIf( PairsMutable( ), to_delete ); EraseIf( PairDataMutable( ), to_delete ); UniqueOrderPaths( ); REPORT_TIME( clock, "used in TruncatePaths" ); } void SupportedHyperBasevector::PopBubbles( BubbleParams const& parms, unsigned nThreads, const long_logging_control& log_control, const long_logging& logc, const long_heuristics& heur ) { double clock1 = WallClockTime( ); BubbleAux aux; ToLeft(aux.to_left), ToRight(aux.to_right); aux.paths_index.resize( EdgeObjectCount() ); aux.mult_fw.resize( EdgeObjectCount( ), 0 ); aux.mult_rc.resize( EdgeObjectCount( ), 0 ); for ( int i = 0; i < Paths( ).isize( ); i++ ) for ( int j = 0; j < Path(i).isize( ); j++ ) { if ( Path(i,j) >= 0 ) { aux.mult_fw[ Path(i,j) ] += WeightFw(i); aux.mult_rc[ Path(i,j) ] += WeightRc(i); aux.paths_index[ Path(i,j) ].push( i, j ); } } vec< std::pair< int, vec<int> > > subs; if ( true ) { BubbleProc proc(*this,parms,aux,log_control,logc,&subs,heur); parallelFor(0,EdgeObjectCount(),proc,nThreads); } REPORT_TIME( clock1, "used popping 1" ); double clock2 = WallClockTime( ); vec< vec< std::pair<int,int> > > subs_index( EdgeObjectCount( ) ); for ( int i = 0; i < subs.isize( ); i++ ) for ( int j = 0; j < subs[i].second.isize( ); j++ ) subs_index[ subs[i].second[j] ].push( i, j ); for ( int i = 0; i < subs.isize( ); i++ ) { int e = subs[i].first; vec<int> p = subs[i].second; for ( int j = 0; j < aux.paths_index[e].isize( ); j++ ) { int id = aux.paths_index[e][j].first; int pos = aux.paths_index[e][j].second; vec<int>& q = PathsMutable( )[id]; for ( int l = pos; l < q.isize( ); l++ ) { int r = BinPosition( aux.paths_index[ q[l] ], std::make_pair(id,l) ); if ( r >= 0 ) { aux.paths_index[ q[l] ].erase( aux.paths_index[ q[l] ].begin( ) + r ); } } vec<int> qnew(q); qnew.resize(pos); qnew.append(p); for ( int l = pos+1; l < q.isize( ); l++ ) qnew.push_back( q[l] ); q = qnew; for ( int l = pos; l < q.isize( ); l++ ) { aux.paths_index[ q[l] ].push_back( std::make_pair(id,l) ); Sort( aux.paths_index[ q[l] ] ); } aux.paths_index[e].clear( ); } for ( int j = 0; j < subs_index[e].isize( ); j++ ) { int id = subs_index[e][j].first, pos = subs_index[e][j].second; vec<int>& q = subs[id].second; for ( int l = pos; l < q.isize( ); l++ ) { int r = BinPosition( subs_index[ q[l] ], std::make_pair(id,l) ); if ( r >= 0 ) { subs_index[ q[l] ].erase( subs_index[ q[l] ].begin( ) + r ); } } vec<int> qnew(q); qnew.resize(pos); qnew.append(p); for ( int l = pos+1; l < q.isize( ); l++ ) qnew.push_back( q[l] ); q = qnew; for ( int l = pos; l < q.isize( ); l++ ) { subs_index[ q[l] ].push_back( std::make_pair(id,l) ); Sort( subs_index[ q[l] ] ); } subs_index[e].clear( ); } } vec<int> to_delete; to_delete.reserve(subs.size()); for ( size_t idx = 0; idx != subs.size(); ++idx ) to_delete.push_back(subs[idx].first); DeleteEdges(to_delete); RemoveEdgelessVertices( ); RemoveUnneededVertices( ); REPORT_TIME( clock2, "used popping 2" ); RemoveDeadEdgeObjects( ); double clock3 = WallClockTime( ); UniqueOrderPaths( ); // Force symmetry of paths and weights. I suppose we might instead try to // figure out how they got asymmetric. vec< vec<int> > new_paths; vec<fix64_6> new_weights_fw, new_weights_rc; vec< vec< std::pair<fix64_6,int64_t> > > new_weights_fw_origin; vec< vec< std::pair<fix64_6,int64_t> > > new_weights_rc_origin; for ( int i1 = 0; i1 < NPaths( ); i1++ ) { const vec<int>& p1 = Path(i1); if ( !InvDef( p1[0] ) ) continue; vec<int> p2; for ( int j = 0; j < p1.isize( ); j++ ) { if ( p1[j] < 0 ) p2.push_back( p1[j] ); else p2.push_back( Inv( p1[j] ) ); } p2.ReverseMe( ); int i2 = BinPosition( Paths( ), p2 ); if ( i2 < 0 ) { new_paths.push_back(p2); new_weights_fw.push_back( WeightFw(i1) ); new_weights_rc.push_back( WeightRc(i1) ); // Temporary if. if ( WeightsFwOrigin( ).size( ) == WeightsFw( ).size( ) ) { new_weights_fw_origin.push_back( WeightFwOrigin(i1) ); new_weights_rc_origin.push_back( WeightRcOrigin(i1) ); } } } PathsMutable( ).append(new_paths); WeightsFwMutable( ).append(new_weights_fw); WeightsRcMutable( ).append(new_weights_rc); WeightsFwOriginMutable( ).append(new_weights_fw_origin); WeightsRcOriginMutable( ).append(new_weights_rc_origin); // Temporary if. if ( WeightsFwOrigin( ).size( ) == WeightsFw( ).size( ) ) { SortSync( PathsMutable( ), WeightsFwMutable( ), WeightsRcMutable( ), WeightsFwOriginMutable( ), WeightsRcOriginMutable( ) ); } else SortSync( PathsMutable( ), WeightsFwMutable( ), WeightsRcMutable( ) ); // Maybe we're doing something here that is fundamentally wrong. // (NOW TURNED OFF.) int npairs = NPairs( ); /* vec<Bool> todel( npairs, False ); for ( int i1 = 0; i1 < NPairs( ); i1++ ) { const vec<int> &p1 = PairLeft(i1), &q1 = PairRight(i1); if ( InvDef( p1[0] ) != InvDef( q1[0] ) ) todel[i1] = True; } EraseIf( PairsMutable( ), todel ); EraseIf( PairDataMutable( ), todel ); */ for ( int i1 = 0; i1 < npairs; i1++ ) { const vec<int> &p1 = PairLeft(i1), &q1 = PairRight(i1); if ( !InvDef( p1[0] ) || !InvDef( q1[0] ) ) continue; vec<int> p2, q2; for ( int j = 0; j < p1.isize( ); j++ ) { if ( p1[j] < 0 ) p2.push_back( p1[j] ); else p2.push_back( Inv( p1[j] ) ); } for ( int j = 0; j < q1.isize( ); j++ ) { if ( q1[j] < 0 ) q2.push_back( q1[j] ); else q2.push_back( Inv( q1[j] ) ); } p2.ReverseMe( ), q2.ReverseMe( ); int i2 = BinPosition( Pairs( ), std::make_pair( q2, p2 ) ); if ( i2 < 0 ) { PairsMutable( ).push_back( std::make_pair( q2, p2 ) ); PairDataMutable( ).push_back( PairData(i1) ); SortSync( PairsMutable( ), PairDataMutable( ) ); } } REPORT_TIME( clock3, "used popping 3" ); FixWeights(logc); TestValid(logc); } bool SupportedHyperBasevector::IsPoppable( int e, BubbleParams const& parms, BubbleAux const& aux, long_logging_control const& log_control, long_logging const& logc, vec<int>* pSubstPath, const long_heuristics& heur ) const { int v = aux.to_left[e]; int w = aux.to_right[e]; // don't consider certain edges with strong evidence if ( aux.mult_fw[e] > parms.max_pop_del && aux.mult_rc[e] > parms.max_pop_del ) return false; if ( Max( aux.mult_fw[e], aux.mult_rc[e] ) > parms.max_pop_del2 ) return false; // establish a min and max path length for alternate paths int ne = EdgeObject(e).isize( ) - K( ) + 1; int low = ne - int( floor( parms.min_pop_ratio * parms.delta_kmers ) ); int high = ne + int( floor( parms.min_pop_ratio * parms.delta_kmers ) ); vec< vec<int> > paths, paths_final; vec<int> pathlens, pathlens_final; vec<fix64_6> mult_fw_final, mult_rc_final; // beginning of depth-first recursion from the starting vertex // to look for alternate paths // NOTE: it would probably be a little faster to go breadth-first // instead. you might more quickly discover multiple alternatives // without fully exploring tiny cycles. for ( int l = 0; l < From(v).isize( ); l++ ) { int f = EdgeObjectIndexByIndexFrom( v, l ); if ( f != e ) { paths.push_back(vec<int>(1,f)); pathlens.push_back( EdgeObject(f).isize( ) - K( ) + 1 ); } } // while there are alternatives to consider while( paths.nonempty( ) ) { vec<int> p = paths.back( ); int n = pathlens.back( ); paths.pop_back( ); // std::cout << "found path " << printSeq(p) << std::endl; // XXXXXXXXXXXXXXXXX pathlens.pop_back( ); int x = aux.to_right[ p.back( ) ]; // if the path under consideration has the right length, and // ends up at the same vertex as the subject edge if ( n >= low && n <= high && x == w ) { fix64_6 pmult_fw = 0, pmult_rc = 0; for ( int l = 0; l < aux.paths_index[ p[0] ].isize( ); l++ ) { int id = aux.paths_index[ p[0] ][l].first; int pos = aux.paths_index[ p[0] ][l].second; if ( Path(id).Contains( p, pos ) ) { pmult_fw += WeightFw(id); pmult_rc += WeightRc(id); } } // if it has appropriate weight, it's a possibility if ( pmult_fw <= parms.max_pop_del || pmult_rc <= parms.max_pop_del ) continue; // if weight insufficient, no need to extend further paths_final.push_back(p); // std::cout << "accepting path " << printSeq(p) << std::endl; // XXX pathlens_final.push_back(n); mult_fw_final.push_back(pmult_fw); mult_rc_final.push_back(pmult_rc); // we're only looking for situations where there's a // single valid alternative path, so quit early when // we've discovered two alternatives if ( paths_final.size() > 1 ) break; } // if the path is already too long, don't extend it further if ( n > high ) continue; // extend path and continue recursive exploration for ( int l = 0; l < From(x).isize( ); l++ ) { int f = EdgeObjectIndexByIndexFrom( x, l ); if ( f != e ) { paths.push_back(p); paths.back().push_back(f); pathlens.push_back( n + EdgeObject(f).isize( ) - K( ) + 1 ); } } } if ( !paths_final.solo( ) ) return false; if ( Abs( pathlens_final[0] - ne ) > parms.delta_kmers ) return false; /* if ( ( mult_fw_final[0] < parms.min_pop_ratio * aux.mult_fw[e] ) && ( mult_rc_final[0] < parms.min_pop_ratio * aux.mult_rc[e] ) ) { continue; } */ // Proper statistical test - note missing from other documentation. // Compare similar code in ImproveLongHyper.cc. const double max_asym_rarity = 0.00001; double f1 = mult_fw_final[0].ToDouble(), r1 = mult_rc_final[0].ToDouble();; double f2 = aux.mult_fw[e].ToDouble(), r2 = aux.mult_rc[e].ToDouble(); if ( f2 > r2 || ( f2 == r2 && f1 > r1 ) ) { std::swap( f1, r1 ); std::swap( f2, r2 ); } int n = int(floor(f1+r1+f2+r2)); if ( f1 == 0 || n == 0 || n > 10000 ) return false; long double p; double q; if ( !heur.FIX_ASYMMETRY_BUG ) { p = Min( 0.5, f1/(f1+r1) ) / 2; q = BinomialSum( n, int(ceil(f2)), p ); } else { p = 0.5; q = BinomialSum( n, int(ceil( Min(f1+r1,f2+r2) )), p ); } if ( q >= max_asym_rarity ) return false; // Report result. if ( logc.verb[ "POP_BUBBLES" ] >= 1 ) { static SpinLockedData gLockedData; SpinLocker lock(gLockedData); std::cout << "\nPopBubbles: replace e = " << e << " by " << printSeq( paths_final[0] ) << std::endl; PRINT2( aux.mult_fw[e], aux.mult_rc[e] ); PRINT2( mult_fw_final[0], mult_rc_final[0] ); } *pSubstPath = paths_final[0]; return true; } namespace { typedef int EdgeId; typedef int VertexId; typedef unsigned SegId; // An ordered sequence of EdgeIds that describe, e.g., a traversal of a graph typedef vec<EdgeId> SHBVPath; // A collection of edgeIds describing, e.g., the set of edges departing a vertex typedef vec<EdgeId> EdgeCollection; // A pair of edgeIds typedef std::pair<EdgeId,EdgeId> EdgePair; // An element of some read's path on the graph struct ReadSegment { ReadSegment()=default; ReadSegment( EdgeId readId, SegId segId ) : mReadId(readId), mSegId(segId) {} EdgeId mReadId; SegId mSegId; }; // an operation we think is a valid simplification of the graph typedef triple<EdgeCollection,EdgeCollection,EdgeCollection> SHBV_Join; // instructions about what pull-aparts to do struct Recommendations : private SpinLockedData { void addRecommendation( std::set<SHBVPath> const& bridges11, std::set<SHBVPath> const& bridges22, EdgeCollection const& reach ); vec<SHBV_Join> mJoins; vec<vec<SHBVPath>> mPaths1, mPaths2; }; // adding a recommendation is thread safe void Recommendations::addRecommendation( std::set<SHBVPath> const& bridges11, std::set<SHBVPath> const& bridges22, EdgeCollection const& reach ) { ForceAssert(bridges11.size()); ForceAssert(bridges22.size()); EdgeId e1 = bridges11.begin()->front(), e2 = bridges22.begin()->front(); EdgeId f1 = bridges11.begin()->back(), f2 = bridges22.begin()->back(); EdgeCollection eee{e1,e2}; EdgeCollection fff{f1,f2}; SHBV_Join join(eee,reach,fff); SpinLocker lock(*this); mJoins.push_back(join); mPaths1.push(bridges11.begin(),bridges11.end()); mPaths2.push(bridges22.begin(),bridges22.end()); } // paths and cum weights for all paths from some edge e to edges f1 or f2 struct PathWeights { PathWeights( SupportedHyperBasevector const& hbv, vec<ReadSegment> const& segs, EdgeId e, EdgeId f1, EdgeId f2 ); // get the total length of a portion of a path in kmers static int getSpan( SupportedHyperBasevector const& hbv, SHBVPath::const_iterator itr, SHBVPath::const_iterator end ) { int span = 0; while ( itr != end ) { span += hbv.EdgeLengthKmers(*itr); ++itr; } return span; } fix64_6 weight1, weight2; // cum weights of paths to f1 and f2 std::set<SHBVPath> bridges1, bridges2; // distinct paths to f1 and f2 int mSpan; // max distance in kmers on any path from the edge to edge f1 or f2 }; PathWeights::PathWeights( SupportedHyperBasevector const& hbv, vec<ReadSegment> const& segs, EdgeId e, EdgeId f1, EdgeId f2 ) : weight1(0), weight2(0), mSpan(0) { auto segsEnd = segs.end(); for ( auto segsItr=segs.begin(); segsItr != segsEnd; ++segsItr ) { SHBVPath const& path = hbv.Path(segsItr->mReadId); fix64_6 const& weight = hbv.Weight(segsItr->mReadId); auto from = path.begin() + segsItr->mSegId; auto beg = from + 1; auto end = path.end(); auto itr = std::find(beg,end,f1); if ( itr != end ) { if ( std::find(beg,itr,e) != itr ) // skip it if there's a later continue; // instance of e weight1 += weight; bridges1.insert(SHBVPath(from,itr+1)); } else if ( (itr=std::find(beg,end,f2)) != end ) { if ( std::find(beg,itr,e) != itr ) // skip if there's a later continue; // instance of e weight2 += weight; bridges2.insert(SHBVPath(from,itr+1)); } else continue; mSpan = std::max(mSpan,getSpan(hbv,beg,itr)); } } // a thing that examines a vertex to decide whether it can be pulled apart class JoinDiscoverer { public: JoinDiscoverer( SupportedHyperBasevector const& hbv, vec<int> const& toLeft, vec<int> const& toRight, int verbosity, double minWeightSplit ) : mHBV(hbv), mToLeft(toLeft), mToRight(toRight), mPathsIndex(hbv.EdgeObjectCount()), mReadLenFudge(hbv.MedianCorrectedReadLength()), mVerbosity(verbosity), mMinWeightSplit(minWeightSplit), mMinWeightSplitLow(2) { EdgeId nEdges = hbv.Paths().isize(); for ( EdgeId edgeId = 0; edgeId != nEdges; edgeId++ ) { vec<EdgeId> const& path = hbv.Path(edgeId); SegId nSegs = path.size(); for ( SegId segId = 0; segId != nSegs; segId++ ) mPathsIndex[path[segId]].push_back(ReadSegment(edgeId,segId)); } } void processVertex( int vertexId, Recommendations* ) const; private: static size_t const MAX_AFFIX_LEN = 5; // scan read paths to find unique prefixes of paths that enter a vertex vec<SHBVPath> findPrefixes( EdgeCollection const& leftAlts ) const { vec<SHBVPath> prefixes; auto altsEnd = leftAlts.end(); for ( auto altsItr=leftAlts.begin(); altsItr != altsEnd; ++altsItr ) { vec<ReadSegment> const& segs = mPathsIndex[*altsItr]; auto segsEnd = segs.end(); for ( auto segsItr=segs.begin(); segsItr != segsEnd; ++segsItr ) { SHBVPath const& path = mHBV.Path(segsItr->mReadId); size_t nextEle = segsItr->mSegId + 1; auto pathEnd = path.begin()+nextEle; auto pathBeg = pathEnd - std::min(nextEle,MAX_AFFIX_LEN); bool found = false; auto end = prefixes.end(); for ( auto itr=prefixes.begin(); itr != end; ++itr ) { SHBVPath const& prefix = *itr; size_t len = std::min(nextEle,prefix.size()); if ( std::equal(pathEnd-len,pathEnd,prefix.end()-len) ) { if ( len < MAX_AFFIX_LEN && nextEle > len ) *itr = SHBVPath(pathBeg,pathEnd); found = true; break; } } if ( !found ) prefixes.push_back(SHBVPath(pathBeg,pathEnd)); } } return prefixes; } // scan read paths to find unique suffixes of paths that leave a vertex vec<SHBVPath> findSuffixes( EdgeCollection const& rightAlts ) const { vec<SHBVPath> suffixes; auto altsEnd = rightAlts.end(); for ( auto altsItr=rightAlts.begin(); altsItr != altsEnd; ++altsItr ) { vec<ReadSegment> const& segs = mPathsIndex[*altsItr]; auto segsEnd = segs.end(); for ( auto segsItr=segs.begin(); segsItr != segsEnd; ++segsItr ) { SHBVPath const& path = mHBV.Path(segsItr->mReadId); auto pathBeg = path.begin()+segsItr->mSegId; size_t pathLen = std::min(MAX_AFFIX_LEN, path.size()-segsItr->mSegId); bool found = false; auto end = suffixes.end(); for ( auto itr=suffixes.begin(); itr != end; ++itr ) { SHBVPath const& suffix = *itr; size_t len = std::min(pathLen,suffix.size()); if ( std::equal(pathBeg,pathBeg+len,suffix.begin()) ) { if ( pathLen > len ) *itr = SHBVPath(pathBeg,pathBeg+pathLen); found = true; break; } } if ( !found ) suffixes.push_back(SHBVPath(pathBeg,pathBeg+pathLen)); } } return suffixes; } // proper edge pairs tile the set of path prefixes or suffixes, i.e., // every path contains one or the other edge, and no path contains both static vec<EdgePair> getProperEdgePairs( vec<SHBVPath> const& paths ) { std::map<EdgeId,BitVec> map; size_t nPaths = paths.size(); for ( size_t idx = 0; idx != nPaths; ++idx ) { SHBVPath const& path = paths[idx]; for ( auto itr=path.begin(),end=path.end(); itr != end; ++itr ) { BitVec& bits = map[*itr]; bits.resize(nPaths,false); bits.set(idx,true); } } vec<EdgePair> pairs; for ( auto itr=map.begin(),end=map.end(); itr != end; ++itr ) { auto itr2 = itr; while ( ++itr2 != end ) { if ( (itr->second & itr2->second).isUniformlyFalse() && nor(itr->second,itr2->second).isUniformlyFalse() ) pairs.push_back(EdgePair(itr->first,itr2->first)); } } return pairs; } // gets a sorted list of EdgeIds that lie between e1 or e2 and f1 or f2. void getReach( PathWeights const& pw1, PathWeights const& pw2, EdgeCollection* pReach ) const { pReach->clear(); for ( SHBVPath const& path : pw1.bridges1 ) { ForceAssertGe(path.size(),2u); pReach->insert(pReach->end(),path.begin()+1,path.end()-1); } for ( SHBVPath const& path : pw1.bridges2 ) { ForceAssertGe(path.size(),2u); pReach->insert(pReach->end(),path.begin()+1,path.end()-1); } for ( SHBVPath const& path : pw2.bridges1 ) { ForceAssertGe(path.size(),2u); pReach->insert(pReach->end(),path.begin()+1,path.end()-1); } for ( SHBVPath const& path : pw2.bridges1 ) { ForceAssertGe(path.size(),2u); pReach->insert(pReach->end(),path.begin()+1,path.end()-1); } UniqueSort(*pReach); } // returns false if the reach is not a complete sub-graph delimited by // e1, e2, f1, and f2 (i.e., if non-reach, non-boundary edges enter or exit // from reach edges). bool checkReach( EdgeCollection const& reach, EdgeId e1, EdgeId e2, EdgeId f1, EdgeId f2 ) const { vec<int> reachVertices; reachVertices.reserve(reach.size()+2); for ( EdgeId e : reach ) { reachVertices.push_back(mToLeft[e]); } reachVertices.push_back(mToLeft[f1]); reachVertices.push_back(mToLeft[f2]); UniqueSort(reachVertices); auto beg = reach.begin(), end = reach.end(); for ( VertexId v : reachVertices ) { for ( EdgeId e : mHBV.ToEdgeObj(v) ) if ( e != e1 && e != e2 && !std::binary_search(beg,end,e) ) return false; for ( EdgeId e : mHBV.FromEdgeObj(v) ) if ( e != f1 && e != f2 && !std::binary_search(beg,end,e) ) return false; } return true; } // do the weights allow a pull apart? bool pullApart( fix64_6 const& weight_11, fix64_6 const& weight_12, fix64_6 const& weight_21, fix64_6 const& weight_22, int span ) const { bool result = false; if ( weight_11 >= mMinWeightSplitLow && weight_22 >= mMinWeightSplitLow && weight_12 == 0 && weight_21 == 0 ) result = true; if ( weight_11 >= mMinWeightSplit && weight_22 >= mMinWeightSplit && weight_12 + weight_21 <= 2 && span <= mReadLenFudge ) result = true; if ( weight_11 >= mMinWeightSplit/2 && weight_22 >= mMinWeightSplit/2 && weight_12 + weight_21 < 2 && span <= mReadLenFudge ) result = true; return result; } // thread-safe logging of a join void log( EdgeId e1, EdgeId e2, EdgeId f1, EdgeId f2, EdgeCollection const& reach, std::set<SHBVPath> const& bridge11, std::set<SHBVPath> const& bridge22, fix64_6 const& weight_11, fix64_6 const& weight_12, fix64_6 const& weight_21, fix64_6 const& weight_22, int span, bool result ) const { SpinLocker lock(gLockCOUT); std::cout << "e1=" << e1 << " e2=" << e2 << " f1=" << f1 << " f2=" << f2 << "\nreach: " << rangePrinter(reach.begin(),reach.end(),",") << "\nbridge11:"; int idx = 0; for ( auto itr=bridge11.begin(),end=bridge11.end(); itr != end; ++itr ) std::cout << "\n[" << ++idx << "] " << rangePrinter(itr->begin(),itr->end(),","); std::cout << "\nbridge22:"; idx = 0; for ( auto itr=bridge22.begin(),end=bridge22.end(); itr != end; ++itr ) std::cout << "\n[" << ++idx << "] " << rangePrinter(itr->begin(),itr->end(),","); std::cout << "\nw11=" << weight_11 << " w22=" << weight_22 << " w12=" << weight_12 << " w21=" << weight_21 << " span=" << span << '\n'; if ( !result ) std::cout << "rejected\n"; std::cout << std::endl; } SupportedHyperBasevector const& mHBV; vec<int> const& mToLeft; vec<int> const& mToRight; vec<vec<ReadSegment>> mPathsIndex; int mReadLenFudge; int mVerbosity; double mMinWeightSplit; fix64_6 mMinWeightSplitLow; static SpinLockedData gLockCOUT; // logging lock }; SpinLockedData JoinDiscoverer::gLockCOUT; size_t const JoinDiscoverer::MAX_AFFIX_LEN; // can this vertex be pulled apart? void JoinDiscoverer::processVertex( int vertexId, Recommendations* pRecs ) const { EdgeCollection const& leftAlts = mHBV.ToEdgeObj(vertexId); size_t nLeftAlts = leftAlts.size(); // only process nodes with some left-diversity to cut down on re-processing if ( nLeftAlts <= 1 ) return; EdgeCollection const& rightAlts = mHBV.FromEdgeObj(vertexId); size_t nRightAlts = rightAlts.size(); if ( !nRightAlts ) // if its a dead-end, skip it return; // get all distinct paths that lead to this vertex vec<SHBVPath> prefixes = findPrefixes(leftAlts); size_t nPrefixes = prefixes.size(); if ( nPrefixes <= 1 ) return; // get all distinct paths that lead from this vertex vec<SHBVPath> suffixes = findSuffixes(rightAlts); size_t nSuffixes = suffixes.size(); if ( nSuffixes <= 1 ) return; // get candidate pairs of "e" edges upstream of vertex vec<EdgePair> ePairs = getProperEdgePairs(prefixes); if ( ePairs.empty() ) return; // get candidate pairs of "f" edges downstream of vertex vec<EdgePair> fPairs = getProperEdgePairs(suffixes); if ( fPairs.empty() ) return; // for each of the valid pairs of e's and f's, find all the reads that // go from one of the e's to one of the f's, and accumulate the read weights EdgeCollection reach; for ( auto eItr=ePairs.begin(),eEnd=ePairs.end(); eItr != eEnd; ++eItr ) { EdgeId e1 = eItr->first, e2 = eItr->second; for ( auto fItr=fPairs.begin(),fEnd=fPairs.end(); fItr != fEnd; ++fItr ) { EdgeId f1 = fItr->first, f2 = fItr->second; if ( e1 == f1 || e1 == f2 || e2 == f1 || e2 == f2 ) continue; PathWeights pw1(mHBV,mPathsIndex[e1],e1,f1,f2); PathWeights pw2(mHBV,mPathsIndex[e2],e2,f1,f2); getReach(pw1,pw2,&reach); // make sure {e1,e2,f1,f2} bound a complete sub-graph if ( !checkReach(reach,e1,e2,f1,f2) ) continue; int span = std::max(pw1.mSpan,pw2.mSpan); if ( pullApart(pw1.weight1,pw1.weight2, pw2.weight1,pw2.weight2,span) ) { pRecs->addRecommendation(pw1.bridges1,pw2.bridges2,reach); if ( mVerbosity >= 2 ) log(e1,e2,f1,f2,reach,pw1.bridges1,pw2.bridges2, pw1.weight1,pw1.weight2,pw2.weight1,pw2.weight2, span,true); } else if ( pullApart(pw1.weight2,pw1.weight1, pw2.weight2,pw2.weight1,span) ) { pRecs->addRecommendation(pw1.bridges2,pw2.bridges1,reach); if ( mVerbosity >= 2 ) log(e1,e2,f2,f1,reach,pw1.bridges2,pw2.bridges1, pw1.weight2,pw1.weight1,pw2.weight2,pw2.weight1, span,true); } else if ( mVerbosity >= 3 && !pw1.bridges1.empty() && !pw2.bridges2.empty() ) { log(e1,e2,f1,f2,reach,pw1.bridges1,pw2.bridges2, pw1.weight1,pw1.weight2,pw2.weight1,pw2.weight2, span,false); } else if ( mVerbosity >= 3 && !pw1.bridges2.empty() && !pw2.bridges1.empty() ) { log(e1,e2,f2,f1,reach,pw1.bridges2,pw2.bridges1, pw1.weight2,pw1.weight1,pw2.weight2,pw2.weight1, span,false); } } } } // run the vertex scanning in parallel /*void findJoins( SupportedHyperBasevector const& hbv, vec<int> const& toLeft, vec<int> const& toRight, int verbosity, double minWeightSplit, Recommendations* pRecs ) { JoinDiscoverer jd(hbv,toLeft,toRight,verbosity,minWeightSplit); unsigned nThreads = getConfiguredNumThreads(); size_t nVertices = hbv.N(); size_t batchSize = ((nVertices+nThreads-1)/nThreads+9)/10; parallelForBatch(0ul,nVertices,batchSize, [jd,pRecs]( int vertexId ) { jd.processVertex(vertexId,pRecs); }, nThreads,verbosity==1); }*/ } // end of anonymous namespace /*void SupportedHyperBasevector::PullApart2( const double min_weight_split, const long_logging& logc ) { // Logging stuff. if (logc.STATUS_LOGGING) std::cout << Date() << ": starting PullApart2" << std::endl; int verbosity = logc.verb["PULL_APART2"]; double clock = WallClockTime(); // Iterate until no improvement. size_t iterationCount = 0; bool progress = true; while ( progress ) { progress = false; if ( verbosity ) std::cout << Date() << ": starting iteration " << ++iterationCount << std::endl; #if 0 if ( true ) { String dotName = "iteration"+ToString(iterationCount)+".dot"; std::ofstream out(dotName.c_str()); PrintSummaryDOT0w(out,false,false,true); out.close(); } #endif vec<int> to_left, to_right; ToLeft(to_left); ToRight(to_right); Recommendations recs; findJoins(*this,to_left,to_right,verbosity,min_weight_split,&recs); vec<SHBV_Join>& joins = recs.mJoins; if ( joins.empty() ) break; // Process joins. std::cout << Date() << ": process joins" << std::endl; vec<vec<SHBVPath>>& paths1 = recs.mPaths1; vec<vec<SHBVPath>>& paths2 = recs.mPaths2; ParallelSortSync(joins, paths1, paths2); if (logc.STATUS_LOGGING) { std::cout << Date() << ": processing " << joins.size() << " potential joins" << std::endl; } if ( verbosity >= 2 ) std::cout << "\n"; vec<Bool> touched(EdgeObjectCount(), False); for ( int i = 0; i < joins.isize(); i++ ) { Bool overlap = False; for ( int j = 0; j < joins[i].first.isize(); j++ ) if ( touched[joins[i].first[j]] ) overlap = True; for ( int j = 0; j < joins[i].second.isize(); j++ ) if ( touched[joins[i].second[j]] ) overlap = True; for ( int j = 0; j < joins[i].third.isize(); j++ ) if ( touched[joins[i].third[j]] ) overlap = True; if ( overlap ) continue; vec<triple<vec<int>, vec<int>, vec<int> > > proc; vec<vec<vec<int> > > proc1, proc2; proc.push_back(joins[i]); proc1.push_back(paths1[i]), proc2.push_back(paths2[i]); if ( Inv(joins[i].first[0]) >= 0 ) { vec<int> a, b, c; a.push_back(Inv(joins[i].third[0]), Inv(joins[i].third[1])); for ( int j = 0; j < joins[i].second.isize(); j++ ) b.push_back(Inv(joins[i].second[j])); Sort(b); c.push_back(Inv(joins[i].first[0]), Inv(joins[i].first[1])); vec<int> all1, all2; all1.append(joins[i].first); all1.append(joins[i].second); all1.append(joins[i].third); all2.append(a), all2.append(b), all2.append(c); Sort(all1), Sort(all2); if ( Meet(all1, all2) ) continue; for ( int j = 0; j < all2.isize(); j++ ) if ( touched[all2[j]] ) overlap = True; if ( overlap ) continue; proc.push(a, b, c); vec<vec<int> > p1 = paths1[i], p2 = paths2[i]; for ( int j = 0; j < p1.isize(); j++ ) { p1[j].ReverseMe(); for ( int l = 0; l < p1[j].isize(); l++ ) p1[j][l] = Inv(p1[j][l]); } for ( int j = 0; j < p2.isize(); j++ ) { p2[j].ReverseMe(); for ( int l = 0; l < p2[j].isize(); l++ ) p2[j][l] = Inv(p2[j][l]); } proc1.push_back(p1), proc2.push_back(p2); } vec<fix64_6> weight(EdgeObjectCount(), 0); for ( int i = 0; i < NPaths(); i++ ) for ( int j = 0; j < Path(i).isize(); j++ ) weight[Path(i)[j]] += Weight(i); vec<int> count(2, 0); for ( int p = 0; p < proc.isize(); p++ ) { if ( verbosity >= 2 ) { int e1 = proc[p].first[0], e2 = proc[p].first[1]; int f1 = proc[p].third[0], f2 = proc[p].third[1]; std::cout << "joining: "; PRINT4(e1, e2, f1, f2); } for ( int j = 0; j < proc[p].first.isize(); j++ ) touched[proc[p].first[j]] = True; for ( int j = 0; j < proc[p].second.isize(); j++ ) touched[proc[p].second[j]] = True; for ( int j = 0; j < proc[p].third.isize(); j++ ) touched[proc[p].third[j]] = True; vec<int> dels; dels.append(proc[p].first); dels.append(proc[p].second); dels.append(proc[p].third); const int max_del_weight = 4; Bool bad = False; for ( int i = 0; i < dels.isize(); i++ ) { Bool used = False; for ( int j = 0; j < proc1[p].isize(); j++ ) if ( Member(proc1[p][j], dels[i]) ) used = True; for ( int j = 0; j < proc2[p].isize(); j++ ) if ( Member(proc2[p][j], dels[i]) ) used = True; if ( used ) continue; if ( weight[dels[i]] > max_del_weight ) bad = True; } if ( bad ) { if ( verbosity >= 2 ) std::cout << "aborting join" << std::endl; continue; } progress = true; int v1 = to_left[proc[p].first[0]]; int v2 = to_left[proc[p].first[1]]; int w1 = to_right[proc[p].third[0]]; int w2 = to_right[proc[p].third[1]]; vec<vec<int> > e(proc1[p]); e.append(proc2[p]); vec<int> f; for ( int j = 0; j < proc1[p].isize(); j++ ) { f.push_back(EdgeObjectCount()); int rid = -1; if ( p == 1 ) rid = EdgeObjectCount() - count[0]; InvMutable().push_back(rid); if ( p == 1 ) { InvMutable(EdgeObjectCount() - count[0]) = EdgeObjectCount(); } AddEdge(v1, w1, Cat(proc1[p][j])); count[p]++; } for ( int j = 0; j < proc2[p].isize(); j++ ) { f.push_back(EdgeObjectCount()); int rid = -1; if ( p == 1 ) rid = EdgeObjectCount() - count[0]; InvMutable().push_back(rid); if ( p == 1 ) { InvMutable(EdgeObjectCount() - count[0]) = EdgeObjectCount(); } AddEdge(v2, w2, Cat(proc2[p][j])); count[p]++; } DeleteEdges(dels); TransformPaths(e, f); } } if ( verbosity >= 2 ) std::cout << "\n"; // Clean up. std::cout << Date() << ": clean up" << std::endl; UniqueOrderPaths(); RemoveEdgelessVertices(); REPORT_TIME( clock, "used in PullApart2"); RemoveDeadEdgeObjects(); RemovePathsWithoutReverseComplements(); RemovePairsWithoutReverseComplements(); FixWeights(logc); TestValid(logc); DeleteReverseComplementComponents(logc); } }*/ void SupportedHyperBasevector::Gulp( const long_logging_control& log_control, const long_logging& logc ) { double clock1 = WallClockTime( ); if (logc.STATUS_LOGGING) std::cout << Date( ) << ": gulping edges" << std::endl; vec<int> to_left, to_right; ToLeft(to_left), ToRight(to_right); vec< vec< std::pair<int,int> > > paths_index( EdgeObjectCount( ) ); for (int i = 0; i < Paths( ).isize(); i++) for (int j = 0; j < Path(i).isize(); j++) paths_index[ Path(i,j) ].push(i, j); const int max_gulp = 20; while(1) { if ( logc.verb[ "GULP" ] >= 1 ) std::cout << Date( ) << ": starting gulp iteration" << std::endl; Bool changed = False; for ( int v = 0; v < N( ); v++ ) { vec<int> dels, rdels, out, rout; vec< vec<int> > in(2), rin(2); if ( To(v).size( ) == 1 && From(v).size( ) == 2 ) { int u = To(v)[0], w1 = From(v)[0], w2 = From(v)[1]; int e = EdgeObjectIndexByIndexTo( v, 0 ); if ( EdgeLengthKmers(e) > max_gulp ) continue; int f1 = EdgeObjectIndexByIndexFrom( v, 0 ); int f2 = EdgeObjectIndexByIndexFrom( v, 1 ); // u --e--> v --f1,f2--> w1,w2 dels.push_back( e, f1, f2 ); int re = Inv(e), rf1 = Inv(f1), rf2 = Inv(f2); rdels.push_back( re, rf1, rf2 ); UniqueSort(dels), UniqueSort(rdels); if ( dels.size( ) != 3 ) continue; if ( InvDef(e) && Meet( dels, rdels ) ) continue; int ef1 = EdgeObjectCount( ), ef2 = EdgeObjectCount( ) + 1; changed = True; AddEdge( u, w1, Cat(e,f1) ), AddEdge( u, w2, Cat(e,f2) ); DeleteEdges(dels); in[0].push_back(e, f1), in[1].push_back(e, f2); out.push_back( ef1, ef2 ); TransformPaths( in, out /*, paths_index */ ); to_left.push_back(u, u), to_right.push_back(w1, w2); if ( !InvDef(e) ) InvMutable( ).push_back( -1, -1 ); else { int rf1e = EdgeObjectCount( ); int rf2e = EdgeObjectCount( ) + 1; int ru = to_right[re]; int rw1 = to_left[rf1], rw2 = to_left[rf2]; AddEdge( rw1, ru, Cat(rf1,re) ); AddEdge( rw2, ru, Cat(rf2,re) ); DeleteEdges(rdels); in[0].clear( ), in[1].clear( ), out.clear( ); in[0].push_back(rf1, re), in[1].push_back(rf2, re); out.push_back( rf1e, rf2e ); TransformPaths( in, out /*, paths_index */ ); to_left.push_back(rw1, rw2), to_right.push_back(ru, ru); InvMutable( ).push_back( rf1e, rf2e, ef1, ef2 ); } } if ( To(v).size( ) == 2 & From(v).size( ) == 1 ) { int u1 = To(v)[0], u2 = To(v)[1], w = From(v)[0]; int e1 = EdgeObjectIndexByIndexTo( v, 0 ); int e2 = EdgeObjectIndexByIndexTo( v, 1 ); int f = EdgeObjectIndexByIndexFrom( v, 0 ); if ( EdgeLengthKmers(f) > max_gulp ) continue; // u1,u2 --e1,e2--> v --f--> w dels.push_back( e1, e2, f ); int re1 = Inv(e1), re2 = Inv(e2), rf = Inv(f); rdels.push_back( re1, re2, rf ); UniqueSort(dels), UniqueSort(rdels); if ( dels.size( ) != 3 ) continue; if ( InvDef(f) && Meet( dels, rdels ) ) continue; int e1f = EdgeObjectCount( ), e2f = EdgeObjectCount( ) + 1; changed = True; AddEdge( u1, w, Cat(e1,f) ), AddEdge( u2, w, Cat(e2,f) ); DeleteEdges(dels); in[0].push_back(e1, f), in[1].push_back(e2, f); out.push_back( e1f, e2f ); TransformPaths( in, out /*, paths_index */ ); to_left.push_back(u1, u2), to_right.push_back(w, w); if ( !InvDef(f) ) InvMutable( ).push_back( -1, -1 ); else { int rfe1 = EdgeObjectCount( ); int rfe2 = EdgeObjectCount( ) + 1; DeleteEdges(rdels); int ru1 = to_right[re1], ru2 = to_right[re2]; int rw = to_left[rf]; AddEdge( rw, ru1, Cat(rf,re1) ); AddEdge( rw, ru2, Cat(rf,re2) ); in[0].clear( ), in[1].clear( ), out.clear( ); in[0].push_back(rf, re1), in[1].push_back(rf, re2); out.push_back( rfe1, rfe2 ); TransformPaths( in, out /*, paths_index */ ); to_left.push_back(rw, rw), to_right.push_back(ru1, ru2); InvMutable( ).push_back( rfe1, rfe2, e1f, e2f ); } } } if ( !changed ) break; } UniqueOrderPaths( ); RemoveEdgelessVertices( ); REPORT_TIME( clock1, "used in gulping 1" ); RemoveDeadEdgeObjects( ); FixWeights(logc); if (logc.STATUS_LOGGING) { std::cout << Date( ) << ": after gulping edges there are " << EdgeObjectCount( ) << " edges" << std::endl; } TestValid(logc); } void SupportedHyperBasevector::Ungulp( const long_logging& logc ) { double clock = WallClockTime( ); if (logc.STATUS_LOGGING) std::cout << Date( ) << ": ungulping edges" << std::endl; const int max_gulp = 20; vec<int> to_left, to_right; ToLeft(to_left), ToRight(to_right); int nv = N( ); vec<int> ins; vec< vec<int> > outs; for ( int v = 0; v < nv; v++ ) { if ( From(v).size( ) != 2 ) continue; int w1 = From(v)[0], w2 = From(v)[1]; if ( w1 == v || w2 == v ) continue; int e1 = EdgeObjectIndexByIndexFrom( v, 0 ); int e2 = EdgeObjectIndexByIndexFrom( v, 1 ); const basevector &E1 = EdgeObject(e1), &E2 = EdgeObject(e2); int re1 = Inv(e1), re2 = Inv(e2); int rv, rw1, rw2; if ( re1 >= 0 ) { rv = to_right[re1], rw1 = to_left[re1], rw2 = to_left[re2]; vec<int> alle; alle.push_back( e1, e2, re1, re2 ); UniqueSort(alle); if ( alle.size( ) != 4 ) continue; vec<int> vert1( {v,w1,w2} ), vert2( {rv,rw1,rw2} ); UniqueSort(vert1), UniqueSort(vert2); if ( Meet( vert1, vert2 ) ) continue; } int n; for ( n = 0; n < Min( E1.isize( ), E2.isize( ) ); n++ ) if ( E1[n] != E2[n] ) break; if ( n == E1.isize( ) || n == E2.isize( ) ) n--; if ( n < K( ) + max_gulp - 1 ) continue; // PRINT4( v, E1.size( ), E2.size( ), n ); // XXXXXXXXXXXXXXXXXXXXXXXXXXXXX basevector c( E1, 0, n ); basevector f1( E1, n - K( ) + 1, E1.isize( ) - ( n - K( ) + 1 ) ); basevector f2( E2, n - K( ) + 1, E2.isize( ) - ( n - K( ) + 1 ) ); // PRINT2( f1.size( ), f2.size( ) ); // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // e1 = f1, e2 = f2; int x = N( ); // PRINT(x); // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX vec<int> us = {0,1}; DeleteEdgesFrom( v, us ); AddVertices(1); AddEdge( v, x, c ); to_left.push_back(v), to_right.push_back(x); AddEdge( x, w1, f1 ); to_left.push_back(x), to_right.push_back(w1); AddEdge( x, w2, f2 ); to_left.push_back(x), to_right.push_back(w2); ins.push_back( e1, e2 ); { int N = EdgeObjectCount( ); outs.push_back( {N-3,N-2} ); outs.push_back( {N-3,N-1} ); } // HyperBasevector::TestValid( ); // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX if ( re1 < 0 ) InvMutable( ).push_back( -1, -1, -1 ); else { basevector rc(c), rf1(f1), rf2(f2); rc.ReverseComplement( ); rf1.ReverseComplement( ), rf2.ReverseComplement( ); int rx = N( ); DeleteEdgesTo( rv, us ); AddVertices(1); AddEdge( rx, rv, rc ); to_left.push_back(rx), to_right.push_back(rv); AddEdge( rw1, rx, rf1 ); to_left.push_back(rw1), to_right.push_back(rx); AddEdge( rw2, rx, rf2 ); to_left.push_back(rw2), to_right.push_back(rx); int N = EdgeObjectCount( ); InvMutable( ).push_back( N-3, N-2, N-1, N-6, N-5, N-4 ); ins.push_back( re1, re2 ); outs.push_back( {N-1,N-3} ); outs.push_back( {N-2,N-3} ); // HyperBasevector::TestValid( ); // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX } } for ( int w = 0; w < nv; w++ ) { if ( To(w).size( ) != 2 ) continue; int v1 = To(w)[0], v2 = To(w)[1]; if ( v1 == w || v2 == w ) continue; int e1 = EdgeObjectIndexByIndexTo( w, 0 ); if ( InvDef(e1) ) continue; int e2 = EdgeObjectIndexByIndexTo( w, 1 ); const basevector &E1 = EdgeObject(e1), &E2 = EdgeObject(e2); int n1 = E1.size( ), n2 = E2.size( ); int n; for ( n = 0; n < Min( E1.isize( ), E2.isize( ) ); n++ ) if ( E1[ n1 - n - 1 ] != E2[ n2 - n - 1 ] ) break; if ( n == E1.isize( ) || n == E2.isize( ) ) n--; if ( n < K( ) + max_gulp - 1 ) continue; // PRINT4( w, E1.size( ), E2.size( ), n ); // XXXXXXXXXXXXXXXXXXXXXXXXXXXXX basevector c( E1, n1 - n, n ); basevector f1( E1, 0, n1 - n + K( ) - 1 ); basevector f2( E2, 0, n2 - n + K( ) - 1 ); // PRINT2( f1.size( ), f2.size( ) ); // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX int x = N( ); // PRINT(x); // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX vec<int> us; us.push_back( 0, 1 ); DeleteEdgesTo( w, us ); AddVertices(1); AddEdge( x, w, c ); AddEdge( v1, x, f1 ); AddEdge( v2, x, f2 ); int N = EdgeObjectCount( ); ins.push_back(e1, e2); outs.push_back( {N-1,N-3} ); outs.push_back( {N-2,N-3} ); InvMutable( ).push_back( -1, -1, -1 ); // HyperBasevector::TestValid( ); // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX } SortSync( ins, outs ); for ( int i = 0; i < NPaths( ); i++ ) for ( int j = 0; j < Path(i).isize( ); j++ ) { int z = BinPosition( ins, Path(i)[j] ); if ( z < 0 ) continue; vec<int> p; for ( int k = 0; k < j; k++ ) p.push_back( Path(i)[k] ); p.append( outs[z] ); for ( int k = j + 1; k < Path(i).isize( ); k++ ) p.push_back( Path(i)[k] ); } // Note not fixing pairs. // TestValid( logc, False ); // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX REPORT_TIME( clock, "used in ungulping" ); RemoveUnneededVertices( ); RemoveDeadEdgeObjects( ); if (logc.STATUS_LOGGING) { std::cout << Date( ) << ": after ungulping there are " << EdgeObjectCount( ) << " edges" << std::endl; } TestValid(logc); } void SupportedHyperBasevector::TrimHangingEnds( const int max_del, const double junk_ratio, const long_heuristics& heur, const long_logging& logc ) { double xclock = WallClockTime( ); if (logc.STATUS_LOGGING) { std::cout << Date( ) << ": see " << EdgeObjectCount( ) << " edges, removing hanging ends" << std::endl; } vec<kmer_count> kc( EdgeObjectCount( ) ); for ( int e = 0; e < EdgeObjectCount( ); e++ ) kc[e].n = EdgeObject(e).isize( ) - K( ) + 1; digraphE<kmer_count> shb_kc( *this, kc ); REPORT_TIME( xclock, "used removing hanging ends head" ); double pclock = WallClockTime( ); const int max_paths = 100; RemoveHangingEnds3( shb_kc, &kmer_count::N, max_del, junk_ratio, max_paths ); REPORT_TIME( pclock, "used removing hanging ends" ); double q1clock = WallClockTime( ); vec<int> e_to_delete; vec<Bool> used; shb_kc.Used(used); for ( int e = 0; e < EdgeObjectCount( ); e++ ) { if ( !used[e] ) { e_to_delete.push_back(e); if ( Inv(e) >= 0 && used[ Inv(e) ] ) e_to_delete.push_back( Inv(e) ); } } if ( logc.verb[ "TRIM" ] >= 1 ) { std::cout << "\nTrimHangingEnds, deleting edges " << printSeq(e_to_delete) << std::endl; } DeleteEdges(e_to_delete); REPORT_TIME( q1clock, "used removing hanging ends tail 1" ); TruncatePaths(logc); if ( heur.EXTRA_STEPS ) { double rclock = WallClockTime( ); RemoveUnneededVertices( ); REPORT_TIME( rclock, "using rh tail 2" ); } RemoveUnneededVertices( ); RemoveDeadEdgeObjects( ); FixWeights(logc); TestValid(logc); // Remove terminal loops of length <= 50 kmers. double rclock2 = WallClockTime( ); vec<int> ldels; const int maxl = 50; for ( int v = 0; v < N( ); v++ ) { if ( To(v).size( ) != 2 || From(v).size( ) != 1 ) continue; if ( From(v)[0] != v ) continue; int e = EdgeObjectIndexByIndexFrom( v, 0 ); if ( EdgeLengthKmers(e) > maxl ) continue; ldels.push_back(e); } for ( int v = 0; v < N( ); v++ ) { if ( From(v).size( ) != 2 || To(v).size( ) != 1 ) continue; if ( To(v)[0] != v ) continue; int e = EdgeObjectIndexByIndexTo( v, 0 ); if ( EdgeLengthKmers(e) > maxl ) continue; ldels.push_back(e); } DeleteEdges(ldels); TruncatePaths(logc); REPORT_TIME( rclock2, "used removing hanging ends tail 2" ); RemoveDeadEdgeObjects( ); FixWeights(logc); TestValid(logc); } void SupportedHyperBasevector::DeleteLowCoverage( const long_heuristics& heur, const long_logging_control& log_control, const long_logging& logc ) { double mclock = WallClockTime( ); vec<int> to_left, to_right, to_delete; ToLeft(to_left), ToRight(to_right); const double low_cov = 2.0; vec<fix64_6> cov( EdgeObjectCount( ), 0.0 ); for ( int i = 0; i < NPaths( ); i++ ) { for ( int j = 0; j < Path(i).isize( ); j++ ) cov[ Path(i)[j] ] += Weight(i); } const double pceil = 0.99; const double minp = 0.0001; vec< vec<fix64_6> > weights( EdgeObjectCount( ) ); vec< triple<int64_t,int,fix64_6> > wid; vec<double> p( EdgeObjectCount( ), 1.0 ); if ( heur.NEW_LC_FILT ) { for ( int i = 0; i < NPaths( ); i++ ) { for ( int k = 0; k < WeightFwOrigin(i).isize( ); k++ ) { wid.push( WeightFwOrigin(i)[k].second, i, WeightFwOrigin(i)[k].first ); } for ( int k = 0; k < WeightRcOrigin(i).isize( ); k++ ) { wid.push( WeightRcOrigin(i)[k].second, i, WeightRcOrigin(i)[k].first ); } } ParallelSort(wid); for ( int64_t i = 0; i < wid.jsize( ); i++ ) { int64_t j; for ( j = i + 1; j < wid.jsize( ); j++ ) if ( wid[j].first != wid[i].first ) break; vec< std::pair<int,fix64_6> > w; for ( int64_t k = i; k < j; k++ ) { vec<int> p = Path( wid[k].second ); UniqueSort(p); for ( int l = 0; l < p.isize( ); l++ ) w.push( p[l], wid[k].third ); } Sort(w); for ( int r = 0; r < w.isize( ); r++ ) { int s; for ( s = r + 1; s < w.isize( ); s++ ) if ( w[s].first != w[r].first ) break; fix64_6 x = 0; for ( int t = r; t < s; t++ ) x += w[t].second; weights[ w[r].first ].push_back(x); r = s - 1; } i = j - 1; } for ( int e = 0; e < EdgeObjectCount( ); e++ ) { Sort( weights[e] ); for ( int j = 0; j < weights[e].isize( ); j++ ) { if ( p[e] < minp ) break; p[e] *= 1.0 - Min( pceil, weights[e][j].ToDouble( ) ); } } } const int min_mult = 5; for ( int e = 0; e < EdgeObjectCount( ); e++ ) { int re = Inv(e), v = to_left[e], w = to_right[e]; fix64_6 c = cov[e]; fix64_6 rc = ( re < 0 ? 1000000000 : cov[re] ); fix64_6 alt_c = 0, alt_rc = 0; for ( int j = 0; j < From(v).isize( ); j++ ) alt_c = Max( alt_c, cov[ EdgeObjectIndexByIndexFrom( v, j ) ] ); for ( int j = 0; j < To(w).isize( ); j++ ) alt_c = Max( alt_c, cov[ EdgeObjectIndexByIndexTo( w, j ) ] ); if ( re >= 0 ) { int v = to_left[re], w = to_right[re]; for ( int j = 0; j < From(v).isize( ); j++ ) { alt_rc = Max( alt_rc, cov[ EdgeObjectIndexByIndexFrom( v, j ) ] ); } for ( int j = 0; j < To(w).isize( ); j++ ) { alt_rc = Max( alt_rc, cov[ EdgeObjectIndexByIndexTo( w, j ) ] ); } } if ( heur.NEW_LC_FILT ) { if ( ( ( c <= low_cov || p[e] >= minp ) && alt_c >= min_mult * c ) || ( ( rc <= low_cov || ( re >= 0 && p[re] >= minp ) ) && alt_rc >= min_mult * rc ) ) { if ( logc.verb[ "LOW_COV" ] >= 1 ) { std::cout << "deleting low-coverage edge " << e << " (c = " << c << ", alt_c = " << alt_c << ", p[e] = " << p[e] << ")" << std::endl; } to_delete.push_back(e); } } else { if ( heur.LC_CAREFUL && alt_c < low_cov ) continue; if ( ( c <= low_cov && alt_c >= min_mult * c ) || ( rc <= low_cov && alt_rc >= min_mult * rc ) ) { if ( logc.verb[ "LOW_COV" ] >= 1 ) { vec<int> comp; for ( int j = 0; j < From(v).isize( ); j++ ) { int e = EdgeObjectIndexByIndexFrom( v, j ); if ( cov[e] == alt_c ) comp.push_back(e); } for ( int j = 0; j < To(w).isize( ); j++ ) { int e = EdgeObjectIndexByIndexTo( w, j ); if ( cov[e] == alt_c ) comp.push_back(e); } UniqueSort(comp); std::cout << "deleting low-coverage edge " << e << " using competing edge(s) " << printSeq(comp) << ", c = " << c << ", alt_c = " << alt_c << std::endl; } to_delete.push_back(e); } } } DeleteEdges(to_delete); vec<Bool> p_to_delete( NPaths( ), False ); for ( int i = 0; i < NPaths( ); i++ ) { Bool OK = True; for ( int j = 0; j < Path(i).isize( ); j++ ) if ( BinMember( to_delete, Path(i)[j] ) ) OK = False; if ( !OK ) p_to_delete[i] = True; } EraseIf( PathsMutable( ), p_to_delete ); // Temporary if. if ( WeightsFwOrigin( ).size( ) == WeightsFw( ).size( ) ) { EraseIf( WeightsFwOriginMutable( ), p_to_delete ); EraseIf( WeightsRcOriginMutable( ), p_to_delete ); } EraseIf( WeightsFwMutable( ), p_to_delete ); EraseIf( WeightsRcMutable( ), p_to_delete ); p_to_delete.resize_and_set( NPairs( ), False ); for ( int i = 0; i < NPairs( ); i++ ) { Bool OK = True; for ( int j = 0; j < PairLeft(i).isize( ); j++ ) if ( BinMember( to_delete, PairLeft(i)[j] ) ) OK = False; if ( !OK ) p_to_delete[i] = True; for ( int j = 0; j < PairRight(i).isize( ); j++ ) if ( BinMember( to_delete, PairRight(i)[j] ) ) OK = False; if ( !OK ) p_to_delete[i] = True; } EraseIf( PairsMutable( ), p_to_delete ); EraseIf( PairDataMutable( ), p_to_delete ); RemoveEdgelessVertices( ); RemoveUnneededVertices( ); REPORT_TIME( mclock, "used deleting low-coverage edges" ); RemoveDeadEdgeObjects( ); }
43.071995
91
0.494119
Amjadhpc
1172cce167b95ca9b05e836c5abee13c484c6b3d
110,612
cpp
C++
groups/bal/ball/ball_fileobserver.t.cpp
hughesr/bde
d593e3213918b9292c25e08cfc5b6651bacdea0d
[ "Apache-2.0" ]
1
2019-01-22T19:44:05.000Z
2019-01-22T19:44:05.000Z
groups/bal/ball/ball_fileobserver.t.cpp
anuranrc/bde
d593e3213918b9292c25e08cfc5b6651bacdea0d
[ "Apache-2.0" ]
null
null
null
groups/bal/ball/ball_fileobserver.t.cpp
anuranrc/bde
d593e3213918b9292c25e08cfc5b6651bacdea0d
[ "Apache-2.0" ]
null
null
null
// ball_fileobserver.t.cpp -*-C++-*- // ---------------------------------------------------------------------------- // NOTICE // // This component is not up to date with current BDE coding standards, and // should not be used as an example for new development. // ---------------------------------------------------------------------------- #include <ball_fileobserver.h> #include <ball_context.h> #include <ball_defaultobserver.h> // for testing only #include <ball_log.h> // for testing only #include <ball_loggermanager.h> // for testing only #include <ball_loggermanagerconfiguration.h> // for testing only #include <ball_multiplexobserver.h> // for testing only #include <ball_recordattributes.h> #include <ball_severity.h> #include <bslim_testutil.h> #include <bslma_defaultallocatorguard.h> #include <bslma_testallocator.h> #include <bdlb_tokenizer.h> #include <bdlt_currenttime.h> #include <bdlt_date.h> #include <bdlt_datetime.h> #include <bdlt_datetimeutil.h> #include <bdlt_epochutil.h> #include <bdlt_localtimeoffset.h> #include <bdls_filesystemutil.h> #include <bdls_processutil.h> #include <bslmt_threadutil.h> #include <bslstl_stringref.h> #include <bsls_assert.h> #include <bsls_platform.h> #include <bsls_timeinterval.h> #include <bsl_climits.h> #include <bsl_cstdio.h> // 'remove' #include <bsl_cstdlib.h> #include <bsl_cstring.h> #include <bsl_ctime.h> #include <bsl_iomanip.h> #include <bsl_iostream.h> #include <bsl_sstream.h> #include <bsl_c_stdio.h> // 'tempname' #include <bsl_c_stdlib.h> // 'unsetenv' #include <sys/types.h> #include <sys/stat.h> #ifdef BSLS_PLATFORM_OS_UNIX #include <glob.h> #include <bsl_c_signal.h> #include <sys/resource.h> #include <bsl_c_time.h> #include <unistd.h> #endif #ifdef BSLS_PLATFORM_OS_WINDOWS #include <windows.h> #endif // Note: on Windows -> WinGDI.h:#define ERROR 0 #if defined(BSLS_PLATFORM_CMP_MSVC) && defined(ERROR) #undef ERROR #endif using namespace BloombergLP; using bsl::cout; using bsl::cerr; using bsl::endl; using bsl::flush; //============================================================================= // TEST PLAN //----------------------------------------------------------------------------- // CREATORS // [ 1] ball::FileObserver(ball::Severity::Level, bslma::Allocator) // [ 1] ~ball::FileObserver() // // MANIPULATORS // [ 1] publish(const ball::Record& record, const ball::Context& context) // [ 1] void disableFileLogging() // [ 2] void disableLifetimeRotation() // [ 2] void disableSizeRotation() // [ 1] void disableStdoutLoggingPrefix() // [ 1] void disableUserFieldsLogging() // [ 1] int enableFileLogging(const char *fileName, bool timestampFlag = false) // [ 1] void enableStdoutLoggingPrefix() // [ 1] void enableUserFieldsLogging() // [ 1] void publish(const ball::Record& record, const ball::Context& context) // [ 2] void forceRotation() // [ 2] void rotateOnSize(int size) // [ 2] void rotateOnLifetime(bdlt::DatetimeInterval timeInterval) // [ 1] void setStdoutThreshold(ball::Severity::Level stdoutThreshold) // [ 1] void setLogFormat(const char*, const char*) // [ 3] void setMaxLogFiles(); // [ 3] int removeExcessLogFiles(); // // ACCESSORS // [ 1] bool isFileLoggingEnabled() const // [ 1] bool isStdoutLoggingPrefixEnabled() const // [ 1] bool isUserFieldsLoggingEnabled() const // [ 1] void getLogFormat(const char**, const char**) const // [ 2] bdlt::DatetimeInterval rotationLifetime() const // [ 2] int rotationSize() const // [ 1] ball::Severity::Level stdoutThreshold() const // [ 3] int maxLogFiles() const; //----------------------------------------------------------------------------- //============================================================================= // STANDARD BDE ASSERT TEST MACROS //----------------------------------------------------------------------------- // Note assert and debug macros all output to cerr instead of cout, unlike // most other test drivers. This is necessary because test case 1 plays // tricks with cout and examines what is written there. namespace { int testStatus = 0; void aSsErT(bool condition, const char *message, int line) { if (condition) { cerr << "Error " __FILE__ "(" << line << "): " << message << " (failed)" << endl; if (0 <= testStatus && testStatus <= 100) { ++testStatus; } } } void aSsErT2(bool condition, const char *message, int line) { if (condition) { cout << "Error " __FILE__ "(" << line << "): " << message << " (failed)" << endl; if (0 <= testStatus && testStatus <= 100) { ++testStatus; } } } } // close unnamed namespace #define ASSERT2(X) { aSsErT2(!(X), #X, __LINE__); } // ============================================================================ // STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BSLIM_TESTUTIL_ASSERT #define ASSERTV BSLIM_TESTUTIL_ASSERTV #define LOOP_ASSERT BSLIM_TESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT #define Q BSLIM_TESTUTIL_Q // Quote identifier literally. #define P BSLIM_TESTUTIL_P // Print identifier and value. #define P_ BSLIM_TESTUTIL_P_ // P(X) without '\n'. #define T_ BSLIM_TESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLIM_TESTUTIL_L_ // current Line number // ============================================================================ // NEGATIVE-TEST MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR) #define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR) #define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR) #define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR) #define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR) #define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR) //============================================================================= // GLOBAL TYPES, CONSTANTS, AND VARIABLES FOR TESTING //----------------------------------------------------------------------------- static int verbose = 0; static int veryVerbose = 0; static int veryVeryVerbose = 0; static int veryVeryVeryVerbose = 0; typedef ball::FileObserver Obj; typedef bdls::FilesystemUtil FileUtil; //============================================================================= // GLOBAL HELPER FUNCTIONS FOR TESTING //----------------------------------------------------------------------------- namespace { bsl::string::size_type replaceSecondSpace(bsl::string *s, char value) // Replace the second space character (' ') in the specified 'string' with // the specified 'value'. Return the index position of the character that // was replaced on success, and 'bsl::string::npos' otherwise. { bsl::string::size_type index = s->find(' '); if (bsl::string::npos != index) { index = s->find(' ', index + 1); if (bsl::string::npos != index) { (*s)[index] = value; } } return index; } bdlt::Datetime getCurrentTimestamp() { time_t currentTime = time(0); struct tm localtm; #ifdef BSLS_PLATFORM_OS_WINDOWS localtm = *localtime(&currentTime); #else localtime_r(&currentTime, &localtm); #endif bdlt::Datetime stamp; bdlt::DatetimeUtil::convertFromTm(&stamp, localtm); return stamp; } void removeFilesByPrefix(const char *prefix) { #ifdef BSLS_PLATFORM_OS_WINDOWS bsl::string filename = prefix; filename += "*"; WIN32_FIND_DATA findFileData; bsl::vector<bsl::string> fileNames; HANDLE hFind = FindFirstFile(filename.c_str(), &findFileData); if (hFind != INVALID_HANDLE_VALUE) { fileNames.push_back(findFileData.cFileName); while (FindNextFile(hFind, &findFileData)) { fileNames.push_back(findFileData.cFileName); } FindClose(hFind); } char tmpPathBuf[MAX_PATH]; GetTempPath(MAX_PATH, tmpPathBuf); bsl::string tmpPath(tmpPathBuf); bsl::vector<bsl::string>::iterator itr; for (itr = fileNames.begin(); itr != fileNames.end(); ++itr) { bsl::string fn = tmpPath + (*itr); if (!DeleteFile(fn.c_str())) { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL); cerr << "Error, " << (char*)lpMsgBuf << endl; LocalFree(lpMsgBuf); } } #else glob_t globbuf; bsl::string filename = prefix; filename += "*"; glob(filename.c_str(), 0, 0, &globbuf); for (int i = 0; i < (int)globbuf.gl_pathc; i++) unlink(globbuf.gl_pathv[i]); globfree(&globbuf); #endif } bsl::string tempFileName(bool verboseFlag) { bsl::string result; #ifdef BSLS_PLATFORM_OS_WINDOWS char tmpPathBuf[MAX_PATH], tmpNameBuf[MAX_PATH]; GetTempPath(MAX_PATH, tmpPathBuf); GetTempFileName(tmpPathBuf, "ball", 0, tmpNameBuf); result = tmpNameBuf; #elif defined(BSLS_PLATFORM_OS_HPUX) char tmpPathBuf[L_tmpnam]; result = tempnam(tmpPathBuf, "ball"); #else char *fn = tempnam(0, "ball"); result = fn; bsl::free(fn); #endif if (verboseFlag) cout << "\tUse " << result << " as a base filename." << endl; // Test Invariant: BSLS_ASSERT(!result.empty()); return result; } bsl::string readPartialFile(bsl::string& fileName, FileUtil::Offset startOffset) // Read everything after the specified 'startOffset' from the file // indicated by the specified 'fileName' and return it as a string. { bsl::string result; result.reserve(FileUtil::getFileSize(fileName) + 1 - startOffset); FILE *fp = fopen(fileName.c_str(), "r"); BSLS_ASSERT_OPT(fp); BSLS_ASSERT_OPT(0 == fseek(fp, startOffset, SEEK_SET)); int c; while (EOF != (c = getc(fp))) { result += (char) c; } fclose(fp); return result; } void publishRecord(Obj *mX, const char *message) { ball::RecordAttributes attr(bdlt::CurrentTime::utc(), 1, 2, "FILENAME", 3, "CATEGORY", 32, message); ball::Record record(attr, ball::UserFields()); ball::Context context(ball::Transmission::e_PASSTHROUGH, 0, 1); mX->publish(record, context); } class LogRotationCallbackTester { // This class can be used as a functor matching the signature of // 'ball::FileObserver2::OnFileRotationCallback'. This class records every // invocation of the function-call operator, and is intended to test // whether 'ball::FileObserver2' calls the log-rotation callback // appropriately. // PRIVATE TYPES struct Rep { int d_invocations; int d_status; bsl::string d_rotatedFileName; explicit Rep(bslma::Allocator *allocator) : d_invocations(0) , d_status(0) , d_rotatedFileName(allocator) { } private: // NOT IMPLEMENTED Rep(const Rep&); Rep& operator=(const Rep&); }; // DATA bsl::shared_ptr<Rep> d_rep; public: // PUBLIC CONSTANTS enum { UNINITIALIZED = INT_MIN }; explicit LogRotationCallbackTester(bslma::Allocator *allocator) // Create a callback tester that will use the specified 'status' and // 'logFileName' to record the arguments to the function call // operator. Set '*status' to 'UNINITIALIZED' and set '*logFileName' // to the empty string. : d_rep() { d_rep.createInplace(allocator, allocator); reset(); } void operator()(int status, const bsl::string& rotatedFileName) // Set the value at the status address supplied at construction to the // specified 'status', and set the value at the log file name address // supplied at construction to the specified 'logFileName'. { ++d_rep->d_invocations; d_rep->d_status = status; d_rep->d_rotatedFileName = rotatedFileName; } void reset() // Set '*status' to 'UNINITIALIZED' and set '*logFileName' to the // empty string. { d_rep->d_invocations = 0; d_rep->d_status = UNINITIALIZED; d_rep->d_rotatedFileName = ""; } // ACCESSORS int numInvocations() const { return d_rep->d_invocations; } // Return the number of times that the function-call operator has been // invoked since the most recent call to 'reset', or if 'reset' has // not been called, since this objects construction. int status() const { return d_rep->d_status; } // Return the status passed to the most recent invocation of the // function-call operation, or 'UNINITIALIZED' if 'numInvocations' is // 0. const bsl::string& rotatedFileName() const // Return a reference to the non-modifiable file name supplied to the // most recent invocation of the function-call operator, or the empty // string if 'numInvocations' is 0. { return d_rep->d_rotatedFileName; } }; typedef LogRotationCallbackTester RotCb; struct TestCurrentTimeCallback { private: // DATA static bsls::TimeInterval s_utcTime; public: // CLASS METHODS static bsls::TimeInterval load(); // return the value corresponding to the most recent call to the // 'setTimeToReport' method. The behavior is undefined unless // 'setUtcTime' has been called. static void setUtcDatetime(const bdlt::Datetime& utcTime); // Set the specified 'utcTime' as the value obtained (after conversion // to 'bdlt::IntervalConversionUtil') from calls to the 'load' method. // The behavior is undefined unless // 'bdlt::EpochUtil::epoch() <= utcTime'. }; bsls::TimeInterval TestCurrentTimeCallback::s_utcTime; bsls::TimeInterval TestCurrentTimeCallback::load() { return s_utcTime; } void TestCurrentTimeCallback::setUtcDatetime(const bdlt::Datetime &utcTime) { ASSERT(bdlt::EpochUtil::epoch() <= utcTime); int rc = bdlt::EpochUtil::convertToTimeInterval(&s_utcTime, utcTime); ASSERT(0 == rc); } struct TestLocalTimeOffsetCallback { private: // DATA static int s_localTimeOffsetInSeconds; static int s_loadCount; public: // CLASS METHODS static bsls::TimeInterval loadLocalTimeOffset( const bdlt::Datetime& utcDatetime); // Return the local time offset that was set by the previous call to // the 'setLocalTimeOffset' method. If the 'setLocalTimeOffset' method // has not been called, load 0. Note that the specified 'utcDateime' // is ignored. static void setLocalTimeOffset(int localTimeOffsetInSeconds); // Set the specified 'localTimeOffsetInSeconds' as the value loaded by // calls to the loadLocalTimeOffset' method. static int loadCount(); // Return the number of times the 'loadLocalTimeOffset' method has been // called since the start of process. }; int TestLocalTimeOffsetCallback::s_localTimeOffsetInSeconds = 0; int TestLocalTimeOffsetCallback::s_loadCount = 0; bsls::TimeInterval TestLocalTimeOffsetCallback::loadLocalTimeOffset( const bdlt::Datetime& utcDatetime) { (void)utcDatetime; // Supress compiler warning. ++s_loadCount; return bsls::TimeInterval(s_localTimeOffsetInSeconds); } void TestLocalTimeOffsetCallback::setLocalTimeOffset( int localTimeOffsetInSeconds) { s_localTimeOffsetInSeconds = localTimeOffsetInSeconds; } int TestLocalTimeOffsetCallback::loadCount() { return s_loadCount; } void splitStringIntoLines(bsl::vector<bsl::string> *result, const char *ascii) { ASSERT(result) ASSERT(ascii) for (bdlb::Tokenizer itr(bslstl::StringRef(ascii), bslstl::StringRef(""), bslstl::StringRef("\n")); itr.isValid(); ++itr) { if (itr.token().length() > 0) { result->push_back(itr.token()); } } } int readFileIntoString(int lineNum, const bsl::string& filename, bsl::string& fileContent) { #ifdef BSLS_PLATFORM_OS_UNIX glob_t globbuf; LOOP_ASSERT(lineNum, 0 == glob((filename+"*").c_str(), 0, 0, &globbuf)); LOOP_ASSERT(lineNum, 1 == globbuf.gl_pathc); bsl::ifstream fs; fs.open(globbuf.gl_pathv[0], bsl::ifstream::in); globfree(&globbuf); LOOP_ASSERT(lineNum, fs.is_open()); fileContent = ""; bsl::string lineContent; int lines = 0; while (getline(fs, lineContent)) { fileContent += lineContent; fileContent += '\n'; lines++; } fs.close(); //bsl::cerr << "number of lines: " << lines << endl; return lines; #else bsl::ifstream fs; fs.open(filename.c_str(), bsl::ifstream::in); LOOP_ASSERT(lineNum, fs.is_open()); fileContent = ""; bsl::string lineContent; int lines = 0; while (getline(fs, lineContent)) { fileContent += lineContent; fileContent += '\n'; lines++; } fs.close(); //bsl::cerr << "number of lines: " << lines << endl; return lines; #endif } void getDatetimeField(bsl::string *result, const bsl::string& filename, int recordNumber) { ASSERT(1 <= recordNumber); bsl::string fileContent; int lineCount = readFileIntoString(__LINE__, filename, fileContent); ASSERT(recordNumber * 2 <= lineCount); bsl::vector<bsl::string> lines; splitStringIntoLines(&lines, fileContent.c_str()); int recordIndex = recordNumber - 1; ASSERT(0 <= recordIndex); ASSERT(lines.size() > recordIndex); const bsl::string& s = lines[recordIndex]; *result = s.substr(0, s.find_first_of(' ')); } } // close unnamed namespace //============================================================================= // MAIN PROGRAM //----------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? bsl::atoi(argv[1]) : 0; verbose = argc > 2; veryVerbose = argc > 3; veryVeryVerbose = argc > 4; veryVeryVeryVerbose = argc > 5; cout << "TEST " << __FILE__ << " CASE " << test << endl << flush; bslma::TestAllocator allocator; bslma::TestAllocator *Z = &allocator; bslma::TestAllocator defaultAllocator; bslma::DefaultAllocatorGuard guard(&defaultAllocator); switch (test) { case 0: case 7: { // -------------------------------------------------------------------- // TESTING: Published Records Show Current Local-Time Offset // Per DRQS 13681097, log records observe DST time transitions when // the default logging functor is used and the 'publishInLocalTime' // attribute is 'true'. // // Concern: //: 1 Log records show the current local time offset (possibly //: different from the local time offset in effect on construction), //: when 'true == isPublishInLocalTimeEnabled()'. //: //: 2 Log records show UTC when //: 'false == isPublishInLocalTimeEnabled()'. //: //: 3 QoI: The local-time offset is obtained not more than once per log //: record. //: //: 4 The helper class 'TestSystemTimeCallback' has a method, 'load', //: that loads the user-specified UTC time, and that method can be //: installed as the system-time callback of 'bdlt::CurrentTime'. //: //: 5 The helper class 'TestLocalTimeOffsetCallback' has a method, //: 'loadLocalTimeOffset', that loads the user-specified local-time //: offset value, and that method can be installed as the local-time //: callback of 'bdlt::CurrentTime', and that the value loaded is not //: influenced by the user-specified 'utcDatetime'. //: //: 6 The helper class method 'TestLocalTimeOffsetCallback::loadCount' //: provides an accurate count of the calls to the //: 'TestLocalTimeOffsetCallback::loadLocalTimeOffset' method. // // Plan: //: 1 Test the helper 'TestSystemTimeCallback' class (C-4): //: //: 1 Using the array-driven technique, confirm that the 'load' //: method obtains the value last set by the 'setUtcDatetime' //: method. Use UTC values that do not coincide with the actual //: UTC datetime. //: //: 2 Install the 'TestSystemTimeCallback::load' method as the //: system-time callback of system-time offset callback of //: 'bdlt::CurrentTime', and run through the same values as used in //: P-1.1. Confirm that values returned from 'bdlt::CurrentTime' //: match the user-specified values. //: //: 2 Test the helper 'TestLocalTimeOffsetCallback' class (C-5): //: //: 1 Using the array-driven technique, confirm that the //: 'loadLocalTimeOffset' method obtains the value last set by the //: 'setLocalTimeOffset' method. At least one value should differ //: from the current, actual local-time offset. //: //: 2 Install the 'TestLocalTimeOffsetCallback::loadLocalTimeOffset' //: method as the local-time offset callback of //: 'bdlt::CurrentTime', and run through the same user-specified //: local time offsets as used in P-2.1. Confirm that values //: returned from 'bdlt::CurrentTime' match the user-specified //: values. Repeat the request for (widely) different UTC //: datetime values to confirm that the local time offset value //: remains that defined by the callback. //: //: 3 Confirm that the value returned by the 'loadCount' method //: increases by exactly 1 each time a local-time offset is //: obtained via 'bdlt::CurrentTime'. (C-6) //: //: 3 Using an ad-hoc approach, confirm that the datetime field of a //: published log record is the expected (arbitrary) UTC datetime //: value when publishing in local-time is disabled. Enable //: publishing in local-time and confirm that the published datetime //: field matches that of the (arbitrary) user-defined local-time //: offsets. Disable publishing in local time, and confirm that log //: records are again published with the UTC datetime. (C-1, C-2) //: //: 4 When publishing in local time is enabled, confirm that there //: exactly 1 request for local time offset for each published //: record. (C-3); // -------------------------------------------------------------------- if (verbose) cout << endl << "TESTING: Published Records Show Current Local-Time Offset" <<endl << "=========================================================" <<endl; const bdlt::Datetime UTC_ARRAY[] = { bdlt::EpochUtil::epoch(), bdlt::Datetime(2001, 9, 11, 8 + 4, // UTC 46, 30, 0), bdlt::Datetime(9999, 12, 31, 23, 59, 59, 999) }; enum { NUM_UTC_ARRAY = sizeof UTC_ARRAY / sizeof *UTC_ARRAY }; if (verbose) cout << "\nTest TestSystemTimeCallback: Direct" << endl; { for (int i = 0; i < NUM_UTC_ARRAY; ++i) { bdlt::Datetime utcDatetime = UTC_ARRAY[i]; if (veryVerbose) { T_ P_(i) P(utcDatetime) } TestCurrentTimeCallback::setUtcDatetime(utcDatetime); bsls::TimeInterval result = TestCurrentTimeCallback::load(); bdlt::Datetime resultAsDatetime = bdlt::EpochUtil::convertFromTimeInterval(result); LOOP_ASSERT(i, utcDatetime == resultAsDatetime); } } if (verbose) cout << "\nTest TestSystemTimeCallback: Installed" << endl; { // Install callback from 'TestSystemTimeCallback'. bdlt::CurrentTime::CurrentTimeCallback originalCurrentTimeCallback = bdlt::CurrentTime::setCurrentTimeCallback( &TestCurrentTimeCallback::load); for (int i = 0; i < NUM_UTC_ARRAY; ++i) { bdlt::Datetime utcDatetime = UTC_ARRAY[i]; if (veryVerbose) { T_ P_(i) P(utcDatetime) } TestCurrentTimeCallback::setUtcDatetime(utcDatetime); bdlt::Datetime result1 = bdlt::CurrentTime::utc(); bslmt::ThreadUtil::microSleep(0, 2); // two seconds bdlt::Datetime result2 = bdlt::CurrentTime::utc(); LOOP_ASSERT(i, utcDatetime == result1); LOOP_ASSERT(i, result2 == result1); } // Restore original system-time callback. bdlt::CurrentTime::setCurrentTimeCallback( originalCurrentTimeCallback); } const int LTO_ARRAY[] = { -86399, -1, 0, 1, 86399 }; enum { NUM_LTO_ARRAY = sizeof LTO_ARRAY / sizeof *LTO_ARRAY }; int loadCount = TestLocalTimeOffsetCallback::loadCount(); ASSERT(0 == loadCount); if (verbose) cout << "\nTest TestLocalTimeOffsetCallback: Direct" << endl; { for (int i = 0; i < NUM_LTO_ARRAY; ++i) { int localTimeOffset = LTO_ARRAY[i]; if (veryVerbose) { T_ P_(i) P(localTimeOffset) } TestLocalTimeOffsetCallback::setLocalTimeOffset( localTimeOffset); for (int j = 0; j < NUM_UTC_ARRAY; ++j) { bdlt::Datetime utcDatetime = UTC_ARRAY[j]; if (veryVerbose) { T_ T_ P_(j) P(utcDatetime) } int result = TestLocalTimeOffsetCallback::loadLocalTimeOffset( utcDatetime).totalSeconds(); ++loadCount; LOOP2_ASSERT(i, j, localTimeOffset == result); LOOP2_ASSERT(i, j, loadCount == TestLocalTimeOffsetCallback::loadCount()); } } } if (verbose) cout << "\nTest TestLocalTimeOffsetCallback: Installed" << endl; { bdlt::LocalTimeOffset::LocalTimeOffsetCallback originalLocalTimeOffsetCallback = bdlt::LocalTimeOffset::setLocalTimeOffsetCallback( &TestLocalTimeOffsetCallback::loadLocalTimeOffset); for (int i = 0; i < NUM_LTO_ARRAY; ++i) { int localTimeOffset = LTO_ARRAY[i]; if (veryVerbose) { T_ P_(i) P(localTimeOffset) } TestLocalTimeOffsetCallback::setLocalTimeOffset( localTimeOffset); for (int j = 0; j < NUM_UTC_ARRAY; ++j) { bdlt::Datetime utcDatetime = UTC_ARRAY[j]; if (veryVerbose) { T_ T_ P_(j) P(utcDatetime) } int result = bdlt::LocalTimeOffset::localTimeOffset(utcDatetime) .totalSeconds(); ++loadCount; LOOP2_ASSERT(i, j, localTimeOffset == result); LOOP2_ASSERT(i, j, loadCount == TestLocalTimeOffsetCallback::loadCount()); } } bdlt::LocalTimeOffset::setLocalTimeOffsetCallback( originalLocalTimeOffsetCallback); } if (verbose) cout << "\nTest Logger" << endl; if (veryVerbose) cout << "\tConfigure Logger and Callbacks" << endl; ball::LoggerManagerConfiguration configuration; ASSERT(0 == configuration.setDefaultThresholdLevelsIfValid( ball::Severity::e_OFF, ball::Severity::e_TRACE, ball::Severity::e_OFF, ball::Severity::e_OFF)); bslma::TestAllocator ta(veryVeryVeryVerbose); Obj mX(ball::Severity::e_WARN, &ta); const Obj& X = mX; ball::LoggerManager::initSingleton(&mX, configuration); bsl::string BASENAME = tempFileName(veryVerbose); P(BASENAME); ASSERT(0 == mX.enableFileLogging(BASENAME.c_str(), true)); bsl::string logfilename; ASSERT(X.isFileLoggingEnabled(&logfilename)); P(logfilename); BALL_LOG_SET_CATEGORY("ball::FileObserverTest"); int logRecordCount = 0; int testLocalTimeOffsetInSeconds; bsl::string datetimeField; bsl::ostringstream expectedDatetimeField; const bdlt::Datetime testUtcDatetime = UTC_ARRAY[1]; bdlt::CurrentTime::CurrentTimeCallback originalCurrentTimeCallback = bdlt::CurrentTime::setCurrentTimeCallback( &TestCurrentTimeCallback::load); TestCurrentTimeCallback::setUtcDatetime(testUtcDatetime); bdlt::LocalTimeOffset::LocalTimeOffsetCallback originalLocalTimeOffsetCallback = bdlt::LocalTimeOffset::setLocalTimeOffsetCallback( &TestLocalTimeOffsetCallback::loadLocalTimeOffset); int expectedLoadCount = TestLocalTimeOffsetCallback::loadCount(); if (veryVerbose) cout << "\tLog with Publish In Local Time Disabled" << endl; ASSERT(!X.isPublishInLocalTimeEnabled()); BALL_LOG_TRACE << "log 1" << BALL_LOG_END; ++logRecordCount; getDatetimeField(&datetimeField, logfilename, logRecordCount); const int SIZE = 32; char buffer[SIZE]; bsl::memset(buffer, 'X', SIZE); testUtcDatetime.printToBuffer(buffer, SIZE, 3); bsl::string EXP(buffer); if (veryVerbose) { T_ P_(EXP) P(datetimeField) } ASSERT(EXP == datetimeField); ASSERTV(expectedLoadCount == TestLocalTimeOffsetCallback::loadCount()); BALL_LOG_TRACE << "log 2" << BALL_LOG_END; ++logRecordCount; getDatetimeField(&datetimeField, logfilename, logRecordCount); bsl::memset(buffer, 'X', SIZE); testUtcDatetime.printToBuffer(buffer, SIZE, 3); EXP.assign(buffer); if (veryVerbose) { T_ P_(EXP) P(datetimeField) } ASSERT(EXP == datetimeField); ASSERTV(expectedLoadCount == TestLocalTimeOffsetCallback::loadCount()); if (veryVerbose) cout << "\tLog with Publish In Local Time Enabled" << endl; mX.enablePublishInLocalTime(); ASSERT(X.isPublishInLocalTimeEnabled()); testLocalTimeOffsetInSeconds = -1 * 60 * 60; TestLocalTimeOffsetCallback::setLocalTimeOffset( testLocalTimeOffsetInSeconds); if (veryVerbose) { T_ P(testLocalTimeOffsetInSeconds); } BALL_LOG_TRACE << "log 3" << BALL_LOG_END; ++logRecordCount; ++expectedLoadCount; getDatetimeField(&datetimeField, logfilename, logRecordCount); bsl::memset(buffer, 'X', SIZE); bdlt::Datetime DT = testUtcDatetime + bdlt::DatetimeInterval(0, 0, 0, testLocalTimeOffsetInSeconds, 0); DT.printToBuffer(buffer, SIZE, 3); EXP.assign(buffer); if (veryVerbose) { T_ P_(EXP) P(datetimeField) } ASSERT(EXP == datetimeField); ASSERT(expectedLoadCount == TestLocalTimeOffsetCallback::loadCount()); testLocalTimeOffsetInSeconds = -2 * 60 * 60; TestLocalTimeOffsetCallback::setLocalTimeOffset( testLocalTimeOffsetInSeconds); if (veryVerbose) { T_ P(testLocalTimeOffsetInSeconds); } BALL_LOG_TRACE << "log 4" << BALL_LOG_END; ++logRecordCount; ++expectedLoadCount; getDatetimeField(&datetimeField, logfilename, logRecordCount); bsl::memset(buffer, 'X', SIZE); DT = testUtcDatetime + bdlt::DatetimeInterval(0, 0, 0, testLocalTimeOffsetInSeconds, 0); DT.printToBuffer(buffer, SIZE, 3); EXP.assign(buffer); if (veryVerbose) { T_ P_(EXP) P(datetimeField) } ASSERT(EXP == datetimeField); ASSERT(expectedLoadCount == TestLocalTimeOffsetCallback::loadCount()); mX.disablePublishInLocalTime(); ASSERT(!X.isPublishInLocalTimeEnabled()); BALL_LOG_TRACE << "log 5" << BALL_LOG_END; ++logRecordCount; // ++expectedLoadCount; getDatetimeField(&datetimeField, logfilename, logRecordCount); bsl::memset(buffer, 'X', SIZE); testUtcDatetime.printToBuffer(buffer, SIZE, 3); EXP.assign(buffer); if (veryVerbose) { T_ P_(EXP) P(datetimeField) } ASSERT(EXP == datetimeField); ASSERT(expectedLoadCount == TestLocalTimeOffsetCallback::loadCount()); if (veryVerbose) cout << "\tLog with Publish In Local Time Disabled Again" << endl; if (veryVerbose) cout << "\tCleanup" << endl; bdlt::CurrentTime::setCurrentTimeCallback(originalCurrentTimeCallback); bdlt::LocalTimeOffset::setLocalTimeOffsetCallback( originalLocalTimeOffsetCallback); mX.disableFileLogging(); FileUtil::remove(logfilename.c_str()); } break; case 6: { // -------------------------------------------------------------------- // TESTING TIME-BASED ROTATION // // Concern: //: 1 'rotateOnTimeInterval' correctly forward call to //: 'ball::FileObserver2'. // // Plan: //: 1 Setup test infrastructure. //: //: 2 Call 'rotateOnTimeInterval' with a large interval and a reference //: time such that the next rotation will occur soon. Verify that //: rotation occurs on the scheduled time. //: //: 3 Call 'disableLifetimeRotation' and verify that no rotation occurs //: afterwards. // // Testing: // void rotateOnTimeInterval(const DtInterval& i, const Datetime& r); // -------------------------------------------------------------------- if (verbose) cout << "\nTesting Time-Based Rotation" << "\n===========================" << endl; ball::LoggerManagerConfiguration configuration; ASSERT(0 == configuration.setDefaultThresholdLevelsIfValid( ball::Severity::e_OFF, ball::Severity::e_TRACE, ball::Severity::e_OFF, ball::Severity::e_OFF)); bslma::TestAllocator ta(veryVeryVeryVerbose); Obj mX(ball::Severity::e_WARN, &ta); const Obj& X = mX; // Set callback to monitor rotation. RotCb cb(Z); mX.setOnFileRotationCallback(cb); ball::LoggerManager::initSingleton(&mX, configuration); const bsl::string BASENAME = tempFileName(veryVerbose); ASSERT(0 == mX.enableFileLogging(BASENAME.c_str())); ASSERT(X.isFileLoggingEnabled()); ASSERT(0 == cb.numInvocations()); BALL_LOG_SET_CATEGORY("ball::FileObserverTest"); if (veryVerbose) cout << "Testing absolute time reference" << endl; { // Reset reference start time. mX.disableFileLogging(); // Ensure log file did not exist FileUtil::remove(BASENAME.c_str()); bdlt::Datetime refTime = bdlt::CurrentTime::local(); refTime += bdlt::DatetimeInterval(-1, 0, 0, 3); mX.rotateOnTimeInterval(bdlt::DatetimeInterval(1), refTime); ASSERT(0 == mX.enableFileLogging(BASENAME.c_str())); BALL_LOG_TRACE << "log" << BALL_LOG_END; LOOP_ASSERT(cb.numInvocations(), 0 == cb.numInvocations()); bslmt::ThreadUtil::microSleep(0, 3); BALL_LOG_TRACE << "log" << BALL_LOG_END; LOOP_ASSERT(cb.numInvocations(), 1 == cb.numInvocations()); ASSERT(1 == FileUtil::exists( cb.rotatedFileName().c_str())); } if (veryVerbose) cout << "Testing 'disableLifetimeRotation'" << endl; { cb.reset(); mX.disableLifetimeRotation(); bslmt::ThreadUtil::microSleep(0, 6); BALL_LOG_TRACE << "log" << BALL_LOG_END; LOOP_ASSERT(cb.numInvocations(), 0 == cb.numInvocations()); } mX.disableFileLogging(); removeFilesByPrefix(BASENAME.c_str()); } break; case 5: { // -------------------------------------------------------------------- // TESTING 'setOnFileRotationCallback' // // Concerns: //: 1 'setOnFileRotationCallback' is properly forwarded to the //: corresponding function in 'ball::FileObserver2' // // Plan: //: 1 Setup callback with 'setOnFileRotationCallback' and verify that //: the callback is invoked on rotation. // // Testing: // void setOnFileRotationCallback(const OnFileRotationCallback&); // -------------------------------------------------------------------- bslma::TestAllocator ta(veryVeryVeryVerbose); Obj mX(ball::Severity::e_WARN, &ta); bsl::string filename = tempFileName(veryVerbose); RotCb cb(Z); mX.setOnFileRotationCallback(cb); ASSERT(0 == cb.numInvocations()); mX.enableFileLogging(filename.c_str()); mX.forceRotation(); ASSERT(1 == cb.numInvocations()); mX.disableFileLogging(); removeFilesByPrefix(filename.c_str()); } break; case 4: { #if defined(BSLS_PLATFORM_OS_UNIX) && !defined(BSLS_PLATFORM_OS_CYGWIN) // 'setrlimit' is not implemented on Cygwin. // Don't run this if we're in the debugger because the debugger stops // and refuses to continue when we hit the file size limit. if (verbose) cerr << "Testing output when the stream fails" << " (UNIX only)." << endl; bslma::TestAllocator ta; ball::LoggerManagerConfiguration configuration; // Publish synchronously all messages regardless of their severity. // This configuration also guarantees that the observer will only see // each message only once. ASSERT(0 == configuration.setDefaultThresholdLevelsIfValid( ball::Severity::e_OFF, ball::Severity::e_TRACE, ball::Severity::e_OFF, ball::Severity::e_OFF)); ball::MultiplexObserver multiplexObserver; ball::LoggerManager::initSingleton(&multiplexObserver, configuration); { bsl::string fn = tempFileName(veryVerbose); struct rlimit rlim; ASSERT(0 == getrlimit(RLIMIT_FSIZE, &rlim)); rlim.rlim_cur = 2048; ASSERT(0 == setrlimit(RLIMIT_FSIZE, &rlim)); struct sigaction act,oact; act.sa_handler = SIG_IGN; sigemptyset(&act.sa_mask); act.sa_flags = 0; ASSERT(0 == sigaction(SIGXFSZ, &act, &oact)); Obj mX(ball::Severity::e_OFF, true, &ta); const Obj& X = mX; bsl::stringstream os; multiplexObserver.registerObserver(&mX); BALL_LOG_SET_CATEGORY("ball::FileObserverTest"); // We want to capture the error message that will be written to // stderr (not cerr). Redirect stderr to a file. We can't // redirect it back; we'll have to use 'ASSERT2' (which outputs to // cout, not cerr) from now on and report a summary to cout at the // end of this case. bsl::string stderrFN = tempFileName(veryVerbose); ASSERT(stderr == freopen(stderrFN.c_str(), "w", stderr)); ASSERT2(0 == mX.enableFileLogging(fn.c_str(), true)); ASSERT2(X.isFileLoggingEnabled()); ASSERT2(1 == mX.enableFileLogging(fn.c_str(), true)); for (int i = 0 ; i < 40 ; ++i) { BALL_LOG_TRACE << "log" << BALL_LOG_END; } fflush(stderr); bsl::fstream stderrFs; stderrFs.open(stderrFN.c_str(), bsl::ios_base::in); bsl::string line; ASSERT2(getline(stderrFs, line)); // we caught an error mX.disableFileLogging(); removeFilesByPrefix(stderrFN.c_str()); removeFilesByPrefix(fn.c_str()); multiplexObserver.deregisterObserver(&mX); if (testStatus > 0) { cout << "Error, non-zero test status = " << testStatus << "." << endl; } } #else if (verbose) { cout << "Skipping case 4 on Windows and Cygwin..." << endl; } #endif } break; case 3: { // -------------------------------------------------------------------- // TESTING LOG FILE ROTATION // // Concerns: // The number of existing log files should not exceed the value of // of 'd_maxLogFiles'. // // Plan: // Set up the file observer so that it would have generated many log // files if there were no limit. Verify that the number of log // files that actually exist does not exceed 'd_maxLogFiles'. // // Testing: // void setMaxLogFiles(); // int maxLogFiles() const; // int removeExcessLogFiles(); // -------------------------------------------------------------------- static bslma::TestAllocator ta(veryVeryVeryVerbose); ball::LoggerManagerConfiguration configuration; // Publish synchronously all messages regardless of their severity. // This configuration also guarantees that the observer will only see // each message only once. ASSERT(0 == configuration.setDefaultThresholdLevelsIfValid( ball::Severity::e_OFF, ball::Severity::e_TRACE, ball::Severity::e_OFF, ball::Severity::e_OFF)); ball::MultiplexObserver multiplexObserver; ball::LoggerManagerScopedGuard guard(&multiplexObserver, configuration, &ta); BALL_LOG_SET_CATEGORY("ball::FileObserverTest"); if (verbose) cout << "Testing log file deletion." << endl; { if (verbose) cout << "\t log file opened with timestamp" << endl; Obj mX(ball::Severity::e_OFF, &ta); const Obj& X = mX; multiplexObserver.registerObserver(&mX); ASSERT(bdlt::DatetimeInterval(0) == X.rotationLifetime()); mX.rotateOnLifetime(bdlt::DatetimeInterval(0,0,0,1)); ASSERT(bdlt::DatetimeInterval(0,0,0,1) == X.rotationLifetime()); multiplexObserver.deregisterObserver(&mX); // TBD #if 0 ASSERT(0 == X.maxLogFiles()); mX.setMaxLogFiles(5); ASSERT(5 == X.maxLogFiles()); bsl::string filename = tempFileName(veryVerbose); #ifdef BSLS_PLATFORM_OS_UNIX ASSERT(0 == mX.enableFileLogging(filename.c_str(), true)); ASSERT(X.isFileLoggingEnabled()); for (int i = 0 ; i < 20; ++i) { BALL_LOG_TRACE << "log" << BALL_LOG_END; bslmt::ThreadUtil::microSleep(1000 * 1000); } glob_t globbuf; ASSERT(0 == glob((filename + ".*").c_str(), 0, 0, &globbuf)); ASSERT(X.maxLogFiles() >= (int)globbuf.gl_pathc); mX.disableFileLogging(); mX.setMaxLogFiles(2); ASSERT(3 == mX.removeExcessLogFiles()); ASSERT(0 == glob((filename + ".*").c_str(), 0, 0, &globbuf)); ASSERT(X.maxLogFiles() >= (int)globbuf.gl_pathc); multiplexObserver.deregisterObserver(&mX); globfree(&globbuf); removeFilesByPrefix(filename.c_str()); #endif #endif } if (verbose) cout << "\t log file opened without timestamp" << endl; { Obj mX(ball::Severity::e_OFF, &ta); const Obj& X = mX; multiplexObserver.registerObserver(&mX); ASSERT(bdlt::DatetimeInterval(0) == X.rotationLifetime()); mX.rotateOnLifetime(bdlt::DatetimeInterval(0,0,0,1)); ASSERT(bdlt::DatetimeInterval(0,0,0,1) == X.rotationLifetime()); multiplexObserver.deregisterObserver(&mX); // TBD #if 0 ASSERT(0 == X.maxLogFiles()); mX.setMaxLogFiles(5); ASSERT(5 == X.maxLogFiles()); bsl::string filename = tempFileName(veryVerbose); #ifdef BSLS_PLATFORM_OS_UNIX ASSERT(0 == mX.enableFileLogging(filename.c_str(), false)); ASSERT(X.isFileLoggingEnabled()); for (int i = 0 ; i < 20; ++i) { BALL_LOG_TRACE << "log" << BALL_LOG_END; bslmt::ThreadUtil::microSleep(1000 * 1000); } glob_t globbuf; ASSERT(0 == glob((filename + ".*").c_str(), 0, 0, &globbuf)); ASSERT(X.maxLogFiles() >= (int)globbuf.gl_pathc); mX.disableFileLogging(); mX.setMaxLogFiles(2); ASSERT(2 == mX.removeExcessLogFiles()); ASSERT(0 == glob((filename + ".*").c_str(), 0, 0, &globbuf)); ASSERT(X.maxLogFiles() >= (int)globbuf.gl_pathc); multiplexObserver.deregisterObserver(&mX); globfree(&globbuf); removeFilesByPrefix(filename.c_str()); #endif #endif } if (verbose) cout << "\t log file name containing timestamp" << endl; { Obj mX(ball::Severity::e_OFF, &ta); const Obj& X = mX; multiplexObserver.registerObserver(&mX); ASSERT(bdlt::DatetimeInterval(0) == X.rotationLifetime()); mX.rotateOnLifetime(bdlt::DatetimeInterval(0,0,0,1)); ASSERT(bdlt::DatetimeInterval(0,0,0,1) == X.rotationLifetime()); multiplexObserver.deregisterObserver(&mX); // TBD #if 0 ASSERT(0 == X.maxLogFiles()); mX.setMaxLogFiles(5); ASSERT(5 == X.maxLogFiles()); bsl::string filename = tempFileName(veryVerbose); #ifdef BSLS_PLATFORM_OS_UNIX BALL_LOG_SET_CATEGORY("ball::FileObserverTest"); ASSERT(0 == mX.enableFileLogging((filename + "%s").c_str(), false)); ASSERT(X.isFileLoggingEnabled()); for (int i = 0 ; i < 20; ++i) { BALL_LOG_TRACE << "log" << BALL_LOG_END; bslmt::ThreadUtil::microSleep(1000 * 1000); } glob_t globbuf; ASSERT(0 == glob((filename + "*").c_str(), 0, 0, &globbuf)); ASSERT(X.maxLogFiles() >= (int)globbuf.gl_pathc); mX.disableFileLogging(); mX.setMaxLogFiles(2); ASSERT(3 == mX.removeExcessLogFiles()); ASSERT(0 == glob((filename + "*").c_str(), 0, 0, &globbuf)); ASSERT(X.maxLogFiles() >= (int)globbuf.gl_pathc); multiplexObserver.deregisterObserver(&mX); globfree(&globbuf); removeFilesByPrefix(filename.c_str()); #endif #endif } } break; case 2: { // -------------------------------------------------------------------- // Rotation functions test // // Concerns: // 1. 'rotateOnSize' triggers a rotation when expected. // 2. 'disableSizeRotation' disables rotation on size // 3. 'forceRotation' triggers a rotation // 4. 'rotateOnLifetime' triggers a rotation when expected // 5. 'disableLifetimeRotation' disables rotation on lifetime // // Test plan: // We will exercise both rotation rules to verify that they work // properly using glob to count the files and proper timing. We will // also verify that the size rule is followed by checking the size of // log files. // // Tactics: // - Ad-Hoc Data Selection Method // - Brute Force Implementation Technique // // Testing: // void disableLifetimeRotation() // void disableSizeRotation() // void forceRotation() // void rotateOnSize(int size) // void rotateOnLifetime(bdlt::DatetimeInterval timeInterval) // bdlt::DatetimeInterval rotationLifetime() const // int rotationSize() const // -------------------------------------------------------------------- ball::LoggerManagerConfiguration configuration; // Publish synchronously all messages regardless of their severity. // This configuration also guarantees that the observer will only see // each message only once. ASSERT(0 == configuration.setDefaultThresholdLevelsIfValid( ball::Severity::e_OFF, ball::Severity::e_TRACE, ball::Severity::e_OFF, ball::Severity::e_OFF)); ball::MultiplexObserver multiplexObserver; ball::LoggerManager::initSingleton(&multiplexObserver, configuration); #ifdef BSLS_PLATFORM_OS_UNIX bslma::TestAllocator ta(veryVeryVeryVerbose); if (verbose) cout << "Test-case infrastructure setup." << endl; { bsl::string filename = tempFileName(veryVerbose); Obj mX(ball::Severity::e_OFF, &ta); const Obj& X = mX; multiplexObserver.registerObserver(&mX); BALL_LOG_SET_CATEGORY("ball::FileObserverTest"); if (verbose) cout << "Testing setup." << endl; { ASSERT(0 == mX.enableFileLogging(filename.c_str(), true)); ASSERT(X.isFileLoggingEnabled()); ASSERT(1 == mX.enableFileLogging(filename.c_str(), true)); BALL_LOG_TRACE << "log 1" << BALL_LOG_END; glob_t globbuf; ASSERT(0 == glob((filename + ".2*").c_str(), 0, 0, &globbuf)); ASSERT(1 == globbuf.gl_pathc); bsl::ifstream fs; fs.open(globbuf.gl_pathv[0], bsl::ifstream::in); globfree(&globbuf); ASSERT(fs.is_open()); int linesNum = 0; bsl::string line; while (getline(fs, line)) { ++linesNum; } fs.close(); ASSERT(2 == linesNum); ASSERT(X.isFileLoggingEnabled()); } if (verbose) cout << "Testing lifetime-constrained rotation." << endl; { ASSERT(bdlt::DatetimeInterval(0) == X.rotationLifetime()); mX.rotateOnLifetime(bdlt::DatetimeInterval(0,0,0,3)); ASSERT(bdlt::DatetimeInterval(0,0,0,3) == X.rotationLifetime()); bslmt::ThreadUtil::microSleep(0, 4); BALL_LOG_TRACE << "log 1" << BALL_LOG_END; BALL_LOG_DEBUG << "log 2" << BALL_LOG_END; // Check that a rotation occurred. glob_t globbuf; ASSERT(0 == glob((filename + ".2*").c_str(), 0, 0, &globbuf)); ASSERT(2 == globbuf.gl_pathc); // Check the number of lines in the file. bsl::ifstream fs; fs.open(globbuf.gl_pathv[1], bsl::ifstream::in); fs.clear(); globfree(&globbuf); ASSERT(fs.is_open()); int linesNum = 0; bsl::string line(&ta); while (getline(fs, line)) { ++linesNum; } fs.close(); ASSERT(4 == linesNum); mX.disableLifetimeRotation(); bslmt::ThreadUtil::microSleep(0, 4); BALL_LOG_FATAL << "log 3" << BALL_LOG_END; // Check that no rotation occurred. ASSERT(0 == glob((filename + ".2*").c_str(), 0, 0, &globbuf)); ASSERT(2 == globbuf.gl_pathc); fs.open(globbuf.gl_pathv[1], bsl::ifstream::in); fs.clear(); globfree(&globbuf); ASSERT(fs.is_open()); linesNum = 0; while (getline(fs, line)) { ++linesNum; } fs.close(); ASSERT(6 == linesNum); } if (verbose) cout << "Testing forced rotation." << endl; { bslmt::ThreadUtil::microSleep(0, 2); mX.forceRotation(); BALL_LOG_TRACE << "log 1" << BALL_LOG_END; BALL_LOG_DEBUG << "log 2" << BALL_LOG_END; BALL_LOG_INFO << "log 3" << BALL_LOG_END; BALL_LOG_WARN << "log 4" << BALL_LOG_END; // Check that the rotation occurred. glob_t globbuf; ASSERT(0 == glob((filename + ".2*").c_str(), 0, 0, &globbuf)); ASSERT(3 == globbuf.gl_pathc); bsl::ifstream fs; fs.open(globbuf.gl_pathv[2], bsl::ifstream::in); fs.clear(); globfree(&globbuf); ASSERT(fs.is_open()); int linesNum = 0; bsl::string line(&ta); while (getline(fs, line)) { ++linesNum; } fs.close(); ASSERT(8 == linesNum); } if (verbose) cout << "Testing size-constrained rotation." << endl; { bslmt::ThreadUtil::microSleep(0, 2); ASSERT(0 == X.rotationSize()); mX.rotateOnSize(1); ASSERT(1 == X.rotationSize()); for (int i = 0 ; i < 30; ++i) { BALL_LOG_TRACE << "log" << BALL_LOG_END; // We sleep because otherwise, the loop is too fast to make // the timestamp change so we cannot observe the rotation. bslmt::ThreadUtil::microSleep(200 * 1000); } glob_t globbuf; ASSERT(0 == glob((filename + ".2*").c_str(), 0, 0, &globbuf)); ASSERT(4 <= globbuf.gl_pathc); // We are not checking the last one since we do not have any // information on its size. bsl::ifstream fs; for (int i = 0; i < (int)globbuf.gl_pathc - 3; ++i) { fs.open(globbuf.gl_pathv[i + 2], bsl::ifstream::in); fs.clear(); ASSERT(fs.is_open()); bsl::string::size_type fileSize = 0; bsl::string line(&ta); while (getline(fs, line)) { fileSize += line.length() + 1; } fs.close(); ASSERT(fileSize > 1024); } int oldNumFiles = (int)globbuf.gl_pathc; globfree(&globbuf); ASSERT(1 == X.rotationSize()); mX.disableSizeRotation(); ASSERT(0 == X.rotationSize()); for (int i = 0 ; i < 30; ++i) { BALL_LOG_TRACE << "log" << BALL_LOG_END; bslmt::ThreadUtil::microSleep(50 * 1000); } // Verify that no rotation occurred. ASSERT(0 == glob((filename + ".2*").c_str(), 0, 0, &globbuf)); ASSERT(oldNumFiles == (int)globbuf.gl_pathc); globfree(&globbuf); } mX.disableFileLogging(); removeFilesByPrefix(filename.c_str()); multiplexObserver.deregisterObserver(&mX); } { // Test with no timestamp. if (verbose) cout << "Test-case infrastructure setup." << endl; bsl::string filename = tempFileName(veryVerbose); Obj mX(ball::Severity::e_OFF, &ta); const Obj& X = mX; multiplexObserver.registerObserver(&mX); BALL_LOG_SET_CATEGORY("ball::FileObserverTest"); if (verbose) cout << "Testing setup." << endl; { ASSERT(0 == mX.enableFileLogging(filename.c_str(), false)); ASSERT(X.isFileLoggingEnabled()); ASSERT(1 == mX.enableFileLogging(filename.c_str(), false)); BALL_LOG_TRACE << "log 1" << BALL_LOG_END; glob_t globbuf; ASSERT(0 == glob((filename+"*").c_str(), 0, 0, &globbuf)); ASSERT(1 == globbuf.gl_pathc); bsl::ifstream fs; fs.open(globbuf.gl_pathv[0], bsl::ifstream::in); globfree(&globbuf); ASSERT(fs.is_open()); int linesNum = 0; bsl::string line; while (getline(fs, line)) { ++linesNum; } fs.close(); ASSERT(2 == linesNum); ASSERT(X.isFileLoggingEnabled()); } if (verbose) cout << "Testing lifetime-constrained rotation." << endl; { ASSERT(bdlt::DatetimeInterval(0) == X.rotationLifetime()); mX.rotateOnLifetime(bdlt::DatetimeInterval(0,0,0,3)); ASSERT(bdlt::DatetimeInterval(0,0,0,3) == X.rotationLifetime()); bslmt::ThreadUtil::microSleep(0, 4); BALL_LOG_TRACE << "log 1" << BALL_LOG_END; BALL_LOG_DEBUG << "log 2" << BALL_LOG_END; // Check that a rotation occurred. glob_t globbuf; ASSERT(0 == glob((filename+"*").c_str(), 0, 0, &globbuf)); ASSERT(2 == globbuf.gl_pathc); // Check the number of lines in the file. bsl::ifstream fs; fs.open(globbuf.gl_pathv[0], bsl::ifstream::in); fs.clear(); globfree(&globbuf); ASSERT(fs.is_open()); int linesNum = 0; bsl::string line(&ta); while (getline(fs, line)) { ++linesNum; } fs.close(); ASSERT(4 == linesNum); mX.disableLifetimeRotation(); bslmt::ThreadUtil::microSleep(0, 4); BALL_LOG_FATAL << "log 3" << BALL_LOG_END; // Check that no rotation occurred. ASSERT(0 == glob((filename+"*").c_str(), 0, 0, &globbuf)); ASSERT(2 == globbuf.gl_pathc); fs.open(globbuf.gl_pathv[0], bsl::ifstream::in); fs.clear(); globfree(&globbuf); ASSERT(fs.is_open()); linesNum = 0; while (getline(fs, line)) { ++linesNum; } fs.close(); ASSERT(6 == linesNum); } mX.disableFileLogging(); removeFilesByPrefix(filename.c_str()); multiplexObserver.deregisterObserver(&mX); } #endif } break; case 1: { // -------------------------------------------------------------------- // Publishing Test // // Concerns: // 1. publish() logs in the expected format: // a.using enable/disableUserFieldsLogging // b.using enable/disableStdoutLogging // // 2. publish() properly ignores the severity below the one // specified at construction on 'stdout' // // 3. publish() publishes all messages to a file if file logging // is enabled // // 4. the name of the log file should be in accordance with what is // defined by the given pattern if file logging is enabled by a // pattern // // 5. setLogFormat can change to the desired output format for both // 'stdout' and the log file // // Plan: // We will set up the observer and check if logged messages are in // the expected format and contain the expected data by comparing the // output of this observer with 'ball::DefaultObserver', that we // slightly modify. Then, we will configure the observer to ignore // different severity and test if only the expected messages are // published. We will use different manipulators to affect output // format and verify that it has changed where expected. // // Tactics: // - Helper Function -1 (see paragraph below) // - Ad-Hoc Data Selection Method // - Brute Force Implementation Technique // // Helper Function: // The helper function is run as a child task with stdout redirected // to a file. This captures stdout in the file so it can be // compared to output to the stringstream passed to the file // observer. The name of the file is generated here and put into // an environment variable so the child process can read it and // compare it with the expected output. // // Testing: // ball::FileObserver(ball::Severity::Level, bslma::Allocator) // ~ball::FileObserver() // publish(const ball::Record& record, const ball::Context& context) // void disableFileLogging() // void disableStdoutLoggingPrefix() // void disableUserFieldsLogging() // int enableFileLogging(const char *fileName, bool timestampFlag) // void enableStdoutLoggingPrefix() // void enableUserFieldsLogging() // void publish(const ball::Record&, const ball::Context&) // void setStdoutThreshold(ball::Severity::Level stdoutThreshold) // bool isFileLoggingEnabled() const // bool isStdoutLoggingPrefixEnabled() const // bool isUserFieldsLoggingEnabled() const // ball::Severity::Level stdoutThreshold() const // bool isPublishInLocalTimeEnabled() const // void setLogFormat(const char*, const char*) // void getLogFormat(const char**, const char**) const // -------------------------------------------------------------------- if (verbose) cout << "Testing threshold and output format.\n" "====================================\n"; bslma::TestAllocator ta; bsl::string fileName = tempFileName(veryVerbose); { const FILE *out = stdout; ASSERT(out == freopen(fileName.c_str(), "w", stdout)); fflush(stdout); } ASSERT(FileUtil::exists(fileName)); ASSERT(0 == FileUtil::getFileSize(fileName)); #if defined(BSLS_PLATFORM_OS_UNIX) && \ (!defined(BSLS_PLATFORM_OS_SOLARIS) || BSLS_PLATFORM_OS_VER_MAJOR >= 10) // For the localtime to be picked to avoid the all.pl env to pollute // us. unsetenv("TZ"); #endif ball::LoggerManagerConfiguration configuration; // Publish synchronously all messages regardless of their severity. // This configuration also guarantees that the observer will only see // each message only once. ASSERT(0 == configuration.setDefaultThresholdLevelsIfValid( ball::Severity::e_OFF, ball::Severity::e_TRACE, ball::Severity::e_OFF, ball::Severity::e_OFF)); ball::MultiplexObserver multiplexObserver; ball::LoggerManager::initSingleton(&multiplexObserver, configuration); if (verbose) cerr << "Testing threshold and output format." << endl; { Obj mX; const Obj& X = mX; ASSERT(ball::Severity::e_WARN == X.stdoutThreshold()); bsl::ostringstream os, dos; ball::DefaultObserver defaultObserver(&dos); ball::MultiplexObserver localMultiObserver; localMultiObserver.registerObserver(&mX); localMultiObserver.registerObserver(&defaultObserver); multiplexObserver.registerObserver(&localMultiObserver); BALL_LOG_SET_CATEGORY("ball::FileObserverTest"); bsl::streambuf *coutSbuf = bsl::cout.rdbuf(); bsl::cout.rdbuf(os.rdbuf()); FileUtil::Offset fileOffset = FileUtil::getFileSize(fileName); // these two lines are a desperate kludge to make windows work -- // this test driver works everywhere else without them. (void) readPartialFile(fileName, 0); fileOffset = FileUtil::getFileSize(fileName); BALL_LOG_TRACE << "not logged" << BALL_LOG_END; ASSERT(FileUtil::getFileSize(fileName) == fileOffset); dos.str(""); BALL_LOG_DEBUG << "not logged" << BALL_LOG_END; ASSERT(FileUtil::getFileSize(fileName) == fileOffset); dos.str(""); BALL_LOG_INFO << "not logged" << BALL_LOG_END; ASSERT(FileUtil::getFileSize(fileName) == fileOffset); dos.str(""); BALL_LOG_WARN << "log WARN" << BALL_LOG_END; // Replace the spaces after pid, __FILE__ to make dos match the // file { bsl::string temp = dos.str(); temp[temp.find(__FILE__) + sizeof(__FILE__) - 1] = ':'; replaceSecondSpace(&temp, ':'); dos.str(temp); } if (veryVeryVerbose) { P_(dos.str()); P(os.str()); } { bsl::string coutS = readPartialFile(fileName, fileOffset); LOOP2_ASSERT(dos.str(), coutS, dos.str() == coutS); } fileOffset = FileUtil::getFileSize(fileName); dos.str(""); mX.setStdoutThreshold(ball::Severity::e_ERROR); ASSERT(ball::Severity::e_ERROR == X.stdoutThreshold()); BALL_LOG_WARN << "not logged" << BALL_LOG_END; ASSERT("" == readPartialFile(fileName, fileOffset)); dos.str(""); BALL_LOG_ERROR << "log ERROR" << BALL_LOG_END; // Replace the spaces after pid, __FILE__ to make dos match the // file { bsl::string temp = dos.str(); temp[temp.find(__FILE__) + sizeof(__FILE__) - 1] = ':'; replaceSecondSpace(&temp, ':'); dos.str(temp); } if (veryVeryVerbose) { P_(dos.str()); P(os.str()); } { bsl::string coutS = readPartialFile(fileName, fileOffset); LOOP2_ASSERT(dos.str(), coutS, dos.str() == coutS); } fileOffset = FileUtil::getFileSize(fileName); dos.str(""); BALL_LOG_FATAL << "log FATAL" << BALL_LOG_END; // Replace the spaces after pid, __FILE__ to make dos match the // file { bsl::string temp = dos.str(); temp[temp.find(__FILE__) + sizeof(__FILE__) - 1] = ':'; replaceSecondSpace(&temp, ':'); dos.str(temp); } if (veryVeryVerbose) { P_(dos.str()); P(os.str()); } { bsl::string coutS = readPartialFile(fileName, fileOffset); LOOP2_ASSERT(dos.str(), coutS, dos.str() == coutS); } fileOffset = FileUtil::getFileSize(fileName); dos.str(""); bsl::cout.rdbuf(coutSbuf); multiplexObserver.deregisterObserver(&localMultiObserver); localMultiObserver.deregisterObserver(&defaultObserver); localMultiObserver.deregisterObserver(&mX); } if (verbose) cerr << "Testing constructor threshold." << endl; { Obj mX(ball::Severity::e_FATAL, &ta); bsl::ostringstream os, dos; FileUtil::Offset fileOffset = FileUtil::getFileSize(fileName); ball::DefaultObserver defaultObserver(&dos); ball::MultiplexObserver localMultiObserver; localMultiObserver.registerObserver(&mX); localMultiObserver.registerObserver(&defaultObserver); multiplexObserver.registerObserver(&localMultiObserver); BALL_LOG_SET_CATEGORY("ball::FileObserverTest"); bsl::streambuf *coutSbuf = bsl::cout.rdbuf(); bsl::cout.rdbuf(os.rdbuf()); ASSERT(FileUtil::getFileSize(fileName) == fileOffset); BALL_LOG_TRACE << "not logged" << BALL_LOG_END; ASSERT(FileUtil::getFileSize(fileName) == fileOffset); dos.str(""); BALL_LOG_DEBUG << "not logged" << BALL_LOG_END; ASSERT(FileUtil::getFileSize(fileName) == fileOffset); dos.str(""); BALL_LOG_INFO << "not logged" << BALL_LOG_END; ASSERT(FileUtil::getFileSize(fileName) == fileOffset); dos.str(""); BALL_LOG_WARN << "not logged" << BALL_LOG_END; ASSERT(FileUtil::getFileSize(fileName) == fileOffset); dos.str(""); BALL_LOG_ERROR << "not logged" << BALL_LOG_END; ASSERT(FileUtil::getFileSize(fileName) == fileOffset); dos.str(""); BALL_LOG_FATAL << "log" << BALL_LOG_END; // Replace the spaces after pid, __FILE__ to make dos match the // file { bsl::string temp = dos.str(); temp[temp.find(__FILE__) + sizeof(__FILE__) - 1] = ':'; replaceSecondSpace(&temp, ':'); dos.str(temp); } if (veryVeryVerbose) { P_(dos.str()); P(os.str()); } { bsl::string coutS = readPartialFile(fileName, fileOffset); LOOP2_ASSERT(dos.str(), coutS, dos.str() == coutS); } ASSERT(dos.str() == readPartialFile(fileName, fileOffset)); fileOffset = FileUtil::getFileSize(fileName); dos.str(""); ASSERT("" == os.str()); bsl::cout.rdbuf(coutSbuf); multiplexObserver.deregisterObserver(&localMultiObserver); localMultiObserver.deregisterObserver(&defaultObserver); localMultiObserver.deregisterObserver(&mX); } if (verbose) cerr << "Testing short format." << endl; { Obj mX; const Obj& X = mX; ASSERT(!X.isPublishInLocalTimeEnabled()); ASSERT( X.isStdoutLoggingPrefixEnabled()); mX.disableStdoutLoggingPrefix(); ASSERT(!X.isStdoutLoggingPrefixEnabled()); bsl::ostringstream os, testOs, dos; FileUtil::Offset fileOffset = FileUtil::getFileSize(fileName); ball::DefaultObserver defaultObserver(&dos); ball::MultiplexObserver localMultiObserver; localMultiObserver.registerObserver(&mX); localMultiObserver.registerObserver(&defaultObserver); multiplexObserver.registerObserver(&localMultiObserver); BALL_LOG_SET_CATEGORY("ball::FileObserverTest"); bsl::streambuf *coutSbuf = bsl::cout.rdbuf(); bsl::cout.rdbuf(os.rdbuf()); BALL_LOG_TRACE << "not logged" << BALL_LOG_END; ASSERT(FileUtil::getFileSize(fileName) == fileOffset); BALL_LOG_DEBUG << "not logged" << BALL_LOG_END; ASSERT(FileUtil::getFileSize(fileName) == fileOffset); BALL_LOG_INFO << "not logged" << BALL_LOG_END; ASSERT(FileUtil::getFileSize(fileName) == fileOffset); BALL_LOG_WARN << "log WARN" << BALL_LOG_END; testOs << "\nWARN " << __FILE__ << ":" << __LINE__ - 1 << " ball::FileObserverTest log WARN " << "\n"; { bsl::string coutS = readPartialFile(fileName, fileOffset); LOOP2_ASSERT(testOs.str(), coutS, testOs.str() == coutS); } fileOffset = FileUtil::getFileSize(fileName); testOs.str(""); BALL_LOG_ERROR << "log ERROR" << BALL_LOG_END; testOs << "\nERROR " << __FILE__ << ":" << __LINE__ - 1 << " ball::FileObserverTest log ERROR " << "\n"; { bsl::string coutS = readPartialFile(fileName, fileOffset); LOOP2_ASSERT(testOs.str(), coutS, testOs.str() == coutS); } fileOffset = FileUtil::getFileSize(fileName); testOs.str(""); ASSERT(!X.isStdoutLoggingPrefixEnabled()); mX.enableStdoutLoggingPrefix(); ASSERT( X.isStdoutLoggingPrefixEnabled()); dos.str(""); BALL_LOG_FATAL << "log FATAL" << BALL_LOG_END; testOs << "\nFATAL " << __FILE__ << ":" << __LINE__ - 1 << " ball::FileObserverTest log FATAL " << "\n"; { // Replace the spaces after pid, __FILE__ to make dos match the // file bsl::string temp = dos.str(); temp[temp.find(__FILE__) + sizeof(__FILE__) - 1] = ':'; replaceSecondSpace(&temp, ':'); dos.str(temp); bsl::string coutS = readPartialFile(fileName, fileOffset); if (veryVeryVerbose) { P_(dos.str()); P(coutS); } LOOP2_ASSERT(dos.str(), coutS, dos.str() == coutS); ASSERT(testOs.str() != coutS); } fileOffset = FileUtil::getFileSize(fileName); ASSERT("" == os.str()); bsl::cout.rdbuf(coutSbuf); multiplexObserver.deregisterObserver(&localMultiObserver); localMultiObserver.deregisterObserver(&defaultObserver); localMultiObserver.deregisterObserver(&mX); } if (verbose) cerr << "Testing short format with local time " << "offset." << endl; { Obj mX(ball::Severity::e_WARN, true, &ta); const Obj& X = mX; ASSERT( X.isPublishInLocalTimeEnabled()); ASSERT( X.isStdoutLoggingPrefixEnabled()); mX.disableStdoutLoggingPrefix(); ASSERT(!X.isStdoutLoggingPrefixEnabled()); FileUtil::Offset fileOffset = FileUtil::getFileSize(fileName); bsl::ostringstream os, testOs, dos; ball::DefaultObserver defaultObserver(&dos); ball::MultiplexObserver localMultiObserver; localMultiObserver.registerObserver(&mX); localMultiObserver.registerObserver(&defaultObserver); multiplexObserver.registerObserver(&localMultiObserver); BALL_LOG_SET_CATEGORY("ball::FileObserverTest"); bsl::streambuf *coutSbuf = bsl::cout.rdbuf(); bsl::cout.rdbuf(os.rdbuf()); BALL_LOG_TRACE << "not logged" << BALL_LOG_END; ASSERT(FileUtil::getFileSize(fileName) == fileOffset); BALL_LOG_DEBUG << "not logged" << BALL_LOG_END; ASSERT(FileUtil::getFileSize(fileName) == fileOffset); BALL_LOG_INFO << "not logged" << BALL_LOG_END; ASSERT(FileUtil::getFileSize(fileName) == fileOffset); BALL_LOG_WARN << "log WARN" << BALL_LOG_END; testOs << "\nWARN " << __FILE__ << ":" << __LINE__ - 1 << " ball::FileObserverTest log WARN " << "\n"; { bsl::string coutS = readPartialFile(fileName, fileOffset); LOOP2_ASSERT(testOs.str(), coutS, testOs.str() == coutS); } fileOffset = FileUtil::getFileSize(fileName); testOs.str(""); BALL_LOG_ERROR << "log ERROR" << BALL_LOG_END; testOs << "\nERROR " << __FILE__ << ":" << __LINE__ - 1 << " ball::FileObserverTest log ERROR " << "\n"; { bsl::string coutS = readPartialFile(fileName, fileOffset); LOOP2_ASSERT(testOs.str(), coutS, testOs.str() == coutS); } fileOffset = FileUtil::getFileSize(fileName); testOs.str(""); ASSERT(!X.isStdoutLoggingPrefixEnabled()); mX.enableStdoutLoggingPrefix(); ASSERT( X.isStdoutLoggingPrefixEnabled()); dos.str(""); BALL_LOG_FATAL << "log FATAL" << BALL_LOG_END; testOs << "FATAL " << __FILE__ << ":" << __LINE__ - 1 << " ball::FileObserverTest log FATAL " << "\n"; // Replace the spaces after pid, __FILE__ { bsl::string temp = dos.str(); temp[temp.find(__FILE__) + sizeof(__FILE__) - 1] = ':'; replaceSecondSpace(&temp, ':'); dos.str(temp); } { bsl::string coutS = readPartialFile(fileName, fileOffset); if (0 == bdlt::LocalTimeOffset::localTimeOffset( bdlt::CurrentTime::utc()).totalSeconds()) { LOOP2_ASSERT(dos.str(), os.str(), dos.str() == coutS); } else { LOOP2_ASSERT(dos.str(), os.str(), dos.str() != coutS); } ASSERT(testOs.str() != coutS); LOOP2_ASSERT(coutS, testOs.str(), bsl::string::npos != coutS.find(testOs.str())); // Now let's verify the actual difference. int defaultObsHour; if (dos.str().length() >= 11) { bsl::istringstream is(dos.str().substr(11, 2)); ASSERT(is >> defaultObsHour); } else { ASSERT(0 && "can't substr(11,2), string too short"); } int fileObsHour; if (coutS.length() >= 11) { bsl::istringstream is(coutS.substr(11, 2)); ASSERT(is >> fileObsHour); } else { ASSERT(0 && "can't substr(11,2), string too short"); } int difference = bdlt::CurrentTime::utc().hour() - bdlt::CurrentTime::local().hour(); LOOP3_ASSERT(fileObsHour, defaultObsHour, difference, (fileObsHour + difference + 24) % 24 == defaultObsHour); { bsl::string temp = dos.str(); temp[11] = coutS[11]; temp[12] = coutS[12]; dos.str(temp); } if (defaultObsHour - difference >= 0 && defaultObsHour - difference < 24) { // UTC and local time are on the same day if (veryVeryVerbose) { P_(dos.str()); P(coutS); } } else if (coutS.length() >= 11) { // UTC and local time are on different days. Ignore date. ASSERT(dos.str().substr(10) == os.str().substr(10)); } else { ASSERT(0 && "can't substr(11,2), string too short"); } fileOffset = FileUtil::getFileSize(fileName); ASSERT(0 == os.str().length()); bsl::cout.rdbuf(coutSbuf); multiplexObserver.deregisterObserver(&localMultiObserver); localMultiObserver.deregisterObserver(&defaultObserver); localMultiObserver.deregisterObserver(&mX); } } if (verbose) cerr << "Testing file logging." << endl; { bsl::string fn = tempFileName(veryVerbose); FileUtil::Offset fileOffset = FileUtil::getFileSize(fileName); Obj mX(ball::Severity::e_WARN, &ta); const Obj& X = mX; bsl::stringstream ss; multiplexObserver.registerObserver(&mX); BALL_LOG_SET_CATEGORY("ball::FileObserverTest"); if (veryVerbose) { cerr << fn << endl; cerr << fileName << endl; } bsl::streambuf *coutSbuf = bsl::cout.rdbuf(); bsl::cout.rdbuf(ss.rdbuf()); ASSERT(0 == mX.enableFileLogging(fn.c_str())); ASSERT(X.isFileLoggingEnabled()); ASSERT(1 == mX.enableFileLogging(fn.c_str())); BALL_LOG_TRACE << "log 1" << BALL_LOG_END; BALL_LOG_DEBUG << "log 2" << BALL_LOG_END; BALL_LOG_INFO << "log 3" << BALL_LOG_END; BALL_LOG_WARN << "log 4" << BALL_LOG_END; BALL_LOG_ERROR << "log 5" << BALL_LOG_END; BALL_LOG_FATAL << "log 6" << BALL_LOG_END; bsl::ifstream fs, coutFs; fs.open(fn.c_str(), bsl::ifstream::in); coutFs.open(fileName.c_str(), bsl::ifstream::in); ASSERT(fs.is_open()); ASSERT(coutFs.is_open()); coutFs.seekg(fileOffset); int linesNum = 0; bsl::string line; while (getline(fs, line)) { bsl::cerr << "Line: " << line << bsl::endl; if (linesNum >= 6) { // check format bsl::string coutLine; getline(coutFs, coutLine); ASSERTV(coutLine, line, coutLine == line); bsl::cerr << "coutLine: '" << coutLine << "'" << endl << "line: '" << line << "'" <<endl; } ++linesNum; } fs.close(); ASSERT(!getline(coutFs, line)); coutFs.close(); ASSERT(12 == linesNum); break; ASSERT(X.isFileLoggingEnabled()); mX.disableFileLogging(); ASSERT(!X.isFileLoggingEnabled()); BALL_LOG_TRACE << "log 1" << BALL_LOG_END; BALL_LOG_DEBUG << "log 2" << BALL_LOG_END; BALL_LOG_INFO << "log 3" << BALL_LOG_END; BALL_LOG_WARN << "log 4" << BALL_LOG_END; BALL_LOG_ERROR << "log 5" << BALL_LOG_END; BALL_LOG_FATAL << "log 6" << BALL_LOG_END; fs.open(fn.c_str(), bsl::ifstream::in); ASSERT(fs.is_open()); fs.clear(); linesNum = 0; while (getline(fs, line)) { ++linesNum; } fs.close(); ASSERT(12 == linesNum); ASSERT(0 == mX.enableFileLogging(fn.c_str())); ASSERT(X.isFileLoggingEnabled()); ASSERT(1 == mX.enableFileLogging(fn.c_str())); BALL_LOG_TRACE << "log 7" << BALL_LOG_END; BALL_LOG_DEBUG << "log 8" << BALL_LOG_END; BALL_LOG_INFO << "log 9" << BALL_LOG_END; BALL_LOG_WARN << "log 1" << BALL_LOG_END; BALL_LOG_ERROR << "log 2" << BALL_LOG_END; BALL_LOG_FATAL << "log 3" << BALL_LOG_END; fs.open(fn.c_str(), bsl::ifstream::in); ASSERT(fs.is_open()); fs.clear(); linesNum = 0; while (getline(fs, line)) { ++linesNum; } fs.close(); ASSERT(24 == linesNum); bsl::cout.rdbuf(coutSbuf); mX.disableFileLogging(); removeFilesByPrefix(fn.c_str()); multiplexObserver.deregisterObserver(&mX); } #ifdef BSLS_PLATFORM_OS_UNIX if (verbose) cerr << "Testing file logging with timestamp." << endl; { bsl::string fn = tempFileName(veryVerbose); Obj mX(ball::Severity::e_WARN, &ta); const Obj& X = mX; bsl::ostringstream os; multiplexObserver.registerObserver(&mX); BALL_LOG_SET_CATEGORY("ball::FileObserverTest"); bsl::streambuf *coutSbuf = bsl::cout.rdbuf(); bsl::cout.rdbuf(os.rdbuf()); ASSERT(0 == mX.enableFileLogging(fn.c_str(), true)); ASSERT(X.isFileLoggingEnabled()); ASSERT(1 == mX.enableFileLogging(fn.c_str(), true)); BALL_LOG_TRACE << "log 1" << BALL_LOG_END; BALL_LOG_DEBUG << "log 2" << BALL_LOG_END; BALL_LOG_INFO << "log 3" << BALL_LOG_END; BALL_LOG_WARN << "log 4" << BALL_LOG_END; BALL_LOG_ERROR << "log 5" << BALL_LOG_END; BALL_LOG_FATAL << "log 6" << BALL_LOG_END; glob_t globbuf; ASSERT(0 == glob((fn + ".2*").c_str(), 0, 0, &globbuf)); ASSERT(1 == globbuf.gl_pathc); bsl::ifstream fs; fs.open(globbuf.gl_pathv[0], bsl::ifstream::in); ASSERT(fs.is_open()); int linesNum = 0; bsl::string line; while (getline(fs, line)) { ++linesNum; } fs.close(); ASSERT(12 == linesNum); ASSERT(X.isFileLoggingEnabled()); bsl::cout.rdbuf(coutSbuf); ASSERT("" == os.str()); mX.disableFileLogging(); removeFilesByPrefix(fn.c_str()); multiplexObserver.deregisterObserver(&mX); } if (verbose) cerr << "Testing log file name pattern." << endl; { bsl::string baseName = tempFileName(veryVerbose); bsl::string pattern = baseName + "%Y%M%D%h%m%s-%p"; Obj mX(ball::Severity::e_WARN, &ta); const Obj& X = mX; multiplexObserver.registerObserver(&mX); BALL_LOG_SET_CATEGORY("ball::FileObserverTest"); bdlt::Datetime startDatetime, endDatetime; mX.disableLifetimeRotation(); mX.disableSizeRotation(); mX.disableFileLogging(); mX.enablePublishInLocalTime(); // loop until startDatetime is equal to endDatetime do { startDatetime = getCurrentTimestamp(); ASSERT(0 == mX.enableFileLogging(pattern.c_str(), false)); ASSERT(X.isFileLoggingEnabled()); ASSERT(1 == mX.enableFileLogging(pattern.c_str(), false)); endDatetime = getCurrentTimestamp(); if (startDatetime.date() != endDatetime.date() || startDatetime.hour() != endDatetime.hour() || startDatetime.minute() != endDatetime.minute() || startDatetime.second() != endDatetime.second()) { // not sure the exact time when the log file was opened // because startDatetime and endDatetime are different; // will try it again bsl::string fn; ASSERT(1 == mX.isFileLoggingEnabled(&fn)); mX.disableFileLogging(); ASSERT(0 == bsl::remove(fn.c_str())); } } while (!X.isFileLoggingEnabled()); ASSERT(startDatetime.year() == endDatetime.year()); ASSERT(startDatetime.month() == endDatetime.month()); ASSERT(startDatetime.day() == endDatetime.day()); ASSERT(startDatetime.hour() == endDatetime.hour()); ASSERT(startDatetime.minute() == endDatetime.minute()); ASSERT(startDatetime.second() == endDatetime.second()); BALL_LOG_INFO<< "log" << BALL_LOG_END; mX.disableFileLogging(); // now construct the name of the log file from startDatetime bsl::ostringstream fnOs; fnOs << baseName; fnOs << bsl::setw(4) << bsl::setfill('0') << startDatetime.year(); fnOs << bsl::setw(2) << bsl::setfill('0') << startDatetime.month(); fnOs << bsl::setw(2) << bsl::setfill('0') << startDatetime.day(); fnOs << bsl::setw(2) << bsl::setfill('0') << startDatetime.hour(); fnOs << bsl::setw(2) << bsl::setfill('0') << startDatetime.minute(); fnOs << bsl::setw(2) << bsl::setfill('0') << startDatetime.second(); fnOs << "-"; fnOs << bdls::ProcessUtil::getProcessId(); // look for the file with the constructed name glob_t globbuf; LOOP_ASSERT(fnOs.str(), 0 == glob(fnOs.str().c_str(), 0, 0, &globbuf)); LOOP_ASSERT(globbuf.gl_pathc, 1 == globbuf.gl_pathc); // read the file to get the number of lines bsl::ifstream fs; fs.open(globbuf.gl_pathv[0], bsl::ifstream::in); fs.clear(); globfree(&globbuf); ASSERT(fs.is_open()); int linesNum = 0; bsl::string line; while (getline(fs, line)) { ++linesNum; } fs.close(); ASSERT(2 == linesNum); mX.disableFileLogging(); removeFilesByPrefix(baseName.c_str()); multiplexObserver.deregisterObserver(&mX); } if (verbose) cerr << "Testing '%%' in file name pattern." << endl; { static const struct { int d_lineNum; // source line number const char *d_patternSuffix_p; // pattern suffix const char *d_filenameSuffix_p; // filename suffix } DATA[] = { //line pattern suffix filename suffix //---- -------------- --------------- { L_, "foo", "foo" }, { L_, "foo%", "foo%" }, { L_, "foo%bar", "foo%bar" }, { L_, "foo%%", "foo" }, { L_, "foo%%bar", "foobar" }, { L_, "foo%%%", "foo%" }, { L_, "foo%%%bar", "foo%bar" }, }; enum { NUM_DATA = sizeof DATA / sizeof *DATA }; for (int ti = 0; ti < NUM_DATA; ++ti) { const int LINE = DATA[ti].d_lineNum; const char *PATTERN = DATA[ti].d_patternSuffix_p; const char *FILENAME = DATA[ti].d_filenameSuffix_p; bsl::string baseName = tempFileName(veryVerbose); bsl::string pattern(baseName); pattern += PATTERN; bsl::string expected(baseName); expected += FILENAME; bsl::string actual; Obj mX(ball::Severity::e_WARN, &ta); const Obj& X = mX; LOOP_ASSERT(LINE, 0 == mX.enableFileLogging( pattern.c_str(), false)); LOOP_ASSERT(LINE, X.isFileLoggingEnabled(&actual)); if (veryVeryVerbose) { P_(PATTERN); P_(expected); P(actual); } LOOP_ASSERT(LINE, expected == actual); mX.disableFileLogging(); // look for the file with the expected name glob_t globbuf; LOOP_ASSERT(LINE, 0 == glob(expected.c_str(), 0, 0, &globbuf)); LOOP_ASSERT(LINE, 1 == globbuf.gl_pathc); removeFilesByPrefix(expected.c_str()); } } if (verbose) cerr << "Testing customized format." << endl; { FileUtil::Offset fileOffset = FileUtil::getFileSize(fileName); Obj mX(ball::Severity::e_WARN, &ta); const Obj& X = mX; ASSERT(ball::Severity::e_WARN == X.stdoutThreshold()); multiplexObserver.registerObserver(&mX); BALL_LOG_SET_CATEGORY("ball::FileObserverTest"); // redirect 'stdout' to a string stream { bsl::string baseName = tempFileName(veryVerbose); ASSERT(0 == mX.enableFileLogging(baseName.c_str(), false)); ASSERT(X.isFileLoggingEnabled()); ASSERT(1 == mX.enableFileLogging(baseName.c_str(), false)); bsl::stringstream os; bsl::streambuf *coutSbuf = bsl::cout.rdbuf(); bsl::cout.rdbuf(os.rdbuf()); // for log file, use bdlt::Datetime format for stdout, use ISO // format mX.setLogFormat("%d %p %t %s %l %c %m %u", "%i %p %t %s %l %c %m %u"); fileOffset = FileUtil::getFileSize(fileName); BALL_LOG_WARN << "log" << BALL_LOG_END; // look for the file with the constructed name glob_t globbuf; ASSERT(0 == glob(baseName.c_str(), 0, 0, &globbuf)); ASSERT(1 == globbuf.gl_pathc); // read the log file to get the record bsl::ifstream fs; fs.open(globbuf.gl_pathv[0], bsl::ifstream::in); fs.clear(); globfree(&globbuf); ASSERT(fs.is_open()); bsl::string line; ASSERT(getline(fs, line)); fs.close(); bsl::string datetime1, datetime2; bsl::string log1, log2; bsl::string::size_type pos; // divide line into datetime and the rest pos = line.find(' '); datetime1 = line.substr(0, pos); log1 = line.substr(pos, line.length()); fflush(stdout); bsl::string fStr = readPartialFile(fileName, fileOffset); ASSERT("" == os.str()); // divide os.str() into datetime and the rest pos = fStr.find(' '); ASSERT(bsl::string::npos != pos); datetime2 = fStr.substr(0, pos); log2 = fStr.substr(pos, fStr.length()-pos); LOOP2_ASSERT(log1, log2, log1 == log2); // Now we try to convert datetime2 from ISO to bdlt::Datetime bsl::istringstream iss(datetime2); int year, month, day, hour, minute, second; char c; iss >> year >> c >> month >> c >> day >> c >> hour >> c >> minute >> c >> second; bdlt::Datetime datetime3(year, month, day, hour, minute, second); bsl::ostringstream oss; oss << datetime3; // Ignore the millisecond field so don't compare the entire // strings. ASSERT(0 == oss.str().compare(0, 18, datetime1, 0, 18)); mX.disableFileLogging(); ASSERT("" == os.str()); fileOffset = FileUtil::getFileSize(fileName); bsl::cout.rdbuf(coutSbuf); mX.disableFileLogging(); removeFilesByPrefix(baseName.c_str()); } // now swap the two string formats if (verbose) cerr << " .. customized format swapped.\n"; { bsl::string baseName = tempFileName(veryVerbose); ASSERT(0 == mX.enableFileLogging(baseName.c_str(), false)); ASSERT(X.isFileLoggingEnabled()); ASSERT(1 == mX.enableFileLogging(baseName.c_str(), false)); ASSERT(X.isFileLoggingEnabled()); fileOffset = FileUtil::getFileSize(fileName); bsl::stringstream os; bsl::streambuf *coutSbuf = bsl::cout.rdbuf(); bsl::cout.rdbuf(os.rdbuf()); mX.setLogFormat("%i %p %t %s %f %l %c %m %u", "%d %p %t %s %f %l %c %m %u"); BALL_LOG_WARN << "log" << BALL_LOG_END; // look for the file with the constructed name glob_t globbuf; ASSERT(0 == glob(baseName.c_str(), 0, 0, &globbuf)); ASSERT(1 == globbuf.gl_pathc); // read the log file to get the record bsl::ifstream fs; fs.open(globbuf.gl_pathv[0], bsl::ifstream::in); fs.clear(); globfree(&globbuf); ASSERT(fs.is_open()); bsl::string line; ASSERT(getline(fs, line)); fs.close(); bsl::string datetime1, datetime2; bsl::string log1, log2; bsl::string::size_type pos; // get datetime and the rest from stdout bsl::string soStr = readPartialFile(fileName, fileOffset); pos = soStr.find(' '); datetime1 = soStr.substr(0, pos); log1 = soStr.substr(pos, soStr.length()); // divide line into datetime and the rest pos = line.find(' '); datetime2 = line.substr(0, pos); log2 = line.substr(pos, line.length()-pos); LOOP2_ASSERT(log1, log2, log1 == log2); // now we try to convert datetime2 from ISO to // bdlt::Datetime bsl::istringstream iss(datetime2); int year, month, day, hour, minute, second; char c; iss >> year >> c >> month >> c >> day >> c >> hour >> c >> minute >> c >> second; bdlt::Datetime datetime3(year, month, day, hour, minute, second); bsl::ostringstream oss; oss << datetime3; // ignore the millisecond field so don't compare the entire // strings ASSERT(0 == oss.str().compare(0, 18, datetime1, 0, 18)); if (veryVerbose) { bsl::cerr << "datetime3: " << datetime3 << bsl::endl; bsl::cerr << "datetime2: " << datetime2 << bsl::endl; bsl::cerr << "datetime1: " << datetime1 << bsl::endl; } fileOffset = FileUtil::getFileSize(fileName); bsl::cout.rdbuf(coutSbuf); mX.disableFileLogging(); removeFilesByPrefix(baseName.c_str()); multiplexObserver.deregisterObserver(&mX); } } #endif if (verbose) cerr << "Testing User-Defined Fields Toggling\n"; { Obj mX(ball::Severity::e_WARN, &ta); const Obj& X = mX; const char *logFileFormat; const char *stdoutFormat; ASSERT(X.isUserFieldsLoggingEnabled()); X.getLogFormat(&logFileFormat, &stdoutFormat); ASSERT(0 == bsl::strcmp(logFileFormat, "\n%d %p:%t %s %f:%l %c %m %u\n")); ASSERT(0 == bsl::strcmp(stdoutFormat, "\n%d %p:%t %s %f:%l %c %m %u\n")); mX.disableUserFieldsLogging(); ASSERT(!X.isUserFieldsLoggingEnabled()); X.getLogFormat(&logFileFormat, &stdoutFormat); ASSERT(0 == bsl::strcmp(logFileFormat, "\n%d %p:%t %s %f:%l %c %m\n")); ASSERT(0 == bsl::strcmp(stdoutFormat, "\n%d %p:%t %s %f:%l %c %m\n")); mX.enableUserFieldsLogging(); ASSERT(X.isUserFieldsLoggingEnabled()); X.getLogFormat(&logFileFormat, &stdoutFormat); ASSERT(0 == bsl::strcmp(logFileFormat, "\n%d %p:%t %s %f:%l %c %m %u\n")); ASSERT(0 == bsl::strcmp(stdoutFormat, "\n%d %p:%t %s %f:%l %c %m %u\n")); // Now change to short format for stdout. ASSERT( X.isStdoutLoggingPrefixEnabled()); mX.disableStdoutLoggingPrefix(); ASSERT(!X.isStdoutLoggingPrefixEnabled()); X.getLogFormat(&logFileFormat, &stdoutFormat); ASSERT(0 == bsl::strcmp(logFileFormat, "\n%d %p:%t %s %f:%l %c %m %u\n")); ASSERT(0 == bsl::strcmp(stdoutFormat, "\n%s %f:%l %c %m %u\n")); mX.disableUserFieldsLogging(); ASSERT(!X.isUserFieldsLoggingEnabled()); X.getLogFormat(&logFileFormat, &stdoutFormat); ASSERT(0 == bsl::strcmp(logFileFormat, "\n%d %p:%t %s %f:%l %c %m\n")); ASSERT(0 == bsl::strcmp(stdoutFormat, "\n%s %f:%l %c %m\n")); mX.enableUserFieldsLogging(); ASSERT(X.isUserFieldsLoggingEnabled()); X.getLogFormat(&logFileFormat, &stdoutFormat); ASSERT(0 == bsl::strcmp(logFileFormat, "\n%d %p:%t %s %f:%l %c %m %u\n")); ASSERT(0 == bsl::strcmp(stdoutFormat, "\n%s %f:%l %c %m %u\n")); // Change back to long format for stdout. ASSERT(!X.isStdoutLoggingPrefixEnabled()); mX.enableStdoutLoggingPrefix(); ASSERT( X.isStdoutLoggingPrefixEnabled()); X.getLogFormat(&logFileFormat, &stdoutFormat); ASSERT(0 == bsl::strcmp(logFileFormat, "\n%d %p:%t %s %f:%l %c %m %u\n")); ASSERT(0 == bsl::strcmp(stdoutFormat, "\n%d %p:%t %s %f:%l %c %m %u\n")); // Now see what happens with customized format. Notice that we // intentionally use the default short format. const char *newLogFileFormat = "\n%s %f:%l %c %m %u\n"; const char *newStdoutFormat = "\n%s %f:%l %c %m %u\n"; mX.setLogFormat(newLogFileFormat, newStdoutFormat); X.getLogFormat(&logFileFormat, &stdoutFormat); ASSERT(0 == bsl::strcmp(logFileFormat, newLogFileFormat)); ASSERT(0 == bsl::strcmp(stdoutFormat, newStdoutFormat)); // Toggling user fields logging should not change the formats. mX.disableUserFieldsLogging(); ASSERT(!X.isUserFieldsLoggingEnabled()); X.getLogFormat(&logFileFormat, &stdoutFormat); ASSERT(0 == bsl::strcmp(logFileFormat, newLogFileFormat)); ASSERT(0 == bsl::strcmp(stdoutFormat, newStdoutFormat)); mX.enableUserFieldsLogging(); ASSERT( X.isUserFieldsLoggingEnabled()); X.getLogFormat(&logFileFormat, &stdoutFormat); ASSERT(0 == bsl::strcmp(logFileFormat, newLogFileFormat)); ASSERT(0 == bsl::strcmp(stdoutFormat, newStdoutFormat)); // Now set short format for stdout. ASSERT(X.isStdoutLoggingPrefixEnabled()); mX.disableStdoutLoggingPrefix(); ASSERT(!X.isStdoutLoggingPrefixEnabled()); X.getLogFormat(&logFileFormat, &stdoutFormat); ASSERT(0 == bsl::strcmp(logFileFormat, newLogFileFormat)); ASSERT(0 == bsl::strcmp(stdoutFormat, newStdoutFormat)); // stdoutFormat should change, since even if we are now using // customized formats, the format happens to be the same as the // default short format. mX.disableUserFieldsLogging(); ASSERT(!X.isUserFieldsLoggingEnabled()); X.getLogFormat(&logFileFormat, &stdoutFormat); ASSERT(0 == bsl::strcmp(logFileFormat, newLogFileFormat)); ASSERT(0 == bsl::strcmp(stdoutFormat, "\n%s %f:%l %c %m\n")); mX.enableUserFieldsLogging(); ASSERT(X.isUserFieldsLoggingEnabled()); X.getLogFormat(&logFileFormat, &stdoutFormat); ASSERT(0 == bsl::strcmp(logFileFormat, newLogFileFormat)); ASSERT(0 == bsl::strcmp(stdoutFormat, newStdoutFormat)); } fclose(stdout); removeFilesByPrefix(fileName.c_str()); } break; default: { cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl; testStatus = -1; } } if (testStatus > 0) { cerr << "Error, non-zero test status = " << testStatus << "." << endl; } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
38.621508
79
0.517656
hughesr
11735a061840d0bbabdb7bf57d273e56d8b72ce5
505
cpp
C++
tests/parsers/headers/cseq_parsers.cpp
voivoid/CppSip
4d5776e777b4f95f60357d8f7c05926222751d33
[ "MIT" ]
null
null
null
tests/parsers/headers/cseq_parsers.cpp
voivoid/CppSip
4d5776e777b4f95f60357d8f7c05926222751d33
[ "MIT" ]
null
null
null
tests/parsers/headers/cseq_parsers.cpp
voivoid/CppSip
4d5776e777b4f95f60357d8f7c05926222751d33
[ "MIT" ]
null
null
null
#include "boost/test/unit_test.hpp" #include "CppSip/parser/headers/cseq.h" #include "parsers/utils.h" namespace CppSipHdr = CppSip::Message::Headers; namespace { define_parser( CSeq, CppSipHdr::CSeq ) } BOOST_AUTO_TEST_SUITE( header_parsers ) BOOST_AUTO_TEST_CASE( test_CSEQ_parser ) { { const auto [ id, method ] = parse_CSeq( "CSeq: 12345 INVITE" ); BOOST_CHECK_EQUAL( "12345", id ); BOOST_CHECK_EQUAL( CppSip::Message::Method::Invite, method ); } } BOOST_AUTO_TEST_SUITE_END()
18.703704
67
0.724752
voivoid
1173978138e68a0eaa676e21d4dc9e160aa79789
9,151
cpp
C++
Ko-Fi Engine/Source/PanelConfiguration.cpp
Chamfer-Studios/Ko-Fi-Engine
cdc7fd9fd8c30803ac2e3fe0ecaf1923bbd7532e
[ "MIT" ]
2
2022-02-26T23:35:53.000Z
2022-03-04T16:25:18.000Z
Ko-Fi Engine/Source/PanelConfiguration.cpp
Chamfer-Studios/Ko-Fi-Engine
cdc7fd9fd8c30803ac2e3fe0ecaf1923bbd7532e
[ "MIT" ]
2
2022-02-23T09:41:09.000Z
2022-03-08T08:46:21.000Z
Ko-Fi Engine/Source/PanelConfiguration.cpp
Chamfer-Studios/Ko-Fi-Engine
cdc7fd9fd8c30803ac2e3fe0ecaf1923bbd7532e
[ "MIT" ]
1
2022-03-03T18:41:32.000Z
2022-03-03T18:41:32.000Z
#include "PanelConfiguration.h" #include "PanelChooser.h" #include "Engine.h" #include "M_Window.h" #include "M_SceneManager.h" #include "M_Renderer3D.h" #include "M_Input.h" #include "M_Audio.h" #include "EngineConfig.h" #include "M_Editor.h" #include "SceneIntro.h" #include <imgui.h> #include "glew.h" PanelConfiguration::PanelConfiguration(M_Editor* editor, EngineConfig* engineConfig) { panelName = "Configuration"; this->engineConfig = engineConfig; this->editor = editor; this->masterVol = 5; } PanelConfiguration::~PanelConfiguration() { } bool PanelConfiguration::Awake() { return true; } bool PanelConfiguration::Update() { OPTICK_EVENT(); ImGui::Begin(panelName.c_str(),0); if (ImGui::BeginMenu("Options")) { if (ImGui::MenuItem("Set Defaults")) { printf_s("%s", "Clicked Set Defaults\n"); } if (ImGui::MenuItem("Load")) { printf_s("%s", "Clicked Load\n"); } if (ImGui::MenuItem("Save")) { printf_s("%s", "Clicked Save\n"); } ImGui::EndMenu(); } if (ImGui::CollapsingHeader("Application")) { static char appName[120]; strcpy_s(appName, 120, engineConfig->title.c_str()); ImGui::InputText("App Name",appName,120,ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll); static char organization[120]; strcpy_s(organization, 120, engineConfig->organization.c_str()); ImGui::InputText("Organization", organization, 120, ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll); if (ImGui::SliderInt("Max FPS", &engineConfig->maxFps, 0, 200)) engineConfig->cappedMs = 1000 / engineConfig->maxFps; char title[25]; sprintf_s(title, 25, "Framerate %.1f", engineConfig->fpsLog[engineConfig->fpsLog.size() - 1]); ImGui::PlotHistogram("##framerate", &engineConfig->fpsLog[0], engineConfig->fpsLog.size(), 0, title, 0.0f, 100, ImVec2(310, 100)); sprintf_s(title, 25, "Milliseconds %.1f", engineConfig->msLog[engineConfig->msLog.size() - 1]); ImGui::PlotHistogram("##milliseconds", &engineConfig->msLog[0], engineConfig->msLog.size(), 0, title, 0.0f, 40.0f, ImVec2(310, 100)); } if (ImGui::CollapsingHeader("Resource Manager")) { if (ImGui::Checkbox("Show Loaded Resources", &editor->toggleResourcesPanel)) {} } if (ImGui::CollapsingHeader("Renderer")) { bool vsync = editor->engine->GetRenderer()->GetVsync(); if (ImGui::Checkbox("VSync", &vsync)) editor->engine->GetRenderer()->SetVsync(vsync); if (ImGui::Checkbox("Draw scene partition tree", &editor->engine->GetSceneManager()->GetCurrentScene()->drawSceneTree)) {} } if (ImGui::CollapsingHeader("Input")) { int mouseX = editor->engine->GetInput()->GetMouseX(); int mouseY = editor->engine->GetInput()->GetMouseY(); ImGui::Text("Mouse Position:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.8196, 0.7176, 0.6078, 1.0), "%i,%i", mouseX, mouseY); mouseX = editor->engine->GetInput()->GetMouseXMotion(); mouseY = editor->engine->GetInput()->GetMouseYMotion(); ImGui::Text("Mouse Motion:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.8196, 0.7176, 0.6078, 1.0), "%i,%i", mouseX, mouseY); int wheel = editor->engine->GetInput()->GetMouseZ(); ImGui::Text("Mouse Wheel:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.8196, 0.7176, 0.6078, 1.0), "%i", wheel); } if (ImGui::CollapsingHeader("Window")) { ImGui::Text("Icon:"); ImGui::SameLine(); if (editor->GetPanelChooser()->IsReadyToClose("PanelConfig")) { std::string file = editor->GetPanelChooser()->OnChooserClosed(); if (!file.empty()) { std::string newFile = file; newFile.erase(newFile.begin()); editor->engine->GetWindow()->SetIcon(newFile.c_str()); } } if (ImGui::Selectable(editor->engine->GetWindow()->GetIcon())) editor->GetPanelChooser()->OpenPanel("PanelConfig", "bmp", { "bmp" }); float brightness = editor->engine->GetWindow()->GetBrightness(); if (ImGui::SliderFloat("Brightness", &brightness, 0.0f, 1.0f)) editor->engine->GetWindow()->AdjustBrightness(brightness); int width = editor->engine->GetWindow()->GetWidth(); int height = editor->engine->GetWindow()->GetHeight(); if (ImGui::SliderInt("Width", &width, 640, 4096) | ImGui::SliderInt("Height", &height, 480, 2160)) { SDL_SetWindowSize(editor->engine->GetWindow()->window, width, height); editor->engine->GetWindow()->SetWidth(width); editor->engine->GetWindow()->SetHeight(height); } ImGui::Text("Refresh rate:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.8196, 0.7176, 0.6078, 1.0),"%u", editor->engine->GetWindow()->GetRefreshRate()); bool temp = editor->engine->GetWindow()->GetFullscreen(); if (ImGui::Checkbox("Fullscreen",&temp)) editor->engine->GetWindow()->SetFullscreen(temp); ImGui::SameLine(); temp = editor->engine->GetWindow()->GetFullscreenDesktop(); if (ImGui::Checkbox("Fullscreen Desktop", &temp)) editor->engine->GetWindow()->SetFullscreenDesktop(temp); temp = editor->engine->GetWindow()->GetResizable(); if (ImGui::Checkbox("Resizable", &temp)) editor->engine->GetWindow()->SetResizable(temp); ImGui::SameLine(); temp = editor->engine->GetWindow()->GetBorderless(); if (ImGui::Checkbox("Borderless", &temp)) editor->engine->GetWindow()->SetBorderless(temp); } if (ImGui::CollapsingHeader("Hardware")) { ImGui::Text("SDL Version:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.8196, 0.7176, 0.6078, 1.0), "%d.%d.%d", engineConfig->sdlVersion.major, engineConfig->sdlVersion.minor, engineConfig->sdlVersion.patch); ImGui::Separator(); ImGui::Text("OpenGL Version:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.8196, 0.7176, 0.6078, 1.0), "%s", engineConfig->gpuVersion); ImGui::Separator(); ImGui::Text("CPUs:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.8196, 0.7176, 0.6078, 1.0),"%d", engineConfig->cpuCores); ImGui::Text("System RAM:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.8196, 0.7176, 0.6078, 1.0), "%d", engineConfig->RAM); ImGui::Text("Caps:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.8196, 0.7176, 0.6078, 1.0), "%s%s%s%s%s%s", engineConfig->hasAVX ?"AVX,":"", engineConfig->hasAVX2 ?"AVX2,":"", engineConfig->hasAltiVec ?"AltiVec,":"", engineConfig->hasMMX ?"MMX,":"", engineConfig->hasRDTSC ?"RDTSC,":"", engineConfig->has3DNow ? "3DNow," : ""); ImGui::TextColored(ImVec4(0.8196, 0.7176, 0.6078, 1.0), "%s%s%s%s%s", engineConfig->hasSSE ? "SSE," : "", engineConfig->hasSSE2 ? "SSE2," : "", engineConfig->hasSSE3 ? "SSE3," : "", engineConfig->hasSSE41 ? "SSE41," : "", engineConfig->hasSSE42 ? "SSE42," : ""); ImGui::Separator(); ImGui::Text("GPU:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.8196, 0.7176, 0.6078, 1.0), "%s", engineConfig->gpuRenderer); ImGui::Text("Brand:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.8196, 0.7176, 0.6078, 1.0), "%s", engineConfig->gpuVendor); ImGui::Text("VRAM Budget:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.8196, 0.7176, 0.6078, 1.0), "%.1f Mb", engineConfig->vramBudget * (1.0 / 1024.0)); ImGui::Text("VRAM Usage:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.8196, 0.7176, 0.6078, 1.0), "%.1f Mb", engineConfig->vramUsage * (1.0 / 1024.0)); ImGui::Text("VRAM Available:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.8196, 0.7176, 0.6078, 1.0), "%.1f Mb", engineConfig->vramAvailable * (1.0 / 1024.0)); ImGui::Text("VRAM Reserved:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.8196, 0.7176, 0.6078, 1.0), "%.1f Mb", engineConfig->vramReserved * (1.0 / 1024.0)); } if (ImGui::CollapsingHeader("OpenGL")) { if (!modifyAttributesMenu) { if (ImGui::Button("Modify attributes") == true) modifyAttributesMenu = true; } if (modifyAttributesMenu) { if (ImGui::Button("Back") == true) modifyAttributesMenu = false; bool enabled = glIsEnabled(GL_DEPTH_TEST); if (ImGui::Checkbox("Depth Test", &enabled)) enabled? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST); enabled = glIsEnabled(GL_CULL_FACE); if (ImGui::Checkbox("Cull Face", &enabled)) enabled ? glEnable(GL_CULL_FACE) : glDisable(GL_CULL_FACE); enabled = glIsEnabled(GL_LIGHTING); if (ImGui::Checkbox("Lighting", &enabled)) enabled ? glEnable(GL_LIGHTING) : glDisable(GL_LIGHTING); enabled = glIsEnabled(GL_COLOR_MATERIAL); if (ImGui::Checkbox("Color Material", &enabled)) enabled ? glEnable(GL_COLOR_MATERIAL) : glDisable(GL_COLOR_MATERIAL); enabled = glIsEnabled(GL_TEXTURE_2D); if (ImGui::Checkbox("Texture 2D", &enabled)) enabled ? glEnable(GL_TEXTURE_2D) : glDisable(GL_TEXTURE_2D); } if (ImGui::Checkbox("Wireframe mode", &wireframe)) { if (wireframe) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } } if (ImGui::CollapsingHeader("Audio")) { if (ImGui::SliderInt("Master Volume", &masterVol, 0, 5)) editor->engine->GetAudio()->SetListenerVolume(masterVol, 5); std::string str = "Master Volume: " + std::to_string(editor->engine->GetAudio()->GetListenerVolume()); ImGui::Text(str.c_str()); } ImGui::End(); return true; }
34.794677
166
0.674571
Chamfer-Studios
1176b4de385af7e2333cf73d93da9cbca6b00a1c
356
cpp
C++
source/main.cpp
danielga/gm_ffi
b3f557a3203febcdf38f24cf6bc476230861284e
[ "BSD-3-Clause" ]
3
2016-03-26T13:09:05.000Z
2021-08-25T16:41:53.000Z
source/main.cpp
danielga/gm_ffi
b3f557a3203febcdf38f24cf6bc476230861284e
[ "BSD-3-Clause" ]
5
2016-06-29T21:10:04.000Z
2021-08-25T13:01:23.000Z
source/main.cpp
danielga/gm_ffi
b3f557a3203febcdf38f24cf6bc476230861284e
[ "BSD-3-Clause" ]
1
2021-01-29T03:56:50.000Z
2021-01-29T03:56:50.000Z
#include <GarrysMod/Lua/Interface.h> extern "C" int luaopen_cffi( lua_State *L ); GMOD_MODULE_OPEN( ) { if( luaopen_cffi( LUA->GetState( ) ) != 0 ) { LUA->Push( -1 ); LUA->SetField( GarrysMod::Lua::INDEX_GLOBAL, "ffi" ); } return 1; } GMOD_MODULE_CLOSE( ) { LUA->PushNil( ); LUA->SetField( GarrysMod::Lua::INDEX_GLOBAL, "ffi" ); return 0; }
16.181818
55
0.640449
danielga
117e063904ed41e24d36f1dad5e1ebde7ef81d85
4,038
cc
C++
modules/bridge/test/bridge_sender_test.cc
yilun917/apollo
022bc600f5cef8005a02e2c3b1a2485f56d6adfc
[ "Apache-2.0" ]
null
null
null
modules/bridge/test/bridge_sender_test.cc
yilun917/apollo
022bc600f5cef8005a02e2c3b1a2485f56d6adfc
[ "Apache-2.0" ]
null
null
null
modules/bridge/test/bridge_sender_test.cc
yilun917/apollo
022bc600f5cef8005a02e2c3b1a2485f56d6adfc
[ "Apache-2.0" ]
1
2020-02-20T13:47:23.000Z
2020-02-20T13:47:23.000Z
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include <arpa/inet.h> #include <netinet/in.h> #include <stdlib.h> #include <sys/socket.h> #include <unistd.h> #include <thread> #include "cyber/common/log.h" #include "cyber/scheduler/scheduler_factory.h" #include "modules/bridge/common/bridge_proto_serialized_buf.h" #include "modules/canbus/proto/chassis.pb.h" #include "modules/common/time/time.h" using apollo::common::time::Clock; bool send(const std::string &remote_ip, uint16_t remote_port, uint32_t count) { if (count == 0) { count = 10000; } float total = static_cast<float>(count); float hundred = 100.00; for (uint32_t i = 0; i < count; i++) { double timestamp_ = Clock::NowInSeconds() - 2.0; float coefficient = static_cast<float>(i); auto pb_msg = std::make_shared<apollo::canbus::Chassis>(); pb_msg->mutable_header()->set_sequence_num(i); pb_msg->mutable_header()->set_timestamp_sec(timestamp_); pb_msg->set_engine_started(true); pb_msg->set_engine_rpm(static_cast<float>(coefficient * 2.0)); pb_msg->set_odometer_m(coefficient); pb_msg->set_fuel_range_m(100); pb_msg->set_throttle_percentage(coefficient * hundred / total); pb_msg->set_brake_percentage(coefficient * hundred / total); pb_msg->set_steering_percentage(coefficient * hundred / total); pb_msg->set_steering_torque_nm(coefficient); pb_msg->set_parking_brake(i % 2 ? true : false); pb_msg->set_high_beam_signal(false); pb_msg->set_low_beam_signal(true); pb_msg->set_left_turn_signal(false); pb_msg->set_right_turn_signal(false); pb_msg->set_horn(false); pb_msg->set_wiper(false); pb_msg->set_disengage_status(false); pb_msg->set_driving_mode(apollo::canbus::Chassis::COMPLETE_MANUAL); pb_msg->set_error_code(apollo::canbus::Chassis::NO_ERROR); pb_msg->set_gear_location(apollo::canbus::Chassis::GEAR_NEUTRAL); struct sockaddr_in server_addr; server_addr.sin_addr.s_addr = inet_addr(remote_ip.c_str()); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(remote_port); ADEBUG << "connecting to server... "; int sock_fd = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK, 0); int res = connect(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)); if (res < 0) { ADEBUG << "connected server failed "; continue; } ADEBUG << "connected to server success. port [" << remote_port << "]"; apollo::bridge::BridgeProtoSerializedBuf<apollo::canbus::Chassis> proto_buf; proto_buf.Serialize(pb_msg, "Chassis"); for (size_t j = 0; j < proto_buf.GetSerializedBufCount(); j++) { ssize_t nbytes = send(sock_fd, proto_buf.GetSerializedBuf(j), proto_buf.GetSerializedBufSize(j), 0); if (nbytes != static_cast<ssize_t>(proto_buf.GetSerializedBufSize(j))) { ADEBUG << "sent msg failed "; break; } ADEBUG << "sent " << nbytes << " bytes to server with sequence num " << i; } close(sock_fd); // 1000Hz std::this_thread::sleep_for(std::chrono::milliseconds(1)); } return true; } int main(int argc, char *argv[]) { uint32_t count = 0; if (argc < 2) { count = 10000; } else { count = atoi(argv[1]); } send("127.0.0.1", 8900, count); return 0; }
36.053571
80
0.664438
yilun917
1187addb4c919f924b5a736a34f10a7eb34b57bc
54
cpp
C++
lib/cmake/Qt5SerialBus/Qt5SerialBus_TinyCanBusPlugin_Import.cpp
samlior/Qt5.15.0-rc2-static-macosx10.15
b9a1698a9a44baefbf3aa258af2ef487f12beff0
[ "blessing" ]
null
null
null
lib/cmake/Qt5SerialBus/Qt5SerialBus_TinyCanBusPlugin_Import.cpp
samlior/Qt5.15.0-rc2-static-macosx10.15
b9a1698a9a44baefbf3aa258af2ef487f12beff0
[ "blessing" ]
null
null
null
lib/cmake/Qt5SerialBus/Qt5SerialBus_TinyCanBusPlugin_Import.cpp
samlior/Qt5.15.0-rc2-static-macosx10.15
b9a1698a9a44baefbf3aa258af2ef487f12beff0
[ "blessing" ]
null
null
null
#include <QtPlugin> Q_IMPORT_PLUGIN(TinyCanBusPlugin)
18
33
0.851852
samlior
118bade351832547369c6167ddddb202d78af347
11,922
cc
C++
caffe2/contrib/opengl/core/rewrite_net.cc
huiqun2001/caffe2
97209961b675c8bea3831450ba46c9e8b7bad3de
[ "MIT" ]
null
null
null
caffe2/contrib/opengl/core/rewrite_net.cc
huiqun2001/caffe2
97209961b675c8bea3831450ba46c9e8b7bad3de
[ "MIT" ]
null
null
null
caffe2/contrib/opengl/core/rewrite_net.cc
huiqun2001/caffe2
97209961b675c8bea3831450ba46c9e8b7bad3de
[ "MIT" ]
null
null
null
// Copyright 2004-present Facebook. All Rights Reserved. #include "rewrite_net.h" #include "caffe2/core/operator.h" #include "caffe2/utils/proto_utils.h" #include <unordered_map> #include <unordered_set> #ifdef CAFFE2_ANDROID #include "../android/AndroidGLContext.h" #endif namespace caffe2 { struct Analysis { struct SSA { using BlobVersions = std::unordered_map<std::string, size_t>; BlobVersions inVersions; BlobVersions outVersions; }; std::vector<SSA> ssa; std::unordered_map<std::string, std::unordered_map<size_t, std::vector<size_t>>> inUsages; }; static Analysis analyzeNet(const NetDef& net) { Analysis::SSA::BlobVersions frontier; Analysis analysis; auto play = [&](size_t i, const OperatorDef& op) { Analysis::SSA::BlobVersions inVersions; for (const auto& s : op.input()) { inVersions[s] = frontier[s]; analysis.inUsages[s][frontier[s]].push_back(i); } Analysis::SSA::BlobVersions outVersions; for (const auto& s : op.output()) { if (frontier.find(s) != frontier.end()) { frontier[s] += 1; } outVersions[s] = frontier[s]; } analysis.ssa.push_back(Analysis::SSA{inVersions, outVersions}); }; for (auto i = 0; i < net.op_size(); ++i) { play(i, net.op(i)); } return analysis; } static void insertCopyToGPUOp(NetDef& predictNet, const std::string& cpu_blob) { auto* op = predictNet.add_op(); op->set_name("CopyToOpenGL"); op->set_type("CopyToOpenGL"); op->add_input(cpu_blob); op->add_output(cpu_blob + "_M"); } static void insertCopyFromGPUOp(NetDef& predictNet, const std::string& cpu_blob) { // add argument "is_last" to the last op to signal this is the last operator before the // CopyFromOpenGL op auto* last_op = predictNet.mutable_op(predictNet.op_size() - 1); auto* arg = last_op->add_arg(); arg->set_name("is_last"); arg->set_i(1); auto* op = predictNet.add_op(); op->set_name("CopyFromOpenGL"); op->set_type("CopyFromOpenGL"); op->add_input(cpu_blob + "_M"); op->add_output(cpu_blob); } static NetDef insertInputOutputCopyOps(const NetDef& def, std::unordered_set<std::string>& glOps) { // Do some validation of the outputs. For this version, we require: // - a single input (first element of external_input()) is consumed by the NetDef // - a single output (first element of external_output()) is produced by the NetDef. // - the input is consumed by def.op(0), and this is the only consumer. // - the output is produced by def.op(-1). CAFFE_ENFORCE_GE(def.external_input_size(), 1); CAFFE_ENFORCE_GE(def.external_output_size(), 1); auto analysis = analyzeNet(def); // enforce a single use of the input blob. CAFFE_ENFORCE_GE(def.op_size(), 1); const auto& inputBlob = def.external_input(0); // Enforce that the input blob has a single usage - in the first operator. CAFFE_ENFORCE(analysis.inUsages[inputBlob][0] == (std::vector<size_t>{0})); // Enforce that the external_output(0) blob is produced by the last operator in this sequence. const auto& outputBlob = def.external_output(0); CAFFE_ENFORCE(analysis.ssa.back().outVersions.find(outputBlob) != analysis.ssa.back().outVersions.end()); const auto& outputBlobVersion = analysis.ssa.back().outVersions[outputBlob]; // This should hold true by definition of the SSA analysis. CAFFE_ENFORCE(analysis.inUsages[outputBlob].find(outputBlobVersion) == analysis.inUsages[outputBlob].end()); NetDef mdef; mdef.CopyFrom(def); mdef.clear_op(); std::unordered_map<std::string, std::set<size_t>> cpu_blobs, gpu_blobs; cpu_blobs[def.external_input(0)].insert(0); for (auto i = 0; i < def.op_size(); i++) { const auto& currentOp = def.op(i); if (glOps.count(currentOp.type()) > 0) { // OpenGL Op // insert copyToOpenGLOp for (auto j = 0; j < currentOp.input_size(); j++) { auto& input = currentOp.input(j); auto version = analysis.ssa[i].inVersions[input]; if (cpu_blobs[input].count(version) > 0) { insertCopyToGPUOp(mdef, input); gpu_blobs[input].insert(version); cpu_blobs[input].erase(version); } } auto* op = mdef.add_op(); op->CopyFrom(currentOp); // swap input blob for (auto j = 0; j < currentOp.input_size(); j++) { auto& input = currentOp.input(j); auto version = analysis.ssa[i].inVersions[input]; if (gpu_blobs[input].count(version) > 0) { op->set_input(j, input + "_M"); } } // swap output blob for (auto j = 0; j < currentOp.output_size(); j++) { auto& output = currentOp.output(j); auto version = analysis.ssa[i].outVersions[output]; op->set_output(j, output + "_M"); gpu_blobs[output].insert(version); } // insert copyFromOpenGLOp after the last op if the last op is an OpenGL op if (i == def.op_size() - 1) { insertCopyFromGPUOp(mdef, currentOp.output(0)); } } else { // CPU Op // insert copyFromOpenGLOp for (auto j = 0; j < currentOp.input_size(); j++) { auto& input = currentOp.input(j); auto version = analysis.ssa[i].inVersions[input]; if (gpu_blobs[input].count(version) > 0) { insertCopyFromGPUOp(mdef, input); } } auto* op = mdef.add_op(); op->CopyFrom(currentOp); for (auto j = 0; j < currentOp.output_size(); j++) { auto& output = currentOp.output(j); auto version = analysis.ssa[i].outVersions[output]; cpu_blobs[output].insert(version); } } } return mdef; } static bool tryFuseAdjacentOps(const OperatorDef& currentOp, const OperatorDef& nextOp, OperatorDef* fusedOp, std::unordered_set<std::string>& glOps) { // Check for possible invalid opportunities. if (currentOp.output_size() != 1 || nextOp.output_size() != 1) { return false; } // The fused op cannot be inplace if (currentOp.output(0) != nextOp.input(0) || currentOp.input(0) == nextOp.output(0)) { return false; } static const std::map<std::pair<std::string, std::string>, std::string> fusionOpportunities = { {{"OpenGLInstanceNorm", "OpenGLPRelu"}, "OpenGLInstanceNormPRelu"}, {{"OpenGLConv", "OpenGLPRelu"}, "OpenGLConvPRelu"}, {{"OpenGLConv", "OpenGLRelu"}, "OpenGLConvRelu"}, {{"OpenGLConvTranspose", "OpenGLPRelu"}, "OpenGLConvTransposePRelu"}}; auto it = fusionOpportunities.find({currentOp.type(), nextOp.type()}); if (it == fusionOpportunities.end()) { return false; } glOps.insert(it->second); fusedOp->CopyFrom(currentOp); fusedOp->set_output(0, nextOp.output(0)); fusedOp->set_type(it->second); for (auto i = 1; i < nextOp.input_size(); i++) { fusedOp->add_input(nextOp.input(i)); } return true; } static NetDef runOpenGLFusion(const NetDef& def, std::unordered_set<std::string>& glOps) { CHECK_GE(def.op_size(), 1); NetDef mdef; mdef.CopyFrom(def); mdef.clear_op(); auto i = 0; while (i < def.op_size()) { if (i == def.op_size() - 1) { VLOG(2) << "Last operator, skipping"; auto* op = mdef.add_op(); op->CopyFrom(def.op(i)); i += 1; continue; } const auto& currentOp = def.op(i); const auto& nextOp = def.op(i + 1); OperatorDef fusedOp; if (tryFuseAdjacentOps(currentOp, nextOp, &fusedOp, glOps)) { VLOG(2) << "Found an adjacent fusion for: " << currentOp.type() << ", " << nextOp.type(); // We can fuse. auto* op = mdef.add_op(); op->CopyFrom(fusedOp); i += 2; continue; } VLOG(2) << "No fusion available for: " << currentOp.type() << ", " << nextOp.type(); // Just emit the current type. auto* op = mdef.add_op(); op->CopyFrom(currentOp); i += 1; } return mdef; } void dumpDefForOpenGL(const NetDef& d) { for (const auto& op : d.op()) { LOG(INFO) << op.input(0) << " -> " << op.type() << " -> " << op.output(0); } } // // For debugging // void dumpDefForOpenGL(const NetDef &net) { // for (const auto &op : net.op()) { // printf("***Operator: %s\n", op.type().c_str()); // for (auto input : op.input()) { // printf("\tInput: %s\n", input.c_str()); // } // // for (auto output : op.output()) { // printf("\tOutput: %s\n", output.c_str()); // } // } //} NetDef rewritePredictNetForOpenGL(const NetDef& predictNet, bool useTextureInput, bool useTiling) { CAFFE_ENFORCE_GE(predictNet.op_size(), 1); NetDef net; net.CopyFrom(predictNet); std::unordered_map<std::string, std::string> replacements( {{"OpenGLPackedInt8BGRANHWCToNCHWCStylizerPreprocess", useTextureInput ? "OpenGLTextureToTextureStylizerPreprocess" : "OpenGLTensorToTextureStylizerPreprocess"}, {"OpenGLBRGNCHWCToPackedInt8BGRAStylizerDeprocess", useTextureInput ? "OpenGLTextureToTextureStylizerDeprocess" : "OpenGLTextureToTensorStylizerDeprocess"}}); std::unordered_set<std::string> openGLOps; // Used to insert copy ops bool needCopyOps = false; const auto& opKeyList = CPUOperatorRegistry()->Keys(); auto opKeySet = std::set<std::string>(opKeyList.begin(), opKeyList.end()); #ifdef CAFFE2_ANDROID // TODO: debug InstanceNorm models on Mali devices AndroidGLContext* context = (AndroidGLContext*)GLContext::getGLContext(); if (context->get_platform() == Mali) { opKeySet.erase("OpenGLInstanceNorm"); opKeySet.erase("OpenGLInstanceNormPRelu"); } #endif for (auto i = 0; i < net.op_size(); ++i) { auto* op = net.mutable_op(i); string openGLOp = std::string("OpenGL") + op->type(); if (replacements.count(openGLOp) > 0) { openGLOp = replacements[openGLOp]; } if (opKeySet.find(openGLOp) != opKeySet.end()) { op->set_type(openGLOp); openGLOps.insert(openGLOp); if (useTiling) { auto* arg = op->add_arg(); arg->set_name("tiling"); arg->set_i(1); } } else { needCopyOps = true; } } if (useTextureInput && needCopyOps) { CAFFE_THROW("OpenGL operator missing"); } net = runOpenGLFusion(net, openGLOps); if (net.op(0).type() == replacements["OpenGLPackedInt8BGRANHWCToNCHWCStylizerPreprocess"]) { // For end-to-end testing if (net.op(net.op_size() - 1).type() != replacements["OpenGLBRGNCHWCToPackedInt8BGRAStylizerDeprocess"]) { auto* last_op = net.mutable_op(net.op_size() - 1); auto output = last_op->output(0) + "M"; last_op->set_output(0, output); auto* copy_op = net.add_op(); copy_op->set_name("CopyFromOpenGL"); copy_op->set_type("CopyFromOpenGL"); copy_op->add_input(output); // rename output blob in case input and output blob has the same name copy_op->add_output(net.external_output(0)); } } else { needCopyOps = true; } // copy ops are needed when the input is not a texture if (needCopyOps) { // For non style transfer cases net = insertInputOutputCopyOps(net, openGLOps); } return net; } bool tryConvertToOpenGL(const NetDef& initNet, const NetDef& predictNet, NetDef* glPredictNet, bool useTextureInput) { try { // Throws if unsupported operators are found. *glPredictNet = rewritePredictNetForOpenGL(predictNet, useTextureInput); dumpDefForOpenGL(*glPredictNet); // Throws if unsupported parameters are found. Workspace ws; ws.RunNetOnce(initNet); ws.CreateNet(*glPredictNet); LOG(INFO) << "OpenGL is successfully enabled"; return true; } catch (const std::exception& e) { LOG(ERROR) << "Caught exception trying to convert NetDef to OpenGL: " << e.what(); return false; } } } // namespace caffe2
33.583099
99
0.635632
huiqun2001
118c35a5565a5d9cce8365a3f49be697a7311e5f
7,825
cpp
C++
src/network/bidirectional_network_graph.cpp
jczaplew/fmm
e325196f355b6c7674d1846401fb14b0d9203301
[ "Apache-2.0" ]
545
2017-11-13T11:45:24.000Z
2022-03-31T12:31:54.000Z
src/network/bidirectional_network_graph.cpp
jczaplew/fmm
e325196f355b6c7674d1846401fb14b0d9203301
[ "Apache-2.0" ]
198
2017-12-28T14:54:27.000Z
2022-03-31T10:54:31.000Z
src/network/bidirectional_network_graph.cpp
jczaplew/fmm
e325196f355b6c7674d1846401fb14b0d9203301
[ "Apache-2.0" ]
145
2018-01-17T14:29:42.000Z
2022-03-16T03:06:47.000Z
#include "network/bidirectional_network_graph.hpp" #include "network/heap.hpp" #include "network/network.hpp" #include "network/network_graph.hpp" #include "util/debug.hpp" #include <cmath> #include <iostream> #include <algorithm> #include <unordered_map> #include <queue> using namespace FMM; using namespace FMM::CORE; using namespace FMM::NETWORK; BidirectionalNetworkGraph::BidirectionalNetworkGraph( const Network &network_arg) : NetworkGraph(network_arg){ SPDLOG_INFO("Create invert indices for bidirectional graph"); const std::vector<Edge> &edges = network.get_edges(); SPDLOG_INFO("Reserve index size {}",num_vertices); inverted_indices.resize(num_vertices); SPDLOG_INFO("Construct graph from network edges start"); int N = edges.size(); for (int i = 0; i < N; ++i) { const Edge &edge = edges[i]; inverted_indices[edge.target].push_back(edge.source); } SPDLOG_INFO("Create invert indices done"); }; std::vector<EdgeIndex> BidirectionalNetworkGraph::shortest_path_bidirectional_dijkstra( NodeIndex source, NodeIndex target) const { SPDLOG_TRACE("Shortest path starts"); if (source == target) return {}; Heap fQ,bQ; PredecessorMap pmap; SuccessorMap smap; DistanceMap fdmap,bdmap; fQ.push(source, 0); pmap.insert({source, source}); fdmap.insert({source, 0}); bQ.push(target, 0); smap.insert({target, target}); bdmap.insert({target, 0}); bool forward_search_flag = true; int prev_node = -1; // previous node examined while (!bQ.empty() && !fQ.empty()) { if (forward_search_flag) { HeapNode node = fQ.top(); fQ.pop(); NodeIndex u = node.index; if (u==prev_node) break; forward_search(&fQ,u,node.value,&pmap,&fdmap); forward_search_flag = false; prev_node = u; } else { // backward search HeapNode node = bQ.top(); bQ.pop(); NodeIndex u = node.index; if (u==prev_node) break; backward_search(&bQ,u,node.value,&smap,&bdmap); forward_search_flag = true; prev_node = u; } } // Backtrack from target to source std::vector<EdgeIndex> fpath = back_track(source, prev_node, pmap, fdmap); std::vector<EdgeIndex> bpath = forward_track(prev_node, target, smap, bdmap); fpath.insert(fpath.end(),bpath.begin(),bpath.end()); return fpath; }; void BidirectionalNetworkGraph::single_target_upperbound_dijkstra( NodeIndex target, double delta, SuccessorMap *smap, DistanceMap *dmap) const { Heap Q; // Initialization Q.push(target, 0); smap->insert({target, target}); dmap->insert({target, 0}); double temp_dist = 0; // Dijkstra search while (!Q.empty()) { HeapNode node = Q.top(); Q.pop(); NodeIndex u = node.index; if (node.value > delta) break; backward_search(&Q,u,node.value,smap,dmap); } }; void BidirectionalNetworkGraph::forward_search( Heap *Q, NodeIndex u, double dist, PredecessorMap *pmap, DistanceMap *dmap) const { OutEdgeIterator out_i, out_end; double temp_dist = 0; for (boost::tie(out_i, out_end) = boost::out_edges(u, g); out_i != out_end; ++out_i) { EdgeDescriptor e = *out_i; NodeIndex v = boost::target(e, g); temp_dist = dist + g[e].length; auto iter = dmap->find(v); if (iter != dmap->end()) { // dmap contains node v if (iter->second > temp_dist) { // a smaller distance is found for v (*pmap)[v] = u; (*dmap)[v] = temp_dist; Q->decrease_key(v, temp_dist); } } else { // dmap does not contain v Q->push(v, temp_dist); pmap->insert({v, u}); dmap->insert({v, temp_dist}); } } }; void BidirectionalNetworkGraph::backward_search( Heap *Q, NodeIndex v, double dist, SuccessorMap *smap, DistanceMap *dmap) const { double temp_dist = 0; const std::vector<NodeIndex> &incoming_nodes = inverted_indices[v]; for (NodeIndex u:incoming_nodes) { double cost = 0; int edge_index = get_edge_index(u,v,&cost); temp_dist = dist + cost; auto iter = dmap->find(u); if (iter != dmap->end()) { if (iter->second > temp_dist) { (*smap)[u] = v; (*dmap)[u] = temp_dist; Q->decrease_key(u, temp_dist); }; } else { Q->push(u, temp_dist); smap->insert({u, v}); dmap->insert({u, temp_dist}); } } }; std::vector<EdgeIndex> BidirectionalNetworkGraph::forward_track( NodeIndex source, NodeIndex target, const SuccessorMap &smap, const DistanceMap &dmap) const { SPDLOG_TRACE("forward_track starts"); if (dmap.find(source) == dmap.end()) { return {}; } else { std::vector<EdgeIndex> path; NodeIndex u = source; NodeIndex v = smap.at(u); while (u != target) { double cost = dmap.at(u) - dmap.at(v); path.push_back(get_edge_index(u, v, cost)); u = v; v = smap.at(u); } return path; } }; std::unordered_set<EdgeID> BidirectionalNetworkGraph::search_edges_within_dist_from_node( NodeIndex source, double delta) const { std::unordered_set<EdgeID> result; Heap Q; DistanceMap dmap; Q.push(source, 0); dmap.insert({source, 0}); OutEdgeIterator out_i, out_end; double temp_dist = 0; // Dijkstra search while (!Q.empty()) { HeapNode node = Q.top(); Q.pop(); NodeIndex u = node.index; if (node.value > delta) break; for (boost::tie(out_i, out_end) = boost::out_edges(u, g); out_i != out_end; ++out_i) { EdgeDescriptor e = *out_i; NodeIndex v = boost::target(e, g); temp_dist = node.value + g[e].length; EdgeID eid = get_edge_id(g[e].index); auto iter = dmap.find(v); if (iter != dmap.end()) { // dmap contains node v if (iter->second > temp_dist) { // a smaller distance is found for v dmap[v] = temp_dist; Q.decrease_key(v, temp_dist); }; if (temp_dist<=delta){ result.insert(eid); } } else { if (temp_dist <= delta) { Q.push(v, temp_dist); dmap.insert({v, temp_dist}); result.insert(eid); } } } } return result; }; std::unordered_set<EdgeID> BidirectionalNetworkGraph::search_edges_within_dist_to_node( NodeIndex target, double delta) const { std::unordered_set<EdgeID> result; Heap Q; DistanceMap dmap; Q.push(target, 0); dmap.insert({target, 0}); OutEdgeIterator out_i, out_end; double temp_dist = 0; // Dijkstra search while (!Q.empty()) { HeapNode node = Q.top(); Q.pop(); NodeIndex v = node.index; if (node.value > delta) break; const std::vector<NodeIndex> &incoming_nodes = inverted_indices[v]; for (NodeIndex u:incoming_nodes) { double cost = 0; // Cost is updated in the command below int edge_index = get_edge_index(u,v,&cost); EdgeID eid = get_edge_id(edge_index); double temp_dist = node.value + cost; auto iter = dmap.find(u); if (iter != dmap.end()) { if (iter->second > temp_dist) { dmap[u] = temp_dist; Q.decrease_key(u, temp_dist); }; if (temp_dist<=delta){ result.insert(eid); } } else { if (temp_dist <= delta) { Q.push(u, temp_dist); dmap.insert({u, temp_dist}); result.insert(eid); } } } } return result; }; std::unordered_set<EdgeID> BidirectionalNetworkGraph::search_edges_within_dist_ft_edge( EdgeID eid, double dist) const { const Edge& edge = get_edge(eid); NodeIndex source = edge.source; NodeIndex target = edge.target; std::unordered_set<EdgeID> result = search_edges_within_dist_from_node(target,dist); std::unordered_set<EdgeID> temp = search_edges_within_dist_to_node(source,dist); result.insert (temp.begin(), temp.end()); return result; };
28.874539
77
0.632971
jczaplew
118c6b9e5f6942c6117d85d95fff59575ff20bd2
2,551
hpp
C++
rocprim/include/rocprim/device/detail/ordered_block_id.hpp
yoichiyoshida/rocPRIM
024f15a9106ad2e9dd831601ed5a017d99382e20
[ "MIT" ]
null
null
null
rocprim/include/rocprim/device/detail/ordered_block_id.hpp
yoichiyoshida/rocPRIM
024f15a9106ad2e9dd831601ed5a017d99382e20
[ "MIT" ]
null
null
null
rocprim/include/rocprim/device/detail/ordered_block_id.hpp
yoichiyoshida/rocPRIM
024f15a9106ad2e9dd831601ed5a017d99382e20
[ "MIT" ]
null
null
null
// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #ifndef ROCPRIM_DEVICE_DETAIL_ORDERED_BLOCK_ID_HPP_ #define ROCPRIM_DEVICE_DETAIL_ORDERED_BLOCK_ID_HPP_ #include <type_traits> #include <limits> #include "../../detail/various.hpp" #include "../../intrinsics.hpp" #include "../../types.hpp" BEGIN_ROCPRIM_NAMESPACE namespace detail { // Helper struct for generating ordered unique ids for blocks in a grid. template<class T /* id type */ = unsigned int> struct ordered_block_id { static_assert(std::is_integral<T>::value, "T must be integer"); using id_type = T; // shared memory temporary storage type struct storage_type { id_type id; }; ROCPRIM_HOST static inline ordered_block_id create(id_type * id) { ordered_block_id ordered_id; ordered_id.id = id; return ordered_id; } ROCPRIM_HOST static inline size_t get_storage_size() { return sizeof(id_type); } ROCPRIM_DEVICE inline void reset() { *id = static_cast<id_type>(0); } ROCPRIM_DEVICE inline id_type get(unsigned int tid, storage_type& storage) { if(tid == 0) { storage.id = ::rocprim::detail::atomic_add(this->id, 1); } ::rocprim::syncthreads(); return storage.id; } id_type* id; }; } // end of detail namespace END_ROCPRIM_NAMESPACE #endif // ROCPRIM_DEVICE_DETAIL_ORDERED_BLOCK_ID_HPP_
28.988636
80
0.705214
yoichiyoshida
118ca1e41e8a0d525fe38b440e681d65243e8549
14,220
cc
C++
src/components/application_manager/test/request_info_test.cc
Sohei-Suzuki-Nexty/sdl_core
68f082169e0a40fccd9eb0db3c83911c28870f07
[ "BSD-3-Clause" ]
249
2015-01-15T16:50:53.000Z
2022-03-24T13:23:34.000Z
src/components/application_manager/test/request_info_test.cc
Sohei-Suzuki-Nexty/sdl_core
68f082169e0a40fccd9eb0db3c83911c28870f07
[ "BSD-3-Clause" ]
2,917
2015-01-12T16:17:49.000Z
2022-03-31T11:57:47.000Z
src/components/application_manager/test/request_info_test.cc
Sohei-Suzuki-Nexty/sdl_core
68f082169e0a40fccd9eb0db3c83911c28870f07
[ "BSD-3-Clause" ]
306
2015-01-12T09:23:20.000Z
2022-01-28T18:06:30.000Z
/* * Copyright (c) 2015, Ford Motor Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the Ford Motor Company nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "application_manager/request_info.h" #include <iostream> #include <limits> #include <vector> #include "application_manager/mock_request.h" #include "gmock/gmock.h" namespace request_info = application_manager::request_controller; namespace test { namespace components { namespace application_manager_test { class TestRequestInfo : public request_info::RequestInfo { public: TestRequestInfo(request_info::RequestPtr request, const RequestType request_type, const date_time::TimeDuration& start_time, const uint64_t timeout_msec) : RequestInfo(request, request_type, start_time, timeout_msec) {} void SetEndTime(const date_time::TimeDuration& end_time) { end_time_ = end_time; } }; class RequestInfoTest : public ::testing::Test { protected: virtual void SetUp() OVERRIDE { count_of_requests_for_test_ = 1000; hmi_connection_key_ = 0; mobile_connection_key1_ = 65431; mobile_connection_key2_ = 65123; mobile_correlation_id = 111; default_timeout_ = 10; } request_info::RequestInfoSet request_info_set_; uint32_t count_of_requests_for_test_; uint32_t hmi_connection_key_; uint32_t mobile_connection_key1_; uint32_t mobile_connection_key2_; uint32_t default_timeout_; uint32_t mobile_correlation_id; std::shared_ptr<TestRequestInfo> CreateTestInfo( uint32_t connection_key, uint32_t correlation_id, request_info::RequestInfo::RequestType request_type, const date_time::TimeDuration& start_time, uint64_t timeout_msec) { std::shared_ptr<MockRequest> mock_request = std::make_shared<MockRequest>(connection_key, correlation_id); std::shared_ptr<TestRequestInfo> request = std::make_shared<TestRequestInfo>( mock_request, request_type, start_time, timeout_msec); return request; } }; TEST_F(RequestInfoTest, RequestInfoEqualEndTime) { const date_time::TimeDuration& time = date_time::getCurrentTime(); for (uint32_t i = 0; i < count_of_requests_for_test_; ++i) { std::shared_ptr<TestRequestInfo> request = CreateTestInfo( i, i, request_info::RequestInfo::MobileRequest, time, default_timeout_); request->SetEndTime(time); EXPECT_TRUE(request_info_set_.Add(request)); } EXPECT_EQ(count_of_requests_for_test_, request_info_set_.Size()); } TEST_F(RequestInfoTest, AddRemoveHMIRequests) { for (uint32_t i = 0; i < count_of_requests_for_test_; ++i) { std::shared_ptr<TestRequestInfo> request = CreateTestInfo(hmi_connection_key_, i, request_info::RequestInfo::HMIRequest, date_time::getCurrentTime(), default_timeout_); EXPECT_TRUE(request_info_set_.Add(request)); EXPECT_TRUE(request_info_set_.RemoveRequest(request)); } EXPECT_EQ(0u, request_info_set_.Size()); } TEST_F(RequestInfoTest, AddHMIRequests_RemoveAllRequests) { std::vector<std::shared_ptr<TestRequestInfo> > requests; // Add hmi requests for (uint32_t i = 0; i < count_of_requests_for_test_; ++i) { std::shared_ptr<TestRequestInfo> request = CreateTestInfo(hmi_connection_key_, i, request_info::RequestInfo::HMIRequest, date_time::getCurrentTime(), default_timeout_); requests.push_back(request); EXPECT_TRUE(request_info_set_.Add(request)); } EXPECT_EQ(count_of_requests_for_test_, request_info_set_.Size()); // Delete every request std::vector<std::shared_ptr<TestRequestInfo> >::iterator req_it = requests.begin(); for (; req_it != requests.end(); ++req_it) { EXPECT_TRUE(request_info_set_.RemoveRequest(*req_it)); } EXPECT_EQ(0u, request_info_set_.Size()); // Delete requests by connection key req_it = requests.begin(); for (; req_it != requests.end(); ++req_it) { EXPECT_TRUE(request_info_set_.Add(*req_it)); } EXPECT_EQ(count_of_requests_for_test_, request_info_set_.Size()); EXPECT_EQ(count_of_requests_for_test_, request_info_set_.RemoveByConnectionKey(hmi_connection_key_)); EXPECT_EQ(0u, request_info_set_.Size()); } TEST_F(RequestInfoTest, AddMobileRequests_RemoveMobileRequests) { std::shared_ptr<TestRequestInfo> mobile_request1 = CreateTestInfo(mobile_connection_key1_, 12345, request_info::RequestInfo::MobileRequest, date_time::getCurrentTime(), default_timeout_); EXPECT_TRUE(request_info_set_.Add(mobile_request1)); std::shared_ptr<TestRequestInfo> mobile_request2 = CreateTestInfo(mobile_connection_key2_, 54321, request_info::RequestInfo::MobileRequest, date_time::getCurrentTime(), default_timeout_); EXPECT_TRUE(request_info_set_.Add(mobile_request2)); EXPECT_EQ(2u, request_info_set_.Size()); EXPECT_EQ(2u, request_info_set_.RemoveMobileRequests()); EXPECT_EQ(0u, request_info_set_.Size()); } TEST_F(RequestInfoTest, AddMobileRequests_RemoveMobileRequestsByConnectionKey) { std::vector<std::shared_ptr<TestRequestInfo> > requests; const uint32_t count_of_mobile_request1 = 200; const uint32_t count_of_mobile_request2 = 100; for (uint32_t i = 0; i < count_of_mobile_request1; ++i) { std::shared_ptr<TestRequestInfo> mobile_request1 = CreateTestInfo(mobile_connection_key1_, i, request_info::RequestInfo::MobileRequest, date_time::getCurrentTime(), default_timeout_); requests.push_back(mobile_request1); EXPECT_TRUE(request_info_set_.Add(mobile_request1)); } EXPECT_EQ(count_of_mobile_request1, request_info_set_.Size()); for (uint32_t i = 0; i < count_of_mobile_request2; ++i) { std::shared_ptr<TestRequestInfo> mobile_request2 = CreateTestInfo(mobile_connection_key2_, i, request_info::RequestInfo::MobileRequest, date_time::getCurrentTime(), default_timeout_); requests.push_back(mobile_request2); EXPECT_TRUE(request_info_set_.Add(mobile_request2)); } EXPECT_EQ(count_of_mobile_request1 + count_of_mobile_request2, request_info_set_.Size()); EXPECT_EQ(count_of_mobile_request1, request_info_set_.RemoveByConnectionKey(mobile_connection_key1_)); EXPECT_EQ(count_of_mobile_request2, request_info_set_.RemoveByConnectionKey(mobile_connection_key2_)); EXPECT_EQ(0u, request_info_set_.Size()); } TEST_F(RequestInfoTest, RequestInfoSetFront) { for (uint32_t i = 0; i < count_of_requests_for_test_; ++i) { std::shared_ptr<TestRequestInfo> request = CreateTestInfo(mobile_connection_key1_, i, request_info::RequestInfo::HMIRequest, date_time::getCurrentTime(), i); request_info_set_.Add(request); } for (uint32_t i = 1; i < count_of_requests_for_test_; ++i) { request_info::RequestInfoPtr request_info = request_info_set_.Front(); EXPECT_TRUE(request_info.use_count() != 0); request_info = request_info_set_.FrontWithNotNullTimeout(); EXPECT_TRUE(request_info.use_count() != 0); EXPECT_TRUE(request_info_set_.RemoveRequest(request_info)); } EXPECT_EQ(1u, request_info_set_.Size()); EXPECT_EQ(1u, request_info_set_.RemoveByConnectionKey(mobile_connection_key1_)); EXPECT_EQ(0u, request_info_set_.Size()); } TEST_F(RequestInfoTest, RequestInfoSetFind) { std::vector<std::pair<uint32_t, uint32_t> > appid_connection_id; for (uint32_t i = 0; i < count_of_requests_for_test_; ++i) { appid_connection_id.push_back( std::pair<uint32_t, uint32_t>(i, count_of_requests_for_test_ - i)); } std::vector<std::pair<uint32_t, uint32_t> >::iterator req_it = appid_connection_id.begin(); const std::vector<std::pair<uint32_t, uint32_t> >::iterator end = appid_connection_id.end(); for (; req_it != end; ++req_it) { std::shared_ptr<TestRequestInfo> request = CreateTestInfo(req_it->first, req_it->second, request_info::RequestInfo::HMIRequest, date_time::getCurrentTime(), 10); EXPECT_TRUE(request_info_set_.Add(request)); } request_info::RequestInfoPtr request = request_info_set_.Find( count_of_requests_for_test_, count_of_requests_for_test_); EXPECT_FALSE(request.use_count() != 0); req_it = appid_connection_id.begin(); for (; req_it != end; ++req_it) { request_info::RequestInfoPtr request = request_info_set_.Find(req_it->first, req_it->second); EXPECT_TRUE(request.use_count() != 0); EXPECT_TRUE(request_info_set_.RemoveRequest(request)); request = request_info_set_.Find(req_it->first, req_it->second); EXPECT_FALSE(request.use_count() != 0); } EXPECT_EQ(0u, request_info_set_.Size()); } TEST_F(RequestInfoTest, RequestInfoSetEqualHash) { request_info::RequestInfoSet request_info_set; const uint32_t connection_key = 65483; const uint32_t corr_id = 65483; std::shared_ptr<TestRequestInfo> request = CreateTestInfo(connection_key, corr_id, request_info::RequestInfo::HMIRequest, date_time::getCurrentTime(), 10); EXPECT_TRUE(request_info_set.Add(request)); EXPECT_FALSE(request_info_set.Add(request)); EXPECT_FALSE(request_info_set.Add(request)); EXPECT_EQ(1u, request_info_set.Size()); request_info::RequestInfoPtr found = request_info_set.Find(connection_key, corr_id); EXPECT_TRUE(found.use_count() != 0); EXPECT_TRUE(request_info_set.RemoveRequest(found)); EXPECT_EQ(0u, request_info_set.Size()); EXPECT_TRUE(request_info_set.Add(request)); EXPECT_FALSE(request_info_set.Add(request)); found = request_info_set.FrontWithNotNullTimeout(); EXPECT_TRUE(found.use_count() != 0); EXPECT_TRUE(request_info_set.RemoveRequest(found)); found = request_info_set.FrontWithNotNullTimeout(); EXPECT_FALSE(found.use_count() != 0); found = request_info_set.Front(); EXPECT_FALSE(found.use_count() != 0); EXPECT_EQ(0u, request_info_set.Size()); } TEST_F(RequestInfoTest, EndTimeisExpired) { date_time::TimeDuration time = date_time::getCurrentTime(); // get just the seconds part of the current time date_time::TimeDuration not_expired = date_time::seconds(date_time::getSecs(date_time::getCurrentTime())); not_expired += date_time::microseconds(std::numeric_limits<time_t>::min()); date_time::TimeDuration expired = date_time::seconds(date_time::getSecs(date_time::getCurrentTime())); expired += date_time::microseconds(std::numeric_limits<time_t>::max()); std::shared_ptr<TestRequestInfo> request = CreateTestInfo(mobile_connection_key1_, mobile_correlation_id, request_info::RequestInfo::MobileRequest, time, default_timeout_); request->SetEndTime(expired); EXPECT_FALSE(request->isExpired()); request->SetEndTime(not_expired); EXPECT_TRUE(request->isExpired()); } TEST_F(RequestInfoTest, UpdateEndTime) { date_time::TimeDuration time = date_time::getCurrentTime(); std::shared_ptr<TestRequestInfo> request = CreateTestInfo(mobile_connection_key1_, mobile_correlation_id, request_info::RequestInfo::MobileRequest, time, default_timeout_); request->SetEndTime(time); request->updateEndTime(); date_time::TimeDuration last_time = request->end_time(); EXPECT_LE(date_time::getSecs(time), date_time::getSecs(last_time)); } TEST_F(RequestInfoTest, UpdateTimeOut) { date_time::TimeDuration time = date_time::getCurrentTime(); std::shared_ptr<TestRequestInfo> request = CreateTestInfo(mobile_connection_key1_, mobile_correlation_id, request_info::RequestInfo::MobileRequest, time, default_timeout_); request->SetEndTime(time); request->updateEndTime(); request->updateTimeOut(100); time = date_time::getCurrentTime(); date_time::TimeDuration last_time = request->end_time(); EXPECT_NEAR( date_time::getSecs(time) + 100, date_time::getSecs(last_time), 500); } } // namespace application_manager_test } // namespace components } // namespace test
39.065934
80
0.702672
Sohei-Suzuki-Nexty
1193aedfa533cb891972c4b3a7f6b8ae4a9be8d9
2,346
cpp
C++
src/Color_tester/Color_tester_view.cpp
InzynierDomu/LED_tester
27e09fb27ac200620d8610416e1ae9e777543a0a
[ "MIT" ]
null
null
null
src/Color_tester/Color_tester_view.cpp
InzynierDomu/LED_tester
27e09fb27ac200620d8610416e1ae9e777543a0a
[ "MIT" ]
null
null
null
src/Color_tester/Color_tester_view.cpp
InzynierDomu/LED_tester
27e09fb27ac200620d8610416e1ae9e777543a0a
[ "MIT" ]
null
null
null
/** * @file Color_tester_view.cpp * @brief UI view for color picker mode * @author by Szymon Markiewicz * @details http://www.inzynierdomu.pl/ * @date 03-2022 */ #include "Color_tester_view.h" #include <cstdlib> #include <iomanip> #include <sstream> #include <string> namespace Color_tester { /** * @brief constructor * @param hal: hardware layer * @param model: data related to PWM characteristics mode */ Color_tester_view::Color_tester_view(IHal& hal, Color_tester_model& model) : m_hal(hal) , m_model(model) , m_cursor_position_x{70, 120, 170} , m_shift_from_cursor(2) {} /** * @brief print all for this mode after changing mode */ void Color_tester_view::print_screen() { m_hal.clear_screen(); m_hal.draw_cursor(58, m_cursor_position_x[static_cast<Cursor_position_name>(m_model.position)] - m_shift_from_cursor); m_hal.print_text("R", 60, 70); m_hal.print_text("G", 60, 120); m_hal.print_text("B", 60, 170); m_hal.draw_frame(199, 79, 82, 82); print_color(0); print_color(1); print_color(2); update_color(); } /** * @brief clear and print color saturation */ void Color_tester_view::update_color_saturation() { m_hal.clear_part_screen(85, m_cursor_position_x[m_model.position], 42, 19); print_color(m_model.position); update_color(); } /** * @brief draw rectangle cursor on current color */ void Color_tester_view::update_cursor() { m_hal.draw_cursor(58, m_cursor_position_x[static_cast<Cursor_position_name>(m_model.position)] - m_shift_from_cursor); } /** * @brief clear rectangle cursor */ void Color_tester_view::clear_cursor() { m_hal.clear_cursor(58, m_cursor_position_x[static_cast<Cursor_position_name>(m_model.position)] - m_shift_from_cursor); } void Color_tester_view::update_color() { m_hal.draw_rect(200, 80, 80, 80, m_model.color.color_short); m_hal.clear_part_screen(179, 170, 130, 22); std::string color_val = "0x"; std::stringstream stream; stream << std::setfill('0') << std::setw(6) << std::uppercase << std::hex << m_model.color.color_long; color_val += stream.str(); m_hal.print_text(color_val, 179, 170); } void Color_tester_view::print_color(uint8_t position) { std::string color_val = std::to_string(m_model.color.color_saturation[position]); m_hal.print_text(color_val, 85, m_cursor_position_x[position]); } } // namespace Color_tester
24.4375
121
0.733589
InzynierDomu
1198b2a29e5d3346bf767d17ac195f249db9431a
4,469
cpp
C++
source/Scene.cpp
Kair0z/Custom-Raytracer
5130c389776d75ba93f2748e25e2c24239dddd2f
[ "MIT" ]
null
null
null
source/Scene.cpp
Kair0z/Custom-Raytracer
5130c389776d75ba93f2748e25e2c24239dddd2f
[ "MIT" ]
null
null
null
source/Scene.cpp
Kair0z/Custom-Raytracer
5130c389776d75ba93f2748e25e2c24239dddd2f
[ "MIT" ]
null
null
null
#include "pch.h" #include "Scene.h" #include "PSphere.h" #include "PPlane.h" #include "LDirection.h" #include "LPoint.h" #include "Camera.h" #include <iostream> #include <iomanip> #include "SDL.h" #include "PTriangle.h" #include "PMesh.h" #include "CatchInput.h" Scene::Scene() : m_ActiveCameraIdx{} { } Scene::~Scene() { Cleanup(); } void Scene::Cleanup() { for (Primitive* pElement : m_pElements) { delete pElement; pElement = nullptr; } for (Light* pLight : m_pLights) { delete pLight; pLight = nullptr; } for (Camera* pCamera : m_pCameras) { delete pCamera; pCamera = nullptr; } } void Scene::Update(float elapsedSec) { for (Primitive* pElement : m_pElements) { if (dynamic_cast<PTriangle*>(pElement) != nullptr) { dynamic_cast<PTriangle*>(pElement)->Rotate(0.f, elapsedSec, 0.f); } PMesh* mesh = dynamic_cast<PMesh*>(pElement); if (mesh != nullptr) { mesh->Rotate(0.f, elapsedSec, 0.f); } } for (Light* pLight : m_pLights) { pLight->Update(elapsedSec); } } bool Scene::HasCamera() const { return bool(m_pCameras.size()); } void Scene::ProcessInput(float elapsedSec) { switch (CatchInput::GetAction()) { case Action::ToggleCamera: ++m_ActiveCameraIdx; if (m_ActiveCameraIdx >= m_pCameras.size()) m_ActiveCameraIdx = 0; break; case Action::ResetCameras: for (Camera* pCam : m_pCameras) { pCam->ResetPosition(); } break; } m_pCameras[m_ActiveCameraIdx]->ProcessInput(elapsedSec); } void Scene::AddElement(PSphere* pSphere) { m_pElements.emplace_back(pSphere); } void Scene::AddElement(PPlane* pPlane) { m_pElements.emplace_back(pPlane); } void Scene::AddElement(LPoint* pPointLight) { m_pLights.emplace_back(pPointLight); } void Scene::AddElement(LDirection* pDirectionLight) { m_pLights.emplace_back(pDirectionLight); } void Scene::AddElement(PTriangle* pTriangle) { m_pElements.emplace_back(pTriangle); } void Scene::AddElement(PMesh* pMesh) { m_pElements.emplace_back(pMesh); } RGBColor Scene::Shade(const HitInfo& hitInfo, const FVector3& toView, bool hardShadowsOn) const { RGBColor result{}; RGBColor materialShade{}; for (Light* pLight : m_pLights) { if (pLight->IsOn()) { float dot = -Elite::Dot(hitInfo.m_Normal, pLight->GetDirection(hitInfo)); // Shadows affect endvalue: // If Hardshadows on --> check also if Point in sight, else, go on to next light OR dot < 0 if (hardShadowsOn && !PointInSight(pLight, hitInfo) || dot < 0) { // --> If hardshadowed --> Biradiancevalue becomes 0 // --> If dot < 0 --> Biradiancevalue becomes 0 dot = 0.f; } // Biradiance affects endvalue + (lambert cosine law): result += pLight->BiradianceValue(hitInfo) * dot; // Material affects endvalue: materialShade += hitInfo.m_pMaterial->Shade(hitInfo, pLight->GetDirection(hitInfo), toView); } } result *= materialShade; return result; } bool Scene::PointInSight(const Light* pLight, const HitInfo& hitInfo) const { // Just so Hit() can input an unused hitinfo (we don't need the point, just need to know if that spot is in shadow) HitInfo hitCopy{ hitInfo }; FVector3 toLightVector{ -pLight->GetDirection(hitCopy) }; float lightDistance = Elite::Distance(hitCopy.m_HitPoint, pLight->GetPos()); Ray pointToLight{ hitCopy.m_HitPoint, toLightVector, 0.01f, lightDistance, Raytype::Shadow }; // If there is a hit --> Point is not in light if (Hit(pointToLight, hitCopy) != nullptr) { return false; } // If there is no hit --> Point is in light else { return true; } } Primitive* Scene::Hit(const Ray& ray, HitInfo& hitInfo) const { // order of hit setup Primitive* closestObj{ nullptr }; float closestT{ ray.m_Max }; HitInfo closestHitInfo{}; // Process-Hit (check every Primitive in graph) for (Primitive* pElement : m_pElements) { if (pElement->IsVisible()) { if (pElement->Hit(ray, closestHitInfo)) { if (closestHitInfo.m_T < closestT) { closestObj = pElement; hitInfo = closestHitInfo; closestT = closestHitInfo.m_T; } } } } return closestObj; } void Scene::AddCamera(Camera* cam, bool isNewActive) { m_pCameras.push_back(cam); if (isNewActive || m_pCameras.size() == 1) // if new active OR first camera in the scene { m_ActiveCameraIdx = int(m_pCameras.size()) - 1; // Idx of last added element } } const Camera* Scene::GetActiveCam() const { if (m_pCameras.empty()) return nullptr; return m_pCameras[m_ActiveCameraIdx]; }
20.040359
116
0.691206
Kair0z
119aef15434d6416111b2583a82e12f23d1b51a9
6,939
cpp
C++
tcaplusdb/src/v20190823/model/ServerDetailInfo.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
tcaplusdb/src/v20190823/model/ServerDetailInfo.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
tcaplusdb/src/v20190823/model/ServerDetailInfo.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/tcaplusdb/v20190823/model/ServerDetailInfo.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Tcaplusdb::V20190823::Model; using namespace std; ServerDetailInfo::ServerDetailInfo() : m_serverUidHasBeenSet(false), m_machineTypeHasBeenSet(false), m_memoryRateHasBeenSet(false), m_diskRateHasBeenSet(false), m_readNumHasBeenSet(false), m_writeNumHasBeenSet(false) { } CoreInternalOutcome ServerDetailInfo::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("ServerUid") && !value["ServerUid"].IsNull()) { if (!value["ServerUid"].IsString()) { return CoreInternalOutcome(Core::Error("response `ServerDetailInfo.ServerUid` IsString=false incorrectly").SetRequestId(requestId)); } m_serverUid = string(value["ServerUid"].GetString()); m_serverUidHasBeenSet = true; } if (value.HasMember("MachineType") && !value["MachineType"].IsNull()) { if (!value["MachineType"].IsString()) { return CoreInternalOutcome(Core::Error("response `ServerDetailInfo.MachineType` IsString=false incorrectly").SetRequestId(requestId)); } m_machineType = string(value["MachineType"].GetString()); m_machineTypeHasBeenSet = true; } if (value.HasMember("MemoryRate") && !value["MemoryRate"].IsNull()) { if (!value["MemoryRate"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `ServerDetailInfo.MemoryRate` IsInt64=false incorrectly").SetRequestId(requestId)); } m_memoryRate = value["MemoryRate"].GetInt64(); m_memoryRateHasBeenSet = true; } if (value.HasMember("DiskRate") && !value["DiskRate"].IsNull()) { if (!value["DiskRate"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `ServerDetailInfo.DiskRate` IsInt64=false incorrectly").SetRequestId(requestId)); } m_diskRate = value["DiskRate"].GetInt64(); m_diskRateHasBeenSet = true; } if (value.HasMember("ReadNum") && !value["ReadNum"].IsNull()) { if (!value["ReadNum"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `ServerDetailInfo.ReadNum` IsInt64=false incorrectly").SetRequestId(requestId)); } m_readNum = value["ReadNum"].GetInt64(); m_readNumHasBeenSet = true; } if (value.HasMember("WriteNum") && !value["WriteNum"].IsNull()) { if (!value["WriteNum"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `ServerDetailInfo.WriteNum` IsInt64=false incorrectly").SetRequestId(requestId)); } m_writeNum = value["WriteNum"].GetInt64(); m_writeNumHasBeenSet = true; } return CoreInternalOutcome(true); } void ServerDetailInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_serverUidHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ServerUid"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_serverUid.c_str(), allocator).Move(), allocator); } if (m_machineTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "MachineType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_machineType.c_str(), allocator).Move(), allocator); } if (m_memoryRateHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "MemoryRate"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_memoryRate, allocator); } if (m_diskRateHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DiskRate"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_diskRate, allocator); } if (m_readNumHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ReadNum"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_readNum, allocator); } if (m_writeNumHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "WriteNum"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_writeNum, allocator); } } string ServerDetailInfo::GetServerUid() const { return m_serverUid; } void ServerDetailInfo::SetServerUid(const string& _serverUid) { m_serverUid = _serverUid; m_serverUidHasBeenSet = true; } bool ServerDetailInfo::ServerUidHasBeenSet() const { return m_serverUidHasBeenSet; } string ServerDetailInfo::GetMachineType() const { return m_machineType; } void ServerDetailInfo::SetMachineType(const string& _machineType) { m_machineType = _machineType; m_machineTypeHasBeenSet = true; } bool ServerDetailInfo::MachineTypeHasBeenSet() const { return m_machineTypeHasBeenSet; } int64_t ServerDetailInfo::GetMemoryRate() const { return m_memoryRate; } void ServerDetailInfo::SetMemoryRate(const int64_t& _memoryRate) { m_memoryRate = _memoryRate; m_memoryRateHasBeenSet = true; } bool ServerDetailInfo::MemoryRateHasBeenSet() const { return m_memoryRateHasBeenSet; } int64_t ServerDetailInfo::GetDiskRate() const { return m_diskRate; } void ServerDetailInfo::SetDiskRate(const int64_t& _diskRate) { m_diskRate = _diskRate; m_diskRateHasBeenSet = true; } bool ServerDetailInfo::DiskRateHasBeenSet() const { return m_diskRateHasBeenSet; } int64_t ServerDetailInfo::GetReadNum() const { return m_readNum; } void ServerDetailInfo::SetReadNum(const int64_t& _readNum) { m_readNum = _readNum; m_readNumHasBeenSet = true; } bool ServerDetailInfo::ReadNumHasBeenSet() const { return m_readNumHasBeenSet; } int64_t ServerDetailInfo::GetWriteNum() const { return m_writeNum; } void ServerDetailInfo::SetWriteNum(const int64_t& _writeNum) { m_writeNum = _writeNum; m_writeNumHasBeenSet = true; } bool ServerDetailInfo::WriteNumHasBeenSet() const { return m_writeNumHasBeenSet; }
27.535714
146
0.686987
suluner
119c658607b40f46704273dfd4a72b3a4d73fb3f
256
hpp
C++
include/RED4ext/Scripting/Natives/Generated/world/ProxyMeshDependencyMode.hpp
flibX0r/RED4ext.SDK
18d075ef7559e35d8b02dc2e00a03ccc7ff4d77b
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/world/ProxyMeshDependencyMode.hpp
flibX0r/RED4ext.SDK
18d075ef7559e35d8b02dc2e00a03ccc7ff4d77b
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/world/ProxyMeshDependencyMode.hpp
flibX0r/RED4ext.SDK
18d075ef7559e35d8b02dc2e00a03ccc7ff4d77b
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> namespace RED4ext { namespace world { enum class ProxyMeshDependencyMode : uint8_t { Auto = 0, Discard = 1, }; } // namespace world } // namespace RED4ext
16
57
0.707031
flibX0r
119efbbd2ade10a020c4b26ff837aaba752a0919
3,808
cpp
C++
dispenso/task_set.cpp
jeffamstutz/dispenso
0fb1db63a386c1ba59cd761677af6e9f0052c61c
[ "MIT" ]
1
2022-01-26T01:12:01.000Z
2022-01-26T01:12:01.000Z
dispenso/task_set.cpp
jeffamstutz/dispenso
0fb1db63a386c1ba59cd761677af6e9f0052c61c
[ "MIT" ]
null
null
null
dispenso/task_set.cpp
jeffamstutz/dispenso
0fb1db63a386c1ba59cd761677af6e9f0052c61c
[ "MIT" ]
null
null
null
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE.md file in the root directory of this source tree. #include "task_set.h" namespace dispenso { void ConcurrentTaskSet::trySetCurrentException() { #if defined(__cpp_exceptions) auto status = kUnset; if (guardException_.compare_exchange_strong(status, kSetting, std::memory_order_acq_rel)) { exception_ = std::current_exception(); guardException_.store(kSet, std::memory_order_release); } #endif // __cpp_exceptions } void TaskSet::trySetCurrentException() { #if defined(__cpp_exceptions) auto status = kUnset; if (guardException_.compare_exchange_strong(status, kSetting, std::memory_order_acq_rel)) { exception_ = std::current_exception(); guardException_.store(kSet, std::memory_order_release); } #endif // __cpp_exceptions } inline void ConcurrentTaskSet::testAndResetException() { #if defined(__cpp_exceptions) if (guardException_.load(std::memory_order_acquire) == kSet) { auto exception = std::move(exception_); guardException_.store(kUnset, std::memory_order_release); std::rethrow_exception(exception); } #endif // __cpp_exceptions } inline void TaskSet::testAndResetException() { #if defined(__cpp_exceptions) if (guardException_.load(std::memory_order_acquire) == kSet) { auto exception = std::move(exception_); guardException_.store(kUnset, std::memory_order_release); std::rethrow_exception(exception); } #endif // __cpp_exceptions } void ConcurrentTaskSet::wait() { // Steal work until our set is unblocked. Note that this is not the // fastest possible way to unblock the current set, but it will alleviate // deadlock, and should provide decent throughput for all waiters. // The deadlock scenario mentioned goes as follows: N threads in the // ThreadPool. Each thread is running code that is using TaskSets. No // progress could be made without stealing. while (outstandingTaskCount_.load(std::memory_order_acquire)) { if (!pool_.tryExecuteNext()) { std::this_thread::yield(); } } testAndResetException(); } bool ConcurrentTaskSet::tryWait(size_t maxToExecute) { while (outstandingTaskCount_.load(std::memory_order_acquire) && maxToExecute--) { if (!pool_.tryExecuteNext()) { break; } } // Must check completion prior to checking exceptions, otherwise there could be a case where // exceptions are checked, then an exception is propagated, and then we return whether all items // have been completed, thus dropping the exception. if (outstandingTaskCount_.load(std::memory_order_acquire)) { return false; } testAndResetException(); return true; } void TaskSet::wait() { // Steal work until our set is unblocked. // The deadlock scenario mentioned goes as follows: N threads in the // ThreadPool. Each thread is running code that is using TaskSets. No // progress could be made without stealing. while (pool_.tryExecuteNextFromProducerToken(token_)) { } while (outstandingTaskCount_.load(std::memory_order_acquire)) { std::this_thread::yield(); } testAndResetException(); } bool TaskSet::tryWait(size_t maxToExecute) { while (outstandingTaskCount_.load(std::memory_order_acquire) && maxToExecute--) { if (!pool_.tryExecuteNextFromProducerToken(token_)) { break; } } // Must check completion prior to checking exceptions, otherwise there could be a case where // exceptions are checked, then an exception is propagated, and then we return whether all items // have been completed, thus dropping the exception. if (outstandingTaskCount_.load(std::memory_order_acquire)) { return false; } testAndResetException(); return true; } } // namespace dispenso
32
98
0.738445
jeffamstutz
11a05285c205c1ee5abb44736ee54f2c8e9e7516
1,207
cpp
C++
src/cmake_project/impl/cprj_includes_parser_context.cpp
lpea/cppinclude
dc126c6057d2fe30569e6e86f66d2c8eebb50212
[ "MIT" ]
177
2020-08-24T19:20:35.000Z
2022-03-27T01:58:04.000Z
src/cmake_project/impl/cprj_includes_parser_context.cpp
lpea/cppinclude
dc126c6057d2fe30569e6e86f66d2c8eebb50212
[ "MIT" ]
15
2020-08-30T17:59:42.000Z
2022-01-12T11:14:10.000Z
src/cmake_project/impl/cprj_includes_parser_context.cpp
lpea/cppinclude
dc126c6057d2fe30569e6e86f66d2c8eebb50212
[ "MIT" ]
11
2020-09-17T23:31:10.000Z
2022-03-04T13:15:21.000Z
#include "cmake_project/impl/cprj_includes_parser_context.hpp" #include <string_view> //------------------------------------------------------------------------------ namespace cmake_project { //------------------------------------------------------------------------------ IncludeParserContext::IncludeParserContext( std::string_view _command ) : m_command{ _command } , m_size{ _command.size() } { } //------------------------------------------------------------------------------ const std::string & IncludeParserContext::getCommand() const { return m_command; } //------------------------------------------------------------------------------ IncludeParserContext::IndexType IncludeParserContext::getCommandSize() const { return m_size; } //------------------------------------------------------------------------------ const IncludeParserContext::Includes & IncludeParserContext::getIncludes() const { return m_includes; } //------------------------------------------------------------------------------ void IncludeParserContext::addInclude( const Path & _path ) { m_includes.push_back( _path ); } //------------------------------------------------------------------------------ }
25.145833
80
0.408451
lpea
11a1a2b66f679c3038332a03db6b1c3ad46fc30b
7,412
cpp
C++
Samples/EmbedDemo/okApp.cpp
gamekit-developers/gamekit
74c896af5826ebe8fb72f2911015738f38ab7bb2
[ "Zlib", "MIT" ]
241
2015-01-04T00:36:58.000Z
2022-01-06T19:19:23.000Z
Samples/EmbedDemo/okApp.cpp
slagusev/gamekit
a6e97fcf2a9c3b9b9799bc12c3643818503ffc7d
[ "MIT" ]
10
2015-07-10T18:27:17.000Z
2019-06-26T20:59:59.000Z
Samples/EmbedDemo/okApp.cpp
slagusev/gamekit
a6e97fcf2a9c3b9b9799bc12c3643818503ffc7d
[ "MIT" ]
82
2015-01-25T18:02:35.000Z
2022-03-05T12:28:17.000Z
/* ------------------------------------------------------------------------------- This file is part of OgreKit. http://gamekit.googlecode.com/ Copyright (c) 2006-2010 harkon.kr Contributor(s): none yet. ------------------------------------------------------------------------------- This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ------------------------------------------------------------------------------- */ #include "StdAfx.h" #include "okApp.h" #include "okUtils.h" #include "Animation/gkAnimationManager.h" #define DEFAULT_CONFIG_FILE "OgreKitStartup.cfg" #define DEFAULT_LOG "oklog.log" #define DEFAULT_SCENE_NAME "DefaultScene" #define DEFAULT_CAMERA_NAME "DefaultCamera" UT_IMPLEMENT_SINGLETON(okApp) okApp::okApp() : m_showPhysicsDebug(false), m_inited(false), m_winCount(0) { gkLogger::enable(DEFAULT_LOG, true); } okApp::~okApp() { if (m_inited) uninit(); gkLogger::disable(); } void okApp::tick (gkScalar rate) { gkCoreApplication::tick(rate); } gkScene* okApp::createEmptyScene() { if (hasScene()) return NULL; gkScene* scene = gkSceneManager::getSingleton().createEmptyScene(); if (scene) { scene->createInstance(); GK_ASSERT(scene->getMainCamera() && scene->getMainCamera()->getCamera()); m_scenes.push_back(scene); } return scene; } bool okApp::setup(void) { if (!createEmptyScene()) { gkPrintf("Can't create empty scene."); return false; } gkWindowSystem::getSingleton().addListener(this); gkPrintf("done\n"); return true; } gkWindow* okApp::createWindow(const gkString& windowHandle, int winSizeX, int winSizeY) { if (!isInited()) return false; gkUserDefs prefs = m_prefs; prefs.winsize.x = winSizeX; prefs.winsize.y = winSizeY; prefs.wintitle = utStringFormat("okwin_%d", m_winCount++); prefs.extWinhandle = windowHandle; gkWindow* window = gkWindowSystem::getSingleton().createWindow(prefs); return window; } void okApp::destroyWindow(gkWindow* win) { if (!isInited()) return; gkWindowSystem::getSingleton().destroyWindow(win); } bool okApp::init(const gkString& cfg, const gkString& windowHandle, int winSizeX, int winSizeY) { m_cfg = cfg; m_prefs.winsize.x = winSizeX; m_prefs.winsize.y = winSizeY; m_prefs.wintitle = utStringFormat("okwin_%d", m_winCount++); m_prefs.verbose = false; m_prefs.grabInput = false; m_prefs.debugPhysics = false; m_prefs.debugPhysicsAabb = false; if (!m_cfg.empty()) { gkPath path = m_cfg; // overide settings if found if (path.isFileInBundle()) { m_prefs.load(path.getPath()); gkPrintf("Load config file: %s", path.getPath().c_str()); } } m_prefs.extWinhandle = windowHandle; if (!initialize()) //create engine & call this->setup return false; if (!m_engine->initializeStepLoop()) return false; m_inited = true; return true; } void okApp::uninit() { if (!m_inited) return; if (m_engine) { m_engine->finalizeStepLoop(); delete m_engine; m_engine = NULL; } m_scenes.clear(); m_inited = false; } gkWindow* okApp::getMainWindow() { return gkWindowSystem::getSingleton().getMainWindow(); } void okApp::unloadAllScenes() { gkBlendLoader::getSingleton().unloadAll(); m_scenes.clear(); } void okApp::unloadScene(gkScene* scene) { if (!scene) return; gkBlendFile* blend = scene->getLoadBlendFile(); gkString groupName = scene->getGroupName(); scene->destroyInstance(); gkSceneManager::getSingleton().destroy(scene); if (blend) gkBlendLoader::getSingleton().unloadFile(blend); else gkResourceGroupManager::getSingleton().destroyResourceGroup(groupName); //destroy empty scene group m_scenes.erase(m_scenes.find(scene)); } gkScene* okApp::loadScene(gkWindow* window, const gkString& blend, const gkString& sceneName, bool ignoreCache) { if (!m_inited) return NULL; GK_ASSERT(window); int options = gkBlendLoader::LO_ONLY_ACTIVE_SCENE | gkBlendLoader::LO_CREATE_UNIQUE_GROUP; if (ignoreCache) options |= gkBlendLoader::LO_IGNORE_CACHE_FILE; gkBlendFile* file = gkBlendLoader::getSingleton().loadFile(blend, options, sceneName); if (!file) { gkPrintf("Can't open the blend file: %s", blend.c_str()); return false; } gkScene* scene = NULL; if (!sceneName.empty()) scene = file->getSceneByName(sceneName); if (!scene) scene = file->getMainScene(); if (!scene) { gkPrintf("Can't create the scene."); return false; } scene->setDisplayWindow(window); if (m_showPhysicsDebug) scene->getDynamicsWorld()->enableDebugPhysics(true, true); scene->createInstance(); m_scenes.push_back(scene); return scene; } gkScene* okApp::mergeScene(gkScene* dstScene, const gkString& blend, const gkString& sceneName, bool ignoreCache) { if (!m_inited) return NULL; GK_ASSERT(dstScene); int options = gkBlendLoader::LO_ONLY_ACTIVE_SCENE | gkBlendLoader::LO_CREATE_UNIQUE_GROUP; if (ignoreCache) options |= gkBlendLoader::LO_IGNORE_CACHE_FILE; gkBlendFile* file = gkBlendLoader::getSingleton().loadFile(blend, options, sceneName); if (!file) { gkPrintf("Can't open the blend file: %s", blend.c_str()); return false; } gkScene* scene = NULL; if (!sceneName.empty()) scene = file->getSceneByName(sceneName); if (!scene) scene = file->getMainScene(); if (!scene) { gkPrintf("Can't create the scene."); return false; } gkSceneManager::getSingleton().copyObjects(scene, dstScene); //m_scenes.push_back(scene); return scene; } gkString okApp::getFirstSceneName() { gkScene* scene = getFirstScene(); return scene ? scene->getName() : ""; } gkBlendFile* okApp::getFirstBlendFile() { return m_scenes.empty() ? NULL : m_scenes[0]->getLoadBlendFile(); } gkBlendFile* okApp::getBlendFile(const gkString& fname) { return gkBlendLoader::getSingleton().getFileByName(fname); } bool okApp::changeScene(gkScene* scene, const gkString& sceneName) { if (!m_inited || !scene) return false; if (scene->getName() == sceneName) return true; gkBlendFile* blend = scene->getLoadBlendFile(); if (!blend) return false; gkScene* newScene = blend->getSceneByName(sceneName); if (!newScene) return false; if (scene) { if (scene == newScene) return false; scene->destroyInstance(); } if (!newScene->isInstanced()) newScene->createInstance(); return true; } bool okApp::step() { if (!m_inited) return false; return m_engine->stepOneFrame(); } void okApp::setShowPhysicsDebug(bool show) { m_showPhysicsDebug = show; for (UTsize i = 0; i < m_scenes.size(); i++) m_scenes[i]->getDynamicsWorld()->enableDebugPhysics(show, true); }
21.73607
113
0.688073
gamekit-developers
11ac3be20d2a90517a9b1370623a40f951d7c8a7
1,148
cpp
C++
src/HAPCompositeAccessory.cpp
lmartu68/Particle-HAP
3e8c3bd7fdc13ceb6fe3d06b92565262ac4f49bd
[ "MIT" ]
59
2019-01-29T12:05:28.000Z
2021-06-16T04:36:53.000Z
src/HAPCompositeAccessory.cpp
lmartu68/Particle-HAP
3e8c3bd7fdc13ceb6fe3d06b92565262ac4f49bd
[ "MIT" ]
16
2019-03-13T12:38:56.000Z
2021-11-13T09:47:36.000Z
src/HAPCompositeAccessory.cpp
lmartu68/Particle-HAP
3e8c3bd7fdc13ceb6fe3d06b92565262ac4f49bd
[ "MIT" ]
19
2019-02-12T04:38:47.000Z
2021-12-09T22:03:29.000Z
// // CompositeAccessory.cpp // HKTester // // Created by Lukas Jezny on 02/03/2019. // Copyright © 2019 Lukas Jezny. All rights reserved. // #include "HAPCompositeAccessory.h" void HAPCompositeAccessory::identity(bool oldValue, bool newValue, HKConnection *sender) { } bool HAPCompositeAccessory::handle() { bool result = false; for(uint i = 0; i < descriptors.size(); i++) { //process only one accessory per "loop" step. So we dont delay Particle connection, Bonjour so much. Never mind it will be process one step later result |= descriptors.at(i)->handle(); } return result; } void HAPCompositeAccessory::initAccessorySet(){ Accessory *accessory = new Accessory(); AccessorySet *accSet = &AccessorySet::getInstance(); addInfoServiceToAccessory(accessory, "Composite accessory", "Vendor name", "Model name", "1","1.0.0", std::bind(&HAPCompositeAccessory::identity, this, std::placeholders::_1, std::placeholders::_2,std::placeholders::_3)); accSet->addAccessory(accessory); for(uint i = 0; i < descriptors.size(); i++) { descriptors.at(i)->initService(accessory); } }
31.888889
226
0.689024
lmartu68
11ae69d2daec2802ea93630f28fc9ec275743e86
790
cpp
C++
COJ/Bingo!.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
1
2019-09-29T03:58:35.000Z
2019-09-29T03:58:35.000Z
COJ/Bingo!.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
null
null
null
COJ/Bingo!.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cstdio> #include <string> #include <cstring> #include <list> #include <iterator> #include <cstdlib> #include <set> //Not sent, probably WA using namespace std; int main () { int n, b, aux, act; list<int> sobrantes; set<int> total; list<int>::iterator itr; cin>>n>>b; while ((n) && (b)) { for (;b--;) { cin>>aux; sobrantes.push_back(aux); } b = sobrantes.size(); for (;b--;) { act = sobrantes.front(); for (itr = sobrantes.begin(); itr != sobrantes.end(); itr++) { total.insert(abs(act - *itr)); } sobrantes.pop_front(); } if (total.size() == n+1) { printf("Y\n"); } else { printf("N\n"); } total.clear(); cin>>n>>b; } return 0; }
15.490196
66
0.520253
MartinAparicioPons
11b5305e8e5681361f9e42be5e1b9e7a3eb23da7
1,021
hpp
C++
ThirdParty/oglplus-develop/include/oglplus/ext/NV_path_rendering/color.hpp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
24
2015-01-31T15:30:49.000Z
2022-01-29T08:36:42.000Z
ThirdParty/oglplus-develop/include/oglplus/ext/NV_path_rendering/color.hpp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
4
2015-08-21T02:29:15.000Z
2020-05-02T13:50:36.000Z
ThirdParty/oglplus-develop/include/oglplus/ext/NV_path_rendering/color.hpp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
9
2015-06-08T22:04:15.000Z
2021-08-16T03:52:11.000Z
/** * @file oglplus/ext/NV_path_rendering/color.hpp * @brief Wrapper for the NV_path_rendering color enumeration * * @author Matus Chochlik * * Copyright 2010-2014 Matus Chochlik. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #pragma once #ifndef OGLPLUS_EXT_NV_PATH_RENDERING_COLOR_1203031902_HPP #define OGLPLUS_EXT_NV_PATH_RENDERING_COLOR_1203031902_HPP #include <oglplus/enumerations.hpp> namespace oglplus { /// Path color mode enumeration /** * @ingroup enumerations * * @glsymbols * @glextref{NV,path_rendering} */ OGLPLUS_ENUM_CLASS_BEGIN(PathNVColor, GLenum) #include <oglplus/enums/ext/nv_path_color.ipp> OGLPLUS_ENUM_CLASS_END(PathNVColor) #if !OGLPLUS_NO_ENUM_VALUE_NAMES #include <oglplus/enums/ext/nv_path_color_names.ipp> #endif #if !OGLPLUS_ENUM_VALUE_RANGES #include <oglplus/enums/ext/nv_path_color_range.ipp> #endif } // namespace oglplus #endif // include guard
24.309524
68
0.782566
vif
11b53e59de6319daaaec98ecd460c63568a18c9f
2,527
cc
C++
gazebo/math/Vector3_TEST.cc
thomas-moulard/gazebo-deb
456da84cfb7b0bdac53241f6c4e86ffe1becfa7d
[ "ECL-2.0", "Apache-2.0" ]
8
2015-07-02T08:23:30.000Z
2020-11-17T19:00:38.000Z
gazebo/math/Vector3_TEST.cc
thomas-moulard/gazebo-deb
456da84cfb7b0bdac53241f6c4e86ffe1becfa7d
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
gazebo/math/Vector3_TEST.cc
thomas-moulard/gazebo-deb
456da84cfb7b0bdac53241f6c4e86ffe1becfa7d
[ "ECL-2.0", "Apache-2.0" ]
10
2015-04-22T18:33:15.000Z
2021-11-16T10:17:45.000Z
/* * Copyright 2013 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <gtest/gtest.h> #include "gazebo/math/Vector3.hh" using namespace gazebo; TEST(Vector3Test, Vector3) { math::Vector3 v; // ::Distance, ::GetLEngth() v.Set(1, 2, 3); EXPECT_FLOAT_EQ(v.GetLength(), v.Distance(math::Vector3(0, 0, 0))); // ::GetRound v.Set(1.23, 2.34, 3.55); EXPECT_TRUE(v.GetRounded() == math::Vector3(1, 2, 4)); // ::Round v.Round(); EXPECT_TRUE(v.Round() == math::Vector3(1, 2, 4)); // ::GetDotProd EXPECT_TRUE(math::equal(17.0, v.Dot(math::Vector3(1, 2, 3)), 1e-2)); // ::GetDistToLine v.Set(0, 0, 0); EXPECT_DOUBLE_EQ(1.0, v.GetDistToLine(math::Vector3(1, -1, 0), math::Vector3(1, 1, 0))); // ::operator= double v = 4.0; EXPECT_TRUE(v == math::Vector3(4, 4, 4)); // ::operator/ vector3 v = v / math::Vector3(1, 2, 4); EXPECT_TRUE(v == math::Vector3(4, 2, 1)); // ::operator / double v = v / 2; EXPECT_TRUE(v == math::Vector3(2, 1, .5)); // ::operator * vector3 v = v * math::Vector3(2, 3, 4); EXPECT_TRUE(v == math::Vector3(4, 3, 2)); // ::operator[] EXPECT_DOUBLE_EQ(v[0], 4); EXPECT_DOUBLE_EQ(v[1], 3); EXPECT_DOUBLE_EQ(v[2], 2); v.Set(1.23, 2.35, 3.654321); v.Round(1); EXPECT_TRUE(v == math::Vector3(1.2, 2.4, 3.7)); // operator GetAbs v.Set(-1, -2, -3); EXPECT_TRUE(v.GetAbs() == math::Vector3(1, 2, 3)); // operator /= v.Set(1, 2, 4); v /= math::Vector3(1, 4, 4); EXPECT_TRUE(v == math::Vector3(1, .5, 1)); // operator *= v.Set(1, 2, 4); v *= math::Vector3(2, .5, .1); EXPECT_TRUE(v.Equal(math::Vector3(2, 1, .4))); // Test the static defines. EXPECT_TRUE(math::Vector3::Zero == math::Vector3(0, 0, 0)); EXPECT_TRUE(math::Vector3::One == math::Vector3(1, 1, 1)); EXPECT_TRUE(math::Vector3::UnitX == math::Vector3(1, 0, 0)); EXPECT_TRUE(math::Vector3::UnitY == math::Vector3(0, 1, 0)); EXPECT_TRUE(math::Vector3::UnitZ == math::Vector3(0, 0, 1)); }
26.882979
75
0.62129
thomas-moulard
11be90e78fbffbad86c8bbb8ce0df2738521ac9e
20,625
cpp
C++
Systems/Engine/Resource.cpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
null
null
null
Systems/Engine/Resource.cpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
null
null
null
Systems/Engine/Resource.cpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// /// /// \file Resource.cpp /// Implementation of the resource system class. /// /// Authors: Chris Peters, Joshua Claeys /// Copyright 2010-2016, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #include "Precompiled.hpp" namespace Zero { const String DataResourceExtension = "data"; namespace Events { DefineEvent(ResourceInstanceModified); DefineEvent(ResourceTagsModified); } namespace Tags { DefineTag(Resource); } const String cNullResource = "null"; //-------------------------------------------------------------------------- Resource Handle Manager //****************************************************************************** void ResourceHandleManager::Allocate(BoundType* type, Handle& handleToInitialize, size_t customFlags) { handleToInitialize.Flags |= HandleFlags::NoReferenceCounting; ResourceHandleData& data = *(ResourceHandleData*)(handleToInitialize.Data); data.mRawObject = (Resource*)zAllocate(type->Size); data.mDebugResource = data.mRawObject; data.mId = 0; memset(data.mRawObject, 0, type->Size); } //************************************************************************************************** void ResourceHandleManager::ObjectToHandle(const byte* object, BoundType* type, Handle& handleToInitialize) { if (object == nullptr) return; Resource* resource = (Resource*)object; ResourceHandleData& data = *(ResourceHandleData*)(handleToInitialize.Data); data.mDebugResource = resource; resource->AddReference(); if(resource->mResourceId == 0) data.mRawObject = resource; else data.mId = resource->mResourceId; } //************************************************************************************************** byte* ResourceHandleManager::HandleToObject(const Handle& handle) { return (byte*)GetResource(handle, true); } //************************************************************************************************** void ResourceHandleManager::AddReference(const Handle& handle) { if(Resource* instance = GetResource(handle, false)) instance->AddReference(); } //************************************************************************************************** ReleaseResult::Enum ResourceHandleManager::ReleaseReference(const Handle& handle) { if(Resource* instance = GetResource(handle, false)) { ErrorIf(instance == nullptr, "I think this should be null when unloading a ResourceLibrary"); instance->Release(); } return ReleaseResult::TakeNoAction; } //************************************************************************************************** void ResourceHandleManager::Delete(const Handle& handle) { if(Resource* resource = GetResource(handle, false)) { ErrorIf(!resource->IsRuntime(), "Only runtime resources should be able to be deleted through" " handles. Otherwise, it should be deleted through its ResourceLibrary"); resource->GetManager()->Remove(resource, RemoveMode::Unloading); delete resource; } } //************************************************************************************************** bool ResourceHandleManager::CanDelete(const Handle& handle) { // We only allow users to delete runtime resources if(Resource* resource = GetResource(handle, false)) return resource->IsRuntime(); return false; } //************************************************************************************************** Resource* ResourceHandleManager::GetResource(const Handle& handle, bool resolveThroughManagerOnNull) { ResourceHandleData& data = *(ResourceHandleData*)(handle.Data); if(data.mRawObject) return data.mRawObject; // If the handle was never assigned a Resource, no reason to use the fallback Resource if(data.mId == 0) return nullptr; // If we can't find the resource, we need to get the fallback from the resource manager // if it exists, otherwise it will just be null Resource* resource = Z::gResources->GetResource(data.mId); if(resource == nullptr && resolveThroughManagerOnNull) { if(ResourceManager* manager = Z::gResources->GetResourceManager(handle.StoredType)) resource = manager->GetFallbackResource(); } return resource; } void SaveResource(cstr fieldName, Resource* resource, Serializer& serializer) { // If the resource is valid (may be null) read its // resourceIdAndName StringRange resourceIdAndName = cNullResource; // Runtime resources can never be loaded from data, so write out null if (resource && !resource->IsRuntime()) resourceIdAndName = resource->ResourceIdName.All(); // Serialize the resourceIdAndName serializer.StringField("string", fieldName, resourceIdAndName); } void LoadResource(HandleParam instance, Property* property, Type* resourceType, StringRange resourceIdName) { // If it's null, do not default if (resourceIdName == cNullResource) { // Set property to null resource. property->SetValue(instance, Any(resourceType)); return; } Resource* resource; // Try to find the resource or use default if it is not found ResourceManager* resourceManger = Z::gResources->Managers.FindValue(resourceType->ToString(), nullptr); if (resourceManger) resource = resourceManger->GetResource(resourceIdName, ResourceNotFound::ReturnNull); else resource = Z::gResources->GetResourceByName(resourceIdName); if (resource) { // Valid resource was serialized property->SetValue(instance, resource); } else { // Serialize failed resource is missing so use default resource ResourceManager* resourceManger = Z::gResources->Managers.FindValue(resourceType->ToString(), nullptr); if (resourceManger) property->SetValue(instance, resourceManger->GetDefaultResource()); } } //--------------------------------------------------------------------- ResourceMetaSerialization ZilchDefineType(ResourceMetaSerialization, builder, type) { } void ResourceMetaSerialization::SerializeProperty(HandleParam instance, Property* property, Serializer& serializer) { Type* resourceType = property->PropertyType; cstr fieldName = property->Name.c_str(); if (serializer.GetMode() == SerializerMode::Loading) { // Serialize a Resource to a String that is a resource name and Id. StringRange resourceIdAndName; if (serializer.StringField("string", fieldName, resourceIdAndName)) LoadResource(instance, property, resourceType, resourceIdAndName); } else { Any value = property->GetValue(instance); Resource* resource = value.Get<Resource*>(); SaveResource(fieldName, resource, serializer); } } void ResourceMetaSerialization::SetDefault(Type* type, Any& any) { ResourceManager* manager = Z::gResources->Managers.FindValue(type->ToString(), nullptr); if (manager != nullptr) { Resource* defaultResource = manager->GetDefaultResource(); if (defaultResource != nullptr) any = defaultResource; else any = (Resource*)nullptr; } else any = (Resource*)nullptr; } String ResourceMetaSerialization::ConvertToString(AnyParam input) { if(Resource* resource = input.Get<Resource*>()) return resource->ResourceIdName; return String(); } bool ResourceMetaSerialization::ConvertFromString(StringParam input, Any& output) { // 'output' can be null, but null is a valid result so return true. output = Z::gResources->GetResourceByName(input); return true; } String ResourceToString(const BoundType* type, const byte* value) { // Convert a Resource to a String Resource* resource = (Resource*)value; if(resource) return resource->ResourceIdName; else return String(); } //METAREFACTOR See below where we set all this information on the meta //bool ResourceStringConversion(MetaType* metaType, StringParam string, Variant& var) //{ // // Find a Resource from String. Allows system to pass strings for resource parameters or properties. // ResourceManager* resourceManger = Z::gResources->Managers.FindValue(metaType->TypeName, NULL); // if(resourceManger) // { // var = resourceManger->GetResource(string, ResourceNotFound::ErrorFallback); // return true; // } // else // { // return false; // } //} //--------------------------------------------------------------------- ResourceDisplayFunctions ZilchDefineType(ResourceDisplayFunctions, builder, Type) { } String ResourceDisplayFunctions::GetName(HandleParam object) { Resource* resource = object.Get<Resource*>(GetOptions::AssertOnNull); return resource->Name; } String ResourceDisplayFunctions::GetDebugText(HandleParam object) { Resource* resource = object.Get<Resource*>(GetOptions::AssertOnNull); StringBuilder builder; builder << "<"; builder << object.StoredType->Name << " "; builder << resource->ResourceIdName; builder << ">"; return builder.ToString(); } //--------------------------------------------------------------------- Resource Memory::Heap* Resource::sHeap = new Memory::Heap("ResourceObjects", Memory::GetRoot()); ZilchDefineType(Resource, builder, type) { type->AddAttribute(ObjectAttributes::cResourceInterface); //METAREFACTOR Handle all this resource stuff //meta->StringConversion = ResourceStringConversion; //meta->SetDefaultValue = ResourceSetDefaultValue; type->HandleManager = ZilchManagerId(ResourceHandleManager); type->Add(new ResourceMetaSerialization()); type->Add(new ResourceDisplayFunctions()); type->Add(new ResourceMetaOperations()); // When serialized as a property, Resources save out a resource id and name ZeroBindSerializationPrimitive(); ZeroBindDocumented(); ZilchBindFieldGetterProperty(Name); type->ToStringFunction = ResourceToString; ZeroBindTag(Tags::Resource); } void* Resource::operator new(size_t size) { return sHeap->Allocate(size); } void Resource::operator delete(void* pMem, size_t size) { return sHeap->Deallocate(pMem, size); } Resource::Resource() { mResourceId = 0; mManager = nullptr; mResourceLibrary = nullptr; mContentItem = nullptr; mBuilderType = nullptr; mIsRuntimeResource = false; mReferenceCount = 0; } HandleOf<Resource> Resource::Clone() { BoundType* type = ZilchVirtualTypeId(this); String msg = String::Format("%s's cannot be runtime cloned", type->Name.c_str()); DoNotifyException("Failed to clone Resource", msg); return nullptr; } DataNode* Resource::GetDataTree() { return nullptr; } Resource* Resource::GetBaseResource() { return Z::gResources->GetResourceByName(mBaseResourceIdName); } bool Resource::InheritsFrom(Resource* baseResource) { forRange(Resource* curr, GetBaseResources()) { if(curr == baseResource) return true; } return false; } bool Resource::CanReference(Resource* resource) { return mResourceLibrary->CanReference(resource->mResourceLibrary); } ResourceTemplate* Resource::GetResourceTemplate() { if (mContentItem) return mContentItem->has(ResourceTemplate); return nullptr; } Resource::InheritRange Resource::GetBaseResources() { InheritRange r(this); r.PopFront(); return r; } BuilderComponent* Resource::GetBuilder() { if(!mContentItem) return nullptr; return (BuilderComponent*)mContentItem->QueryComponentId(mBuilderType); } void Resource::AddReference() { AtomicPreIncrement(&mReferenceCount); } int Resource::Release() { ErrorIf(mReferenceCount == 0, "Invalid Release."); int referenceCount = (int)AtomicPreDecrement(&mReferenceCount); if(referenceCount == 0) { // Resources owned by a resource library should only be deleted by that library. // Library unloading flag will only be true while a library is clearing its own handles. ErrorIf(!IsRuntime() && !ResourceLibrary::IsLibraryUnloading(), "A library resource is being removed but not by the library."); mManager->Remove(this, RemoveMode::Deleted); delete this; } return referenceCount; } void Resource::GetDependencies(HashSet<ContentItem*>& dependencies, HandleParam instance) { Handle resourceInstance = instance; if(resourceInstance.IsNull()) resourceInstance = this; // Get all resources used by this component HashSet<Resource*> usedResources; GetResourcesFromProperties(resourceInstance, usedResources); // Filter runtime and non-writable resources forRange(Resource* resource, usedResources.All()) { if(resource->IsWritable() && !resource->IsRuntime()) { dependencies.Insert(resource->mContentItem); // Add all dependencies of the resource resource->GetDependencies(dependencies); } } } void Resource::UpdateContentItem(ContentItem* contentItem) { mContentItem = contentItem; } void Resource::GetTags(Array<String>& tags) { // Add both core and user tags to the same array GetTags(tags, tags); } void Resource::GetTags(HashSet<String>& tags) { // Add both core and user tags to the same array static Array<String> temp; temp.Clear(); GetTags(temp, temp); forRange(String tag, temp.All()) { tags.Insert(tag); } } void Resource::GetTags(Array<String>& coreTags, Array<String>& userTags) { // First add the resource type as a tag coreTags.PushBack(ZilchVirtualTypeId(this)->Name); if(!FilterTag.Empty()) coreTags.PushBack(FilterTag); // Add all tags from the content item if(mContentItem != nullptr) mContentItem->GetTags(userTags); } void Resource::AddTags(HashSet<String>& tags) { Array<String> tagArray; GetTags(tagArray); forRange(String tag, tagArray.All()) { tags.Insert(tag); } } void Resource::SetTags(HashSet<String>& tags) { if(mContentItem != nullptr) mContentItem->SetTags(tags); } void Resource::RemoveTags(HashSet<String>& tags) { if(mContentItem != nullptr) mContentItem->RemoveTags(tags); } bool Resource::HasTag(StringParam tag) { if(mContentItem) return mContentItem->HasTag(tag); return false; } String Resource::GetNameOrFilePath() { if(mContentItem) return mContentItem->GetFullPath(); return Name; } bool Resource::IsWritable() { if(mContentItem) { bool isWritable = mContentItem->mLibrary->GetWritable( ); // Check dev config to override what the content item says if(!isWritable) { if(DeveloperConfig* devConfig = Z::gEngine->GetConfigCog( )->has(Zero::DeveloperConfig)) isWritable = devConfig->mCanModifyReadOnlyResources; } return isWritable; } return false; } bool Resource::IsRuntime() { return mIsRuntimeResource; } ResourceManager* Resource::GetManager() { return mManager; } void Resource::SendModified() { ResourceEvent event; event.Manager = mManager; event.EventResource = this; mManager->DispatchEvent(Events::ResourceModified, &event); Z::gResources->DispatchEvent(Events::ResourceModified, &event); DispatchEvent(Events::ObjectStructureModified, &event); } //---------------------------------------------------------------- Inherit Range Resource::InheritRange::InheritRange(Resource* current) : mCurrent(current) { } Resource* Resource::InheritRange::Front() { return mCurrent; } void Resource::InheritRange::PopFront() { ReturnIf(Empty(), , "Cannot pop front on an empty range."); mCurrent = mCurrent->GetBaseResource(); } bool Resource::InheritRange::Empty() { return (mCurrent == nullptr); } //---------------------------------------------------------------- Data Resource ZilchDefineType(DataResource, builder, type) { type->Add(new DataResourceInheritance()); type->AddAttribute(ObjectAttributes::cResourceInterface); ZeroBindDocumented(); } void DataResource::Save(StringParam filename) { // Cannot use ObjectSaver with the current way resource id's are expected to be assigned. // Added resources that don't come from a template save to temp file before an id is given by the content system, // but interfaces used by ObjectSaver require a handle and resource handles require an id... SaveToDataFile(*this, filename); //ObjectSaver saver; //Status status; //saver.Open(status, filename.c_str()); //ReturnIf(status.Failed(), , "Failed to save resource '%s' to '%s'\n", Name.c_str(), filename.c_str()); //saver.SaveDefinition(this); //saver.Close(); } HandleOf<Resource> DataResource::Clone() { HandleOf<DataResource> resourceHandle(mManager->CreateRuntimeInternal()); DataResource* resource = resourceHandle; // Save ourself to a buffer ObjectSaver saver; saver.OpenBuffer(); saver.SaveInstance(this); // Serialize the new resource with the saved data DataTreeLoader loader; Status status; loader.OpenBuffer(status, saver.GetString()); ReturnIf(status.Failed(), nullptr, "Failed to serialize runtime clone"); PolymorphicNode resourceNode; loader.GetPolymorphic(resourceNode); resource->Serialize(loader); loader.EndPolymorphic(); resource->Initialize(); return resourceHandle; } DataNode* DataResource::GetDataTree() { Status status; ObjectLoader loader; loader.OpenFile(status, mContentItem->GetFullPath()); return loader.TakeOwnershipOfFirstRoot(); } //------------------------------------------------------------------------ Data Resource Inheritance ZilchDefineType(DataResourceInheritance, builder, type) { } String DataResourceInheritance::GetInheritId(HandleParam object, InheritIdContext::Enum context) { DataResource* resource = object.Get<DataResource*>(); if(context == InheritIdContext::Definition) return resource->mBaseResourceIdName; return String(); } void DataResourceInheritance::SetInheritId(HandleParam object, StringParam inheritId) { DataResource* resource = object.Get<DataResource*>(); resource->mBaseResourceIdName = inheritId; } bool DataResourceInheritance::ShouldStoreLocalModifications(HandleParam object) { DataResource* resource = object.Get<DataResource*>(); return !resource->mBaseResourceIdName.Empty(); } //------------------------------------------------------------------------- Resource Meta Operations //************************************************************************************************** ZilchDefineType(ResourceMetaOperations, builder, type) { } //************************************************************************************************** u64 ResourceMetaOperations::GetUndoHandleId(HandleParam object) { Resource* resource = object.Get<Resource*>(); return (u64)resource->mResourceId; } //************************************************************************************************** Any ResourceMetaOperations::GetUndoData(HandleParam object) { Resource* resource = object.Get<Resource*>(GetOptions::AssertOnNull); bool isModified = Z::gResources->mModifiedResources.Contains(resource->mResourceId); // Temporary until we fix issues with how this works isModified = true; return isModified; } //************************************************************************************************** void ResourceMetaOperations::ObjectModified(HandleParam object, bool intermediateChange) { MetaOperations::ObjectModified(object, intermediateChange); if(!intermediateChange) { Resource* resource = object.Get<Resource*>(GetOptions::AssertOnNull); resource->ResourceModified(); Z::gResources->mModifiedResources.Insert(resource->mResourceId); } // We used to dispatch an event on the Manager. Should we? } //************************************************************************************************** void ResourceMetaOperations::RestoreUndoData(HandleParam object, AnyParam undoData) { Resource* resource = object.Get<Resource*>(GetOptions::AssertOnNull); bool wasModified = undoData.Get<bool>(); if(wasModified == false) Z::gResources->mModifiedResources.Erase(resource->mResourceId); } }//namespace Zero
29.422254
132
0.636606
jodavis42
11bf27c160201211f01279d3b1d7cc1bd00726dc
11,479
cpp
C++
tests/ParserTests/ParserTests_Literals.cpp
mattmassicotte/three
3986c656724d1317bdb46d4777f8f952103d7ce7
[ "MIT" ]
8
2015-01-02T21:40:55.000Z
2016-05-12T10:48:09.000Z
tests/ParserTests/ParserTests_Literals.cpp
mattmassicotte/three
3986c656724d1317bdb46d4777f8f952103d7ce7
[ "MIT" ]
null
null
null
tests/ParserTests/ParserTests_Literals.cpp
mattmassicotte/three
3986c656724d1317bdb46d4777f8f952103d7ce7
[ "MIT" ]
null
null
null
#include "../ParserTestsBase.h" #include "compiler/constructs/DataType.h" class ParserTests_Literals : public ParserTestsBase { }; TEST_F(ParserTests_Literals, IntegerLiteral) { ASTNode* node = this->parseSingleFunction("def test(Int a)\n" " a = 1\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("Integer Literal", node->childAtIndex(1)->nodeName()); IntegerLiteralNode* literal = dynamic_cast<IntegerLiteralNode*>(node->childAtIndex(1)); ASSERT_EQ(1, literal->value()); ASSERT_EQ(DataType::Kind::Integer, literal->dataType().kind()); ASSERT_EQ(0, literal->dataType().widthSpecifier()); ASSERT_EQ(DataType::Access::Read, literal->dataType().access()); } TEST_F(ParserTests_Literals, NegativeIntegerLiteral) { ASTNode* node = this->parseSingleFunction("def test(Int a)\n" " a = -1\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); node = node->childAtIndex(1); ASSERT_EQ("Unary Minus Operator", node->nodeName()); ASSERT_EQ("Integer Literal", node->childAtIndex(0)->nodeName()); IntegerLiteralNode* literal = dynamic_cast<IntegerLiteralNode*>(node->childAtIndex(0)); ASSERT_EQ(1, literal->value()); ASSERT_EQ(DataType::Kind::Integer, literal->dataType().kind()); ASSERT_EQ(DataType::Access::Read, literal->dataType().access()); } TEST_F(ParserTests_Literals, IntegerLiteralWithTypeSpecifier) { ASTNode* node = this->parseSingleFunction("def test(Int a)\n" " a = 1:Natural:64\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("Integer Literal", node->childAtIndex(1)->nodeName()); IntegerLiteralNode* literal = dynamic_cast<IntegerLiteralNode*>(node->childAtIndex(1)); ASSERT_EQ(1, literal->value()); ASSERT_EQ(DataType::Kind::Natural, literal->dataType().kind()); ASSERT_EQ(64, literal->dataType().widthSpecifier()); ASSERT_EQ(DataType::Access::Read, literal->dataType().access()); } TEST_F(ParserTests_Literals, FloatLiteral) { ASTNode* node = this->parseSingleFunction("def test(Int a)\n" " a = 1.0\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("Real Literal", node->childAtIndex(1)->nodeName()); RealLiteralNode* literal = dynamic_cast<RealLiteralNode*>(node->childAtIndex(1)); ASSERT_EQ(1.0, literal->value()); ASSERT_EQ(DataType::Kind::Float, literal->dataType().kind()); ASSERT_EQ(0, literal->dataType().widthSpecifier()); ASSERT_EQ(DataType::Access::Read, literal->dataType().access()); } TEST_F(ParserTests_Literals, FloatLiteralWithTypeSpecifier) { ASTNode* node = this->parseSingleFunction("def test(Int a)\n" " a = 1.0:Real:64\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("Real Literal", node->childAtIndex(1)->nodeName()); RealLiteralNode* literal = dynamic_cast<RealLiteralNode*>(node->childAtIndex(1)); ASSERT_EQ(1.0, literal->value()); ASSERT_EQ(DataType::Kind::Real, literal->dataType().kind()); ASSERT_EQ(64, literal->dataType().widthSpecifier()); ASSERT_EQ(DataType::Access::Read, literal->dataType().access()); } TEST_F(ParserTests_Literals, HexLiteral) { ASTNode* node = this->parseSingleFunction("def test(Int a)\n" " a = 0x4d2\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("Integer Literal", node->childAtIndex(1)->nodeName()); IntegerLiteralNode* literal = dynamic_cast<IntegerLiteralNode*>(node->childAtIndex(1)); ASSERT_EQ(1234, literal->value()); ASSERT_EQ(DataType::Kind::Integer, literal->dataType().kind()); ASSERT_EQ(0, literal->dataType().widthSpecifier()); ASSERT_EQ(DataType::Access::Read, literal->dataType().access()); } TEST_F(ParserTests_Literals, BinaryLiteral) { ASTNode* node = this->parseSingleFunction("def test(Int a)\n" " a = 0b010011010010\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("Integer Literal", node->childAtIndex(1)->nodeName()); IntegerLiteralNode* literal = dynamic_cast<IntegerLiteralNode*>(node->childAtIndex(1)); ASSERT_EQ(1234, literal->value()); ASSERT_EQ(DataType::Kind::Integer, literal->dataType().kind()); ASSERT_EQ(0, literal->dataType().widthSpecifier()); ASSERT_EQ(DataType::Access::Read, literal->dataType().access()); } TEST_F(ParserTests_Literals, NullLiteral) { ASTNode* node = this->parseSingleFunction("def test(*Int a)\n" " a = null\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("Null Literal", node->childAtIndex(1)->nodeName()); NullLiteralNode* literal = dynamic_cast<NullLiteralNode*>(node->childAtIndex(1)); ASSERT_EQ(DataType::Kind::Pointer, literal->dataType().kind()); ASSERT_EQ(DataType::Access::Read, literal->dataType().access()); ASSERT_EQ(1, literal->dataType().subtypeCount()); ASSERT_EQ(DataType::Kind::Void, literal->dataType().subtypeAtIndex(0).kind()); ASSERT_EQ(DataType::Access::Read, literal->dataType().subtypeAtIndex(0).access()); } TEST_F(ParserTests_Literals, StringLiteral) { ASTNode* node = this->parseSingleFunction("def test(*Char a)\n" " a = \"hello\"\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("String Literal", node->childAtIndex(1)->nodeName()); StringLiteralNode* literal = dynamic_cast<StringLiteralNode*>(node->childAtIndex(1)); ASSERT_EQ("hello", literal->stringValue()); ASSERT_EQ(DataType::Kind::Pointer, literal->dataType().kind()); ASSERT_EQ(DataType::Access::Read, literal->dataType().access()); ASSERT_EQ(1, literal->dataType().subtypeCount()); ASSERT_EQ(DataType::Kind::Character, literal->dataType().subtypeAtIndex(0).kind()); ASSERT_EQ(DataType::CharacterEncoding::UTF8, literal->dataType().subtypeAtIndex(0).characterEncoding()); } TEST_F(ParserTests_Literals, StringLiteralAscii) { ASTNode* node = this->parseSingleFunction("def test(*Char a)\n" " a = \"hello\":ascii\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("String Literal", node->childAtIndex(1)->nodeName()); StringLiteralNode* literal = dynamic_cast<StringLiteralNode*>(node->childAtIndex(1)); ASSERT_EQ("hello", literal->stringValue()); ASSERT_EQ(DataType::Kind::Pointer, literal->dataType().kind()); ASSERT_EQ(1, literal->dataType().subtypeCount()); ASSERT_EQ(DataType::Kind::Character, literal->dataType().subtypeAtIndex(0).kind()); ASSERT_EQ(DataType::CharacterEncoding::ASCII, literal->dataType().subtypeAtIndex(0).characterEncoding()); } TEST_F(ParserTests_Literals, StringLiteralUTF16LE) { ASTNode* node = this->parseSingleFunction("def test(*Char a)\n" " a = \"hello\":utf16le\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("String Literal", node->childAtIndex(1)->nodeName()); StringLiteralNode* literal = dynamic_cast<StringLiteralNode*>(node->childAtIndex(1)); ASSERT_EQ("hello", literal->stringValue()); ASSERT_EQ(DataType::Kind::Pointer, literal->dataType().kind()); ASSERT_EQ(1, literal->dataType().subtypeCount()); ASSERT_EQ(DataType::Kind::Character, literal->dataType().subtypeAtIndex(0).kind()); ASSERT_EQ(DataType::CharacterEncoding::UTF16LE, literal->dataType().subtypeAtIndex(0).characterEncoding()); } TEST_F(ParserTests_Literals, CharacterLiteral) { ASTNode* node = this->parseSingleFunction("def test(Char a)\n" " a = 'h'\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("Character Literal", node->childAtIndex(1)->nodeName()); CharacterLiteralNode* literal = dynamic_cast<CharacterLiteralNode*>(node->childAtIndex(1)); ASSERT_EQ("h", literal->value()); ASSERT_EQ(DataType::Kind::Character, literal->dataType().kind()); ASSERT_EQ(DataType::CharacterEncoding::UTF8, literal->dataType().characterEncoding()); ASSERT_EQ(0, literal->dataType().subtypeCount()); } TEST_F(ParserTests_Literals, CharacterLiteralAscii) { ASTNode* node = this->parseSingleFunction("def test(Char a)\n" " a = 'h':ascii\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("Character Literal", node->childAtIndex(1)->nodeName()); CharacterLiteralNode* literal = dynamic_cast<CharacterLiteralNode*>(node->childAtIndex(1)); ASSERT_EQ("h", literal->value()); ASSERT_EQ(DataType::Kind::Character, literal->dataType().kind()); ASSERT_EQ(DataType::CharacterEncoding::ASCII, literal->dataType().characterEncoding()); ASSERT_EQ(0, literal->dataType().subtypeCount()); } TEST_F(ParserTests_Literals, TrueLiteral) { ASTNode* node = this->parseSingleFunction("def test(Bool a)\n" " a = true\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("Boolean Literal", node->childAtIndex(1)->nodeName()); BooleanLiteralNode* literal = dynamic_cast<BooleanLiteralNode*>(node->childAtIndex(1)); ASSERT_TRUE(literal->value()); ASSERT_EQ(DataType::Kind::Boolean, literal->dataType().kind()); ASSERT_EQ(0, literal->dataType().subtypeCount()); } TEST_F(ParserTests_Literals, FalseLiteral) { ASTNode* node = this->parseSingleFunction("def test(Bool a)\n" " a = false\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("Boolean Literal", node->childAtIndex(1)->nodeName()); BooleanLiteralNode* literal = dynamic_cast<BooleanLiteralNode*>(node->childAtIndex(1)); ASSERT_FALSE(literal->value()); ASSERT_EQ(DataType::Kind::Boolean, literal->dataType().kind()); ASSERT_EQ(0, literal->dataType().subtypeCount()); }
40.850534
111
0.612248
mattmassicotte
11c2ca55023c9ef3e88b0ee19757d529057f4850
1,133
cpp
C++
TGEditor/TGEditor.cpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
TGEditor/TGEditor.cpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
TGEditor/TGEditor.cpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
#include "TGEditor.hpp" Texture tex1; Texture tex2; Mesh mesh; Mesh mesh2; Font arial; Camera camera; tg_ui::UIEntity entity = tg_ui::UIEntity({0, 0}, {0.3, 0.15}); int main() { Editor editor = Editor(); std::cout << "Starting Editor" << std::endl; tg_ui::UITextureComponent texture = tg_ui::UITextureComponent(&tex2); entity.addComponent(&texture); tg_ui::ui_scene_entity.addChildren(&entity); initTGEngine(&editor.main_window, &drawloop, &init); std::cout << "Clean exit! Bye :wave:!" << std::endl; return 0; } void init() { arial = { "resource\\arial.ttf", 60.0f }; loadfont(&arial); loadFromFBX(&mesh, "resource\\loop.fbx"); loadFromFBX(&mesh2, "resource\\schachbrett.fbx"); tex1 = { "resource\\ODST_Helmet.png" }; tex2 = { "resource\\test_logo.png" }; createTexture(&tex1); createTexture(&tex2); createActor(&mesh)->preRotate(PI / 2, 1.0f, 0, 0)->preScale(0.5f, 0.5f, 0.5f)->prePos(0, 1.0f, 0)->applyPretransform(); //createActor(&mesh2)->preScale(0.4, 0.4, 0.4)->applyPretransform(); createFirstPersonCamera(&camera); } void drawloop(IndexBuffer* ibuffer, VertexBuffer* vbuffer) { }
21.377358
120
0.676964
ThePixly
11c94aef96b9693f36ccfe4c0f938afca3d0f1f3
2,066
cpp
C++
logic/extensions.cpp
cpuwolf/opentrack
5541cfc68d87c2fc254eb2f2a5aad79831871a88
[ "ISC" ]
1
2018-02-06T08:36:39.000Z
2018-02-06T08:36:39.000Z
logic/extensions.cpp
cpuwolf/opentrack
5541cfc68d87c2fc254eb2f2a5aad79831871a88
[ "ISC" ]
null
null
null
logic/extensions.cpp
cpuwolf/opentrack
5541cfc68d87c2fc254eb2f2a5aad79831871a88
[ "ISC" ]
null
null
null
#include "extensions.hpp" #include <functional> #include "compat/util.hpp" using namespace options; using ext_fun_type = void(IExtension::*)(Pose&); using ext_mask = IExtension::event_mask; using ext_ord = IExtension::event_ordinal; static constexpr struct event_type_mapping { ext_fun_type ptr; ext_mask mask; ext_ord idx; } ordinal_to_function[] = { { &IExtension::process_raw, ext_mask::on_raw, ext_ord::ev_raw, }, { &IExtension::process_before_filter, ext_mask::on_before_filter, ext_ord::ev_before_filter, }, { &IExtension::process_before_mapping, ext_mask::on_before_mapping, ext_ord::ev_before_mapping, }, { &IExtension::process_finished, ext_mask::on_finished, ext_ord::ev_finished, }, }; bool event_handler::is_enabled(const QString& name) { #if 1 return true; #else if (!ext_bundle->contains(name)) return false; return ext_bundle->get<bool>(name); #endif } event_handler::event_handler(Modules::dylib_list const& extensions) : ext_bundle(make_bundle("extensions")) { for (std::shared_ptr<dylib> const& lib : extensions) { std::shared_ptr<IExtension> ext(reinterpret_cast<IExtension*>(lib->Constructor())); std::shared_ptr<IExtensionDialog> dlg(reinterpret_cast<IExtensionDialog*>(lib->Dialog())); std::shared_ptr<Metadata> m(reinterpret_cast<Metadata*>(lib->Meta())); const ext_mask mask = ext->hook_types(); if (!is_enabled(lib->module_name)) continue; #if 1 qDebug() << "extension" << lib->module_name << "mask" << (void*)mask; #endif for (event_type_mapping const& mapping : ordinal_to_function) { const unsigned i = mapping.idx; const ext_mask mask_ = mapping.mask; if (mask & mask_) extensions_for_event[i].push_back({ ext, dlg, m }); } } } void event_handler::run_events(event_ordinal k, Pose& pose) { auto fun = std::mem_fn(ordinal_to_function[k].ptr); for (extension& x : extensions_for_event[k]) fun(*x.logic, pose); }
28.694444
107
0.674734
cpuwolf
11cbcf069349a496a1f758a35b9ac9c0e03b8f24
1,924
cpp
C++
src/math/fft.cpp
SYury/mipt-zzzzz-teambook
72731effc3ccc279ed670ed712a3f76c524865ac
[ "MIT" ]
null
null
null
src/math/fft.cpp
SYury/mipt-zzzzz-teambook
72731effc3ccc279ed670ed712a3f76c524865ac
[ "MIT" ]
null
null
null
src/math/fft.cpp
SYury/mipt-zzzzz-teambook
72731effc3ccc279ed670ed712a3f76c524865ac
[ "MIT" ]
null
null
null
typedef complex<double> ftype; const double pi = acos(-1); ftype w[maxn]; template<typename T> void fft(T *in, ftype *out, int n, int k = 1) { if(n == 1) { *out = *in; return; } n /= 2; fft(in, out, n, 2 * k); fft(in + k, out + n, n, 2 * k); for(int i = 0; i < n; i++) { ftype t = out[i + n] * w[i + n]; out[i + n] = out[i] - t; out[i] += t; } } vector<int> nrm(vector<int> x) { while(x.size() && x.back() == 0) { x.pop_back(); } return x; } vector<int> mul(vector<int> a, vector<int> b) { int n = a.size() + b.size() - 1; while(__builtin_popcount(n) != 1) { n++; } while((int)a.size() < n) { a.push_back(0); } while((int)b.size() < n) { b.push_back(0); } static ftype A[maxn], B[maxn]; static ftype C[maxn], D[maxn]; for(int i = 0; i < n; i++) { A[i] = {a[i] & mask, a[i] >> shift}; B[i] = {b[i] & mask, b[i] >> shift}; } fft(A, C, n); fft(B, D, n); for(int i = 0; i < n; i++) { ftype c0 = (C[i] + conj(C[(n - i) % n])) / ftype(2, 0); ftype c1 = (C[i] - conj(C[(n - i) % n])) / ftype(0, 2); ftype d0 = (D[i] + conj(D[(n - i) % n])) / ftype(2, 0); ftype d1 = (D[i] - conj(D[(n - i) % n])) / ftype(0, 2); A[i] = c0 * d0 + ftype(0, 1) * c1 * d1; B[i] = c0 * d1 + d0 * c1; } fft(A, C, n); fft(B, D, n); reverse(C + 1, C + n); reverse(D + 1, D + n); for(int i = 0; i < n; i++) { int64_t A0 = llround(real(C[i]) / n); int64_t A1 = llround(real(D[i]) / n); int64_t A2 = llround(imag(C[i]) / n); a[i] = (A0 + (A1 % mod << shift) + (A2 % mod << 2 * shift)) % mod; } return a; } void init() { for(int i = 1; i < maxn; i *= 2) { for(int j = 0; j < i; j++) { w[i + j] = polar(1., pi * j / i); } } }
25.653333
74
0.405405
SYury
11d0f9de17d3fc48efa7122e43a9d2f769acd6c1
2,559
cpp
C++
src/services/pcn-nat/src/serializer/NatJsonObject.cpp
francescomessina/polycube
38f2fb4ffa13cf51313b3cab9994be738ba367be
[ "ECL-2.0", "Apache-2.0" ]
337
2018-12-12T11:50:15.000Z
2022-03-15T00:24:35.000Z
src/services/pcn-nat/src/serializer/NatJsonObject.cpp
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
253
2018-12-17T21:36:15.000Z
2022-01-17T09:30:42.000Z
src/services/pcn-nat/src/serializer/NatJsonObject.cpp
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
90
2018-12-19T15:49:38.000Z
2022-03-27T03:56:07.000Z
/** * nat API * nat API generated from nat.yang * * OpenAPI spec version: 1.0.0 * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/polycube-network/swagger-codegen.git * branch polycube */ /* Do not edit this file manually */ #include "NatJsonObject.h" #include <regex> namespace io { namespace swagger { namespace server { namespace model { NatJsonObject::NatJsonObject() { m_nameIsSet = false; m_ruleIsSet = false; m_nattingTableIsSet = false; } NatJsonObject::NatJsonObject(const nlohmann::json &val) : JsonObjectBase(val) { m_nameIsSet = false; m_ruleIsSet = false; m_nattingTableIsSet = false; if (val.count("name")) { setName(val.at("name").get<std::string>()); } if (val.count("rule")) { if (!val["rule"].is_null()) { RuleJsonObject newItem { val["rule"] }; setRule(newItem); } } if (val.count("natting-table")) { for (auto& item : val["natting-table"]) { NattingTableJsonObject newItem{ item }; m_nattingTable.push_back(newItem); } m_nattingTableIsSet = true; } } nlohmann::json NatJsonObject::toJson() const { nlohmann::json val = nlohmann::json::object(); if (!getBase().is_null()) { val.update(getBase()); } if (m_nameIsSet) { val["name"] = m_name; } if (m_ruleIsSet) { val["rule"] = JsonObjectBase::toJson(m_rule); } { nlohmann::json jsonArray; for (auto& item : m_nattingTable) { jsonArray.push_back(JsonObjectBase::toJson(item)); } if (jsonArray.size() > 0) { val["natting-table"] = jsonArray; } } return val; } std::string NatJsonObject::getName() const { return m_name; } void NatJsonObject::setName(std::string value) { m_name = value; m_nameIsSet = true; } bool NatJsonObject::nameIsSet() const { return m_nameIsSet; } RuleJsonObject NatJsonObject::getRule() const { return m_rule; } void NatJsonObject::setRule(RuleJsonObject value) { m_rule = value; m_ruleIsSet = true; } bool NatJsonObject::ruleIsSet() const { return m_ruleIsSet; } void NatJsonObject::unsetRule() { m_ruleIsSet = false; } const std::vector<NattingTableJsonObject>& NatJsonObject::getNattingTable() const{ return m_nattingTable; } void NatJsonObject::addNattingTable(NattingTableJsonObject value) { m_nattingTable.push_back(value); m_nattingTableIsSet = true; } bool NatJsonObject::nattingTableIsSet() const { return m_nattingTableIsSet; } void NatJsonObject::unsetNattingTable() { m_nattingTableIsSet = false; } } } } }
17.895105
82
0.677999
francescomessina
11d5afa4c990b22e96b78db375dc349177a406bb
11,589
cpp
C++
src/plugins/blogique/core.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
1
2017-01-12T07:05:45.000Z
2017-01-12T07:05:45.000Z
src/plugins/blogique/core.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
src/plugins/blogique/core.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2010-2012 Oleg Linkin * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #include "core.h" #include <QtDebug> #include <QTimer> #include <QMessageBox> #include <QMainWindow> #include <interfaces/iplugin2.h> #include <interfaces/core/irootwindowsmanager.h> #include <util/xpc/util.h> #include <util/xpc/notificationactionhandler.h> #include "interfaces/blogique/ibloggingplatformplugin.h" #include "interfaces/blogique/ibloggingplatform.h" #include "commentsmanager.h" #include "exportwizard.h" #include "pluginproxy.h" #include "storagemanager.h" #include "blogiquewidget.h" #include "xmlsettingsmanager.h" namespace LeechCraft { namespace Blogique { Core::Core () : PluginProxy_ (std::make_shared<PluginProxy> ()) , StorageManager_ (new StorageManager ("org.LeechCraft.Blogique", this)) , CommentsManager_ (new CommentsManager (this)) , AutoSaveTimer_ (new QTimer (this)) { connect (AutoSaveTimer_, SIGNAL (timeout ()), this, SIGNAL (checkAutoSave ())); XmlSettingsManager::Instance ().RegisterObject ("AutoSave", this, "handleAutoSaveIntervalChanged"); handleAutoSaveIntervalChanged (); } Core& Core::Instance () { static Core c; return c; } QIcon Core::GetIcon () const { static QIcon icon ("lcicons:/plugins/blogique/resources/images/blogique.svg"); return icon; } void Core::SetCoreProxy (ICoreProxy_ptr proxy) { Proxy_ = proxy; } ICoreProxy_ptr Core::GetCoreProxy () { return Proxy_; } void Core::AddPlugin (QObject *plugin) { IPlugin2 *plugin2 = qobject_cast<IPlugin2*> (plugin); if (!plugin2) { qWarning () << Q_FUNC_INFO << plugin << "isn't a IPlugin2"; return; } QByteArray sig = QMetaObject::normalizedSignature ("initPlugin (QObject*)"); if (plugin->metaObject ()->indexOfMethod (sig) != -1) QMetaObject::invokeMethod (plugin, "initPlugin", Q_ARG (QObject*, PluginProxy_.get ())); QSet<QByteArray> classes = plugin2->GetPluginClasses (); if (classes.contains ("org.LeechCraft.Plugins.Blogique.Plugins.IBlogPlatformPlugin")) AddBlogPlatformPlugin (plugin); } QList<IBloggingPlatform*> Core::GetBloggingPlatforms () const { QList<IBloggingPlatform*> result; std::for_each (BlogPlatformPlugins_.begin (), BlogPlatformPlugins_.end (), [&result] (decltype (BlogPlatformPlugins_.front ()) bpp) { const auto& protos = qobject_cast<IBloggingPlatformPlugin*> (bpp)-> GetBloggingPlatforms (); Q_FOREACH (QObject *obj, protos) result << qobject_cast<IBloggingPlatform*> (obj); }); result.removeAll (0); return result; } QList<IAccount*> Core::GetAccounts () const { auto bloggingPlatforms = GetBloggingPlatforms (); QList<IAccount*> result; std::for_each (bloggingPlatforms.begin (), bloggingPlatforms.end (), [&result] (decltype (bloggingPlatforms.front ()) bp) { const auto& accountsObjList = bp->GetRegisteredAccounts (); std::transform (accountsObjList.begin (), accountsObjList.end (), std::back_inserter (result), [] (decltype (accountsObjList.front ()) accountObj) { return qobject_cast<IAccount*> (accountObj); }); }); result.removeAll (0); return result; } IAccount* Core::GetAccountByID (const QByteArray& id) const { for (auto acc : GetAccounts ()) if (acc->GetAccountID () == id) return acc; return 0; } void Core::SendEntity (const Entity& e) { emit gotEntity (e); } void Core::DelayedProfilesUpdate () { QTimer::singleShot (15000, this, SLOT (updateProfiles ())); } StorageManager* Core::GetStorageManager () const { return StorageManager_; } CommentsManager* Core::GetCommentsManager () const { return CommentsManager_; } BlogiqueWidget* Core::CreateBlogiqueWidget () { auto newTab = new BlogiqueWidget; connect (newTab, SIGNAL (removeTab (QWidget*)), &Core::Instance (), SIGNAL (removeTab (QWidget*))); connect (&Core::Instance (), SIGNAL (checkAutoSave ()), newTab, SLOT (handleAutoSave ())); connect (&Core::Instance (), SIGNAL (entryPosted ()), newTab, SLOT (handleEntryPosted ())); connect (&Core::Instance (), SIGNAL (entryRemoved ()), newTab, SLOT (handleEntryRemoved ())); connect (&Core::Instance (), SIGNAL (tagsUpdated (QHash<QString, int>)), newTab, SLOT (handleTagsUpdated (QHash<QString, int>))); connect (&Core::Instance (), SIGNAL (insertTag (QString)), newTab, SLOT (handleInsertTag (QString))); connect (&Core::Instance (), SIGNAL (gotError (int, QString, QString)), newTab, SLOT (handleGotError (int, QString, QString))); connect (&Core::Instance (), SIGNAL (gotError (int, QString, QString)), newTab, SLOT (handleGotError (int, QString, QString))); connect (&Core::Instance (), SIGNAL (accountAdded (QObject*)), newTab, SLOT (handleAccountAdded (QObject*))); connect (&Core::Instance (), SIGNAL (accountRemoved (QObject*)), newTab, SLOT (handleAccountRemoved (QObject*))); return newTab; } void Core::AddBlogPlatformPlugin (QObject *plugin) { IBloggingPlatformPlugin *ibpp = qobject_cast<IBloggingPlatformPlugin*> (plugin); if (!ibpp) qWarning () << Q_FUNC_INFO << "plugin" << plugin << "tells it implements the IBlogPlatformPlugin but cast failed"; else { BlogPlatformPlugins_ << plugin; handleNewBloggingPlatforms (ibpp->GetBloggingPlatforms ()); } } void Core::handleNewBloggingPlatforms (const QObjectList& platforms) { Q_FOREACH (QObject *platformObj, platforms) { IBloggingPlatform *platform = qobject_cast<IBloggingPlatform*> (platformObj); Q_FOREACH (QObject *accObj, platform->GetRegisteredAccounts ()) addAccount (accObj); connect (platform->GetQObject (), SIGNAL (accountAdded (QObject*)), this, SLOT (addAccount (QObject*))); connect (platform->GetQObject (), SIGNAL (accountRemoved (QObject*)), this, SLOT (handleAccountRemoved (QObject*))); connect (platform->GetQObject (), SIGNAL (accountValidated (QObject*, bool)), this, SLOT (handleAccountValidated (QObject*, bool))); connect (platform->GetQObject (), SIGNAL (insertTag (QString)), this, SIGNAL (insertTag (QString))); } } void Core::addAccount (QObject *accObj) { IAccount *account = qobject_cast<IAccount*> (accObj); if (!account) { qWarning () << Q_FUNC_INFO << "account doesn't implement IAccount*" << accObj << sender (); return; } connect (accObj, SIGNAL (requestEntriesBegin ()), this, SIGNAL (requestEntriesBegin ())); connect (accObj, SIGNAL (entryPosted (QList<Entry>)), this, SLOT (handleEntryPosted (QList<Entry>))); connect (accObj, SIGNAL (entryRemoved (int)), this, SLOT (handleEntryRemoved (int))); connect (accObj, SIGNAL (entryUpdated (QList<Entry>)), this, SLOT (handleEntryUpdated (QList<Entry>))); connect (accObj, SIGNAL (tagsUpdated (QHash<QString, int>)), this, SIGNAL (tagsUpdated (QHash<QString, int>))); connect (accObj, SIGNAL (gotRecentComments (QList<CommentEntry>)), CommentsManager_, SLOT (handleGotRecentComments (QList<CommentEntry>))); connect (accObj, SIGNAL (commentsDeleted (QList<qint64>)), CommentsManager_, SLOT (handleCommentsDeleted (QList<qint64>))); connect (accObj, SIGNAL (gotError (int, QString, QString)), this, SIGNAL (gotError (int, QString, QString))); emit accountAdded (accObj); } void Core::handleAccountRemoved (QObject *accObj) { IAccount *acc = qobject_cast<IAccount*> (accObj); if (!acc) { qWarning () << Q_FUNC_INFO << "account doesn't implement IAccount*" << accObj << sender (); return; } emit accountRemoved (accObj); } void Core::handleAccountValidated (QObject *accObj, bool validated) { IAccount *acc = qobject_cast<IAccount*> (accObj); if (!acc) { qWarning () << Q_FUNC_INFO << "account doesn't implement IAccount*" << accObj << sender (); return; } emit accountValidated (accObj, validated); } void Core::updateProfiles () { for (auto acc : GetAccounts ()) acc->updateProfile (); } void Core::handleEntryPosted (const QList<Entry>& entries) { auto acc = qobject_cast<IAccount*> (sender ()); if (!acc) return; auto e = Util::MakeNotification ("Blogique", tr ("Entry was posted successfully:") + QString (" <a href=\"%1\">%1</a>\n") .arg (entries.value (0).EntryUrl_.toString ()), Priority::PInfo_); auto nh = new Util::NotificationActionHandler (e, this); nh->AddFunction (tr ("Open Link"), [this, entries] () { auto urlEntity = Util::MakeEntity (entries.value (0).EntryUrl_, {}, OnlyHandle | FromUserInitiated); SendEntity (urlEntity); }); emit gotEntity (e); acc->RequestStatistics (); acc->RequestTags (); emit entryPosted (); } void Core::handleEntryRemoved (int) { auto acc = qobject_cast<IAccount*> (sender ()); if (!acc) return; SendEntity (Util::MakeNotification ("Blogique", tr ("Entry was removed successfully."), Priority::PInfo_)); acc->RequestStatistics (); acc->RequestTags (); emit entryRemoved (); } void Core::handleEntryUpdated (const QList<Entry>& entries) { auto acc = qobject_cast<IAccount*> (sender ()); if (!acc) return; if (entries.isEmpty ()) return; SendEntity (Util::MakeNotification ("Blogique", tr ("Entry was updated successfully."), Priority::PInfo_)); acc->RequestStatistics (); acc->RequestTags (); } void Core::handleAutoSaveIntervalChanged () { AutoSaveTimer_->start (XmlSettingsManager::Instance () .property ("AutoSave").toInt () * 1000); } void Core::exportBlog () { ExportWizard *wizard = new ExportWizard (Proxy_->GetRootWindowsManager ()-> GetPreferredWindow ()); wizard->setWindowTitle (tr ("Export blog")); wizard->show (); } } }
27.462085
87
0.670377
MellonQ
11d6afa8d19152ec96b88173ac1146576b9201f2
1,026
cpp
C++
aprindere/a.cpp
MarianVasilca/The100DayProject
df207c5a96b917a8a0134d9138bf000400120746
[ "MIT" ]
null
null
null
aprindere/a.cpp
MarianVasilca/The100DayProject
df207c5a96b917a8a0134d9138bf000400120746
[ "MIT" ]
null
null
null
aprindere/a.cpp
MarianVasilca/The100DayProject
df207c5a96b917a8a0134d9138bf000400120746
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> using namespace std; ifstream fin("aprindere.in"); ofstream fout("aprindere.out"); const int NMax = 1005; int N, M, T[NMax]; bool Room[NMax]; vector < int > V[NMax]; int Result; void Read() { fin >> N >> M; for(int i = 0; i < N; i++) fin >> Room[ i ]; for(int i = 0; i < M; i++) { int room, total_rooms, temp_room; fin >> room; fin >> T[ room ] >> total_rooms; for(int j = 0; j < total_rooms; j++) { fin >> temp_room; V[room].push_back(temp_room); } } } void Solve() { for(int i = 0; i < N; i++) { if(!Room [ i ]) { Result += T[ i ]; for(unsigned int j = 0; j < V[ i ].size(); j++) { int Neighbor = V[ i ][ j ]; Room [ Neighbor ] = !Room[ Neighbor ]; } } } fout << Result << "\n"; } int main() { Read(); Solve(); return 0; }
16.819672
59
0.437622
MarianVasilca
11d903a7f33944dee2c22ff52b49ff48e55aa65f
1,005
cpp
C++
Infrastructure/KEI.Infrastructure.CLR/ViewService.cpp
athulrajts/Resusables
0ef297ab0501b305589402d0aec0c1da80313b04
[ "MIT" ]
null
null
null
Infrastructure/KEI.Infrastructure.CLR/ViewService.cpp
athulrajts/Resusables
0ef297ab0501b305589402d0aec0c1da80313b04
[ "MIT" ]
null
null
null
Infrastructure/KEI.Infrastructure.CLR/ViewService.cpp
athulrajts/Resusables
0ef297ab0501b305589402d0aec0c1da80313b04
[ "MIT" ]
null
null
null
#pragma once #include "pch.h" #include "ViewService.h" #include "ViewServiceNativeWrapper.h" void ViewService::AutoInitialize() { ViewServiceNativeWrapper::AutoInitialize(); } void ViewService::InitializeBaseViewService() { ViewServiceNativeWrapper::InitializeBaseViewService(); } void ViewService::ErrorDialog(std::string message, bool is_modal) { ViewServiceNativeWrapper::ErrorDialog(message, is_modal); } void ViewService::WarningDialog(std::string message, bool is_modal) { ViewServiceNativeWrapper::WarningDialog(message, is_modal); } void ViewService::InformationDialog(std::string message, bool is_modal) { ViewServiceNativeWrapper::InformationDialog(message, is_modal); } PromptResult ViewService::PromptDialog(std::string message, PromptOptions option) { return ViewServiceNativeWrapper::PromptDialog(message, option); } std::string ViewService::BrowseFile(std::string filterName, std::string fileterExts) { return ViewServiceNativeWrapper::BrowseFile(filterName, fileterExts); }
24.512195
84
0.806965
athulrajts
11e27b71ae3749e8135fba827b08b6b6a8a5de7f
3,308
cpp
C++
Userland/Libraries/LibJS/Runtime/BoundFunction.cpp
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
19,438
2019-05-20T15:11:11.000Z
2022-03-31T23:31:32.000Z
Userland/Libraries/LibJS/Runtime/BoundFunction.cpp
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
7,882
2019-05-20T01:03:52.000Z
2022-03-31T23:26:31.000Z
Userland/Libraries/LibJS/Runtime/BoundFunction.cpp
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
2,721
2019-05-23T00:44:57.000Z
2022-03-31T22:49:34.000Z
/* * Copyright (c) 2020, Jack Karamanian <karamanian.jack@gmail.com> * Copyright (c) 2021, Linus Groh <linusg@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #include <LibJS/Runtime/AbstractOperations.h> #include <LibJS/Runtime/BoundFunction.h> #include <LibJS/Runtime/GlobalObject.h> namespace JS { BoundFunction::BoundFunction(GlobalObject& global_object, FunctionObject& bound_target_function, Value bound_this, Vector<Value> bound_arguments, i32 length, Object* constructor_prototype) : FunctionObject(*global_object.function_prototype()) , m_bound_target_function(&bound_target_function) , m_bound_this(bound_this) , m_bound_arguments(move(bound_arguments)) , m_constructor_prototype(constructor_prototype) , m_name(String::formatted("bound {}", bound_target_function.name())) , m_length(length) { } void BoundFunction::initialize(GlobalObject& global_object) { auto& vm = this->vm(); Base::initialize(global_object); define_direct_property(vm.names.length, Value(m_length), Attribute::Configurable); } BoundFunction::~BoundFunction() { } // 10.4.1.1 [[Call]] ( thisArgument, argumentsList ), https://tc39.es/ecma262/#sec-bound-function-exotic-objects-call-thisargument-argumentslist ThrowCompletionOr<Value> BoundFunction::internal_call([[maybe_unused]] Value this_argument, MarkedValueList arguments_list) { // 1. Let target be F.[[BoundTargetFunction]]. auto& target = *m_bound_target_function; // 2. Let boundThis be F.[[BoundThis]]. auto bound_this = m_bound_this; // 3. Let boundArgs be F.[[BoundArguments]]. auto& bound_args = m_bound_arguments; // 4. Let args be the list-concatenation of boundArgs and argumentsList. auto args = MarkedValueList { heap() }; args.extend(bound_args); args.extend(move(arguments_list)); // 5. Return ? Call(target, boundThis, args). return call(global_object(), &target, bound_this, move(args)); } // 10.4.1.2 [[Construct]] ( argumentsList, newTarget ), https://tc39.es/ecma262/#sec-bound-function-exotic-objects-construct-argumentslist-newtarget ThrowCompletionOr<Object*> BoundFunction::internal_construct(MarkedValueList arguments_list, FunctionObject& new_target) { // 1. Let target be F.[[BoundTargetFunction]]. auto& target = *m_bound_target_function; // 2. Assert: IsConstructor(target) is true. VERIFY(Value(&target).is_constructor()); // 3. Let boundArgs be F.[[BoundArguments]]. auto& bound_args = m_bound_arguments; // 4. Let args be the list-concatenation of boundArgs and argumentsList. auto args = MarkedValueList { heap() }; args.extend(bound_args); args.extend(move(arguments_list)); // 5. If SameValue(F, newTarget) is true, set newTarget to target. auto* final_new_target = &new_target; if (this == &new_target) final_new_target = &target; // 6. Return ? Construct(target, args, newTarget). return construct(global_object(), target, move(args), final_new_target); } void BoundFunction::visit_edges(Visitor& visitor) { Base::visit_edges(visitor); visitor.visit(m_bound_target_function); visitor.visit(m_bound_this); for (auto argument : m_bound_arguments) visitor.visit(argument); visitor.visit(m_constructor_prototype); } }
34.458333
188
0.727328
r00ster91
11e5c9efdf01e3677d4334c92efee3985861cd27
355
cpp
C++
C++/std/template/template.cpp
Martinfx/C-Learn
7e8d55a4ee45f66b96cf5235f2259b4d465d3db2
[ "Apache-2.0" ]
16
2017-08-15T22:25:43.000Z
2020-01-03T22:51:06.000Z
C++/std/template/template.cpp
Martinfx/C-Learn
7e8d55a4ee45f66b96cf5235f2259b4d465d3db2
[ "Apache-2.0" ]
null
null
null
C++/std/template/template.cpp
Martinfx/C-Learn
7e8d55a4ee45f66b96cf5235f2259b4d465d3db2
[ "Apache-2.0" ]
3
2017-11-23T04:35:14.000Z
2019-03-21T06:42:52.000Z
#include <iostream> /* namespace utils { template<class T> inline bool operator!= (const T& x, const T& y) { return !(x == y); } template<class T> inline bool operator> (const T& x, const T& y) { return (y < x); } template<class T> inline bool operator<= (const T& x, const T& y) { return !(y < x ); } }*/ int main() { return 0; }
14.2
49
0.577465
Martinfx
eb1b398c17441adc3497135d69d0d1455789d7f1
2,489
cpp
C++
unittests/rapidschema/schema/schema_test.cpp
ledergec/rapidschema
3a43202b604f5f036abc6ebfbac5d3e1112b3347
[ "Apache-2.0" ]
3
2019-02-07T16:14:20.000Z
2019-03-06T01:38:38.000Z
unittests/rapidschema/schema/schema_test.cpp
ledergec/rapidschema
3a43202b604f5f036abc6ebfbac5d3e1112b3347
[ "Apache-2.0" ]
26
2019-01-10T16:23:15.000Z
2019-04-30T21:13:17.000Z
unittests/rapidschema/schema/schema_test.cpp
ledergec/rapidschema
3a43202b604f5f036abc6ebfbac5d3e1112b3347
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2019 Christian Ledergerber #ifdef RAPIDSCHEMA_WITH_SCHEMA_GENERATION #include <gtest/gtest.h> #include <gmock/gmock.h> #include "rapidschema/ostream_operators.h" #include "rapidschema/schema/object_schema.h" #include "rapidschema/test_utils.h" namespace rapidschema { namespace schema { using testing::Test; class SchemaTest : public Test { public: ObjectSchema object_; }; /////////////////////////// Parse DOM Style ///////////////////////////////////////////// TEST_F(SchemaTest, CanParseSchema) { auto result = ParseConfig(R"( { "type": "object", "properties": { "integerProperty": { "type": "integer", "minimum": 10, "maximum": 20, "exclusiveMinimum": 5, "exclusiveMaximum": 30 }, "numberProperty": { "type":"number", "minimum": 10.0, "maximum": 20.0, "exclusiveMinimum": 5.0, "exclusiveMaximum": 30.0 }, "stringProperty": { "type": "string", "minLength": 10, "maxLength": 20 }, "constStringProperty": { "const": "constant string value" }, "constIntegerProperty": { "const": 1 }, "constNumberProperty": { "const": 1.0 }, "oneOfProperty": { "oneOf": [ { "type": "number", "multipleOf": 5.0 }, { "type": "number", "multipleOf": 3.0 } ] } }, "patternProperties": { "patternProperty1.*": { "type": "object" } }, "additionalProperties": false, "required": ["property1"] } )", &object_); std::cout << result << std::endl; ASSERT_TRUE(result.Success()); } } // namespace schema } // namespace rapidschema #endif
30.728395
89
0.376456
ledergec
eb1b92ffacbf27fd93c6b2d9834c2fa859e9a6c3
5,186
cpp
C++
worker/src/RTC/RembClient.cpp
liwf616/mediasoup
99d1c696bd4b985ea8bf5348b7f520998e165c32
[ "ISC" ]
2
2020-09-03T01:37:57.000Z
2020-09-03T01:38:15.000Z
worker/src/RTC/RembClient.cpp
liwf616/mediasoup
99d1c696bd4b985ea8bf5348b7f520998e165c32
[ "ISC" ]
1
2021-08-24T01:39:43.000Z
2021-08-24T01:39:43.000Z
worker/src/RTC/RembClient.cpp
baiyfcu/mediasoup
fede86766ad87b184ef139dfe631b30a82506451
[ "0BSD" ]
1
2021-06-11T10:53:24.000Z
2021-06-11T10:53:24.000Z
#define MS_CLASS "RTC::RembClient" // #define MS_LOG_DEV #include "RTC/RembClient.hpp" #include "DepLibUV.hpp" #include "Logger.hpp" namespace RTC { /* Static. */ static constexpr uint64_t EventInterval{ 2000 }; // In ms. static constexpr uint64_t MaxElapsedTime{ 5000 }; // In ms. static constexpr uint64_t InitialAvailableBitrateDuration{ 8000 }; // in ms. /* Instance methods. */ RembClient::RembClient( RTC::RembClient::Listener* listener, uint32_t initialAvailableBitrate, uint32_t minimumAvailableBitrate) : listener(listener), initialAvailableBitrate(initialAvailableBitrate), minimumAvailableBitrate(minimumAvailableBitrate) { MS_TRACE(); } RembClient::~RembClient() { MS_TRACE(); } void RembClient::ReceiveRembFeedback(RTC::RTCP::FeedbackPsRembPacket* remb) { MS_TRACE(); auto previousAvailableBitrate = this->availableBitrate; uint64_t now = DepLibUV::GetTime(); bool notify{ false }; CheckStatus(now); // Update availableBitrate. this->availableBitrate = static_cast<uint32_t>(remb->GetBitrate()); // If REMB reports less than initialAvailableBitrate during // InitialAvailableBitrateDuration, honor initialAvailableBitrate. // clang-format off if ( this->availableBitrate < this->initialAvailableBitrate && now - this->initialAvailableBitrateAt <= InitialAvailableBitrateDuration ) // clang-format on { this->availableBitrate = this->initialAvailableBitrate; } // Otherwise if REMB reports less than minimumAvailableBitrate, honor it. else if (this->availableBitrate < this->minimumAvailableBitrate) { this->availableBitrate = this->minimumAvailableBitrate; } // Emit event if EventInterval elapsed. if (now - this->lastEventAt >= EventInterval) { notify = true; } // Also emit the event fast if we detect a high REMB value decrease. else if (this->availableBitrate < previousAvailableBitrate * 0.75) { MS_WARN_TAG( bwe, "high REMB value decrease detected, notifying the listener [before:%" PRIu32 ", now:%" PRIu32 "]", previousAvailableBitrate, this->availableBitrate); notify = true; } if (notify) { this->lastEventAt = now; this->listener->OnRembClientAvailableBitrate(this, this->availableBitrate); } CalculateProbationTargetBitrate(); } void RembClient::SentRtpPacket(RTC::RtpPacket* packet, bool /*retransmitted*/) { MS_TRACE(); // Increase transmission counter. this->transmissionCounter.Update(packet); } void RembClient::SentProbationRtpPacket(RTC::RtpPacket* packet) { MS_TRACE(); MS_DEBUG_DEV("[seq:%" PRIu16 ", size:%zu]", packet->GetSequenceNumber(), packet->GetSize()); // Increase probation transmission counter. this->probationTransmissionCounter.Update(packet); } uint32_t RembClient::GetAvailableBitrate() { MS_TRACE(); uint64_t now = DepLibUV::GetTime(); CheckStatus(now); return this->availableBitrate; } void RembClient::ResecheduleNextEvent() { MS_TRACE(); this->lastEventAt = DepLibUV::GetTime(); } bool RembClient::IsProbationNeeded() { MS_TRACE(); if (!this->probationTargetBitrate) return false; auto now = DepLibUV::GetTime(); auto probationTransmissionBitrate = this->probationTransmissionCounter.GetBitrate(now); return (probationTransmissionBitrate <= this->probationTargetBitrate); } inline void RembClient::CheckStatus(uint64_t now) { MS_TRACE(); if (now - this->lastEventAt > MaxElapsedTime) { MS_DEBUG_DEV(bwe, "resetting REMB client"); this->initialAvailableBitrateAt = now; this->availableBitrate = this->initialAvailableBitrate; CalculateProbationTargetBitrate(); } } inline void RembClient::CalculateProbationTargetBitrate() { MS_TRACE(); auto previousProbationTargetBitrate = this->probationTargetBitrate; this->probationTargetBitrate = 0; if (this->availableBitrate == 0) return; uint64_t now = DepLibUV::GetTime(); auto transmissionBitrate = this->transmissionCounter.GetBitrate(now); auto factor = static_cast<float>(transmissionBitrate) / static_cast<float>(this->availableBitrate); // Just consider probation if transmission bitrate is close to available bitrate // (without exceeding it much). if (factor >= 0.8 && factor <= 1.2) { if (this->availableBitrate > transmissionBitrate) this->probationTargetBitrate = 2 * (this->availableBitrate - transmissionBitrate); else this->probationTargetBitrate = 0.5 * transmissionBitrate; } // If there is no bitrate, set available bitrate as probation target bitrate. else if (factor == 0) { this->probationTargetBitrate = this->availableBitrate; } if (this->probationTargetBitrate != previousProbationTargetBitrate) { MS_DEBUG_TAG( bwe, "probation %s [bitrate:%" PRIu32 ", availableBitrate:%" PRIu32 ", factor:%f, probationTargetBitrate:%" PRIu32 "]", this->probationTargetBitrate ? "enabled" : "disabled", transmissionBitrate, this->availableBitrate, factor, this->probationTargetBitrate); } } } // namespace RTC
25.93
94
0.707675
liwf616
eb21bd57582ca283642401a4502c769b9313fc2d
7,516
cpp
C++
test/flatzinc/test_fzn_comparison.cpp
SaGagnon/gecode-5.5.0-cbs
e871b320a9b2031423bb0fa452b1a5c09641a041
[ "MIT-feh" ]
1
2020-06-26T11:10:55.000Z
2020-06-26T11:10:55.000Z
test/flatzinc/test_fzn_comparison.cpp
SaGagnon/gecode-5.5.0-cbs
e871b320a9b2031423bb0fa452b1a5c09641a041
[ "MIT-feh" ]
null
null
null
test/flatzinc/test_fzn_comparison.cpp
SaGagnon/gecode-5.5.0-cbs
e871b320a9b2031423bb0fa452b1a5c09641a041
[ "MIT-feh" ]
1
2020-06-26T11:10:57.000Z
2020-06-26T11:10:57.000Z
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <tack@gecode.org> * * Copyright: * Guido Tack, 2014 * * Last modified: * $Date: 2014-11-04 13:28:32 +0100 (Tue, 04 Nov 2014) $ by $Author: schulte $ * $Revision: 14287 $ * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #include "test/flatzinc.hh" namespace Test { namespace FlatZinc { namespace { /// Helper class to create and register tests class Create { public: /// Perform creation and registration Create(void) { (void) new FlatZincTest("fzn_comparison", "var bool: b1;\n\ var bool: b2;\n\ var bool: b3;\n\ var bool: b4;\n\ var bool: b5;\n\ var bool: b6;\n\ \n\ var bool: rb1;\n\ var bool: rb2;\n\ var bool: rb3;\n\ var bool: rb4;\n\ var bool: rb5;\n\ var bool: rb6;\n\ \n\ var 1.0..10.0: f1;\n\ var 1.0..10.0: f2;\n\ var 1.0..10.0: f3;\n\ var 1.0..10.0: f4;\n\ var 1.0..10.0: f5;\n\ var 1.0..10.0: f6;\n\ \n\ var bool: rf1;\n\ var bool: rf2;\n\ var bool: rf3;\n\ var bool: rf4;\n\ var bool: rf5;\n\ var bool: rf6;\n\ \n\ var 1..10: i1;\n\ var 1..10: i2;\n\ var 1..10: i3;\n\ var 1..10: i4;\n\ var 1..10: i5;\n\ var 1..10: i6;\n\ \n\ var bool: ri1;\n\ var bool: ri2;\n\ var bool: ri3;\n\ var bool: ri4;\n\ var bool: ri5;\n\ var bool: ri6;\n\ \n\ array [1..3] of var 1.0..10.0: fa1;\n\ array [1..3] of var 1.0..10.0: fa2;\n\ array [1..3] of var 1.0..10.0: fa3;\n\ array [1..3] of var 1.0..10.0: fa4;\n\ array [1..3] of var 1.0..10.0: fa5;\n\ \n\ var bool: rfa1;\n\ var bool: rfa2;\n\ var bool: rfa3;\n\ var bool: rfa4;\n\ var bool: rfa5;\n\ \n\ array [1..3] of var 1..10: ia1;\n\ array [1..3] of var 1..10: ia2;\n\ array [1..3] of var 1..10: ia3;\n\ array [1..3] of var 1..10: ia4;\n\ array [1..3] of var 1..10: ia5;\n\ \n\ var bool: ria1;\n\ var bool: ria2;\n\ var bool: ria3;\n\ var bool: ria4;\n\ var bool: ria5;\n\ \n\ var set of 1..3: s1;\n\ var set of 1..3: s2;\n\ var set of 1..3: s3;\n\ var set of 1..3: s4;\n\ var set of 1..3: s5;\n\ var set of 1..3: s6;\n\ \n\ var bool: rs1;\n\ var bool: rs2;\n\ var bool: rs3;\n\ var bool: rs4;\n\ var bool: rs5;\n\ var bool: rs6;\n\ \n\ % int_{lt,le,eq,ne}\n\ \n\ constraint int_lt(2, 3);\n\ constraint int_lt(2, i1);\n\ constraint int_lt(i1, 9);\n\ \n\ constraint int_le(2, 3);\n\ constraint int_le(2, i2);\n\ constraint int_le(i2, 9);\n\ \n\ constraint int_le(2, i3);\n\ constraint int_le(i3, 9);\n\ \n\ constraint int_lt(2, i4);\n\ constraint int_lt(i4, 9);\n\ \n\ constraint int_eq(2, 2);\n\ constraint int_eq(2, i5);\n\ \n\ constraint int_ne(2, 3);\n\ constraint int_ne(1, i6);\n\ \n\ % int_{lt,le,eq,ne}_reif\n\ \n\ constraint int_lt_reif(2, 3, ri1);\n\ constraint int_lt_reif(2, i1, ri1);\n\ constraint int_lt_reif(i1, 9, ri1);\n\ \n\ constraint int_le_reif(2, 3, ri2);\n\ constraint int_le_reif(2, i2, ri2);\n\ constraint int_le_reif(i2, 9, ri2);\n\ \n\ constraint int_le_reif(2, 3, ri3);\n\ constraint int_le_reif(2, i3, ri3);\n\ constraint int_le_reif(i3, 9, ri3);\n\ \n\ constraint int_lt_reif(2, 3, ri4);\n\ constraint int_lt_reif(2, i4, ri4);\n\ constraint int_lt_reif(i4, 9, ri4);\n\ \n\ constraint int_eq_reif(2, 2, ri5);\n\ constraint int_eq_reif(2, i5, ri5);\n\ \n\ constraint int_ne_reif(2, 3, ri6);\n\ constraint int_ne_reif(1, i6, ri6);\n\ \n\ % float_{lt,le,ge,gt,eq,ne}\n\ \n\ % constraint float_lt(2.0, 3.0);\n\ % constraint float_lt(2.0, f1);\n\ % constraint float_lt(f1, 9.0);\n\ \n\ constraint float_le(2.0, 3.0);\n\ constraint float_le(2.0, f2);\n\ constraint float_le(f2, 9.0);\n\ \n\ constraint float_le(2.0, f3);\n\ constraint float_le(f3, 9.0);\n\ \n\ constraint float_eq(2.0, 2.0);\n\ constraint float_eq(2.0, f5);\n\ \n\ % constraint float_ne(2.0, 3.0);\n\ % constraint float_ne(2.0, f6);\n\ \n\ % float_{lt,le,eq,ne}_reif\n\ \n\ % constraint float_lt_reif(2.0, 3.0, rf1);\n\ % constraint float_lt_reif(2.0, f1, rf1);\n\ % constraint float_lt_reif(f1, 9.0, rf1);\n\ \n\ constraint float_le_reif(2.0, 3.0, rf2);\n\ constraint float_le_reif(2.0, f2, rf2);\n\ constraint float_le_reif(f2, 9.0, rf2);\n\ \n\ constraint float_le_reif(2.0, 3.0, rf3);\n\ constraint float_le_reif(2.0, f3, rf3);\n\ constraint float_le_reif(f3, 9.0, rf3);\n\ \n\ constraint float_eq_reif(2.0, 2.0, rf5);\n\ constraint float_eq_reif(2.0, f5, rf5);\n\ \n\ % constraint float_ne_reif(2.0, 3.0, rf6);\n\ % constraint float_ne_reif(2.0, f6, rf6);\n\ \n\ % set_{lt,le,gt,ge,eq,ne}\n\ \n\ constraint set_lt({}, {1, 2, 3});\n\ constraint set_lt({}, s1);\n\ constraint set_lt(s1, {1, 2, 3});\n\ \n\ constraint set_le({}, {1, 2, 3});\n\ constraint set_le({1}, s2);\n\ constraint set_le(s2, {1, 2, 3});\n\ \n\ constraint set_lt({}, {1, 2, 3});\n\ constraint set_lt({}, s3);\n\ constraint set_lt(s3, {1, 2, 3});\n\ \n\ constraint set_le({}, {1, 2, 3});\n\ constraint set_le({1}, s4);\n\ constraint set_le(s4, {1, 2, 3});\n\ \n\ constraint set_eq({1, 2, 3}, {1, 2, 3});\n\ constraint set_eq(s5, {1, 2, 3});\n\ \n\ constraint set_ne({}, {1, 2, 3});\n\ constraint set_ne(s6, {1, 2, 3});\n\ \n\ % int_lin_{lt,le,gt,ge,eq}\n\ \n\ % constraint int_lin_lt([1, 2, 3], [1, 2, 3], 100);\n\ % constraint int_lin_lt([1, 2, 3], ia1, 10);\n\ \n\ constraint int_lin_le([1, 2, 3], [1, 2, 3], 100);\n\ constraint int_lin_le([1, 2, 3], ia2, 10);\n\ \n\ % constraint int_lin_gt([1, 2, 3], [1, 2, 3], 10);\n\ % constraint int_lin_gt([1, 2, 3], ia3, 10);\n\ \n\ constraint int_lin_le([-1, -2, -3], [1, 2, 3], -10);\n\ constraint int_lin_le([-1, -2, -3], ia4, -10);\n\ \n\ constraint int_lin_eq([1, 2, 3], [1, 2, 3], 14);\n\ constraint int_lin_eq([1, 2, 3], ia5, 14);\n\ \n\ % int_lin_{lt,le,gt,ge,eq}_reif\n\ \n\ % constraint int_lin_lt_reif([1, 2, 3], [1, 2, 3], 100, ria1);\n\ % constraint int_lin_lt_reif([1, 2, 3], ia1, 10, ria1);\n\ \n\ constraint int_lin_le_reif([1, 2, 3], [1, 2, 3], 100, ria2);\n\ constraint int_lin_le_reif([1, 2, 3], ia2, 10, ria2);\n\ \n\ % constraint int_lin_gt_reif([1, 2, 3], [1, 2, 3], 10, ria3);\n\ % constraint int_lin_gt_reif([1, 2, 3], ia3, 10, ria3);\n\ \n\ constraint int_lin_le_reif([-1, -2, -3], [1, 2, 3], -10, ria4);\n\ constraint int_lin_le_reif([-1, -2, -3], ia4, -10, ria4);\n\ \n\ constraint int_lin_eq_reif([1, 2, 3], [1, 2, 3], 14, ria5);\n\ constraint int_lin_eq_reif([1, 2, 3], ia5, 14, ria5);\n\ \n\ solve satisfy;\n\ ", "----------\n"); } }; Create c; } }} // STATISTICS: test-flatzinc
26.37193
82
0.629457
SaGagnon
eb226527f12a72f0327adcf8e105df8ccd0f2534
2,266
cpp
C++
plansys2_pddl_parser/test/pddl_parser_test.cpp
movefasta/ros2_planning_system
c058cb16960b49a1c0f7d80280408a27136a9cc2
[ "Apache-2.0" ]
null
null
null
plansys2_pddl_parser/test/pddl_parser_test.cpp
movefasta/ros2_planning_system
c058cb16960b49a1c0f7d80280408a27136a9cc2
[ "Apache-2.0" ]
null
null
null
plansys2_pddl_parser/test/pddl_parser_test.cpp
movefasta/ros2_planning_system
c058cb16960b49a1c0f7d80280408a27136a9cc2
[ "Apache-2.0" ]
null
null
null
// Copyright 2022 Marco Roveri - University of Trento // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include <string> #include <vector> #include <sstream> #include <map> #include <algorithm> #include "rclcpp/rclcpp.hpp" #include "ament_index_cpp/get_package_share_directory.hpp" #include "plansys2_pddl_parser/Instance.h" #include "gtest/gtest.h" using namespace std::chrono_literals; class PDDLParserTestCase : public ::testing::Test { protected: static void SetUpTestCase() { rclcpp::init(0, nullptr); } }; TEST(PDDLParserTestCase, pddl_parser) { std::string pkgpath = ament_index_cpp::get_package_share_directory("plansys2_pddl_parser"); std::string domain_file = pkgpath + "/pddl/dom1.pddl"; std::string instance_file = pkgpath + "/pddl/prob1.pddl"; std::ifstream domain_ifs(domain_file); ASSERT_TRUE(domain_ifs.good()); std::string domain_str(( std::istreambuf_iterator<char>(domain_ifs)), std::istreambuf_iterator<char>()); ASSERT_NE(domain_str, ""); std::ifstream instance_ifs(instance_file); ASSERT_TRUE(instance_ifs.good()); std::string instance_str(( std::istreambuf_iterator<char>(instance_ifs)), std::istreambuf_iterator<char>()); ASSERT_NE(instance_str, ""); // Read domain and instance bool okparse = false; bool okprint = false; try { parser::pddl::Domain domain( domain_str ); parser::pddl::Instance instance( domain, instance_str ); okparse = true; try { std::cout << domain << std::endl; std::cout << instance << std::endl; okprint = true; } catch (std::runtime_error e) { } } catch (std::runtime_error e) { } ASSERT_TRUE(okparse); ASSERT_TRUE(okprint); }
29.815789
93
0.699029
movefasta
eb264b1064b526a6a4f3cc469c456bae41638427
7,878
hpp
C++
preview/cplusplus/examples/hello-encode-cpp/src/util.hpp
alexelizarov/oneVPL
cdf7444dc971544d148c51e0d93a2df1bb55dda7
[ "MIT" ]
null
null
null
preview/cplusplus/examples/hello-encode-cpp/src/util.hpp
alexelizarov/oneVPL
cdf7444dc971544d148c51e0d93a2df1bb55dda7
[ "MIT" ]
null
null
null
preview/cplusplus/examples/hello-encode-cpp/src/util.hpp
alexelizarov/oneVPL
cdf7444dc971544d148c51e0d93a2df1bb55dda7
[ "MIT" ]
1
2021-06-17T07:38:18.000Z
2021-06-17T07:38:18.000Z
//============================================================================== // Copyright Intel Corporation // // SPDX-License-Identifier: MIT //============================================================================== /// /// Utility library header file for sample code /// /// @file #ifndef PREVIEW_CPLUSPLUS_EXAMPLES_COMMON_UTIL_UTIL_HPP_ #define PREVIEW_CPLUSPLUS_EXAMPLES_COMMON_UTIL_UTIL_HPP_ #include <string.h> #include <map> #include "vpl/preview/vpl.hpp" #if (MFX_VERSION >= 2000) #include "vpl/mfxdispatcher.h" #endif #ifdef __linux__ #include <fcntl.h> #include <unistd.h> #endif #if defined(_WIN32) || defined(_WIN64) #include <atlbase.h> #include <d3d11.h> #include <dxgi1_2.h> #include <windows.h> CComPtr<ID3D11Device> g_pD3D11Device; CComPtr<ID3D11DeviceContext> g_pD3D11Ctx; CComPtr<IDXGIFactory2> g_pDXGIFactory; IDXGIAdapter *g_pAdapter; std::map<mfxMemId *, void *> allocResponses; std::map<void *, mfxFrameAllocResponse> allocDecodeResponses; std::map<void *, int> allocDecodeRefCount; typedef struct { mfxMemId memId; mfxMemId memIdStage; uint16_t rw; } CustomMemId; const struct { mfxIMPL impl; // actual implementation uint32_t adapterID; // device adapter number } implTypes[] = { { MFX_IMPL_HARDWARE, 0 }, { MFX_IMPL_HARDWARE2, 1 }, { MFX_IMPL_HARDWARE3, 2 }, { MFX_IMPL_HARDWARE4, 3 } }; #define MSDK_SAFE_RELEASE(X) \ { \ if (X) { \ X->Release(); \ X = NULL; \ } \ } #elif defined(__linux__) #ifdef LIBVA_SUPPORT #include "va/va.h" #include "va/va_drm.h" #endif #endif #define WAIT_100_MILLISECONDS 100 #define MAX_PATH 260 #define MAX_WIDTH 3840 #define MAX_HEIGHT 2160 #define IS_ARG_EQ(a, b) (!strcmp((a), (b))) #define VERIFY(x, y) \ if (!(x)) { \ printf("%s\n", y); \ goto end; \ } #define ALIGN16(value) (((value + 15) >> 4) << 4) #define ALIGN32(X) (((uint32_t)((X) + 31)) & (~(uint32_t)31)) enum ExampleParams { PARAM_IMPL = 0, PARAM_INFILE, PARAM_INRES, PARAM_COUNT }; enum ParamGroup { PARAMS_CREATESESSION = 0, PARAMS_DECODE, PARAMS_ENCODE, PARAMS_VPP, PARAMS_TRANSCODE }; typedef struct _Params { mfxIMPL impl; #if (MFX_VERSION >= 2000) mfxVariant implValue; #endif char *infileName; char *inmodelName; uint16_t srcWidth; uint16_t srcHeight; bool useVideoMemory; } Params; char *ValidateFileName(char *in) { if (in) { if (strnlen(in, MAX_PATH) > MAX_PATH) return NULL; } return in; } bool ValidateSize(char *in, uint16_t *vsize, uint32_t vmax) { if (in) { *vsize = static_cast<uint16_t>(strtol(in, NULL, 10)); if (*vsize <= vmax) return true; } *vsize = 0; return false; } bool ParseArgsAndValidate(int argc, char *argv[], Params *params, ParamGroup group) { int idx; char *s; // init all params to 0 *params = {}; params->impl = MFX_IMPL_SOFTWARE; #if (MFX_VERSION >= 2000) params->implValue.Type = MFX_VARIANT_TYPE_U32; params->implValue.Data.U32 = MFX_IMPL_TYPE_SOFTWARE; #endif for (idx = 1; idx < argc;) { // all switches must start with '-' if (argv[idx][0] != '-') { printf("ERROR - invalid argument: %s\n", argv[idx]); return false; } // switch string, starting after the '-' s = &argv[idx][1]; idx++; // search for match if (IS_ARG_EQ(s, "i")) { params->infileName = ValidateFileName(argv[idx++]); if (!params->infileName) { return false; } } else if (IS_ARG_EQ(s, "m")) { params->inmodelName = ValidateFileName(argv[idx++]); if (!params->inmodelName) { return false; } } else if (IS_ARG_EQ(s, "w")) { if (!ValidateSize(argv[idx++], &params->srcWidth, MAX_WIDTH)) return false; } else if (IS_ARG_EQ(s, "h")) { if (!ValidateSize(argv[idx++], &params->srcHeight, MAX_HEIGHT)) return false; } else if (IS_ARG_EQ(s, "hw")) { params->impl = MFX_IMPL_HARDWARE; #if (MFX_VERSION >= 2000) params->implValue.Data.U32 = MFX_IMPL_TYPE_HARDWARE; #endif } else if (IS_ARG_EQ(s, "sw")) { params->impl = MFX_IMPL_SOFTWARE; #if (MFX_VERSION >= 2000) params->implValue.Data.U32 = MFX_IMPL_TYPE_SOFTWARE; #endif } else if (IS_ARG_EQ(s, "vmem")) { params->useVideoMemory = true; } } // input file required by all except createsession if ((group != PARAMS_CREATESESSION) && (!params->infileName)) { printf("ERROR - input file name (-i) is required\n"); return false; } // VPP and encode samples require an input resolution if ((PARAMS_VPP == group) || (PARAMS_ENCODE == group)) { if ((!params->srcWidth) || (!params->srcHeight)) { printf("ERROR - source width/height required\n"); return false; } } return true; } #if defined(_WIN32) || defined(_WIN64) IDXGIAdapter *GetIntelDeviceAdapterHandle(mfxIMPL impl) { uint32_t adapterNum = 0; mfxIMPL baseImpl = MFX_IMPL_BASETYPE(impl); // Extract Media SDK base implementation type // get corresponding adapter number for (uint8_t i = 0; i < sizeof(implTypes) / sizeof(implTypes[0]); i++) { if (implTypes[i].impl == baseImpl) { adapterNum = implTypes[i].adapterID; break; } } HRESULT hres = CreateDXGIFactory(__uuidof(IDXGIFactory2), reinterpret_cast<void **>(&g_pDXGIFactory)); if (FAILED(hres)) return NULL; IDXGIAdapter *adapter; hres = g_pDXGIFactory->EnumAdapters(adapterNum, &adapter); if (FAILED(hres)) return NULL; return adapter; } #endif void PrepareFrameInfo(mfxFrameInfo *fi, uint32_t format, uint16_t w, uint16_t h) { // Video processing input data format fi->FourCC = format; fi->ChromaFormat = MFX_CHROMAFORMAT_YUV420; fi->CropX = 0; fi->CropY = 0; fi->CropW = w; fi->CropH = h; fi->PicStruct = MFX_PICSTRUCT_PROGRESSIVE; fi->FrameRateExtN = 30; fi->FrameRateExtD = 1; // width must be a multiple of 16 // height must be a multiple of 16 in case of frame picture and a multiple of 32 in case of field picture fi->Width = ALIGN16(fi->CropW); fi->Height = (MFX_PICSTRUCT_PROGRESSIVE == fi->PicStruct) ? ALIGN16(fi->CropH) : ALIGN32(fi->CropH); } uint32_t GetSurfaceSize(uint32_t FourCC, uint32_t width, uint32_t height) { uint32_t nbytes = 0; switch (FourCC) { case MFX_FOURCC_I420: case MFX_FOURCC_NV12: nbytes = width * height + (width >> 1) * (height >> 1) + (width >> 1) * (height >> 1); break; case MFX_FOURCC_I010: case MFX_FOURCC_P010: nbytes = width * height + (width >> 1) * (height >> 1) + (width >> 1) * (height >> 1); nbytes *= 2; break; case MFX_FOURCC_RGB4: nbytes = width * height * 4; break; default: break; } return nbytes; } int GetFreeSurfaceIndex(mfxFrameSurface1 *SurfacesPool, uint16_t nPoolSize) { for (uint16_t i = 0; i < nPoolSize; i++) { if (0 == SurfacesPool[i].Data.Locked) return i; } return MFX_ERR_NOT_FOUND; } #endif //PREVIEW_CPLUSPLUS_EXAMPLES_COMMON_UTIL_UTIL_HPP_
27.449477
109
0.567784
alexelizarov
eb2af48276d5818980313b1efa66d74927901f65
1,093
cc
C++
src/Main.cc
vanessavvp/cc-pr2-turing-machine
463d43190bd884cb3ead63fb4177a7dae8b6479b
[ "MIT" ]
null
null
null
src/Main.cc
vanessavvp/cc-pr2-turing-machine
463d43190bd884cb3ead63fb4177a7dae8b6479b
[ "MIT" ]
null
null
null
src/Main.cc
vanessavvp/cc-pr2-turing-machine
463d43190bd884cb3ead63fb4177a7dae8b6479b
[ "MIT" ]
null
null
null
/** * PROJECT HEADER * @file Main.cc * @author: Vanessa Valentina Villalba Perez * Contact: alu0101265704@ull.edu.es * @date: 30/10/2021 * Subject: Complejidad Computacional * Practice: Number º2 * Purpose: Implementing a Turing Machine */ #include <iostream> #include <filesystem> #include "../include/TuringMachine.h" using namespace std; int main(int argc, char** argv) { string inputFilename, inputString, menuRepeated; cout << "\n\tTuring Machine with infinite tape in both directions and every movement(L,R,S)" << endl; try { cout << "\nPlease, enter the input file path of the Turing Machine definition: "; cin >> inputFilename; do { cout << "Enter the input string for the Turing Machine Tape: "; cin >> inputString; TuringMachine turingMachine(inputFilename, inputString); turingMachine.checkString(inputString); cout << "\nDo you want to repeat the process [y/n]: "; cin >> menuRepeated; } while ((menuRepeated == "y") || (menuRepeated == "Y")); } catch (const string error) { cerr << error << endl; } }
29.540541
103
0.670631
vanessavvp
eb2b14c9f35fb7af54a313c756c87e588ee4e811
3,332
cpp
C++
source/RegistreBorne.cpp
fantome3/test1
6b28cbbe87110baa68ef22ed7aeba13f538fcaef
[ "MIT" ]
null
null
null
source/RegistreBorne.cpp
fantome3/test1
6b28cbbe87110baa68ef22ed7aeba13f538fcaef
[ "MIT" ]
null
null
null
source/RegistreBorne.cpp
fantome3/test1
6b28cbbe87110baa68ef22ed7aeba13f538fcaef
[ "MIT" ]
null
null
null
/* * RegistreBorne.cpp * * Created on: 2018-11-09 * Author: etudiant */ #include "RegistreBorne.h" #include "Borne.h" #include "BorneException.h" #include <sstream> namespace bornesQuebec { RegistreBorne::RegistreBorne(const std::string& p_nomRegistre):m_nomRegistreBorne(p_nomRegistre) { PRECONDITION(!p_nomRegistre.empty()); POSTCONDITION(m_nomRegistreBorne == p_nomRegistre); INVARIANTS(); } /** * @fn reqNomRegistreBorne * @return une chaine de caractere */ const std::string& RegistreBorne::reqNomRegistreBorne() const { return m_nomRegistreBorne; } /** * @fn reqRegistreBorneFormate * @return une chaine de caractere */ std::string RegistreBorne::reqRegistreBorneFormate() const{ std::ostringstream affiche; affiche << "Registre : " << m_nomRegistreBorne << std::endl; std::vector<Borne *>::const_iterator iter; for(iter = m_vBornes.begin(); iter < m_vBornes.end(); iter++){ affiche << (*iter)->reqBorneFormate(); } return affiche.str(); } /** * @fn BorneEstDejaPresente * @brief verifie si une borne est déjà dans le registre * @param p_borne * @return */ bool RegistreBorne::BorneEstDejaPresente(const Borne& p_borne) const{ bool present = false; std::vector<Borne *>::const_iterator iter; for(iter = m_vBornes.begin(); iter < m_vBornes.end(); iter++){ if(*(*iter) == p_borne) //! je compare les 02 elts grace à l'opérateur== ds Borne present = true; } return present; } /** * @fn ajouteBorne * @brief on ajoute la borne dans notre vecteur s'elle n'est pas déjà présente et * dans le cas contraire, elle lance une exception * @param p_borne */ void RegistreBorne::ajouteBorne(const Borne& p_borne){ PRECONDITION(!BorneEstDejaPresente(p_borne)); if(BorneEstDejaPresente(p_borne)) throw BorneDejaPresenteException("borne déjà présente dans la liste"); m_vBornes.push_back(p_borne.clone()); } /** * @fn verifiePresenceBorne(int p_identifiant) * @brief permet de vérifier si une borne est présentent dans le vecteur en le parcourant * tout en vérifiant la valeur de chaque identité présent. * @param p_identifiant * @return */ bool RegistreBorne::verifiePresenceBorne(int p_identifiant) const{ bool identifiantPresent = false; std::vector<Borne *>::const_iterator iter; for(iter = m_vBornes.begin(); iter < m_vBornes.end(); iter++){ if ((*iter)->reqIdentifiant() == p_identifiant) identifiantPresent = true; } return identifiantPresent; } /** * @fn supprimeBorne * @brief on supprime la borne dans notre vecteur si elle est présente * @param p_borne */ void RegistreBorne::supprimeBorne(int p_identifiant){ PRECONDITION(verifiePresenceBorne(p_identifiant)); if(!verifiePresenceBorne(p_identifiant)) throw BorneAbsenteException("désoler, la borne n'est pas présente dans la liste"); std::vector<Borne*>::iterator iter; for(iter = m_vBornes.begin(); iter < m_vBornes.end(); iter++){ if((*iter)->reqIdentifiant() == p_identifiant){ delete(*iter); iter = m_vBornes.erase(iter); } } } void RegistreBorne::verifieInvariant() const{ INVARIANT(!m_nomRegistreBorne.empty()); } /** * @breif destructeur des objets de notre class */ RegistreBorne::~RegistreBorne() { for(std::vector<Borne*>::iterator iter = m_vBornes.begin(); iter < m_vBornes.end(); iter++) delete(*iter); } } /* namespace bornesQuebec */
24.144928
96
0.718187
fantome3
eb3072e187b54684263490e5bbfb9bfc246c28ff
10,636
cpp
C++
VkLayer_profiler_layer/profiler_overlay/imgui_widgets/imgui_histogram_ex.cpp
lstalmir/VulkanProfiler
da06f27d71bf753bdef575ba1ed35e0acb8e84e7
[ "MIT" ]
1
2021-03-11T12:10:20.000Z
2021-03-11T12:10:20.000Z
VkLayer_profiler_layer/profiler_overlay/imgui_widgets/imgui_histogram_ex.cpp
lstalmir/VulkanProfiler
da06f27d71bf753bdef575ba1ed35e0acb8e84e7
[ "MIT" ]
10
2020-12-09T15:14:11.000Z
2021-01-23T18:52:26.000Z
VkLayer_profiler_layer/profiler_overlay/imgui_widgets/imgui_histogram_ex.cpp
lstalmir/VulkanProfiler
da06f27d71bf753bdef575ba1ed35e0acb8e84e7
[ "MIT" ]
null
null
null
// Copyright (c) 2019-2021 Lukasz Stalmirski // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // Enable internal ImVec operators #define IMGUI_DEFINE_MATH_OPERATORS #include "imgui_histogram_ex.h" #include <imgui_internal.h> #include <algorithm> namespace ImGuiX { // Fast access to native ImGui functions and structures. using namespace ImGui; /*************************************************************************\ Function: GetHistogramColumnData Description: Index values with specified stride. \*************************************************************************/ inline static const HistogramColumnData& GetHistogramColumnData( const HistogramColumnData* values, int values_stride, int index ) { const ImU8* ptr = reinterpret_cast<const ImU8*>(values); return *reinterpret_cast<const HistogramColumnData*>(ptr + (index * values_stride)); } /*************************************************************************\ Function: Clamp \*************************************************************************/ template<typename T> inline static T Clamp( T value, T min, T max ) { return std::min( max, std::max( min, value ) ); } /*************************************************************************\ Function: ColorSaturation Description: Control saturation of the color. \*************************************************************************/ inline static ImU32 ColorSaturation( ImU32 color, float saturation ) { // Compute average component value ImU32 r = ((color) & 0xFF); ImU32 g = ((color >> 8) & 0xFF); ImU32 b = ((color >> 16) & 0xFF); float avg = (r + g + b) / 3.0f; // Scale differences float r_diff_scaled = (r - avg) * saturation; float g_diff_scaled = (g - avg) * saturation; float b_diff_scaled = (b - avg) * saturation; // Convert back to 0-255 ranges r = static_cast<ImU32>(Clamp<int>( static_cast<int>(avg + r_diff_scaled), 0, 255 )); g = static_cast<ImU32>(Clamp<int>( static_cast<int>(avg + g_diff_scaled), 0, 255 )); b = static_cast<ImU32>(Clamp<int>( static_cast<int>(avg + b_diff_scaled), 0, 255 )); // Construct output color value return (r) | (g << 8) | (b << 16) | (color & 0xFF000000); } /*************************************************************************\ PlotHistogramEx \*************************************************************************/ void PlotHistogramEx( const char* label, const HistogramColumnData* values, int values_count, int values_offset, int values_stride, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, std::function<HistogramColumnHoverCallback> hover_cb, std::function<HistogramColumnClickCallback> click_cb ) { // Implementation is based on ImGui::PlotEx function (which is called by PlotHistogram). ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if( window->SkipItems ) return; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID( label ); const ImVec2 label_size = CalcTextSize( label, NULL, true ); if( graph_size.x == 0.0f ) graph_size.x = CalcItemWidth(); if( graph_size.y == 0.0f ) graph_size.y = label_size.y + (style.FramePadding.y * 2); const ImRect frame_bb( window->DC.CursorPos, window->DC.CursorPos + graph_size ); const ImRect inner_bb( frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding ); const ImRect total_bb( frame_bb.Min, frame_bb.Max + ImVec2( label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0 ) ); ItemSize( total_bb, style.FramePadding.y ); if( !ItemAdd( total_bb, 0, &frame_bb ) ) return; const bool hovered = ItemHoverable( frame_bb, id ) && inner_bb.Contains( g.IO.MousePos ); // Determine scale from values if not specified if( scale_min == FLT_MAX || scale_max == FLT_MAX ) { float y_min = FLT_MAX; float y_max = -FLT_MAX; for( int i = 0; i < values_count; i++ ) { const float y = GetHistogramColumnData( values, values_stride, i ).y; if( y != y ) // Ignore NaN values continue; y_min = ImMin( y_min, y ); y_max = ImMax( y_max, y ); } if( scale_min == FLT_MAX ) scale_min = y_min; if( scale_max == FLT_MAX ) scale_max = y_max; } // Adjust scale to have some normalized value { scale_min = floorf( scale_min / 10000.f ) * 10000.f; scale_max = ceilf( scale_max / 10000.f ) * 10000.f; } // Determine horizontal scale from values float x_size = 0.f; for( int i = 0; i < values_count; i++ ) x_size += GetHistogramColumnData( values, values_stride, i ).x; //RenderFrame( frame_bb.Min, frame_bb.Max, GetColorU32( ImGuiCol_FrameBg ), true, style.FrameRounding ); // Render horizontal lines { // Divide range to 10 equal parts const float step = inner_bb.GetHeight() / 10.f; const ImU32 lineCol = GetColorU32( ImGuiCol_Separator, 0.2f ); for( int i = 0; i < 10; ++i ) { window->DrawList->AddLine( { inner_bb.Min.x, inner_bb.Min.y + (i * step) }, { inner_bb.Max.x, inner_bb.Min.y + (i * step) }, lineCol ); } } int idx_hovered = -1; if( values_count > 0 ) { int res_w = ImMin( (int)graph_size.x, values_count ); int item_count = values_count; const int v_step = values_count / res_w; const float t_step = 1.0f / (float)x_size; const float inv_scale = (scale_min == scale_max) ? 0.0f : (1.0f / (scale_max - scale_min)); float v0 = GetHistogramColumnData( values, values_stride, (0 + values_offset) % values_count ).y; float t0 = 0.0f; ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate( (v0 - scale_min) * inv_scale ) ); // Point in the normalized space of our target rectangle float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (-scale_min * inv_scale) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands bool hovered_column_found = false; for( int n = 0; n < res_w; n++ ) { const int v1_idx = n * v_step; IM_ASSERT( v1_idx >= 0 && v1_idx < values_count ); const auto& column_data = GetHistogramColumnData( values, values_stride, (v1_idx + values_offset) % values_count ); const float t1 = t0 + t_step * ImMax( 1.f, column_data.x ); const float v1 = GetHistogramColumnData( values, values_stride, (v1_idx + values_offset + 1) % values_count ).y; const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate( (v1 - scale_min) * inv_scale ) ); const ImU32 col_base = column_data.color; const ImU32 col_hovered = ColorSaturation( col_base, 1.5f ); // NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU. ImVec2 pos0 = ImLerp( inner_bb.Min, inner_bb.Max, tp0 ); ImVec2 pos1 = ImLerp( inner_bb.Min, inner_bb.Max, ImVec2( tp1.x, histogram_zero_line_t ) ); if( pos1.x >= pos0.x + 2.0f ) pos1.x -= 1.0f; if( hovered && hovered_column_found == false && ImRect( pos0, pos1 ).Contains( g.IO.MousePos ) ) { if( hover_cb ) hover_cb( column_data ); if( click_cb && GetIO().MouseClicked[ ImGuiMouseButton_Left ] ) click_cb( column_data ); window->DrawList->AddRectFilled( pos0, pos1, col_hovered ); // Don't check other blocks hovered_column_found = true; } else { window->DrawList->AddRectFilled( pos0, pos1, col_base ); } v0 = v1; t0 = t1; tp0 = tp1; } } // Text overlay if( overlay_text ) RenderTextClipped( ImVec2( frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y ), frame_bb.Max, overlay_text, NULL, NULL, ImVec2( 0.5f, 0.0f ) ); if( label_size.x > 0.0f ) RenderText( ImVec2( frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y ), label ); // Render scale { const float range = scale_max - scale_min; char scale[ 16 ] = { 0 }; if( range < 100000.f ) sprintf( scale, "%.0f", range ); else if( range < 10000000000000.f ) sprintf( scale, "%.0fk", ceilf( range / 1000.f ) ); RenderText( inner_bb.Min, scale ); } } }
39.835206
172
0.540429
lstalmir
eb311c5c4416306f420d98ae17ae072153ca572c
684
hpp
C++
src/cmake_project/api/cprj_loader.hpp
lpea/cppinclude
dc126c6057d2fe30569e6e86f66d2c8eebb50212
[ "MIT" ]
177
2020-08-24T19:20:35.000Z
2022-03-27T01:58:04.000Z
src/cmake_project/api/cprj_loader.hpp
lpea/cppinclude
dc126c6057d2fe30569e6e86f66d2c8eebb50212
[ "MIT" ]
15
2020-08-30T17:59:42.000Z
2022-01-12T11:14:10.000Z
src/cmake_project/api/cprj_loader.hpp
lpea/cppinclude
dc126c6057d2fe30569e6e86f66d2c8eebb50212
[ "MIT" ]
11
2020-09-17T23:31:10.000Z
2022-03-04T13:15:21.000Z
#pragma once #include <stdfwd/memory> //------------------------------------------------------------------------------ namespace compilation_db { class Database; } //------------------------------------------------------------------------------ namespace cmake_project { class Project; //------------------------------------------------------------------------------ class Loader { public: using ProjectPtr = stdfwd::unique_ptr< Project >; virtual ~Loader() = default; virtual ProjectPtr load( const compilation_db::Database & _db ) = 0; virtual ProjectPtr createEmptyProject() = 0; }; //------------------------------------------------------------------------------ }
20.117647
80
0.383041
lpea
eb3342b742cd316632282b99a06f9a3c0748a646
59,021
hpp
C++
include/cuda/IterativeProcessingKernel3D.hpp
tugluk/MGARD
360a2fb853adbb1d758704960d4f51e85e4d3f57
[ "Apache-2.0" ]
null
null
null
include/cuda/IterativeProcessingKernel3D.hpp
tugluk/MGARD
360a2fb853adbb1d758704960d4f51e85e4d3f57
[ "Apache-2.0" ]
null
null
null
include/cuda/IterativeProcessingKernel3D.hpp
tugluk/MGARD
360a2fb853adbb1d758704960d4f51e85e4d3f57
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021, Oak Ridge National Laboratory. * MGARD-GPU: MultiGrid Adaptive Reduction of Data Accelerated by GPUs * Author: Jieyang Chen (chenj3@ornl.gov) * Date: April 2, 2021 */ #ifndef MGRAD_CUDA_ITERATIVE_PROCESSING_KERNEL_3D_TEMPLATE #define MGRAD_CUDA_ITERATIVE_PROCESSING_KERNEL_3D_TEMPLATE #include "IterativeProcessingKernel3D.h" namespace mgard_cuda { template <typename T, int R, int C, int F, int G> __global__ void _ipk_1_3d(int nr, int nc, int nf_c, T *am, T *bm, T *dist_f, T *v, int ldv1, int ldv2) { int c_gl = blockIdx.x * C; int r_gl = blockIdx.y * R; int f_gl = threadIdx.x; int c_sm = threadIdx.x; int r_sm = threadIdx.y; int f_sm = threadIdx.x; T *vec = v + get_idx(ldv1, ldv2, r_gl, c_gl, 0); T *sm = SharedMemory<T>(); int ldsm1 = F + G; int ldsm2 = C; T *vec_sm = sm; T *bm_sm = sm + R * ldsm1 * ldsm2; T *dist_sm = bm_sm + ldsm1; register T prev_vec_sm = 0.0; int c_rest = min(C, nc - blockIdx.x * C); int r_rest = min(R, nr - blockIdx.y * R); int f_rest = nf_c; int f_ghost = min(nf_c, G); int f_main = F; // printf("r_sm: %d, r_rest: %d, c_sm: %d, c_rest: %d f_sm: %d, f_rest %d , // nf_c: %d\n", r_sm, r_rest, c_sm, c_rest, f_sm, f_rest, nf_c); // printf("test %f", vec_sm[get_idx(ldsm1, ldsm2, 0, 1, 0)]); /* Load first ghost */ if (r_sm < r_rest && f_sm < f_ghost) { for (int i = 0; i < c_rest; i++) { vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] = vec[get_idx(ldv1, ldv2, r_sm, i, f_gl)]; // if (r_sm == 0) printf("r0_stride = %d, vec_sm[%d] = %f\n", r0_stride, // i, vec_sm[i * ldsm + c_sm]); } if (r_sm == 0) bm_sm[f_sm] = bm[f_gl]; } f_rest -= f_ghost; __syncthreads(); while (f_rest > F - f_ghost) { // if (c_gl == 0 && c_sm == 0 && r_gl == 0 && r_sm == 0) printf("%d %d\n", // f_rest, F - f_ghost); f_main = min(F, f_rest); if (r_sm < r_rest && f_sm < f_main) { for (int i = 0; i < c_rest; i++) { vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm + f_ghost)] = vec[get_idx(ldv1, ldv2, r_sm, i, f_gl + f_ghost)]; } if (r_sm == 0) bm_sm[f_sm + f_ghost] = bm[f_gl + f_ghost]; } __syncthreads(); /* Computation of v in parallel*/ if (r_sm < r_rest && c_sm < c_rest) { // if (r_gl == 0 && c_gl == 0 && r_sm == 0 && c_sm == 0) printf("%f + %f * // %f -> %f\n", // vec_sm[get_idx(ldsm1, // ldsm2, r_sm, c_sm, 0)], // prev_vec_sm, bm_sm[0], // vec_sm[get_idx(ldsm1, // ldsm2, r_sm, c_sm, // 0)]+prev_vec_sm * // bm_sm[0]); // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] = // __fma_rn(prev_vec_sm, bm_sm[0], vec_sm[get_idx(ldsm1, ldsm2, // r_sm, c_sm, 0)]); // #else // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] -= prev_vec_sm * // bm_sm[0]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] = tridiag_forward( prev_vec_sm, bm_sm[0], vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)]); //#pragma unroll 32 for (int i = 1; i < F; i++) { // if (c_gl == 0 && c_sm == 1 && blockIdx.x == 0 && blockIdx.y == 0 && // r_sm == 0) { // printf("%f + %f * %f -> %f(%d %d %d)\n", // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)], // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i - 1)], bm_sm[i], // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)]- // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i - 1)] * // bm_sm[i], r_sm, c_sm, i); // } // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)] = // __fma_rn(vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i - 1)], // bm_sm[i], vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)]); // #else // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)] -= // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i - 1)] * bm_sm[i]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)] = tridiag_forward( vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i - 1)], bm_sm[i], vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)]); // printf("calc[%d]: %f\n", i, vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, // i)]); if (r_gl == 0 && c_gl == 0) // printf("out[%d %d %d] %f\n", r_sm, c_sm, i, vec_sm[get_idx(ldsm1, // ldsm2, r_sm, c_sm, i)]); } /* Store last v */ prev_vec_sm = vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, F - 1)]; } __syncthreads(); /* flush results to v */ if (r_sm < r_rest && f_sm < F) { for (int i = 0; i < c_rest; i++) { // if (blockIdx.x == 0 && blockIdx.y == 0 && r_sm == 0 && i == 1) { // printf("store [%d %d %d] %f<-%f [%d %d %d]\n", // r_sm, i, f_gl, vec[get_idx(ldv1, ldv2, r_sm, i, f_gl)], // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)], r_sm, i, f_sm); // } vec[get_idx(ldv1, ldv2, r_sm, i, f_gl)] = vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)]; // if (blockIdx.x == 0 && blockIdx.y == 0 && r_sm == 0 && i == 1) { // printf("store [%d %d %d] %f<-%f [%d %d %d]\n", // r_sm, i, f_gl, vec[get_idx(ldv1, ldv2, r_sm, i, f_gl)], // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)], r_sm, i, f_sm); // } } } __syncthreads(); /* Update unloaded col */ f_rest -= f_main; /* Advance c */ f_gl += F; /* Copy next ghost to main */ f_ghost = min(G, f_main - (F - G)); if (r_sm < r_rest && f_sm < f_ghost) { for (int i = 0; i < c_rest; i++) { vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] = vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm + F)]; } if (r_sm == 0) bm_sm[f_sm] = bm_sm[f_sm + blockDim.x]; } __syncthreads(); } // end of while /* Load all rest col */ if (r_sm < r_rest && f_sm < f_rest) { for (int i = 0; i < c_rest; i++) { vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm + f_ghost)] = vec[get_idx(ldv1, ldv2, r_sm, i, f_gl + f_ghost)]; } if (r_sm == 0) bm_sm[f_sm + f_ghost] = bm[f_gl + f_ghost]; } __syncthreads(); /* Only 1 col remain */ if (f_ghost + f_rest == 1) { if (r_sm < r_rest && c_sm < c_rest) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] = // __fma_rn(prev_vec_sm, bm_sm[0], vec_sm[get_idx(ldsm1, ldsm2, // r_sm, c_sm, 0)]); // #else // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] -= prev_vec_sm * // bm_sm[0]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] = tridiag_forward( prev_vec_sm, bm_sm[0], vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)]); // printf ("prev_vec_sm = %f\n", prev_vec_sm ); // printf ("vec_sm[r_sm * ldsm + 0] = %f\n", vec_sm[r_sm * ldsm + 0] ); } //__syncthreads(); } else { if (r_sm < r_rest && c_sm < c_rest) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] = // __fma_rn(prev_vec_sm, bm_sm[0], vec_sm[get_idx(ldsm1, ldsm2, // r_sm, c_sm, 0)]); // #else // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] -= prev_vec_sm * // bm_sm[0]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] = tridiag_forward( prev_vec_sm, bm_sm[0], vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)]); for (int i = 1; i < f_ghost + f_rest; i++) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)] = // __fma_rn(vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i - 1)], // bm_sm[i], // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)]); // #else // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)] -= // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i - 1)] * bm_sm[i]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)] = tridiag_forward( vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i - 1)], bm_sm[i], vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)]); } } } __syncthreads(); /* flush results to v */ if (r_sm < r_rest && f_sm < f_ghost + f_rest) { for (int i = 0; i < c_rest; i++) { vec[get_idx(ldv1, ldv2, r_sm, i, f_gl)] = vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)]; // printf("c_stride = %d, c_sm = %d, vec_sm = %f, vec[%d] = // %f\n",c_stride, c_sm, vec_sm[r_sm * ldsm + 0],i * row_stride * lddv + // c_stride, vec[i * row_stride * lddv + c_stride]); } } __syncthreads(); /* backward */ T *am_sm = bm_sm; f_rest = nf_c; f_ghost = min(nf_c, G); f_main = F; f_gl = threadIdx.x; prev_vec_sm = 0.0; /* Load first ghost */ if (r_sm < r_rest && f_sm < f_ghost) { for (int i = 0; i < c_rest; i++) { vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] = vec[get_idx(ldv1, ldv2, r_sm, i, (nf_c - 1) - f_gl)]; // if (r_sm == 0) printf("r0_stride = %d, vec_sm[%d] = %f\n", r0_stride, // i, vec_sm[i * ldsm + c_sm]); } } if (r_sm == 0) { am_sm[f_sm] = am[(nf_c - 1) - f_gl]; dist_sm[f_sm] = dist_f[(nf_c - 1) - f_gl]; // * -1; } f_rest -= f_ghost; __syncthreads(); while (f_rest > F - f_ghost) { f_main = min(F, f_rest); if (r_sm < r_rest && f_sm < f_main) { for (int i = 0; i < c_rest; i++) { vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm + f_ghost)] = vec[get_idx(ldv1, ldv2, r_sm, i, (nf_c - 1) - f_gl - f_ghost)]; } } if (r_sm == 0) { am_sm[f_sm + f_ghost] = am[(nf_c - 1) - f_gl - f_ghost]; dist_sm[f_sm + f_ghost] = dist_f[(nf_c - 1) - f_gl - f_ghost]; // * -1; } __syncthreads(); /* Computation of v in parallel*/ if (r_sm < r_rest && c_sm < c_rest) { // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] = // (vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] - dist_sm[0] * // prev_vec_sm) / am_sm[0]; if (r_gl == 0 && c_gl == 0 && r_sm == 0 && // c_sm == 0) // printf("(%f + %f * %f) * %f -> %f\n", // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)], // dist_sm[0], prev_vec_sm, am_sm[0], // (vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] - dist_sm[0] // * prev_vec_sm) / am_sm[0]); // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] = // __fma_rn(dist_sm[0], prev_vec_sm, // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)]) * am_sm[0]; // #else // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] = // (vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] - dist_sm[0] * // prev_vec_sm) / am_sm[0]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] = tridiag_backward(prev_vec_sm, dist_sm[0], am_sm[0], vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)]); //#pragma unroll 32 for (int i = 1; i < F; i++) { // if (r_gl == 0 && c_gl == 0 && r_sm == 0 && c_sm == 0) // printf("(%f + %f * %f) * %f -> %f\n", // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)], // dist_sm[i], vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i-1)], // (vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)] - dist_sm[i] // * vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i-1)]) * // am_sm[i]); // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)] = // __fma_rn(dist_sm[i], vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i // - 1)], // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)]) * am_sm[i]; // #else // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)] = // (vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)] - // dist_sm[i] * vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i - // 1)]) / am_sm[i]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)] = tridiag_backward( vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i - 1)], dist_sm[i], am_sm[i], vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)]); } /* Store last v */ prev_vec_sm = vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, blockDim.x - 1)]; } __syncthreads(); /* flush results to v */ if (r_sm < r_rest && f_sm < F) { for (int i = 0; i < c_rest; i++) { vec[get_idx(ldv1, ldv2, r_sm, i, (nf_c - 1) - f_gl)] = vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)]; } } __syncthreads(); /* Update unloaded col */ f_rest -= f_main; /* Advance c */ f_gl += F; /* Copy next ghost to main */ f_ghost = min(G, f_main - (F - G)); if (r_sm < r_rest && f_sm < f_ghost) { for (int i = 0; i < c_rest; i++) { vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] = vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm + F)]; } if (r_sm == 0) { am_sm[f_sm] = am_sm[f_sm + F]; dist_sm[f_sm] = dist_sm[f_sm + F]; } } __syncthreads(); } // end of while /* Load all rest col */ if (r_sm < r_rest && f_sm < f_rest) { for (int i = 0; i < c_rest; i++) { vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm + f_ghost)] = vec[get_idx(ldv1, ldv2, r_sm, i, (nf_c - 1) - f_gl - f_ghost)]; } } if (r_sm == 0) { am_sm[f_sm + f_ghost] = am[(nf_c - 1) - f_gl - f_ghost]; dist_sm[f_sm + f_ghost] = dist_f[(nf_c - 1) - f_gl - f_ghost]; } __syncthreads(); /* Only 1 col remain */ if (f_ghost + f_rest == 1) { if (r_sm < r_rest && c_sm < c_rest) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] = // __fma_rn(dist_sm[0], prev_vec_sm, // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)]) * am_sm[0]; // #else // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] = // (vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] - dist_sm[0] * // prev_vec_sm) / am_sm[0]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] = tridiag_backward(prev_vec_sm, dist_sm[0], am_sm[0], vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)]); // printf ("prev_vec_sm = %f\n", prev_vec_sm ); // printf ("vec_sm[r_sm * ldsm + 0] = %f\n", vec_sm[r_sm * ldsm + 0] ); } //__syncthreads(); } else { if (r_sm < r_rest && c_sm < c_rest) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] = // __fma_rn(dist_sm[0], prev_vec_sm, // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)]) * am_sm[0]; // #else // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] = // (vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] - dist_sm[0] * // prev_vec_sm) / am_sm[0]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)] = tridiag_backward(prev_vec_sm, dist_sm[0], am_sm[0], vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, 0)]); for (int i = 1; i < f_ghost + f_rest; i++) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)] = // __fma_rn(dist_sm[i], vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i // - 1)], // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)]) * am_sm[i]; // #else // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)] = // (vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)] - // vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i - 1)] * // dist_sm[i]) / am_sm[i]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)] = tridiag_backward( vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i - 1)], dist_sm[i], am_sm[i], vec_sm[get_idx(ldsm1, ldsm2, r_sm, c_sm, i)]); } } } __syncthreads(); /* flush results to v */ if (r_sm < r_rest && f_sm < f_ghost + f_rest) { for (int i = 0; i < c_rest; i++) { vec[get_idx(ldv1, ldv2, r_sm, i, (nf_c - 1) - f_gl)] = vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)]; // printf("c_stride = %d, c_sm = %d, vec_sm = %f, vec[%d] = // %f\n",c_stride, c_sm, vec_sm[r_sm * ldsm + 0],i * row_stride * lddv + // c_stride, vec[i * row_stride * lddv + c_stride]); } } __syncthreads(); } template <uint32_t D, typename T, int R, int C, int F, int G> void ipk_1_3d_adaptive_launcher(Handle<D, T> &handle, int nr, int nc, int nf_c, T *am, T *bm, T *ddist_f, T *dv, int lddv1, int lddv2, int queue_idx) { // std::cout << "test\n"; int total_thread_x = nc; int total_thread_y = nr; int total_thread_z = 1; int tbx, tby, tbz, gridx, gridy, gridz; dim3 threadsPerBlock, blockPerGrid; size_t sm_size; tbx = std::max(C, std::min(C, total_thread_x)); tby = std::max(R, std::min(R, total_thread_y)); tbz = 1; sm_size = (R * C + 2) * (F + G) * sizeof(T); gridx = ceil((float)total_thread_x / tbx); gridy = ceil((float)total_thread_y / tby); gridz = 1; threadsPerBlock = dim3(F, tby, tbz); blockPerGrid = dim3(gridx, gridy, gridz); _ipk_1_3d<T, R, C, F, G><<<blockPerGrid, threadsPerBlock, sm_size, *(cudaStream_t *)handle.get(queue_idx)>>>( nr, nc, nf_c, am, bm, ddist_f, dv, lddv1, lddv2); gpuErrchk(cudaGetLastError()); #ifdef MGARD_CUDA_DEBUG gpuErrchk(cudaDeviceSynchronize()); #endif // std::cout << "test\n"; } template <uint32_t D, typename T> void ipk_1_3d(Handle<D, T> &handle, int nr, int nc, int nf_c, T *am, T *bm, T *ddist_f, T *dv, int lddv1, int lddv2, int queue_idx, int config) { #define IPK(R, C, F, G) \ { \ ipk_1_3d_adaptive_launcher<D, T, R, C, F, G>( \ handle, nr, nc, nf_c, am, bm, ddist_f, dv, lddv1, lddv2, queue_idx); \ } bool profile = false; #ifdef MGARD_CUDA_KERNEL_PROFILE profile = true; #endif if (D == 3) { if (profile || config == 6) { IPK(2, 2, 128, 2) } if (profile || config == 5) { IPK(2, 2, 64, 2) } if (profile || config == 4) { IPK(2, 2, 32, 2) } if (profile || config == 3) { IPK(4, 4, 16, 4) } if (profile || config == 2) { IPK(8, 8, 8, 4) } if (profile || config == 1) { IPK(4, 4, 4, 4) } if (profile || config == 0) { IPK(2, 2, 2, 2) } } else if (D == 2) { if (profile || config == 6) { IPK(1, 2, 128, 2) } if (profile || config == 5) { IPK(1, 2, 64, 2) } if (profile || config == 4) { IPK(1, 2, 32, 2) } if (profile || config == 3) { IPK(1, 4, 16, 4) } if (profile || config == 2) { IPK(1, 8, 8, 4) } if (profile || config == 1) { IPK(1, 4, 4, 4) } if (profile || config == 0) { IPK(1, 2, 4, 2) } } else if (D == 1) { if (profile || config == 6) { IPK(1, 1, 128, 2) } if (profile || config == 5) { IPK(1, 1, 64, 2) } if (profile || config == 4) { IPK(1, 1, 32, 2) } if (profile || config == 3) { IPK(1, 1, 16, 4) } if (profile || config == 2) { IPK(1, 1, 8, 4) } if (profile || config == 1) { IPK(1, 1, 8, 4) } if (profile || config == 0) { IPK(1, 1, 8, 2) } } #undef IPK } template <typename T, int R, int C, int F, int G> __global__ void _ipk_2_3d(int nr, int nc_c, int nf_c, T *am, T *bm, T *dist_c, T *v, int ldv1, int ldv2) { int f_gl = blockIdx.x * F; int r_gl = blockIdx.y * R; int c_gl = 0; int f_sm = threadIdx.x; int r_sm = threadIdx.y; int c_sm = threadIdx.x; T *vec = v + get_idx(ldv1, ldv2, r_gl, 0, f_gl); T *sm = SharedMemory<T>(); int ldsm1 = F; int ldsm2 = C + G; T *vec_sm = sm; T *bm_sm = sm + R * ldsm1 * ldsm2; T *dist_sm = bm_sm + ldsm2; register T prev_vec_sm = 0.0; int f_rest = min(F, nf_c - blockIdx.x * F); int r_rest = min(R, nr - blockIdx.y * R); // if (blockIdx.x == 1 && blockIdx.y == 0 && f_sm == 0 && r_sm == 0) { // printf("f_rest: %d r_rest: %d\n", f_rest, r_rest); // } int c_rest = nc_c; int c_ghost = min(nc_c, G); int c_main = C; /* Load first ghost */ if (r_sm < r_rest && f_sm < f_rest) { for (int i = 0; i < c_ghost; i++) { vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] = vec[get_idx(ldv1, ldv2, r_sm, c_gl + i, f_sm)]; // if (r_sm == 0) printf("r0_stride = %d, vec_sm[%d] = %f\n", r0_stride, // i, vec_sm[i * ldsm + c_sm]); } } if (r_sm == 0 && c_sm < c_ghost) bm_sm[c_sm] = bm[c_gl + c_sm]; c_rest -= c_ghost; __syncthreads(); while (c_rest > C - c_ghost) { // printf("%d %d %d\n", c_rest, C, c_ghost); c_main = min(C, c_rest); if (r_sm < r_rest && f_sm < f_rest) { for (int i = 0; i < c_main; i++) { vec_sm[get_idx(ldsm1, ldsm2, r_sm, i + c_ghost, f_sm)] = vec[get_idx(ldv1, ldv2, r_sm, c_gl + i + c_ghost, f_sm)]; } } if (r_sm == 0 && c_sm < c_main) bm_sm[c_sm + c_ghost] = bm[c_gl + c_sm + c_ghost]; __syncthreads(); /* Computation of v in parallel*/ if (r_sm < r_rest && f_sm < f_rest) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)] = // __fma_rn(prev_vec_sm, bm_sm[0], vec_sm[get_idx(ldsm1, ldsm2, // r_sm, 0, f_sm)]); // #else // vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)] -= prev_vec_sm * // bm_sm[0]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)] = tridiag_forward( prev_vec_sm, bm_sm[0], vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)]); for (int i = 1; i < C; i++) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] = // __fma_rn(vec_sm[get_idx(ldsm1, ldsm2, r_sm, i - 1, f_sm)], // bm_sm[i], // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)]); // #else // // if (blockIdx.x == 1 && blockIdx.y == 0 && f_sm == 0 && r_sm // == 0) { // // printf("calc: %f %f %f -> %f \n", vec_sm[get_idx(ldsm1, // ldsm2, r_sm, i, f_sm)], // // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i - 1, f_sm)], // bm_sm[i], vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] - // // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i - 1, f_sm)] * // bm_sm[i]); // // } // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] -= // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i - 1, f_sm)] * bm_sm[i]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] = tridiag_forward( vec_sm[get_idx(ldsm1, ldsm2, r_sm, i - 1, f_sm)], bm_sm[i], vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)]); } /* Store last v */ prev_vec_sm = vec_sm[get_idx(ldsm1, ldsm2, r_sm, C - 1, f_sm)]; } __syncthreads(); /* flush results to v */ if (r_sm < r_rest && f_sm < f_rest) { for (int i = 0; i < C; i++) { // if (blockIdx.x == 1 && blockIdx.y == 0 && f_sm == 0 && r_sm == 0) { // printf("store: %f\n", vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, // f_sm)]); // } vec[get_idx(ldv1, ldv2, r_sm, c_gl + i, f_sm)] = vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)]; } } __syncthreads(); /* Update unloaded col */ c_rest -= c_main; /* Advance c */ c_gl += C; /* Copy next ghost to main */ c_ghost = min(G, c_main - (C - G)); if (r_sm < r_rest && f_sm < f_rest) { for (int i = 0; i < c_ghost; i++) { vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] = vec_sm[get_idx(ldsm1, ldsm2, r_sm, i + C, f_sm)]; } } if (r_sm == 0 && c_sm < c_ghost) bm_sm[c_sm] = bm_sm[c_sm + C]; __syncthreads(); } // end of while /* Load all rest col */ if (r_sm < r_rest && f_sm < f_rest) { for (int i = 0; i < c_rest; i++) { vec_sm[get_idx(ldsm1, ldsm2, r_sm, i + c_ghost, f_sm)] = vec[get_idx(ldv1, ldv2, r_sm, c_gl + i + c_ghost, f_sm)]; } } if (r_sm == 0 && c_sm < c_rest) bm_sm[c_sm + c_ghost] = bm[c_gl + c_sm + c_ghost]; __syncthreads(); /* Only 1 col remain */ if (c_ghost + c_rest == 1) { if (r_sm < r_rest && f_sm < f_rest) { // vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)] -= prev_vec_sm * bm_sm[0]; // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)] = // __fma_rn(prev_vec_sm, bm_sm[0], vec_sm[get_idx(ldsm1, ldsm2, // r_sm, 0, f_sm)]); // #else // vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)] -= prev_vec_sm * // bm_sm[0]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)] = tridiag_forward( prev_vec_sm, bm_sm[0], vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)]); // printf ("prev_vec_sm = %f\n", prev_vec_sm ); // printf ("vec_sm[r_sm * ldsm + 0] = %f\n", vec_sm[r_sm * ldsm + 0] ); } //__syncthreads(); } else { if (r_sm < r_rest && f_sm < f_rest) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)] = // __fma_rn(prev_vec_sm, bm_sm[0], vec_sm[get_idx(ldsm1, ldsm2, // r_sm, 0, f_sm)]); // #else // vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)] -= prev_vec_sm * // bm_sm[0]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)] = tridiag_forward( prev_vec_sm, bm_sm[0], vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)]); for (int i = 1; i < c_ghost + c_rest; i++) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] = // __fma_rn(vec_sm[get_idx(ldsm1, ldsm2, r_sm, i - 1, f_sm)], // bm_sm[i], // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)]); // #else // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] -= // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i - 1, f_sm)] * bm_sm[i]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] = tridiag_forward( vec_sm[get_idx(ldsm1, ldsm2, r_sm, i - 1, f_sm)], bm_sm[i], vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)]); } } } __syncthreads(); /* flush results to v */ if (r_sm < r_rest && f_sm < f_rest) { for (int i = 0; i < c_ghost + c_rest; i++) { vec[get_idx(ldv1, ldv2, r_sm, c_gl + i, f_sm)] = vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)]; // printf("c_stride = %d, c_sm = %d, vec_sm = %f, vec[%d] = // %f\n",c_stride, c_sm, vec_sm[r_sm * ldsm + 0],i * row_stride * lddv + // c_stride, vec[i * row_stride * lddv + c_stride]); } } __syncthreads(); /* backward */ T *am_sm = bm_sm; c_rest = nc_c; c_ghost = min(nc_c, G); c_main = C; c_gl = 0; prev_vec_sm = 0.0; // if (f_gl+f_sm == 0 && r_gl+r_sm == 0 && idx[3] == 0) debug = false; // if (debug) printf("block id: (%d %d %d) thread id: (%d %d %d)\n", // blockIdx.x, blockIdx.y, blockIdx.z, // threadIdx.x, threadIdx.y, threadIdx.z); /* Load first ghost */ if (r_sm < r_rest && f_sm < f_rest) { for (int i = 0; i < c_ghost; i++) { vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] = vec[get_idx(ldv1, ldv2, r_sm, (nc_c - 1) - (c_gl + i), f_sm)]; // if (debug) printf("load vec_sm[%d] = %f\n", get_idx(ldsm1, ldsm2, r_sm, // i, f_sm), vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)]); } } if (r_sm == 0 && c_sm < c_ghost) { am_sm[c_sm] = am[(nc_c - 1) - (c_gl + c_sm)]; dist_sm[c_sm] = dist_c[(nc_c - 1) - (c_gl + c_sm)]; } c_rest -= c_ghost; __syncthreads(); while (c_rest > C - c_ghost) { // printf("%d %d %d\n", c_rest, C, c_ghost); c_main = min(C, c_rest); if (r_sm < r_rest && f_sm < f_rest) { for (int i = 0; i < c_main; i++) { vec_sm[get_idx(ldsm1, ldsm2, r_sm, i + c_ghost, f_sm)] = vec[get_idx( ldv1, ldv2, r_sm, (nc_c - 1) - (c_gl + i + c_ghost), f_sm)]; // if (debug) printf("load vec_sm[%d] = %f\n", get_idx(ldsm1, ldsm2, // r_sm, i + c_ghost, f_sm), vec_sm[get_idx(ldsm1, ldsm2, r_sm, i + // c_ghost, f_sm)]); } } if (r_sm == 0 && c_sm < c_main) { am_sm[c_sm + c_ghost] = am[(nc_c - 1) - (c_gl + c_sm + c_ghost)]; dist_sm[c_sm + c_ghost] = dist_c[(nc_c - 1) - (c_gl + c_sm + c_ghost)]; } __syncthreads(); // if (r_gl == 0 && f_gl == 0 && r_sm == 0 && f_sm == 0) // printf("*****test\n"); /* Computation of v in parallel*/ if (r_sm < r_rest && f_sm < f_rest) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)] = // __fma_rn(dist_sm[0], prev_vec_sm, vec_sm[get_idx(ldsm1, ldsm2, // r_sm, 0, f_sm)]) * am_sm[0]; // #else // // if (r_gl == 0 && f_gl == 0 && r_sm == 0 && f_sm == 0) // // printf("(%f + %f * %f) * %f -> %f\n", // // vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)], // // dist_sm[0], prev_vec_sm, am_sm[0], // // (vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)] - // dist_sm[0] * prev_vec_sm) / am_sm[0]); vec_sm[get_idx(ldsm1, // ldsm2, r_sm, 0, f_sm)] = (vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, // f_sm)] - dist_sm[0] * prev_vec_sm) / am_sm[0]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, c_sm)] = tridiag_backward(prev_vec_sm, dist_sm[0], am_sm[0], vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, c_sm)]); // if (debug) printf("calc vec_sm[%d] = %f\n", get_idx(ldsm1, ldsm2, r_sm, // 0, f_sm), vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)]); for (int i = 1; i < C; i++) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] = // __fma_rn(dist_sm[i], vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, // f_sm)], // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i - 1, f_sm)]) * am_sm[i]; // #else // // if (r_gl == 0 && f_gl == 0 && r_sm == 0 && f_sm == 0) // // printf("(%f + %f * %f) * %f -> %f\n", // // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)], // // dist_sm[i], vec_sm[get_idx(ldsm1, ldsm2, r_sm, // i-1, f_sm)], am_sm[i], // // (vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] - // // dist_sm[i] * vec_sm[get_idx(ldsm1, ldsm2, r_sm, i - 1, // f_sm)]) / am_sm[i]); // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] = // (vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] - // dist_sm[i] * vec_sm[get_idx(ldsm1, ldsm2, r_sm, i - 1, // f_sm)]) / am_sm[i]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] = tridiag_backward( vec_sm[get_idx(ldsm1, ldsm2, r_sm, i - 1, f_sm)], dist_sm[i], am_sm[i], vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)]); // if (debug) printf("calc vec_sm[%d] = %f\n", get_idx(ldsm1, ldsm2, // r_sm, i, f_sm), vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)]); } /* Store last v */ prev_vec_sm = vec_sm[get_idx(ldsm1, ldsm2, r_sm, C - 1, f_sm)]; } __syncthreads(); /* flush results to v */ if (r_sm < r_rest && f_sm < f_rest) { for (int i = 0; i < C; i++) { vec[get_idx(ldv1, ldv2, r_sm, (nc_c - 1) - (c_gl + i), f_sm)] = vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)]; } } __syncthreads(); /* Update unloaded col */ c_rest -= c_main; /* Advance c */ c_gl += C; /* Copy next ghost to main */ c_ghost = min(G, c_main - (C - G)); if (r_sm < r_rest && f_sm < f_rest) { for (int i = 0; i < c_ghost; i++) { vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] = vec_sm[get_idx(ldsm1, ldsm2, r_sm, i + C, f_sm)]; } } if (r_sm == 0 && c_sm < c_ghost) { am_sm[c_sm] = am_sm[c_sm + C]; dist_sm[c_sm] = dist_sm[c_sm + C]; } __syncthreads(); } // end of while // Load all rest col if (r_sm < r_rest && f_sm < f_rest) { for (int i = 0; i < c_rest; i++) { vec_sm[get_idx(ldsm1, ldsm2, r_sm, i + c_ghost, f_sm)] = vec[get_idx( ldv1, ldv2, r_sm, (nc_c - 1) - (c_gl + i + c_ghost), f_sm)]; // if (debug) printf("load ec_sm[%d] = %f\n", get_idx(ldsm1, ldsm2, r_sm, // i + c_ghost, f_sm), vec_sm[get_idx(ldsm1, ldsm2, r_sm, i + c_ghost, // f_sm)]); } } if (r_sm == 0 && c_sm < c_rest) { am_sm[c_sm + c_ghost] = am[(nc_c - 1) - (c_gl + c_sm + c_ghost)]; dist_sm[c_sm + c_ghost] = dist_c[(nc_c - 1) - (c_gl + c_sm + c_ghost)]; } __syncthreads(); /* Only 1 col remain */ if (c_ghost + c_rest == 1) { if (r_sm < r_rest && f_sm < f_rest) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)] = // __fma_rn(dist_sm[0], prev_vec_sm, vec_sm[get_idx(ldsm1, ldsm2, // r_sm, 0, f_sm)]) * am_sm[0]; // #else // // if (r_gl == 0 && f_gl == 0 && r_sm == 0 && f_sm == 0) // // printf("(%f + %f * %f) * %f -> %f\n", // // vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)], // // dist_sm[0], prev_vec_sm, am_sm[0], // // (vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)] - // dist_sm[0] * prev_vec_sm) / am_sm[0]); vec_sm[get_idx(ldsm1, // ldsm2, r_sm, 0, f_sm)] = (vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, // f_sm)] - dist_sm[0] * prev_vec_sm) / am_sm[0]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, c_sm)] = tridiag_backward(prev_vec_sm, dist_sm[0], am_sm[0], vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, c_sm)]); // if (debug) printf("calc vec_sm[%d] = %f\n", get_idx(ldsm1, ldsm2, r_sm, // 0, f_sm), vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)]); // printf ("prev_vec_sm = %f\n", prev_vec_sm ); // printf ("vec_sm[r_sm * ldsm + 0] = %f\n", vec_sm[r_sm * ldsm + 0] ); } //__syncthreads(); } else { if (r_sm < r_rest && f_sm < f_rest) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)] = // __fma_rn(dist_sm[0], prev_vec_sm, vec_sm[get_idx(ldsm1, ldsm2, // r_sm, 0, f_sm)]) * am_sm[0]; // #else // // if (r_gl == 0 && f_gl == 0 && r_sm == 0 && f_sm == 0) // // printf("(%f + %f * %f) * %f -> %f\n", // // vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)], // // dist_sm[0], prev_vec_sm, am_sm[0], // // (vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)] - // dist_sm[0] * prev_vec_sm) / am_sm[0]); vec_sm[get_idx(ldsm1, // ldsm2, r_sm, 0, f_sm)] = (vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, // f_sm)] - dist_sm[0] * prev_vec_sm) / am_sm[0]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, c_sm)] = tridiag_backward(prev_vec_sm, dist_sm[0], am_sm[0], vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, c_sm)]); // if (debug) printf("calc vec_sm[%d] = %f\n", get_idx(ldsm1, ldsm2, r_sm, // 0, f_sm), vec_sm[get_idx(ldsm1, ldsm2, r_sm, 0, f_sm)]); for (int i = 1; i < c_ghost + c_rest; i++) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] = // __fma_rn(dist_sm[i], vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, // f_sm)], // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i - 1, f_sm)]) * am_sm[i]; // #else // // if (r_gl == 0 && f_gl == 0 && r_sm == 0 && f_sm == 0) // // printf("(%f + %f * %f) * %f -> %f\n", // // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)], // // dist_sm[i], vec_sm[get_idx(ldsm1, ldsm2, r_sm, // i-1, f_sm)], am_sm[i], // // (vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] - // // dist_sm[i] * vec_sm[get_idx(ldsm1, ldsm2, r_sm, i - 1, // f_sm)]) / am_sm[i]); // vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] = // (vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] - // dist_sm[i] * vec_sm[get_idx(ldsm1, ldsm2, r_sm, i - 1, // f_sm)]) / am_sm[i]; // #endif vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)] = tridiag_backward( vec_sm[get_idx(ldsm1, ldsm2, r_sm, i - 1, f_sm)], dist_sm[i], am_sm[i], vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)]); // if (debug) printf("calc vec_sm[%d] = %f\n", get_idx(ldsm1, ldsm2, // r_sm, i, f_sm), vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)]); } } } __syncthreads(); /* flush results to v */ if (r_sm < r_rest && f_sm < f_rest) { for (int i = 0; i < c_ghost + c_rest; i++) { vec[get_idx(ldv1, ldv2, r_sm, (nc_c - 1) - (c_gl + i), f_sm)] = vec_sm[get_idx(ldsm1, ldsm2, r_sm, i, f_sm)]; // printf("c_stride = %d, c_sm = %d, vec_sm = %f, vec[%d] = // %f\n",c_stride, c_sm, vec_sm[r_sm * ldsm + 0],i * row_stride * lddv + // c_stride, vec[i * row_stride * lddv + c_stride]); } } __syncthreads(); } template <uint32_t D, typename T, int R, int C, int F, int G> void ipk_2_3d_adaptive_launcher(Handle<D, T> &handle, int nr, int nc_c, int nf_c, T *am, T *bm, T *ddist_c, T *dv, int lddv1, int lddv2, int queue_idx) { int total_thread_x = nf_c; int total_thread_y = nr; int total_thread_z = 1; int tbx, tby, tbz, gridx, gridy, gridz; dim3 threadsPerBlock, blockPerGrid; size_t sm_size; tbx = std::max(F, std::min(F, total_thread_x)); tby = std::max(R, std::min(R, total_thread_y)); tbz = 1; sm_size = (R * F + 2) * (C + G) * sizeof(T); gridx = ceil((float)total_thread_x / tbx); gridy = ceil((float)total_thread_y / tby); gridz = 1; threadsPerBlock = dim3(tbx, tby, tbz); blockPerGrid = dim3(gridx, gridy, gridz); _ipk_2_3d<T, R, C, F, G><<<blockPerGrid, threadsPerBlock, sm_size, *(cudaStream_t *)handle.get(queue_idx)>>>( nr, nc_c, nf_c, am, bm, ddist_c, dv, lddv1, lddv2); gpuErrchk(cudaGetLastError()); #ifdef MGARD_CUDA_DEBUG gpuErrchk(cudaDeviceSynchronize()); #endif } template <uint32_t D, typename T> void ipk_2_3d(Handle<D, T> &handle, int nr, int nc_c, int nf_c, T *am, T *bm, T *ddist_c, T *dv, int lddv1, int lddv2, int queue_idx, int config) { #define IPK(R, C, F, G) \ { \ ipk_2_3d_adaptive_launcher<D, T, R, C, F, G>( \ handle, nr, nc_c, nf_c, am, bm, ddist_c, dv, lddv1, lddv2, queue_idx); \ } bool profile = false; #ifdef MGARD_CUDA_KERNEL_PROFILE profile = true; #endif if (D == 3) { if (profile || config == 6) { IPK(2, 2, 128, 2) } if (profile || config == 5) { IPK(2, 2, 64, 2) } if (profile || config == 4) { IPK(2, 2, 32, 2) } if (profile || config == 3) { IPK(4, 4, 16, 4) } if (profile || config == 2) { IPK(8, 8, 8, 4) } if (profile || config == 1) { IPK(4, 4, 4, 4) } if (profile || config == 0) { IPK(2, 2, 2, 2) } } else if (D == 2) { if (profile || config == 6) { IPK(1, 2, 128, 2) } if (profile || config == 5) { IPK(1, 2, 64, 2) } if (profile || config == 4) { IPK(1, 2, 32, 2) } if (profile || config == 3) { IPK(1, 4, 16, 4) } if (profile || config == 2) { IPK(1, 8, 8, 4) } if (profile || config == 1) { IPK(1, 4, 4, 4) } if (profile || config == 0) { IPK(1, 2, 4, 2) } } else { printf("Error: ipk_2_3d is only for 3D and 2D data\n"); } #undef IPK } template <typename T, int R, int C, int F, int G> __global__ void _ipk_3_3d(int nr_c, int nc_c, int nf_c, T *am, T *bm, T *dist_r, T *v, int ldv1, int ldv2) { int f_gl = blockIdx.x * F; int c_gl = blockIdx.y * C; int r_gl = 0; int f_sm = threadIdx.x; int c_sm = threadIdx.y; int r_sm = threadIdx.x; T *vec = v + get_idx(ldv1, ldv2, 0, c_gl, f_gl); T *sm = SharedMemory<T>(); int ldsm1 = F; int ldsm2 = C; T *vec_sm = sm; T *bm_sm = sm + (R + G) * ldsm1 * ldsm2; T *dist_sm = bm_sm + (R + G); register T prev_vec_sm = 0.0; int f_rest = min(F, nf_c - blockIdx.x * F); int c_rest = min(C, nc_c - blockIdx.y * C); int r_rest = nr_c; int r_ghost = min(nr_c, G); int r_main = R; /* Load first ghost */ if (c_sm < c_rest && f_sm < f_rest) { for (int i = 0; i < r_ghost; i++) { vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)] = vec[get_idx(ldv1, ldv2, r_gl + i, c_sm, f_sm)]; // if (r_sm == 0) printf("r0_stride = %d, vec_sm[%d] = %f\n", r0_stride, // i, vec_sm[i * ldsm + c_sm]); } } if (c_sm == 0 && r_sm < r_ghost) bm_sm[r_sm] = bm[r_gl + r_sm]; r_rest -= r_ghost; __syncthreads(); while (r_rest > R - r_ghost) { r_main = min(R, r_rest); if (c_sm < c_rest && f_sm < f_rest) { for (int i = 0; i < r_main; i++) { vec_sm[get_idx(ldsm1, ldsm2, i + r_ghost, c_sm, f_sm)] = vec[get_idx(ldv1, ldv2, r_gl + i + r_ghost, c_sm, f_sm)]; // printf("%d\n", r_gl + i + r_ghost); } } if (c_sm == 0 && r_sm < r_main) bm_sm[r_sm + r_ghost] = bm[r_gl + r_sm + r_ghost]; __syncthreads(); /* Computation of v in parallel*/ if (c_sm < c_rest && f_sm < f_rest) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] = // __fma_rn(prev_vec_sm, bm_sm[0], vec_sm[get_idx(ldsm1, ldsm2, 0, // c_sm, f_sm)]); // #else // vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] -= prev_vec_sm * // bm_sm[0]; // #endif vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] = tridiag_forward( prev_vec_sm, bm_sm[0], vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)]); for (int i = 1; i < R; i++) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)] = // __fma_rn(vec_sm[get_idx(ldsm1, ldsm2, i - 1, c_sm, f_sm)], // bm_sm[i], // vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)]); // #else // vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)] -= // vec_sm[get_idx(ldsm1, ldsm2, i - 1, c_sm, f_sm)] * bm_sm[i]; // #endif vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)] = tridiag_forward( vec_sm[get_idx(ldsm1, ldsm2, i - 1, c_sm, f_sm)], bm_sm[i], vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)]); } /* Store last v */ prev_vec_sm = vec_sm[get_idx(ldsm1, ldsm2, R - 1, c_sm, f_sm)]; } __syncthreads(); /* flush results to v */ if (c_sm < c_rest && f_sm < f_rest) { for (int i = 0; i < R; i++) { vec[get_idx(ldv1, ldv2, r_gl + i, c_sm, f_sm)] = vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)]; } } __syncthreads(); // /* Update unloaded col */ r_rest -= r_main; /* Advance c */ r_gl += R; /* Copy next ghost to main */ r_ghost = min(G, r_main - (R - G)); if (c_sm < c_rest && f_sm < f_rest) { for (int i = 0; i < r_ghost; i++) { vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)] = vec_sm[get_idx(ldsm1, ldsm2, i + R, c_sm, f_sm)]; } } if (c_sm == 0 && r_sm < r_ghost) bm_sm[r_sm] = bm_sm[r_sm + R]; __syncthreads(); } // end of while /* Load all rest col */ if (c_sm < c_rest && f_sm < f_rest) { for (int i = 0; i < r_rest; i++) { vec_sm[get_idx(ldsm1, ldsm2, i + r_ghost, c_sm, f_sm)] = vec[get_idx(ldv1, ldv2, r_gl + i + r_ghost, c_sm, f_sm)]; } } if (c_sm == 0 && r_sm < r_rest) bm_sm[r_sm + r_ghost] = bm[r_gl + r_sm + r_ghost]; __syncthreads(); /* Only 1 col remain */ if (r_ghost + r_rest == 1) { if (c_sm < c_rest && f_sm < f_rest) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] = // __fma_rn(prev_vec_sm, bm_sm[0], vec_sm[get_idx(ldsm1, ldsm2, 0, // c_sm, f_sm)]); // #else // vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] -= prev_vec_sm * // bm_sm[0]; // #endif vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] = tridiag_forward( prev_vec_sm, bm_sm[0], vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)]); // printf ("prev_vec_sm = %f\n", prev_vec_sm ); // printf ("vec_sm[r_sm * ldsm + 0] = %f\n", vec_sm[r_sm * ldsm + 0] ); } //__syncthreads(); } else { if (c_sm < c_rest && f_sm < f_rest) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] = // __fma_rn(prev_vec_sm, bm_sm[0], vec_sm[get_idx(ldsm1, ldsm2, 0, // c_sm, f_sm)]); // #else // vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] -= prev_vec_sm * // bm_sm[0]; // #endif vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] = tridiag_forward( prev_vec_sm, bm_sm[0], vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)]); for (int i = 1; i < r_ghost + r_rest; i++) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)] = // __fma_rn(vec_sm[get_idx(ldsm1, ldsm2, i - 1, c_sm, f_sm)], // bm_sm[i], // vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)]); // #else // vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)] -= // vec_sm[get_idx(ldsm1, ldsm2, i - 1, c_sm, f_sm)] * bm_sm[i]; // #endif vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)] = tridiag_forward( vec_sm[get_idx(ldsm1, ldsm2, i - 1, c_sm, f_sm)], bm_sm[i], vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)]); } } } __syncthreads(); /* flush results to v */ if (c_sm < c_rest && f_sm < f_rest) { for (int i = 0; i < r_ghost + r_rest; i++) { vec[get_idx(ldv1, ldv2, r_gl + i, c_sm, f_sm)] = vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)]; // printf("c_stride = %d, c_sm = %d, vec_sm = %f, vec[%d] = // %f\n",c_stride, c_sm, vec_sm[r_sm * ldsm + 0],i * row_stride * lddv + // c_stride, vec[i * row_stride * lddv + c_stride]); } } __syncthreads(); /* backward */ T *am_sm = bm_sm; r_rest = nr_c; r_ghost = min(nr_c, G); r_main = R; r_gl = 0; prev_vec_sm = 0.0; /* Load first ghost */ if (c_sm < c_rest && f_sm < f_rest) { for (int i = 0; i < r_ghost; i++) { vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)] = vec[get_idx(ldv1, ldv2, (nr_c - 1) - (r_gl + i), c_sm, f_sm)]; // if (r_sm == 0) printf("r0_stride = %d, vec_sm[%d] = %f\n", r0_stride, // i, vec_sm[i * ldsm + c_sm]); } } if (c_sm == 0 && r_sm < r_ghost) { am_sm[r_sm] = am[(nr_c - 1) - (r_gl + r_sm)]; dist_sm[r_sm] = dist_r[(nr_c - 1) - (r_gl + r_sm)]; } r_rest -= r_ghost; __syncthreads(); while (r_rest > R - r_ghost) { r_main = min(R, r_rest); if (c_sm < c_rest && f_sm < f_rest) { for (int i = 0; i < r_main; i++) { vec_sm[get_idx(ldsm1, ldsm2, i + r_ghost, c_sm, f_sm)] = vec[get_idx( ldv1, ldv2, (nr_c - 1) - (r_gl + i + r_ghost), c_sm, f_sm)]; } } if (c_sm == 0 && r_sm < r_main) { am_sm[r_sm + r_ghost] = am[(nr_c - 1) - (r_gl + r_sm + r_ghost)]; dist_sm[r_sm + r_ghost] = dist_r[(nr_c - 1) - (r_gl + r_sm + r_ghost)]; } __syncthreads(); /* Computation of v in parallel*/ if (c_sm < c_rest && f_sm < f_rest) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] = // __fma_rn(dist_sm[0], prev_vec_sm, vec_sm[get_idx(ldsm1, ldsm2, 0, // c_sm, f_sm)]) * am_sm[0]; // #else // vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] = // (vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] - dist_sm[0] * // prev_vec_sm) / am_sm[0]; // #endif vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] = tridiag_backward(prev_vec_sm, dist_sm[0], am_sm[0], vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)]); for (int i = 1; i < R; i++) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)] = // __fma_rn(dist_sm[i], vec_sm[get_idx(ldsm1, ldsm2, i - 1, c_sm, // f_sm)], // vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)]) * am_sm[i]; // #else // vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)] = // (vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)] - // dist_sm[i] * vec_sm[get_idx(ldsm1, ldsm2, i - 1, c_sm, // f_sm)]) / am_sm[i]; // #endif vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)] = tridiag_backward( vec_sm[get_idx(ldsm1, ldsm2, i - 1, c_sm, f_sm)], dist_sm[i], am_sm[i], vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)]); } /* Store last v */ prev_vec_sm = vec_sm[get_idx(ldsm1, ldsm2, R - 1, c_sm, f_sm)]; } __syncthreads(); /* flush results to v */ if (c_sm < c_rest && f_sm < f_rest) { for (int i = 0; i < R; i++) { // if (blockIdx.x == 0 && blockIdx.y == 0 && threadIdx.x == 0 && // threadIdx.y == 0) { // printf("%d %d %d (%f) <- %d %d %d\n", (nr - 1) - (r_gl + i), c_sm, // f_sm, // vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)], i, c_sm, // f_sm); // } vec[get_idx(ldv1, ldv2, (nr_c - 1) - (r_gl + i), c_sm, f_sm)] = vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)]; } } __syncthreads(); // /* Update unloaded col */ r_rest -= r_main; /* Advance c */ r_gl += R; /* Copy next ghost to main */ r_ghost = min(G, r_main - (R - G)); if (c_sm < c_rest && f_sm < f_rest) { for (int i = 0; i < r_ghost; i++) { vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)] = vec_sm[get_idx(ldsm1, ldsm2, i + R, c_sm, f_sm)]; } } if (c_sm == 0 && r_sm < r_ghost) { am_sm[r_sm] = am_sm[r_sm + R]; dist_sm[r_sm] = dist_sm[r_sm + R]; } __syncthreads(); } // end of while /* Load all rest col */ if (c_sm < c_rest && f_sm < f_rest) { for (int i = 0; i < r_rest; i++) { vec_sm[get_idx(ldsm1, ldsm2, i + r_ghost, c_sm, f_sm)] = vec[get_idx( ldv1, ldv2, (nr_c - 1) - (r_gl + i + r_ghost), c_sm, f_sm)]; } } if (c_sm == 0 && r_sm < r_rest) { am_sm[r_sm + r_ghost] = am[(nr_c - 1) - (r_gl + r_sm + r_ghost)]; dist_sm[r_sm + r_ghost] = dist_r[(nr_c - 1) - (r_gl + r_sm + r_ghost)]; } __syncthreads(); /* Only 1 col remain */ if (r_ghost + r_rest == 1) { if (c_sm < c_rest && f_sm < f_rest) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] = // __fma_rn(dist_sm[0], prev_vec_sm, vec_sm[get_idx(ldsm1, ldsm2, 0, // c_sm, f_sm)]) * am_sm[0]; // #else // vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] = // (vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] - dist_sm[0] * // prev_vec_sm) / am_sm[0]; // #endif // if (blockIdx.x == 0 && blockIdx.y == 0 && threadIdx.x == 0 && // threadIdx.y == 0) { // printf("backward 1 (%f) %f %f %f %f\n", tridiag_backward(prev_vec_sm, // dist_sm[0], am_sm[0], // vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)]), prev_vec_sm, // dist_sm[0], am_sm[0], vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, // f_sm)]); // } vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] = tridiag_backward(prev_vec_sm, dist_sm[0], am_sm[0], vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)]); // printf ("prev_vec_sm = %f\n", prev_vec_sm ); // printf ("vec_sm[r_sm * ldsm + 0] = %f\n", vec_sm[r_sm * ldsm + 0] ); } //__syncthreads(); } else { if (c_sm < c_rest && f_sm < f_rest) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] = // __fma_rn(dist_sm[0], prev_vec_sm, vec_sm[get_idx(ldsm1, ldsm2, 0, // c_sm, f_sm)]) * am_sm[0]; // #else // vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] = // (vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] - dist_sm[0] * // prev_vec_sm) / am_sm[0]; // #endif // if (blockIdx.x == 0 && blockIdx.y == 0 && threadIdx.x == 0 && // threadIdx.y == 0) { // printf("backward 1 (%f) %f %f %f %f\n", tridiag_backward(prev_vec_sm, // dist_sm[0], am_sm[0], // vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)]), prev_vec_sm, // dist_sm[0], am_sm[0], vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, // f_sm)]); // } vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)] = tridiag_backward(prev_vec_sm, dist_sm[0], am_sm[0], vec_sm[get_idx(ldsm1, ldsm2, 0, c_sm, f_sm)]); for (int i = 1; i < r_ghost + r_rest; i++) { // #ifdef MGARD_CUDA_FMA // vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)] = // __fma_rn(dist_sm[i], vec_sm[get_idx(ldsm1, ldsm2, i - 1, c_sm, // f_sm)], // vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)]) * am_sm[i]; // #else // vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)] = // (vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)] - // dist_sm[i] * vec_sm[get_idx(ldsm1, ldsm2, i - 1, c_sm, // f_sm)]) / am_sm[i]; // #endif // if (blockIdx.x == 0 && blockIdx.y == 0 && threadIdx.x == 0 && // threadIdx.y == 0) { printf("backward R=%d (%f) %f %f %f %f\n", i, // tridiag_backward(vec_sm[get_idx(ldsm1, ldsm2, i - 1, c_sm, f_sm)], // dist_sm[i], am_sm[i], vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, // f_sm)]), vec_sm[get_idx(ldsm1, ldsm2, i - 1, c_sm, f_sm)], // dist_sm[i], am_sm[i], vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, // f_sm)]); // } vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)] = tridiag_backward( vec_sm[get_idx(ldsm1, ldsm2, i - 1, c_sm, f_sm)], dist_sm[i], am_sm[i], vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)]); } } } __syncthreads(); /* flush results to v */ if (c_sm < c_rest && f_sm < f_rest) { for (int i = 0; i < r_ghost + r_rest; i++) { vec[get_idx(ldv1, ldv2, (nr_c - 1) - (r_gl + i), c_sm, f_sm)] = vec_sm[get_idx(ldsm1, ldsm2, i, c_sm, f_sm)]; // printf("c_stride = %d, c_sm = %d, vec_sm = %f, vec[%d] = // %f\n",c_stride, c_sm, vec_sm[r_sm * ldsm + 0],i * row_stride * lddv + // c_stride, vec[i * row_stride * lddv + c_stride]); } } __syncthreads(); } template <uint32_t D, typename T, int R, int C, int F, int G> void ipk_3_3d_adaptive_launcher(Handle<D, T> &handle, int nr_c, int nc_c, int nf_c, T *am, T *bm, T *ddist_r, T *dv, int lddv1, int lddv2, int queue_idx) { // printf("am: "); // print_matrix_cuda(1, nr, am, nr); // printf("bm: "); // print_matrix_cuda(1, nr, bm, nr); int total_thread_x = nf_c; int total_thread_y = nc_c; int total_thread_z = 1; int tbx, tby, tbz, gridx, gridy, gridz; dim3 threadsPerBlock, blockPerGrid; size_t sm_size; tbx = std::max(F, std::min(F, total_thread_x)); tby = std::max(C, std::min(C, total_thread_y)); tbz = 1; sm_size = (C * F + 2) * (R + G) * sizeof(T); gridx = ceil((float)total_thread_x / tbx); gridy = ceil((float)total_thread_y / tby); gridz = 1; threadsPerBlock = dim3(tbx, tby, tbz); blockPerGrid = dim3(gridx, gridy, gridz); _ipk_3_3d<T, R, C, F, G><<<blockPerGrid, threadsPerBlock, sm_size, *(cudaStream_t *)handle.get(queue_idx)>>>( nr_c, nc_c, nf_c, am, bm, ddist_r, dv, lddv1, lddv2); gpuErrchk(cudaGetLastError()); #ifdef MGARD_CUDA_DEBUG gpuErrchk(cudaDeviceSynchronize()); #endif } template <uint32_t D, typename T> void ipk_3_3d(Handle<D, T> &handle, int nr_c, int nc_c, int nf_c, T *am, T *bm, T *ddist_r, T *dv, int lddv1, int lddv2, int queue_idx, int config) { #define IPK(R, C, F, G) \ { \ ipk_3_3d_adaptive_launcher<D, T, R, C, F, G>(handle, nr_c, nc_c, nf_c, am, \ bm, ddist_r, dv, lddv1, \ lddv2, queue_idx); \ } bool profile = false; #ifdef MGARD_CUDA_KERNEL_PROFILE profile = true; #endif if (D == 3) { if (profile || config == 6) { IPK(2, 2, 128, 2) } if (profile || config == 5) { IPK(2, 2, 64, 2) } if (profile || config == 4) { IPK(2, 2, 32, 2) } if (profile || config == 3) { IPK(2, 2, 16, 2) } if (profile || config == 2) { IPK(8, 8, 8, 4) } if (profile || config == 1) { IPK(4, 4, 4, 4) } if (profile || config == 0) { IPK(2, 2, 2, 2) } } else { printf("Error: ipk_3_3d is only for 3D data\n"); } #undef IPK } } // namespace mgard_cuda #endif
36.796135
80
0.498382
tugluk
eb34689f1915f9d5e1da9e004f0a54641fa9bbe2
574
cpp
C++
CPlusPlusFundamentals/ArrayVectors/AbaveAverageVector/main.cpp
bozhikovstanislav/Cpp-SoftUni
6562d15b9e3a550b11566630a1bc1ec65670bff7
[ "MIT" ]
null
null
null
CPlusPlusFundamentals/ArrayVectors/AbaveAverageVector/main.cpp
bozhikovstanislav/Cpp-SoftUni
6562d15b9e3a550b11566630a1bc1ec65670bff7
[ "MIT" ]
null
null
null
CPlusPlusFundamentals/ArrayVectors/AbaveAverageVector/main.cpp
bozhikovstanislav/Cpp-SoftUni
6562d15b9e3a550b11566630a1bc1ec65670bff7
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> float averageNumber(std::vector<int> vc, int n) { float sum=0; float average=0; for (int num:vc) { sum+=num; } average=sum/n; return average; } int main() { unsigned long n = 0; std::cin >> n; std::vector<int> numbers(n); for (int &number : numbers) { std::cin >> number; } float averahe = averageNumber(numbers, n); for (int number : numbers) { if (number > averahe) { number; } std::cout << " " << number; } return 0; }
19.133333
49
0.520906
bozhikovstanislav
eb357337ce22e2a7ca4f73e6b29810f443e52151
2,668
cpp
C++
JavaScriptCore/runtime/ErrorPrototype.cpp
explorer-ading/cricket-jscore
b10eabc016cec3db87f9976684839ddaf4cca0b1
[ "MIT" ]
1
2019-06-10T09:50:51.000Z
2019-06-10T09:50:51.000Z
JavaScriptCore/runtime/ErrorPrototype.cpp
explorer-ading/cricket-jscore
b10eabc016cec3db87f9976684839ddaf4cca0b1
[ "MIT" ]
null
null
null
JavaScriptCore/runtime/ErrorPrototype.cpp
explorer-ading/cricket-jscore
b10eabc016cec3db87f9976684839ddaf4cca0b1
[ "MIT" ]
null
null
null
/* * Copyright (C) 1999-2000 Harri Porten (porten@kde.org) * Copyright (C) 2003, 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "config.h" #include "ErrorPrototype.h" #include "JSFunction.h" #include "JSString.h" #include "JSStringBuilder.h" #include "ObjectPrototype.h" #include "PrototypeFunction.h" #include "UString.h" namespace JSC { ASSERT_CLASS_FITS_IN_CELL(ErrorPrototype); static JSValue JSC_HOST_CALL errorProtoFuncToString(ExecState*, JSObject*, JSValue, const ArgList&); // ECMA 15.9.4 ErrorPrototype::ErrorPrototype(ExecState* exec, NonNullPassRefPtr<Structure> structure, Structure* prototypeFunctionStructure) : ErrorInstance(structure) { // The constructor will be added later in ErrorConstructor's constructor putDirectWithoutTransition(exec->propertyNames().name, jsNontrivialString(exec, "Error"), DontEnum); putDirectWithoutTransition(exec->propertyNames().message, jsNontrivialString(exec, "Unknown error"), DontEnum); putDirectFunctionWithoutTransition(exec, new (exec) NativeFunctionWrapper(exec, prototypeFunctionStructure, 0, exec->propertyNames().toString, errorProtoFuncToString), DontEnum); } JSValue JSC_HOST_CALL errorProtoFuncToString(ExecState* exec, JSObject*, JSValue thisValue, const ArgList&) { JSObject* thisObj = thisValue.toThisObject(exec); JSValue name = thisObj->get(exec, exec->propertyNames().name); JSValue message = thisObj->get(exec, exec->propertyNames().message); // Mozilla-compatible format. if (!name.isUndefined()) { if (!message.isUndefined()) return jsMakeNontrivialString(exec, name.toString(exec), ": ", message.toString(exec)); return jsNontrivialString(exec, name.toString(exec)); } if (!message.isUndefined()) return jsMakeNontrivialString(exec, "Error: ", message.toString(exec)); return jsNontrivialString(exec, "Error"); } } // namespace JSC
39.235294
182
0.743628
explorer-ading