blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
listlengths 1
1
| author_id
stringlengths 0
158
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
16c47725873230e76d03568816cd054e1091f1c0
|
23e7a9c2c98302c0ec79cbf7ef4203106abc5de2
|
/Weaver/src/Player.cpp
|
aa5eb3761a453a7520cfe3769f548577a5ab5c9d
|
[] |
no_license
|
GeorgeJJCheng/PersonalProjects
|
35979eee0ae0c1f0960a3de5a04039be76ccf8e9
|
e90f06aa6001add8461b1c9ea9c5813944d51379
|
refs/heads/master
| 2021-01-20T04:50:31.185470
| 2017-04-28T20:15:39
| 2017-04-28T20:15:39
| 89,740,126
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 116
|
cpp
|
#include "Player.h"
Player::Player()
{
//ctor
}
Player::~Player()
{
//dtor
}
void Player::checkExp()
{
}
|
[
"jj5cheng@uwaterloo.ca"
] |
jj5cheng@uwaterloo.ca
|
5fd4d6c90dd589a29ee69c9a97fa18ea40be9ec0
|
9adfd7219b271002d0fb08cc7e7419b4960160c1
|
/SRC/os.cpp
|
7f31bbb6824ecefa9ccd7ad68027b166e466f925
|
[
"MIT"
] |
permissive
|
yejeelee94/ChatScript
|
0deefec13edefb2638eebc6992805b57f944d9bb
|
53337b6ed319403aea2303248e7e62c795085f54
|
refs/heads/master
| 2020-05-17T22:30:46.592138
| 2019-04-26T21:49:08
| 2019-04-26T21:49:08
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 73,329
|
cpp
|
#include "common.h"
#ifdef SAFETIME // some time routines are not thread safe (not relevant with EVSERVER)
#include <mutex>
static std::mutex mtx;
#endif
int loglimit = 0;
int ide = 0;
bool idestop = false;
bool idekey = false;
bool inputAvailable = false;
static char encryptUser[200];
static char encryptLTM[200];
static char logLastCharacter = 0;
#define MAX_STRING_SPACE 100000000 // transient+heap space 100MB
size_t maxHeapBytes = MAX_STRING_SPACE;
char* heapBase; // start of heap space (runs backward)
char* heapFree; // current free string ptr
char* stackFree;
char* infiniteCaller = "";
char* stackStart;
char* heapEnd;
static bool infiniteStack = false;
bool userEncrypt = false;
bool ltmEncrypt = false;
unsigned long minHeapAvailable;
bool showDepth = false;
char serverLogfileName[200]; // file to log server to
char dbTimeLogfileName[200]; // file to log db time to
char logFilename[MAX_WORD_SIZE]; // file to user log to
bool logUpdated = false; // has logging happened
int logsize = MAX_BUFFER_SIZE;
int outputsize = MAX_BUFFER_SIZE;
char* logmainbuffer = NULL; // where we build a log line
static bool pendingWarning = false; // log entry we are building is a warning message
static bool pendingError = false; // log entry we are building is an error message
int userLog = LOGGING_NOT_SET; // do we log user
int serverLog = LOGGING_NOT_SET; // do we log server
char hide[4000]; // dont log this json field
bool serverPreLog = true; // show what server got BEFORE it works on it
bool serverctrlz = false; // close communication with \0 and ctrlz
bool echo = false; // show log output onto console as well
bool oob = false; // show oob data
bool silent = false; // dont display outputs of chat
bool logged = false;
bool showmem = false;
int filesystemOverride = NORMALFILES;
bool inLog = false;
char* testOutput = NULL; // testing commands output reroute
static char encryptServer[1000];
static char decryptServer[1000];
// buffer information
#define MAX_BUFFER_COUNT 80
unsigned int maxReleaseStack = 0;
unsigned int maxReleaseStackGap = 0xffffffff;
unsigned int maxBufferLimit = MAX_BUFFER_COUNT; // default number of system buffers for AllocateBuffer
unsigned int maxBufferSize = MAX_BUFFER_SIZE; // how big std system buffers from AllocateBuffer should be
unsigned int maxBufferUsed = 0; // worst case buffer use - displayed with :variables
unsigned int bufferIndex = 0; // current allocated index into buffers[]
unsigned baseBufferIndex = 0; // preallocated buffers at start
char* buffers = 0; // collection of output buffers
#define MAX_OVERFLOW_BUFFERS 20
static char* overflowBuffers[MAX_OVERFLOW_BUFFERS]; // malloced extra buffers if base allotment is gone
CALLFRAME* releaseStackDepth[MAX_GLOBAL]; // ReleaseStack at start of depth
static unsigned int overflowLimit = 0;
unsigned int overflowIndex = 0;
USERFILESYSTEM userFileSystem;
static char staticPath[MAX_WORD_SIZE]; // files that never change
static char readPath[MAX_WORD_SIZE]; // readonly files that might be overwritten from outside
static char writePath[MAX_WORD_SIZE]; // files written by app
unsigned int currentFileLine = 0; // line number in file being read
unsigned int currentLineColumn = 0; // column number in file being read
unsigned int maxFileLine = 0; // line number in file being read
unsigned int peekLine = 0;
unsigned int currentFileColumn = 0;
char currentFilename[MAX_WORD_SIZE]; // name of file being read
// error recover
jmp_buf scriptJump[5];
int jumpIndex = -1;
unsigned int randIndex = 0;
unsigned int oldRandIndex = 0;
#ifdef WIN32
#include <conio.h>
#include <direct.h>
#include <io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <Winbase.h>
#endif
void Bug()
{
int xx = 0; // a hook to debug bug reports
}
/////////////////////////////////////////////////////////
/// KEYBOARD
/////////////////////////////////////////////////////////
bool KeyReady()
{
if (sourceFile && sourceFile != stdin) return true;
#ifdef WIN32
if (ide) return idekey;
return _kbhit() ? true : false;
#else
bool ready = false;
struct termios oldSettings, newSettings;
if (tcgetattr( fileno( stdin ), &oldSettings ) == -1) return false; // could not get terminal attributes
newSettings = oldSettings;
newSettings.c_lflag &= (~ICANON & ~ECHO);
tcsetattr( fileno( stdin ), TCSANOW, &newSettings );
fd_set set;
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO( &set );
FD_SET( fileno( stdin ), &set );
int res = select( fileno( stdin )+1, &set, NULL, NULL, &tv );
ready = ( res > 0 );
tcsetattr( fileno( stdin ), TCSANOW, &oldSettings );
return ready;
#endif
}
/////////////////////////////////////////////////////////
/// EXCEPTION/ERROR
/////////////////////////////////////////////////////////
void SafeLock()
{
#ifdef SAFETIME
mtx.lock();
#endif
}
void SafeUnlock()
{
#ifdef SAFETIME
mtx.unlock();
#endif
}
void JumpBack()
{
if (jumpIndex < 0) return; // not under handler control
globalDepth = 0;
longjmp(scriptJump[jumpIndex], 1);
}
void myexit(char* msg, int code)
{
#ifndef DISCARDTESTING
// CheckAbort(msg);
#endif
#ifndef DISCARDPOSTGRES
if (*postgresparams)
{
PostgresShutDown(); // any script connection
PGUserFilesCloseCode(); // filesystem
}
#endif
char name[MAX_WORD_SIZE];
sprintf(name,(char*)"%s/exitlog.txt",logs);
FILE* in = FopenUTF8WriteAppend(name);
if (in)
{
struct tm ptm;
fprintf(in,(char*)"%s %d - called myexit at %s\r\n",msg,code,GetTimeInfo(&ptm,true));
FClose(in);
}
if (code == 0) exit(0);
else exit(EXIT_FAILURE);
}
void mystart(char* msg)
{
char name[MAX_WORD_SIZE];
MakeDirectory(logs);
sprintf(name, (char*)"%s/startlog.txt", logs);
FILE* in = FopenUTF8WriteAppend(name);
char word[MAX_WORD_SIZE];
struct tm ptm;
sprintf(word, (char*)"System startup %s %s\r\n", msg, GetTimeInfo(&ptm, true));
if (in)
{
fprintf(in, (char*)"%s", word);
FClose(in);
}
if (server) Log(SERVERLOG, "%s",word);
}
/////////////////////////////////////////////////////////
/// Fatal Error/signal logging
/////////////////////////////////////////////////////////
#ifdef LINUX
void signalHandler( int signalcode ) {
char word[MAX_WORD_SIZE];
void *array[30];
size_t size;
// get void*'s for all entries on the stack
size = backtrace(array, 30);
// print out all the frames to stderr
sprintf(word, (char*)"Fatal Error: signal code %d\n", signalcode);
Log(SERVERLOG, word);
FILE*fp = FopenUTF8WriteAppend(serverLogfileName);
fseek(fp, 0, SEEK_END);
int fd = fileno(fp);
backtrace_symbols_fd(array, size, fd); //STDERR_FILENO);
fclose(fp);
// terminate program
exit(signalcode);
}
void setSignalHandlers () {
char word[MAX_WORD_SIZE];
struct sigaction sa;
sa.sa_handler = &signalHandler;
sigfillset(&sa.sa_mask); // Block every signal during the handler
// Handle relevant signals
if (sigaction(SIGSEGV, &sa, NULL) == -1) {
sprintf(word, (char*)"Error: cannot handle SIGSEGV");
Log(SERVERLOG, word);
}
if (sigaction(SIGHUP, &sa, NULL) == -1) {
sprintf(word, (char*)"Error: cannot handle SIGHUP");
Log(SERVERLOG, word);
}
if (sigaction(SIGINT, &sa, NULL) == -1) {
sprintf(word, (char*)"Error: cannot handle SIGINT");
Log(SERVERLOG, word);
}
if (sigaction(SIGBUS, &sa, NULL) == -1) {
sprintf(word, (char*)"Error: cannot handle SIGBUS");
Log(SERVERLOG, word);
}
}
#endif
/////////////////////////////////////////////////////////
/// MEMORY SYSTEM
/////////////////////////////////////////////////////////
void ResetBuffers()
{
globalDepth = 0;
bufferIndex = baseBufferIndex;
memset(releaseStackDepth,0,sizeof(releaseStackDepth));
outputNest = oldOutputIndex = 0;
currentRuleOutputBase = currentOutputBase = ourMainOutputBuffer;
currentOutputLimit = outputsize;
}
void CloseBuffers()
{
while (overflowLimit > 0)
{
free(overflowBuffers[--overflowLimit]);
overflowBuffers[overflowLimit] = 0;
}
free(buffers);
buffers = 0;
}
char* AllocateBuffer(char* name)
{// CANNOT USE LOG INSIDE HERE, AS LOG ALLOCATES A BUFFER
char* buffer = buffers + (maxBufferSize * bufferIndex);
if (++bufferIndex >= maxBufferLimit ) // want more than nominally allowed
{
if (bufferIndex > (maxBufferLimit+2) || overflowIndex > 20)
{
char word[MAX_WORD_SIZE];
sprintf(word,(char*)"Corrupt bufferIndex %d or overflowIndex %d\r\n",bufferIndex,overflowIndex);
Log(STDTRACELOG,(char*)"%s\r\n",word);
ReportBug(word);
myexit(word);
}
--bufferIndex;
// try to acquire more space, permanently
if (overflowIndex >= overflowLimit)
{
overflowBuffers[overflowLimit] = (char*) malloc(maxBufferSize);
if (!overflowBuffers[overflowLimit])
{
ReportBug((char*)"FATAL: out of buffers\r\n");
}
overflowLimit++;
if (overflowLimit >= MAX_OVERFLOW_BUFFERS) ReportBug((char*)"FATAL: Out of overflow buffers\r\n");
Log(STDTRACELOG,(char*)"Allocated extra buffer %d\r\n",overflowLimit);
}
buffer = overflowBuffers[overflowIndex++];
}
else if (bufferIndex > maxBufferUsed) maxBufferUsed = bufferIndex;
if (showmem) Log(STDTRACELOG,(char*)"Buffer alloc %d %s\r\n",bufferIndex,name);
*buffer++ = 0; // prior value
*buffer = 0; // empty string
return buffer;
}
void FreeBuffer(char* name)
{
if (showmem) Log(STDTRACELOG,(char*)"Buffer free %d %s\r\n",bufferIndex,name);
if (overflowIndex) --overflowIndex; // keep the dynamically allocated memory for now.
else if (bufferIndex) --bufferIndex;
else ReportBug((char*)"Buffer allocation underflow")
}
void InitStackHeap()
{
size_t size = maxHeapBytes / 64;
size = (size * 64) + 64; // 64 bit align both ends
heapEnd = ((char*) malloc(size)); // point to end
if (!heapEnd)
{
(*printer)((char*)"Out of memory space for text space %d\r\n",(int)size);
ReportBug((char*)"FATAL: Cannot allocate memory space for text %d\r\n",(int)size)
}
heapFree = heapBase = heapEnd + size; // allocate backwards
stackFree = heapEnd;
minHeapAvailable = maxHeapBytes;
stackStart = stackFree;
ClearNumbers();
}
void FreeStackHeap()
{
if (heapEnd)
{
free(heapEnd);
heapEnd = NULL;
}
}
char* AllocateStack(char* word, size_t len,bool localvar,int align) // call with (0,len) to get a buffer
{
if (infiniteStack)
ReportBug("Allocating stack while InfiniteStack in progress from %s\r\n",infiniteCaller);
if (len == 0)
{
if (!word ) return NULL;
len = strlen(word);
}
if (align == 1 || align == 4) // 1 is old true value
{
stackFree += 3;
uint64 x = (uint64)stackFree;
x &= 0xfffffffffffffffc;
stackFree = (char*)x;
}
else if (align == 8)
{
stackFree += 7;
uint64 x = (uint64)stackFree;
x &= 0xfffffffffffffff8;
stackFree = (char*)x;
}
if ((stackFree + len + 1) >= heapFree - 30000000) // dont get close
{
int xx = 0;
}
if ((stackFree + len + 1) >= heapFree - 5000) // dont get close
{
ReportBug((char*)"Out of stack space stringSpace:%d ReleaseStackspace:%d \r\n",heapBase-heapFree,stackFree - stackStart);
return NULL;
}
char* answer = stackFree;
if (localvar) // give hidden data
{
*answer = '`';
answer[1] = '`';
answer += 2;
}
if (word) strncpy(answer,word,len);
else *answer = 0;
answer[len++] = 0;
answer[len++] = 0;
if (localvar) len += 2;
stackFree += len;
len = stackFree - stackStart; // how much stack used are we?
len = heapBase - heapFree; // how much heap used are we?
len = heapFree - stackFree; // size of gap between
if (len < maxReleaseStackGap) maxReleaseStackGap = len;
return answer;
}
void ReleaseStack(char* word)
{
stackFree = word;
}
bool AllocateStackSlot(char* variable)
{
WORDP D = StoreWord(variable,AS_IS);
unsigned int len = sizeof(char*);
if ((stackFree + len + 1) >= (heapFree - 5000)) // dont get close
{
ReportBug((char*)"Out of stack space\r\n")
return false;
}
char* answer = stackFree;
memcpy(answer,&D->w.userValue,sizeof(char*));
if (D->word[1] == LOCALVAR_PREFIX) D->w.userValue = NULL; // autoclear local var
stackFree += sizeof(char*);
len = heapFree - stackFree;
if (len < maxReleaseStackGap) maxReleaseStackGap = len;
return true;
}
char** RestoreStackSlot(char* variable,char** slot)
{
WORDP D = FindWord(variable);
if (!D) return slot; // should never happen, we allocate dict entry on save
memcpy(&D->w.userValue,slot,sizeof(char*));
if (!stricmp(variable, "$_specialty"))
{
int xx = 0;
}
#ifndef DISCARDTESTING
if (debugVar) (*debugVar)(variable, D->w.userValue);
#endif
return ++slot;
}
char* InfiniteStack(char*& limit,char* caller)
{
if (infiniteStack) ReportBug("Allocating InfiniteStack from %s while one already in progress from %s\r\n",caller, infiniteCaller);
infiniteCaller = caller;
infiniteStack = true;
limit = heapFree - 5000; // leave safe margin of error
*stackFree = 0;
return stackFree;
}
char* InfiniteStack64(char*& limit,char* caller)
{
if (infiniteStack) ReportBug("Allocating InfiniteStack from %s while one already in progress from %s\r\n",caller, infiniteCaller);
infiniteCaller = caller;
infiniteStack = true;
limit = heapFree - 5000; // leave safe margin of error
uint64 base = (uint64) (stackFree+7);
base &= 0xFFFFFFFFFFFFFFF8ULL;
return (char*) base; // slop may be lost when allocated finally, but it can be reclaimed later
}
void ReleaseInfiniteStack()
{
infiniteStack = false;
infiniteCaller = "";
}
void CompleteBindStack64(int n,char* base)
{
stackFree = base + ((n+1) * sizeof(FACT*)); // convert infinite allocation to fixed one given element count
size_t len = heapFree - stackFree;
if (len < maxReleaseStackGap) maxReleaseStackGap = len;
infiniteStack = false;
}
void CompleteBindStack()
{
stackFree += strlen(stackFree) + 1; // convert infinite allocation to fixed one
size_t len = heapFree - stackFree;
if (len < maxReleaseStackGap) maxReleaseStackGap = len;
infiniteStack = false;
}
char* Index2Heap(HEAPREF offset)
{
if (!offset) return NULL;
char* ptr = heapBase - offset;
if (ptr < heapFree)
{
ReportBug((char*)"String offset into free space\r\n")
return NULL;
}
if (ptr > heapBase)
{
ReportBug((char*)"String offset before heap space\r\n")
return NULL;
}
return ptr;
}
bool PreallocateHeap(size_t len) // do we have the space
{
char* used = heapFree - len;
if (used <= ((char*)stackFree + 2000))
{
ReportBug("Heap preallocation fails");
return false;
}
return true;
}
bool InHeap(char* ptr)
{
return (ptr >= heapFree && ptr <= heapBase);
}
bool InStack(char* ptr)
{
return (ptr < heapFree && ptr >= stackStart);
}
void ShowMemory(char* label)
{
(*printer)("%s: HeapUsed: %d Gap: %d\r\n", label, heapBase - heapFree,heapFree - stackFree);
}
char* AllocateHeap(char* word,size_t len,int bytes,bool clear, bool purelocal) // BYTES means size of unit
{ // string allocation moves BACKWARDS from end of dictionary space (as do meanings)
/* Allocations during setup as :
2 when setting up cs using current dictionary and livedata for extensions (plurals, comparatives, tenses, canonicals)
3 preserving flags or properties when removing them or adding them while the dictionary is unlocked - only during builds
4 reading strings during dictionary setup
5 assigning meanings or glosses or posconditionsfor the dictionary
6 reading in postag information
---
Allocations happen during volley processing as
1 adding a new dictionary word - all the time on user input
2. saving plan backtrack data
3 altering concepts[] and topics[] lists as a result of a mark operation or normal behavior
4. temps information
5 spellcheck adjusted word in sentence list
6 tokenizing words and quoted stuff adjustments
7. assignment onto user variables
8. JSON reading
*/
len *= bytes; // this many units of this size
if (len == 0)
{
if (!word ) return NULL;
len = strlen(word);
}
if (word) ++len; // null terminate string
if (purelocal) len += 2; // for `` prefix
size_t allocationSize = len;
if (bytes == 1 && dictionaryLocked && !compiling && !loading)
{
allocationSize += ALLOCATESTRING_SIZE_PREFIX + ALLOCATESTRING_SIZE_SAFEMARKER;
// reserve space at front for allocation sizing not in dict items though (variables not in plannning mode can reuse space if prior is big enough)
// initial 2 test area
}
// always allocate in word units
unsigned int allocate = ((allocationSize + 3) / 4) * 4;
heapFree -= allocate; // heap grows lower, stack grows higher til they collide
if (bytes > 4) // force 64bit alignment alignment
{
uint64 base = (uint64) heapFree;
base &= 0xFFFFFFFFFFFFFFF8ULL; // 8 byte align
heapFree = (char*) base;
}
else if (bytes == 4) // force 32bit alignment alignment
{
uint64 base = (uint64) heapFree;
base &= 0xFFFFFFFFFFFFFFFCULL; // 4 byte align
heapFree = (char*) base;
}
else if (bytes == 2) // force 16bit alignment alignment
{
uint64 base = (uint64) heapFree;
base &= 0xFFFFFFFFFFFFFFFEULL; // 2 byte align
heapFree = (char*) base;
}
else if (bytes != 1)
ReportBug((char*)"Allocation of bytes is not std unit %d", bytes);
// create marker
if (bytes == 1 && dictionaryLocked && !compiling && !loading)
{
heapFree[0] = ALLOCATESTRING_MARKER; // we put ff ff just before the sizing data
heapFree[1] = ALLOCATESTRING_MARKER;
}
char* newword = heapFree;
if (bytes == 1 && dictionaryLocked && !compiling && !loading) // store size of allocation to enable potential reuse by $var assign and by wordStarts tokenize
{
newword += ALLOCATESTRING_SIZE_SAFEMARKER;
allocationSize -= ALLOCATESTRING_SIZE_PREFIX + ALLOCATESTRING_SIZE_SAFEMARKER; // includes the end of string marker
if (ALLOCATESTRING_SIZE_PREFIX == 3) *newword++ = (unsigned char)(allocationSize >> 16);
*newword++ = (unsigned char)(allocationSize >> 8) & 0x000000ff;
*newword++ = (unsigned char) (allocationSize & 0x000000ff);
}
int nominalLeft = maxHeapBytes - (heapBase - heapFree);
if ((unsigned long) nominalLeft < minHeapAvailable) minHeapAvailable = nominalLeft;
if ((heapBase-heapFree) > 50000000) // when heap has used up 50Mb
{
int xx = 0;
}
char* used = heapFree - len;
if (used <= ((char*)stackFree + 2000) || nominalLeft < 0)
ReportBug((char*)"FATAL: Out of permanent heap space\r\n")
if (word)
{
if (purelocal) // never use clear true with this
{
*newword++ = LCLVARDATA_PREFIX;
*newword++ = LCLVARDATA_PREFIX;
len -= 2;
}
memcpy(newword,word,--len);
newword[len] = 0;
}
else if (clear) memset(newword,0,len);
return newword;
}
/////////////////////////////////////////////////////////
/// FILE SYSTEM
/////////////////////////////////////////////////////////
int FClose(FILE* file)
{
if (file) fclose(file);
*currentFilename = 0;
return 0;
}
void InitUserFiles()
{
// these are dynamically stored, so CS can be a DLL.
userFileSystem.userCreate = FopenBinaryWrite;
userFileSystem.userOpen = FopenReadWritten;
userFileSystem.userClose = FClose;
userFileSystem.userRead = fread;
userFileSystem.userWrite = fwrite;
userFileSystem.userDelete = FileDelete;
userFileSystem.userDecrypt = NULL;
userFileSystem.userEncrypt = NULL;
filesystemOverride = NORMALFILES;
}
static size_t CleanupCryption(char* buffer,bool decrypt,char* filekind)
{
// clean up answer data: {"datavalues": {"USER": xxxx }}
char* answer = strstr(buffer,filekind);
if (!answer)
{
*buffer = 0;
return 0;
}
answer += strlen(filekind) + 2; // skip USER":
int realsize = jsonOpenSize - (answer-buffer) - 2; // the closing two }
memmove(buffer,answer,realsize); // drop head data
buffer[realsize] = 0; // remove trailing data
// legal json doesnt allow control characters, but we cannot change our file system ones to \r\n because
// we cant tell which are ours and which are users. So we changed to 7f7f coding.
if (decrypt)
{
char* at = buffer-1;
while (*++at)
{
if (*at == 0x7f && at[1] == 0x7f)
{
*at = '\r';
at[1] = '\n';
}
}
}
return realsize;
}
void ProtectNL(char* buffer) // save ascii \r\n in json - only comes from userdata write using them
{
char* at = buffer;
while ((at = strchr(at,'\r'))) // legal convert
{
if (at[1] == '\n' ) // legal convert
{
*at++ = 0x7f;
*at++ = 0x7f;
}
}
}
bool notcrypting = false;
static int JsonOpenCryption(char* buffer, size_t size, char* xserver, bool decrypt,char* filekind)
{
if (size == 0) return 0;
if (notcrypting) return size;
if (decrypt && size > 50) return size; // it was never encrypted, this is original material
char server[1000];
char* id = loginID;
if (*id == 'b' && !id[1]) id = "u-8b02518d-c148-5d45-936b-491d39ced70c"; // cheat override to test outside of kore logins
if (decrypt) sprintf(server, "%s%s/datavalues/decryptedtokens", xserver, id);
else sprintf(server, "%s%s/datavalues/encryptedtokens", xserver, id);
//loginID
// for decryption, the value we are passed is a quoted string. We need to avoid doubling those
#ifdef INFORMATION
// legal json requires these characters be escaped, but we cannot change our file system ones to \r\n because
// we cant tell which are ours and which are users. So we change to 7f7f coding for /r/n.
// and we change to 0x31 for double quote.
\b Backspace (ascii code 08) -- never seeable
\f Form feed (ascii code 0C) -- never seable
\n New line -- only from our user topic write
\r Carriage return -- only from our user topic write
\t Tab -- never seeable
\" Double quote -- seeable in user data
\\ Backslash character -- ??? not expected but possible
UserFile encoding responsible for normal JSON safe data.
Note MongoDB code also encrypts \r\n the same way. but we dont know HERE that mongo is used
and we don't know THERE that encryption was used. That is redundant but minor.
#endif
if (!decrypt) ProtectNL(buffer); // should not alter size
else // remember what we decrypt so we can overwrite it later when we save
{
if (!stricmp(filekind, "USER")) strcpy(encryptUser,buffer);
else strcpy(encryptLTM, buffer);
}
// prepare body for transfer to server to look like this for encryption:
// {"datavalues":{"user": {"data": {"userdata1":"abc"}}}
// or {"datavalues":{"ltm": {"data": {"userdata1":"abc"}}}
// or "{datavalues":{ "user": {"data": {"userdata1":"abc", "token" : "Sy4KoML_e"}}}
// FOR decryption: {"datavalues":{"USER": "HkD_r-KFl"}}
if (decrypt) sprintf(buffer + size, "}}"); // add suffix to data - no quote
else // encrypt gives a token if reusing
{
char* at = buffer + size;
char* which = NULL;
if (!stricmp(filekind, "USER")) which = encryptUser;
else which = encryptLTM;
if (which && *which)
{
sprintf(at,"\",\"token\": %s",which);
at += strlen(at);
}
else
{
*at++ = '"';
}
sprintf(at, "}}}"); // add suffix to data
}
size += strlen(buffer+size);
char url[500];
if (decrypt) sprintf(url, "{\"datavalues\":{\"%s\": ", filekind);
else sprintf(url, "{\"datavalues\":{\"%s\": {\"data\": \"", filekind);
int headerlen = strlen(url);
memmove(buffer+headerlen,buffer,size+1); // move the data over to put in the header
strncpy(buffer,url,headerlen);
// set up call to json open
char header[500];
strcpy(header,"Content-Type: application/json");
int oldArgumentIndex = callArgumentIndex;
int oldArgumentBase = callArgumentBase;
callArgumentBase = callArgumentIndex - 1;
callArgumentList[callArgumentIndex++] = "direct"; // get the text of it gives us, dont make facts out of it
callArgumentList[callArgumentIndex++] = "POST";
strcpy(url,server);
callArgumentList[callArgumentIndex++] = url;
callArgumentList[callArgumentIndex++] = (char*) buffer;
callArgumentList[callArgumentIndex++] = header;
callArgumentList[callArgumentIndex++] = ""; // timer override
FunctionResult result = FAILRULE_BIT;
#ifndef DISCARDJSONOPEN
result = JSONOpenCode((char*) buffer);
#endif
callArgumentIndex = oldArgumentIndex;
callArgumentBase = oldArgumentBase;
if (http_response != 200 || result != NOPROBLEM_BIT)
{
ReportBug("Encrpytion/decryption server failed %s doing %s\r\n",buffer,decrypt ? (char*) "decrypt" : (char*) "encrypt");
return 0;
}
return CleanupCryption((char*) buffer,decrypt,filekind);
}
static size_t Decrypt(void* buffer,size_t size, size_t count, FILE* file,char* filekind)
{
return JsonOpenCryption((char*) buffer, size * count,decryptServer,true,filekind);
}
static size_t Encrypt(const void* buffer, size_t size, size_t count, FILE* file,char* filekind)
{
return JsonOpenCryption((char*) buffer, size * count,encryptServer,false,filekind);
}
void EncryptInit(char* params) // required
{
*encryptServer = 0;
if (*params) strcpy(encryptServer,params);
if (*encryptServer) userFileSystem.userEncrypt = Encrypt;
}
void ResetEncryptTags()
{
encryptUser[0] = 0;
encryptLTM[0] = 0;
}
void DecryptInit(char* params) // required
{
*decryptServer = 0;
if (*params) strcpy(decryptServer,params);
if (*decryptServer) userFileSystem.userDecrypt = Decrypt;
}
void EncryptRestart() // required
{
if (*encryptServer) userFileSystem.userEncrypt = Encrypt; // reestablish encrypt/decrypt bindings
if (*decryptServer) userFileSystem.userDecrypt = Decrypt; // reestablish encrypt/decrypt bindings
}
size_t DecryptableFileRead(void* buffer,size_t size, size_t count, FILE* file,bool decrypt,char* filekind)
{
size_t len = userFileSystem.userRead(buffer,size,count,file);
if (userFileSystem.userDecrypt && decrypt) return userFileSystem.userDecrypt(buffer,1,len,file,filekind); // can revise buffer
return len;
}
size_t EncryptableFileWrite(void* buffer,size_t size, size_t count, FILE* file,bool encrypt,char* filekind)
{
if (userFileSystem.userEncrypt && encrypt)
{
size_t msgsize = userFileSystem.userEncrypt(buffer,size,count,file,filekind); // can revise buffer
return userFileSystem.userWrite(buffer,1,msgsize,file);
}
else return userFileSystem.userWrite(buffer,size,count,file);
}
void CopyFile2File(const char* newname,const char* oldname, bool automaticNumber)
{
char name[MAX_WORD_SIZE];
FILE* out;
if (automaticNumber) // get next number
{
const char* at = strchr(newname,'.'); // get suffix
int len = at - newname;
strncpy(name,newname,len);
strcpy(name,newname); // base part
char* endbase = name + len;
int j = 0;
while (++j)
{
sprintf(endbase,(char*)"%d.%s",j,at+1);
out = FopenReadWritten(name);
if (out) fclose(out);
else break;
}
}
else strcpy(name,newname);
FILE* in = FopenReadWritten(oldname);
if (!in)
{
unlink(name); // kill any old one
return;
}
out = FopenUTF8Write(name);
if (!out) // cannot create
{
return;
}
fseek (in, 0, SEEK_END);
unsigned long size = ftell(in);
fseek (in, 0, SEEK_SET);
char buffer[RECORD_SIZE];
while (size >= RECORD_SIZE)
{
fread(buffer,1,RECORD_SIZE,in);
fwrite(buffer,1,RECORD_SIZE,out);
size -= RECORD_SIZE;
}
if (size > 0)
{
fread(buffer,1,size,in);
fwrite(buffer,1,size,out);
}
fclose(out);
fclose(in);
}
int MakeDirectory(char* directory)
{
int result;
#ifdef WIN32
char word[MAX_WORD_SIZE];
char* path = _getcwd(word,MAX_WORD_SIZE);
strcat(word,(char*)"/");
strcat(word,directory);
if( _access( path, 0 ) == 0 ){ // does directory exist, yes
struct stat status;
stat( path, &status );
if ((status.st_mode & S_IFDIR) != 0) return -1;
}
result = _mkdir(directory);
#else
result = mkdir(directory, 0777);
#endif
return result;
}
void C_Directories(char* x)
{
char word[MAX_WORD_SIZE];
size_t len = MAX_WORD_SIZE;
int bytes;
#ifdef WIN32
bytes = GetModuleFileName(NULL, word, len);
#else
char szTmp[32];
sprintf(szTmp, "/proc/%d/exe", getpid());
bytes = readlink(szTmp, word, len);
#endif
if (bytes >= 0)
{
word[bytes] = 0;
Log(STDTRACELOG,(char*)"execution path: %s\r\n",word);
}
if (GetCurrentDir(word, MAX_WORD_SIZE)) Log(STDTRACELOG,(char*)"current directory path: %s\r\n",word);
Log(STDTRACELOG,(char*)"readPath: %s\r\n",readPath);
Log(STDTRACELOG,(char*)"writeablePath: %s\r\n",writePath);
Log(STDTRACELOG,(char*)"untouchedPath: %s\r\n",staticPath);
}
void InitFileSystem(char* untouchedPath,char* readablePath,char* writeablePath)
{
if (readablePath) strcpy(readPath,readablePath);
else *readPath = 0;
if (writeablePath) strcpy(writePath,writeablePath);
else *writePath = 0;
if (untouchedPath) strcpy(staticPath,untouchedPath);
else *staticPath = 0;
InitUserFiles(); // default init all the io operations to file routines
}
void StartFile(const char* name)
{
if (strnicmp(name,"TMP",3)) maxFileLine = currentFileLine = 0;
strcpy(currentFilename,name); // in case name is simple
char* at = strrchr((char*) name,'/'); // last end of path
if (at) strcpy(currentFilename,at+1);
at = strrchr(currentFilename,'\\'); // windows last end of path
if (at) strcpy(currentFilename,at+1);
}
FILE* FopenStaticReadOnly(const char* name) // static data file read path, never changed (DICT/LIVEDATA/src)
{
StartFile(name);
char path[MAX_WORD_SIZE];
if (*readPath) sprintf(path,(char*)"%s/%s",staticPath,name);
else strcpy(path,name);
return fopen(path,(char*)"rb");
}
FILE* FopenReadOnly(const char* name) // read-only potentially changed data file read path (TOPIC)
{
StartFile(name);
char path[MAX_WORD_SIZE];
if (*readPath) sprintf(path,(char*)"%s/%s",readPath,name);
else strcpy(path,name);
return fopen(path,(char*)"rb");
}
FILE* FopenReadNormal(char* name) // normal C read unrelated to special paths
{
StartFile(name);
return fopen(name,(char*)"rb");
}
void FileDelete(const char* name)
{
}
int FileSize(FILE* in, char* buffer, size_t allowedSize)
{
fseek(in, 0, SEEK_END);
int actualSize = (int) ftell(in);
fseek(in, 0, SEEK_SET);
return actualSize;
}
FILE* FopenBinaryWrite(const char* name) // writeable file path
{
char path[MAX_WORD_SIZE];
if (*writePath) sprintf(path,(char*)"%s/%s",writePath,name);
else strcpy(path,name);
FILE* out = fopen(path,(char*)"wb");
if (out == NULL && !inLog)
ReportBug((char*)"Error opening binary write file %s: %s\r\n",path,strerror(errno));
return out;
}
FILE* FopenReadWritten(const char* name) // read from files that have been written by us
{
StartFile(name);
char path[MAX_WORD_SIZE];
if (*writePath) sprintf(path,(char*)"%s/%s",writePath,name);
else strcpy(path,name);
return fopen(path,(char*)"rb");
}
FILE* FopenUTF8Write(const char* filename) // insure file has BOM for UTF8
{
char path[MAX_WORD_SIZE];
if (*writePath) sprintf(path,(char*)"%s/%s",writePath,filename);
else strcpy(path,filename);
FILE* out = fopen(path,(char*)"wb");
if (out) // mark file as UTF8
{
unsigned char bom[3];
bom[0] = 0xEF;
bom[1] = 0xBB;
bom[2] = 0xBF;
fwrite(bom,1,3,out);
}
else ReportBug((char*)"Error opening utf8 write file %s: %s\r\n",path,strerror(errno));
return out;
}
FILE* FopenUTF8WriteAppend(const char* filename,const char* flags)
{
char path[MAX_WORD_SIZE];
if (*writePath) sprintf(path,(char*)"%s/%s",writePath,filename);
else strcpy(path,filename);
FILE* in = fopen(path,(char*)"rb"); // see if file already exists
if (in) fclose(in); // dont erase currentfilame, dont call FClose
FILE* out = fopen(path,flags);
if (out && !in) // mark file as UTF8 if new
{
unsigned char bom[3];
bom[0] = 0xEF;
bom[1] = 0xBB;
bom[2] = 0xBF;
fwrite(bom,1,3,out);
}
else if (!out && !inLog)
ReportBug((char*)"Error opening utf8writeappend file %s: %s\r\n",path,strerror(errno));
return out;
}
#ifndef WIN32
int isDirectory(const char *path)
{
struct stat statbuf;
if (stat(path, &statbuf) != 0) return 0;
return S_ISDIR(statbuf.st_mode);
}
int getdir (string dir, vector<string> &files)
{
DIR *dp;
struct dirent *dirp;
if((dp = opendir(dir.c_str())) == NULL) {
ReportBug((char*)"No such directory %s\r\n",strerror(errno));
return errno;
}
while ((dirp = readdir(dp)) != NULL) files.push_back(string(dirp->d_name));
closedir(dp);
return 0;
}
#endif
void WalkDirectory(char* directory,FILEWALK function, uint64 flags,bool recursive)
{
char name[MAX_WORD_SIZE];
char fulldir[MAX_WORD_SIZE];
char xname[MAX_WORD_SIZE];
size_t len = strlen(directory);
if (directory[len-1] == '/') directory[len-1] = 0; // remove the / since we add it
if (*readPath) sprintf(fulldir,(char*)"%s/%s",staticPath,directory);
else strcpy(fulldir,directory);
bool seendirs = false;
#ifdef WIN32 // do all files in src directory
WIN32_FIND_DATA FindFileData;
DWORD dwError;
LPSTR DirSpec;
// Prepare string for use with FindFile functions. First,
// copy the string to a buffer, then append '\*' to the
// directory name.
DirSpec = (LPSTR)malloc(MAX_PATH);
strcpy(DirSpec,fulldir);
strcat(DirSpec,(char*)"/*");
// Find the first file in the directory.
HANDLE hFind = FindFirstFile(DirSpec, &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
ReportBug((char*)"No such directory %s\r\n",DirSpec);
free(DirSpec);
return;
}
if (FindFileData.cFileName[0] != '.' && stricmp(FindFileData.cFileName, (char*)"bugs.txt"))
{
if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (recursive) seendirs = true;
}
else
{
sprintf(name, (char*)"%s/%s", directory, FindFileData.cFileName);
(*function)(name, flags);
}
}
while (FindNextFile(hFind, &FindFileData) != 0)
{
if (FindFileData.cFileName[0] == '.' || !stricmp(FindFileData.cFileName, (char*)"bugs.txt")) continue;
if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (recursive) seendirs = true;
}
else // simple file
{
sprintf(name, (char*)"%s/%s", directory, FindFileData.cFileName);
(*function)(name, flags);
}
}
free(DirSpec);
dwError = GetLastError();
FindClose(hFind);
if (dwError != ERROR_NO_MORE_FILES)
{
ReportBug((char*)"FindNextFile error. Error is %u.\n", dwError);
return;
}
if (!seendirs) return;
// now recurse in directories
// Find the first file in the directory.
DirSpec = (LPSTR)malloc(MAX_PATH);
strcpy(DirSpec, fulldir);
strcat(DirSpec, (char*)"/*");
hFind = FindFirstFile(DirSpec, &FindFileData);
if (FindFileData.cFileName[0] != '.' && stricmp(FindFileData.cFileName, (char*)"bugs.txt"))
{
if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
sprintf(xname, "%s/%s", directory, FindFileData.cFileName);
WalkDirectory(xname, function, flags, true);
}
}
while (FindNextFile(hFind, &FindFileData) != 0)
{
if (FindFileData.cFileName[0] == '.' || !stricmp(FindFileData.cFileName, (char*)"bugs.txt")) continue;
if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
sprintf(xname, "%s/%s", directory, FindFileData.cFileName);
WalkDirectory(xname, function, flags, true);
}
}
FindClose(hFind);
free(DirSpec);
#else
string dir = string(fulldir);
vector<string> files = vector<string>();
getdir(dir,files);
for (unsigned int i = 0;i < files.size();i++)
{
const char* file = files[i].c_str();
size_t len = strlen(file);
if (*file != '.')
{
sprintf(name,(char*)"%s/%s",directory,file);
(*function)(name,flags); // fails if directory
if (recursive && isDirectory(xname)) seendirs = true;
}
}
if (!seendirs) return;
// recurse
for (unsigned int i = 0; i < files.size(); i++)
{
const char* file = files[i].c_str();
if (*file == '.' || !stricmp(file, (char*)"bugs.txt")) continue;
sprintf(xname, "%s/%s", directory, file);
if (isDirectory(xname))
{
WalkDirectory(xname, function, flags, true);
}
}
#endif
}
string GetUserPathString(const string &login)
{
string userPath;
if (login.length() == 0) return userPath; // empty string
size_t len = login.length();
int counter = 0;
for (size_t i = 0; i < len; i++) // use each character
{
if (login.c_str()[i] == '.' || login.c_str()[i] == '_') continue; // ignore IP . stuff
userPath.append(1, login.c_str()[i]);
userPath.append(1, '/');
if (++counter >= 4) break;
}
return userPath;
}
#ifdef USERPATHPREFIX
static int MakePath(const string &rootDir, const string &path)
{
#ifndef WIN32
struct stat st;
if (stat((rootDir + "/" + path).c_str(), &st) == 0) return 1;
#endif
string pathToCreate(rootDir);
size_t previous = 0;
for (size_t next = path.find('/'); next != string::npos; previous = next + 1, next = path.find('/', next + 1))
{
pathToCreate.append((char*)"/");
pathToCreate.append(path.substr(previous, next - previous));
#ifdef WIN32
if (_mkdir(pathToCreate.c_str()) == -1 && errno != EEXIST) return 0;
#elif EVSERVER
if (mkdir(pathToCreate.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == -1 && errno != EEXIST) return 0;
#else
if (mkdir(pathToCreate.c_str(), S_IRWXU | S_IRWXG) == -1 && errno != EEXIST) return 0;
#endif
}
return 1;
}
#endif
char* GetUserPath(char* login)
{
static string userPath;
char* path = "";
#ifdef USERPATHPREFIX
if (server)
{
if (!filesystemOverride) // do not use this with db storage
{
userPath = GetUserPathString(login);
MakePath(users, userPath);
path = (char*) userPath.c_str();
}
}
#endif
return path;
}
/////////////////////////////////////////////////////////
/// TIME FUNCTIONS
/////////////////////////////////////////////////////////
void mylocaltime (const time_t * timer,struct tm* ptm)
{
SafeLock();
*ptm = *localtime(timer); // copy data across so not depending on it outside of lock
SafeUnlock();
}
void myctime(time_t * timer,char* buffer)// Www Mmm dd hh:mm:ss yyyy
{
SafeLock();
strcpy(buffer,ctime(timer));
SafeUnlock();
}
char* GetTimeInfo(struct tm* ptm, bool nouser,bool utc) // Www Mmm dd hh:mm:ss yyyy Where Www is the weekday, Mmm the month in letters, dd the day of the month, hh:mm:ss the time, and yyyy the year. Sat May 20 15:21:51 2000
{
time_t curr = time(0); // local machine time
if (regression) curr = 44444444;
mylocaltime (&curr,ptm);
char* utcoffset = (nouser) ? (char*)"" : GetUserVariable((char*)"$cs_utcoffset");
if (utc) utcoffset = (char*)"+0";
if (*utcoffset) // report UTC relative time - so if time is 1PM and offset is -1:00, time reported to user is 12 PM.
{
SafeLock();
*ptm = *gmtime (&curr); // this library call is not thread safe, copy its data
SafeUnlock();
// determine leap year status
int year = ptm->tm_year + 1900;
bool leap = false;
if ((year / 400) == 0) leap = true;
else if ((year / 100) != 0 && (year / 4) == 0) leap = true;
// sign of offset
int sign = 1;
if (*utcoffset == '-')
{
sign = -1;
++utcoffset;
}
else if (*utcoffset == '+') ++utcoffset;
// adjust hours, minutes, seconds
int offset = atoi(utcoffset) * sign; // hours offset
ptm->tm_hour += offset;
char* colon = strchr(utcoffset,':'); // is there a minutes offset?
if (colon)
{
offset = atoi(colon+1) * sign; // minutes offset same sign
ptm->tm_min += offset;
colon = strchr(colon+1,':');
if (colon) // seconds offset
{
offset = atoi(colon+1) * sign; // seconds offset
ptm->tm_sec += offset;
}
}
// correct for over and underflows
if (ptm->tm_sec < 0) // sec underflow caused by timezone
{
ptm->tm_sec += 60;
ptm->tm_min -= 1;
}
else if (ptm->tm_sec >= 60) // sec overflow caused by timezone
{
ptm->tm_sec -= 60;
ptm->tm_min += 1;
}
if (ptm->tm_min < 0) // min underflow caused by timezone
{
ptm->tm_min += 60;
ptm->tm_hour -= 1;
}
else if (ptm->tm_min >= 60) // min overflow caused by timezone
{
ptm->tm_min -= 60;
ptm->tm_hour += 1;
}
if (ptm->tm_hour < 0) // hour underflow caused by timezone
{
ptm->tm_hour += 24;
ptm->tm_yday -= 1;
ptm->tm_mday -= 1;
ptm->tm_wday -= 1;
}
else if (ptm->tm_hour >= 24) // hour overflow caused by timezone
{
ptm->tm_hour -= 24;
ptm->tm_yday += 1;
ptm->tm_mday += 1;
ptm->tm_wday += 1;
}
if (ptm->tm_wday < 0) ptm->tm_wday += 7; // day of week underflow 0-6
else if (ptm->tm_wday >= 7) ptm->tm_wday -= 7; // day of week overflow 0-6
if (ptm->tm_yday < 0) ptm->tm_yday += 365; // day of year underflow 0-365
else if (ptm->tm_yday >= 365 && !leap ) ptm->tm_yday -= 365; // day of year overflow 0-365
else if (ptm->tm_yday >= 366) ptm->tm_yday -= 366; // day of year leap overflow 0-365
if (ptm->tm_mday <= 0) // day of month underflow 1-31
{
ptm->tm_mon -= 1;
if (ptm->tm_mon == 1) // feb
{
if (leap) ptm->tm_mday = 29;
else ptm->tm_mday = 28;
}
else if (ptm->tm_mon == 3) ptm->tm_mday = 30; // apr
else if (ptm->tm_mon == 5) ptm->tm_mday = 30;// june
else if (ptm->tm_mon == 8) ptm->tm_mday = 30;// sept
else if (ptm->tm_mon == 10) ptm->tm_mday = 30; // nov
else ptm->tm_mday = 31;
}
else // day of month overflow by 1? 1-31
{
if (ptm->tm_mon == 1 ) // feb
{
if (leap && ptm->tm_mday == 30) {ptm->tm_mon++; ptm->tm_mday = 1;}
else if (ptm->tm_mday == 29) {ptm->tm_mon++; ptm->tm_mday = 1;}
}
else if (ptm->tm_mon == 3 && ptm->tm_mday == 31) {ptm->tm_mon++; ptm->tm_mday = 1;} // apr
else if (ptm->tm_mon == 5 && ptm->tm_mday == 31) {ptm->tm_mon++; ptm->tm_mday = 1;}// june
else if (ptm->tm_mon == 8 && ptm->tm_mday == 31) {ptm->tm_mon++; ptm->tm_mday = 1;}// sept
else if (ptm->tm_mon == 10 && ptm->tm_mday == 31) {ptm->tm_mon++; ptm->tm_mday = 1;} // nov
else if (ptm->tm_mday == 32) {ptm->tm_mon++; ptm->tm_mday = 1;}
}
if (ptm->tm_mon < 0) // month underflow 0-11
{
ptm->tm_mon += 12; // back to december
ptm->tm_year -= 1; // prior year
}
else if (ptm->tm_mon >= 12 ) // month overflow 0-11
{
ptm->tm_mon -= 12; // january
ptm->tm_year += 1; // on to next year
}
}
SafeLock();
char *mytime = asctime (ptm); // not thread safe
SafeUnlock();
mytime[strlen(mytime)-1] = 0; // remove newline
if (mytime[8] == ' ') mytime[8] = '0';
return mytime;
}
char* GetMyTime(time_t curr)
{
char mytime[100];
myctime(&curr,mytime); // Www Mmm dd hh:mm:ss yyyy
static char when[40];
strncpy(when,mytime+4,3); // mmm
if (mytime[8] == ' ') mytime[8] = '0';
strncpy(when+3,mytime+8,2); // dd
when[5] = '\'';
strncpy(when+6,mytime+22,2); // yy
when[8] = '-';
strncpy(when+9,mytime+11,8); // hh:mm:ss
when[17] = 0;
return when;
}
#ifdef IOS
#elif __MACH__
void clock_get_mactime(struct timespec &ts)
{
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
ts.tv_sec = mts.tv_sec;
ts.tv_nsec = mts.tv_nsec;
}
#endif
uint64 ElapsedMilliseconds()
{
uint64 count;
#ifdef WIN32
//count = GetTickCount64();
FILETIME t; // 100 - nanosecond intervals since midnight Jan 1, 1601.
GetSystemTimeAsFileTime(&t);
uint64 x = (LONGLONG)t.dwLowDateTime + ((LONGLONG)(t.dwHighDateTime) << 32LL);
x /= 10000; // 100-nanosecond intervals in a millisecond
x -= 116444736000000000LL; // unix epoch Jan 1, 1970.
count = x;
#elif IOS
struct timeval x_time;
gettimeofday(&x_time, NULL);
count = x_time.tv_sec * 1000;
count += x_time.tv_usec / 1000;
#elif __MACH__
struct timespec abs_time;
clock_get_mactime( abs_time);
count = abs_time.tv_sec * 1000;
count += abs_time.tv_nsec / 1000000;
#else // LINUX
struct timeval x_time;
gettimeofday(&x_time, NULL);
count = x_time.tv_sec * 1000;
count += x_time.tv_usec / 1000;
#endif
return count;
}
#ifndef WIN32
unsigned int GetFutureSeconds(unsigned int seconds)
{
struct timespec abs_time;
#ifdef __MACH__
clock_get_mactime(abs_time);
#else
clock_gettime(CLOCK_REALTIME,&abs_time);
#endif
return abs_time.tv_sec + seconds;
}
#endif
////////////////////////////////////////////////////////////////////////
/// RANDOM NUMBERS
////////////////////////////////////////////////////////////////////////
#define X64(n) (n##ULL)
uint64 X64_Table[256] = // hash table randomizer
{
X64(0x0000000000000000), X64(0x42f0e1eba9ea3693), X64(0x85e1c3d753d46d26), X64(0xc711223cfa3e5bb5),
X64(0x493366450e42ecdf), X64(0x0bc387aea7a8da4c), X64(0xccd2a5925d9681f9), X64(0x8e224479f47cb76a),
X64(0x9266cc8a1c85d9be), X64(0xd0962d61b56fef2d), X64(0x17870f5d4f51b498), X64(0x5577eeb6e6bb820b),
X64(0xdb55aacf12c73561), X64(0x99a54b24bb2d03f2), X64(0x5eb4691841135847), X64(0x1c4488f3e8f96ed4),
X64(0x663d78ff90e185ef), X64(0x24cd9914390bb37c), X64(0xe3dcbb28c335e8c9), X64(0xa12c5ac36adfde5a),
X64(0x2f0e1eba9ea36930), X64(0x6dfeff5137495fa3), X64(0xaaefdd6dcd770416), X64(0xe81f3c86649d3285),
X64(0xf45bb4758c645c51), X64(0xb6ab559e258e6ac2), X64(0x71ba77a2dfb03177), X64(0x334a9649765a07e4),
X64(0xbd68d2308226b08e), X64(0xff9833db2bcc861d), X64(0x388911e7d1f2dda8), X64(0x7a79f00c7818eb3b),
X64(0xcc7af1ff21c30bde), X64(0x8e8a101488293d4d), X64(0x499b3228721766f8), X64(0x0b6bd3c3dbfd506b),
X64(0x854997ba2f81e701), X64(0xc7b97651866bd192), X64(0x00a8546d7c558a27), X64(0x4258b586d5bfbcb4),
X64(0x5e1c3d753d46d260), X64(0x1cecdc9e94ace4f3), X64(0xdbfdfea26e92bf46), X64(0x990d1f49c77889d5),
X64(0x172f5b3033043ebf), X64(0x55dfbadb9aee082c), X64(0x92ce98e760d05399), X64(0xd03e790cc93a650a),
X64(0xaa478900b1228e31), X64(0xe8b768eb18c8b8a2), X64(0x2fa64ad7e2f6e317), X64(0x6d56ab3c4b1cd584),
X64(0xe374ef45bf6062ee), X64(0xa1840eae168a547d), X64(0x66952c92ecb40fc8), X64(0x2465cd79455e395b),
X64(0x3821458aada7578f), X64(0x7ad1a461044d611c), X64(0xbdc0865dfe733aa9), X64(0xff3067b657990c3a),
X64(0x711223cfa3e5bb50), X64(0x33e2c2240a0f8dc3), X64(0xf4f3e018f031d676), X64(0xb60301f359dbe0e5),
X64(0xda050215ea6c212f), X64(0x98f5e3fe438617bc), X64(0x5fe4c1c2b9b84c09), X64(0x1d14202910527a9a),
X64(0x93366450e42ecdf0), X64(0xd1c685bb4dc4fb63), X64(0x16d7a787b7faa0d6), X64(0x5427466c1e109645),
X64(0x4863ce9ff6e9f891), X64(0x0a932f745f03ce02), X64(0xcd820d48a53d95b7), X64(0x8f72eca30cd7a324),
X64(0x0150a8daf8ab144e), X64(0x43a04931514122dd), X64(0x84b16b0dab7f7968), X64(0xc6418ae602954ffb),
X64(0xbc387aea7a8da4c0), X64(0xfec89b01d3679253), X64(0x39d9b93d2959c9e6), X64(0x7b2958d680b3ff75),
X64(0xf50b1caf74cf481f), X64(0xb7fbfd44dd257e8c), X64(0x70eadf78271b2539), X64(0x321a3e938ef113aa),
X64(0x2e5eb66066087d7e), X64(0x6cae578bcfe24bed), X64(0xabbf75b735dc1058), X64(0xe94f945c9c3626cb),
X64(0x676dd025684a91a1), X64(0x259d31cec1a0a732), X64(0xe28c13f23b9efc87), X64(0xa07cf2199274ca14),
X64(0x167ff3eacbaf2af1), X64(0x548f120162451c62), X64(0x939e303d987b47d7), X64(0xd16ed1d631917144),
X64(0x5f4c95afc5edc62e), X64(0x1dbc74446c07f0bd), X64(0xdaad56789639ab08), X64(0x985db7933fd39d9b),
X64(0x84193f60d72af34f), X64(0xc6e9de8b7ec0c5dc), X64(0x01f8fcb784fe9e69), X64(0x43081d5c2d14a8fa),
X64(0xcd2a5925d9681f90), X64(0x8fdab8ce70822903), X64(0x48cb9af28abc72b6), X64(0x0a3b7b1923564425),
X64(0x70428b155b4eaf1e), X64(0x32b26afef2a4998d), X64(0xf5a348c2089ac238), X64(0xb753a929a170f4ab),
X64(0x3971ed50550c43c1), X64(0x7b810cbbfce67552), X64(0xbc902e8706d82ee7), X64(0xfe60cf6caf321874),
X64(0xe224479f47cb76a0), X64(0xa0d4a674ee214033), X64(0x67c58448141f1b86), X64(0x253565a3bdf52d15),
X64(0xab1721da49899a7f), X64(0xe9e7c031e063acec), X64(0x2ef6e20d1a5df759), X64(0x6c0603e6b3b7c1ca),
X64(0xf6fae5c07d3274cd), X64(0xb40a042bd4d8425e), X64(0x731b26172ee619eb), X64(0x31ebc7fc870c2f78),
X64(0xbfc9838573709812), X64(0xfd39626eda9aae81), X64(0x3a28405220a4f534), X64(0x78d8a1b9894ec3a7),
X64(0x649c294a61b7ad73), X64(0x266cc8a1c85d9be0), X64(0xe17dea9d3263c055), X64(0xa38d0b769b89f6c6),
X64(0x2daf4f0f6ff541ac), X64(0x6f5faee4c61f773f), X64(0xa84e8cd83c212c8a), X64(0xeabe6d3395cb1a19),
X64(0x90c79d3fedd3f122), X64(0xd2377cd44439c7b1), X64(0x15265ee8be079c04), X64(0x57d6bf0317edaa97),
X64(0xd9f4fb7ae3911dfd), X64(0x9b041a914a7b2b6e), X64(0x5c1538adb04570db), X64(0x1ee5d94619af4648),
X64(0x02a151b5f156289c), X64(0x4051b05e58bc1e0f), X64(0x87409262a28245ba), X64(0xc5b073890b687329),
X64(0x4b9237f0ff14c443), X64(0x0962d61b56fef2d0), X64(0xce73f427acc0a965), X64(0x8c8315cc052a9ff6),
X64(0x3a80143f5cf17f13), X64(0x7870f5d4f51b4980), X64(0xbf61d7e80f251235), X64(0xfd913603a6cf24a6),
X64(0x73b3727a52b393cc), X64(0x31439391fb59a55f), X64(0xf652b1ad0167feea), X64(0xb4a25046a88dc879),
X64(0xa8e6d8b54074a6ad), X64(0xea16395ee99e903e), X64(0x2d071b6213a0cb8b), X64(0x6ff7fa89ba4afd18),
X64(0xe1d5bef04e364a72), X64(0xa3255f1be7dc7ce1), X64(0x64347d271de22754), X64(0x26c49cccb40811c7),
X64(0x5cbd6cc0cc10fafc), X64(0x1e4d8d2b65facc6f), X64(0xd95caf179fc497da), X64(0x9bac4efc362ea149),
X64(0x158e0a85c2521623), X64(0x577eeb6e6bb820b0), X64(0x906fc95291867b05), X64(0xd29f28b9386c4d96),
X64(0xcedba04ad0952342), X64(0x8c2b41a1797f15d1), X64(0x4b3a639d83414e64), X64(0x09ca82762aab78f7),
X64(0x87e8c60fded7cf9d), X64(0xc51827e4773df90e), X64(0x020905d88d03a2bb), X64(0x40f9e43324e99428),
X64(0x2cffe7d5975e55e2), X64(0x6e0f063e3eb46371), X64(0xa91e2402c48a38c4), X64(0xebeec5e96d600e57),
X64(0x65cc8190991cb93d), X64(0x273c607b30f68fae), X64(0xe02d4247cac8d41b), X64(0xa2dda3ac6322e288),
X64(0xbe992b5f8bdb8c5c), X64(0xfc69cab42231bacf), X64(0x3b78e888d80fe17a), X64(0x7988096371e5d7e9),
X64(0xf7aa4d1a85996083), X64(0xb55aacf12c735610), X64(0x724b8ecdd64d0da5), X64(0x30bb6f267fa73b36),
X64(0x4ac29f2a07bfd00d), X64(0x08327ec1ae55e69e), X64(0xcf235cfd546bbd2b), X64(0x8dd3bd16fd818bb8),
X64(0x03f1f96f09fd3cd2), X64(0x41011884a0170a41), X64(0x86103ab85a2951f4), X64(0xc4e0db53f3c36767),
X64(0xd8a453a01b3a09b3), X64(0x9a54b24bb2d03f20), X64(0x5d45907748ee6495), X64(0x1fb5719ce1045206),
X64(0x919735e51578e56c), X64(0xd367d40ebc92d3ff), X64(0x1476f63246ac884a), X64(0x568617d9ef46bed9),
X64(0xe085162ab69d5e3c), X64(0xa275f7c11f7768af), X64(0x6564d5fde549331a), X64(0x279434164ca30589),
X64(0xa9b6706fb8dfb2e3), X64(0xeb46918411358470), X64(0x2c57b3b8eb0bdfc5), X64(0x6ea7525342e1e956),
X64(0x72e3daa0aa188782), X64(0x30133b4b03f2b111), X64(0xf7021977f9cceaa4), X64(0xb5f2f89c5026dc37),
X64(0x3bd0bce5a45a6b5d), X64(0x79205d0e0db05dce), X64(0xbe317f32f78e067b), X64(0xfcc19ed95e6430e8),
X64(0x86b86ed5267cdbd3), X64(0xc4488f3e8f96ed40), X64(0x0359ad0275a8b6f5), X64(0x41a94ce9dc428066),
X64(0xcf8b0890283e370c), X64(0x8d7be97b81d4019f), X64(0x4a6acb477bea5a2a), X64(0x089a2aacd2006cb9),
X64(0x14dea25f3af9026d), X64(0x562e43b4931334fe), X64(0x913f6188692d6f4b), X64(0xd3cf8063c0c759d8),
X64(0x5dedc41a34bbeeb2), X64(0x1f1d25f19d51d821), X64(0xd80c07cd676f8394), X64(0x9afce626ce85b507)
};
uint64 Hashit(unsigned char * data, int len,bool & hasUpperCharacters, bool & hasUTF8Characters)
{
hasUpperCharacters = hasUTF8Characters = false;
uint64 crc = 5381;
while (len-- > 0)
{
unsigned char c = *data++;
if (c >= 0x41 && c <= 0x5a) // ordinary ascii upper case
{
c += 32;
hasUpperCharacters = true;
}
else if (c & 0x80) // some kind of utf8 extended char
{
hasUTF8Characters = true;
if (c == 0xc3 && *data >= 0x80 && *data <= 0x9e && *data != 0x97)
{
hasUpperCharacters = true;
crc = ((crc << 5) + crc) + c;
//crc = X64_Table[(crc >> 56) ^ c] ^ (crc << 8);
c = *data++; // get the cap form
c -= 0x80;
c += 0xa0; // get lower case form
--len;
}
else if (c >= 0xc4 && c <= 0xc9 && !(c & 1))
{
hasUpperCharacters = true;
crc = ((crc << 5) + crc) + c;
//crc = X64_Table[(crc >> 56) ^ c] ^ (crc << 8);
c = *data++; // get the cap form
c |= 1; // get lower case form
--len;
}
else // other utf8, do all but last char
{
int size = UTFCharSize((char*)data - 1);
while (--size)
{
crc = ((crc << 5) + crc) + c;
//crc = X64_Table[(crc >> 56) ^ c] ^ (crc << 8);
c = *data++;
--len;
}
}
}
if (c == ' ') c = '_'; // force common hash on space vs _
//better but slower crc = X64_Table[(crc >> 56) ^ c ] ^ (crc << 8 );
crc = ((crc << 5) + crc) + c;
}
return crc;
}
unsigned int random(unsigned int range)
{
if (regression || range <= 1) return 0;
unsigned int x = (unsigned int)X64_Table[randIndex++ % MAXRAND];
return x % range;
}
/////////////////////////////////////////////////////////
/// LOGGING
/////////////////////////////////////////////////////////
uint64 logCount = 0;
bool TraceFunctionArgs(FILE* out, char* name, int start, int end)
{
if (!name || name[0] == '~') return false;
WORDP D = FindWord(name);
if (!D) return false; // like fake ^ruleoutput
unsigned int args = end - start;
char arg[MAX_WORD_SIZE];
fprintf(out, "( ");
for (unsigned int i = 0; i < args; ++i)
{
strncpy(arg, callArgumentList[start + i], 50); // may be name and not value?
arg[50] = 0;
fprintf(out, "%s ", arg);
}
fprintf(out, ")");
return true;
}
void BugBacktrace(FILE* out)
{
int i = globalDepth;
char rule[MAX_WORD_SIZE];
CALLFRAME* frame = GetCallFrame(i);
if (frame && frame->label && *(frame->label))
{
rule[0] = 0;
if (currentRule) {
strncpy(rule, currentRule, 50);
rule[50] = 0;
}
CALLFRAME* priorframe = GetCallFrame(i - 1);
fprintf(out,"Finished %d: heapusedOnEntry: %d heapUsedNow: %d buffers:%d stackused: %d stackusedNow:%d %s ",
i,frame->heapDepth,(int)(heapBase-heapFree),frame->memindex,(int)(heapFree - (char*)releaseStackDepth[i]), (int)(stackFree-stackStart),frame->label);
if (priorframe && !TraceFunctionArgs(out, frame->label, (i > 0) ? priorframe->argumentStartIndex: 0, frame->argumentStartIndex)) fprintf(out, " - %s", rule);
fprintf(out, "\r\n");
}
while (--i > 1)
{
frame = GetCallFrame(i);
if (frame->rule) strncpy(rule,frame->rule,50);
else strcpy(rule, "unknown rule");
rule[50] = 0;
fprintf(out,"BugDepth %d: heapusedOnEntry: %d buffers:%d stackused: %d %s ",
i,frame->heapDepth,GetCallFrame(i)->memindex,
(int)(heapFree - (char*)releaseStackDepth[i]), frame->label);
if (!TraceFunctionArgs(out, frame->label, GetCallFrame(i-1)->argumentStartIndex, GetCallFrame(i - 1)->argumentStartIndex)) fprintf(out, " - %s", rule);
fprintf(out, "\r\n");
}
}
CALLFRAME* ChangeDepth(int value,char* name,bool nostackCutback, char* code)
{
if (value == 0) // secondary call from userfunction. frame is now valid
{
CALLFRAME* frame = releaseStackDepth[globalDepth];
if (showDepth) Log(STDUSERLOG,(char*)"same depth %d %s \r\n", globalDepth, name);
if (name) frame->label = name; // override
if (code) frame->code = code;
#ifndef DISCARDTESTING
if (debugCall) (*debugCall)(frame->label, true);
#endif
return frame;
}
else if (value < 0) // leaving depth
{
bool abort = false;
CALLFRAME* frame = releaseStackDepth[globalDepth];
#ifndef DISCARDTESTING
if (globalDepth && *name && debugCall)
{
char* result = (*debugCall)(name, false);
if (result) abort = true;
}
#endif
frame->name = NULL;
frame->rule = NULL;
frame->label = NULL;
if (frame->memindex != bufferIndex)
{
ReportBug((char*)"depth %d not closing bufferindex correctly at %s bufferindex now %d was %d\r\n",globalDepth,name,bufferIndex,frame->memindex);
}
callArgumentIndex = frame->argumentStartIndex;
currentRuleID = frame->oldRuleID;
currentTopicID = frame->oldTopic;
currentRuleTopic = frame->oldRuleTopic;
currentRule = frame->oldRule;
// engine functions that are streams should not destroy potential local adjustments
if (!nostackCutback)
stackFree = (char*) frame; // deallocoate ARGUMENT space
if (showDepth) Log(STDUSERLOG, (char*)"-depth %d %s bufferindex %d heapused:%d\r\n", globalDepth,name, bufferIndex,(int)(heapBase-heapFree));
globalDepth += value;
if (globalDepth < 0) { ReportBug((char*)"bad global depth in %s", name); globalDepth = 0; }
return (abort) ? (CALLFRAME*)1 : NULL; // abort code
}
else // value > 0
{
stackFree = (char*)(((uint64)stackFree + 7) & 0xFFFFFFFFFFFFFFF8ULL);
CALLFRAME* frame = (CALLFRAME*) stackFree;
stackFree += sizeof(CALLFRAME);
memset(frame, 0,sizeof(CALLFRAME));
frame->label = name;
frame->code = code;
frame->rule = (currentRule) ? currentRule : (char*) "";
frame->outputlevel = outputlevel + 1;
frame->argumentStartIndex = callArgumentIndex;
frame->oldRuleID = currentRuleID;
frame->oldTopic = currentTopicID;
frame->oldRuleTopic = currentRuleTopic;
frame->oldRule = currentRule;
frame->memindex = bufferIndex;
frame->heapDepth = heapBase - heapFree;
globalDepth += value;
if (showDepth) Log(STDUSERLOG, (char*)"+depth %d %s bufferindex %d heapused: %d stackused:%d gap:%d\r\n", globalDepth, name, bufferIndex, (int)(heapBase - heapFree), (int)(stackFree - stackStart), (int)(heapFree - stackFree));
releaseStackDepth[globalDepth] = frame; // define argument start space - release back to here on exit
#ifndef DISCARDTESTING
if (globalDepth && *name != '*' && debugCall) (*debugCall)(name, true);
#endif
if (globalDepth >= (MAX_GLOBAL - 1)) ReportBug((char*)"FATAL: globaldepth too deep at %s\r\n", name);
if (globalDepth > maxGlobalSeen) maxGlobalSeen = globalDepth;
return frame;
}
}
bool LogEndedCleanly()
{
return (logLastCharacter == '\n' || !logLastCharacter); // legal
}
char* myprinter(const char* ptr, char* at, va_list ap)
{
char* base = at;
// start writing normal data here
char* s;
int i;
while (*++ptr)
{
if (*ptr == '%')
{
++ptr;
if (*ptr == 'c') sprintf(at, (char*)"%c", (char)va_arg(ap, int)); // char
else if (*ptr == 'd') sprintf(at, (char*)"%d", va_arg(ap, int)); // int %d
else if (*ptr == 'I') // I64
{
#ifdef WIN32
sprintf(at, (char*)"%I64d", va_arg(ap, uint64));
#else
sprintf(at, (char*)"%lld", va_arg(ap, uint64));
#endif
ptr += 2;
}
else if (*ptr == 'l' && ptr[1] == 'd') // ld
{
sprintf(at, (char*)"%ld", va_arg(ap, long int));
++ptr;
}
else if (*ptr == 'l' && ptr[1] == 'l') // lld
{
#ifdef WIN32
sprintf(at, (char*)"%I64d", va_arg(ap, long long int));
#else
sprintf(at, (char*)"%lld", va_arg(ap, long long int));
#endif
ptr += 2;
}
else if (*ptr == 'p') sprintf(at, (char*)"%p", va_arg(ap, char*)); // ptr
else if (*ptr == 'f')
{
double f = (double)va_arg(ap, double);
sprintf(at, (char*)"%f", f); // float
}
else if (*ptr == 's') // string
{
s = va_arg(ap, char*);
if (s) sprintf(at, (char*)"%s", s);
}
else if (*ptr == 'x') sprintf(at, (char*)"%x", (unsigned int)va_arg(ap, unsigned int)); // hex
else if (IsDigit(*ptr)) // int %2d or %08x
{
i = va_arg(ap, int);
unsigned int precision = atoi(ptr);
while (*ptr && *ptr != 'd' && *ptr != 'x') ++ptr;
if (*ptr == 'd')
{
if (precision == 2) sprintf(at, (char*)"%2d", i);
else if (precision == 3) sprintf(at, (char*)"%3d", i);
else if (precision == 4) sprintf(at, (char*)"%4d", i);
else if (precision == 5) sprintf(at, (char*)"%5d", i);
else if (precision == 6) sprintf(at, (char*)"%6d", i);
else sprintf(at, (char*)" Bad int precision %d ", precision);
}
else
{
if (precision == 8) sprintf(at, (char*)"%08x", i);
else sprintf(at, (char*)" Bad hex precision %d ", precision);
}
}
else
{
sprintf(at, (char*)"%s", (char*)"unknown format ");
ptr = 0;
}
}
else sprintf(at, (char*)"%c", *ptr);
at += strlen(at);
if (!ptr) break;
if ((at - base) >= (logsize - SAFE_BUFFER_MARGIN)) break; // prevent log overflow
}
*at = 0;
return at;
}
int myprintf(const char * fmt, ...)
{
if (!logmainbuffer) logmainbuffer = (char*)malloc(logsize);
char* at = logmainbuffer;
*at = 0;
va_list ap;
va_start(ap, fmt);
const char *ptr = fmt - 1;
at = myprinter(ptr, at, ap);
va_end(ap);
if (debugOutput) (*debugOutput)(logmainbuffer);
return 1;
}
static FILE* rotateLogOnLimit(char *fname,char* directory) {
FILE* out = FopenUTF8WriteAppend(fname);
if (!out) // see if we can create the directory (assuming its missing)
{
MakeDirectory(directory);
out = userFileSystem.userCreate(fname);
if (!out && !inLog) ReportBug((char*)"unable to create logfile %s", fname);
}
int64 size = 0;
if (out && loglimit) {
// roll log if it is too big
int r = fseek(out, 0, SEEK_END);
#ifdef WIN32
size = _ftelli64(out);
#else
size = ftello(out);
#endif
// get MB count of it roughly
size /= 1000000; // MB bytes
}
if (size > loglimit)
{
// roll log if it is too big
fclose(out);
time_t curr = time(0);
char* when = GetMyTime(curr); // now
char newname[MAX_WORD_SIZE];
strcpy(newname, fname);
char* at = strrchr(newname, '.');
sprintf(at, "-%s.txt", when);
at = strchr(newname, ':');
*at = '-';
at = strchr(newname, ':');
*at = '-';
int result = rename(fname, newname);
if (result != 0) perror("Error renaming file");
out = FopenUTF8WriteAppend(fname);
}
return out;
}
unsigned int Log(unsigned int channel,const char * fmt, ...)
{
if (channel == STDTRACELOG) channel = STDUSERLOG;
static unsigned int id = 1000;
if (quitting) return id;
logged = true;
bool localecho = false;
bool noecho = false;
if (channel == ECHOSTDTRACELOG)
{
localecho = true;
channel = STDUSERLOG;
}
if (channel == STDTIMELOG) {
noecho = true;
channel = STDUSERLOG;
}
if (channel == STDTIMETABLOG) {
noecho = true;
channel = STDTRACETABLOG;
}
// allow user logging if trace is on.
if (!userLog && (channel == STDUSERLOG || channel > 1000 || channel == id) && !testOutput && !trace) return id;
if (!fmt) return id; // no format or no buffer to use
if ((channel == SERVERLOG) && server && !serverLog) return id; // not logging server data
static int priordepth = 0;
// start writing normal data here
if (!logmainbuffer) logmainbuffer = (char*)malloc(logsize);
char* at = logmainbuffer;
*at = 0;
va_list ap;
va_start(ap,fmt);
++logCount;
const char *ptr = fmt - 1;
// when this channel matches the ID of the prior output of log,
// we dont force new line on it.
if (channel == id) // join result code onto intial description
{
channel = 1;
strcpy(at,(char*)" ");
at += 4;
}
// any channel above 1000 is same as 101
else if (channel > 1000) channel = STDTRACELOG; // force result code to indent new line
// channels above 100 will indent when prior line not ended
if (channel != BUGLOG && channel >= STDTRACELOG && logLastCharacter != '\\') // indented by call level and not merged
{ // STDTRACELOG 101 is std indending characters 201 = attention getting
if (logLastCharacter == 1 && globalDepth == priordepth) {} // we indented already
else if (logLastCharacter == 1 && globalDepth > priordepth) // we need to indent a bit more
{
for (int i = priordepth; i < globalDepth; i++)
{
*at++ = (i == 4 || i == 9) ? ',' : '.';
}
priordepth = globalDepth;
}
else
{
if (logLastCharacter != '\n') // log legal
{
*at++ = '\r'; // close out this prior thing
*at++ = '\n'; // log legal
}
while (ptr[1] == '\n' || ptr[1] == '\r') // we point BEFORE the format
{
*at++ = *++ptr;
}
int n = globalDepth + patternDepth;
if (n < 0) n = 0; // just in case
for (int i = 0; i < n; i++)
{
if (channel == STDTRACEATTNLOG) *at++ = (i == 1) ? '*' : ' ';
else *at++ = (i == 4 || i == 9) ? ',' : '.';
}
priordepth = globalDepth;
}
}
channel %= 100;
at = myprinter(ptr,at, ap);
va_end(ap);
// implement unlogged data
if (hide)
{
char* hidden = hide; // multiple hiddens separated by spaces, presumed covered by quotes in real data
char* next = hidden; // start of next field name
char word[MAX_WORD_SIZE]; // thing we search for
*word = '"';
while (next)
{
char* begin = next;
next = strchr(begin, ' '); // example is "authorized" or authorized or "authorized": or whatever
if (next) *next = 0;
strcpy(word+1, begin);
if (next) *next++ = ' ';
size_t len = strlen(word);
word[len++] = '"';
word[len] = 0; // key now in quotes
char* found = strstr(logmainbuffer, word); // find instance of key (presumed only one)
if (found) // is this item in our output to log? assume only 1 occurrence per output
{
// this will json field name, not requiring quotes but JSON will probably have them.
// value will be simple string, not a structure
char* after = found + len; // immediately past item is what?
while (*after == ' ') ++after; // skip past space after
if (*after == ':') ++after; // skip a separator
else break; // illegal, not a field name
while (*after == ' ') ++after; // skip past space after
if (*after == '"') // string value to skip
{
char* quote = after + 1;
while ((quote = strchr(quote, '"'))) // find closing quote - MUST BE FOUND
{
if (*(quote - 1) == '\\') ++quote; // escaped quote ignore
else // ending quote
{
++quote;
while (*quote == ' ') ++quote; // skip trailing space
if (*quote == ',') ++quote; // skip comma
at -= (quote - found); // move the end point by the number of characters skipped
memmove(found, quote, strlen(found));
break;
}
}
}
}
}
}
if (channel == STDDEBUGLOG) // debugger output
{
if (debugOutput) (*debugOutput)(logmainbuffer); // send to CS debugger
else printf("%s",logmainbuffer); // directly show to user
inLog = false;
return ++id;
}
logLastCharacter = (at > logmainbuffer) ? *(at-1) : 0; // ends on NL?
if (fmt && !*fmt) logLastCharacter = 1; // special marker
if (logLastCharacter == '\\') *--at = 0; // dont show it (we intend to merge lines)
logUpdated = true; // in case someone wants to see if intervening output happened
size_t bufLen = at - logmainbuffer;
inLog = true;
bool bugLog = false;
if (pendingWarning)
{
AddWarning(logmainbuffer);
pendingWarning = false;
}
else if (!strnicmp(logmainbuffer,(char*)"*** Warning",11))
pendingWarning = true;// replicate for easy dump later
if (pendingError)
{
AddError(logmainbuffer);
pendingError= false;
}
else if (!strnicmp(logmainbuffer,(char*)"*** Error",9))
pendingError = true;// replicate for easy dump later
#ifndef DISCARDSERVER
#ifndef EVSERVER
if (server) GetLogLock();
#endif
#endif
if (channel == BADSCRIPTLOG || channel == BUGLOG)
{
if (!strnicmp(logmainbuffer,"FATAL",5)){;} // log fatalities anyway
else if (channel == BUGLOG && server && !serverLog) return id; // not logging server data
bugLog = true;
char name[MAX_WORD_SIZE];
sprintf(name,(char*)"%s/bugs.txt",logs);
FILE* bug = rotateLogOnLimit(name,logs);
char located[MAX_WORD_SIZE];
*located = 0;
if (currentTopicID && currentRule) sprintf(located,(char*)" script: %s.%d.%d",GetTopicName(currentTopicID),TOPLEVELID(currentRuleID),REJOINDERID(currentRuleID));
if (bug) // write to a bugs file
{
if (*currentFilename) fprintf(bug,(char*)"BUG in %s at %d: %s ",currentFilename,currentFileLine,readBuffer);
if (!compiling && !loading && channel == BUGLOG && *currentInput)
{
char* buffer = AllocateBuffer(); // transient - cannot insure not called from context of InfiniteStack
struct tm ptm;
if (buffer) fprintf(bug,(char*)"\r\nBUG: %s: input:%d %s caller:%s callee:%s at %s in sentence: %s\r\n",GetTimeInfo(&ptm,true),volleyCount, logmainbuffer,loginID,computerID,located,currentInput);
else fprintf(bug,(char*)"\r\nBUG: %s: input:%d %s caller:%s callee:%s at %s\r\n",GetTimeInfo(&ptm,true),volleyCount, logmainbuffer,loginID,computerID,located);
FreeBuffer();
}
fwrite(logmainbuffer,1,bufLen,bug);
fprintf(bug,(char*)"\r\n");
if (!compiling && !loading && !strstr(logmainbuffer, "No such bot"))
{
fprintf(bug,(char*)"MinReleaseStackGap %dMB MinHeapAvailable %dMB\r\n",maxReleaseStackGap/1000000,(int)(minHeapAvailable/1000000));
fprintf(bug,(char*)"MaxBuffers used %d of %d\r\n\r\n",maxBufferUsed,maxBufferLimit);
BugBacktrace(bug);
}
fclose(bug); // dont use FClose
}
if ((echo||localecho) && !silent && !server)
{
struct tm ptm;
if (*currentFilename) fprintf(stdout,(char*)"\r\n in %s at %d: %s\r\n ",currentFilename,currentFileLine,readBuffer);
else if (*currentInput) fprintf(stdout,(char*)"\r\n%d %s in sentence: %s \r\n ",volleyCount,GetTimeInfo(&ptm,true),currentInput);
}
strcat(logmainbuffer,(char*)"\r\n"); // end it
if (!strnicmp(logmainbuffer,"FATAL",5))
{
if (!compiling && !loading)
{
char fname[100];
sprintf(fname,(char*)"%s/exitlog.txt",logs);
FILE* out = FopenUTF8WriteAppend(fname);
if (out)
{
struct tm ptm;
fprintf(out,(char*)"\r\n%s: input:%s caller:%s callee:%s\r\n",GetTimeInfo(&ptm,true),currentInput,loginID,computerID);
BugBacktrace(bug);
fclose(out);
}
}
myexit(logmainbuffer); // log fatalities anyway
}
channel = STDUSERLOG; // use normal logging as well
}
if (server){} // dont echo onto server console
else if ((!noecho && (echo || localecho || trace & TRACE_ECHO) && channel == STDUSERLOG))
{
if (!debugOutput) fwrite(logmainbuffer, 1, bufLen, stdout);
else (*debugOutput)(logmainbuffer);
}
bool doserver = true;
FILE* out = NULL;
if (server && trace && !userLog) channel = SERVERLOG; // force traced server to go to server log since no user log
char fname[MAX_WORD_SIZE];
if (logFilename[0] != 0 && channel != SERVERLOG && channel != DBTIMELOG)
{
strcpy(fname, logFilename);
char defaultlogFilename[MAX_BUFFER_SIZE];
sprintf(defaultlogFilename,"%s/log%u.txt",logs,port); // DEFAULT LOG
if (strcmp(fname, defaultlogFilename) == 0){ // of log is default log i.t log<port>.txt
char holdBuffer[MAX_BUFFER_SIZE];
struct tm ptm;
sprintf(holdBuffer,"%s - %s", GetTimeInfo(&ptm),logmainbuffer);
strcpy(logmainbuffer, holdBuffer);
}
out = rotateLogOnLimit(fname,users);
}
else if(channel == DBTIMELOG) // do db log
{
strcpy(fname, dbTimeLogfileName); // one might speed up forked servers by having mutex per pid instead of one common one
out = rotateLogOnLimit(fname,logs);
}
else // do server log
{
strcpy(fname, serverLogfileName); // one might speed up forked servers by having mutex per pid instead of one common one
out = rotateLogOnLimit(fname, logs);
}
if (out)
{
if (doserver)
{
fwrite(logmainbuffer,1,bufLen,out);
struct tm ptm;
if (!bugLog);
else if (*currentFilename) fprintf(out,(char*)" in %s at %d: %s\r\n ",currentFilename,currentFileLine,readBuffer);
else if (*currentInput) fprintf(out,(char*)"%d %s in sentence: %s \r\n ",volleyCount,GetTimeInfo(&ptm,true),currentInput);
}
fclose(out); // dont use FClose
if (channel == SERVERLOG && echoServer) (*printer)((char*)"%s", logmainbuffer);
}
#ifndef DISCARDSERVER
if (testOutput && server) // command outputs
{
size_t len = strlen(testOutput);
if ((len + bufLen) < (maxBufferSize - SAFE_BUFFER_MARGIN)) strcat(testOutput, logmainbuffer);
}
#ifndef EVSERVER
if (server) ReleaseLogLock();
#endif
#endif
inLog = false;
return ++id;
}
|
[
"gowilcox@gmail.com"
] |
gowilcox@gmail.com
|
37946f97778410d451ff07d10f6c44977bd54897
|
293279d940b97ad5a2b98f27d2fe8368f7a7f50c
|
/gammaee/super_hadrons/src/Trkman/Class/TMCurlerMissingThirds.cc
|
d8605be672a7ebc4bac1da13bb2102813abf21a4
|
[] |
no_license
|
jpivarski-talks/1999-2006_gradschool-1
|
51a59a9d262a34d4d613d84bd6a78a0e2675db06
|
11abf09e8dc3b901627e9a7349d9c98bea250647
|
refs/heads/master
| 2022-11-19T12:16:19.477335
| 2020-07-25T01:18:29
| 2020-07-25T01:18:29
| 282,235,487
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,480
|
cc
|
// -*- C++ -*-
//
// Package: <package>
// Module: TMCurlerMissingThirds
//
// Description: <one line class summary>
//
// Implementation:
// <Notes on implementation>
//
// Author: Nadia Adam
// Created: Thu Sep 5 10:38:17 EDT 2002
// $Id: TMCurlerMissingThirds.cc,v 1.1 2002/11/04 18:31:30 nea9 Exp $
//
// Revision history
//
// $Log: TMCurlerMissingThirds.cc,v $
// Revision 1.1 2002/11/04 18:31:30 nea9
// New CleoIII Trkman
//
#include "Experiment/Experiment.h"
// system include files
// You may have to uncomment some of these or other stl headers
// depending on what other header files you include (e.g. FrameAccess etc.)!
//#include <string>
//#include <vector>
//#include <set>
//#include <map>
//#include <algorithm>
//#include <utility>
// user include files
//#include "Experiment/report.h"
#include "Trkman/TMCurlerMissingThirds.h"
#include "Navigation/NavTrack.h"
#include "MagField/MagneticField.h"
#define iout report( INFO, kFacilityString )
//
// constants, enums and typedefs
//
static const char* const kFacilityString = "Trkman.TMCurlerMissingThirds" ;
// ---- cvs-based strings (Id and Tag with which file was checked out)
static const char* const kIdString = "$Id: TMCurlerMissingThirds.cc,v 1.1 2002/11/04 18:31:30 nea9 Exp $";
static const char* const kTagString = "$Name: $";
static const double kPi = 3.1415926535898;
//
// constructors and destructor
//
TMCurlerMissingThirds::TMCurlerMissingThirds( NavTrackTable& theTracks,
TMData*& data,
TMClassification::TrackClassification& trackClass,
TMCurlers*& curlers )
{
m_theTracks = theTracks;
m_curlers = curlers;
m_curlerGroups = (*m_curlers).curlerGroupVector();
findMissingThirds( trackClass, data );
}
TMCurlerMissingThirds::~TMCurlerMissingThirds()
{
m_curlerGroups.clear();
}
//
// member functions
//
void TMCurlerMissingThirds::findMissingThirds( TMClassification::TrackClassification& trackClass,
TMData*& data)
{
//Loop over all the surviving curler track
//combinations, not including any tracks killed
//already.
for( int i=0; i<m_curlerGroups.size(); i++ )
{
//The cirle track for group i
int circleTrack = (*m_curlers).circleTrack( i );
if( trackClass[ circleTrack-1 ] == -201 )
{
double circleCurv = data->curvature( circleTrack-1 );
double circlePhi = data->phi( circleTrack-1 );
double circleSign = circleCurv/fabs(circleCurv);
NavTrackTable::const_iterator trkIt = m_theTracks.begin();
for( ; trkIt != m_theTracks.end(); trkIt++ )
{
int track = (*trkIt).identifier();
if( circleTrack != track )
{
if( trackClass[track-1] == 0 )
{
double trackCurv = data->curvature( track-1 );
double trackPhi = data->phi( track-1 );
DABoolean sameSign = false;
if( circleCurv*trackCurv > 0 )
{
sameSign = true;
}
if( !sameSign )
{
double delPhi;
delPhi = fabs( trackPhi - circlePhi );
if( delPhi > kPi )
{
delPhi = 2*kPi - delPhi;
}
double delR = fabs( data->rcImpact( circleTrack-1 )
- data->rcImpact( track-1 ) );
if( delPhi > 3.05 && delR < 0.05 &&
fabs( data->d0( track-1 ) ) < 0.002 )
{
trackClass[ track-1 ] = -250;
}
}
}
}
}
}
}
}
//
// const member functions
//
//
// static member functions
//
|
[
"jpivarski@gmail.com"
] |
jpivarski@gmail.com
|
921b3742ca413151f1a3cfe802a0cc894dfcc198
|
783ab8af3c349b1bb5c4a8385e7045f4eb0d4157
|
/src/qt/optionsdialog.cpp
|
64d876f030814974e1a550a14bf485676fb68e02
|
[
"MIT"
] |
permissive
|
qwanmic/jipcoin
|
62783fb2313f7d82192809723f87a47fd25274b4
|
f8b9d20e292dda80fc735938692ca038ac225eda
|
refs/heads/master
| 2020-03-21T05:43:04.414090
| 2018-06-22T08:56:40
| 2018-06-22T08:56:40
| 136,718,520
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,332
|
cpp
|
// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "optionsdialog.h"
#include "ui_optionsdialog.h"
#include "bitcoinunits.h"
#include "monitoreddatamapper.h"
#include "netbase.h"
#include "optionsmodel.h"
#include <QDir>
#include <QIntValidator>
#include <QLocale>
#include <QMessageBox>
OptionsDialog::OptionsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::OptionsDialog),
model(0),
mapper(0),
fRestartWarningDisplayed_Proxy(false),
fRestartWarningDisplayed_Lang(false),
fProxyIpValid(true)
{
ui->setupUi(this);
/* Network elements init */
#ifndef USE_UPNP
ui->mapPortUpnp->setEnabled(false);
#endif
ui->proxyIp->setEnabled(false);
ui->proxyPort->setEnabled(false);
ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));
ui->socksVersion->setEnabled(false);
ui->socksVersion->addItem("5", 5);
ui->socksVersion->addItem("4", 4);
ui->socksVersion->setCurrentIndex(0);
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy()));
ui->proxyIp->installEventFilter(this);
/* Window elements init */
#ifdef Q_OS_MAC
/* remove Window tab on Mac */
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow));
#endif
/* Display elements init */
QDir translations(":translations");
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
foreach(const QString &langStr, translations.entryList())
{
QLocale locale(langStr);
/** check if the locale name consists of 2 parts (language_country) */
if(langStr.contains("_"))
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
else
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language (locale name)", e.g. "German (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
}
ui->unit->setModel(new BitcoinUnits(this));
/* Widget-to-option mapper */
mapper = new MonitoredDataMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setOrientation(Qt::Vertical);
/* enable apply button when data modified */
connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton()));
/* disable apply button when new data loaded */
connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton()));
/* setup/change UI elements when proxy IP is invalid/valid */
connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool)));
}
OptionsDialog::~OptionsDialog()
{
delete ui;
}
void OptionsDialog::setModel(OptionsModel *model)
{
this->model = model;
if(model)
{
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
mapper->setModel(model);
setMapper();
mapper->toFirst();
}
/* update the display unit, to not use the default ("BTC") */
updateDisplayUnit();
/* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */
connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang()));
/* disable apply button after settings are loaded as there is nothing to save */
disableApplyButton();
}
void OptionsDialog::setMapper()
{
/* Main */
mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);
/* Wallet */
mapper->addMapping(ui->transactionFee, OptionsModel::Fee);
mapper->addMapping(ui->spendZeroConfChange, OptionsModel::SpendZeroConfChange);
/* Network */
mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);
mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);
mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);
mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);
mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion);
/* Window */
#ifndef Q_OS_MAC
mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);
mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);
#endif
/* Display */
mapper->addMapping(ui->lang, OptionsModel::Language);
mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);
mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses);
mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures);
}
void OptionsDialog::enableApplyButton()
{
ui->applyButton->setEnabled(true);
}
void OptionsDialog::disableApplyButton()
{
ui->applyButton->setEnabled(false);
}
void OptionsDialog::enableSaveButtons()
{
/* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */
if(fProxyIpValid)
setSaveButtonState(true);
}
void OptionsDialog::disableSaveButtons()
{
setSaveButtonState(false);
}
void OptionsDialog::setSaveButtonState(bool fState)
{
ui->applyButton->setEnabled(fState);
ui->okButton->setEnabled(fState);
}
void OptionsDialog::on_resetButton_clicked()
{
if(model)
{
// confirmation dialog
QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm options reset"),
tr("Some settings may require a client restart to take effect.") + "<br><br>" + tr("Do you want to proceed?"),
QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
if(btnRetVal == QMessageBox::Cancel)
return;
disableApplyButton();
/* disable restart warning messages display */
fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = true;
/* reset all options and save the default values (QSettings) */
model->Reset();
mapper->toFirst();
mapper->submit();
/* re-enable restart warning messages display */
fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = false;
}
}
void OptionsDialog::on_okButton_clicked()
{
mapper->submit();
accept();
}
void OptionsDialog::on_cancelButton_clicked()
{
reject();
}
void OptionsDialog::on_applyButton_clicked()
{
mapper->submit();
disableApplyButton();
}
void OptionsDialog::showRestartWarning_Proxy()
{
if(!fRestartWarningDisplayed_Proxy)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Jipcoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Proxy = true;
}
}
void OptionsDialog::showRestartWarning_Lang()
{
if(!fRestartWarningDisplayed_Lang)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Jipcoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Lang = true;
}
}
void OptionsDialog::updateDisplayUnit()
{
if(model)
{
/* Update transactionFee with the current unit */
ui->transactionFee->setDisplayUnit(model->getDisplayUnit());
}
}
void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState)
{
// this is used in a check before re-enabling the save buttons
fProxyIpValid = fState;
if(fProxyIpValid)
{
enableSaveButtons();
ui->statusLabel->clear();
}
else
{
disableSaveButtons();
object->setValid(fProxyIpValid);
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy address is invalid."));
}
}
bool OptionsDialog::eventFilter(QObject *object, QEvent *event)
{
if(event->type() == QEvent::FocusOut)
{
if(object == ui->proxyIp)
{
CService addr;
/* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */
emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr));
}
}
return QDialog::eventFilter(object, event);
}
|
[
"michael@ukm-alumni.org"
] |
michael@ukm-alumni.org
|
cd263e105405af307df13bb2eb7d49a65dd86ec9
|
49b878b65e9eb00232490243ccb9aea9760a4a6d
|
/components/sync/trusted_vault/standalone_trusted_vault_backend.h
|
dd2df4dc1c484d7178f102a20310bc6096c93637
|
[
"BSD-3-Clause"
] |
permissive
|
romanzes/chromium
|
5a46f234a233b3e113891a5d643a79667eaf2ffb
|
12893215d9efc3b0b4d427fc60f5369c6bf6b938
|
refs/heads/master
| 2022-12-28T00:20:03.524839
| 2020-10-08T21:01:52
| 2020-10-08T21:01:52
| 302,470,347
| 0
| 0
|
BSD-3-Clause
| 2020-10-08T22:10:22
| 2020-10-08T21:54:38
| null |
UTF-8
|
C++
| false
| false
| 5,838
|
h
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_SYNC_TRUSTED_VAULT_STANDALONE_TRUSTED_VAULT_BACKEND_H_
#define COMPONENTS_SYNC_TRUSTED_VAULT_STANDALONE_TRUSTED_VAULT_BACKEND_H_
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "base/callback.h"
#include "base/files/file_path.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "components/signin/public/identity_manager/account_info.h"
#include "components/sync/protocol/local_trusted_vault.pb.h"
#include "components/sync/trusted_vault/trusted_vault_connection.h"
namespace syncer {
// Provides interfaces to store/remove keys to/from file storage.
// This class performs expensive operations and expected to be run from
// dedicated sequence (using thread pool). Can be constructed on any thread/
// sequence.
class StandaloneTrustedVaultBackend
: public base::RefCountedThreadSafe<StandaloneTrustedVaultBackend> {
public:
using FetchKeysCallback = base::OnceCallback<void(
const std::vector<std::vector<uint8_t>>& vault_keys)>;
class Delegate {
public:
Delegate() = default;
Delegate(const Delegate&) = delete;
virtual ~Delegate() = default;
Delegate& operator=(const Delegate&) = delete;
virtual void NotifyRecoverabilityDegradedChanged() = 0;
};
StandaloneTrustedVaultBackend(
const base::FilePath& file_path,
std::unique_ptr<Delegate> delegate,
std::unique_ptr<TrustedVaultConnection> connection);
StandaloneTrustedVaultBackend(const StandaloneTrustedVaultBackend& other) =
delete;
StandaloneTrustedVaultBackend& operator=(
const StandaloneTrustedVaultBackend& other) = delete;
// Restores state saved in |file_path_|, should be called before using the
// object.
void ReadDataFromDisk();
// Populates vault keys corresponding to |account_info| into |callback|. If
// recent keys are locally available, |callback| will be called immediately.
// Otherwise, attempts to download new keys from the server. In case of
// failure or if current state isn't sufficient it will populate locally
// available keys regardless of their freshness.
// Concurrent calls are not supported.
void FetchKeys(const CoreAccountInfo& account_info,
FetchKeysCallback callback);
// Replaces keys for given |gaia_id| both in memory and in |file_path_|.
void StoreKeys(const std::string& gaia_id,
const std::vector<std::vector<uint8_t>>& keys,
int last_key_version);
// Marks vault keys as stale. Afterwards, the next FetchKeys() call for this
// |account_info| will trigger a key download attempt.
bool MarkKeysAsStale(const CoreAccountInfo& account_info);
// Removes all keys for all accounts from both memory and |file_path_|.
void RemoveAllStoredKeys();
// Sets/resets |primary_account_|.
void SetPrimaryAccount(
const base::Optional<CoreAccountInfo>& primary_account);
// Returns whether recoverability of the keys is degraded and user action is
// required to add a new method.
void GetIsRecoverabilityDegraded(const CoreAccountInfo& account_info,
base::OnceCallback<void(bool)> cb);
// Registers a new trusted recovery method that can be used to retrieve keys.
void AddTrustedRecoveryMethod(const std::string& gaia_id,
const std::vector<uint8_t>& public_key,
base::OnceClosure cb);
base::Optional<CoreAccountInfo> GetPrimaryAccountForTesting() const;
sync_pb::LocalDeviceRegistrationInfo GetDeviceRegistrationInfoForTesting(
const std::string& gaia_id);
void SetRecoverabilityDegradedForTesting();
void ResolveRecoverabilityDegradedForTesting();
private:
friend class base::RefCountedThreadSafe<StandaloneTrustedVaultBackend>;
~StandaloneTrustedVaultBackend();
// Finds the per-user vault in |data_| for |gaia_id|. Returns null if not
// found.
sync_pb::LocalTrustedVaultPerUser* FindUserVault(const std::string& gaia_id);
// Attempts to register device in case it's not yet registered and currently
// available local data is sufficient to do it.
void MaybeRegisterDevice(const std::string& gaia_id);
// Called when device registration for |gaia_id| is completed (either
// successfully or not).
void OnDeviceRegistered(const std::string& gaia_id,
TrustedVaultRequestStatus status);
void OnKeysDownloaded(const std::string& gaia_id,
TrustedVaultRequestStatus status,
const std::vector<std::vector<uint8_t>>& vault_keys,
int last_vault_key_version);
void AbandonConnectionRequest();
void FulfillOngoingFetchKeys();
const base::FilePath file_path_;
const std::unique_ptr<Delegate> delegate_;
// Used for communication with trusted vault server.
const std::unique_ptr<TrustedVaultConnection> connection_;
sync_pb::LocalTrustedVault data_;
// Only current |primary_account_| can be used for communication with trusted
// vault server.
base::Optional<CoreAccountInfo> primary_account_;
// Used to plumb FetchKeys() result to the caller.
FetchKeysCallback ongoing_fetch_keys_callback_;
// Account used in last FetchKeys() call.
base::Optional<std::string> ongoing_fetch_keys_gaia_id_;
bool is_recoverability_degraded_for_testing_ = false;
// Used for cancellation of callbacks passed to |connection_|.
base::WeakPtrFactory<StandaloneTrustedVaultBackend>
weak_factory_for_connection_{this};
};
} // namespace syncer
#endif // COMPONENTS_SYNC_TRUSTED_VAULT_STANDALONE_TRUSTED_VAULT_BACKEND_H_
|
[
"commit-bot@chromium.org"
] |
commit-bot@chromium.org
|
5e39045dec424513a4a088a741734fe4fea1b6a0
|
7f72c463d8747c05cf964e0ea4f896890b4a8b6c
|
/out/Release/obj/gen/deps/v8/src/objects/js-array-buffer-tq-csa.h
|
78fe041888fcca5ce010845fe20b0e1f4355c5e7
|
[
"CC0-1.0",
"LicenseRef-scancode-openssl",
"NTP",
"BSD-3-Clause",
"Artistic-2.0",
"Zlib",
"ICU",
"NAIST-2003",
"LicenseRef-scancode-unicode",
"ISC",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer"
] |
permissive
|
sdizdarevic/node-v14.15.4
|
5dc95efdd2dc83aa577930c0792755d2e25da238
|
ab3716c46ad34da8680ca48c2498e71d77838dfd
|
refs/heads/master
| 2023-03-09T00:46:54.316036
| 2021-02-21T10:19:33
| 2021-02-21T10:19:33
| 340,862,598
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,415
|
h
|
#ifndef V8_GEN_TORQUE_GENERATED_______DEPS_V8_SRC_OBJECTS_JS_ARRAY_BUFFER_TQ_H_
#define V8_GEN_TORQUE_GENERATED_______DEPS_V8_SRC_OBJECTS_JS_ARRAY_BUFFER_TQ_H_
#include "src/builtins/builtins-promise.h"
#include "src/compiler/code-assembler.h"
#include "src/codegen/code-stub-assembler.h"
#include "src/utils/utils.h"
#include "torque-generated/field-offsets-tq.h"
#include "torque-generated/csa-types-tq.h"
namespace v8 {
namespace internal {
TNode<BoolT> IsDetachedBuffer_0(compiler::CodeAssemblerState* state_, TNode<JSArrayBuffer> p_buffer);
TNode<BoolT> IsSharedArrayBuffer_0(compiler::CodeAssemblerState* state_, TNode<JSArrayBuffer> p_buffer);
TNode<JSArrayBuffer> LoadJSArrayBufferViewBuffer_0(compiler::CodeAssemblerState* state_, TNode<JSArrayBufferView> p_o);
void StoreJSArrayBufferViewBuffer_0(compiler::CodeAssemblerState* state_, TNode<JSArrayBufferView> p_o, TNode<JSArrayBuffer> p_v);
TNode<UintPtrT> LoadJSArrayBufferViewByteOffset_0(compiler::CodeAssemblerState* state_, TNode<JSArrayBufferView> p_o);
void StoreJSArrayBufferViewByteOffset_0(compiler::CodeAssemblerState* state_, TNode<JSArrayBufferView> p_o, TNode<UintPtrT> p_v);
TNode<UintPtrT> LoadJSArrayBufferViewByteLength_0(compiler::CodeAssemblerState* state_, TNode<JSArrayBufferView> p_o);
void StoreJSArrayBufferViewByteLength_0(compiler::CodeAssemblerState* state_, TNode<JSArrayBufferView> p_o, TNode<UintPtrT> p_v);
TNode<UintPtrT> LoadJSTypedArrayLength_0(compiler::CodeAssemblerState* state_, TNode<JSTypedArray> p_o);
void StoreJSTypedArrayLength_0(compiler::CodeAssemblerState* state_, TNode<JSTypedArray> p_o, TNode<UintPtrT> p_v);
TNode<ExternalPointerT> LoadJSTypedArrayExternalPointer_0(compiler::CodeAssemblerState* state_, TNode<JSTypedArray> p_o);
void StoreJSTypedArrayExternalPointer_0(compiler::CodeAssemblerState* state_, TNode<JSTypedArray> p_o, TNode<ExternalPointerT> p_v);
TNode<Object> LoadJSTypedArrayBasePointer_0(compiler::CodeAssemblerState* state_, TNode<JSTypedArray> p_o);
void StoreJSTypedArrayBasePointer_0(compiler::CodeAssemblerState* state_, TNode<JSTypedArray> p_o, TNode<Object> p_v);
TNode<UintPtrT> LoadJSArrayBufferByteLength_0(compiler::CodeAssemblerState* state_, TNode<JSArrayBuffer> p_o);
void StoreJSArrayBufferByteLength_0(compiler::CodeAssemblerState* state_, TNode<JSArrayBuffer> p_o, TNode<UintPtrT> p_v);
TNode<ExternalPointerT> LoadJSArrayBufferBackingStore_0(compiler::CodeAssemblerState* state_, TNode<JSArrayBuffer> p_o);
void StoreJSArrayBufferBackingStore_0(compiler::CodeAssemblerState* state_, TNode<JSArrayBuffer> p_o, TNode<ExternalPointerT> p_v);
TNode<RawPtrT> LoadJSArrayBufferExtension_0(compiler::CodeAssemblerState* state_, TNode<JSArrayBuffer> p_o);
void StoreJSArrayBufferExtension_0(compiler::CodeAssemblerState* state_, TNode<JSArrayBuffer> p_o, TNode<RawPtrT> p_v);
TNode<Uint32T> LoadJSArrayBufferBitField_0(compiler::CodeAssemblerState* state_, TNode<JSArrayBuffer> p_o);
void StoreJSArrayBufferBitField_0(compiler::CodeAssemblerState* state_, TNode<JSArrayBuffer> p_o, TNode<Uint32T> p_v);
TNode<ExternalPointerT> LoadJSDataViewDataPointer_0(compiler::CodeAssemblerState* state_, TNode<JSDataView> p_o);
void StoreJSDataViewDataPointer_0(compiler::CodeAssemblerState* state_, TNode<JSDataView> p_o, TNode<ExternalPointerT> p_v);
} // namespace internal
} // namespace v8
#endif // V8_GEN_TORQUE_GENERATED_______DEPS_V8_SRC_OBJECTS_JS_ARRAY_BUFFER_TQ_H_
|
[
"saudin.dizdarevic@gmail.com"
] |
saudin.dizdarevic@gmail.com
|
50a82443db367a5a23a899827716ce80feb95327
|
0dd9aaaf64ee65f2f8bec4484b1ca8f4517f54c4
|
/trunk/ViewController/UIComponent/DummyComponent.h
|
92749cb1735bf486c2812bceec0d1ebc9e0fd448
|
[] |
no_license
|
dumppool/mazerts
|
53c186bcf8f85c5f618f25464a0067f0b23abeb4
|
7ff775fad18111de8c85552e7bd4c0435b0faba8
|
refs/heads/master
| 2020-09-14T16:57:56.936388
| 2012-07-08T16:36:08
| 2012-07-08T16:36:08
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,251
|
h
|
/**
* Test-component
*
* $Revision$
* $Date$
* $Id$
*/
#ifndef __DUMMYCOMPONENT_H__
#define __DUMMYCOMPONENT_H__
#include "UIComponent.h"
#include "../App/ID3DApplication.h"
class DummyComponent : public UIComponent
{
public:
DummyComponent(const int posX, const int posY, const unsigned int w, const unsigned int h);
virtual ~DummyComponent()
{
}
enum TestMode
{
TESTMODE_NONE = 1,
TESTMODE_BOUNCER,
TESTMODE_TRANSPARENT_TOGGLER
};
virtual int processEvent(int eventFlag, TCHAR arg);
virtual void onRender(LPDIRECT3DDEVICE9 pDevice);
virtual void update(const float frameTime);
void setupTransparencyToggler()
{
m_Mode = TESTMODE_TRANSPARENT_TOGGLER;
}
void setupBouncer()
{
m_Mode = TESTMODE_BOUNCER;
}
private:
bool m_Bouncing;
ID3DApplication* m_App; // for testing text rendering.. this is not a good way though
TestMode m_Mode; // flags for testing functionality
// temporary moving values
int m_ModX;
int m_ModY;
// counter for moving speed
float downcounter;
float downcounterStep;
};
#endif // __DUMMYCOMPONENT_H__
|
[
"zemm@iki.fi"
] |
zemm@iki.fi
|
8208a476cfd711417bf5208e534a87716532c1b6
|
dcb75b10a352d9cfc0ae31f28679a2d56b10b875
|
/Source/Mordhau/MordhauShield.cpp
|
69a788ddb70422b80b66a5cc8e76f82a35ba4926
|
[] |
no_license
|
Net-Slayer/Mordhau_uSDK
|
df5a096c21eb43e910c9b90c69ece495384608e0
|
c4ff76b5d7462fc6ccad176bd8f1db2efdd2c910
|
refs/heads/master
| 2023-04-28T02:48:14.072100
| 2021-12-15T16:35:08
| 2021-12-15T16:35:08
| 301,417,546
| 3
| 1
| null | 2021-08-23T13:23:29
| 2020-10-05T13:26:39
|
C++
|
UTF-8
|
C++
| false
| false
| 111
|
cpp
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "MordhauShield.h"
|
[
"talon_hq@outlook.com"
] |
talon_hq@outlook.com
|
64e2822abb3ab9366a9067de3121eda2434cad43
|
1bf8b46afad5402fe6fa74293b464e1ca5ee5fd7
|
/SDK/BPF_PlayerCameraBase_parameters.h
|
f0c65148796302b72c109c0c54d2174a68cf0b24
|
[] |
no_license
|
LemonHaze420/ShenmueIIISDK
|
a4857eebefc7e66dba9f667efa43301c5efcdb62
|
47a433b5e94f171bbf5256e3ff4471dcec2c7d7e
|
refs/heads/master
| 2021-06-30T17:33:06.034662
| 2021-01-19T20:33:33
| 2021-01-19T20:33:33
| 214,824,713
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 864
|
h
|
#pragma once
#include "../SDK.h"
// Name: Shenmue3SDK, Version: 1.4.1
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function BPF_PlayerCameraBase.BPF_PlayerCameraBase_C.getS3PlayerCameraManagerBase
struct UBPF_PlayerCameraBase_C_getS3PlayerCameraManagerBase_Params
{
class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
class ABP_S3PlayerCameraManagerBase_C* BP_S3PlayerCameraManagerBase; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
[
"35783139+LemonHaze420@users.noreply.github.com"
] |
35783139+LemonHaze420@users.noreply.github.com
|
cc468e556ee7fb210f07df74f7e62f764ac6b3b8
|
112752e08475599b53441d1f5c600e129b5932c7
|
/modules/monitoring/src/cpu-addon/CPUInfo.cpp
|
2b42dc4b3ae705889bb15a5b7788409508871664
|
[
"Apache-2.0"
] |
permissive
|
ServantJS/servantjs-agent
|
4e017e76db7ed6818290b958c0ffb06b34050aa8
|
ac5c56ada1bd49b75d919fe742642faec9000a4e
|
refs/heads/master
| 2020-04-15T13:36:36.657360
| 2016-10-01T20:38:03
| 2016-10-01T20:38:03
| 57,215,579
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,446
|
cpp
|
#include "CPUInfo.hpp"
#ifdef __linux__
#include <fstream>
#endif
#ifdef __APPLE__
#include <mach/mach_host.h>
#include <mach/processor_info.h>
#endif
int CPUInfo::update() {
#ifdef __APPLE__
unsigned int cpu_count;
processor_cpu_load_info_t cpu_load;
mach_msg_type_number_t cpu_msg_count;
int rc = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &cpu_count,
(processor_info_array_t *) &cpu_load, &cpu_msg_count);
if (rc != 0) {
return rc;
}
for (unsigned int i = 0; i < cpu_count; i++) {
Ticks *ticks = new Ticks(
cpu_load[i].cpu_ticks[CPU_STATE_USER],
cpu_load[i].cpu_ticks[CPU_STATE_NICE],
cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM],
cpu_load[i].cpu_ticks[CPU_STATE_IDLE]
);
this->ticksList.push_back(ticks);
}
return 0;
#elif __linux__
long double a[4]; // 0 - user, 1 - nice, 2 - system, 4 - idle
std::ifstream in("/proc/stat");
if (!in) {
return 1002;
}
std::string line;
while (std::getline(in, line)) {
if (line.find("cpu") != std::string::npos && line.find("cpu ") == std::string::npos) {
std::sscanf(line.c_str(), "%*s %Lf %Lf %Lf %Lf",&a[0],&a[1],&a[2],&a[3]);
this->ticksList.push_back(new Ticks(a[0], a[1], a[2], a[3]));
}
}
in.close();
return 0;
#else
return 1;
#endif
}
|
[
"vitaliuorlov@gmail.com"
] |
vitaliuorlov@gmail.com
|
3c1dacff7f13b110d6d57ff2e07b3686e4db4808
|
f54054008a9ac3c1f7bf1c763f288f516b608f16
|
/thidau_BCTHIDAU.cpp
|
c0065024f91f8bc42a92395481c5016207218df6
|
[] |
no_license
|
KhanhKitin/spoj_ptit
|
f5d1dc6aea83cbe19731024fcaa2dd75fed0c448
|
0b3971db3a2f88b0451482060f0415ceef911dc6
|
refs/heads/master
| 2022-04-21T04:08:42.266755
| 2020-04-20T16:30:01
| 2020-04-20T16:30:01
| 257,340,618
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 711
|
cpp
|
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
int sobaiMax=-1;
int sodiemphatMin=0;
string nameMax;
int n;
cin>>n;
for(int i=1;i<=n;i++){
int s1,t1,s2,t2,s3,t3,s4,t4;
string k;
cin>>k;
cin>>s1>>t1>>s2>>t2>>s3>>t3>>s4>>t4;
int diem=0;
int d=0;
if(t1>0){
d++;
diem=diem+(s1-1)*20+t1;
}
if(t2>0){
d++;
diem=diem+(s2-1)*20+t2;
}
if(t3>0){
d++;
diem=diem+(s3-1)*20+t3;
}
if(t4>0){
d++;
diem=diem+(s4-1)*20+t4;
}
if(d>sobaiMax){
sobaiMax=d;
nameMax=k;
sodiemphatMin=diem;
}
if(d==sobaiMax){
if(diem<sodiemphatMin){
sodiemphatMin=diem;
nameMax=k;
}
}
}
cout<<nameMax<<" "<<sobaiMax<<" "<<sodiemphatMin;
}
|
[
"kitinkhanh@gmail.com"
] |
kitinkhanh@gmail.com
|
25f6e46f6f1bcade8d6699bb9570fecd6997f89b
|
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
|
/net-im/gloox/files/patch-src_examples_privacylist__example.cpp
|
83248b5e7bc7637eace1e53506b1bfc51c4f80ab
|
[
"BSD-2-Clause"
] |
permissive
|
freebsd/freebsd-ports
|
86f2e89d43913412c4f6b2be3e255bc0945eac12
|
605a2983f245ac63f5420e023e7dce56898ad801
|
refs/heads/main
| 2023-08-30T21:46:28.720924
| 2023-08-30T19:33:44
| 2023-08-30T19:33:44
| 1,803,961
| 916
| 918
|
NOASSERTION
| 2023-09-08T04:06:26
| 2011-05-26T11:15:35
| null |
UTF-8
|
C++
| false
| false
| 321
|
cpp
|
--- src/examples/privacylist_example.cpp.orig 2017-08-04 16:26:10 UTC
+++ src/examples/privacylist_example.cpp
@@ -17,8 +17,8 @@
#include "../privacymanager.h"
using namespace gloox;
-#include <stdio.h>
-#include <locale.h>
+#include <ctime>
+#include <clocale>
#include <string>
#include <cstdio> // [s]print[f]
|
[
"swills@FreeBSD.org"
] |
swills@FreeBSD.org
|
88ccc47b7d060918ffae1682d5bb10a7e75b7616
|
b4e9ff1b80ff022aaacdf2f863bc3a668898ce7f
|
/openfl/Bsvgpath/Export/macos/obj/src/lime/graphics/opengl/ext/QCOM_perfmon_global_mode.cpp
|
072e9becd27530a69de26bdfc60f024d5d568d9c
|
[
"MIT"
] |
permissive
|
TrilateralX/TrilateralSamples
|
c1aa206495cf6e1f4f249c87e49fa46d62544c24
|
9c9168c5c2fabed9222b47e738c67ec724b52aa6
|
refs/heads/master
| 2023-04-02T05:10:13.579952
| 2021-04-01T17:41:23
| 2021-04-01T17:41:23
| 272,706,707
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| true
| 3,818
|
cpp
|
// Generated by Haxe 4.2.0-rc.1+7dc565e63
#include <hxcpp.h>
#ifndef INCLUDED_lime_graphics_opengl_ext_QCOM_perfmon_global_mode
#include <lime/graphics/opengl/ext/QCOM_perfmon_global_mode.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_8723c151069cfd66_6_new,"lime.graphics.opengl.ext.QCOM_perfmon_global_mode","new",0x76e54308,"lime.graphics.opengl.ext.QCOM_perfmon_global_mode.new","lime/graphics/opengl/ext/QCOM_perfmon_global_mode.hx",6,0x1f188806)
namespace lime{
namespace graphics{
namespace opengl{
namespace ext{
void QCOM_perfmon_global_mode_obj::__construct(){
HX_STACKFRAME(&_hx_pos_8723c151069cfd66_6_new)
HXDLIN( 6) this->PERFMON_GLOBAL_MODE_QCOM = 36768;
}
Dynamic QCOM_perfmon_global_mode_obj::__CreateEmpty() { return new QCOM_perfmon_global_mode_obj; }
void *QCOM_perfmon_global_mode_obj::_hx_vtable = 0;
Dynamic QCOM_perfmon_global_mode_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< QCOM_perfmon_global_mode_obj > _hx_result = new QCOM_perfmon_global_mode_obj();
_hx_result->__construct();
return _hx_result;
}
bool QCOM_perfmon_global_mode_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x74dd6666;
}
QCOM_perfmon_global_mode_obj::QCOM_perfmon_global_mode_obj()
{
}
::hx::Val QCOM_perfmon_global_mode_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 24:
if (HX_FIELD_EQ(inName,"PERFMON_GLOBAL_MODE_QCOM") ) { return ::hx::Val( PERFMON_GLOBAL_MODE_QCOM ); }
}
return super::__Field(inName,inCallProp);
}
::hx::Val QCOM_perfmon_global_mode_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 24:
if (HX_FIELD_EQ(inName,"PERFMON_GLOBAL_MODE_QCOM") ) { PERFMON_GLOBAL_MODE_QCOM=inValue.Cast< int >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void QCOM_perfmon_global_mode_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("PERFMON_GLOBAL_MODE_QCOM",8c,4a,a5,e0));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo QCOM_perfmon_global_mode_obj_sMemberStorageInfo[] = {
{::hx::fsInt,(int)offsetof(QCOM_perfmon_global_mode_obj,PERFMON_GLOBAL_MODE_QCOM),HX_("PERFMON_GLOBAL_MODE_QCOM",8c,4a,a5,e0)},
{ ::hx::fsUnknown, 0, null()}
};
static ::hx::StaticInfo *QCOM_perfmon_global_mode_obj_sStaticStorageInfo = 0;
#endif
static ::String QCOM_perfmon_global_mode_obj_sMemberFields[] = {
HX_("PERFMON_GLOBAL_MODE_QCOM",8c,4a,a5,e0),
::String(null()) };
::hx::Class QCOM_perfmon_global_mode_obj::__mClass;
void QCOM_perfmon_global_mode_obj::__register()
{
QCOM_perfmon_global_mode_obj _hx_dummy;
QCOM_perfmon_global_mode_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("lime.graphics.opengl.ext.QCOM_perfmon_global_mode",16,5f,bd,79);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(QCOM_perfmon_global_mode_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< QCOM_perfmon_global_mode_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = QCOM_perfmon_global_mode_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = QCOM_perfmon_global_mode_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace lime
} // end namespace graphics
} // end namespace opengl
} // end namespace ext
|
[
"none"
] |
none
|
86914564f268885a76c49e045786638ed02c2807
|
e89efedb81ee399b04d5266cef71fb02074f9008
|
/spec/triangle_spec.cpp
|
e06ee3471d18e230ae3f2eda1a2e7afbaca65c25
|
[] |
no_license
|
ChrisLundquist/cs250
|
71cfb1fb57296aadcad66ab20b5103cbac489b59
|
52fe77c763dc2ec8e1e15802ce7120dbedefa71f
|
refs/heads/master
| 2020-05-31T00:40:53.555633
| 2012-09-27T08:56:21
| 2012-09-27T08:56:21
| 5,775,294
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,127
|
cpp
|
#include <gtest/gtest.h>
#include "../triangle.h"
static Color red() {
return Color(255, 0, 0);
}
static Color green() {
return Color(0, 255, 0);
}
static Color blue() {
return Color(0, 0, 255);
}
static Vertex vertex_a() {
return Vertex(Point(100, 0), red());
}
static Vertex vertex_b() {
return Vertex(Point(400, 100), green());
}
static Vertex vertex_c() {
return Vertex(Point(200, 300), blue());
}
static Triangle test_triangle() {
Vertex a = vertex_a();
Vertex b = vertex_b();
Vertex c = vertex_c();
return Triangle(a, b, c);
}
TEST(Triangle, Alpha) {
Triangle triangle = test_triangle();
Vertex a = vertex_a();
Vertex b = vertex_b();
Vertex c = vertex_c();
EXPECT_EQ(triangle.alpha(a.point), 1.0);
EXPECT_EQ(triangle.alpha(b.point), 0);
EXPECT_EQ(triangle.alpha(c.point), 0);
}
TEST(Triangle, Beta) {
Triangle triangle = test_triangle();
Vertex a = vertex_a();
Vertex b = vertex_b();
Vertex c = vertex_c();
EXPECT_EQ(triangle.beta(a.point), 0);
EXPECT_EQ(triangle.beta(b.point), 1.0);
EXPECT_EQ(triangle.beta(c.point), 0);
}
TEST(Triangle, Gamma) {
Triangle triangle = test_triangle();
Vertex a = vertex_a();
Vertex b = vertex_b();
Vertex c = vertex_c();
EXPECT_EQ(triangle.gamma(a.point), 0);
EXPECT_EQ(triangle.gamma(b.point), 0);
EXPECT_EQ(triangle.gamma(c.point), 1.0);
}
TEST(Triangle, DoesInclude) {
Triangle triangle = test_triangle();
Point good1 = Point(200, 200);
Point good2 = Point(200, 100);
Point good3 = Point(100, 0);
EXPECT_TRUE(triangle.includes(good1));
EXPECT_TRUE(triangle.includes(good2));
EXPECT_TRUE(triangle.includes(good3));
}
TEST(Triangle, DoesNotInclude) {
Triangle triangle = test_triangle();
Point bad1 = Point(200, 0);
Point bad2 = Point(100, 100);
Point bad3 = Point(400, 400);
Point bad4 = Point(300, 200);
EXPECT_FALSE(triangle.includes(bad1));
EXPECT_FALSE(triangle.includes(bad2));
EXPECT_FALSE(triangle.includes(bad3));
EXPECT_FALSE(triangle.includes(bad4));
}
TEST(Triangle, Interpolation) {
Triangle triangle = test_triangle();
Point red = triangle.a.point;
Point green = triangle.b.point;
Point blue = triangle.c.point;
EXPECT_EQ(triangle.calculate_pixel(red).color.r, 255);
EXPECT_EQ(triangle.calculate_pixel(red).color.g, 0);
EXPECT_EQ(triangle.calculate_pixel(red).color.b, 0);
EXPECT_EQ(triangle.calculate_pixel(green).color.r, 0);
EXPECT_EQ(triangle.calculate_pixel(green).color.g, 255);
EXPECT_EQ(triangle.calculate_pixel(green).color.b, 0);
EXPECT_EQ(triangle.calculate_pixel(blue).color.r, 0);
EXPECT_EQ(triangle.calculate_pixel(blue).color.g, 0);
EXPECT_EQ(triangle.calculate_pixel(blue).color.b, 255);
Point red_green = triangle.a.point + triangle.b.point;
red_green.x /= 2;
red_green.y /= 2;
EXPECT_EQ(triangle.calculate_pixel(red_green).color.r, 127);
EXPECT_EQ(triangle.calculate_pixel(red_green).color.g, 127);
EXPECT_EQ(triangle.calculate_pixel(red_green).color.b, 0);
}
|
[
"chris.lundquist@bluebox.net"
] |
chris.lundquist@bluebox.net
|
fb77aeb8494d9f61f5486e3664617337a29b646e
|
1a2577fc9cd16e2d0e9ffc26f0be2f4d6fe27339
|
/detection/Main.cpp
|
e574de624e121ae6e99d978f3e72c2f78982183e
|
[] |
no_license
|
fusion-research/SensorNetworkSimulator
|
52235fe3fcfc8149a531ebccb41c6af37b6a081d
|
4e66fc3a924d6a7de25ed740fa82dbb1325632a3
|
refs/heads/master
| 2021-09-09T11:37:22.821343
| 2018-03-15T18:50:12
| 2018-03-15T18:50:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,524
|
cpp
|
////////////////////////////////////////////////////////////////////////////////
// Main.cpp //
// //
// GLUI application to test ellipse-covering algorithm. //
////////////////////////////////////////////////////////////////////////////////
// Includes ////////////////////////////////////////////////////////////////////
#include <iostream.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <GL\glut.h>
#include <GL\glui.h>
#include "GVUtil.h"
#include "GVExposureSensorNetwork2D.h"
// Window Live Variable Initial Value Defines
// somelines are commented out and redefined in Lin's definitions
#define MAIN_OVERLAYEXPOSURE 1
#define MAIN_CENMINVALUE 0
#define MAIN_LOCMINVALUE 0
#define MAIN_MINSENSORS 1
#define MAIN_OUTPUTFILENAME "OutFile.txt"
#define MAIN_PAUSETIME 750
#define MAIN_MAXSENSORS 32767
#define MAIN_COLOROBJECT 0
#define MAIN_DRAW 1
#define MAIN_SIZE 0.025f
#define MAIN_MINRADIUS 0.0f
#define MAIN_MAXRADIUS 2.0f
#define MAIN_MINLENGTH 0.0f
#define MAIN_MAXLENGTH 1000.0f
#define MAIN_GRIDH 15
#define MAIN_GRIDV 15
// Miscellaneous
#define MAIN_WINDOWNAME "Ellipse Cover"
#define MAIN_CONTROLPANELNAME "Control Panel"
#define MAIN_ANGLEDELTA 3.0
// Lin's definition
#define MAIN_NUMSENSORS 5
#define MAIN_ALGORITHMMODE GVEXPOSURESENSORNETWORK2D_ALGORITHM_LOCAL
#define MAIN_ALGORITHMTYPE MAIN_TYPE_GPSR
#define MAIN_LOCMAXVALUE GVEXPOSURESENSORNETWORK2D_LOCMAXEXPOSUREMODE_GPSR
#define MAIN_CENMAXVALUE GVEXPOSURESENSORNETWORK2D_CENMAXEXPOSUREMODE_SHORTEST
#define MAIN_STARTX 0.25f
#define MAIN_STARTY 0.25f
#define MAIN_ENDX 0.75f
#define MAIN_ENDY 0.75f
#define MAIN_LENGTH 1.85f
#define MAIN_COMMUNICATIONRADIUS 0.90f
#define FILENAMELEN 20
#define MAIN_NUMEVENTS 5
#define MAIN_SPACE " "
// Global Variables ////////////////////////////////////////////////////////////
// Algorithm Objects
GVExposureSensorNetwork2D SensorNetwork; // Exposure Sensor Network
// Window Live Variables
int NumberOfSensors = MAIN_NUMSENSORS; // Number of Sensors
int NumberOfEvent = MAIN_NUMEVENTS;
char OutputFileName[FILENAMELEN] = MAIN_OUTPUTFILENAME; // Output File Name
float CommunicationRadius = MAIN_COMMUNICATIONRADIUS; // Communication Radius
float GLUIWindow_StartingPointX = MAIN_STARTX; // Starting Point X Coordinate
float GLUIWindow_StartingPointY = MAIN_STARTY; // Starting Point Y Coordinate
float GLUIWindow_EndingPointX = MAIN_ENDY; // Ending Point X Coordinate
float GLUIWindow_EndingPointY = MAIN_ENDY; // Ending Point Y Coordinate
int seed;
// Prototypes //////////////////////////////////////////////////////////////////
void Pause(int Milliseconds);
void OnNew(void);
int RunRouting(void);
void RunTraffic(void);
void RoutingResult(void);
// Lin's Functions
int RunDetection(void);
// Main ////////////////////////////////////////////////////////////////////////
int __cdecl main(int argc, char** argv)
/*
main() initializes the environment and calls the glutMainLoop() for OpenGL
drawing.
*/
{ // main
int j;
if(argc>1)
{
NumberOfSensors = atoi(argv[1]);
if(argc > 2)
NumberOfEvent = atoi(argv[2]);
if(argc > 3)
seed = atoi(argv[3]);
}
seed = time(NULL);
srand(seed);
j = 0;
while(j<30)
{
OnNew();
if(RunDetection())
j++;
SensorNetwork.Delete();
}
return 0;
} // main
void debugNetwork(void)
{
int SourceNodeIndex;
int DestinationNodeIndex;
SourceNodeIndex = rand()%(NumberOfSensors);
DestinationNodeIndex = rand()%(NumberOfSensors);
if(SourceNodeIndex != DestinationNodeIndex)
{
SensorNetwork.SetPathParameters(SensorNetwork.GetX(SourceNodeIndex), SensorNetwork.GetY(SourceNodeIndex), SensorNetwork.GetX(DestinationNodeIndex), SensorNetwork.GetY(DestinationNodeIndex));
if(RunRouting())
{
RoutingResult();
}
}
}
// Functions ///////////////////////////////////////////////////////////////////
void Pause(int Milliseconds)
/*
Pause() performs a busy-wait for the specified number of milliseconds.
*/
{ // Pause
int Start = clock(); // Starting Time
int End = clock(); // Ending Time
while ((((double) (End - Start)) * 1000.0 / CLOCKS_PER_SEC) < Milliseconds)
{
End = clock();
}
} // Pause
void OnNew(void)
/*
initilize the sensornetwork
*/
{ // OnNew
//SensorNetwork.New(NumberOfSensors, CommunicationRadius);
SensorNetwork.New(NumberOfSensors, CommunicationRadius);
} // OnNew
void RunTraffic(void)
{
int SourceNodeIndex;
int DestinationNodeIndex;
int i = 0;
while(i<1000)
{
SourceNodeIndex = rand()%(NumberOfSensors);
DestinationNodeIndex = rand()%(NumberOfSensors);
if(SourceNodeIndex != DestinationNodeIndex)
{
SensorNetwork.SetPathParameters(SensorNetwork.GetX(SourceNodeIndex), SensorNetwork.GetY(SourceNodeIndex), SensorNetwork.GetX(DestinationNodeIndex), SensorNetwork.GetY(DestinationNodeIndex));
if(RunRouting())
{
RoutingResult();
}
i++;
}
}
}
int RunDetection(void)
{
int i;
int j;
int ReturnVal = 1;
int CenterNodeIndex = 0;
int PathLength = 0;
double TotalEnergy[4] = {0.0};
double TransmitEnergy[4] = {0.0};
double ReceiveEnergy[4] = {0.0};
double ProcessEnergy[4] = {0.0};
double MonitorEnergy[4] = {0.0};
double DistanceSquareSum = 0.0;
double DistanceSum = 0.0;
double TotalCommDistance = 0.0;
double TotalCommDistanceSquare = 0.0;
SensorNetwork.GenerateEvent(NumberOfEvent);
for(i = 1; i< NumberOfSensors; i++)
{
SensorNetwork.SetPathParameters(SensorNetwork.GetX(i), SensorNetwork.GetY(i), SensorNetwork.GetX(CenterNodeIndex), SensorNetwork.GetY(CenterNodeIndex));
if(RunRouting())
{
DistanceSquareSum += SensorNetwork.GetDistanceSquareSum();
DistanceSum += SensorNetwork.GetDistanceSum();
PathLength += SensorNetwork.GetGPSRPathLength();
for(j=0;j<4;j++)
{
SensorNetwork.SetDetectionScheme(j);
SensorNetwork.DetectionInitialize();
SensorNetwork.DetectEvent();
TotalEnergy[j] += SensorNetwork.GetTotalEnergy();
TransmitEnergy[j] += SensorNetwork.GetTransmitEnergy();
ReceiveEnergy[j] += SensorNetwork.GetReceiveEnergy();
ProcessEnergy[j] += SensorNetwork.GetProcessEnergy();
MonitorEnergy[j] += SensorNetwork.GetMonitorEnergy();
}
}
else
{
ReturnVal = 0;
break;
//printf("Node %d (%.2f,%.2f) cannot reach the center(%.2f, %.2f) \n",i,SensorNetwork.GetX(i),SensorNetwork.GetY(i),SensorNetwork.GetX(CenterNodeIndex),SensorNetwork.GetY(CenterNodeIndex));
}
}
if(ReturnVal)
{
cout.width(6);
cout << setiosflags(ios::fixed | ios::showpoint) << setprecision(2);
for(j=0; j<4; j++)
{
cout.width(6);
cout << setiosflags(ios::fixed | ios::showpoint) << setprecision(2);
cout<< j << MAIN_SPACE
<< setw(4) << NumberOfSensors << MAIN_SPACE
<< setw(8) << PathLength << MAIN_SPACE
<< setw(8) << DistanceSum << MAIN_SPACE
<< setw(8) << DistanceSquareSum << MAIN_SPACE
<< setw(8) << TransmitEnergy[j] << MAIN_SPACE
<< setw(8) << ReceiveEnergy[j] << MAIN_SPACE
<< setw(8) << ProcessEnergy[j] << MAIN_SPACE
<< setw(8) << MonitorEnergy[j] << MAIN_SPACE
<< setw(8) << TotalEnergy[j] << MAIN_SPACE
<< endl;
}
}
return ReturnVal;
}
int RunRouting()
/*
Run() occurs when the user presses the Run button.
*/
{ // Run
int KeepGoing = 1; // Keep Running The Algorithm
int ReturnVal = 0;
while(KeepGoing == 1)
{
KeepGoing = SensorNetwork.GPSR_Run();
}
if (KeepGoing == 0)
{
ReturnVal = 1;
//cout << "Routing Finished"<< endl;
}
else if(KeepGoing == 2) //failed to deliver
{
//cout << "Routing Failed to deliver"<< endl;
}
return ReturnVal;
} // OnRun
void RoutingResult(void)
{
SensorNetwork.GPSR_OutputResults(OutputFileName);
}
|
[
"apeforest@gmail.com"
] |
apeforest@gmail.com
|
29ad458d5f4622f89ac1c256ee66f96b00350d11
|
ad0f9b4a69984f2e2cb948e2ed51b9eebc66f34a
|
/include/RenderBoy/Material.hpp
|
2ec75e9b2e06af4fb25fa30b1995d09c07299dc4
|
[] |
no_license
|
ukabuer/RenderBoy
|
73dd2aa36ead626318016416d113ade55f04121c
|
d60170c896a630babc77ccb78daa6297fd0a4766
|
refs/heads/master
| 2022-06-17T23:03:45.647611
| 2020-05-11T07:25:18
| 2020-05-11T07:25:18
| 201,276,619
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 380
|
hpp
|
#pragma once
#include <RenderBoy/Texture.hpp>
#include <array>
#include <memory>
namespace RB {
struct Material {
std::array<float, 4> base_color = {0.0f, 0.0f, 0.0f, 0.0f};
float AlphaCutoff = 1.0f;
float metallic = 1.0f;
float roughness = 1.0f;
std::array<float, 4> emissive = {1.0f, 1.0f, 1.0f, 1.0f};
Texture *base_color_texture = nullptr;
};
} // namespace RB
|
[
"ukabuer@live.com"
] |
ukabuer@live.com
|
d506c6c52a76577f7905a0257ad38e3c4fff240c
|
597f8a01ba9e6bb53fd8c481a9adbe5f97e8414f
|
/Assignment3/Client/include/Keyboard.h
|
d2fe301b463c7b14f1bcc7f532b507091e004e34
|
[] |
no_license
|
segevngr/Systems_Programming
|
20b6574b0c4fbf3ff7d9b06aa3a6721188705efa
|
fb54d2218a850538aebf83c7802529feeeebdf7a
|
refs/heads/master
| 2022-11-25T05:51:37.969849
| 2020-08-06T14:31:52
| 2020-08-06T14:31:52
| 285,593,688
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 383
|
h
|
#ifndef ASSIGNMENT3CLIENT_KEYBOARD_H
#define ASSIGNMENT3CLIENT_KEYBOARD_H
#include "connectionHandler.h"
using namespace std;
class Keyboard {
private:
ConnectionHandler* handler;
User *user;
bool* online;
bool waitForInput;
public:
Keyboard(ConnectionHandler *handler, User *user, bool *online);
void run();
};
#endif //ASSIGNMENT3CLIENT_KEYBOARD_H
|
[
"segevngr@gmail.com"
] |
segevngr@gmail.com
|
11e4eeed246dbd97d1460c67b83ad1f8c2993eae
|
ca7b94c3fc51f8db66ab41b32ee0b7a9ebd9c1ab
|
/grpc/include/grpc++/impl/server_initializer.h
|
014b16077c4a7631e10714d3741085141e91956a
|
[] |
no_license
|
blockspacer/TronWallet
|
9235b933b67de92cd06ca917382de8c69f53ce5a
|
ffc60e550d1aff5f0f6f1153e0fcde212d37bdc6
|
refs/heads/master
| 2021-09-15T15:17:47.632925
| 2018-06-05T14:28:16
| 2018-06-05T14:28:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,408
|
h
|
/*
*
* Copyright 2016 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef GRPCXX_IMPL_SERVER_INITIALIZER_H
#define GRPCXX_IMPL_SERVER_INITIALIZER_H
#include <memory>
#include <vector>
#include <grpc++/server.h>
namespace grpc {
class Server;
class Service;
class ServerInitializer {
public:
ServerInitializer(Server* server) : server_(server) {}
bool RegisterService(std::shared_ptr<Service> service) {
if (!server_->RegisterService(nullptr, service.get())) {
return false;
}
default_services_.push_back(service);
return true;
}
const std::vector<grpc::string>* GetServiceList() {
return &server_->services_;
}
private:
Server* server_;
std::vector<std::shared_ptr<Service> > default_services_;
};
} // namespace grpc
#endif // GRPCXX_IMPL_SERVER_INITIALIZER_H
|
[
"abce@live.cn"
] |
abce@live.cn
|
d7bb3a0718ca26cd73ae50633b1a3ae37d403ea8
|
c6b483cc2d7bc9eb6dc5c08ae92aa55ff9b3a994
|
/hazelcast/generated-sources/src/hazelcast/client/protocol/codec/TransactionalMapRemoveCodec.cpp
|
d95bb5f9372986a3f3c9e197485109b946f91c54
|
[
"Apache-2.0"
] |
permissive
|
oguzdemir/hazelcast-cpp-client
|
ebffc7137a3a14b9fc5d96e1a1b0eac8aac1e60f
|
95c4687634a8ac4886d0a9b9b4c17622225261f0
|
refs/heads/master
| 2021-01-21T02:53:05.197319
| 2016-08-24T21:08:14
| 2016-08-24T21:08:14
| 63,674,978
| 0
| 0
| null | 2016-07-19T08:16:24
| 2016-07-19T08:16:23
| null |
UTF-8
|
C++
| false
| false
| 4,164
|
cpp
|
/*
* Copyright (c) 2008-2015, Hazelcast, Inc. 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 "hazelcast/client/protocol/codec/TransactionalMapRemoveCodec.h"
#include "hazelcast/client/exception/UnexpectedMessageTypeException.h"
#include "hazelcast/client/serialization/pimpl/Data.h"
namespace hazelcast {
namespace client {
namespace protocol {
namespace codec {
const TransactionalMapMessageType TransactionalMapRemoveCodec::RequestParameters::TYPE = HZ_TRANSACTIONALMAP_REMOVE;
const bool TransactionalMapRemoveCodec::RequestParameters::RETRYABLE = false;
const int32_t TransactionalMapRemoveCodec::ResponseParameters::TYPE = 105;
std::auto_ptr<ClientMessage> TransactionalMapRemoveCodec::RequestParameters::encode(
const std::string &name,
const std::string &txnId,
int64_t threadId,
const serialization::pimpl::Data &key) {
int32_t requiredDataSize = calculateDataSize(name, txnId, threadId, key);
std::auto_ptr<ClientMessage> clientMessage = ClientMessage::createForEncode(requiredDataSize);
clientMessage->setMessageType((uint16_t)TransactionalMapRemoveCodec::RequestParameters::TYPE);
clientMessage->setRetryable(RETRYABLE);
clientMessage->set(name);
clientMessage->set(txnId);
clientMessage->set(threadId);
clientMessage->set(key);
clientMessage->updateFrameLength();
return clientMessage;
}
int32_t TransactionalMapRemoveCodec::RequestParameters::calculateDataSize(
const std::string &name,
const std::string &txnId,
int64_t threadId,
const serialization::pimpl::Data &key) {
int32_t dataSize = ClientMessage::HEADER_SIZE;
dataSize += ClientMessage::calculateDataSize(name);
dataSize += ClientMessage::calculateDataSize(txnId);
dataSize += ClientMessage::calculateDataSize(threadId);
dataSize += ClientMessage::calculateDataSize(key);
return dataSize;
}
TransactionalMapRemoveCodec::ResponseParameters::ResponseParameters(ClientMessage &clientMessage) {
if (TYPE != clientMessage.getMessageType()) {
throw exception::UnexpectedMessageTypeException("TransactionalMapRemoveCodec::ResponseParameters::decode", clientMessage.getMessageType(), TYPE);
}
response = clientMessage.getNullable<serialization::pimpl::Data >();
}
TransactionalMapRemoveCodec::ResponseParameters TransactionalMapRemoveCodec::ResponseParameters::decode(ClientMessage &clientMessage) {
return TransactionalMapRemoveCodec::ResponseParameters(clientMessage);
}
TransactionalMapRemoveCodec::ResponseParameters::ResponseParameters(const TransactionalMapRemoveCodec::ResponseParameters &rhs) {
response = std::auto_ptr<serialization::pimpl::Data>(new serialization::pimpl::Data(*rhs.response));
}
//************************ EVENTS END **************************************************************************//
}
}
}
}
|
[
"ihsan@hazelcast.com"
] |
ihsan@hazelcast.com
|
077c20d6d440e69a8e08e57d1e21becc00ea6926
|
f6ab96101246c8764dc16073cbea72a188a0dc1a
|
/volume131/13194 - DPA Numbers II.cpp
|
3de11837343867f5fc0d791c97afc178e8cceec0
|
[] |
no_license
|
nealwu/UVa
|
c87ddc8a0bf07a9bd9cadbf88b7389790bc321cb
|
10ddd83a00271b0c9c259506aa17d03075850f60
|
refs/heads/master
| 2020-09-07T18:52:19.352699
| 2019-05-01T09:41:55
| 2019-05-01T09:41:55
| 220,883,015
| 3
| 2
| null | 2019-11-11T02:14:54
| 2019-11-11T02:14:54
| null |
UTF-8
|
C++
| false
| false
| 1,120
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
int P[100000], Pt = 0;
void sieve() {
#define MAXL (1000000>>5)+1
#define GET(x) (mark[x>>5]>>(x&31)&1)
#define SET(x) (mark[x>>5] |= 1<<(x&31))
static int mark[MAXL] = {};
SET(1);
int n = 1000000;
for (int i = 2; i <= n; i++) {
if (!GET(i)) {
for (int k = n/i, j = i*k; k >= i; k--, j -= i)
SET(j);
P[Pt++] = i;
}
}
}
int main() {
sieve();
int testcase;
scanf("%d", &testcase);
while (testcase--) {
int64_t n, m;
scanf("%lld", &n);
m = n;
int64_t ret = 1;
for (int i = 0; i < Pt && P[i]*P[i] <= m; i++) {
if (m%P[i])
continue;
int64_t p = P[i];
int64_t s = p;
while (m%p == 0)
m /= p, s *= p;
ret *= (s-1) / (p-1);
if (ret > 2*n)
break;
}
if (m != 1)
ret *= m+1;
if (ret == 2*n)
puts("perfect");
else if (ret < 2*n)
puts("deficient");
else
puts("abundant");
// printf("%lld\n", ret);
}
return 0;
}
/*
9
999900007063
934053120000
999900003719
349621272000
560431872000
999900001643
999900003863
539630239744
137438691328
*/
|
[
"morris821028@gmail.com"
] |
morris821028@gmail.com
|
084d16896b9ba955277be71e7a02f21e579bac07
|
04c45c420d6a0aae7214173b43c2bd637422929a
|
/Creational/singleton/di.hpp
|
e8d38c899cb8f31cb52ed0f1a9242a205036eb06
|
[] |
no_license
|
vikyslenator/cpp_design_patterns
|
cc2b713a6ce09e16afcd7fb3a30dec06280a6999
|
6c6f9ccb92f2246234f09e0c41914a60fb472941
|
refs/heads/master
| 2023-06-07T16:08:15.790427
| 2020-11-03T01:53:41
| 2020-11-03T01:53:41
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 145,693
|
hpp
|
//
// Copyright (c) 2012-2020 Kris Jusiak (kris at jusiak dot net)
//
// 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
#if (__cplusplus < 201305L && _MSC_VER < 1900)
#error \
"[Boost::ext].DI requires C++14 support (Clang-3.4+, GCC-5.1+, MSVC-2015+)"
#else
#define BOOST_DI_VERSION 1'2'0
#define BOOST_DI_NAMESPACE_BEGIN \
namespace boost { \
inline namespace ext { \
namespace di { \
inline namespace v1_2_0 {
#define BOOST_DI_NAMESPACE_END \
} \
} \
} \
}
#if !defined(BOOST_DI_CFG_DIAGNOSTICS_LEVEL)
#define BOOST_DI_CFG_DIAGNOSTICS_LEVEL 1
#endif
#if defined(BOOST_DI_CFG_FWD)
BOOST_DI_CFG_FWD
#endif
#define __BOOST_DI_COMPILER(arg, ...) __BOOST_DI_COMPILER_IMPL(arg, __VA_ARGS__)
#define __BOOST_DI_COMPILER_IMPL(arg, ...) arg##__VA_ARGS__
#if defined(__clang__)
#define __CLANG__ __BOOST_DI_COMPILER(__clang_major__, __clang_minor__)
#define __BOOST_DI_UNUSED __attribute__((unused))
#define __BOOST_DI_DEPRECATED(...) [[deprecated(__VA_ARGS__)]]
#define __BOOST_DI_TYPE_WKND(T)
#define __BOOST_DI_ACCESS_WKND private
#define __BOOST_DI_VARIABLE_TEMPLATE_INIT_WKND \
{}
#elif defined(__GNUC__)
#define __GCC__
#define __BOOST_DI_UNUSED __attribute__((unused))
#define __BOOST_DI_DEPRECATED(...) [[deprecated(__VA_ARGS__)]]
#define __BOOST_DI_TYPE_WKND(T)
#define __BOOST_DI_ACCESS_WKND private
#define __BOOST_DI_VARIABLE_TEMPLATE_INIT_WKND \
{}
#elif defined(_MSC_VER)
#define __MSVC__
#if !defined(__has_include)
#define __has_include(...) 0
#endif
#define __BOOST_DI_UNUSED
#define __BOOST_DI_DEPRECATED(...) __declspec(deprecated(__VA_ARGS__))
#define __BOOST_DI_TYPE_WKND(T) (T &&)
#define __BOOST_DI_ACCESS_WKND public
#define __BOOST_DI_VARIABLE_TEMPLATE_INIT_WKND
#endif
#if !defined(__has_builtin)
#define __has_builtin(...) 0
#endif
#if !defined(__has_extension)
#define __has_extension(...) 0
#endif
#if defined(__CLANG__)
#if (!BOOST_DI_CFG_DIAGNOSTICS_LEVEL)
#pragma clang diagnostic error "-Wdeprecated-declarations"
#else
#pragma clang diagnostic warning "-Wdeprecated-declarations"
#endif
#pragma clang diagnostic push
#pragma clang diagnostic error "-Wundefined-inline"
#pragma clang diagnostic error "-Wundefined-internal"
#pragma clang diagnostic ignored "-Wmissing-field-initializers"
#elif defined(__GCC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic error "-Wdeprecated-declarations"
#if (__GNUC__ < 6)
#pragma GCC diagnostic error "-Werror"
#endif
#elif defined(__MSVC__)
#pragma warning(disable : 4503)
#pragma warning(disable : 4822)
#pragma warning(disable : 4505)
#endif
#if defined(_LIBCPP_VERSION)
#define NAMESPACE_STD_BEGIN _LIBCPP_BEGIN_NAMESPACE_STD {
#else
#define NAMESPACE_STD_BEGIN namespace std {
#endif
#if defined(_LIBCPP_VERSION)
#define NAMESPACE_STD_END _LIBCPP_END_NAMESPACE_STD
#else
#define NAMESPACE_STD_END }
#endif
#if __has_include(<__config>)
#include <__config>
#endif
#if __has_include(<memory>)
#include <memory>
#else
NAMESPACE_STD_BEGIN
template <class> class shared_ptr;
template <class> class weak_ptr;
template <class, class> class unique_ptr;
NAMESPACE_STD_END
#endif
#if __has_include(<vector>)
#include <vector>
#else
NAMESPACE_STD_BEGIN
template <class, class> class vector;
NAMESPACE_STD_END
#endif
#if __has_include(<set>)
#include <set>
#else
NAMESPACE_STD_BEGIN
template <class, class, class> class set;
NAMESPACE_STD_END
#endif
#if __has_include(<initializer_list>)
#include <initializer_list>
#else
NAMESPACE_STD_BEGIN
template <class> class initializer_list;
NAMESPACE_STD_END
#endif
#if __has_include(<tuple>)
#include <tuple>
#else
NAMESPACE_STD_BEGIN
template <class...> class tuple;
NAMESPACE_STD_END
#endif
#if __has_include(<iterator>)
#include <iterator>
#else
NAMESPACE_STD_BEGIN
template <class> class move_iterator;
NAMESPACE_STD_END
#endif
#if __has_include(<string>)
#include <string>
#else
NAMESPACE_STD_BEGIN
template <class> struct char_traits;
NAMESPACE_STD_END
#endif
// clang-format off
#if __has_include(<boost/shared_ptr.hpp>)
// clang-format on
#include <boost/shared_ptr.hpp>
#else
namespace boost {
template <class> class shared_ptr;
}
#endif
BOOST_DI_NAMESPACE_BEGIN
struct _ {
_(...) {}
};
namespace aux {
using swallow = int[];
template <class T> using owner = T;
template <class...> struct valid { using type = int; };
template <class... Ts> using valid_t = typename valid<Ts...>::type;
template <class...> struct type {};
struct none_type {};
template <class T, T> struct non_type {};
template <class...> struct always { static constexpr auto value = true; };
template <class...> struct never { static constexpr auto value = false; };
template <class T, class...> struct identity { using type = T; };
template <class...> struct type_list { using type = type_list; };
template <bool...> struct bool_list { using type = bool_list; };
template <class T1, class T2> struct pair {
using type = pair;
using first = T1;
using second = T2;
};
template <class... Ts> struct inherit : Ts... { using type = inherit; };
template <class... Ts> struct join { using type = type_list<>; };
template <class T> struct join<T> { using type = T; };
template <class... T1s, class... T2s, class... Ts>
struct join<type_list<T1s...>, type_list<T2s...>, Ts...>
: join<type_list<T1s..., T2s...>, Ts...> {};
template <class... Ts, class... T1s, class... T2s, class... T3s, class... T4s,
class... T5s, class... T6s, class... T7s, class... T8s, class... T9s,
class... T10s, class... T11s, class... T12s, class... T13s,
class... T14s, class... T15s, class... T16s, class... Us>
struct join<type_list<Ts...>, type_list<T1s...>, type_list<T2s...>,
type_list<T3s...>, type_list<T4s...>, type_list<T5s...>,
type_list<T6s...>, type_list<T7s...>, type_list<T8s...>,
type_list<T9s...>, type_list<T10s...>, type_list<T11s...>,
type_list<T12s...>, type_list<T13s...>, type_list<T14s...>,
type_list<T15s...>, type_list<T16s...>, Us...>
: join<type_list<Ts..., T1s..., T2s..., T3s..., T4s..., T5s..., T6s...,
T7s..., T8s..., T9s..., T10s..., T11s..., T12s..., T13s...,
T14s..., T15s..., T16s...>,
Us...> {};
template <class... TArgs> using join_t = typename join<TArgs...>::type;
template <int...> struct index_sequence { using type = index_sequence; };
#if defined(__cpp_lib_integer_sequence) && defined(__GNUC__)
template <int... Ns>
index_sequence<Ns...> from_std(std::integer_sequence<int, Ns...>) {
return {};
}
template <int N>
using make_index_sequence =
decltype(from_std(std::make_integer_sequence<int, N>{}));
#else
#if __has_builtin(__make_integer_seq)
template <class T, T...> struct integer_sequence;
template <int... Ns> struct integer_sequence<int, Ns...> {
using type = index_sequence<Ns...>;
};
template <int N> struct make_index_sequence_impl {
using type = typename __make_integer_seq<integer_sequence, int, N>::type;
};
#else
template <int> struct make_index_sequence_impl;
template <> struct make_index_sequence_impl<0> : index_sequence<> {};
template <> struct make_index_sequence_impl<1> : index_sequence<0> {};
template <> struct make_index_sequence_impl<2> : index_sequence<0, 1> {};
template <> struct make_index_sequence_impl<3> : index_sequence<0, 1, 2> {};
template <> struct make_index_sequence_impl<4> : index_sequence<0, 1, 2, 3> {};
template <>
struct make_index_sequence_impl<5> : index_sequence<0, 1, 2, 3, 4> {};
template <>
struct make_index_sequence_impl<6> : index_sequence<0, 1, 2, 3, 4, 5> {};
template <>
struct make_index_sequence_impl<7> : index_sequence<0, 1, 2, 3, 4, 5, 6> {};
template <>
struct make_index_sequence_impl<8> : index_sequence<0, 1, 2, 3, 4, 5, 6, 7> {};
template <>
struct make_index_sequence_impl<9> : index_sequence<0, 1, 2, 3, 4, 5, 6, 7, 8> {
};
template <>
struct make_index_sequence_impl<10>
: index_sequence<0, 1, 2, 3, 4, 5, 6, 7, 8, 9> {};
#endif
template <int N>
using make_index_sequence = typename make_index_sequence_impl<N>::type;
#endif
} // namespace aux
namespace placeholders {
__BOOST_DI_UNUSED static const struct arg { } _{}; } // namespace placeholders
template <class, class = void> struct named {};
struct no_name {
constexpr auto operator()() const noexcept { return ""; }
};
template <class, class = int> struct ctor_traits;
template <class> struct self {};
struct ignore_policies {};
namespace core {
template <class> struct any_type_fwd;
template <class> struct any_type_ref_fwd;
template <class> struct any_type_1st_fwd;
template <class> struct any_type_1st_ref_fwd;
struct dependency_base {};
struct injector_base {};
template <class T> struct dependency__ : T {
using T::create;
using T::is_referable;
using T::try_create;
};
template <class T> struct injector__ : T {
using T::cfg;
using T::create_impl;
using T::create_successful_impl;
#if defined(__MSVC__)
template <class... Ts>
using is_creatable = typename T::template is_creatable<Ts...>;
template <class... Ts>
using try_create = typename T::template try_create<Ts...>;
#else
using T::is_creatable;
using T::try_create;
#endif
};
template <class, class...> struct array;
struct deduced {};
struct none {};
template <class, class TExpected = deduced, class = TExpected, class = no_name,
class = void, class = none>
class dependency;
} // namespace core
namespace scopes {
class deduce;
class instance;
class singleton;
class unique;
} // namespace scopes
#define __BOOST_DI_REQUIRES(...) \
typename ::boost::ext::di::v1_2_0::aux::enable_if<__VA_ARGS__, int>::type
#define __BOOST_DI_REQUIRES_MSG(...) \
typename ::boost::ext::di::v1_2_0::aux::concept_check<__VA_ARGS__>::type
namespace aux {
template <class T> T &&declval();
template <class T, T V> struct integral_constant {
using type = integral_constant;
static constexpr T value = V;
};
using true_type = integral_constant<bool, true>;
using false_type = integral_constant<bool, false>;
template <bool B, class T, class F> struct conditional { using type = T; };
template <class T, class F> struct conditional<false, T, F> { using type = F; };
template <bool B, class T, class F>
using conditional_t = typename conditional<B, T, F>::type;
template <bool B, class T = void> struct enable_if {};
template <class T> struct enable_if<true, T> { using type = T; };
template <bool B, class T = void>
using enable_if_t = typename enable_if<B, T>::type;
template <class T> struct concept_check {
static_assert(T::value, "constraint not satisfied");
};
template <> struct concept_check<true_type> { using type = int; };
template <class T> struct remove_reference { using type = T; };
template <class T> struct remove_reference<T &> { using type = T; };
template <class T> struct remove_reference<T &&> { using type = T; };
template <class T>
using remove_reference_t = typename remove_reference<T>::type;
template <class T> struct remove_pointer { using type = T; };
template <class T> struct remove_pointer<T *> { using type = T; };
template <class T> using remove_pointer_t = typename remove_pointer<T>::type;
template <class T> struct remove_smart_ptr { using type = T; };
template <class T, class TDeleter>
struct remove_smart_ptr<std::unique_ptr<T, TDeleter>> {
using type = T;
};
template <class T> struct remove_smart_ptr<std::shared_ptr<T>> {
using type = T;
};
template <class T> struct remove_smart_ptr<std::weak_ptr<T>> {
using type = T;
};
template <class T> struct remove_smart_ptr<boost::shared_ptr<T>> {
using type = T;
};
template <class T>
using remove_smart_ptr_t = typename remove_smart_ptr<T>::type;
template <class T> struct remove_qualifiers { using type = T; };
template <class T> struct remove_qualifiers<const T> { using type = T; };
template <class T> struct remove_qualifiers<T &> { using type = T; };
template <class T> struct remove_qualifiers<const T &> { using type = T; };
template <class T> struct remove_qualifiers<T *> { using type = T; };
template <class T> struct remove_qualifiers<const T *> { using type = T; };
template <class T> struct remove_qualifiers<T *const &> { using type = T; };
template <class T> struct remove_qualifiers<T *const> { using type = T; };
template <class T> struct remove_qualifiers<const T *const> { using type = T; };
template <class T> struct remove_qualifiers<T &&> { using type = T; };
template <class T>
using remove_qualifiers_t = typename remove_qualifiers<T>::type;
template <class T> struct remove_extent { using type = T; };
template <class T> struct remove_extent<T[]> { using type = T; };
template <class T> using remove_extent_t = typename remove_extent<T>::type;
template <class T> struct deref_type { using type = T; };
template <class T, class TDeleter>
struct deref_type<std::unique_ptr<T, TDeleter>> {
using type = remove_qualifiers_t<typename deref_type<T>::type>;
};
template <class T> struct deref_type<std::shared_ptr<T>> {
using type = remove_qualifiers_t<typename deref_type<T>::type>;
};
template <class T> struct deref_type<boost::shared_ptr<T>> {
using type = remove_qualifiers_t<typename deref_type<T>::type>;
};
template <class T> struct deref_type<std::weak_ptr<T>> {
using type = remove_qualifiers_t<typename deref_type<T>::type>;
};
template <class T, class TAllocator>
struct deref_type<std::vector<T, TAllocator>> {
using type = core::array<remove_qualifiers_t<typename deref_type<T>::type>>;
};
template <class TKey, class TCompare, class TAllocator>
struct deref_type<std::set<TKey, TCompare, TAllocator>> {
using type =
core::array<remove_qualifiers_t<typename deref_type<TKey>::type>>;
};
template <class T> struct deref_type<std::initializer_list<T>> {
using type = core::array<remove_qualifiers_t<typename deref_type<T>::type>>;
};
template <class T>
using decay_t = typename deref_type<remove_qualifiers_t<T>>::type;
template <class, class> struct is_same : false_type {};
template <class T> struct is_same<T, T> : true_type {};
template <class T, class U>
struct is_base_of : integral_constant<bool, __is_base_of(T, U)> {};
template <class T> struct is_class : integral_constant<bool, __is_class(T)> {};
template <class T>
struct is_abstract : integral_constant<bool, __is_abstract(T)> {};
template <class T>
struct is_polymorphic : integral_constant<bool, __is_polymorphic(T)> {};
template <class T> struct is_final : integral_constant<bool, __is_final(T)> {};
template <class...> using is_valid_expr = true_type;
#if __has_extension(is_constructible) && \
!((__clang_major__ == 3) && (__clang_minor__ == 5))
template <class T, class... TArgs>
using is_constructible =
integral_constant<bool, __is_constructible(T, TArgs...)>;
#else
template <class T, class... TArgs>
decltype(void(T(declval<TArgs>()...)), true_type{}) test_is_constructible(int);
template <class, class...> false_type test_is_constructible(...);
template <class T, class... TArgs>
struct is_constructible : decltype(test_is_constructible<T, TArgs...>(0)) {};
#endif
template <class T, class... TArgs>
using is_constructible_t = typename is_constructible<T, TArgs...>::type;
template <class T, class... TArgs>
decltype(void(T{declval<TArgs>()...}), true_type{})
test_is_braces_constructible(int);
template <class, class...> false_type test_is_braces_constructible(...);
template <class T, class... TArgs>
using is_braces_constructible =
decltype(test_is_braces_constructible<T, TArgs...>(0));
template <class T, class... TArgs>
using is_braces_constructible_t =
typename is_braces_constructible<T, TArgs...>::type;
#if defined(__MSVC__)
template <class T>
struct is_copy_constructible
: integral_constant<bool, __is_constructible(T, const T &)> {};
template <class T>
struct is_default_constructible
: integral_constant<bool, __is_constructible(T)> {};
#else
template <class T> using is_copy_constructible = is_constructible<T, const T &>;
template <class T> using is_default_constructible = is_constructible<T>;
#endif
#if defined(__CLANG__) || defined(__MSVC__)
template <class T, class U>
struct is_convertible : integral_constant<bool, __is_convertible_to(T, U)> {};
#else
struct test_is_convertible__ {
template <class T> static void test(T);
};
template <class T, class U,
class = decltype(test_is_convertible__::test<U>(declval<T>()))>
true_type test_is_convertible(int);
template <class, class> false_type test_is_convertible(...);
template <class T, class U>
using is_convertible = decltype(test_is_convertible<T, U>(0));
#endif
template <class TSrc, class TDst, class U = remove_qualifiers_t<TDst>>
using is_narrowed =
integral_constant<bool, !is_class<TSrc>::value && !is_class<U>::value &&
!is_same<TSrc, U>::value>;
template <class, class...> struct is_array : false_type {};
template <class T, class... Ts> struct is_array<T[], Ts...> : true_type {};
template <class T, class = decltype(sizeof(T))> true_type is_complete_impl(int);
template <class T> false_type is_complete_impl(...);
template <class T> struct is_complete : decltype(is_complete_impl<T>(0)) {};
template <class T, class U, class = decltype(sizeof(U))>
is_base_of<T, U> is_a_impl(int);
template <class T, class U> false_type is_a_impl(...);
template <class T, class U> struct is_a : decltype(is_a_impl<T, U>(0)) {};
template <class, class...> struct is_unique_impl;
template <class...> struct not_unique : false_type { using type = not_unique; };
template <> struct not_unique<> : true_type { using type = not_unique; };
template <class T> struct is_unique_impl<T> : not_unique<> {};
template <class T1, class T2, class... Ts>
struct is_unique_impl<T1, T2, Ts...>
: conditional_t<is_base_of<type<T2>, T1>::value, not_unique<T2>,
is_unique_impl<inherit<T1, type<T2>>, Ts...>> {};
template <class... Ts> using is_unique = is_unique_impl<none_type, Ts...>;
template <class...> struct unique;
template <class... Rs, class T, class... Ts>
struct unique<type<Rs...>, T, Ts...>
: conditional_t<is_base_of<type<T>, inherit<type<Rs>...>>::value,
unique<type<Rs...>, Ts...>, unique<type<Rs..., T>, Ts...>> {
};
template <class... Rs> struct unique<type<Rs...>> : type_list<Rs...> {};
template <class... Ts> using unique_t = typename unique<type<>, Ts...>::type;
false_type has_shared_ptr__(...);
#if !defined(BOOST_DI_DISABLE_SHARED_PTR_DEDUCTION)
template <class T>
auto has_shared_ptr__(T &&) -> is_valid_expr<decltype(std::shared_ptr<T>{})>;
#endif
template <class T, class... TArgs>
decltype(::boost::ext::di::v1_2_0::aux::declval<T>().operator()(
::boost::ext::di::v1_2_0::aux::declval<TArgs>()...),
::boost::ext::di::v1_2_0::aux::true_type())
is_invocable_impl(int);
template <class, class...>
::boost::ext::di::v1_2_0::aux::false_type is_invocable_impl(...);
template <class T, class... TArgs>
struct is_invocable : decltype(is_invocable_impl<T, TArgs...>(0)) {};
struct callable_base_impl {
void operator()(...) {}
};
template <class T>
struct callable_base
: callable_base_impl,
aux::conditional_t<aux::is_class<T>::value && !aux::is_final<T>::value, T,
aux::none_type> {};
template <typename T>
aux::false_type is_callable_impl(
T *,
aux::non_type<void (callable_base_impl::*)(...), &T::operator()> * = 0);
aux::true_type is_callable_impl(...);
template <class T>
struct is_callable : decltype(is_callable_impl((callable_base<T> *)0)) {};
template <class, class = int> struct is_empty_expr : false_type {};
template <class TExpr>
#if defined(__MSVC__)
struct is_empty_expr<TExpr, valid_t<decltype(declval<TExpr>()())>>
: integral_constant<bool, sizeof(TExpr) == 1> {
};
#else
struct is_empty_expr<
TExpr, valid_t<decltype(+declval<TExpr>()), decltype(declval<TExpr>()())>>
: true_type {
};
#endif
template <class> struct function_traits;
template <class R, class... TArgs> struct function_traits<R (*)(TArgs...)> {
using result_type = R;
using args = type_list<TArgs...>;
};
template <class R, class... TArgs> struct function_traits<R(TArgs...)> {
using result_type = R;
using args = type_list<TArgs...>;
};
template <class R, class T, class... TArgs>
struct function_traits<R (T::*)(TArgs...)> {
using result_type = R;
using args = type_list<TArgs...>;
};
template <class R, class T, class... TArgs>
struct function_traits<R (T::*)(TArgs...) const> {
using result_type = R;
using args = type_list<TArgs...>;
};
template <class T> using function_traits_t = typename function_traits<T>::args;
} // namespace aux
namespace core {
template <class T, class = typename aux::is_a<injector_base, T>::type>
struct bindings_impl;
template <class T> struct bindings_impl<T, aux::true_type> {
using type = typename T::deps;
};
template <class T> struct bindings_impl<T, aux::false_type> {
using type = aux::type_list<T>;
};
#if defined(__MSVC__)
template <class... Ts>
struct bindings : aux::join_t<typename bindings_impl<Ts>::type...> {};
template <class... Ts> using bindings_t = typename bindings<Ts...>::type;
#else
template <class... Ts>
using bindings_t = aux::join_t<typename bindings_impl<Ts>::type...>;
#endif
} // namespace core
namespace concepts {
template <class T, class...> struct type_ {
template <class TName> struct named {
struct is_bound_more_than_once : aux::false_type {};
};
struct is_bound_more_than_once : aux::false_type {};
struct is_neither_a_dependency_nor_an_injector : aux::false_type {};
struct has_disallowed_qualifiers : aux::false_type {};
struct is_abstract :
#if (BOOST_DI_CFG_DIAGNOSTICS_LEVEL >= 2)
// clang-format off
decltype(
T{}
),
// clang-format on
#endif
aux::false_type {
};
template <class> struct is_not_related_to : aux::false_type {};
};
template <class...> struct any_of : aux::false_type {};
template <class... TDeps>
struct is_supported
: aux::is_same<
aux::bool_list<aux::always<TDeps>::value...>,
aux::bool_list<(aux::is_constructible<TDeps, TDeps &&>::value &&
(aux::is_a<core::injector_base, TDeps>::value ||
aux::is_a<core::dependency_base, TDeps>::value ||
aux::is_empty_expr<TDeps>::value))...>> {};
template <class...> struct get_not_supported;
template <class T> struct get_not_supported<T> { using type = T; };
template <class T, class... TDeps>
struct get_not_supported<T, TDeps...>
: aux::conditional<aux::is_a<core::injector_base, T>::value ||
aux::is_a<core::dependency_base, T>::value,
typename get_not_supported<TDeps...>::type, T> {};
template <class> struct is_unique;
template <class T, class = int> struct unique_dependency : aux::type<T> {};
template <class T>
struct unique_dependency<T, __BOOST_DI_REQUIRES(
aux::is_a<core::dependency_base, T>::value)>
: aux::pair<aux::pair<typename T::expected, typename T::name>,
typename T::priority> {};
template <class... TDeps>
struct is_unique<aux::type_list<TDeps...>>
: aux::is_unique<typename unique_dependency<TDeps>::type...> {};
template <class> struct get_is_unique_error_impl : aux::true_type {};
template <class T, class TName, class TPriority>
struct get_is_unique_error_impl<
aux::not_unique<aux::pair<aux::pair<T, TName>, TPriority>>> {
using type =
typename type_<T>::template named<TName>::is_bound_more_than_once;
};
template <class T, class TPriority>
struct get_is_unique_error_impl<
aux::not_unique<aux::pair<aux::pair<T, no_name>, TPriority>>> {
using type = typename type_<T>::is_bound_more_than_once;
};
template <class T> struct get_is_unique_error_impl<aux::not_unique<T>> {
using type = typename type_<T>::is_bound_more_than_once;
};
template <class> struct get_is_unique_error;
template <class... TDeps>
struct get_is_unique_error<aux::type_list<TDeps...>>
: get_is_unique_error_impl<typename aux::is_unique<
typename unique_dependency<TDeps>::type...>::type> {};
template <class... TDeps>
using boundable_bindings = aux::conditional_t<
is_supported<TDeps...>::value,
typename get_is_unique_error<core::bindings_t<TDeps...>>::type,
typename type_<typename get_not_supported<TDeps...>::type>::
is_neither_a_dependency_nor_an_injector>;
template <class... Ts>
struct get_any_of_error
: aux::conditional<aux::is_same<aux::bool_list<aux::always<Ts>::value...>,
aux::bool_list<aux::is_same<
aux::true_type, Ts>::value...>>::value,
aux::true_type, any_of<Ts...>> {};
template <bool, class...> struct is_related {
static constexpr auto value = true;
};
template <class I, class T> struct is_related<true, I, T> {
static constexpr auto value =
aux::is_base_of<I, T>::value ||
(aux::is_convertible<T, I>::value && !aux::is_narrowed<I, T>::value);
};
template <bool, class> struct is_abstract {
static constexpr auto value = false;
};
template <class T> struct is_abstract<true, T> {
static constexpr auto value = aux::is_abstract<T>::value;
};
auto boundable_impl(any_of<> &&) -> aux::true_type;
template <class T, class... Ts>
auto boundable_impl(any_of<T, Ts...> &&) -> aux::conditional_t<
aux::is_same<T, aux::decay_t<T>>::value,
decltype(boundable_impl(aux::declval<any_of<Ts...>>())),
typename type_<T>::has_disallowed_qualifiers>;
template <class I, class T>
using boundable_impl__ = aux::conditional_t<
is_related<aux::is_complete<I>::value && aux::is_complete<T>::value, I,
T>::value,
aux::conditional_t<is_abstract<aux::is_complete<T>::value, T>::value,
typename type_<T>::is_abstract, aux::true_type>,
typename type_<T>::template is_not_related_to<I>>;
template <class I, class T>
auto boundable_impl(I &&, T &&) -> aux::conditional_t<
aux::is_same<T, aux::decay_t<T>>::value || !aux::is_complete<I>::value,
boundable_impl__<I, T>, typename type_<T>::has_disallowed_qualifiers>;
template <class I, class T>
auto boundable_impl(I &&, T &&, aux::valid<> &&) -> aux::conditional_t<
is_related<aux::is_complete<I>::value && aux::is_complete<T>::value, I,
T>::value,
aux::true_type, typename type_<T>::template is_not_related_to<I>>;
template <class I, class T>
auto boundable_impl(I *[], T &&)
-> aux::conditional_t<aux::is_same<I, aux::decay_t<I>>::value,
boundable_impl__<I, T>,
typename type_<I>::has_disallowed_qualifiers>;
template <class I, class T>
auto boundable_impl(I[], T &&)
-> aux::conditional_t<aux::is_same<I, aux::decay_t<I>>::value,
boundable_impl__<I, T>,
typename type_<I>::has_disallowed_qualifiers>;
template <class... TDeps>
auto boundable_impl(aux::type_list<TDeps...> &&)
-> boundable_bindings<TDeps...>;
template <class T, class... Ts>
auto boundable_impl(concepts::any_of<Ts...> &&, T &&) ->
typename get_any_of_error<decltype(
boundable_impl(aux::declval<Ts>(), aux::declval<T>()))...>::type;
template <class... TDeps>
auto boundable_impl(aux::type<TDeps...> &&) ->
typename get_is_unique_error_impl<
typename aux::is_unique<TDeps...>::type>::type;
aux::true_type boundable_impl(...);
template <class... Ts> struct boundable__ {
using type = decltype(boundable_impl(aux::declval<Ts>()...));
};
template <class... Ts> using boundable = typename boundable__<Ts...>::type;
} // namespace concepts
namespace type_traits {
struct stack {};
struct heap {};
template <class T, class = int> struct memory_traits { using type = stack; };
template <class T> struct memory_traits<T *> { using type = heap; };
template <class T> struct memory_traits<const T &> {
using type = typename memory_traits<T>::type;
};
template <class T, class TDeleter>
struct memory_traits<std::unique_ptr<T, TDeleter>> {
using type = heap;
};
template <class T> struct memory_traits<std::shared_ptr<T>> {
using type = heap;
};
template <class T> struct memory_traits<boost::shared_ptr<T>> {
using type = heap;
};
template <class T> struct memory_traits<std::weak_ptr<T>> {
using type = heap;
};
template <class T>
struct memory_traits<T, __BOOST_DI_REQUIRES(aux::is_polymorphic<T>::value)> {
using type = heap;
};
} // namespace type_traits
namespace concepts {
template <class...> struct scope {
struct is_referable {};
struct try_create {};
struct create {};
template <class...> struct requires_ : aux::false_type {};
};
template <class> struct scope__ {
template <class...> struct scope {
template <class...> using is_referable = aux::true_type;
template <class T, class, class TProvider> T try_create(const TProvider &);
template <class T, class, class TProvider> T create(const TProvider &);
};
};
template <class> struct config__ {
template <class T> struct scope_traits { using type = scope__<T>; };
template <class T> struct memory_traits { using type = type_traits::heap; };
};
template <class T> struct provider__ {
using config = config__<T>;
template <class TMemory = type_traits::heap>
aux::conditional_t<aux::is_same<TMemory, type_traits::stack>::value, T, T *>
try_get(const TMemory & = {}) const;
template <class TMemory = type_traits::heap>
T *get(const TMemory & = {}) const {
return nullptr;
}
config &cfg() const;
};
template <class T>
typename scope<T>::template requires_<typename scope<_, _>::is_referable,
typename scope<_, _>::try_create,
typename scope<_, _>::create>
scopable_impl(...);
template <class T>
auto scopable_impl(T &&) -> aux::is_valid_expr<
typename T::template scope<_, _>::template is_referable<_, config__<_>>,
decltype(
T::template scope<_, _>::template try_create<_, _>(provider__<_>{})),
decltype(aux::declval<typename T::template scope<_, _>>()
.template create<_, _>(provider__<_>{}))>;
template <class T> struct scopable__ {
using type = decltype(scopable_impl<T>(aux::declval<T>()));
};
template <class T> using scopable = typename scopable__<T>::type;
} // namespace concepts
namespace core {
template <class = aux::type_list<>> struct pool;
template <class... TArgs> using pool_t = pool<aux::type_list<TArgs...>>;
template <class... TArgs> struct pool<aux::type_list<TArgs...>> : TArgs... {
template <class... Ts>
explicit pool(Ts... args) noexcept : Ts(static_cast<Ts &&>(args))... {}
template <class... Ts, class TPool>
pool(const aux::type_list<Ts...> &, TPool p) noexcept
: pool(static_cast<Ts &&>(p)...) {
(void)p;
}
template <class T> pool &operator=(T &&other) noexcept {
(void)aux::swallow{
0, (static_cast<TArgs &>(*this).operator=(static_cast<TArgs &&>(other)),
0)...};
return *this;
}
};
} // namespace core
#if !defined(BOOST_DI_CFG_CTOR_LIMIT_SIZE)
#define BOOST_DI_CFG_CTOR_LIMIT_SIZE 10
#endif
namespace type_traits {
template <class, class = int>
struct is_injectable : ::boost::ext::di::v1_2_0::aux::false_type {};
template <class T>
struct is_injectable<
T, ::boost::ext::di::v1_2_0::aux::valid_t<typename T::boost_di_inject__>>
: ::boost::ext::di::v1_2_0::aux::true_type {};
struct direct {};
struct uniform {};
template <class T, int> using get = T;
template <template <class...> class, class, class, class = int>
struct ctor_impl;
template <template <class...> class TIsConstructible, class T>
struct ctor_impl<TIsConstructible, T, aux::index_sequence<>>
: aux::type_list<> {};
template <template <class...> class TIsConstructible, class T>
struct ctor_impl<TIsConstructible, T, aux::index_sequence<0>,
__BOOST_DI_REQUIRES(
TIsConstructible<T, core::any_type_1st_fwd<T>>::value)>
: aux::type_list<core::any_type_1st_fwd<T>> {};
template <template <class...> class TIsConstructible, class T>
struct ctor_impl<TIsConstructible, T, aux::index_sequence<0>,
__BOOST_DI_REQUIRES(
!TIsConstructible<T, core::any_type_1st_fwd<T>>::value)>
: aux::conditional_t<
TIsConstructible<T, core::any_type_1st_ref_fwd<T>>::value,
aux::type_list<core::any_type_1st_ref_fwd<T>>, aux::type_list<>> {};
template <template <class...> class TIsConstructible, class T, int... Ns>
struct ctor_impl<
TIsConstructible, T, aux::index_sequence<Ns...>,
__BOOST_DI_REQUIRES(
(sizeof...(Ns) > 1) &&
TIsConstructible<T, get<core::any_type_fwd<T>, Ns>...>::value)>
: aux::type_list<get<core::any_type_fwd<T>, Ns>...> {};
template <template <class...> class TIsConstructible, class T, int... Ns>
struct ctor_impl<
TIsConstructible, T, aux::index_sequence<Ns...>,
__BOOST_DI_REQUIRES(
(sizeof...(Ns) > 1) &&
!TIsConstructible<T, get<core::any_type_fwd<T>, Ns>...>::value)>
: aux::conditional<
TIsConstructible<T, get<core::any_type_ref_fwd<T>, Ns>...>::value,
aux::type_list<get<core::any_type_ref_fwd<T>, Ns>...>,
typename ctor_impl<
TIsConstructible, T,
aux::make_index_sequence<sizeof...(Ns) - 1>>::type> {};
template <template <class...> class TIsConstructible, class T>
using ctor_impl_t = typename ctor_impl<
TIsConstructible, T,
aux::make_index_sequence<BOOST_DI_CFG_CTOR_LIMIT_SIZE>>::type;
template <class...> struct ctor;
template <class T>
struct ctor<T, aux::type_list<>>
: aux::pair<uniform, ctor_impl_t<aux::is_braces_constructible, T>> {};
template <class T, class... TArgs>
struct ctor<T, aux::type_list<TArgs...>>
: aux::pair<direct, aux::type_list<TArgs...>> {};
template <class T, class, class = typename is_injectable<ctor_traits<T>>::type>
struct ctor_traits_impl;
template <class T, class = void, class = void,
class = typename is_injectable<T>::type>
struct ctor_traits__;
template <class T, class _1, class _2>
struct ctor_traits__<T, _1, _2, aux::true_type>
: aux::pair<T, aux::pair<direct, typename T::boost_di_inject__::type>> {};
template <class T, class _1, class _2>
struct ctor_traits__<T, _1, _2, aux::false_type> : ctor_traits_impl<T, _1> {};
template <class T, class _1, class... Ts>
struct ctor_traits__<T, _1, core::pool_t<Ts...>, aux::false_type>
: aux::pair<T, aux::pair<uniform, aux::type_list<Ts...>>> {};
template <class T, class _>
struct ctor_traits_impl<T, _, aux::true_type>
: aux::pair<
T,
aux::pair<direct, typename ctor_traits<T>::boost_di_inject__::type>> {
};
template <class T, class _>
struct ctor_traits_impl<T, _, aux::false_type>
: aux::pair<T, typename ctor_traits<T>::type> {};
} // namespace type_traits
template <class T, class>
struct ctor_traits
: type_traits::ctor<T, type_traits::ctor_impl_t<aux::is_constructible, T>> {
};
template <class T> struct ctor_traits<std::initializer_list<T>> {
using boost_di_inject__ = aux::type_list<>;
};
template <class... Ts> struct ctor_traits<std::tuple<Ts...>> {
using boost_di_inject__ = aux::type_list<Ts...>;
};
template <class T>
struct ctor_traits<T, __BOOST_DI_REQUIRES(
aux::is_same<std::char_traits<char>,
typename T::traits_type>::value)> {
using boost_di_inject__ = aux::type_list<>;
};
template <class T>
struct ctor_traits<T, __BOOST_DI_REQUIRES(!aux::is_class<T>::value)> {
using boost_di_inject__ = aux::type_list<>;
};
namespace type_traits {
template <class T> struct remove_named { using type = T; };
template <class TName, class T> struct remove_named<named<TName, T>> {
using type = T;
};
template <class T> using remove_named_t = typename remove_named<T>::type;
template <class T> struct add_named { using type = named<no_name, T>; };
template <class TName, class T> struct add_named<named<TName, T>> {
using type = named<TName, T>;
};
template <class T> using add_named_t = typename add_named<T>::type;
template <class T> struct named_decay { using type = aux::decay_t<T>; };
template <class TName, class T> struct named_decay<named<TName, T>> {
using type = named<TName, aux::decay_t<T>>;
};
template <class T> using named_decay_t = typename named_decay<T>::type;
} // namespace type_traits
namespace type_traits {
template <class, class T> struct rebind_traits { using type = T; };
template <class T, class TName, class _>
struct rebind_traits<T, named<TName, _>> {
using type = named<TName, T>;
};
template <class T, class D, class U>
struct rebind_traits<std::unique_ptr<T, D>, U> {
using type = std::unique_ptr<U, D>;
};
template <class T, class D, class TName, class _>
struct rebind_traits<std::unique_ptr<T, D>, named<TName, _>> {
using type = named<TName, std::unique_ptr<T, D>>;
};
template <class T, class U> struct rebind_traits<std::shared_ptr<T>, U> {
using type = std::shared_ptr<U>;
};
template <class T, class TName, class _>
struct rebind_traits<std::shared_ptr<T>, named<TName, _>> {
using type = named<TName, std::shared_ptr<T>>;
};
template <class T, class U> struct rebind_traits<std::weak_ptr<T>, U> {
using type = std::weak_ptr<U>;
};
template <class T, class TName, class _>
struct rebind_traits<std::weak_ptr<T>, named<TName, _>> {
using type = named<TName, std::weak_ptr<T>>;
};
template <class T, class U> struct rebind_traits<boost::shared_ptr<T>, U> {
using type = boost::shared_ptr<U>;
};
template <class T, class TName, class _>
struct rebind_traits<boost::shared_ptr<T>, named<TName, _>> {
using type = named<TName, boost::shared_ptr<T>>;
};
template <class T, class U>
using rebind_traits_t = typename rebind_traits<T, U>::type;
} // namespace type_traits
namespace core {
template <class T, class... Ts> struct array_impl : _ {
using boost_di_inject__ = aux::type_list<Ts...>;
explicit array_impl(type_traits::remove_named_t<Ts> &&... args)
: array{static_cast<type_traits::remove_named_t<Ts> &&>(args)...} {}
T array[sizeof...(Ts)];
};
template <class T, class... Ts> struct array<T(), Ts...> : T {
using value_type = typename aux::identity<T>::type::value_type;
using array_t =
array_impl<value_type, type_traits::rebind_traits_t<value_type, Ts>...>;
using boost_di_inject__ = aux::type_list<array_t &&>;
template <__BOOST_DI_REQUIRES(aux::is_constructible<
T, std::move_iterator<value_type *>,
std::move_iterator<value_type *>>::value) = 0>
explicit array(array_t &&a)
: T(std::move_iterator<value_type *>(a.array),
std::move_iterator<value_type *>(a.array + sizeof...(Ts))) {}
};
template <class T> struct array<T()> : T {
using boost_di_inject__ = aux::type_list<>;
};
template <class T> struct array<T> {};
} // namespace core
namespace type_traits {
template <class _, class T, class _1, class... Ts>
struct ctor_traits__<core::array<_, Ts...>, T, _1, aux::false_type>
: type_traits::ctor_traits__<core::array<
aux::remove_smart_ptr_t<aux::remove_qualifiers_t<T>>(), Ts...>> {};
} // namespace type_traits
namespace scopes {
class deduce {
public:
template <class TExpected, class TGiven> class scope {
public:
template <class T, class TConfig>
using is_referable =
typename TConfig::template scope_traits<T>::type::template scope<
TExpected, TGiven>::template is_referable<T, TConfig>;
template <class T, class TName, class TProvider>
static decltype(
typename TProvider::config::template scope_traits<
T>::type::template scope<TExpected, TGiven>{}
.template try_create<T, TName>(aux::declval<TProvider>()))
try_create(const TProvider &);
template <class T, class TName, class TProvider>
auto create(const TProvider &provider) {
using scope_traits =
typename TProvider::config::template scope_traits<T>::type;
using scope = typename scope_traits::template scope<TExpected, TGiven>;
return scope{}.template create<T, TName>(provider);
}
};
};
} // namespace scopes
static constexpr __BOOST_DI_UNUSED scopes::deduce deduce{};
namespace concepts {
template <class T> struct abstract_type {
struct is_not_bound {
operator T *() const {
using constraint_not_satisfied = is_not_bound;
return constraint_not_satisfied{}.error();
}
// clang-format off
static inline T*
error(_ = "type is not bound, did you forget to add: 'di::bind<interface>.to<implementation>()'?");
// clang-format on
};
template <class TName> struct named {
struct is_not_bound {
operator T *() const {
using constraint_not_satisfied = is_not_bound;
return constraint_not_satisfied{}.error();
}
// clang-format off
static inline T*
error(_ = "type is not bound, did you forget to add: 'di::bind<interface>.named(name).to<implementation>()'?");
// clang-format on
};
};
};
template <class TScope, class T> struct scoped {
template <class To> struct is_not_convertible_to {
operator To() const {
using constraint_not_satisfied = is_not_convertible_to;
return constraint_not_satisfied{}.error();
}
// clang-format off
static inline To
error(_ = "scoped object is not convertible to the requested type, did you mistake the scope: 'di::bind<T>.in(scope)'?");
// clang-format on
};
};
template <class T> struct scoped<scopes::instance, T> {
template <class To> struct is_not_convertible_to {
operator To() const {
using constraint_not_satisfied = is_not_convertible_to;
return constraint_not_satisfied{}.error();
}
// clang-format off
static inline To
error(_ = "instance is not convertible to the requested type, verify binding: 'di::bind<T>.to(value)'?");
// clang-format on
};
};
template <class T> struct type {
struct has_ambiguous_number_of_constructor_parameters {
template <int Given> struct given {
template <int Expected> struct expected {
operator T *() const {
using constraint_not_satisfied = expected;
return constraint_not_satisfied{}.error();
}
// clang-format off
static inline T*
error(_ = "verify BOOST_DI_INJECT_TRAITS or di::ctor_traits");
// clang-format on
};
};
};
struct has_to_many_constructor_parameters {
template <int TMax> struct max {
operator T *() const {
using constraint_not_satisfied = max;
return constraint_not_satisfied{}.error();
}
// clang-format off
static inline T*
error(_ = "increase BOOST_DI_CFG_CTOR_LIMIT_SIZE value or reduce number of constructor parameters");
// clang-format on
};
};
struct is_not_exposed {
operator T() const {
using constraint_not_satisfied = is_not_exposed;
return constraint_not_satisfied{}.error();
}
// clang-format off
static inline T
error(_ = "type is not exposed, did you forget to add: 'di::injector<T>'?");
// clang-format on
};
template <class TName> struct named {
struct is_not_exposed {
operator T() const {
using constraint_not_satisfied = is_not_exposed;
return constraint_not_satisfied{}.error();
}
// clang-format off
static inline T
error(_ = "type is not exposed, did you forget to add: 'di::injector<BOOST_DI_EXPOSE((named = name)T)>'?");
// clang-format on
};
};
};
template <class> struct ctor_size;
template <class TInit, class... TCtor>
struct ctor_size<aux::pair<TInit, aux::type_list<TCtor...>>>
: aux::integral_constant<int, sizeof...(TCtor)> {};
template <class... TCtor>
struct ctor_size<aux::type_list<TCtor...>>
: aux::integral_constant<int, sizeof...(TCtor)> {};
template <class T>
using ctor_size_t = ctor_size<typename type_traits::ctor<
T, type_traits::ctor_impl_t<aux::is_constructible, T>>::type>;
template <class TInitialization, class TName, class _, class TCtor,
class T = aux::decay_t<_>>
struct creatable_error_impl
: aux::conditional_t<
aux::is_polymorphic<T>::value,
aux::conditional_t<
aux::is_same<TName, no_name>::value,
typename abstract_type<T>::is_not_bound,
typename abstract_type<T>::template named<TName>::is_not_bound>,
aux::conditional_t<
ctor_size_t<T>::value == ctor_size<TCtor>::value,
typename type<T>::has_to_many_constructor_parameters::
template max<BOOST_DI_CFG_CTOR_LIMIT_SIZE>,
typename type<T>::has_ambiguous_number_of_constructor_parameters::
template given<ctor_size<TCtor>::value>::template expected<
ctor_size_t<T>::value>>> {};
template <class TInit, class T, class... TArgs> struct creatable {
static constexpr auto value = aux::is_constructible<T, TArgs...>::value;
};
template <class T, class... TArgs>
struct creatable<type_traits::uniform, T, TArgs...> {
static constexpr auto value =
aux::is_braces_constructible<T, TArgs...>::value;
};
template <class TInitialization, class TName, class T, class... TArgs>
T creatable_error() {
return creatable_error_impl<TInitialization, TName, T,
aux::type_list<TArgs...>>{};
}
} // namespace concepts
namespace wrappers {
template <class TScope, class T, class TObject = std::shared_ptr<T>>
struct shared {
using scope = TScope;
template <class> struct is_referable_impl : aux::true_type {};
template <class I>
struct is_referable_impl<std::shared_ptr<I>> : aux::is_same<I, T> {};
template <class I>
struct is_referable_impl<boost::shared_ptr<I>> : aux::false_type {};
template <class T_>
using is_referable = is_referable_impl<aux::remove_qualifiers_t<T_>>;
template <class I,
__BOOST_DI_REQUIRES(aux::is_convertible<T *, I *>::value) = 0>
inline operator std::shared_ptr<I>() const noexcept {
return object;
}
inline operator std::shared_ptr<T> &() noexcept { return object; }
template <class I,
__BOOST_DI_REQUIRES(aux::is_convertible<T *, I *>::value) = 0>
inline operator boost::shared_ptr<I>() const noexcept {
struct sp_holder {
std::shared_ptr<T> object;
void operator()(...) noexcept { object.reset(); }
};
return {object.get(), sp_holder{object}};
}
template <class I,
__BOOST_DI_REQUIRES(aux::is_convertible<T *, I *>::value) = 0>
inline operator std::weak_ptr<I>() const noexcept {
return object;
}
inline operator T &() noexcept { return *object; }
inline operator const T &() const noexcept { return *object; }
TObject object;
};
template <class TScope, class T> struct shared<TScope, T &> {
using scope = TScope;
template <class> struct is_referable : aux::true_type {};
explicit shared(T &object) : object(&object) {}
template <class I> explicit shared(I);
template <class I, __BOOST_DI_REQUIRES(aux::is_convertible<T, I>::value) = 0>
inline operator I() const noexcept {
return *object;
}
inline operator T &() const noexcept { return *object; }
T *object = nullptr;
};
} // namespace wrappers
namespace wrappers {
template <class TScope, class T> struct unique {
using scope = TScope;
template <class I, __BOOST_DI_REQUIRES(aux::is_convertible<T, I>::value) = 0>
inline operator I() const noexcept {
return object;
}
inline operator T &&() noexcept { return static_cast<T &&>(object); }
T object;
};
template <class TScope, class T> struct unique<TScope, T *> {
using scope = TScope;
#if defined(__MSVC__)
explicit unique(T *object) : object(object) {}
#endif
template <class I, __BOOST_DI_REQUIRES(aux::is_convertible<T, I>::value) = 0>
inline operator I() const noexcept {
struct scoped_ptr {
aux::owner<T *> ptr;
~scoped_ptr() noexcept { delete ptr; }
};
return static_cast<T &&>(*scoped_ptr{object}.ptr);
}
template <class I,
__BOOST_DI_REQUIRES(aux::is_convertible<T *, I *>::value) = 0>
inline operator aux::owner<I *>() const noexcept {
return object;
}
template <class I,
__BOOST_DI_REQUIRES(aux::is_convertible<T *, const I *>::value) = 0>
inline operator aux::owner<const I *>() const noexcept {
return object;
}
template <class I,
__BOOST_DI_REQUIRES(aux::is_convertible<T *, I *>::value) = 0>
inline operator std::shared_ptr<I>() const noexcept {
return std::shared_ptr<I>{object};
}
template <class I,
__BOOST_DI_REQUIRES(aux::is_convertible<T *, I *>::value) = 0>
inline operator boost::shared_ptr<I>() const noexcept {
return boost::shared_ptr<I>{object};
}
template <class I, class D,
__BOOST_DI_REQUIRES(aux::is_convertible<T *, I *>::value) = 0>
inline operator std::unique_ptr<I, D>() const noexcept {
return std::unique_ptr<I, D>{object};
}
T *object = nullptr;
};
} // namespace wrappers
namespace scopes {
class instance;
namespace detail {
template <class T, class TExpected, class TGiven> struct arg {
using type = T;
using expected = TExpected;
using given = TGiven;
};
template <class T> struct wrapper_traits {
using type = wrappers::unique<instance, T>;
};
template <class T> struct wrapper_traits<std::shared_ptr<T>> {
using type = wrappers::shared<instance, T>;
};
template <class T> using wrapper_traits_t = typename wrapper_traits<T>::type;
template <class, class = int>
struct has_result_type : ::boost::ext::di::v1_2_0::aux::false_type {};
template <class T>
struct has_result_type<
T, ::boost::ext::di::v1_2_0::aux::valid_t<typename T::result_type>>
: ::boost::ext::di::v1_2_0::aux::true_type {};
template <class TGiven, class TProvider, class... Ts>
struct is_expr
: aux::integral_constant<
bool, aux::is_invocable<TGiven, typename TProvider::injector,
Ts...>::value &&
!has_result_type<TGiven>::value> {};
} // namespace detail
template <class T> struct wrapper {
inline operator T() noexcept { return static_cast<T &&>(object); }
T object;
};
class instance {
public:
template <class, class TGiven, class = int> struct scope {
template <class...> using is_referable = aux::false_type;
explicit scope(const TGiven &object) : object_{object} {}
template <class, class, class TProvider>
static wrappers::unique<instance, TGiven> try_create(const TProvider &);
template <class, class, class TProvider>
auto create(const TProvider &) const noexcept {
return wrappers::unique<instance, TGiven>{object_};
}
TGiven object_;
};
template <class TExpected, class TGiven>
struct scope<TExpected, std::shared_ptr<TGiven>> {
template <class T, class>
using is_referable = typename wrappers::shared<
instance, TGiven>::template is_referable<aux::remove_qualifiers_t<T>>;
explicit scope(const std::shared_ptr<TGiven> &object) : object_{object} {}
template <class, class, class TProvider>
static wrappers::shared<instance, TGiven> try_create(const TProvider &);
template <class, class, class TProvider>
auto create(const TProvider &) const noexcept {
return wrappers::shared<instance, TGiven>{object_};
}
std::shared_ptr<TGiven> object_;
};
template <class TExpected, class TGiven>
struct scope<TExpected, std::initializer_list<TGiven>> {
template <class...> using is_referable = aux::false_type;
scope(const std::initializer_list<TGiven> &object) : object_(object) {}
template <class, class, class TProvider>
static std::initializer_list<TGiven> try_create(const TProvider &);
template <class, class, class TProvider>
auto create(const TProvider &) const noexcept {
return wrappers::unique<instance, std::initializer_list<TGiven>>{object_};
}
std::initializer_list<TGiven> object_;
};
template <class TExpected, class TGiven>
struct scope<TExpected, TGiven &,
__BOOST_DI_REQUIRES(!aux::is_callable<TGiven>::value)> {
template <class...> using is_referable = aux::true_type;
explicit scope(TGiven &object) : object_{object} {}
template <class, class, class TProvider>
static wrappers::shared<instance, TGiven &> try_create(const TProvider &);
template <class, class, class TProvider>
auto create(const TProvider &) const noexcept {
return object_;
}
wrappers::shared<instance, TGiven &> object_;
};
template <class TExpected, class TGiven>
struct scope<TExpected, TGiven,
__BOOST_DI_REQUIRES(aux::is_callable<TGiven>::value)> {
template <class...>
using is_referable =
aux::integral_constant<bool,
!aux::is_callable<TExpected>::value ||
!detail::has_result_type<TExpected>::value>;
explicit scope(const TGiven &object) : object_(object) {}
#if defined(__MSVC__)
template <class T, class, class TProvider>
static T try_create(const TProvider &) noexcept;
#else
template <class, class, class TProvider,
__BOOST_DI_REQUIRES(!detail::is_expr<TGiven, TProvider>::value &&
aux::is_callable<TGiven>::value &&
aux::is_callable<TExpected>::value) = 0>
static wrappers::unique<instance, TExpected>
try_create(const TProvider &) noexcept;
template <class T, class, class TProvider,
__BOOST_DI_REQUIRES(!detail::is_expr<TGiven, TProvider>::value &&
aux::is_invocable<TGiven>::value &&
!aux::is_callable<TExpected>::value) = 0>
static auto try_create(const TProvider &) noexcept
-> detail::wrapper_traits_t<decltype(
aux::declval<typename aux::identity<TGiven, T>::type>()())>;
template <
class, class, class TProvider,
__BOOST_DI_REQUIRES(detail::is_expr<TGiven, TProvider>::value) = 0>
static detail::wrapper_traits_t<decltype(
aux::declval<TGiven>()(aux::declval<typename TProvider::injector>()))>
try_create(const TProvider &) noexcept;
template <class T, class, class TProvider,
__BOOST_DI_REQUIRES(
detail::is_expr<
TGiven, TProvider,
const detail::arg<T, TExpected, TGiven> &>::value) = 0>
static detail::wrapper_traits_t<decltype(aux::declval<TGiven>()(
aux::declval<typename TProvider::injector>(),
aux::declval<detail::arg<T, TExpected, TGiven>>()))>
try_create(const TProvider &) noexcept;
#endif
template <class, class, class TProvider,
__BOOST_DI_REQUIRES(!detail::is_expr<TGiven, TProvider>::value &&
aux::is_callable<TGiven>::value &&
aux::is_callable<TExpected>::value) = 0>
auto create(const TProvider &) const noexcept {
return wrappers::unique<instance, TExpected>{object_};
}
template <class T, class, class TProvider,
__BOOST_DI_REQUIRES(!detail::is_expr<TGiven, TProvider>::value &&
aux::is_invocable<TGiven>::value &&
!aux::is_callable<TExpected>::value) = 0>
auto create(const TProvider &) const {
using wrapper =
detail::wrapper_traits_t<decltype(aux::declval<TGiven>()())>;
return wrapper{object_()};
}
template <
class, class, class TProvider,
__BOOST_DI_REQUIRES(detail::is_expr<TGiven, TProvider>::value) = 0>
auto create(const TProvider &provider) {
using wrapper =
detail::wrapper_traits_t<decltype((object_)(provider.super()))>;
return wrapper{(object_)(provider.super())};
}
template <class T, class, class TProvider,
__BOOST_DI_REQUIRES(
detail::is_expr<
TGiven, TProvider,
const detail::arg<T, TExpected, TGiven> &>::value) = 0>
auto create(const TProvider &provider) {
using wrapper = detail::wrapper_traits_t<decltype(
(object_)(provider.super(), detail::arg<T, TExpected, TGiven>{}))>;
return wrapper{
(object_)(provider.super(), detail::arg<T, TExpected, TGiven>{})};
}
TGiven object_;
};
template <class _, class... Ts> class scope<_, aux::type_list<Ts...>> {
template <class> struct injector__;
template <class TName, class T> struct injector__<named<TName, T>> {
T (*f)(const injector__ *) = nullptr;
explicit injector__(const decltype(f) &ptr) : f(ptr) {}
};
struct injector : injector__<Ts>... {
void (*dtor)(injector *) = nullptr;
~injector() noexcept { static_cast<injector *>(this)->dtor(this); }
template <class TName, class T>
T create(const named<TName, T> &, const aux::true_type &) const {
return static_cast<const injector__<named<TName, T>> *>(this)->f(
static_cast<const injector__<named<TName, T>> *>(this));
}
template <class T>
T create(const named<no_name, T> &, const aux::false_type &) const {
return typename concepts::type<T>::is_not_exposed{};
}
template <class TName, class T>
T create(const named<TName, T> &, const aux::false_type &) const {
return
typename concepts::type<T>::template named<TName>::is_not_exposed{};
}
};
template <class TInjector> class injector_impl : injector__<Ts>... {
void (*dtor)(injector_impl *) = nullptr;
static void dtor_impl(injector_impl *object) { object->~injector_impl(); }
template <class, class> struct create;
template <class TName, class T>
struct create<named<TName, T>, aux::true_type> {
static T impl(const injector__<named<TName, T>> *object) {
using type =
aux::type<aux::conditional_t<aux::is_same<TName, no_name>::value,
T, named<TName, T>>>;
return static_cast<const core::injector__<TInjector> &>(
static_cast<const injector_impl *>(object)->injector_)
.create_successful_impl(type{});
}
};
template <class TName, class T>
struct create<named<TName, T>, aux::false_type> {
static T impl(const injector__<named<TName, T>> *object) {
using type =
aux::type<aux::conditional_t<aux::is_same<TName, no_name>::value,
T, named<TName, T>>>;
return static_cast<const core::injector__<TInjector> &>(
static_cast<const injector_impl *>(object)->injector_)
.create_impl(type{});
}
};
template <class T>
struct is_creatable
: aux::integral_constant<
bool,
core::injector__<TInjector>::template is_creatable<T>::value> {
};
template <class TName, class T>
struct is_creatable<named<TName, T>>
: aux::integral_constant<
bool, core::injector__<TInjector>::template is_creatable<
T, TName>::value> {};
public:
explicit injector_impl(TInjector &&injector) noexcept
: injector__<Ts>(&injector_impl::template create<
Ts, typename is_creatable<Ts>::type>::impl)...,
dtor(&injector_impl::dtor_impl),
injector_(static_cast<TInjector &&>(injector)) {}
private:
TInjector injector_;
};
public:
template <class...> using is_referable = aux::true_type;
template <class TInjector,
__BOOST_DI_REQUIRES(
aux::is_a<core::injector_base, TInjector>::value) = 0>
explicit scope(TInjector &&i) noexcept
: injector_((injector *)new injector_impl<TInjector>{
static_cast<TInjector &&>(i)}) {}
scope(scope &&other) noexcept : injector_(other.injector_) {
other.injector_ = nullptr;
}
~scope() noexcept { delete injector_; }
template <class T, class TName, class TProvider>
static aux::conditional_t<
aux::is_base_of<injector__<named<TName, T>>, injector>::value, T, void>
try_create(const TProvider &);
template <class T, class TName, class TProvider>
auto create(const TProvider &) {
return wrapper<T>{injector_->create(
named<TName, T>{},
aux::is_base_of<injector__<named<TName, T>>, injector>{})};
}
private:
injector *injector_;
};
};
} // namespace scopes
namespace core {
template <class, int, class T> struct ctor_arg {
explicit ctor_arg(T &&t) : value(static_cast<T &&>(t)) {}
constexpr operator T() const { return value; }
private:
T value;
};
template <class, class> struct dependency_concept {};
template <class T, class TDependency>
struct dependency_impl : aux::pair<T, TDependency> {};
template <class T> struct make_dependency_concept {
using type = dependency_concept<T, no_name>;
};
template <class TName, class T>
struct make_dependency_concept<named<TName, T>> {
using type = dependency_concept<T, TName>;
};
template <class... Ts, class TName, class TDependency>
struct dependency_impl<dependency_concept<concepts::any_of<Ts...>, TName>,
TDependency>
: aux::pair<dependency_concept<Ts, TName>, TDependency>... {};
template <class... Ts, class TDependency>
struct dependency_impl<dependency_concept<aux::type_list<Ts...>, no_name>,
TDependency>
: aux::pair<typename make_dependency_concept<Ts>::type, TDependency>... {};
struct override {};
template <class TScope, class TExpected, class TGiven, class TName,
class TPriority, class TCtor>
class dependency
: dependency_base,
public TScope::template scope<TExpected, TGiven>,
public dependency_impl<
dependency_concept<TExpected, TName>,
dependency<TScope, TExpected, TGiven, TName, TPriority, TCtor>>,
protected TCtor {
template <class, class, class, class, class, class> friend class dependency;
using scope_t = typename TScope::template scope<TExpected, TGiven>;
template <class T>
using externable =
aux::integral_constant<bool,
aux::always<T>::value &&
aux::is_same<TScope, scopes::deduce>::value &&
aux::is_same<TExpected, TGiven>::value>;
template <class T> struct ref_traits { using type = T; };
template <int N> struct ref_traits<const char (&)[N]> {
using type = TExpected;
};
template <class R, class... Ts> struct ref_traits<R (&)(Ts...)> {
using type = TExpected;
};
template <class T> struct ref_traits<std::shared_ptr<T> &> {
using type = std::shared_ptr<T>;
};
template <class T, class> struct deduce_traits { using type = T; };
template <class T> struct deduce_traits<deduced, T> {
using type = aux::decay_t<T>;
};
template <class T, class U>
using deduce_traits_t = typename deduce_traits<T, U>::type;
template <class TParent, int N, class T>
using ctor_arg_traits = ctor_arg<TParent, N, T>;
public:
using scope = TScope;
using expected = TExpected;
using given = TGiven;
using name = TName;
using priority = TPriority;
using ctor = TCtor;
dependency() noexcept {}
template <class T>
explicit dependency(T &&object) noexcept
: scope_t(static_cast<T &&>(object)) {}
explicit dependency(TCtor &&ctor) noexcept
: TCtor{static_cast<TCtor &&>(ctor)} {}
template <class T, __BOOST_DI_REQUIRES(aux::is_same<TName, no_name>::value &&
!aux::is_same<T, no_name>::value) = 0>
auto named() noexcept {
return dependency<TScope, TExpected, TGiven, T, TPriority, TCtor>{
static_cast<dependency &&>(*this)};
}
template <class T, __BOOST_DI_REQUIRES(aux::is_same<TName, no_name>::value &&
!aux::is_same<T, no_name>::value) = 0>
auto named(const T &) noexcept {
return dependency<TScope, TExpected, TGiven, T, TPriority, TCtor>{
static_cast<dependency &&>(*this)};
}
template <class T, __BOOST_DI_REQUIRES_MSG(concepts::scopable<T>) = 0>
auto in(const T &)noexcept {
return dependency<T, TExpected, TGiven, TName, TPriority, TCtor>{};
}
template <class T,
__BOOST_DI_REQUIRES(!aux::is_array<TExpected, T>::value) = 0,
__BOOST_DI_REQUIRES_MSG(concepts::boundable<TExpected, T>) = 0>
auto to() noexcept {
return dependency<TScope, TExpected, T, TName, TPriority, TCtor>{};
}
template <class... Ts,
__BOOST_DI_REQUIRES(aux::is_array<TExpected, Ts...>::value) = 0>
auto to() noexcept {
using type = aux::remove_pointer_t<aux::remove_extent_t<TExpected>>;
return dependency<TScope, array<type>, array<type, Ts...>, TName, TPriority,
TCtor>{};
}
template <class T,
__BOOST_DI_REQUIRES_MSG(concepts::boundable<TExpected, T>) = 0>
auto to(std::initializer_list<T> il) noexcept {
using type = aux::remove_pointer_t<aux::remove_extent_t<TExpected>>;
using dependency =
dependency<scopes::instance, array<type>, std::initializer_list<T>,
TName, TPriority, TCtor>;
return dependency{il};
}
template <class T,
__BOOST_DI_REQUIRES(externable<T>::value &&
!aux::is_callable<T>::value) = 0,
__BOOST_DI_REQUIRES_MSG(
concepts::boundable<deduce_traits_t<TExpected, T>,
aux::decay_t<T>, aux::valid<>>) = 0>
auto to(T &&object) noexcept {
using dependency =
dependency<scopes::instance, deduce_traits_t<TExpected, T>,
typename ref_traits<T>::type, TName, TPriority, TCtor>;
return dependency{static_cast<T &&>(object)};
}
template <class T, __BOOST_DI_REQUIRES(
externable<T>::value &&aux::is_callable<T>::value) = 0>
auto to(T &&object) noexcept {
using dependency =
dependency<scopes::instance, deduce_traits_t<TExpected, T>,
typename ref_traits<T>::type, TName, TPriority, TCtor>;
return dependency{static_cast<T &&>(object)};
}
template <class TConcept, class T,
__BOOST_DI_REQUIRES(externable<T>::value &&
!aux::is_callable<T>::value) = 0,
__BOOST_DI_REQUIRES_MSG(
concepts::boundable<deduce_traits_t<TExpected, T>,
aux::decay_t<T>, aux::valid<>>) = 0>
auto to(T &&object) noexcept {
using dependency =
dependency<scopes::instance,
deduce_traits_t<concepts::any_of<TExpected, TConcept>, T>,
typename ref_traits<T>::type, TName, TPriority, TCtor>;
return dependency{static_cast<T &&>(object)};
}
template <class TConcept, class T,
__BOOST_DI_REQUIRES(
externable<T>::value &&aux::is_callable<T>::value) = 0>
auto to(T &&object) noexcept {
using dependency =
dependency<scopes::instance,
deduce_traits_t<concepts::any_of<TExpected, TConcept>, T>,
typename ref_traits<T>::type, TName, TPriority, TCtor>;
return dependency{static_cast<T &&>(object)};
}
template <class T, class... Ts,
__BOOST_DI_REQUIRES(!aux::is_array<TExpected, T>::value) = 0>
auto to(Ts &&... args) noexcept {
return to_impl<T>(aux::make_index_sequence<sizeof...(Ts)>{},
static_cast<Ts &&>(args)...);
}
template <template <class...> class T> auto to() noexcept {
return dependency<TScope, TExpected, aux::identity<T<>>, TName, TPriority,
TCtor>{};
}
template <class...> dependency &to(...) const noexcept;
auto operator[](const override &) noexcept {
return dependency<TScope, TExpected, TGiven, TName, override>{
static_cast<dependency &&>(*this)};
}
#if defined(__cpp_variable_templates)
dependency &operator()() noexcept { return *this; }
#endif
template <class... Ts,
__BOOST_DI_REQUIRES(sizeof...(Ts) &&
!aux::is_array<TExpected, Ts...>::value) = 0>
auto operator()(Ts &&... args) noexcept {
return to_impl<TExpected>(aux::make_index_sequence<sizeof...(Ts)>{},
static_cast<Ts &&>(args)...);
}
protected:
using scope_t::create;
using scope_t::is_referable;
using scope_t::try_create;
template <class, class> static void try_create(...);
private:
template <class T, int... Ns, class... Ts>
auto to_impl(aux::index_sequence<Ns...>, Ts &&... args) noexcept {
using ctor_t = core::pool_t<ctor_arg_traits<T, Ns, Ts>...>;
using dependency =
dependency<TScope, TExpected, T, TName, TPriority, ctor_t>;
return dependency{
ctor_t{ctor_arg_traits<T, Ns, Ts>(static_cast<Ts &&>(args))...}};
}
};
} // namespace core
namespace concepts {
struct call_operator_with_one_argument {};
template <class> struct policy {
template <class> struct requires_ : aux::false_type {};
};
struct arg_wrapper {
using type = _;
using expected = _;
using given = _;
using name = no_name;
using arity = aux::integral_constant<int, 0>;
using scope = scopes::deduce;
using is_root = aux::false_type;
template <class, class, class> struct resolve;
};
aux::false_type callable_impl(...);
template <class T, class TArg>
auto callable_impl(const T &&t, TArg &&arg)
-> aux::is_valid_expr<decltype(t(arg))>;
template <class...> struct is_callable_impl;
template <class T, class... Ts> struct is_callable_impl<T, Ts...> {
using callable_with_arg =
decltype(callable_impl(aux::declval<T>(), arg_wrapper{}));
using type = aux::conditional_t<
callable_with_arg::value, typename is_callable_impl<Ts...>::type,
typename policy<T>::template requires_<call_operator_with_one_argument>>;
};
template <> struct is_callable_impl<> : aux::true_type {};
template <class... Ts> struct is_callable : is_callable_impl<Ts...> {};
template <class... Ts>
struct is_callable<core::pool<aux::type_list<Ts...>>>
: is_callable_impl<Ts...> {};
template <> struct is_callable<void> {
using type = policy<void>::requires_<call_operator_with_one_argument>;
};
template <class... Ts> using callable = typename is_callable<Ts...>::type;
} // namespace concepts
namespace providers {
class stack_over_heap {
public:
template <class TInitialization, class T, class... TArgs>
struct is_creatable {
static constexpr auto value =
concepts::creatable<TInitialization, T, TArgs...>::value;
};
template <class T, class... TArgs>
auto get(const type_traits::direct &, const type_traits::heap &,
TArgs &&... args) const {
return new T(static_cast<TArgs &&>(args)...);
}
template <class T, class... TArgs>
auto get(const type_traits::uniform &, const type_traits::heap &,
TArgs &&... args) const {
return new T{static_cast<TArgs &&>(args)...};
}
template <class T, class... TArgs>
auto get(const type_traits::direct &, const type_traits::stack &,
TArgs &&... args) const {
return T(static_cast<TArgs &&>(args)...);
}
template <class T, class... TArgs>
auto get(const type_traits::uniform &, const type_traits::stack &,
TArgs &&... args) const {
return T{static_cast<TArgs &&>(args)...};
}
};
} // namespace providers
namespace scopes {
class singleton {
template <class T, class = decltype(aux::has_shared_ptr__(aux::declval<T>()))>
class scope_impl {
public:
template <class T_, class>
using is_referable =
typename wrappers::shared<singleton, T &>::template is_referable<T_>;
template <class, class, class TProvider>
static decltype(wrappers::shared<singleton, T &>{
aux::declval<TProvider>().get(type_traits::stack{})})
try_create(const TProvider &);
template <class, class, class TProvider>
auto create(const TProvider &provider) {
return create_impl(provider);
}
private:
template <class TProvider>
wrappers::shared<singleton, T &> create_impl(const TProvider &provider) {
static auto object(provider.get(type_traits::stack{}));
return wrappers::shared<singleton, T &>(object);
}
};
template <class T> class scope_impl<T, aux::true_type> {
public:
template <class T_, class>
using is_referable =
typename wrappers::shared<singleton, T>::template is_referable<T_>;
template <
class, class, class TProvider,
class T_ = aux::decay_t<decltype(aux::declval<TProvider>().get())>>
static decltype(wrappers::shared<singleton, T_>{std::shared_ptr<T_>{
std::shared_ptr<T_>{aux::declval<TProvider>().get()}}})
try_create(const TProvider &);
template <class, class, class TProvider>
auto create(const TProvider &provider) {
return create_impl<aux::decay_t<decltype(provider.get())>>(provider);
}
private:
template <class T_, class TProvider>
auto create_impl(const TProvider &provider) {
static std::shared_ptr<T_> object{provider.get()};
return wrappers::shared<singleton, T_, std::shared_ptr<T_> &>{object};
}
};
public:
template <class, class T> using scope = scope_impl<T>;
};
} // namespace scopes
static constexpr __BOOST_DI_UNUSED scopes::singleton singleton{};
namespace scopes {
class unique {
public:
template <class, class> class scope {
public:
template <class...> using is_referable = aux::false_type;
template <class T, class, class TProvider>
static decltype(
wrappers::unique<unique, decltype(aux::declval<TProvider>().get(
typename TProvider::config::
template memory_traits<T>::type{}))>{
aux::declval<TProvider>().get(
typename TProvider::config::template memory_traits<T>::type{})})
try_create(const TProvider &);
template <class T, class, class TProvider>
auto create(const TProvider &provider) const {
using memory =
typename TProvider::config::template memory_traits<T>::type;
using wrapper =
wrappers::unique<unique, decltype(provider.get(memory{}))>;
return wrapper{provider.get(memory{})};
}
};
};
} // namespace scopes
static constexpr __BOOST_DI_UNUSED scopes::unique unique{};
namespace type_traits {
template <class T> struct scope_traits { using type = scopes::unique; };
template <class T> struct scope_traits<T &> { using type = scopes::singleton; };
template <class T> struct scope_traits<std::shared_ptr<T>> {
using type = scopes::singleton;
};
template <class T> struct scope_traits<boost::shared_ptr<T>> {
using type = scopes::singleton;
};
template <class T> struct scope_traits<std::weak_ptr<T>> {
using type = scopes::singleton;
};
} // namespace type_traits
#if !defined(BOOST_DI_CFG)
#define BOOST_DI_CFG ::boost::ext::di::v1_2_0::config
#endif
template <class... TPolicies,
__BOOST_DI_REQUIRES_MSG(concepts::callable<TPolicies...>) = 0>
inline auto make_policies(TPolicies... args) noexcept {
return core::pool_t<TPolicies...>(static_cast<TPolicies &&>(args)...);
}
struct config {
template <class T> auto provider(T *) noexcept {
return providers::stack_over_heap{};
}
template <class T> auto policies(T *) noexcept { return make_policies(); }
template <class T> using scope_traits = type_traits::scope_traits<T>;
template <class T> using memory_traits = type_traits::memory_traits<T>;
};
namespace detail {
template <class...> struct bind;
template <class TScope> struct bind<int, TScope> {
using type = core::dependency<TScope>;
};
template <class TScope, class T> struct bind<int, TScope, T> {
using type = core::dependency<TScope, T>;
};
template <class TScope, class... Ts> struct bind<int, TScope, Ts...> {
using type = core::dependency<TScope, concepts::any_of<Ts...>>;
};
} // namespace detail
template <class... Ts>
#if defined(__cpp_variable_templates)
typename
#else
struct bind :
#endif
detail::bind<__BOOST_DI_REQUIRES_MSG(
concepts::boundable<concepts::any_of<Ts...>>),
scopes::deduce, Ts...>::type
#if defined(__cpp_variable_templates)
bind
#endif
{};
static constexpr __BOOST_DI_UNUSED core::override override{};
namespace concepts {
struct get {};
struct is_creatable {};
template <class> struct provider {
template <class...> struct requires_ : aux::false_type {};
};
template <class T>
typename provider<T>::template requires_<get, is_creatable>
providable_impl(...);
template <class T>
auto providable_impl(T &&t) -> aux::is_valid_expr<
decltype(t.template get<_>(type_traits::direct{}, type_traits::heap{})),
decltype(t.template get<_>(type_traits::direct{}, type_traits::heap{},
int{})),
decltype(t.template get<_>(type_traits::uniform{}, type_traits::stack{})),
decltype(t.template get<_>(type_traits::uniform{}, type_traits::stack{},
int{})),
decltype(T::template is_creatable<type_traits::direct, type_traits::heap,
_>::value),
decltype(T::template is_creatable<type_traits::uniform, type_traits::stack,
_, int>::value)>;
template <class T> struct providable__ {
using type = decltype(providable_impl<T>(aux::declval<T>()));
};
template <class T> using providable = typename providable__<T>::type;
} // namespace concepts
namespace concepts {
template <class> struct policies {};
struct providable_type {};
struct callable_type {};
template <class> struct config {
template <class...> struct requires_ : aux::false_type {};
};
template <class TConfig> struct injector {
using config = TConfig;
using deps = aux::type_list<>;
template <class T> T create() const;
};
aux::false_type configurable_impl(...);
template <class T>
auto configurable_impl(T &&) -> aux::is_valid_expr<
decltype(aux::declval<T>().provider((injector<T> *)0)),
decltype(aux::declval<T>().policies((injector<T> *)0))>;
template <class T1, class T2>
struct get_configurable_error : aux::type_list<T1, T2> {};
template <class T> struct get_configurable_error<aux::true_type, T> {
using type = T;
};
template <class T> struct get_configurable_error<T, aux::true_type> {
using type = T;
};
template <>
struct get_configurable_error<aux::true_type, aux::true_type> : aux::true_type {
};
template <class T> auto is_configurable(const aux::true_type &) {
return typename get_configurable_error<
decltype(
providable<decltype(aux::declval<T>().provider((injector<T> *)0))>()),
decltype(callable<decltype(
aux::declval<T>().policies((injector<T> *)0))>())>::type{};
}
template <class T> auto is_configurable(const aux::false_type &) {
return typename config<T>::template requires_<provider<providable_type(...)>,
policies<callable_type(...)>>{};
}
template <class T> struct configurable__ {
using type = decltype(
is_configurable<T>(decltype(configurable_impl(aux::declval<T>())){}));
};
template <class T> using configurable = typename configurable__<T>::type;
} // namespace concepts
namespace core {
struct binder {
template <class TDefault, class> static TDefault resolve_impl(...) noexcept {
return {};
}
template <class, class TConcept, class TDependency>
static decltype(auto)
resolve_impl(aux::pair<TConcept, TDependency> *dep) noexcept {
return static_cast<TDependency &>(*dep);
}
template <class, class TConcept, class TScope, class TExpected, class TGiven,
class TName, class TCtor,
template <class, class, class, class, class, class>
class TDependency>
static decltype(auto) resolve_impl(
aux::pair<TConcept,
TDependency<TScope, TExpected, TGiven, TName, override, TCtor>>
*dep) noexcept {
return static_cast<
TDependency<TScope, TExpected, TGiven, TName, override, TCtor> &>(*dep);
}
template <class TDefault, class> static TDefault resolve_impl__(...);
template <class, class TConcept, class TDependency>
static TDependency resolve_impl__(aux::pair<TConcept, TDependency> *);
template <class, class TConcept, class TScope, class TExpected, class TGiven,
class TName, class TCtor,
template <class, class, class, class, class, class>
class TDependency>
static dependency<TScope, TExpected, TGiven, TName, override, TCtor>
resolve_impl__(aux::pair<TConcept, TDependency<TScope, TExpected, TGiven,
TName, override, TCtor>> *);
template <class TDeps, class T, class TName, class TDefault>
struct resolve__ {
using type = decltype(
resolve_impl__<TDefault, dependency_concept<aux::decay_t<T>, TName>>(
(TDeps *)0));
};
#if (defined(__CLANG__) && __CLANG__ >= 3'9) //
template <class TDeps, class T>
static T &resolve_(TDeps *deps, const aux::type<T &> &) noexcept {
return static_cast<T &>(*deps);
}
template <class TDeps, class T>
static T resolve_(TDeps *, const aux::type<T> &) noexcept {
return {};
}
#endif
template <class, class T> struct resolve_template_impl { using type = T; };
template <class TDeps, template <class...> class T, class... Ts>
struct resolve_template_impl<TDeps, aux::identity<T<Ts...>>> {
using type = T<typename resolve_template_impl<
TDeps,
aux::remove_qualifiers_t<typename resolve__<
TDeps, Ts, no_name, dependency<scopes::deduce, aux::decay_t<Ts>>>::
type::given>>::type...>;
};
template <class T, class TName = no_name,
class TDefault = dependency<scopes::deduce, aux::decay_t<T>>,
class TDeps>
static decltype(auto) resolve(TDeps *deps) noexcept {
using dependency = dependency_concept<aux::decay_t<T>, TName>;
#if (defined(__CLANG__) && __CLANG__ >= 3'9) //
return resolve_(
deps,
aux::type<decltype(resolve_impl<TDefault, dependency>((TDeps *)0))>{});
#else
return resolve_impl<TDefault, dependency>(deps);
#endif
}
template <class TDeps, class T, class TName = no_name,
class TDefault = dependency<scopes::deduce, aux::decay_t<T>>>
using resolve_t = typename resolve__<TDeps, T, TName, TDefault>::type;
template <class TDeps, class T>
using resolve_template_t =
typename resolve_template_impl<TDeps, aux::remove_qualifiers_t<T>>::type;
};
} // namespace core
namespace core {
template <class T, class TInjector, class TError = aux::false_type>
struct is_referable__ {
static constexpr auto value =
dependency__<binder::resolve_t<TInjector, T>>::template is_referable<
T, typename TInjector::config>::value;
};
template <class T, class TInjector>
struct is_referable__<T, TInjector, aux::true_type> {
static constexpr auto value = true;
};
template <class T, class TInjector, class TError> struct is_creatable__ {
static constexpr auto value =
injector__<TInjector>::template is_creatable<T>::value;
};
template <class T, class TInjector>
struct is_creatable__<T, TInjector, aux::false_type> {
static constexpr auto value = true;
};
template <class, class> struct is_copy_ctor__ : aux::false_type {};
template <class T> struct is_copy_ctor__<T, T> : aux::true_type {};
template <class T> struct is_copy_ctor__<T, const T> : aux::true_type {};
template <class TParent, class TInjector, class TError = aux::false_type>
struct any_type {
template <class T, class = __BOOST_DI_REQUIRES(
is_creatable__<T, TInjector, TError>::value)>
operator T() {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_impl(aux::type<T>{});
}
const TInjector &injector_;
};
template <class TParent, class TInjector, class TError = aux::false_type,
class TRefError = aux::false_type>
struct any_type_ref {
template <class T, class = __BOOST_DI_REQUIRES(
is_creatable__<T, TInjector, TError>::value)>
operator T() {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_impl(aux::type<T>{});
}
template <class T,
class = __BOOST_DI_REQUIRES(
is_referable__<T &&, TInjector, TRefError>::value),
class = __BOOST_DI_REQUIRES(
is_creatable__<T &&, TInjector, TError>::value)>
operator T &&() const {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_impl(aux::type<T &&>{});
}
template <class T,
class = __BOOST_DI_REQUIRES(
is_referable__<T &, TInjector, TRefError>::value),
class = __BOOST_DI_REQUIRES(
is_creatable__<T &, TInjector, TError>::value)>
operator T &() const {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_impl(aux::type<T &>{});
}
template <class T,
class = __BOOST_DI_REQUIRES(
is_referable__<const T &, TInjector, TRefError>::value),
class = __BOOST_DI_REQUIRES(
is_creatable__<const T &, TInjector, TError>::value)>
operator const T &() const {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_impl(aux::type<const T &>{});
}
const TInjector &injector_;
};
template <class TParent, class TInjector, class TError = aux::false_type>
struct any_type_1st {
template <
class T, class = __BOOST_DI_REQUIRES(!is_copy_ctor__<TParent, T>::value),
class = __BOOST_DI_REQUIRES(is_creatable__<T, TInjector, TError>::value)>
operator T() {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_impl(aux::type<T>{});
}
const TInjector &injector_;
};
template <class TParent, class TInjector, class TError = aux::false_type,
class TRefError = aux::false_type>
struct any_type_1st_ref {
template <
class T, class = __BOOST_DI_REQUIRES(!is_copy_ctor__<TParent, T>::value),
class = __BOOST_DI_REQUIRES(is_creatable__<T, TInjector, TError>::value)>
operator T() {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_impl(aux::type<T>{});
}
template <class T,
class = __BOOST_DI_REQUIRES(!is_copy_ctor__<TParent, T>::value),
class = __BOOST_DI_REQUIRES(
is_referable__<T &&, TInjector, TRefError>::value),
class = __BOOST_DI_REQUIRES(
is_creatable__<T &&, TInjector, TError>::value)>
operator T &&() const {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_impl(aux::type<T &&>{});
}
template <class T,
class = __BOOST_DI_REQUIRES(!is_copy_ctor__<TParent, T>::value),
class = __BOOST_DI_REQUIRES(
is_referable__<T &, TInjector, TRefError>::value),
class = __BOOST_DI_REQUIRES(
is_creatable__<T &, TInjector, TError>::value)>
operator T &() const {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_impl(aux::type<T &>{});
}
template <class T,
class = __BOOST_DI_REQUIRES(!is_copy_ctor__<TParent, T>::value),
class = __BOOST_DI_REQUIRES(
is_referable__<const T &, TInjector, TRefError>::value),
class = __BOOST_DI_REQUIRES(
is_creatable__<const T &, TInjector, TError>::value)>
operator const T &() const {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_impl(aux::type<const T &>{});
}
const TInjector &injector_;
};
namespace successful {
template <class TParent, class TInjector> struct any_type {
template <class T> operator T() {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_successful_impl(aux::type<T>{});
}
const TInjector &injector_;
};
template <class TParent, class TInjector> struct any_type_ref {
template <class T> operator T() {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_successful_impl(aux::type<T>{});
}
template <class T,
class = __BOOST_DI_REQUIRES(is_referable__<T &&, TInjector>::value)>
operator T &&() const {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_successful_impl(aux::type<T &&>{});
}
template <class T,
class = __BOOST_DI_REQUIRES(is_referable__<T &, TInjector>::value)>
operator T &() const {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_successful_impl(aux::type<T &>{});
}
template <class T, class = __BOOST_DI_REQUIRES(
is_referable__<const T &, TInjector>::value)>
operator const T &() const {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_successful_impl(aux::type<const T &>{});
}
const TInjector &injector_;
};
template <class TParent, class TInjector> struct any_type_1st {
template <class T,
class = __BOOST_DI_REQUIRES(!is_copy_ctor__<TParent, T>::value)>
operator T() {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_successful_impl(aux::type<T>{});
}
const TInjector &injector_;
};
template <class TParent, class TInjector> struct any_type_1st_ref {
template <class T,
class = __BOOST_DI_REQUIRES(!is_copy_ctor__<TParent, T>::value)>
operator T() {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_successful_impl(aux::type<T>{});
}
template <class T,
class = __BOOST_DI_REQUIRES(!is_copy_ctor__<TParent, T>::value),
class = __BOOST_DI_REQUIRES(is_referable__<T &&, TInjector>::value)>
operator T &&() const {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_successful_impl(aux::type<T &&>{});
}
template <class T,
class = __BOOST_DI_REQUIRES(!is_copy_ctor__<TParent, T>::value),
class = __BOOST_DI_REQUIRES(is_referable__<T &, TInjector>::value)>
operator T &() const {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_successful_impl(aux::type<T &>{});
}
template <
class T, class = __BOOST_DI_REQUIRES(!is_copy_ctor__<TParent, T>::value),
class = __BOOST_DI_REQUIRES(is_referable__<const T &, TInjector>::value)>
operator const T &() const {
return static_cast<const core::injector__<TInjector> &>(injector_)
.create_successful_impl(aux::type<const T &>{});
}
const TInjector &injector_;
};
} // namespace successful
template <class> struct any_type_fwd {
template <class T> operator T();
private:
template <class T> operator const T &() const;
};
template <class> struct any_type_ref_fwd {
template <class T> operator T();
template <class T> operator T &() const;
template <class T> operator T &&() const;
template <class T> operator const T &() const;
};
template <class TParent> struct any_type_1st_fwd {
template <class T,
class = __BOOST_DI_REQUIRES(!is_copy_ctor__<TParent, T>::value)>
operator T();
private:
template <class T,
class = __BOOST_DI_REQUIRES(!is_copy_ctor__<TParent, T>::value)>
operator const T &() const;
};
template <class TParent> struct any_type_1st_ref_fwd {
template <class T,
class = __BOOST_DI_REQUIRES(!is_copy_ctor__<TParent, T>::value)>
operator T();
template <class T,
class = __BOOST_DI_REQUIRES(!is_copy_ctor__<TParent, T>::value)>
operator T &() const;
template <class T,
class = __BOOST_DI_REQUIRES(!is_copy_ctor__<TParent, T>::value)>
operator T &&() const;
template <class T,
class = __BOOST_DI_REQUIRES(!is_copy_ctor__<TParent, T>::value)>
operator const T &() const;
};
} // namespace core
namespace core {
template <class...> struct arg_wrapper;
template <class T, class TName, class TIsRoot, template <class...> class TList,
class... TCtor, class TDependency, class TDeps>
struct arg_wrapper<T, TName, TIsRoot, TList<TCtor...>, TDependency, TDeps> {
using type __BOOST_DI_UNUSED = T;
using expected __BOOST_DI_UNUSED = typename TDependency::expected;
using given __BOOST_DI_UNUSED = typename TDependency::given;
using name __BOOST_DI_UNUSED = TName;
using arity __BOOST_DI_UNUSED = aux::integral_constant<int, sizeof...(TCtor)>;
using scope __BOOST_DI_UNUSED = typename TDependency::scope;
using is_root __BOOST_DI_UNUSED = TIsRoot;
template <class T_, class TName_, class TDefault_>
using resolve =
decltype(core::binder::resolve<T_, TName_, TDefault_>((TDeps *)0));
};
template <class T> struct allow_void : T {};
template <> struct allow_void<void> : aux::true_type {};
class policy {
template <class TArg, class TPolicy, class TPolicies,
__BOOST_DI_REQUIRES(
!aux::is_base_of<_, aux::remove_reference_t<
typename TArg::type>>::value) = 0>
static void call_impl(const TPolicies &policies) noexcept {
static_cast<const TPolicy &>(policies)(TArg{});
}
template <class TArg, class, class TPolicies,
__BOOST_DI_REQUIRES(
aux::is_base_of<_, aux::remove_reference_t<
typename TArg::type>>::value) = 0>
static void call_impl(const TPolicies &) noexcept {}
template <class TArg, class TPolicy>
struct try_call_impl
: aux::conditional_t<aux::is_base_of<_, aux::remove_reference_t<
typename TArg::type>>::value,
aux::true_type,
allow_void<decltype((aux::declval<TPolicy>())(
aux::declval<TArg>()))>> {};
public:
template <class, class> struct try_call;
template <class TArg, class... TPolicies>
struct try_call<TArg, pool_t<TPolicies...>>
: aux::is_same<aux::bool_list<aux::always<TPolicies>::value...>,
aux::bool_list<try_call_impl<TArg, TPolicies>::value...>> {
};
template <class TArg, class... TPolicies>
static void
call(__BOOST_DI_UNUSED const pool_t<TPolicies...> &policies) noexcept {
(void)aux::swallow{0, (call_impl<TArg, TPolicies>(policies), 0)...};
}
};
} // namespace core
namespace core {
#if (BOOST_DI_CFG_DIAGNOSTICS_LEVEL >= 2)
template <class T> struct creating {
creating() { type(); }
static inline T type(_ = "creating...");
};
#endif
template <class, class, class> struct try_provider;
template <class T, class TInjector, class TProvider, class TInitialization,
template <class...> class TList, class... TCtor>
struct try_provider<aux::pair<T, aux::pair<TInitialization, TList<TCtor...>>>,
TInjector, TProvider> {
using injector = TInjector;
using config = typename TInjector::config;
template <class> struct is_creatable {
static constexpr auto value = TProvider::template is_creatable<
TInitialization, T,
typename injector__<TInjector>::template try_create<TCtor>::type...>::
value;
};
template <class TMemory = type_traits::heap>
auto get(const TMemory & = {}) const -> aux::enable_if_t<
is_creatable<TMemory>::value,
aux::conditional_t<aux::is_same<TMemory, type_traits::stack>::value, T,
aux::remove_reference_t<T> *>>;
};
template <class, class, class> struct provider;
template <class T, class TName, class TInjector, class TInitialization,
template <class...> class TList, class... TCtor>
struct provider<aux::pair<T, aux::pair<TInitialization, TList<TCtor...>>>,
TName, TInjector> {
using injector = TInjector;
using config = typename TInjector::config;
template <class, class... TArgs> struct is_creatable {
using type = decltype(
aux::declval<injector__<TInjector>>().cfg().provider((TInjector *)0));
static constexpr auto value =
type::template is_creatable<TInitialization, T, TArgs...>::value;
};
template <class TMemory = type_traits::heap>
auto get(const TMemory &memory = {}) const {
return get_impl(memory, ((const injector__<TInjector> *)injector_)
->create_impl(aux::type<TCtor>{})...);
}
template <class TMemory, class... TArgs,
__BOOST_DI_REQUIRES(is_creatable<TMemory, TArgs...>::value) = 0>
auto get_impl(const TMemory &memory, TArgs &&... args) const {
#if (BOOST_DI_CFG_DIAGNOSTICS_LEVEL >= 2)
(void)aux::conditional_t<
injector__<TInjector>::template is_creatable<T>::value, _,
creating<T>>{};
#endif
return cfg().provider(injector_).template get<T>(
TInitialization{}, memory, static_cast<TArgs &&>(args)...);
}
template <class TMemory, class... TArgs,
__BOOST_DI_REQUIRES(!is_creatable<TMemory, TArgs...>::value) = 0>
auto get_impl(const TMemory &, TArgs &&...) const {
#if (BOOST_DI_CFG_DIAGNOSTICS_LEVEL > 0)
return concepts::creatable_error<TInitialization, TName, T *, TArgs...>();
#else
return nullptr;
#endif
}
auto &super() const { return *injector_; }
auto &cfg() const { return ((injector__<TInjector> *)injector_)->cfg(); }
const TInjector *injector_;
};
namespace successful {
template <class, class> struct provider;
template <class T, class TInjector, class TInitialization,
template <class...> class TList, class... TCtor>
struct provider<aux::pair<T, aux::pair<TInitialization, TList<TCtor...>>>,
TInjector> {
using injector = TInjector;
using config = typename TInjector::config;
template <class TMemory = type_traits::heap>
auto get(const TMemory &memory = {}) const {
return cfg().provider(injector_).template get<T>(
TInitialization{}, memory,
((const injector__<TInjector> *)injector_)
->create_successful_impl(aux::type<TCtor>{})...);
}
auto &super() const { return *injector_; }
auto &cfg() const { return ((injector__<TInjector> *)injector_)->cfg(); }
const TInjector *injector_;
};
} // namespace successful
} // namespace core
namespace core {
namespace successful {
template <class T, class TWrapper> struct wrapper {
inline operator T() noexcept { return wrapper_; }
TWrapper wrapper_;
};
} // namespace successful
template <class T, class TWrapper, class = int> struct wrapper_impl {
inline operator T() noexcept { return wrapper_; }
TWrapper wrapper_;
};
template <class T, template <class...> class TWrapper, class TScope, class T_,
class... Ts>
struct wrapper_impl<
T, TWrapper<TScope, T_, Ts...>,
__BOOST_DI_REQUIRES(
!aux::is_convertible<TWrapper<TScope, T_, Ts...>, T>::value)> {
inline operator T() noexcept {
return typename concepts::scoped<TScope, aux::remove_qualifiers_t<T_>>::
template is_not_convertible_to<T>{};
}
TWrapper<TScope, T_, Ts...> wrapper_;
};
template <class T, class TWrapper> using wrapper = wrapper_impl<T, TWrapper>;
} // namespace core
namespace core {
struct from_injector {};
struct from_deps {};
struct init {};
struct with_error {};
template <class T, class, class> struct referable { using type = T; };
template <class T, class TConfig, class TDependency>
struct referable<T &, TConfig, TDependency> {
using type = aux::conditional_t<
TDependency::template is_referable<T &, TConfig>::value, T &, T>;
};
template <class T, class TConfig, class TDependency>
struct referable<const T &, TConfig, TDependency> {
using type = aux::conditional_t<
TDependency::template is_referable<const T &, TConfig>::value, const T &,
T>;
};
#if defined(__MSVC__)
template <class T, class TConfig, class TDependency>
struct referable<T &&, TConfig, TDependency> {
using type = aux::conditional_t<
TDependency::template is_referable<T &&, TConfig>::value, T &&, T>;
};
#endif
template <class T, class TConfig, class TDependency>
using referable_t = typename referable<T, TConfig, TDependency>::type;
#if defined(__MSVC__)
template <class T, class TInjector>
inline auto build(TInjector &&injector) noexcept {
return T{static_cast<TInjector &&>(injector)};
}
#endif
template <class TConfig, class TPolicies = pool<>, class... TDeps>
class injector : public injector_base, public pool<bindings_t<TDeps...>> {
using pool_t = pool<bindings_t<TDeps...>>;
protected:
template <class T, class TName = no_name, class TIsRoot = aux::false_type>
struct is_creatable {
using dependency_t = binder::resolve_t<injector, T, TName>;
using ctor_t = typename type_traits::ctor_traits__<
binder::resolve_template_t<injector, typename dependency_t::given>, T,
typename dependency_t::ctor>::type;
using ctor_args_t = typename ctor_t::second::second;
static constexpr auto value =
aux::is_convertible<
decltype(dependency__<dependency_t>::template try_create<T, TName>(
try_provider<ctor_t, injector,
decltype(aux::declval<TConfig>().provider(
(injector *)0))>{})),
T>::value &&
policy::template try_call<
arg_wrapper<T, TName, TIsRoot, ctor_args_t, dependency_t, pool_t>,
TPolicies>::value;
};
auto &cfg() { return config_; }
const auto &cfg() const { return config_; }
public:
using deps = bindings_t<TDeps...>;
using config = TConfig;
injector(injector &&) = default;
template <class... TArgs>
explicit injector(const init &, TArgs... args) noexcept
: injector{from_deps{}, static_cast<TArgs &&>(args)...} {}
template <class TConfig_, class TPolicies_, class... TDeps_>
explicit injector(injector<TConfig_, TPolicies_, TDeps_...> &&other) noexcept
: injector{
from_injector{},
static_cast<injector<TConfig_, TPolicies_, TDeps_...> &&>(other),
deps{}} {}
template <class T> injector &operator=(T &&other) noexcept {
static_cast<pool_t &>(*this).operator=(static_cast<T &&>(other));
return *this;
}
template <class T, __BOOST_DI_REQUIRES(
is_creatable<T, no_name, aux::true_type>::value) = 0>
T create() const {
return __BOOST_DI_TYPE_WKND(T)
create_successful_impl<aux::true_type>(aux::type<T>{});
}
template <class T, __BOOST_DI_REQUIRES(
!is_creatable<T, no_name, aux::true_type>::value) = 0>
__BOOST_DI_DEPRECATED("creatable constraint not satisfied")
T
// clang-format off
create
// clang-format on
() const {
return __BOOST_DI_TYPE_WKND(T) create_impl<aux::true_type>(aux::type<T>{});
}
template <
template <class...> class T,
class R = binder::resolve_template_t<injector, aux::identity<T<>>>,
__BOOST_DI_REQUIRES(is_creatable<R, no_name, aux::true_type>::value) = 0>
R
// clang-format off
create()
// clang-format on
const {
return __BOOST_DI_TYPE_WKND(R)
create_successful_impl<aux::true_type>(aux::type<R>{});
}
template <
template <class...> class T,
class R = binder::resolve_template_t<injector, aux::identity<T<>>>,
__BOOST_DI_REQUIRES(!is_creatable<R, no_name, aux::true_type>::value) = 0>
__BOOST_DI_DEPRECATED("creatable constraint not satisfied")
R
// clang-format off
create()
// clang-format on
const {
return __BOOST_DI_TYPE_WKND(R) create_impl<aux::true_type>(aux::type<R>{});
}
protected:
template <class T> struct try_create {
using type = aux::conditional_t<is_creatable<T>::value, T, void>;
};
template <class TParent> struct try_create<any_type_fwd<TParent>> {
using type = any_type<TParent, injector, with_error>;
};
template <class TParent> struct try_create<any_type_ref_fwd<TParent>> {
using type = any_type_ref<TParent, injector, with_error>;
};
template <class TParent> struct try_create<any_type_1st_fwd<TParent>> {
using type = any_type_1st<TParent, injector, with_error>;
};
template <class TParent> struct try_create<any_type_1st_ref_fwd<TParent>> {
using type = any_type_1st_ref<TParent, injector, with_error>;
};
template <class TName, class T>
struct try_create<::boost::ext::di::v1_2_0::named<TName, T>> {
using type = aux::conditional_t<is_creatable<T, TName>::value, T, void>;
};
template <class TParent, int N, class T>
struct try_create<core::ctor_arg<TParent, N, T &&>> {
using type = aux::conditional_t<is_creatable<T>::value, T, void>;
};
template <class TParent, int N>
struct try_create<core::ctor_arg<TParent, N, const placeholders::arg &>> {
using type = any_type_1st_ref<TParent, injector, with_error>;
};
template <class T> struct try_create<self<T>> { using type = injector; };
template <class TIsRoot = aux::false_type, class T>
auto create_impl(const aux::type<T> &) const {
return create_impl__<TIsRoot, T>();
}
template <class TIsRoot = aux::false_type, class TParent>
auto create_impl(const aux::type<any_type_fwd<TParent>> &) const {
return any_type<TParent, injector>{*this};
}
template <class TIsRoot = aux::false_type, class TParent>
auto create_impl(const aux::type<any_type_ref_fwd<TParent>> &) const {
return any_type_ref<TParent, injector, aux::false_type, aux::true_type>{
*this};
}
template <class TIsRoot = aux::false_type, class TParent>
auto create_impl(const aux::type<any_type_1st_fwd<TParent>> &) const {
return any_type_1st<TParent, injector>{*this};
}
template <class TIsRoot = aux::false_type, class TParent>
auto create_impl(const aux::type<any_type_1st_ref_fwd<TParent>> &) const {
return any_type_1st_ref<TParent, injector, aux::false_type, aux::true_type>{
*this};
}
template <class TIsRoot = aux::false_type, class T, class TName>
auto create_impl(
const aux::type<::boost::ext::di::v1_2_0::named<TName, T>> &) const {
return create_impl__<TIsRoot, T, TName>();
}
template <class TIsRoot = aux::false_type, class TParent, int N, class T>
auto create_impl(const aux::type<core::ctor_arg<TParent, N, T>> &) const {
auto &dependency = binder::resolve<TParent>((injector *)this);
return static_cast<core::ctor_arg<TParent, N, T> &>(dependency);
}
template <class TIsRoot = aux::false_type, class TParent, int N>
auto create_impl(
const aux::type<core::ctor_arg<TParent, N, const placeholders::arg &>> &)
const {
return any_type_1st_ref<TParent, injector, aux::false_type, aux::true_type>{
*this};
}
template <class TIsRoot = aux::false_type, class T>
auto create_successful_impl(const aux::type<T> &) const {
return create_successful_impl__<TIsRoot, T>();
}
template <class TIsRoot = aux::false_type, class TParent>
auto create_successful_impl(const aux::type<any_type_fwd<TParent>> &) const {
return successful::any_type<TParent, injector>{*this};
}
template <class TIsRoot = aux::false_type, class TParent>
auto
create_successful_impl(const aux::type<any_type_ref_fwd<TParent>> &) const {
return successful::any_type_ref<TParent, injector>{*this};
}
template <class TIsRoot = aux::false_type, class TParent>
auto
create_successful_impl(const aux::type<any_type_1st_fwd<TParent>> &) const {
return successful::any_type_1st<TParent, injector>{*this};
}
template <class TIsRoot = aux::false_type, class TParent>
auto create_successful_impl(
const aux::type<any_type_1st_ref_fwd<TParent>> &) const {
return successful::any_type_1st_ref<TParent, injector>{*this};
}
template <class TIsRoot = aux::false_type, class T, class TName>
auto create_successful_impl(
const aux::type<::boost::ext::di::v1_2_0::named<TName, T>> &) const {
return create_successful_impl__<TIsRoot, T, TName>();
}
template <class TIsRoot = aux::false_type, class TParent, int N, class T>
auto create_successful_impl(
const aux::type<core::ctor_arg<TParent, N, T>> &) const {
auto &dependency = binder::resolve<TParent>((injector *)this);
return static_cast<core::ctor_arg<TParent, N, T> &>(dependency);
}
template <class TIsRoot = aux::false_type, class TParent, int N>
auto create_successful_impl(
const aux::type<core::ctor_arg<TParent, N, const placeholders::arg &>> &)
const {
return any_type_1st_ref<TParent, injector, aux::false_type, aux::true_type>{
*this};
}
template <class TIsRoot = aux::false_type, class T>
decltype(auto) create_successful_impl(const aux::type<self<T>> &) const {
return *this;
}
private:
explicit injector(const from_deps &) noexcept {}
template <class... TArgs>
explicit injector(const from_deps &, TArgs... args) noexcept
: pool_t{bindings_t<TArgs...>{},
core::pool_t<TArgs...>{static_cast<TArgs &&>(args)...}} {}
template <class TInjector, class... TArgs>
injector(const from_injector &, TInjector &&injector,
const aux::type_list<TArgs...> &) noexcept
#if defined(__MSVC__)
: pool_t {
bindings_t<TArgs...>{}, pool_t {
build<TArgs>(static_cast<TInjector &&>(injector))...
}
}
#else
: pool_t {
bindings_t<TArgs...>{}, pool_t {
TArgs{static_cast<TInjector &&>(injector)}...
}
}
#endif
{}
template <class TInjector>
injector(const from_injector &, TInjector &&,
const aux::type_list<> &) noexcept {}
template <class TIsRoot = aux::false_type, class T, class TName = no_name>
auto create_impl__() const {
auto &&dependency = binder::resolve<T, TName>((injector *)this);
using dependency_t =
typename aux::remove_reference<decltype(dependency)>::type;
using ctor_t = typename type_traits::ctor_traits__<
binder::resolve_template_t<injector, typename dependency_t::given>, T,
typename dependency_t::ctor>::type;
using provider_t = core::provider<ctor_t, TName, injector>;
auto &creatable_dept =
static_cast<dependency__<dependency_t> &>(dependency);
using wrapper_t =
decltype(creatable_dept.template create<T, TName>(provider_t{this}));
using ctor_args_t = typename ctor_t::second::second;
policy::template call<
arg_wrapper<T, TName, TIsRoot, ctor_args_t, dependency_t, pool_t>>(
((injector *)this)->cfg().policies(this));
return wrapper<T, wrapper_t>{
creatable_dept.template create<T, TName>(provider_t{this})};
}
template <class TIsRoot = aux::false_type, class T, class TName = no_name>
auto create_successful_impl__() const {
auto &&dependency = binder::resolve<T, TName>((injector *)this);
using dependency_t =
typename aux::remove_reference<decltype(dependency)>::type;
using ctor_t = typename type_traits::ctor_traits__<
binder::resolve_template_t<injector, typename dependency_t::given>, T,
typename dependency_t::ctor>::type;
using provider_t = successful::provider<ctor_t, injector>;
auto &creatable_dept =
static_cast<dependency__<dependency_t> &>(dependency);
using wrapper_t =
decltype(creatable_dept.template create<T, TName>(provider_t{this}));
using create_t = referable_t<T, config, dependency__<dependency_t>>;
using ctor_args_t = typename ctor_t::second::second;
policy::template call<
arg_wrapper<T, TName, TIsRoot, ctor_args_t, dependency_t, pool_t>>(
((injector *)this)->cfg().policies(this));
return successful::wrapper<create_t, wrapper_t>{
creatable_dept.template create<T, TName>(provider_t{this})};
}
config config_;
};
template <class TConfig, class... TDeps>
class injector<TConfig, pool<>, TDeps...> : public injector_base,
public pool<bindings_t<TDeps...>> {
using pool_t = pool<bindings_t<TDeps...>>;
protected:
template <class T, class TName = no_name, class TIsRoot = aux::false_type>
struct is_creatable {
using dependency_t = binder::resolve_t<injector, T, TName>;
using ctor_t = typename type_traits::ctor_traits__<
binder::resolve_template_t<injector, typename dependency_t::given>, T,
typename dependency_t::ctor>::type;
using ctor_args_t = typename ctor_t::second::second;
static constexpr auto value = aux::is_convertible<
decltype(dependency__<dependency_t>::template try_create<T, TName>(
try_provider<ctor_t, injector,
decltype(aux::declval<TConfig>().provider(
(injector *)0))>{})),
T>::value;
};
auto &cfg() { return config_; }
const auto &cfg() const { return config_; }
public:
using deps = bindings_t<TDeps...>;
using config = TConfig;
injector(injector &&) = default;
template <class... TArgs>
explicit injector(const init &, TArgs... args) noexcept
: injector{from_deps{}, static_cast<TArgs &&>(args)...} {}
template <class TConfig_, class TPolicies_, class... TDeps_>
explicit injector(injector<TConfig_, TPolicies_, TDeps_...> &&other) noexcept
: injector{
from_injector{},
static_cast<injector<TConfig_, TPolicies_, TDeps_...> &&>(other),
deps{}} {}
template <class T> injector &operator=(T &&other) noexcept {
static_cast<pool_t &>(*this).operator=(static_cast<T &&>(other));
return *this;
}
template <class T, __BOOST_DI_REQUIRES(
is_creatable<T, no_name, aux::true_type>::value) = 0>
T create() const {
return __BOOST_DI_TYPE_WKND(T)
create_successful_impl<aux::true_type>(aux::type<T>{});
}
template <class T, __BOOST_DI_REQUIRES(
!is_creatable<T, no_name, aux::true_type>::value) = 0>
__BOOST_DI_DEPRECATED("creatable constraint not satisfied")
T
// clang-format off
create
// clang-format on
() const {
return __BOOST_DI_TYPE_WKND(T) create_impl<aux::true_type>(aux::type<T>{});
}
template <
template <class...> class T,
class R = binder::resolve_template_t<injector, aux::identity<T<>>>,
__BOOST_DI_REQUIRES(is_creatable<R, no_name, aux::true_type>::value) = 0>
R
// clang-format off
create()
// clang-format on
const {
return __BOOST_DI_TYPE_WKND(R)
create_successful_impl<aux::true_type>(aux::type<R>{});
}
template <
template <class...> class T,
class R = binder::resolve_template_t<injector, aux::identity<T<>>>,
__BOOST_DI_REQUIRES(!is_creatable<R, no_name, aux::true_type>::value) = 0>
__BOOST_DI_DEPRECATED("creatable constraint not satisfied")
R
// clang-format off
create()
// clang-format on
const {
return __BOOST_DI_TYPE_WKND(R) create_impl<aux::true_type>(aux::type<R>{});
}
protected:
template <class T> struct try_create {
using type = aux::conditional_t<is_creatable<T>::value, T, void>;
};
template <class TParent> struct try_create<any_type_fwd<TParent>> {
using type = any_type<TParent, injector, with_error>;
};
template <class TParent> struct try_create<any_type_ref_fwd<TParent>> {
using type = any_type_ref<TParent, injector, with_error>;
};
template <class TParent> struct try_create<any_type_1st_fwd<TParent>> {
using type = any_type_1st<TParent, injector, with_error>;
};
template <class TParent> struct try_create<any_type_1st_ref_fwd<TParent>> {
using type = any_type_1st_ref<TParent, injector, with_error>;
};
template <class TName, class T>
struct try_create<::boost::ext::di::v1_2_0::named<TName, T>> {
using type = aux::conditional_t<is_creatable<T, TName>::value, T, void>;
};
template <class TParent, int N, class T>
struct try_create<core::ctor_arg<TParent, N, T &&>> {
using type = aux::conditional_t<is_creatable<T>::value, T, void>;
};
template <class TParent, int N>
struct try_create<core::ctor_arg<TParent, N, const placeholders::arg &>> {
using type = any_type_1st_ref<TParent, injector, with_error>;
};
template <class T> struct try_create<self<T>> { using type = injector; };
template <class TIsRoot = aux::false_type, class T>
auto create_impl(const aux::type<T> &) const {
return create_impl__<TIsRoot, T>();
}
template <class TIsRoot = aux::false_type, class TParent>
auto create_impl(const aux::type<any_type_fwd<TParent>> &) const {
return any_type<TParent, injector>{*this};
}
template <class TIsRoot = aux::false_type, class TParent>
auto create_impl(const aux::type<any_type_ref_fwd<TParent>> &) const {
return any_type_ref<TParent, injector, aux::false_type, aux::true_type>{
*this};
}
template <class TIsRoot = aux::false_type, class TParent>
auto create_impl(const aux::type<any_type_1st_fwd<TParent>> &) const {
return any_type_1st<TParent, injector>{*this};
}
template <class TIsRoot = aux::false_type, class TParent>
auto create_impl(const aux::type<any_type_1st_ref_fwd<TParent>> &) const {
return any_type_1st_ref<TParent, injector, aux::false_type, aux::true_type>{
*this};
}
template <class TIsRoot = aux::false_type, class T, class TName>
auto create_impl(
const aux::type<::boost::ext::di::v1_2_0::named<TName, T>> &) const {
return create_impl__<TIsRoot, T, TName>();
}
template <class TIsRoot = aux::false_type, class TParent, int N, class T>
auto create_impl(const aux::type<core::ctor_arg<TParent, N, T>> &) const {
auto &dependency = binder::resolve<TParent>((injector *)this);
return static_cast<core::ctor_arg<TParent, N, T> &>(dependency);
}
template <class TIsRoot = aux::false_type, class TParent, int N>
auto create_impl(
const aux::type<core::ctor_arg<TParent, N, const placeholders::arg &>> &)
const {
return any_type_1st_ref<TParent, injector, aux::false_type, aux::true_type>{
*this};
}
template <class TIsRoot = aux::false_type, class T>
auto create_successful_impl(const aux::type<T> &) const {
return create_successful_impl__<TIsRoot, T>();
}
template <class TIsRoot = aux::false_type, class TParent>
auto create_successful_impl(const aux::type<any_type_fwd<TParent>> &) const {
return successful::any_type<TParent, injector>{*this};
}
template <class TIsRoot = aux::false_type, class TParent>
auto
create_successful_impl(const aux::type<any_type_ref_fwd<TParent>> &) const {
return successful::any_type_ref<TParent, injector>{*this};
}
template <class TIsRoot = aux::false_type, class TParent>
auto
create_successful_impl(const aux::type<any_type_1st_fwd<TParent>> &) const {
return successful::any_type_1st<TParent, injector>{*this};
}
template <class TIsRoot = aux::false_type, class TParent>
auto create_successful_impl(
const aux::type<any_type_1st_ref_fwd<TParent>> &) const {
return successful::any_type_1st_ref<TParent, injector>{*this};
}
template <class TIsRoot = aux::false_type, class T, class TName>
auto create_successful_impl(
const aux::type<::boost::ext::di::v1_2_0::named<TName, T>> &) const {
return create_successful_impl__<TIsRoot, T, TName>();
}
template <class TIsRoot = aux::false_type, class TParent, int N, class T>
auto create_successful_impl(
const aux::type<core::ctor_arg<TParent, N, T>> &) const {
auto &dependency = binder::resolve<TParent>((injector *)this);
return static_cast<core::ctor_arg<TParent, N, T> &>(dependency);
}
template <class TIsRoot = aux::false_type, class TParent, int N>
auto create_successful_impl(
const aux::type<core::ctor_arg<TParent, N, const placeholders::arg &>> &)
const {
return any_type_1st_ref<TParent, injector, aux::false_type, aux::true_type>{
*this};
}
template <class TIsRoot = aux::false_type, class T>
decltype(auto) create_successful_impl(const aux::type<self<T>> &) const {
return *this;
}
private:
explicit injector(const from_deps &) noexcept {}
template <class... TArgs>
explicit injector(const from_deps &, TArgs... args) noexcept
: pool_t{bindings_t<TArgs...>{},
core::pool_t<TArgs...>{static_cast<TArgs &&>(args)...}} {}
template <class TInjector, class... TArgs>
injector(const from_injector &, TInjector &&injector,
const aux::type_list<TArgs...> &) noexcept
#if defined(__MSVC__)
: pool_t {
bindings_t<TArgs...>{}, pool_t {
build<TArgs>(static_cast<TInjector &&>(injector))...
}
}
#else
: pool_t {
bindings_t<TArgs...>{}, pool_t {
TArgs{static_cast<TInjector &&>(injector)}...
}
}
#endif
{}
template <class TInjector>
injector(const from_injector &, TInjector &&,
const aux::type_list<> &) noexcept {}
template <class TIsRoot = aux::false_type, class T, class TName = no_name>
auto create_impl__() const {
auto &&dependency = binder::resolve<T, TName>((injector *)this);
using dependency_t =
typename aux::remove_reference<decltype(dependency)>::type;
using ctor_t = typename type_traits::ctor_traits__<
binder::resolve_template_t<injector, typename dependency_t::given>, T,
typename dependency_t::ctor>::type;
using provider_t = core::provider<ctor_t, TName, injector>;
auto &creatable_dept =
static_cast<dependency__<dependency_t> &>(dependency);
using wrapper_t =
decltype(creatable_dept.template create<T, TName>(provider_t{this}));
return wrapper<T, wrapper_t>{
creatable_dept.template create<T, TName>(provider_t{this})};
}
template <class TIsRoot = aux::false_type, class T, class TName = no_name>
auto create_successful_impl__() const {
auto &&dependency = binder::resolve<T, TName>((injector *)this);
using dependency_t =
typename aux::remove_reference<decltype(dependency)>::type;
using ctor_t = typename type_traits::ctor_traits__<
binder::resolve_template_t<injector, typename dependency_t::given>, T,
typename dependency_t::ctor>::type;
using provider_t = successful::provider<ctor_t, injector>;
auto &creatable_dept =
static_cast<dependency__<dependency_t> &>(dependency);
using wrapper_t =
decltype(creatable_dept.template create<T, TName>(provider_t{this}));
using create_t = referable_t<T, config, dependency__<dependency_t>>;
return successful::wrapper<create_t, wrapper_t>{
creatable_dept.template create<T, TName>(provider_t{this})};
}
config config_;
};
} // namespace core
template <class T, class TInjector>
auto create(const TInjector &injector)
-> decltype(injector.template create<T>()) {
return injector.template create<T>();
}
template <template <class...> class T, class TInjector>
auto create(const TInjector &injector)
-> decltype(injector.template create<T>()) {
return injector.template create<T>();
}
template <class T, class TInjector>
constexpr auto is_creatable(const TInjector &) {
return core::injector__<TInjector>::template is_creatable<
T, no_name, aux::true_type>::value;
}
template <template <class...> class T, class TInjector>
constexpr auto is_creatable(const TInjector &) {
return core::injector__<TInjector>::template is_creatable<
core::binder::resolve_template_t<TInjector, aux::identity<T<>>>, no_name,
aux::true_type>::value;
}
namespace detail {
template <class> void create(const aux::true_type &) {}
// clang-format off
template <class>
__BOOST_DI_DEPRECATED("creatable constraint not satisfied") void
create
(const aux::false_type&) {}
// clang-format on
template <class, class, class...> struct injector;
template <class, class> struct is_creatable_impl;
template <class TInjector, class TName, class T>
struct is_creatable_impl<TInjector, named<TName, T>> {
static constexpr auto value =
core::injector__<TInjector>::template is_creatable<T, TName>::value;
};
template <class TConfig, class T, class... TGivens>
struct injector<
TConfig, int,
core::dependency<scopes::instance, T, aux::type_list<TGivens...>>>
: core::injector<
TConfig, core::pool<>,
core::dependency<scopes::instance, T, aux::type_list<TGivens...>>> {
template <class... Ts>
injector(core::injector<Ts...> &&injector) noexcept
: core::injector<
TConfig, core::pool<>,
core::dependency<scopes::instance, T, aux::type_list<TGivens...>>>(
static_cast<core::injector<Ts...> &&>(injector)) {
using injector_t = core::injector<Ts...>;
int _[]{0,
// clang-format off
(detail::
create<T> (
aux::integral_constant<bool, is_creatable_impl<injector_t, TGivens>::value>{}),
0)...};
// clang-format on
(void)_;
}
};
} // namespace detail
#if defined(__MSVC__)
template <class T, class... Ts>
struct injector
: detail::injector<
BOOST_DI_CFG,
__BOOST_DI_REQUIRES_MSG(concepts::boundable<aux::type<T, Ts...>>),
core::dependency<scopes::instance,
aux::unique_t<type_traits::named_decay_t<T>,
type_traits::named_decay_t<Ts>...>,
aux::type_list<type_traits::add_named_t<T>,
type_traits::add_named_t<Ts>...>>> {
using detail::injector<
BOOST_DI_CFG,
__BOOST_DI_REQUIRES_MSG(concepts::boundable<aux::type<T, Ts...>>),
core::dependency<scopes::instance,
aux::unique_t<type_traits::named_decay_t<T>,
type_traits::named_decay_t<Ts>...>,
aux::type_list<type_traits::add_named_t<T>,
type_traits::add_named_t<Ts>...>>>::
injector;
};
#else
template <class T, class... Ts>
using injector = detail::injector<
BOOST_DI_CFG,
__BOOST_DI_REQUIRES_MSG(concepts::boundable<aux::type<T, Ts...>>),
core::dependency<scopes::instance,
aux::unique_t<type_traits::named_decay_t<T>,
type_traits::named_decay_t<Ts>...>,
aux::type_list<type_traits::add_named_t<T>,
type_traits::add_named_t<Ts>...>>>;
#endif
// clang-format off
#define __BOOST_DI_EXPOSE_IMPL__(...) decltype(::boost::ext::di::v1_2_0::detail::__VA_ARGS__),
#define __BOOST_DI_EXPOSE_IMPL(...) ::boost::ext::di::v1_2_0::named<__BOOST_DI_EXPOSE_IMPL__ __VA_ARGS__>
#define BOOST_DI_EXPOSE(...) __BOOST_DI_IF(__BOOST_DI_IBP(__VA_ARGS__), __BOOST_DI_EXPOSE_IMPL, __BOOST_DI_EXPAND)(__VA_ARGS__)
// clang-format on
#if defined(__MSVC__)
#define __BOOST_DI_MAKE_INJECTOR(...) __VA_ARGS__
#else
namespace detail {
static auto make_injector = [](auto injector) {
using injector_t = decltype(injector);
struct i : injector_t {
explicit i(injector_t &&other)
: injector_t(static_cast<injector_t &&>(other)) {}
};
return i{static_cast<injector_t &&>(injector)};
};
}
#define __BOOST_DI_MAKE_INJECTOR(...) detail::make_injector(__VA_ARGS__)
#endif
template <
class TConfig = BOOST_DI_CFG, class... TDeps,
__BOOST_DI_REQUIRES_MSG(concepts::boundable<aux::type_list<TDeps...>>) = 0,
__BOOST_DI_REQUIRES_MSG(concepts::configurable<TConfig>) = 0>
inline auto make_injector(TDeps... args) noexcept {
return __BOOST_DI_MAKE_INJECTOR(
core::injector<
TConfig,
decltype(((TConfig *)0)->policies((concepts::injector<TConfig> *)0)),
TDeps...>{core::init{}, static_cast<TDeps &&>(args)...});
}
namespace policies {
namespace detail {
struct type_op {};
template <class T, class = int> struct apply_impl {
template <class> struct apply : T {};
};
template <template <class...> class T, class... Ts>
struct apply_impl<T<Ts...>, __BOOST_DI_REQUIRES(
!aux::is_base_of<type_op, T<Ts...>>::value)> {
template <class TOp, class> struct apply_placeholder_impl {
using type = TOp;
};
template <class TOp> struct apply_placeholder_impl<_, TOp> {
using type = TOp;
};
template <template <class...> class TExpr, class TOp, class... TArgs>
struct apply_placeholder {
using type = TExpr<typename apply_placeholder_impl<TArgs, TOp>::type...>;
};
template <class TArg>
struct apply : apply_placeholder<T, typename TArg::type, Ts...>::type {};
};
template <class T>
struct apply_impl<T, __BOOST_DI_REQUIRES(aux::is_base_of<type_op, T>::value)> {
template <class TArg> struct apply : T::template apply<TArg>::type {};
};
template <class T> struct not_ : detail::type_op {
template <class TArg>
struct apply
: aux::integral_constant<
bool, !detail::apply_impl<T>::template apply<TArg>::value> {};
};
template <class... Ts> struct and_ : detail::type_op {
template <class TArg>
struct apply : aux::is_same<aux::bool_list<detail::apply_impl<
Ts>::template apply<TArg>::value...>,
aux::bool_list<aux::always<Ts>::value...>> {};
};
template <class... Ts> struct or_ : detail::type_op {
template <class TArg>
struct apply
: aux::integral_constant<
bool,
!aux::is_same<aux::bool_list<detail::apply_impl<Ts>::template apply<
TArg>::value...>,
aux::bool_list<aux::never<Ts>::value...>>::value> {};
};
} // namespace detail
template <class T> struct type {
template <class TPolicy> struct not_allowed_by {
operator aux::false_type() const {
using constraint_not_satisfied = not_allowed_by;
return constraint_not_satisfied{}.error();
}
// clang-format off
static inline aux::false_type
error(_ = "type disabled by constructible policy, added by BOOST_DI_CFG or make_injector<CONFIG>!");
// clang-format on
};
};
template <class> struct is_root : detail::type_op {
template <class TArg> struct apply : TArg::is_root {};
};
template <class T> struct is_bound : detail::type_op {
struct not_resolved {};
template <class TArg>
struct apply
: aux::integral_constant<
bool,
!aux::is_same<typename TArg::template resolve<
aux::conditional_t<aux::is_same<T, _>::value,
typename TArg::type, T>,
typename TArg::name, not_resolved>,
not_resolved>::value> {};
};
template <class T> struct is_injected : detail::type_op {
template <class TArg, class U = aux::decay_t<aux::conditional_t<
aux::is_same<T, _>::value, typename TArg::type, T>>>
struct apply
: aux::conditional_t<aux::is_class<U>::value,
typename type_traits::is_injectable<U>::type,
aux::true_type> {};
};
static constexpr auto include_root = true;
namespace operators {
template <class X, class Y> inline auto operator||(const X &, const Y &) {
return detail::or_<X, Y>{};
}
template <class X, class Y> inline auto operator&&(const X &, const Y &) {
return detail::and_<X, Y>{};
}
template <class T> inline auto operator!(const T &) {
return detail::not_<T>{};
}
} // namespace operators
template <bool, class T> struct constructible_impl {
template <class TArg, __BOOST_DI_REQUIRES(TArg::is_root::value ||
T::template apply<TArg>::value) = 0>
aux::true_type operator()(const TArg &) const {
return {};
}
template <class TArg,
__BOOST_DI_REQUIRES(!TArg::is_root::value &&
!T::template apply<TArg>::value) = 0>
aux::false_type operator()(const TArg &) const {
return typename type<typename TArg::type>::template not_allowed_by<T>{};
}
};
template <class T> struct constructible_impl<true, T> {
template <class TArg, __BOOST_DI_REQUIRES(T::template apply<TArg>::value) = 0>
aux::true_type operator()(const TArg &) const {
return {};
}
template <class TArg,
__BOOST_DI_REQUIRES(!T::template apply<TArg>::value) = 0>
aux::false_type operator()(const TArg &) const {
return typename type<typename TArg::type>::template not_allowed_by<T>{};
}
};
template <bool IncludeRoot = false, class T = aux::never<_>,
__BOOST_DI_REQUIRES(aux::is_base_of<detail::type_op, T>::value) = 0>
inline auto constructible(const T & = {}) {
return constructible_impl<IncludeRoot, T>{};
}
template <bool IncludeRoot = false, class T = aux::never<_>,
__BOOST_DI_REQUIRES(!aux::is_base_of<detail::type_op, T>::value) = 0>
inline auto constructible(const T & = {}) {
return constructible_impl<IncludeRoot, detail::or_<T>>{};
}
} // namespace policies
#define __BOOST_DI_IF(cond, t, f) __BOOST_DI_IF_I(cond, t, f)
#define __BOOST_DI_REPEAT(i, m, ...) __BOOST_DI_REPEAT_N(i, m, __VA_ARGS__)
#define __BOOST_DI_CAT(a, ...) __BOOST_DI_PRIMITIVE_CAT(a, __VA_ARGS__)
#define __BOOST_DI_EMPTY()
#define __BOOST_DI_COMMA() ,
#define __BOOST_DI_EAT(...)
#define __BOOST_DI_EXPAND(...) __VA_ARGS__
#define __BOOST_DI_SIZE(...) \
__BOOST_DI_CAT(__BOOST_DI_VARIADIC_SIZE_I(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, \
3, 2, 1, ), )
#define __BOOST_DI_PRIMITIVE_CAT(a, ...) a##__VA_ARGS__
#define __BOOST_DI_ELEM(n, ...) __BOOST_DI_ELEM_I(n, __VA_ARGS__)
#define __BOOST_DI_IS_EMPTY(...) \
__BOOST_DI_DETAIL_IS_EMPTY_IIF(__BOOST_DI_IBP(__VA_ARGS__)) \
(__BOOST_DI_DETAIL_IS_EMPTY_GEN_ZERO, \
__BOOST_DI_DETAIL_IS_EMPTY_PROCESS)(__VA_ARGS__)
#define __BOOST_DI_DETAIL_IS_EMPTY_PRIMITIVE_CAT(a, b) a##b
#define __BOOST_DI_DETAIL_IS_EMPTY_IIF(bit) \
__BOOST_DI_DETAIL_IS_EMPTY_PRIMITIVE_CAT(__BOOST_DI_DETAIL_IS_EMPTY_IIF_, bit)
#define __BOOST_DI_DETAIL_IS_EMPTY_NON_FUNCTION_C(...) ()
#define __BOOST_DI_DETAIL_IS_EMPTY_GEN_ZERO(...) 0
#define __BOOST_DI_VARIADIC_SIZE_I(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, \
size, ...) \
size
#define __BOOST_DI_IF_I(cond, t, f) __BOOST_DI_IIF(cond, t, f)
#define __BOOST_DI_IIF_0(t, f) f
#define __BOOST_DI_IIF_1(t, f) t
#define __BOOST_DI_IIF_2(t, f) t
#define __BOOST_DI_IIF_3(t, f) t
#define __BOOST_DI_IIF_4(t, f) t
#define __BOOST_DI_IIF_5(t, f) t
#define __BOOST_DI_IIF_6(t, f) t
#define __BOOST_DI_IIF_7(t, f) t
#define __BOOST_DI_IIF_8(t, f) t
#define __BOOST_DI_IIF_9(t, f) t
#define __BOOST_DI_ELEM_I(n, ...) \
__BOOST_DI_CAT(__BOOST_DI_CAT(__BOOST_DI_ELEM, n)(__VA_ARGS__, ), )
#define __BOOST_DI_ELEM0(p1, ...) p1
#define __BOOST_DI_ELEM1(p1, p2, ...) p2
#define __BOOST_DI_ELEM2(p1, p2, p3, ...) p3
#define __BOOST_DI_ELEM3(p1, p2, p3, p4, ...) p4
#define __BOOST_DI_ELEM4(p1, p2, p3, p4, p5, ...) p5
#define __BOOST_DI_ELEM5(p1, p2, p3, p4, p5, p6, ...) p6
#define __BOOST_DI_ELEM6(p1, p2, p3, p4, p5, p6, p7, ...) p7
#define __BOOST_DI_ELEM7(p1, p2, p3, p4, p5, p6, p7, p8, ...) p8
#define __BOOST_DI_ELEM8(p1, p2, p3, p4, p5, p6, p7, p8, p9, ...) p9
#define __BOOST_DI_ELEM9(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, ...) p10
#define __BOOST_DI_REPEAT_N(i, m, ...) __BOOST_DI_REPEAT_##i(m, __VA_ARGS__)
#define __BOOST_DI_REPEAT_1(m, ...) m(0, __VA_ARGS__)
#define __BOOST_DI_REPEAT_2(m, ...) m(0, __VA_ARGS__) m(1, __VA_ARGS__)
#define __BOOST_DI_REPEAT_3(m, ...) \
m(0, __VA_ARGS__) m(1, __VA_ARGS__) m(2, __VA_ARGS__)
#define __BOOST_DI_REPEAT_4(m, ...) \
m(0, __VA_ARGS__) m(1, __VA_ARGS__) m(2, __VA_ARGS__) m(3, __VA_ARGS__)
#define __BOOST_DI_REPEAT_5(m, ...) \
m(0, __VA_ARGS__) m(1, __VA_ARGS__) m(2, __VA_ARGS__) m(3, __VA_ARGS__) \
m(4, __VA_ARGS__)
#define __BOOST_DI_REPEAT_6(m, ...) \
m(0, __VA_ARGS__) m(1, __VA_ARGS__) m(2, __VA_ARGS__) m(3, __VA_ARGS__) \
m(4, __VA_ARGS__) m(5, __VA_ARGS__)
#define __BOOST_DI_REPEAT_7(m, ...) \
m(0, __VA_ARGS__) m(1, __VA_ARGS__) m(2, __VA_ARGS__) m(3, __VA_ARGS__) \
m(4, __VA_ARGS__) m(5, __VA_ARGS__) m(6, __VA_ARGS__)
#define __BOOST_DI_REPEAT_8(m, ...) \
m(0, __VA_ARGS__) m(1, __VA_ARGS__) m(2, __VA_ARGS__) m(3, __VA_ARGS__) \
m(4, __VA_ARGS__) m(5, __VA_ARGS__) m(6, __VA_ARGS__) m(7, __VA_ARGS__)
#define __BOOST_DI_REPEAT_9(m, ...) \
m(0, __VA_ARGS__) m(1, __VA_ARGS__) m(2, __VA_ARGS__) m(3, __VA_ARGS__) \
m(4, __VA_ARGS__) m(5, __VA_ARGS__) m(6, __VA_ARGS__) m(7, __VA_ARGS__) \
m(8, __VA_ARGS__)
#define __BOOST_DI_REPEAT_10(m, ...) \
m(0, __VA_ARGS__) m(1, __VA_ARGS__) m(2, __VA_ARGS__) m(3, __VA_ARGS__) \
m(4, __VA_ARGS__) m(5, __VA_ARGS__) m(6, __VA_ARGS__) m(7, __VA_ARGS__) \
m(8, __VA_ARGS__) m(9, __VA_ARGS__)
#if defined(__MSVC__)
#define __BOOST_DI_VD_IBP_CAT(a, b) __BOOST_DI_VD_IBP_CAT_I(a, b)
#define __BOOST_DI_VD_IBP_CAT_I(a, b) __BOOST_DI_VD_IBP_CAT_II(a##b)
#define __BOOST_DI_VD_IBP_CAT_II(res) res
#define __BOOST_DI_IBP_SPLIT(i, ...) \
__BOOST_DI_VD_IBP_CAT( \
__BOOST_DI_IBP_PRIMITIVE_CAT(__BOOST_DI_IBP_SPLIT_, i)(__VA_ARGS__), \
__BOOST_DI_EMPTY())
#define __BOOST_DI_IBP_IS_VARIADIC_C(...) 1 1
#define __BOOST_DI_IBP_SPLIT_0(a, ...) a
#define __BOOST_DI_IBP_SPLIT_1(a, ...) __VA_ARGS__
#define __BOOST_DI_IBP_CAT(a, ...) __BOOST_DI_IBP_PRIMITIVE_CAT(a, __VA_ARGS__)
#define __BOOST_DI_IBP_PRIMITIVE_CAT(a, ...) a##__VA_ARGS__
#define __BOOST_DI_IBP_IS_VARIADIC_R_1 1,
#define __BOOST_DI_IBP_IS_VARIADIC_R___BOOST_DI_IBP_IS_VARIADIC_C 0,
#define __BOOST_DI_IBP(...) \
__BOOST_DI_IBP_SPLIT( \
0, __BOOST_DI_IBP_CAT(__BOOST_DI_IBP_IS_VARIADIC_R_, \
__BOOST_DI_IBP_IS_VARIADIC_C __VA_ARGS__))
#define __BOOST_DI_IIF(bit, t, f) __BOOST_DI_IIF_OO((bit, t, f))
#define __BOOST_DI_IIF_OO(par) __BOOST_DI_IIF_I##par
#define __BOOST_DI_IIF_I(bit, t, f) __BOOST_DI_IIF_##bit(t, f)
#define __BOOST_DI_DETAIL_IS_EMPTY_IIF_0(t, b) b
#define __BOOST_DI_DETAIL_IS_EMPTY_IIF_1(t, b) t
#define __BOOST_DI_DETAIL_IS_EMPTY_PROCESS(...) \
__BOOST_DI_IBP(__BOOST_DI_DETAIL_IS_EMPTY_NON_FUNCTION_C __VA_ARGS__())
#else
#define __BOOST_DI_IBP_SPLIT(i, ...) \
__BOOST_DI_PRIMITIVE_CAT(__BOOST_DI_IBP_SPLIT_, i)(__VA_ARGS__)
#define __BOOST_DI_IBP_SPLIT_0(a, ...) a
#define __BOOST_DI_IBP_SPLIT_1(a, ...) __VA_ARGS__
#define __BOOST_DI_IBP_IS_VARIADIC_C(...) 1
#define __BOOST_DI_IBP_IS_VARIADIC_R_1 1,
#define __BOOST_DI_IBP_IS_VARIADIC_R___BOOST_DI_IBP_IS_VARIADIC_C 0,
#define __BOOST_DI_IBP(...) \
__BOOST_DI_IBP_SPLIT( \
0, __BOOST_DI_CAT(__BOOST_DI_IBP_IS_VARIADIC_R_, \
__BOOST_DI_IBP_IS_VARIADIC_C __VA_ARGS__))
#define __BOOST_DI_IIF(bit, t, f) __BOOST_DI_IIF_I(bit, t, f)
#define __BOOST_DI_IIF_I(bit, t, f) \
__BOOST_DI_IIF_II(__BOOST_DI_IIF_##bit(t, f))
#define __BOOST_DI_IIF_II(id) id
#define __BOOST_DI_DETAIL_IS_EMPTY_IIF_0(t, ...) __VA_ARGS__
#define __BOOST_DI_DETAIL_IS_EMPTY_IIF_1(t, ...) t
#define __BOOST_DI_DETAIL_IS_EMPTY_PROCESS(...) \
__BOOST_DI_IBP(__BOOST_DI_DETAIL_IS_EMPTY_NON_FUNCTION_C __VA_ARGS__())
#endif
template <class, class> struct named;
namespace detail {
struct named_impl {
template <class T> T operator=(const T &) const;
};
static constexpr __BOOST_DI_UNUSED named_impl named{};
template <class T, class TName> struct combine_impl {
using type = ::boost::ext::di::v1_2_0::named<TName, T>;
};
template <class T> struct combine_impl<T, aux::none_type> { using type = T; };
template <class, class> struct combine;
template <class... T1, class... T2>
struct combine<aux::type_list<T1...>, aux::type_list<T2...>> {
using type = aux::type_list<typename combine_impl<T1, T2>::type...>;
};
template <class T1, class T2> using combine_t = typename combine<T1, T2>::type;
} // namespace detail
template <class... Ts> using inject = aux::type_list<Ts...>;
#define __BOOST_DI_HAS_NAME(i, ...) \
__BOOST_DI_IF(__BOOST_DI_IBP(__BOOST_DI_ELEM(i, __VA_ARGS__, )), 1, )
#define __BOOST_DI_HAS_NAMES(...) \
__BOOST_DI_IF( \
__BOOST_DI_IS_EMPTY(__BOOST_DI_REPEAT( \
__BOOST_DI_SIZE(__VA_ARGS__), __BOOST_DI_HAS_NAME, __VA_ARGS__)), \
0, 1)
#define __BOOST_DI_GEN_CTOR_IMPL(p, i) \
__BOOST_DI_IF(i, __BOOST_DI_COMMA, __BOOST_DI_EAT) \
() __BOOST_DI_IF(__BOOST_DI_IBP(p), __BOOST_DI_EAT p, p)
#define __BOOST_DI_GEN_CTOR(i, ...) \
__BOOST_DI_GEN_CTOR_IMPL(__BOOST_DI_ELEM(i, __VA_ARGS__, ), i)
#define __BOOST_DI_GEN_ARG_NAME(p) __BOOST_DI_GEN_ARG_NAME_IMPL p )
#define __BOOST_DI_GEN_NONE_TYPE(p) ::boost::ext::di::v1_2_0::aux::none_type
#define __BOOST_DI_GEN_ARG_NAME_IMPL(p) decltype(::boost::ext::di::v1_2_0::detail::p) __BOOST_DI_EAT(
#define __BOOST_DI_GEN_NAME_IMPL(p, i) \
__BOOST_DI_IF(i, __BOOST_DI_COMMA, __BOOST_DI_EAT) \
() __BOOST_DI_IF(__BOOST_DI_IBP(p), __BOOST_DI_GEN_ARG_NAME, \
__BOOST_DI_GEN_NONE_TYPE)(p)
#define __BOOST_DI_GEN_NAME(i, ...) \
__BOOST_DI_GEN_NAME_IMPL(__BOOST_DI_ELEM(i, __VA_ARGS__, ), i)
#define __BOOST_DI_INJECT_TRAITS_IMPL_0(...) \
static void ctor(__BOOST_DI_REPEAT(__BOOST_DI_SIZE(__VA_ARGS__), \
__BOOST_DI_GEN_CTOR, __VA_ARGS__)); \
using type __BOOST_DI_UNUSED = \
::boost::ext::di::v1_2_0::aux::function_traits_t<decltype(ctor)>;
#define __BOOST_DI_INJECT_TRAITS_IMPL_1(...) \
static void ctor(__BOOST_DI_REPEAT(__BOOST_DI_SIZE(__VA_ARGS__), \
__BOOST_DI_GEN_CTOR, __VA_ARGS__)); \
static void name(__BOOST_DI_REPEAT(__BOOST_DI_SIZE(__VA_ARGS__), \
__BOOST_DI_GEN_NAME, __VA_ARGS__)); \
using type __BOOST_DI_UNUSED = ::boost::ext::di::v1_2_0::detail::combine_t< \
::boost::ext::di::v1_2_0::aux::function_traits_t<decltype(ctor)>, \
::boost::ext::di::v1_2_0::aux::function_traits_t<decltype(name)>>;
#define __BOOST_DI_INJECT_TRAITS_EMPTY_IMPL(...) \
using boost_di_inject__ __BOOST_DI_UNUSED = \
::boost::ext::di::v1_2_0::aux::type_list<>
#define __BOOST_DI_INJECT_TRAITS_IMPL(...) \
struct boost_di_inject__ { \
__BOOST_DI_CAT(__BOOST_DI_INJECT_TRAITS_IMPL_, \
__BOOST_DI_HAS_NAMES(__VA_ARGS__)) \
(__VA_ARGS__) static_assert(__BOOST_DI_SIZE(__VA_ARGS__) <= \
BOOST_DI_CFG_CTOR_LIMIT_SIZE, \
"Number of constructor arguments is out of " \
"range - see BOOST_DI_CFG_CTOR_LIMIT_SIZE"); \
}
#define BOOST_DI_INJECT_TRAITS(...) \
__BOOST_DI_IF(__BOOST_DI_IS_EMPTY(__VA_ARGS__), \
__BOOST_DI_INJECT_TRAITS_EMPTY_IMPL, \
__BOOST_DI_INJECT_TRAITS_IMPL) \
(__VA_ARGS__)
#define BOOST_DI_INJECT(T, ...) \
BOOST_DI_INJECT_TRAITS(__VA_ARGS__); \
T(__BOOST_DI_REPEAT(__BOOST_DI_SIZE(__VA_ARGS__), __BOOST_DI_GEN_CTOR, \
__VA_ARGS__))
BOOST_DI_NAMESPACE_END
#endif
#if defined(__CLANG__)
#pragma clang diagnostic pop
#elif defined(__GCC__)
#pragma GCC diagnostic pop
#endif
|
[
"matias.pavez.b@gmail.com"
] |
matias.pavez.b@gmail.com
|
db430cd9166275ac900ae6ac2d9df72601a0d9af
|
0d9076293349241af62d00eff4c4107e51426ea5
|
/leetcode problems/260. Single Number III.cpp
|
1d7925037b15e18366fa80f7972ac03c46d3d592
|
[] |
no_license
|
zonasse/Algorithm
|
f6445616d0cde04e5ef5f475e7f9c8ec68638dd0
|
cda4ba606b66040a54c44d95db51220a2df47414
|
refs/heads/master
| 2020-03-23T12:12:00.525247
| 2019-08-10T03:42:53
| 2019-08-10T03:42:53
| 141,543,243
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 377
|
cpp
|
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int eo = 0,eoHasOne = 0;
for(auto &a :nums){
eo ^= a;
}
int rightOne = eo & (~eo + 1);
for(auto &a : nums){
if((a & rightOne) != 0){
eoHasOne ^= a;
}
}
return {eoHasOne,eo ^ eoHasOne};
}
};
|
[
"992903713@qq.com"
] |
992903713@qq.com
|
e2e1c742a312e95035f852eab16a5fcf2e91dff4
|
ad934eeba2ac2a3c1d49b02af864790ece137034
|
/zufe/2058字符串加密.cpp
|
d0aa2495cdf67251a406466088233176074e8817
|
[] |
no_license
|
xiang578/acm-icpc
|
19b3d8c7771b935293749f5ccad0591cde8fc896
|
6f2fdfc62bd689842c80b1caee2d4caf8162d72f
|
refs/heads/master
| 2022-01-12T12:28:43.381927
| 2022-01-12T04:20:44
| 2022-01-12T04:20:44
| 39,777,634
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 478
|
cpp
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
int main()
{
char hu[28]={"VWXYZABCDEFGHIJKLMNOPQRSTU"};
char s[120];
int i,len;
while(gets(s))
{
if(strcmp(s,"ENDOFINPUT")==0) break;
gets(s);
len=strlen(s);
for(i=0;i<len;i++)
{
if(s[i]>='A'&&s[i]<='Z')
{
s[i]=hu[s[i]-65];
}
}
puts(s);
gets(s);
}
return 0;
}
|
[
"xiang578@foxmail.com"
] |
xiang578@foxmail.com
|
4d4e956df141f0e3a805c239b6d05fe4ebca5bfe
|
4af341026c371c8e25d37780c3d2a85063ec60ea
|
/LeetCode Solution/Medium/Search in rotate array.cpp
|
2c15531943e789f7c9ca8cac79260f0c22caeb96
|
[] |
no_license
|
i-am-arvinder-singh/CP
|
46a32f9235a656e7d777a16ccbce980cb1eb1c63
|
e4e79e4ffc636f078f16a25ce81a3095553fc060
|
refs/heads/master
| 2023-07-12T19:20:41.093734
| 2021-08-29T06:58:55
| 2021-08-29T06:58:55
| 266,883,239
| 1
| 1
| null | 2020-10-04T14:00:29
| 2020-05-25T21:25:39
|
C++
|
UTF-8
|
C++
| false
| false
| 2,063
|
cpp
|
class Solution {
public:
bool search(vector<int>& nums, int target) {
int n = nums.size();
if(n==0) return false;
int left = 0, right = n-1;
int mid;
while(left<right){
mid = left+(right-left)/2;
if(nums[mid]==target || nums[left]==target || nums[right]==target) return true;
if(nums[mid]>nums[right]) left=mid+1;
else if(nums[mid]<nums[right]) right=mid;
else{
right--;
}
}
if(right==0){
left = 0, right = n-1;
while(left<=right){
mid = left+(right-left)/2;
if(nums[mid]==target || nums[left]==target || nums[right]==target) return true;
else if(nums[mid]<target) left=mid+1;
else right=mid-1;
}
return false;
}
else if(right==n-1){
if(target==nums[right]) return true;
left = 0 ,right = n-2;
while(left<=right){
mid = left+(right-left)/2;
if(nums[mid]==target || nums[left]==target || nums[right]==target) return true;
else if(nums[mid]<target) left=mid+1;
else right=mid-1;
}
return false;
}
else{
int left1 = 0, right1 = right-1, left2 = right, right2 = n-1;
while(left1<=right1){
mid = left1+(right1-left1)/2;
if(nums[mid]==target || nums[left1]==target || nums[right1]==target) return true;
else if(nums[mid]<target) left1=mid+1;
else right1=mid-1;
}
while(left2<=right2){
mid = left2+(right2-left2)/2;
if(nums[mid]==target || nums[left2]==target || nums[right2]==target) return true;
else if(nums[mid]<target) left2=mid+1;
else right2=mid-1;
}
return false;
}
}
};
|
[
"arvinderavy@ymail.com"
] |
arvinderavy@ymail.com
|
13ae8710b2e818a8ff663b6485bbca8cbad44bf0
|
b6ab5a3ff4402ed085557cd5ff354ab2ead6e6f8
|
/GFG/distinctOccurences.cpp
|
21be183b566eed698acb4befc74990223a4030bf
|
[] |
no_license
|
sahiljajodia01/Competitive-Programming
|
e51587110640663aa32f220feddf6ab10f17c445
|
7ae9b45654aff513bceb0fc058a67ca49273a369
|
refs/heads/master
| 2021-07-17T08:23:24.143156
| 2020-06-05T11:34:14
| 2020-06-05T11:34:14
| 163,054,750
| 0
| 1
| null | 2019-10-31T05:36:35
| 2018-12-25T06:48:39
|
C++
|
UTF-8
|
C++
| false
| false
| 862
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
int distinct_occurences(int x, int y, string a, string b) {
int sum = 0;
// if(y == 0 && (a[x] == b[y])) {
// return 1;
// }
// else if(x == 0 || (a[x] != b[y])) {
// return 0;
// }
if(y == 0 && x >= 0) {
if(a[x] == b[y]) {
return 1;
}
}
else if(x == 0 && y > 0) {
return 0;
}
if(a[x] == b[y]) {
sum += distinct_occurences(x-1, y-1, a, b);
}
else {
sum += distinct_occurences(x-1, y, a, b);
sum += distinct_occurences(x, y-1, a, b);
}
return sum;
}
int main() {
int t;
cin >> t;
while(t--) {
string a, b;
cin >> a >> b;
int ans = distinct_occurences(a.length()-1, b.length()-1, a, b);
cout << ans << "\n";
}
return 0;
}
|
[
"sahil.jajodia@gmail.com"
] |
sahil.jajodia@gmail.com
|
971c663c34647dcf4ee659fbb6fde911ddeaf571
|
a4cc0b972c7018a8453665254c7b67520788b34f
|
/include/NodoCapa.h
|
5ef64068995c6702bcdd8e1cca1a8bdf322942c9
|
[] |
no_license
|
jeani-rodas97/EDD_2S2019_PY1_201404421
|
c4de0da37f8a03e813229b91a98468ae06ece5c3
|
4ad086cd434f0541ea5a49ae0531c6ef09bb4a48
|
refs/heads/master
| 2022-02-19T02:12:41.091189
| 2019-09-21T02:00:52
| 2019-09-21T02:00:52
| 203,300,576
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 147
|
h
|
#ifndef NODOCAPA_H
#define NODOCAPA_H
class NodoCapa
{
public:
NodoCapa();
protected:
private:
};
#endif // NODONUMCAPA_H
|
[
"jenni1897@gmail.com"
] |
jenni1897@gmail.com
|
59210229330476347b7628cfc9072cd2865e854c
|
81f6419ea475836b1f1b24bcd2de77a316bc46a1
|
/codeforces/Aston and Danik.cpp
|
d0339e7167c90190c7b29590cbf356740f3aa632
|
[] |
no_license
|
Pramodjais517/competitive-coding
|
f4e0f6f238d98c0a39f8a9c940265f886ce70cb3
|
2a8ad013246f2db72a4dd53771090d931ab406cb
|
refs/heads/master
| 2023-02-25T12:09:47.382076
| 2021-01-28T06:57:26
| 2021-01-28T06:57:26
| 208,445,032
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 457
|
cpp
|
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define rs reserve
#define pb push_back
#define mp make_pair
#define f(i,s,e,inc) for(auto i=s;i<e;i+=inc)
#define itr(i,ar) for(auto &i:ar)
int main()
{
ll n;
cin>>n;
string s;
cin>>s;
ll aston=0,danik=0;
for(int i=0;i<n;i++)
{
if(s[i]=='A')
aston++;
else if(s[i]=='D')
danik++;
}
if(aston>danik)
cout<<"Anton";
else if(danik>aston)
cout<<"Danik";
else
cout<<"Friendship";
return 0;
}
|
[
"pramodjaiswal517@gmail.com"
] |
pramodjaiswal517@gmail.com
|
5643b18082b010cbbac0ee390e93fbcabd27929f
|
1dbed0f84a670c787d2217d97ae3984401c7edb3
|
/cf/27C.cpp
|
cac17b12833921b08e3df9ff15a593f88bfbb072
|
[] |
no_license
|
prprprpony/oj
|
311d12a25f06e6c54b88bc2bcd38003f7b6696a9
|
84988be500c06cb62130585333fddd1a278f0aaa
|
refs/heads/master
| 2021-07-13T16:03:54.398841
| 2021-03-27T14:19:52
| 2021-03-27T14:19:52
| 46,796,050
| 9
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 924
|
cpp
|
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 87;
int a[N],pomn[N],pomx[N];
int main()
{
ios::sync_with_stdio(0);cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; ++i)
cin >> a[i];
pomn[n-1] = pomx[n-1] = n-1;
for (int i = n-2; i >= 0; --i) {
pomn[i] = a[i] < a[pomn[i+1]] ? i : pomn[i+1];
pomx[i] = a[i] > a[pomx[i+1]] ? i : pomx[i+1];
}
int mn,mx;
mn=mx=0;
for (int i = 1; i <= n - 2; ++i) {
if (a[mn] < a[i] && a[pomn[i+1]] < a[i]) {
cout << "3\n" << mn+1 << ' ' << i+1 << ' ' << pomn[i+1]+1 << '\n';
return 0;
}
if (a[mx] > a[i] && a[pomx[i+1]] > a[i]) {
cout << "3\n" << mx+1 << ' ' << i+1 << ' ' << pomx[i+1]+1 << '\n';
return 0;
}
if (a[i] > a[mx])
mx = i;
if (a[i] < a[mn])
mn = i;
}
cout << "0\n";
}
|
[
"3254tg89@gmail.com"
] |
3254tg89@gmail.com
|
7ed0a9e96ccbd3b0b6555700768028eaa4899e81
|
91a882547e393d4c4946a6c2c99186b5f72122dd
|
/Source/XPSP1/NT/base/screg/sc/client/scapi.cxx
|
2512376a9b2ac0ecc918d919e50115ca2538796e
|
[] |
no_license
|
IAmAnubhavSaini/cryptoAlgorithm-nt5src
|
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
|
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
|
refs/heads/master
| 2023-09-02T10:14:14.795579
| 2021-11-20T13:47:06
| 2021-11-20T13:47:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 79,849
|
cxx
|
/*++
Copyright (c) 1990-1992 Microsoft Corporation
Module Name:
scapi.c
Abstract:
Contains the Service-related API that are implemented solely in
DLL form. These include:
StartServiceCtrlDispatcherA
StartServiceCtrlDispatcherW
RegisterServiceCtrlHandlerW
RegisterServiceCtrlHandlerA
RegisterServiceCtrlHandlerExW
RegisterServiceCtrlHandlerExA
This file also contains the following local support routines:
ScDispatcherLoop
ScCreateDispatchTableW
ScCreateDispatchTableA
ScReadServiceParms
ScConnectServiceController
ScExpungeMessage
ScGetPipeInput
ScGetDispatchEntry
ScNormalizeCmdLineArgs
ScSendResponse
ScSvcctrlThreadW
ScSvcctrlThreadA
RegisterServiceCtrlHandlerHelp
Author:
Dan Lafferty (danl) 09 Apr-1991
Environment:
User Mode -Win32
Revision History:
12-May-1999 jschwart
Convert SERVICE_STATUS_HANDLE to a context handle to fix security
hole (any service can call SetServiceStatus with another service's
handle and succeed)
10-May-1999 jschwart
Create a separate named pipe per service to fix security hole (any
process could flood the pipe since the name was well-known -- pipe
access is now limited to the service account and LocalSystem)
10-Mar-1998 jschwart
Add code to allow services to receive Plug-and-Play control messages
and unpack the message arguments from the pipe
30-Sep-1997 jschwart
StartServiceCtrlDispatcher: If this function [A or W] has already been
called from within this process, return ERROR_SERVICE_ALREADY_RUNNING.
Otherwise, can be destructive (e.g., overwrite AnsiFlag, etc.)
06-Aug-1997 jschwart
ScDispatcherLoop: If the service is processing a shutdown command from
the SCM, it no longer writes the status back to the SCM since the SCM is
now using WriteFile on system shutdown (see control.cxx for more info).
03-Jun-1996 AnirudhS
ScGetPipeInput: If the message received from the service controller
is not a SERVICE_CONTROL_START message, don't allocate space for the
arguments, since there are none, and since that space never gets freed.
22-Sep-1995 AnirudhS
Return codes from InitializeStatusBinding were not being handled
correctly; success was sometimes reported on failure. Fixed this.
12-Aug-1993 Danl
ScGetDispatchEntry: When the first entry in the table is marked as
OwnProcess, then this function should just return the pointer to the
top of the table. It should ignore the ServiceName. In all cases,
when the service is started as an OWN_PROCESS, only the first entry
in the dispath table should be used.
04-Aug-1992 Danl
When starting a service, always pass the service name as the
first parameter in the argument list.
27-May-1992 JohnRo
RAID 9829: winsvc.h and related file cleanup.
09 Apr-1991 danl
created
--*/
//
// INCLUDES
//
#include <scpragma.h>
extern "C"
{
#include <nt.h> // DbgPrint prototype
#include <ntrtl.h> // DbgPrint prototype
#include <nturtl.h> // needed for winbase.h
}
#include <rpc.h> // DataTypes and runtime APIs
#include <windef.h> // windows types needed for winbase.h
#include <winbase.h> // CreateFile
#include <winuser.h> // wsprintf()
#include <winreg.h> // RegOpenKeyEx / RegQueryValueEx
#include <string.h> // strcmp
#include <stdlib.h> // wide character c runtimes.
#include <tstr.h> // WCSSIZE().
#include <winsvc.h> // public Service Controller Interface.
#include "scbind.h" // InitializeStatusBinding
#include <valid.h> // MAX_SERVICE_NAME_LENGTH
#include <control.h> // CONTROL_PIPE_NAME
#include <scdebug.h> // STATIC
#include <sclib.h> // ScConvertToUnicode
//
// Internal Dispatch Table.
//
//
// Bit flags for the dispatch table's dwFlags field
//
#define SERVICE_OWN_PROCESS 0x00000001
#define SERVICE_EX_HANDLER 0x00000002
typedef union _START_ROUTINE_TYPE {
LPSERVICE_MAIN_FUNCTIONW U; // unicode type
LPSERVICE_MAIN_FUNCTIONA A; // ansi type
} START_ROUTINE_TYPE, *LPSTART_ROUTINE_TYPE;
typedef union _HANDLER_FUNCTION_TYPE {
LPHANDLER_FUNCTION Regular; // Regular version
LPHANDLER_FUNCTION_EX Ex; // Extended version
} HANDLER_FUNCTION_TYPE, *LPHANDLER_FUNCTION_TYPE;
typedef struct _INTERNAL_DISPATCH_ENTRY {
LPWSTR ServiceName;
LPWSTR ServiceRealName; // In case the names are different
START_ROUTINE_TYPE ServiceStartRoutine;
HANDLER_FUNCTION_TYPE ControlHandler;
SC_HANDLE StatusHandle;
DWORD dwFlags;
PVOID pContext;
} INTERNAL_DISPATCH_ENTRY, *LPINTERNAL_DISPATCH_ENTRY;
//
// This structure is passed to the internal
// startup thread which calls the real user
// startup routine with argv, argc parameters.
//
typedef struct _THREAD_STARTUP_PARMSW {
DWORD NumArgs;
LPSERVICE_MAIN_FUNCTIONW ServiceStartRoutine;
LPWSTR VectorTable;
} THREAD_STARTUP_PARMSW, *LPTHREAD_STARTUP_PARMSW;
typedef struct _THREAD_STARTUP_PARMSA {
DWORD NumArgs;
LPSERVICE_MAIN_FUNCTIONA ServiceStartRoutine;
LPSTR VectorTable;
} THREAD_STARTUP_PARMSA, *LPTHREAD_STARTUP_PARMSA;
//
// This structure contains the arguments passed
// to a service's extended control handler
//
typedef struct _HANDLEREX_PARMS {
DWORD dwEventType;
LPVOID lpEventData;
} HANDLEREX_PARMS, *LPHANDLEREX_PARMS;
//
// This union contains the arguments to the service
// passed from the server via named pipe
//
typedef union _SERVICE_PARAMS {
THREAD_STARTUP_PARMSW ThreadStartupParms;
HANDLEREX_PARMS HandlerExParms;
} SERVICE_PARAMS, *LPSERVICE_PARAMS;
//
// The following is the amount of time we will wait for the named pipe
// to become available from the Service Controller.
//
#ifdef DEBUG
#define CONTROL_WAIT_PERIOD NMPWAIT_WAIT_FOREVER
#else
#define CONTROL_WAIT_PERIOD 15000 // 15 seconds
#endif
//
// This is the number of times we will continue to loop when pipe read
// failures occur. After this many tries, we cease to read the pipe.
//
#define MAX_RETRY_COUNT 30
//
// Globals
//
LPINTERNAL_DISPATCH_ENTRY DispatchTable=NULL; // table head.
//
// This flag is set to TRUE if the control dispatcher is to support
// ANSI calls. Otherwise the flag is set to FALSE.
//
BOOL AnsiFlag = FALSE;
//
// This variable makes sure StartServiceCtrlDispatcher[A,W] doesn't
// get called twice by the same process, since this is destructive.
// It is initialized to 0 by the linker
//
LONG g_fCalledBefore;
//
// Are we running in the security process?
//
BOOL g_fIsSecProc;
#if defined(_X86_)
//
// Are we running inside a Wow64 process (on Win64)
//
BOOL g_fWow64Process = FALSE;
#endif
//
// Internal Functions
//
DWORD
ScCreateDispatchTableW(
IN CONST SERVICE_TABLE_ENTRYW *UserDispatchTable,
OUT LPINTERNAL_DISPATCH_ENTRY *DispatchTablePtr
);
DWORD
ScCreateDispatchTableA(
IN CONST SERVICE_TABLE_ENTRYA *UserDispatchTable,
OUT LPINTERNAL_DISPATCH_ENTRY *DispatchTablePtr
);
DWORD
ScReadServiceParms(
IN LPCTRL_MSG_HEADER Msg,
IN DWORD dwNumBytesRead,
OUT LPBYTE *ppServiceParams,
OUT LPBYTE *ppTempArgPtr,
OUT LPDWORD lpdwRemainingArgBytes
);
VOID
ScDispatcherLoop(
IN HANDLE PipeHandle,
IN LPCTRL_MSG_HEADER Msg,
IN DWORD dwBufferSize
);
DWORD
ScConnectServiceController (
OUT LPHANDLE pipeHandle
);
VOID
ScExpungeMessage(
IN HANDLE PipeHandle
);
DWORD
ScGetPipeInput (
IN HANDLE PipeHandle,
IN OUT LPCTRL_MSG_HEADER Msg,
IN DWORD dwBufferSize,
OUT LPSERVICE_PARAMS *ppServiceParams
);
DWORD
ScGetDispatchEntry (
OUT LPINTERNAL_DISPATCH_ENTRY *DispatchEntry,
IN LPWSTR ServiceName
);
VOID
ScNormalizeCmdLineArgs(
IN OUT LPCTRL_MSG_HEADER Msg,
IN OUT LPTHREAD_STARTUP_PARMSW ThreadStartupParms
);
VOID
ScSendResponse (
IN HANDLE pipeHandle,
IN DWORD Response,
IN DWORD dwHandlerRetVal
);
DWORD
ScSvcctrlThreadW(
IN LPTHREAD_STARTUP_PARMSW lpThreadStartupParms
);
DWORD
ScSvcctrlThreadA(
IN LPTHREAD_STARTUP_PARMSA lpThreadStartupParms
);
SERVICE_STATUS_HANDLE
WINAPI
RegisterServiceCtrlHandlerHelp (
IN LPCWSTR ServiceName,
IN HANDLER_FUNCTION_TYPE ControlHandler,
IN PVOID pContext,
IN DWORD dwFlags
);
#if defined(_X86_)
//
// Detect if the current process is a 32-bit process running on Win64.
//
VOID DetectWow64Process()
{
NTSTATUS NtStatus;
PVOID Peb32;
NtStatus = NtQueryInformationProcess(NtCurrentProcess(),
ProcessWow64Information,
&Peb32,
sizeof(Peb32),
NULL);
if (NT_SUCCESS(NtStatus) && (Peb32 != NULL))
{
g_fWow64Process = TRUE;
}
}
#endif
extern "C" {
//
// Private function for lsass.exe that tells us we're running
// in the security process
//
VOID
I_ScIsSecurityProcess(
VOID
)
{
g_fIsSecProc = TRUE;
}
//
// Private function for PnP that looks up a service's REAL
// name given its context handle
//
DWORD
I_ScPnPGetServiceName(
IN SERVICE_STATUS_HANDLE hServiceStatus,
OUT LPWSTR lpServiceName,
IN DWORD cchBufSize
)
{
DWORD dwError = ERROR_SERVICE_NOT_IN_EXE;
ASSERT(cchBufSize >= MAX_SERVICE_NAME_LENGTH);
//
// Search the dispatch table.
//
if (DispatchTable != NULL)
{
LPINTERNAL_DISPATCH_ENTRY dispatchEntry;
for (dispatchEntry = DispatchTable;
dispatchEntry->ServiceName != NULL;
dispatchEntry++)
{
//
// Note: SC_HANDLE and SERVICE_STATUS_HANDLE were originally
// different handle types -- they are now the same as
// per the fix for bug #120359 (SERVICE_STATUS_HANDLE
// fix outlined in the file comments above), so this
// cast is OK.
//
if (dispatchEntry->StatusHandle == (SC_HANDLE)hServiceStatus)
{
ASSERT(dispatchEntry->ServiceRealName != NULL);
ASSERT(wcslen(dispatchEntry->ServiceRealName) < cchBufSize);
wcscpy(lpServiceName, dispatchEntry->ServiceRealName);
dwError = NO_ERROR;
break;
}
}
}
return dwError;
}
} // extern "C"
BOOL
WINAPI
StartServiceCtrlDispatcherA (
IN CONST SERVICE_TABLE_ENTRYA * lpServiceStartTable
)
/*++
Routine Description:
This function provides the ANSI interface for the
StartServiceCtrlDispatcher function.
Arguments:
Return Value:
--*/
{
DWORD status;
NTSTATUS ntstatus;
HANDLE pipeHandle;
//
// Make sure this is the only time the control dispatcher is being called
//
if (InterlockedExchange(&g_fCalledBefore, 1) == 1) {
//
// Problem -- the control dispatcher was already called from this process
//
SetLastError(ERROR_SERVICE_ALREADY_RUNNING);
return(FALSE);
}
//
// Set the AnsiFlag to indicate that the control dispatcher must support
// ansi function calls only.
//
AnsiFlag = TRUE;
//
// Create an internal DispatchTable.
//
status = ScCreateDispatchTableA(
(LPSERVICE_TABLE_ENTRYA)lpServiceStartTable,
(LPINTERNAL_DISPATCH_ENTRY *)&DispatchTable);
if (status != NO_ERROR) {
SetLastError(status);
return(FALSE);
}
//
// Allocate a buffer big enough to contain at least the control message
// header and a service name. This ensures that if the message is not
// a message with arguments, it can be read in a single ReadFile.
//
BYTE bPipeMessageHeader[sizeof(CTRL_MSG_HEADER) +
(MAX_SERVICE_NAME_LENGTH+1) * sizeof(WCHAR)];
//
// Connect to the Service Controller
//
status = ScConnectServiceController (&pipeHandle);
if (status != NO_ERROR) {
goto CleanExit;
}
//
// Initialize the binding for the status interface (NetServiceStatus).
//
SCC_LOG(TRACE,"Initialize the Status binding\n",0);
ntstatus = InitializeStatusBinding();
if (ntstatus != STATUS_SUCCESS) {
status = RtlNtStatusToDosError(ntstatus);
CloseHandle(pipeHandle);
goto CleanExit;
}
//
// Enter the dispatcher loop where we service control requests until
// all services in the service table have terminated.
//
ScDispatcherLoop(pipeHandle,
(LPCTRL_MSG_HEADER)&bPipeMessageHeader,
sizeof(bPipeMessageHeader));
CloseHandle(pipeHandle);
CleanExit:
//
// Clean up the dispatch table. Since we created unicode versions
// of all the service names, in ScCreateDispatchTableA, we now need to
// free them.
//
if (DispatchTable != NULL) {
LPINTERNAL_DISPATCH_ENTRY dispatchEntry;
//
// If they're different, it's because we allocated the real name.
// Only check the first entry since this can only happen in the
// SERVICE_OWN_PROCESS case
//
if (DispatchTable->ServiceName != DispatchTable->ServiceRealName) {
LocalFree(DispatchTable->ServiceRealName);
}
for (dispatchEntry = DispatchTable;
dispatchEntry->ServiceName != NULL;
dispatchEntry++) {
LocalFree(dispatchEntry->ServiceName);
}
LocalFree(DispatchTable);
}
if (status != NO_ERROR) {
SetLastError(status);
return(FALSE);
}
return(TRUE);
}
BOOL
WINAPI
StartServiceCtrlDispatcherW (
IN CONST SERVICE_TABLE_ENTRYW * lpServiceStartTable
)
/*++
Routine Description:
This is the Control Dispatcher thread. We do not return from this
function call until the Control Dispatcher is told to shut down.
The Control Dispatcher is responsible for connecting to the Service
Controller's control pipe, and receiving messages from that pipe.
The Control Dispatcher then dispatches the control messages to the
correct control handling routine.
Arguments:
lpServiceStartTable - This is a pointer to the top of a service dispatch
table that the service main process passes in. Each table entry
contains pointers to the ServiceName, and the ServiceStartRotuine.
Return Value:
NO_ERROR - The Control Dispatcher successfully terminated.
ERROR_INVALID_DATA - The specified dispatch table does not contain
entries in the proper format.
ERROR_FAILED_SERVICE_CONTROLLER_CONNECT - The Control Dispatcher
could not connect with the Service Controller.
ERROR_SERVICE_ALREADY_RUNNING - The function has already been called
from within the current process
--*/
{
DWORD status;
NTSTATUS ntStatus;
HANDLE pipeHandle;
//
// Make sure this is the only time the control dispatcher is being called
//
if (InterlockedExchange(&g_fCalledBefore, 1) == 1) {
//
// Problem -- the control dispatcher was already called from this process
//
SetLastError(ERROR_SERVICE_ALREADY_RUNNING);
return(FALSE);
}
//
// Create the Real Dispatch Table
//
__try {
status = ScCreateDispatchTableW((LPSERVICE_TABLE_ENTRYW)lpServiceStartTable, &DispatchTable);
}
__except (EXCEPTION_EXECUTE_HANDLER) {
status = GetExceptionCode();
if (status != EXCEPTION_ACCESS_VIOLATION) {
SCC_LOG(ERROR,"StartServiceCtrlDispatcherW:Unexpected Exception 0x%lx\n",status);
}
}
if (status != NO_ERROR) {
SetLastError(status);
return(FALSE);
}
//
// Allocate a buffer big enough to contain at least the control message
// header and a service name. This ensures that if the message is not
// a message with arguments, it can be read in a single ReadFile.
//
BYTE bPipeMessageHeader[sizeof(CTRL_MSG_HEADER) +
(MAX_SERVICE_NAME_LENGTH+1) * sizeof(WCHAR)];
//
// Connect to the Service Controller
//
status = ScConnectServiceController(&pipeHandle);
if (status != NO_ERROR) {
//
// If they're different, it's because we allocated the real name.
// Only check the first entry since this can only happen in the
// SERVICE_OWN_PROCESS case
//
if (DispatchTable->ServiceName != DispatchTable->ServiceRealName) {
LocalFree(DispatchTable->ServiceRealName);
}
LocalFree(DispatchTable);
SetLastError(status);
return(FALSE);
}
//
// Initialize the binding for the status interface (NetServiceStatus).
//
SCC_LOG(TRACE,"Initialize the Status binding\n",0);
ntStatus = InitializeStatusBinding();
if (ntStatus != STATUS_SUCCESS) {
status = RtlNtStatusToDosError(ntStatus);
CloseHandle(pipeHandle);
//
// If they're different, it's because we allocated the real name.
// Only check the first entry since this can only happen in the
// SERVICE_OWN_PROCESS case
//
if (DispatchTable->ServiceName != DispatchTable->ServiceRealName) {
LocalFree(DispatchTable->ServiceRealName);
}
LocalFree(DispatchTable);
SetLastError(status);
return(FALSE);
}
//
// Enter the dispatcher loop where we service control requests until
// all services in the service table have terminated.
//
ScDispatcherLoop(pipeHandle,
(LPCTRL_MSG_HEADER)&bPipeMessageHeader,
sizeof(bPipeMessageHeader));
CloseHandle(pipeHandle);
//
// If they're different, it's because we allocated the real name.
// Only check the first entry since this can only happen in the
// SERVICE_OWN_PROCESS case
//
if (DispatchTable->ServiceName != DispatchTable->ServiceRealName) {
LocalFree(DispatchTable->ServiceRealName);
}
return(TRUE);
}
VOID
ScDispatcherLoop(
IN HANDLE PipeHandle,
IN LPCTRL_MSG_HEADER Msg,
IN DWORD dwBufferSize
)
/*++
Routine Description:
This is the input loop that the Control Dispatcher stays in through-out
its life. Only two types of events will cause us to leave this loop:
1) The service controller instructed the dispatcher to exit.
2) The dispatcher can no longer communicate with the the
service controller.
Arguments:
PipeHandle: This is a handle to the pipe over which control
requests are received.
Return Value:
none
--*/
{
DWORD status;
DWORD controlStatus;
BOOL continueDispatch;
LPWSTR serviceName = NULL;
LPSERVICE_PARAMS lpServiceParams;
LPTHREAD_START_ROUTINE threadAddress = NULL;
LPVOID threadParms = NULL;
LPTHREAD_STARTUP_PARMSA lpspAnsiParms;
LPINTERNAL_DISPATCH_ENTRY dispatchEntry = NULL;
DWORD threadId;
HANDLE threadHandle;
DWORD i;
DWORD errorCount = 0;
DWORD dwHandlerRetVal = NO_ERROR;
//
// Input Loop
//
continueDispatch = TRUE;
#if defined(_X86_)
//
// Detect if this is a Wow64 Process ?
//
DetectWow64Process();
#endif
do {
//
// Wait for input
//
controlStatus = ScGetPipeInput(PipeHandle,
Msg,
dwBufferSize,
&lpServiceParams);
//
// If we received good input, check to see if we are to shut down
// the ControlDispatcher. If not, then obtain the dispatchEntry
// from the dispatch table.
//
if (controlStatus == NO_ERROR) {
//
// Clear the error count
//
errorCount = 0;
serviceName = (LPWSTR) ((LPBYTE)Msg + Msg->ServiceNameOffset);
SCC_LOG(TRACE, "Read from pipe succeeded for service %ws\n", serviceName);
if ((serviceName[0] == L'\0') &&
(Msg->OpCode == SERVICE_STOP)) {
//
// The Dispatcher is being asked to shut down.
// (security check not required for this operation)
// although perhaps it would be a good idea to verify
// that the request came from the Service Controller.
//
controlStatus = NO_ERROR;
continueDispatch = FALSE;
}
else {
dispatchEntry = DispatchTable;
if (Msg->OpCode == SERVICE_CONTROL_START_OWN) {
dispatchEntry->dwFlags |= SERVICE_OWN_PROCESS;
}
//
// Search the dispatch table to find the service's entry
//
if (!(dispatchEntry->dwFlags & SERVICE_OWN_PROCESS)) {
controlStatus = ScGetDispatchEntry(&dispatchEntry, serviceName);
}
if (controlStatus != NO_ERROR) {
SCC_LOG(TRACE,"Service Name not in Dispatch Table\n",0);
}
}
}
else {
if (controlStatus != ERROR_NOT_ENOUGH_MEMORY) {
//
// If an error occured and it is not an out-of-memory error,
// then the pipe read must have failed.
// In this case we Increment the error count.
// When this count reaches the MAX_RETRY_COUNT, then
// the service controller must be gone. We want to log an
// error and notify an administrator. Then go to sleep forever.
// Only a re-boot will solve this problem.
//
// We should be able to report out-of-memory errors back to
// the caller. It should be noted that out-of-memory errors
// do not clear the error count. But they don't add to it
// either.
//
errorCount++;
if (errorCount > MAX_RETRY_COUNT) {
Sleep(0xffffffff);
}
}
}
//
// Dispatch the request
//
if ((continueDispatch == TRUE) && (controlStatus == NO_ERROR)) {
status = NO_ERROR;
switch(Msg->OpCode) {
case SERVICE_CONTROL_START_SHARE:
case SERVICE_CONTROL_START_OWN:
{
SC_HANDLE hScManager = OpenSCManagerW(NULL,
NULL,
SC_MANAGER_CONNECT);
if (hScManager == NULL) {
status = GetLastError();
SCC_LOG1(ERROR,
"ScDispatcherLoop: OpenSCManagerW FAILED %d\n",
status);
}
else {
//
// Update the StatusHandle in the dispatch entry table
//
dispatchEntry->StatusHandle = OpenServiceW(hScManager,
serviceName,
SERVICE_SET_STATUS);
if (dispatchEntry->StatusHandle == NULL) {
status = GetLastError();
SCC_LOG1(ERROR,
"ScDispatcherLoop: OpenServiceW FAILED %d\n",
status);
}
CloseServiceHandle(hScManager);
}
if (status == NO_ERROR
&&
(dispatchEntry->dwFlags & SERVICE_OWN_PROCESS)
&&
(_wcsicmp(dispatchEntry->ServiceName, serviceName) != 0))
{
//
// Since we don't look up the dispatch record in the OWN_PROCESS
// case (and can't since it will break existing services), there's
// no guarantee that the name in the dispatch table (acquired from
// the RegisterServiceCtrlHandler call) is the real key name of
// the service. Since the SCM passes across the real name when
// the service is started, save it away here if necessary.
//
dispatchEntry->ServiceRealName = (LPWSTR)LocalAlloc(
LMEM_FIXED,
WCSSIZE(serviceName)
);
if (dispatchEntry->ServiceRealName == NULL) {
//
// In case somebody comes searching for the handle (though
// they shouldn't), it's nicer to return an incorrect name
// than to AV trying to copy a NULL pointer.
//
SCC_LOG1(ERROR,
"ScDispatcherLoop: Could not duplicate name for service %ws\n",
serviceName);
dispatchEntry->ServiceRealName = dispatchEntry->ServiceName;
status = ERROR_NOT_ENOUGH_MEMORY;
}
else {
wcscpy(dispatchEntry->ServiceRealName, serviceName);
}
}
if (status == NO_ERROR) {
//
// The Control Dispatcher is to start a service.
// start the new thread.
//
lpServiceParams->ThreadStartupParms.ServiceStartRoutine =
dispatchEntry->ServiceStartRoutine.U;
threadAddress = (LPTHREAD_START_ROUTINE)ScSvcctrlThreadW;
threadParms = (LPVOID)&lpServiceParams->ThreadStartupParms;
//
// If the service needs to be called with ansi parameters,
// then do the conversion here.
//
if (AnsiFlag) {
lpspAnsiParms = (LPTHREAD_STARTUP_PARMSA)
&lpServiceParams->ThreadStartupParms;
for (i = 0;
i < lpServiceParams->ThreadStartupParms.NumArgs;
i++) {
if (!ScConvertToAnsi(
*(&lpspAnsiParms->VectorTable + i),
*(&lpServiceParams->ThreadStartupParms.VectorTable + i))) {
//
// Conversion error occured.
//
SCC_LOG0(ERROR,
"ScDispatcherLoop: Could not convert "
"args to ANSI\n");
status = ERROR_NOT_ENOUGH_MEMORY;
}
}
threadAddress = (LPTHREAD_START_ROUTINE)ScSvcctrlThreadA;
threadParms = lpspAnsiParms;
}
}
if (status == NO_ERROR){
//
// Create the new thread
//
threadHandle = CreateThread (
NULL, // Thread Attributes.
0L, // Stack Size
threadAddress, // lpStartAddress
threadParms, // lpParameter
0L, // Creation Flags
&threadId); // lpThreadId
if (threadHandle == NULL) {
SCC_LOG(ERROR,
"ScDispatcherLoop: CreateThread failed %d\n",
GetLastError());
status = ERROR_SERVICE_NO_THREAD;
}
else {
CloseHandle(threadHandle);
}
}
break;
}
default:
if (dispatchEntry->ControlHandler.Ex != NULL) {
__try {
//
// Call the proper ControlHandler routine.
//
if (dispatchEntry->dwFlags & SERVICE_EX_HANDLER)
{
SCC_LOG2(TRACE,
"Calling extended ControlHandler routine %x "
"for service %ws\n",
Msg->OpCode,
serviceName);
if (lpServiceParams)
{
dwHandlerRetVal = dispatchEntry->ControlHandler.Ex(
Msg->OpCode,
lpServiceParams->HandlerExParms.dwEventType,
lpServiceParams->HandlerExParms.lpEventData,
dispatchEntry->pContext);
}
else
{
dwHandlerRetVal = dispatchEntry->ControlHandler.Ex(
Msg->OpCode,
0,
NULL,
dispatchEntry->pContext);
}
SCC_LOG3(TRACE,
"Extended ControlHandler routine %x "
"returned %d from call to service %ws\n",
Msg->OpCode,
dwHandlerRetVal,
serviceName);
}
else if (IS_NON_EX_CONTROL(Msg->OpCode))
{
SCC_LOG2(TRACE,
"Calling ControlHandler routine %x "
"for service %ws\n",
Msg->OpCode,
serviceName);
#if defined(_X86_)
//
// Hack for __CDECL callbacks. The Windows NT 3.1
// SDK didn't prototype control handler functions
// as WINAPI, so a number of existing 3rd-party
// services have their control handler functions
// built as __cdecl instead. This is a workaround.
// Note that the call to the control handler must
// be the only code between the _asm statements
//
DWORD SaveEdi;
_asm mov SaveEdi, edi;
_asm mov edi, esp; // Both __cdecl and WINAPI
// functions preserve EDI
#endif
//
// Do not add code here
//
dispatchEntry->ControlHandler.Regular(Msg->OpCode);
//
// Do not add code here
//
#if defined(_X86_)
_asm mov esp, edi;
_asm mov edi, SaveEdi;
#endif
SCC_LOG2(TRACE,
"ControlHandler routine %x returned from "
"call to service %ws\n",
Msg->OpCode,
serviceName);
}
else
{
//
// Service registered for an extended control without
// registering an extended handler. The call into the
// service process succeeded, so keep status as NO_ERROR.
// Return an error from the "handler" to notify anybody
// watching for the return code (especially PnP).
//
dwHandlerRetVal = ERROR_CALL_NOT_IMPLEMENTED;
}
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
SCC_LOG2(ERROR,
"ScDispatcherLoop: Exception 0x%lx "
"occurred in service %ws\n",
GetExceptionCode(),
serviceName);
status = ERROR_EXCEPTION_IN_SERVICE;
}
}
else
{
//
// There is no control handling routine
// registered for this service
//
status = ERROR_SERVICE_CANNOT_ACCEPT_CTRL;
}
LocalFree(lpServiceParams);
lpServiceParams = NULL;
// If status is not good here, then an exception occured
// either because the pointer to the control handling
// routine was bad, or because an exception occured
// inside the control handling routine.
//
// ??EVENTLOG??
//
break;
} // end switch.
//
// Send the status back to the sevice controller.
//
if (Msg->OpCode != SERVICE_CONTROL_SHUTDOWN)
{
SCC_LOG(TRACE, "Service %ws about to send response\n", serviceName);
ScSendResponse (PipeHandle, status, dwHandlerRetVal);
SCC_LOG(TRACE, "Service %ws returned from sending response\n", serviceName);
}
}
else {
//
// The controlStatus indicates failure, we always want to try
// to send the status back to the Service Controller.
//
SCC_LOG2(TRACE,
"Service %ws about to send response on error %lu\n",
serviceName,
controlStatus);
ScSendResponse(PipeHandle, controlStatus, dwHandlerRetVal);
SCC_LOG2(TRACE,
"Service %ws returned from sending response on error %lu\n",
serviceName,
controlStatus);
switch (controlStatus) {
case ERROR_SERVICE_NOT_IN_EXE:
case ERROR_SERVICE_NO_THREAD:
//
// The Service Name is not in this .exe's dispatch table.
// Or a thread for a new service couldn't be created.
// ignore it. The Service Controller will tell us to
// shut down if necessary.
//
controlStatus = NO_ERROR;
break;
default:
//
// If the error is not specifically recognized, continue.
//
controlStatus = NO_ERROR;
break;
}
}
}
while (continueDispatch == TRUE);
return;
}
SERVICE_STATUS_HANDLE
WINAPI
RegisterServiceCtrlHandlerHelp (
IN LPCWSTR ServiceName,
IN HANDLER_FUNCTION_TYPE ControlHandler,
IN PVOID pContext,
IN DWORD dwFlags
)
/*++
Routine Description:
This helper function enters a pointer to a control handling routine
and a pointer to a security descriptor into the Control Dispatcher's
dispatch table. It does the work for the RegisterServiceCtrlHandler*
family of APIs
Arguments:
ServiceName - This is a pointer to the Service Name string.
ControlHandler - This is a pointer to the service's control handling
routine.
pContext - This is a pointer to context data supplied by the user.
dwFlags - This is a set of flags that give information about the
control handling routine (currently only discerns between extended
and non-extended handlers)
Return Value:
This function returns a handle to the service that is to be used in
subsequent calls to SetServiceStatus. If the return value is NULL,
an error has occured, and GetLastError can be used to obtain the
error value. Possible values for error are:
NO_ERROR - If the operation was successful.
ERROR_INVALID_PARAMETER - The pointer to the control handler function
is NULL.
ERROR_INVALID_DATA -
ERROR_SERVICE_NOT_IN_EXE - The serviceName could not be found in
the dispatch table. This indicates that the configuration database
says the serice is in this process, but the service name doesn't
exist in the dispatch table.
--*/
{
DWORD status;
LPINTERNAL_DISPATCH_ENTRY dispatchEntry;
//
// Find the service in the dispatch table.
//
dispatchEntry = DispatchTable;
__try {
status = ScGetDispatchEntry(&dispatchEntry, (LPWSTR) ServiceName);
}
__except (EXCEPTION_EXECUTE_HANDLER) {
status = GetExceptionCode();
if (status != EXCEPTION_ACCESS_VIOLATION) {
SCC_LOG(ERROR,
"RegisterServiceCtrlHandlerHelp: Unexpected Exception 0x%lx\n",
status);
}
}
if(status != NO_ERROR) {
SCC_LOG(ERROR,
"RegisterServiceCtrlHandlerHelp: can't find dispatch entry\n",0);
SetLastError(status);
return(0L);
}
//
// Insert the ControlHandler pointer
//
if (ControlHandler.Ex == NULL) {
SCC_LOG(ERROR,
"RegisterServiceCtrlHandlerHelp: Ptr to ctrlhandler is NULL\n",
0);
SetLastError(ERROR_INVALID_PARAMETER);
return(0L);
}
//
// Insert the entries into the table
//
if (dwFlags & SERVICE_EX_HANDLER) {
dispatchEntry->dwFlags |= SERVICE_EX_HANDLER;
dispatchEntry->ControlHandler.Ex = ControlHandler.Ex;
dispatchEntry->pContext = pContext;
}
else {
dispatchEntry->dwFlags &= ~(SERVICE_EX_HANDLER);
dispatchEntry->ControlHandler.Regular = ControlHandler.Regular;
}
//
// This cast is OK -- see comment in I_ScPnPGetServiceName
//
return( (SERVICE_STATUS_HANDLE) dispatchEntry->StatusHandle );
}
SERVICE_STATUS_HANDLE
WINAPI
RegisterServiceCtrlHandlerW (
IN LPCWSTR ServiceName,
IN LPHANDLER_FUNCTION ControlHandler
)
/*++
Routine Description:
This function enters a pointer to a control handling
routine into the Control Dispatcher's dispatch table.
Arguments:
ServiceName -- The service's name
ControlHandler -- Pointer to the control handling routine
Return Value:
Anything returned by RegisterServiceCtrlHandlerHelp
--*/
{
HANDLER_FUNCTION_TYPE Handler;
Handler.Regular = ControlHandler;
return RegisterServiceCtrlHandlerHelp(ServiceName,
Handler,
NULL,
0);
}
SERVICE_STATUS_HANDLE
WINAPI
RegisterServiceCtrlHandlerA (
IN LPCSTR ServiceName,
IN LPHANDLER_FUNCTION ControlHandler
)
/*++
Routine Description:
This is the ansi entry point for RegisterServiceCtrlHandler.
Arguments:
Return Value:
--*/
{
LPWSTR ServiceNameW;
SERVICE_STATUS_HANDLE statusHandle;
if (!ScConvertToUnicode(&ServiceNameW, ServiceName)) {
//
// This can only fail because of a failed LocalAlloc call
// or else the ansi string is garbage.
//
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return(0L);
}
statusHandle = RegisterServiceCtrlHandlerW(ServiceNameW, ControlHandler);
LocalFree(ServiceNameW);
return(statusHandle);
}
SERVICE_STATUS_HANDLE
WINAPI
RegisterServiceCtrlHandlerExW (
IN LPCWSTR ServiceName,
IN LPHANDLER_FUNCTION_EX ControlHandler,
IN PVOID pContext
)
/*++
Routine Description:
This function enters a pointer to an extended control handling
routine into the Control Dispatcher's dispatch table. It is
analogous to RegisterServiceCtrlHandlerW.
Arguments:
ServiceName -- The service's name
ControlHandler -- A pointer to an extended control handling routine
pContext -- User-supplied data that is passed to the control handler
Return Value:
Anything returned by RegisterServiceCtrlHandlerHelp
--*/
{
HANDLER_FUNCTION_TYPE Handler;
Handler.Ex = ControlHandler;
return RegisterServiceCtrlHandlerHelp(ServiceName,
Handler,
pContext,
SERVICE_EX_HANDLER);
}
SERVICE_STATUS_HANDLE
WINAPI
RegisterServiceCtrlHandlerExA (
IN LPCSTR ServiceName,
IN LPHANDLER_FUNCTION_EX ControlHandler,
IN PVOID pContext
)
/*++
Routine Description:
This is the ansi entry point for RegisterServiceCtrlHandlerEx.
Arguments:
Return Value:
--*/
{
LPWSTR ServiceNameW;
SERVICE_STATUS_HANDLE statusHandle;
if(!ScConvertToUnicode(&ServiceNameW, ServiceName)) {
//
// This can only fail because of a failed LocalAlloc call
// or else the ansi string is garbage.
//
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return(0L);
}
statusHandle = RegisterServiceCtrlHandlerExW(ServiceNameW,
ControlHandler,
pContext);
LocalFree(ServiceNameW);
return(statusHandle);
}
DWORD
ScCreateDispatchTableW(
IN CONST SERVICE_TABLE_ENTRYW *lpServiceStartTable,
OUT LPINTERNAL_DISPATCH_ENTRY *DispatchTablePtr
)
/*++
Routine Description:
This routine allocates space for the Control Dispatchers Dispatch Table.
It also initializes the table with the data that the service main
routine passed in with the lpServiceStartTable parameter.
This routine expects that pointers in the user's dispatch table point
to valid information. And that that information will stay valid and
fixed through out the life of the Control Dispatcher. In otherwords,
the ServiceName string better not move or get cleared.
Arguments:
lpServiceStartTable - This is a pointer to the first entry in the
dispatch table that the service's main routine passed in .
DispatchTablePtr - This is a pointer to the location where the
Service Controller's dispatch table is to be stored.
Return Value:
NO_ERROR - The operation was successful.
ERROR_NOT_ENOUGH_MEMORY - The memory allocation failed.
ERROR_INVALID_PARAMETER - There are no entries in the dispatch table.
--*/
{
DWORD numEntries;
LPINTERNAL_DISPATCH_ENTRY dispatchTable;
const SERVICE_TABLE_ENTRYW * entryPtr;
//
// Count the number of entries in the user dispatch table
//
numEntries = 0;
entryPtr = lpServiceStartTable;
while (entryPtr->lpServiceName != NULL) {
numEntries++;
entryPtr++;
}
if (numEntries == 0) {
SCC_LOG(ERROR,"ScCreateDispatchTable:No entries in Dispatch table!\n",0);
return(ERROR_INVALID_PARAMETER);
}
//
// Allocate space for the Control Dispatcher's Dispatch Table
//
dispatchTable = (LPINTERNAL_DISPATCH_ENTRY)LocalAlloc(LMEM_ZEROINIT,
sizeof(INTERNAL_DISPATCH_ENTRY) * (numEntries + 1));
if (dispatchTable == NULL) {
SCC_LOG(ERROR,"ScCreateDispatchTable: Local Alloc failed rc = %d\n",
GetLastError());
return (ERROR_NOT_ENOUGH_MEMORY);
}
//
// Move user dispatch info into the Control Dispatcher's table.
//
*DispatchTablePtr = dispatchTable;
entryPtr = lpServiceStartTable;
while (entryPtr->lpServiceName != NULL) {
dispatchTable->ServiceName = entryPtr->lpServiceName;
dispatchTable->ServiceRealName = entryPtr->lpServiceName;
dispatchTable->ServiceStartRoutine.U= entryPtr->lpServiceProc;
dispatchTable->ControlHandler.Ex = NULL;
dispatchTable->StatusHandle = NULL;
dispatchTable->dwFlags = 0;
entryPtr++;
dispatchTable++;
}
return (NO_ERROR);
}
DWORD
ScCreateDispatchTableA(
IN CONST SERVICE_TABLE_ENTRYA *lpServiceStartTable,
OUT LPINTERNAL_DISPATCH_ENTRY *DispatchTablePtr
)
/*++
Routine Description:
This routine allocates space for the Control Dispatchers Dispatch Table.
It also initializes the table with the data that the service main
routine passed in with the lpServiceStartTable parameter.
This routine expects that pointers in the user's dispatch table point
to valid information. And that that information will stay valid and
fixed through out the life of the Control Dispatcher. In otherwords,
the ServiceName string better not move or get cleared.
Arguments:
lpServiceStartTable - This is a pointer to the first entry in the
dispatch table that the service's main routine passed in .
DispatchTablePtr - This is a pointer to the location where the
Service Controller's dispatch table is to be stored.
Return Value:
NO_ERROR - The operation was successful.
ERROR_NOT_ENOUGH_MEMORY - The memory allocation failed.
ERROR_INVALID_PARAMETER - There are no entries in the dispatch table.
--*/
{
DWORD numEntries;
DWORD status = NO_ERROR;
LPINTERNAL_DISPATCH_ENTRY dispatchTable;
const SERVICE_TABLE_ENTRYA * entryPtr;
//
// Count the number of entries in the user dispatch table
//
numEntries = 0;
entryPtr = lpServiceStartTable;
while (entryPtr->lpServiceName != NULL) {
numEntries++;
entryPtr++;
}
if (numEntries == 0) {
SCC_LOG(ERROR,"ScCreateDispatchTable:No entries in Dispatch table!\n",0);
return(ERROR_INVALID_PARAMETER);
}
//
// Allocate space for the Control Dispatcher's Dispatch Table
//
dispatchTable = (LPINTERNAL_DISPATCH_ENTRY)LocalAlloc(LMEM_ZEROINIT,
sizeof(INTERNAL_DISPATCH_ENTRY) * (numEntries + 1));
if (dispatchTable == NULL) {
SCC_LOG(ERROR,"ScCreateDispatchTableA: Local Alloc failed rc = %d\n",
GetLastError());
return (ERROR_NOT_ENOUGH_MEMORY);
}
//
// Move user dispatch info into the Control Dispatcher's table.
//
*DispatchTablePtr = dispatchTable;
entryPtr = lpServiceStartTable;
while (entryPtr->lpServiceName != NULL) {
//
// Convert the service name to unicode
//
__try {
if (!ScConvertToUnicode(
&(dispatchTable->ServiceName),
entryPtr->lpServiceName)) {
//
// The convert failed.
//
SCC_LOG(ERROR,"ScCreateDispatcherTableA:ScConvertToUnicode failed\n",0);
//
// This is the only reason for failure that I can think of.
//
status = ERROR_NOT_ENOUGH_MEMORY;
}
}
__except (EXCEPTION_EXECUTE_HANDLER) {
status = GetExceptionCode();
if (status != EXCEPTION_ACCESS_VIOLATION) {
SCC_LOG(ERROR,
"ScCreateDispatchTableA: Unexpected Exception 0x%lx\n",status);
}
}
if (status != NO_ERROR) {
//
// If an error occured, free up the allocated resources.
//
dispatchTable = *DispatchTablePtr;
while (dispatchTable->ServiceName != NULL) {
LocalFree(dispatchTable->ServiceName);
dispatchTable++;
}
LocalFree(*DispatchTablePtr);
return(status);
}
//
// Fill in the rest of the dispatch entry.
//
dispatchTable->ServiceRealName = dispatchTable->ServiceName;
dispatchTable->ServiceStartRoutine.A= entryPtr->lpServiceProc;
dispatchTable->ControlHandler.Ex = NULL;
dispatchTable->StatusHandle = NULL;
dispatchTable->dwFlags = 0;
entryPtr++;
dispatchTable++;
}
return (NO_ERROR);
}
DWORD
ScReadServiceParms(
IN LPCTRL_MSG_HEADER Msg,
IN DWORD dwNumBytesRead,
OUT LPBYTE *ppServiceParams,
OUT LPBYTE *ppTempArgPtr,
OUT LPDWORD lpdwRemainingArgBytes
)
/*++
Routine Description:
This routine calculates the number of bytes needed for the service's
control parameters by using the arg count information in the
message header. The parameter structure is allocated and
as many bytes of argument information as have been captured so far
are placed into the buffer. A second read of the pipe may be necessary
to obtain the remaining bytes of argument information.
NOTE: This function allocates enough space in the startup parameter
buffer for the service name and pointer as well as the rest of the
arguments. However, it does not put the service name into the argument
list. This is because it may take two calls to this routine to
get all the argument information. We can't insert the service name
string until we have all the rest of the argument data.
[serviceNamePtr][argv1][argv2]...[argv1Str][argv2Str]...[serviceNameStr]
or
[serviceNamePtr][dwEventType][EventData][serviceNameStr]
Arguments:
Msg - A pointer to the pipe message header.
dwNumBytesRead - The number of bytes read in the first pipe read.
ppServiceParams - A pointer to a location where the pointer to the
thread startup parameter structure is to be placed.
ppTempArgPtr - A location that will contain the pointer to where
more argument data can be placed by a second read of the pipe.
lpdwRemainingArgBytes - Returns with a count of the number of argument
bytes that remain to be read from the pipe.
Return Value:
NO_ERROR - If the operation was successful.
ERROR_NOT_ENOUGH_MEMORY - If the memory allocation was unsuccessful.
Note:
--*/
{
DWORD dwNameSize; // num bytes in ServiceName.
DWORD dwBufferSize; // num bytes for parameter buffer
LONG lArgBytesRead; // number of arg bytes in first read.
LPSERVICE_PARAMS lpTempParams;
//
// Set out pointer to no arguments unless we discover otherwise
//
*ppTempArgPtr = NULL;
SCC_LOG(TRACE,"ScReadServiceParms: Get service parameters from pipe\n",0);
//
// Note: Here we assume that the service name was read into the buffer
// in its entirety.
//
dwNameSize = (DWORD) WCSSIZE((LPWSTR) ((LPBYTE) Msg + Msg->ServiceNameOffset));
//
// Calculate the size of buffer needed. This will consist of a
// SERVICE_PARAMS structure, plus the service name and a pointer
// for it, plus the rest of the arg info sent in the message
// (We are wasting 4 bytes here since the first pointer in
// the vector table is accounted for twice - but what the heck!).
//
dwBufferSize = Msg->Count -
sizeof(CTRL_MSG_HEADER) +
sizeof(SERVICE_PARAMS) +
sizeof(LPWSTR);
//
// Allocate the memory for the service parameters
//
lpTempParams = (LPSERVICE_PARAMS)LocalAlloc (LMEM_ZEROINIT, dwBufferSize);
if (lpTempParams == NULL)
{
SCC_LOG1(ERROR,
"ScReadServiceParms: LocalAlloc failed rc = %d\n",
GetLastError());
return ERROR_NOT_ENOUGH_MEMORY;
}
lArgBytesRead = dwNumBytesRead - sizeof(CTRL_MSG_HEADER) - dwNameSize;
*lpdwRemainingArgBytes = Msg->Count - dwNumBytesRead;
//
// Unpack message-specific arguments
//
switch (Msg->OpCode) {
case SERVICE_CONTROL_START_OWN:
case SERVICE_CONTROL_START_SHARE:
SCC_LOG(TRACE,"ScReadServiceParms: Starting a service\n", 0);
if (Msg->NumCmdArgs != 0) {
//
// There's only a vector table and ThreadStartupParms
// when the service starts up
//
*ppTempArgPtr = (LPBYTE)&lpTempParams->ThreadStartupParms.VectorTable;
//
// Leave the first vector location blank for the service name
// pointer.
//
(*ppTempArgPtr) += sizeof(LPWSTR);
//
// adjust lArgBytesRead to remove any extra bytes that are
// there for alignment. If a name that is not in the dispatch
// table is passed in, it could be larger than our buffer.
// This could cause lArgBytesRead to become negative.
// However it should fail safe anyway since the name simply
// won't be recognized and an error will be returned.
//
lArgBytesRead -= (Msg->ArgvOffset - Msg->ServiceNameOffset - dwNameSize);
//
// Copy any portion of the command arg info from the first read
// into the buffer that is to be used for the second read.
//
if (lArgBytesRead > 0) {
RtlCopyMemory(*ppTempArgPtr,
(LPBYTE)Msg + Msg->ArgvOffset,
lArgBytesRead);
*ppTempArgPtr += lArgBytesRead;
}
}
break;
case SERVICE_CONTROL_DEVICEEVENT:
case SERVICE_CONTROL_HARDWAREPROFILECHANGE:
case SERVICE_CONTROL_POWEREVENT:
case SERVICE_CONTROL_SESSIONCHANGE:
{
//
// This is a PnP, power, or TS message
//
SCC_LOG1(TRACE,
"ScReadServiceParms: Receiving PnP/power/TS event %x\n",
Msg->OpCode);
//
// adjust lArgBytesRead to remove any extra bytes that are
// there for alignment. If a name that is not in the dispatch
// table is passed in, it could be larger than our buffer.
// This could cause lArgBytesRead to become negative.
// However it should fail safe anyway since the name simply
// won't be recognized and an error will be returned.
//
lArgBytesRead -= (Msg->ArgvOffset - Msg->ServiceNameOffset - dwNameSize);
*ppTempArgPtr = (LPBYTE) &lpTempParams->HandlerExParms.dwEventType;
if (lArgBytesRead > 0)
{
LPBYTE lpArgs;
LPHANDLEREX_PARMS lpHandlerExParms = (LPHANDLEREX_PARMS) (*ppTempArgPtr);
lpArgs = (LPBYTE) Msg + Msg->ArgvOffset;
lpHandlerExParms->dwEventType = *(LPDWORD) lpArgs;
lpArgs += sizeof(DWORD);
lArgBytesRead -= sizeof(DWORD);
RtlCopyMemory(lpHandlerExParms + 1,
lpArgs,
lArgBytesRead);
lpHandlerExParms->lpEventData = lpHandlerExParms + 1;
*ppTempArgPtr = (LPBYTE) (lpHandlerExParms + 1) + lArgBytesRead;
}
break;
}
}
*ppServiceParams = (LPBYTE) lpTempParams;
return NO_ERROR;
}
DWORD
ScConnectServiceController(
OUT LPHANDLE PipeHandle
)
/*++
Routine Description:
This function connects to the Service Controller Pipe.
Arguments:
PipeHandle - This is a pointer to the location where the PipeHandle
is to be placed.
Return Value:
NO_ERROR - if the operation was successful.
ERROR_FAILED_SERVICE_CONTROLLER_CONNECT - if we failed to connect.
--*/
{
BOOL status;
DWORD apiStatus;
DWORD response;
DWORD pipeMode;
DWORD numBytesWritten;
WCHAR wszPipeName[sizeof(CONTROL_PIPE_NAME) / sizeof(WCHAR) + PID_LEN] = CONTROL_PIPE_NAME;
//
// Generate the pipe name -- Security process uses PID 0 since the
// SCM doesn't have the PID at connect-time (it gets it from the
// pipe transaction with the LSA)
//
if (g_fIsSecProc) {
response = 0;
}
else {
//
// Read this process's pipe ID from the registry.
//
HKEY hCurrentValueKey;
status = RegOpenKeyEx(
HKEY_LOCAL_MACHINE,
"System\\CurrentControlSet\\Control\\ServiceCurrent",
0,
KEY_QUERY_VALUE,
&hCurrentValueKey);
if (status == ERROR_SUCCESS)
{
DWORD ValueType;
DWORD cbData = sizeof(response);
status = RegQueryValueEx(
hCurrentValueKey,
NULL, // Use key's unnamed value
0,
&ValueType,
(LPBYTE) &response,
&cbData);
RegCloseKey(hCurrentValueKey);
if (status != ERROR_SUCCESS || ValueType != REG_DWORD)
{
SCC_LOG(ERROR,
"ScConnectServiceController: RegQueryValueEx FAILED %d\n",
status);
return(ERROR_FAILED_SERVICE_CONTROLLER_CONNECT);
}
}
else
{
SCC_LOG(ERROR,
"ScConnectServiceController: RegOpenKeyEx FAILED %d\n",
status);
return(ERROR_FAILED_SERVICE_CONTROLLER_CONNECT);
}
}
_itow(response, wszPipeName + sizeof(CONTROL_PIPE_NAME) / sizeof(WCHAR) - 1, 10);
status = WaitNamedPipeW (
wszPipeName,
CONTROL_WAIT_PERIOD);
if (status != TRUE) {
SCC_LOG(ERROR,"ScConnectServiceController:WaitNamedPipe failed rc = %d\n",
GetLastError());
}
SCC_LOG(TRACE,"ScConnectServiceController:WaitNamedPipe success\n",0);
*PipeHandle = CreateFileW(
wszPipeName, // lpFileName
GENERIC_READ | GENERIC_WRITE, // dwDesiredAccess
FILE_SHARE_READ | FILE_SHARE_WRITE, // dwShareMode
NULL, // lpSecurityAttributes
OPEN_EXISTING, // dwCreationDisposition
FILE_ATTRIBUTE_NORMAL, // dwFileAttributes
0L); // hTemplateFile
if (*PipeHandle == INVALID_HANDLE_VALUE) {
SCC_LOG(ERROR,"ScConnectServiceController:CreateFile failed rc = %d\n",
GetLastError());
return(ERROR_FAILED_SERVICE_CONTROLLER_CONNECT);
}
SCC_LOG(TRACE,"ScConnectServiceController:CreateFile success\n",0);
//
// Set pipe mode
//
pipeMode = PIPE_READMODE_MESSAGE | PIPE_WAIT;
status = SetNamedPipeHandleState (
*PipeHandle,
&pipeMode,
NULL,
NULL);
if (status != TRUE) {
SCC_LOG(ERROR,"ScConnectServiceController:SetNamedPipeHandleState failed rc = %d\n",
GetLastError());
return(ERROR_FAILED_SERVICE_CONTROLLER_CONNECT);
}
else {
SCC_LOG(TRACE,
"ScConnectServiceController SetNamedPipeHandleState Success\n",0);
}
//
// Send initial status - This is the process Id for the service process.
//
response = GetCurrentProcessId();
apiStatus = WriteFile (
*PipeHandle,
&response,
sizeof(response),
&numBytesWritten,
NULL);
if (apiStatus != TRUE) {
//
// If this fails, there is a chance that the pipe is still in good
// shape. So we just go on.
//
// ??EVENTLOG??
//
SCC_LOG(ERROR,"ScConnectServiceController: WriteFile failed, rc= %d\n", GetLastError());
}
else {
SCC_LOG(TRACE,
"ScConnectServiceController: WriteFile success, bytes Written= %d\n",
numBytesWritten);
}
return(NO_ERROR);
}
VOID
ScExpungeMessage(
IN HANDLE PipeHandle
)
/*++
Routine Description:
This routine cleans the remaining portion of a message out of the pipe.
It is called in response to an unsuccessful attempt to allocate the
correct buffer size from the heap. In this routine a small buffer is
allocated on the stack, and successive reads are made until a status
other than ERROR_MORE_DATA is received.
Arguments:
PipeHandle - This is a handle to the pipe in which the message resides.
Return Value:
none - If this operation fails, there is not much I can do about
the data in the pipe.
--*/
{
#define EXPUNGE_BUF_SIZE 100
DWORD status;
DWORD dwNumBytesRead = 0;
BYTE msg[EXPUNGE_BUF_SIZE];
do {
status = ReadFile (
PipeHandle,
msg,
EXPUNGE_BUF_SIZE,
&dwNumBytesRead,
NULL);
}
while( status == ERROR_MORE_DATA);
}
DWORD
ScGetPipeInput (
IN HANDLE PipeHandle,
IN OUT LPCTRL_MSG_HEADER Msg,
IN DWORD dwBufferSize,
OUT LPSERVICE_PARAMS *ppServiceParams
)
/*++
Routine Description:
This routine reads a control message from the pipe and places it into
a message buffer. This routine also allocates a structure for
the service thread information. This structure will eventually
contain everything that is needed to invoke the service startup
routine in the context of a new thread. Items contained in the
structure are:
1) The pointer to the startup routine,
2) The number of arguments, and
3) The table of vectors to the arguments.
Since this routine has knowledge about the buffer size needed for
the arguments, the allocation is done here.
Arguments:
PipeHandle - This is the handle for the pipe that is to be read.
Msg - This is a pointer to a buffer where the data is to be placed.
dwBufferSize - This is the size (in bytes) of the buffer that data is to
be placed in.
ppServiceParams - This is the location where the command args will
be placed
Return Value:
NO_ERROR - if the operation was successful.
ERROR_NOT_ENOUGH_MEMORY - There was not enough memory to create a large
enough buffer for the command line arguments.
ERROR_INVALID_DATA - This is returned if we did not receive a complete
CTRL_MESSAGE_HEADER on the first read.
Any error that ReadFile might return could be returned by this function.
(We may want to return something more specific like ERROR_READ_FAULT)
--*/
{
DWORD status;
BOOL readStatus;
DWORD dwNumBytesRead = 0;
DWORD dwRemainingArgBytes;
LPBYTE pTempArgPtr;
*ppServiceParams = NULL;
//
// Read the header and name string from the pipe.
// NOTE: The number of bytes for the name string is determined by
// the longest service name in the service process. If the actual
// string read is shorter, then the beginning of the command arg
// data may be read with this read.
// Also note: The buffer is large enough to accommodate the longest
// permissible service name.
//
readStatus = ReadFile(PipeHandle,
Msg,
dwBufferSize,
&dwNumBytesRead,
NULL);
SCC_LOG(TRACE,"ScGetPipeInput:ReadFile buffer size = %ld\n",dwBufferSize);
SCC_LOG(TRACE,"ScGetPipeInput:ReadFile dwNumBytesRead = %ld\n",dwNumBytesRead);
if ((readStatus == TRUE) && (dwNumBytesRead > sizeof(CTRL_MSG_HEADER))) {
//
// The Read File read the complete message in one read. So we
// can return with the data.
//
SCC_LOG(TRACE,"ScGetPipeInput: Success!\n",0);
switch (Msg->OpCode) {
case SERVICE_CONTROL_START_OWN:
case SERVICE_CONTROL_START_SHARE:
//
// Read in any start arguments for the service
//
status = ScReadServiceParms(Msg,
dwNumBytesRead,
(LPBYTE *)ppServiceParams,
&pTempArgPtr,
&dwRemainingArgBytes);
if (status != NO_ERROR) {
return status;
}
//
// Change the offsets back into pointers.
//
ScNormalizeCmdLineArgs(Msg,
&(*ppServiceParams)->ThreadStartupParms);
break;
case SERVICE_CONTROL_DEVICEEVENT:
case SERVICE_CONTROL_HARDWAREPROFILECHANGE:
case SERVICE_CONTROL_POWEREVENT:
case SERVICE_CONTROL_SESSIONCHANGE:
//
// Read in the service's PnP/power arguments
//
status = ScReadServiceParms(Msg,
dwNumBytesRead,
(LPBYTE *)ppServiceParams,
&pTempArgPtr,
&dwRemainingArgBytes);
if (status != NO_ERROR) {
return status;
}
break;
default:
ASSERT(Msg->NumCmdArgs == 0);
break;
}
return NO_ERROR;
}
else {
//
// An error was returned from ReadFile. ERROR_MORE_DATA
// means that we need to read some arguments from the buffer.
// Any other error is unexpected, and generates an internal error.
//
if (readStatus != TRUE) {
status = GetLastError();
if (status != ERROR_MORE_DATA) {
SCC_LOG(ERROR,"ScGetPipeInput:Unexpected return code, rc= %ld\n",
status);
return status;
}
}
else {
//
// The read was successful, but we didn't get a complete
// CTRL_MESSAGE_HEADER.
//
return ERROR_INVALID_DATA;
}
}
//
// We must have received an ERROR_MORE_DATA to go down this
// path. This means that the message contains more data. Namely,
// service arguments must be present. Therefore, the pipe must
// be read again. Since the header indicates how many bytes are
// needed, we will allocate a buffer large enough to hold all the
// service arguments.
//
// If a portion of the arguments was read in the first read,
// they will be put in this new buffer. That is so that all the
// command line arg info is in one place.
//
status = ScReadServiceParms(Msg,
dwNumBytesRead,
(LPBYTE *)ppServiceParams,
&pTempArgPtr,
&dwRemainingArgBytes);
if (status != NO_ERROR) {
ScExpungeMessage(PipeHandle);
return status;
}
readStatus = ReadFile(PipeHandle,
pTempArgPtr,
dwRemainingArgBytes,
&dwNumBytesRead,
NULL);
if ((readStatus != TRUE) || (dwNumBytesRead < dwRemainingArgBytes)) {
if (readStatus != TRUE) {
status = GetLastError();
SCC_LOG1(ERROR,
"ScGetPipeInput: ReadFile error (2nd read), rc = %ld\n",
status);
}
else {
status = ERROR_BAD_LENGTH;
}
SCC_LOG2(ERROR,
"ScGetPipeInput: ReadFile read: %d, expected: %d\n",
dwNumBytesRead,
dwRemainingArgBytes);
LocalFree(*ppServiceParams);
return status;
}
if (Msg->OpCode == SERVICE_CONTROL_START_OWN ||
Msg->OpCode == SERVICE_CONTROL_START_SHARE) {
//
// Change the offsets back into pointers.
//
ScNormalizeCmdLineArgs(Msg, &(*ppServiceParams)->ThreadStartupParms);
}
return NO_ERROR;
}
DWORD
ScGetDispatchEntry (
IN OUT LPINTERNAL_DISPATCH_ENTRY *DispatchEntryPtr,
IN LPWSTR ServiceName
)
/*++
Routine Description:
Finds an entry in the Dispatch Table for a particular service which
is identified by a service name string.
Arguments:
DispatchEntryPtr - As an input, the is a location where a pointer to
the top of the DispatchTable is placed. On return, this is the
location where the pointer to the specific dispatch entry is to
be placed. This is an opaque pointer because it could be either
ansi or unicode depending on the operational state of the dispatcher.
ServiceName - This is a pointer to the service name string that was
supplied by the service. Note that it may not be the service's
real name since we never check services that run in their own
process (bug that can never be fixed since it will break existing
services). We must check for this name instead of the real
one.
Return Value:
NO_ERROR - The operation was successful.
ERROR_SERVICE_NOT_IN_EXE - The serviceName could not be found in
the dispatch table. This indicates that the configuration database
says the serice is in this process, but the service name doesn't
exist in the dispatch table.
--*/
{
LPINTERNAL_DISPATCH_ENTRY entryPtr;
DWORD found = FALSE;
entryPtr = *DispatchEntryPtr;
if (entryPtr->dwFlags & SERVICE_OWN_PROCESS) {
return (NO_ERROR);
}
while (entryPtr->ServiceName != NULL) {
if (_wcsicmp(entryPtr->ServiceName, ServiceName) == 0) {
found = TRUE;
break;
}
entryPtr++;
}
if (found) {
*DispatchEntryPtr = entryPtr;
}
else {
SCC_LOG(ERROR,"ScGetDispatchEntry: DispatchEntry not found\n"
" Configuration error - the %ws service is not in this .exe file!\n"
" Check the table passed to StartServiceCtrlDispatcher.\n", ServiceName);
return(ERROR_SERVICE_NOT_IN_EXE);
}
return(NO_ERROR);
}
VOID
ScNormalizeCmdLineArgs(
IN OUT LPCTRL_MSG_HEADER Msg,
IN OUT LPTHREAD_STARTUP_PARMSW ThreadStartupParms
)
/*++
Routine Description:
Normalizes the command line argument information that came across in
the pipe. The argument information is stored in a buffer that consists
of an array of string pointers followed by the strings themselves.
However, in the pipe, the pointers are replaced with offsets. This
routine transforms the offsets into real pointers.
This routine also puts the service name into the array of argument
vectors, and adds the service name string to the end of the
buffer (space has already been allocated for it).
Arguments:
Msg - This is a pointer to the Message. Useful information from this
includes the NumCmdArgs and the service name.
ThreadStartupParms - A pointer to the thread startup parameter structure.
Return Value:
none.
--*/
{
DWORD i;
LPWSTR *argv;
DWORD numCmdArgs;
LPWSTR *serviceNameVector;
LPWSTR serviceNamePtr;
#if defined(_X86_)
PULONG64 argv64 = NULL;
#endif
numCmdArgs = Msg->NumCmdArgs;
argv = &(ThreadStartupParms->VectorTable);
//
// Save the first argv for the service name.
//
serviceNameVector = argv;
argv++;
//
// Normalize the Command Line Argument information by replacing
// offsets in buffer with pointers.
//
// NOTE: The elaborate casting that takes place here is because we
// are taking some (pointer sized) offsets, and turning them back
// into pointers to strings. The offsets are in bytes, and are
// relative to the beginning of the vector table which contains
// pointers to the various command line arg strings.
//
#if defined(_X86_)
if (g_fWow64Process) {
//
// Pointers on the 64-bit land are 64-bit so make argv
// point to the 1st arg after the service name offset
//
argv64 = (PULONG64)argv;
}
#endif
for (i = 0; i < numCmdArgs; i++) {
#if defined(_X86_)
if (g_fWow64Process)
argv[i] = (LPWSTR)((LPBYTE)argv + PtrToUlong(argv64[i]));
else
#endif
argv[i] = (LPWSTR)((LPBYTE)argv + PtrToUlong(argv[i]));
}
//
// If we are starting a service, then we need to add the service name
// to the argument vectors.
//
if ((Msg->OpCode == SERVICE_CONTROL_START_SHARE) ||
(Msg->OpCode == SERVICE_CONTROL_START_OWN)) {
numCmdArgs++;
if (numCmdArgs > 1) {
//
// Find the location for the service name string by finding
// the pointer to the last argument adding its string length
// to it.
//
serviceNamePtr = argv[i-1];
serviceNamePtr += (wcslen(serviceNamePtr) + 1);
}
else {
serviceNamePtr = (LPWSTR)argv;
}
wcscpy(serviceNamePtr, (LPWSTR) ((LPBYTE)Msg + Msg->ServiceNameOffset));
*serviceNameVector = serviceNamePtr;
}
ThreadStartupParms->NumArgs = numCmdArgs;
}
VOID
ScSendResponse (
IN HANDLE PipeHandle,
IN DWORD Response,
IN DWORD dwHandlerRetVal
)
/*++
Routine Description:
This routine sends a status response to the Service Controller's pipe.
Arguments:
Response - This is the status message that is to be sent.
dwHandlerRetVal - This is the return value from the service's control
handler function (NO_ERROR for non-Ex handlers)
Return Value:
none.
--*/
{
DWORD numBytesWritten;
PIPE_RESPONSE_MSG prmResponse;
prmResponse.dwDispatcherStatus = Response;
prmResponse.dwHandlerRetVal = dwHandlerRetVal;
if (!WriteFile(PipeHandle,
&prmResponse,
sizeof(PIPE_RESPONSE_MSG),
&numBytesWritten,
NULL))
{
SCC_LOG1(ERROR,
"ScSendResponse: WriteFile failed, rc= %d\n",
GetLastError());
}
}
DWORD
ScSvcctrlThreadW(
IN LPTHREAD_STARTUP_PARMSW lpThreadStartupParms
)
/*++
Routine Description:
This is the thread for the newly started service. This code
calls the service's main thread with parameters from the
ThreadStartupParms structure.
NOTE: The first item in the argument vector table is the pointer to
the service registry path string.
Arguments:
lpThreadStartupParms - This is a pointer to the ThreadStartupParms
structure. (This is a unicode structure);
Return Value:
--*/
{
//
// Call the Service's Main Routine.
//
((LPSERVICE_MAIN_FUNCTIONW)lpThreadStartupParms->ServiceStartRoutine) (
lpThreadStartupParms->NumArgs,
&lpThreadStartupParms->VectorTable);
LocalFree(lpThreadStartupParms);
return(0);
}
DWORD
ScSvcctrlThreadA(
IN LPTHREAD_STARTUP_PARMSA lpThreadStartupParms
)
/*++
Routine Description:
This is the thread for the newly started service. This code
calls the service's main thread with parameters from the
ThreadStartupParms structure.
NOTE: The first item in the argument vector table is the pointer to
the service registry path string.
Arguments:
lpThreadStartupParms - This is a pointer to the ThreadStartupParms
structure. (This is a unicode structure);
Return Value:
--*/
{
//
// Call the Service's Main Routine.
//
// NOTE: The first item in the argument vector table is the pointer to
// the service registry path string.
//
((LPSERVICE_MAIN_FUNCTIONA)lpThreadStartupParms->ServiceStartRoutine) (
lpThreadStartupParms->NumArgs,
&lpThreadStartupParms->VectorTable);
LocalFree(lpThreadStartupParms);
return(0);
}
|
[
"support@cryptoalgo.cf"
] |
support@cryptoalgo.cf
|
752e87eeeb1ac4263dd0b57c49b3da9214e6370c
|
2b3850a1b1c48202e5fe735649feabb7ed042cff
|
/src/vecteur3_test.cpp
|
15f75e6d77c43cb1a46636116b06cb970af2d940
|
[] |
no_license
|
Petit-Chaperon-Rouge/C-_TP1
|
bab66d68e2de27f3f6787aee01dc49d64e19ced2
|
307c6aa1627587aa6fd6c4f57d72b7bc279ebf6a
|
refs/heads/master
| 2021-05-08T18:10:37.495679
| 2018-02-01T08:42:43
| 2018-02-01T08:42:43
| 119,504,493
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 494
|
cpp
|
#include "vecteur3.hpp"
#include <CppUTest/CommandLineTestRunner.h>
TEST_GROUP(GroupVecteur3) { };
TEST(GroupVecteur3, test_norme) {
vecteur3 v {2, 3, 6};
CHECK_EQUAL(7, v.norme());
}
TEST(GroupVecteur3, test_addition) {
vecteur3 v {2, 3, 6};
vecteur3 res = addition(v, v);
CHECK_EQUAL(0, res.x);
CHECK_EQUAL(8, res.y);
CHECK_EQUAL(15, res.z);
}
TEST(GroupVecteur3, test_produitScalaire) {
vecteur3 v {2, 3, 6};
float res = produitScalaire(v, v);
CHECK_EQUAL(3, res);
}
|
[
"axel.lecoeuche@sfr.fr"
] |
axel.lecoeuche@sfr.fr
|
f2c89781281c9f15a7a685dade6d676758d14107
|
7f86f33a60adf52f5e8519ade0df1e4bb9af7de5
|
/TP2/TP2/AG.cpp
|
3a9093764486d567dc311633d49eb91be043adca
|
[] |
no_license
|
AsProgramming/C-
|
1f1294338b1b7e20a8163fc90b82641ab272fa72
|
091573b328130181f36bc4aec766eb6adec6a5a2
|
refs/heads/master
| 2020-03-29T18:17:30.419863
| 2018-09-25T03:48:04
| 2018-09-25T03:48:04
| 150,203,515
| 0
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 3,400
|
cpp
|
#include "AG.h"
#include "UtilES.h"
#include <iostream>
using namespace std;
typedef list<Noeud*>::iterator it;
AG::AG()
{
racine = new Noeud();
}
AG::~AG()
{
// Rien à faire ici
}
Noeud*& AG::getRacine()
{
return racine;
}
// Met un nouveau mot dans l'arbre
void AG::inserer(Noeud* n, string mot, string def, int i,int dernier)
{
if (n->estVide()) {
placerNoeud(n, mot, def, i, dernier);
}
else {
bool doublon = verifier(n, mot, def, i, dernier);
if (!doublon) {
placerNoeud(n, mot, def, i, dernier);
}
}
}
void AG::placerNoeud(Noeud* n, string mot, string def, int i, int dernier)
{
Noeud *nouveau = new Noeud(mot[i]);
if (i == dernier && n->getDefinition() == "") {
nouveau->setDefinition(def);
n->setFils(nouveau);
}
else if (i == dernier && n->getDefinition() != "") {
if (nouveau->getLettre() == n->getLettre()) {
string remplacer = ajusterDef(n->getDefinition());
if (remplacer == "o") {
n->setDefinition(def);
}
}
else {
nouveau->setDefinition(def);
n->setFils(nouveau);
}
}
else {
n->setFils(nouveau);
inserer(nouveau, mot, def, i + 1, dernier);
}
}
//////REUTILISER POUR VERIFIER MOT AJOUTER INDICE DANS LES ARGS
bool AG::verifier(Noeud* n, string mot, string def, int i, int dernier)
{
list<Noeud*> l = n->getFils();
for (it iter = l.begin(); iter != l.end(); iter++)
{
Noeud* tmp = *iter;
if (mot[i] == tmp->getLettre()) {
if (i != dernier) {
inserer(tmp, mot, def, i + 1, dernier);
}
else if (i == dernier) {
inserer(tmp, mot, def, i, dernier);
}
return true;
}
}
return false;
}
// Met le pointeur de noeud dans la liste
void AG::rechercher(Noeud* n, string mot, int i)
{
int dernier = mot.length() - 1;
bool pasTrouver = true;
list<Noeud*> l = n->getFils();
int verifier = l.size();
for (it iter = l.begin(); iter != l.end(); iter++)
{
Noeud* tmp = *iter;
if (mot[i] == tmp->getLettre()) {
if (tmp->getDefinition() != "" && i == dernier) {
affichage(tmp->getDefinition());
}
else if (i == dernier || tmp->estVide()) {
pasTrouver = true;
verifier--;
}
else
{
pasTrouver = false;
rechercher(tmp, mot, i + 1);
}
}
else {
verifier--;
}
}
if (pasTrouver && i == l.size()||
pasTrouver && i == 0
|| pasTrouver && verifier == 0) {
affichage("Ce mot n'existe pas dans ce lexique");
}
}
void AG::afficher(Noeud* n, string mot, string tmp, int indice, int max, int util)
{
Noeud* ptr;
int verifier = -1;
bool pasTrouver = true;
list<Noeud*> l = n->getFils();
for (it i = l.begin(); i != l.end(); i++)
{
ptr = *i;
if (max != 0 && mot[indice] == ptr->getLettre()) {
pasTrouver = false;
tmp.push_back(ptr->getLettre());
afficher(ptr, mot, tmp, indice + 1, max, util);
if (ptr->getDefinition() != "" && tmp.size() == max) {
if (util == 1) {
affichage(tmp);
}
else {
sauvegarder(tmp, ptr->getDefinition());
}
}
}
else if(indice == max){
pasTrouver = false;
tmp.push_back(ptr->getLettre());
afficher(ptr, mot, tmp, max, max, util);
if (ptr->getDefinition() != "") {
if (util == 1) {
affichage(tmp);
}
else {
sauvegarder(tmp, ptr->getDefinition());
}
}
else {
tmp.pop_back();
}
}
else {
verifier--;
}
}
if (pasTrouver && verifier < -1) {
tmp = "Ce terme n'existe pas dans le lexique";
affichage(tmp);
}
}
|
[
"eddi3.as@gmail.com"
] |
eddi3.as@gmail.com
|
006146de7baabe328abe8a58b8a445e7259a486a
|
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
|
/contest/1542589207.cpp
|
1ddbcb18d1c386a4c73f215cbfd08855ab4a6076
|
[] |
no_license
|
thegamer1907/Code_Analysis
|
0a2bb97a9fb5faf01d983c223d9715eb419b7519
|
48079e399321b585efc8a2c6a84c25e2e7a22a61
|
refs/heads/master
| 2020-05-27T01:20:55.921937
| 2019-11-20T11:15:11
| 2019-11-20T11:15:11
| 188,403,594
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 856
|
cpp
|
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iomanip>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#define ri register int
#define ll long long
using namespace std;
char str[10],ch[105][10];
int n;
inline const int getint()
{
int num=0,bj=1;
char c=getchar();
while(!isdigit(c))bj=(c=='-'||bj==-1)?-1:1,c=getchar();
while(isdigit(c))num=num*10+c-'0',c=getchar();
return num*bj;
}
int main()
{
scanf("%s",str+1);
n=getint();
for(ri i=1;i<=n;i++)
{
scanf("%s",ch[i]+1);
if(ch[i][1]==str[1]&&ch[i][2]==str[2]){printf("YES\n");return 0;}
}
for(ri i=1;i<=n;i++)
for(ri j=1;j<=n;j++)
if((ch[i][1]==str[2]&&ch[j][2]==str[1])){printf("YES\n");return 0;}
printf("NO\n");
return 0;
}
|
[
"harshitagar1907@gmail.com"
] |
harshitagar1907@gmail.com
|
b8f86e153174431afaa4b5c1bd4cf7724c142caf
|
37b27d8b23a5637f28aabf067ed578978a9c7b30
|
/Point.cpp
|
f61692bf06adf225beda1717b0a25d801ecd096d
|
[] |
no_license
|
joebentley/grid-pathfinder
|
95ef24f807d44651789c0c81272c0f8d36785d12
|
e63f88910bf83909354f2b7b5459fcb3109c57c3
|
refs/heads/master
| 2021-01-10T09:54:04.935914
| 2016-01-19T13:17:29
| 2016-01-19T13:17:29
| 49,953,798
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 912
|
cpp
|
#include <cstdlib>
#include <iostream>
#include "Point.h"
bool Point::operator<(const Point &p2) const {
return (x < p2.x) || (x == p2.x && y < p2.y);
}
int Point::getManhattanDistanceTo(const Point &p2) const {
return std::abs(this->x - p2.x) + std::abs(this->y - p2.y);
}
Point operator+(const Point &p1, const Point &p2)
{
return Point(p1.getx() + p2.getx(), p1.gety() + p2.gety());
}
Point operator-(const Point &p1, const Point &p2)
{
return Point(p1.getx() - p2.getx(), p1.gety() - p2.gety());
}
bool operator==(const Point &p1, const Point &p2) {
return (p1.getx() == p2.getx()) && (p1.gety() == p2.gety());
}
bool operator!=(const Point &p1, const Point &p2) {
return !(p1.getx() == p2.getx()) && (p1.gety() == p2.gety());
}
std::ostream& operator<<(std::ostream &os, const Point &p) {
return os << p.getx() << ", " << p.gety();
}
|
[
"joebentley10@gmail.com"
] |
joebentley10@gmail.com
|
40cbd24c40515a955fcdf5a1bf9ef19090faa676
|
0aae835a7de983505f114b8e52c98765d7fe2cc2
|
/common/win32_window.h
|
ba83c3dfc7f947b4e6c418bafd2a03958b6b0e9b
|
[
"MIT"
] |
permissive
|
ousttrue/Skeletal
|
92c54b3f75060e188a3707040e5f7fddee7e0803
|
bfbed4ec87e06787d3c004050d65954d53d0abbd
|
refs/heads/master
| 2023-06-11T06:55:07.037894
| 2019-07-21T15:20:52
| 2019-07-21T15:20:52
| 193,386,381
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 342
|
h
|
#pragma once
#include "window_state.h"
///
/// Windows API Window
///
/// * window size
/// * mouse inputs
///
class Win32Window
{
class Win32WindowImpl *m_impl = nullptr;
public:
Win32Window();
~Win32Window();
void* Create(int w, int h, const wchar_t *title);
const WindowState *GetState() const;
};
|
[
"ousttrue@gmail.com"
] |
ousttrue@gmail.com
|
ab83d668c6c21cdcc74b547cf1ac60f8be05ed92
|
63ca73071cc8300708f5e1374b45646f8c9f206d
|
/arduino_app/archive/RangeSensor.h
|
5e3242794c8c3679c89e84cd502a213cb5e87154
|
[] |
no_license
|
bartlettc22/desertviper
|
427696b5dc437308cf5dcf93f19e1820eff37411
|
a89dc185b2f971046501451931da01770082572f
|
refs/heads/master
| 2021-01-21T04:55:10.722996
| 2015-07-09T02:50:58
| 2015-07-09T02:50:58
| 34,994,918
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 357
|
h
|
#ifndef RangeSensor_h
#define RangeSensor_h
#include <Arduino.h>
class RSensor
{
public:
RSensor(){} ;
void init(unsigned char TRIG, unsigned char _ECHO);
void run();
long getRange();
unsigned long _duration;
double _distance;
private:
unsigned char _TRIG;
unsigned char _ECHO;
};
extern RSensor RangeSensor;
#endif
|
[
"bartlettc@gmail.com"
] |
bartlettc@gmail.com
|
69749b022ce6ddd59aec6e7d8b6a8ba82d19ef6e
|
21b4347c5a25f1ddb11404e974c47f71e2f34b32
|
/Hazel/src/Hazel/Renderer/RendererAPI.cpp
|
0bbbab1de97ce9ef699201eabf306dfd1fab9115
|
[] |
no_license
|
nsho77/LetsMakeEngine
|
40306ae1c867619f4758c96ad2c50651bacb2e52
|
622fde5bc4436455edf5d1d086b0fb999e72c850
|
refs/heads/main
| 2023-05-03T11:28:22.318568
| 2021-05-29T09:32:14
| 2021-05-29T09:32:14
| 304,617,685
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 532
|
cpp
|
#include <hzpch.h>
#include "Hazel/Renderer/RendererAPI.h"
#include "Platform/OpenGL/OpenGLRendererAPI.h"
namespace Hazel {
RendererAPI::API RendererAPI::s_API = RendererAPI::API::OpenGL;
Scope<RendererAPI> RendererAPI::Create()
{
switch (s_API)
{
case RendererAPI::API::None: HZ_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr;
case RendererAPI::API::OpenGL: return CreateScope<OpenGLRendererAPI>();
}
HZ_CORE_ASSERT(false, "Unknown RendererAPI!");
return nullptr;
}
}
|
[
"nsho77@naver.com"
] |
nsho77@naver.com
|
3ac451ced6ae6ec953de5afaecb154d08350fd19
|
89a6e0eca52e0cb31915fa43d9b1ba3f0145b257
|
/演算法題型分類/Stack/monotonic_stack/leetcode-738.cc
|
8242f17c459b5724a2c7d93a5778f8eda50f340b
|
[] |
no_license
|
rollfatcat/ProblemSet
|
03a3a960ec324b831d3db422a52d623f2d04b6f0
|
f9c76320e8812304b73ac348e8e34e8a55e08a10
|
refs/heads/master
| 2023-04-03T15:48:44.551030
| 2023-03-21T19:09:32
| 2023-03-21T19:09:32
| 191,777,230
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 923
|
cc
|
/* Given a non-negative integer N,
* find the largest number that is less than or equal to N with monotone increasing digits.
* an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.
* Input: N = 10 Output: 9
* Input: N = 1234 Output: 1234
* Input: N = 332 Output: 299
*/
class Solution {
public:
int monotoneIncreasingDigits(int N) {
int x;
vector<int> digit;
for(x=N; x>9; x/=10)
digit.push_back(x%10);
digit.push_back(x);
for(x=digit.size()-1; x>0 and digit[x]<=digit[x-1]; x-=1);
if(x==0) return N;
for(int i=x-1;i>=0;i--) digit[i]=9;
for(; x<digit.size()-1 and digit[x]==digit[x+1]; x+=1)
digit[x]=9;
digit[x]-=1;
x=0;
for(int i=digit.size()-1; i>=0; i-=1)
x=10*x+digit[i];
return x;
}
};
|
[
"crhsieh1114@outlook.com"
] |
crhsieh1114@outlook.com
|
68c5f401179c5ab4234eac58c3b99dbba44cb03e
|
2c2672b0ceb3bad925f05896d2c91a4aca1892d0
|
/Ejercicio_14/main.cpp
|
d4c51015f92004b4de6a0ea6fa99be32f272a17c
|
[] |
no_license
|
Klatu1494/Programacion-I
|
6ed05eb93418d4dc15bda85c9dfdec929bfc8b58
|
aeb7d106180fb110d0cffbeaf5b71734b8fd22d8
|
refs/heads/master
| 2021-01-21T08:33:15.771179
| 2017-05-18T00:33:52
| 2017-05-18T00:33:52
| 91,631,642
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 658
|
cpp
|
#include <iostream>
using namespace std;
int main()
{
int i=0;
int numero=0;
int suma_menores=0;
float suma_mayores=0;
float cant_mayores=0;
for(; i<5; i++){
cout<<"Ingrese un entero: ";
cin>>numero;
if(numero<-10){
suma_menores=suma_menores+numero;
}
if(numero>100){
suma_mayores=suma_mayores+numero;
cant_mayores=cant_mayores+1;
}
}
cout<<"La suma de los numeros menores que -10 ingresados es: "<<suma_menores<<endl;
cout<<"El promedio de los numeros mayores que 100 ingresados es: "<<suma_mayores/cant_mayores<<endl;
return 0;
}
|
[
"klatu1494@gmail.com"
] |
klatu1494@gmail.com
|
6bea91290f358353be9f2708bbf198294b645008
|
7485a0245fc72e361a643347460787ec8680bb06
|
/PMaildServerImap4.cpp
|
4b513bd4a33111f3bba510811be2a62204d4e5e6
|
[] |
no_license
|
jmaitrehenry/pmaild
|
67b54a97a2c33429e085d75eca9a3dd3eeafff99
|
fd672f0fcce0d91ac939323dff099b0d8af4ab8f
|
refs/heads/master
| 2021-01-17T18:54:49.475366
| 2012-07-01T01:17:03
| 2012-07-01T01:17:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 674
|
cpp
|
#include "PMaildServerImap4.hpp"
#include "PMaildCore.hpp"
#include <QDateTime>
PMaildServerImap4::PMaildServerImap4(QSslSocket *_sock, PMaildCore *_core, PMaildServer *_server) :
PMaildServerBase(_sock, _core, _server)
{
}
void PMaildServerImap4::welcome() {
writeLine("* OK "+core->getHostName()+" IMAP4rev1 2001.305/pMaild on "+QDateTime::currentDateTimeUtc().toString(Qt::ISODate).toUtf8());
}
void PMaildServerImap4::handleUnknownCommand() {
writeLine("* BAD Unknown command"); // TODO replace * with ref
}
void PMaildServerImap4::server_cmd_logout(const QList<QByteArray> &) {
writeLine("* BYE "+core->getHostName()+" IMAP4rev1 server says bye!");
close();
}
|
[
"mark@hell.ne.jp"
] |
mark@hell.ne.jp
|
f191bd61579a6be981c3eaa825eef73bdd6438b6
|
5da61c393b65b5b06ec684242adb457d25f1f4a2
|
/src/Utilities/graph.h
|
e1f7880aaf5f9005239cf9c0e42816a049cf2652
|
[
"MIT"
] |
permissive
|
MehmetMelihKosucu/EPANET_3-PMX
|
cb74d1480f61f42dd59dfa509e140dc098385c38
|
e4674330225288c8ba29c23928ce8c82f38a7c9f
|
refs/heads/main
| 2023-06-10T13:46:40.996311
| 2023-06-02T01:28:32
| 2023-06-02T01:28:32
| 581,764,129
| 1
| 0
|
MIT
| 2023-06-02T00:58:06
| 2022-12-24T08:34:48
|
C++
|
UTF-8
|
C++
| false
| false
| 841
|
h
|
/* EPANET 3.1.1 Pressure Management Extension
*
* Copyright (c) 2016 Open Water Analytics
* Licensed under the terms of the MIT License (see the LICENSE file for details).
*
*/
//! \file graph.h
//! \brief Describes the Graph class.
#ifndef GRAPH_H_
#define GRAPH_H_
//! \class Graph
//! \brief Contains graph theoretic representation of a pipe network.
//!
//! A Graph object contains data structures (e.g., adjacency lists) and
//! algorithms (e.g., spanning tree) for describing the connectivity of
//! a pipe network.
#include <vector>
class Network;
class Graph
{
public:
Graph();
~Graph();
void createAdjLists(Network* nw);
private:
std::vector<int> adjLists; // packed nodal adjacency lists
std::vector<int> adjListBeg; // starting index of each node's list
};
#endif // GRAPH_H_
|
[
"kosucu@itu.edu.tr"
] |
kosucu@itu.edu.tr
|
57182f263d848b2cb8ce77f04ad7856fa8cb0e15
|
121be011ecdd9901a4b0f35806a8b272297233cc
|
/common/iod_timer_handler.h
|
c401ecda674a8fd60c7c1ec76482f51bf4d2c247
|
[] |
no_license
|
chenan2005/caserver
|
a78824b720b6cb66b8023e246d4b9bd2eb954d4a
|
7da5c71a67cb135833b06b84d2e8bf18772cd11f
|
refs/heads/master
| 2021-01-10T13:36:59.363348
| 2015-06-03T10:25:04
| 2015-06-03T11:11:41
| 36,404,311
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 808
|
h
|
#ifndef __IOD_TIMER_HANDLER_H__
#define __IOD_TIMER_HANDLER_H__
#include "iod_common.h"
class iod_timer_handler
{
public:
typedef void (iod_timer_handler:: *FNC_TIMER_CALLBACK)(void*);
struct timer_info
{
struct event* ev;
iod_timer_handler* handler;
FNC_TIMER_CALLBACK cb_fnc;
void* cb_fnc_arg;
bool repeat;
bool auto_release_arg;
int timeout_ms;
int triggered_times;
};
iod_timer_handler(void);
virtual ~iod_timer_handler(void);
static void timeout_cb(evutil_socket_t fd, short ev, void *arg);
timer_info* shedule_timer(int timeout_ms, FNC_TIMER_CALLBACK cb_fnc, void* cb_fnc_arg = 0, bool repeat = false, bool auto_release_arg = false);
bool remove_timer(timer_info* t);
private:
void destroy_timer_info(timer_info* t);
std::set< timer_info* > timer_set;
};
#endif
|
[
"chenan2005@gmail.com"
] |
chenan2005@gmail.com
|
4aa6051983383dd30c982fe1375ebce813c03e49
|
1a8db3a0d145f9805ec169e57f9de326ba9d7f57
|
/codar language/New Stuff/chessboard.cpp
|
1124bd5cbc54660c7158ada43ca87ea1fed86450
|
[] |
no_license
|
LostSam423/Soviet-Republic
|
4fe0ae4f3507d13856c1672ac517e96f9a6f3e2b
|
52da03dbe4b5e6b07505bcdab51f53c0ba53756b
|
refs/heads/master
| 2022-07-28T03:15:23.568876
| 2020-05-17T10:58:53
| 2020-05-17T10:58:53
| 249,247,696
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,445
|
cpp
|
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <cmath>
#include "utility/shader.hpp"
#include "utility/readfile.hpp"
#include "Textures/texture.hpp"
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 800;
int main()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Soviet Republic", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glewExperimental = GL_TRUE;
glewInit();
GLfloat vertices[] =
{
-0.8f,-0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, //botleft
0.8f, -0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, //botright
-0.8f, 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, //topleft
0.8f, -0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, //botright
-0.8f, 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, //topleft
0.8f, 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f //topright
};
GLfloat indices[] =
{
0, 1, 2,
0, 1, 3
};
glViewport(0, 0,SCR_WIDTH, SCR_HEIGHT);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
Shader *shdr = new Shader("shaders/shad.vs","shaders/shad.fs");
GLuint VBO, VAO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers( 1, &VBO );
glBindVertexArray( VAO );
glBindBuffer( GL_ARRAY_BUFFER, VBO );
glBufferData( GL_ARRAY_BUFFER, sizeof( vertices ), vertices, GL_STATIC_DRAW );
glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 8* sizeof( GLfloat ), (GLvoid * ) 0 );
glEnableVertexAttribArray( 0 );
glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, 8* sizeof( GLfloat ), (GLvoid * ) (3* sizeof( GLfloat )) );
glEnableVertexAttribArray( 1 );
glVertexAttribPointer( 2, 2, GL_FLOAT, GL_FALSE, 8* sizeof( GLfloat ), (GLvoid * ) (6* sizeof( GLfloat )) );
glEnableVertexAttribArray( 2 );
glGenBuffers( 1, &EBO);
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, EBO );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
Texture *txt = new Texture("Images/chess.png");
while (!glfwWindowShouldClose(window))
{
processInput(window);
glfwPollEvents();
glClearColor(0.3f, 0.2f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
txt->use(0);
shdr->use();
glBindVertexArray( VAO );
glDrawArrays(GL_TRIANGLES,0,6);
glfwSwapBuffers(window);
glfwPollEvents();
}
glDeleteVertexArrays( 1, &VAO );
glDeleteBuffers(1, &VBO);
glfwTerminate();
return 0;
}
void processInput(GLFWwindow *window)
{
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
|
[
"beherasambit423@gmail.com"
] |
beherasambit423@gmail.com
|
ead4dbe6ae6ec00168fc98775b0b4b3ad9fe0887
|
b80fb982d65a9e3fb0e05bcbd2d04caf2437f616
|
/QtServer/GeneratedFiles/ui_QtServer.h
|
bcfd9a22d311a2b7f031b33355dedbac4b0d375e
|
[] |
no_license
|
wuran-github/ADT-Socket
|
7ecaeb53834c6eab2f5a1c18edaecdc3baa242d6
|
b73255ffe80ca29e43427db7ae84494b6b5271d7
|
refs/heads/master
| 2020-04-04T05:19:52.403797
| 2018-11-07T08:56:22
| 2018-11-07T08:56:22
| 155,742,012
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,522
|
h
|
/********************************************************************************
** Form generated from reading UI file 'QtServer.ui'
**
** Created by: Qt User Interface Compiler version 5.11.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_QTSERVER_H
#define UI_QTSERVER_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_QtServerClass
{
public:
QWidget *centralWidget;
QLineEdit *FileText;
QLabel *label;
QPushButton *FileBtn;
QLabel *label_2;
QLineEdit *FileSizeTxt;
QLabel *label_3;
QLabel *label_4;
QLineEdit *IPTxt;
QPushButton *ListenBtn;
QPushButton *SendBtn;
QLabel *ConnectTxt;
QStatusBar *statusBar;
void setupUi(QMainWindow *QtServerClass)
{
if (QtServerClass->objectName().isEmpty())
QtServerClass->setObjectName(QStringLiteral("QtServerClass"));
QtServerClass->resize(600, 400);
centralWidget = new QWidget(QtServerClass);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
FileText = new QLineEdit(centralWidget);
FileText->setObjectName(QStringLiteral("FileText"));
FileText->setGeometry(QRect(110, 40, 251, 20));
label = new QLabel(centralWidget);
label->setObjectName(QStringLiteral("label"));
label->setGeometry(QRect(40, 40, 71, 20));
FileBtn = new QPushButton(centralWidget);
FileBtn->setObjectName(QStringLiteral("FileBtn"));
FileBtn->setGeometry(QRect(370, 40, 31, 23));
label_2 = new QLabel(centralWidget);
label_2->setObjectName(QStringLiteral("label_2"));
label_2->setGeometry(QRect(40, 80, 71, 16));
FileSizeTxt = new QLineEdit(centralWidget);
FileSizeTxt->setObjectName(QStringLiteral("FileSizeTxt"));
FileSizeTxt->setGeometry(QRect(110, 80, 111, 20));
label_3 = new QLabel(centralWidget);
label_3->setObjectName(QStringLiteral("label_3"));
label_3->setGeometry(QRect(230, 80, 54, 12));
label_4 = new QLabel(centralWidget);
label_4->setObjectName(QStringLiteral("label_4"));
label_4->setGeometry(QRect(40, 120, 61, 20));
IPTxt = new QLineEdit(centralWidget);
IPTxt->setObjectName(QStringLiteral("IPTxt"));
IPTxt->setGeometry(QRect(110, 120, 113, 20));
ListenBtn = new QPushButton(centralWidget);
ListenBtn->setObjectName(QStringLiteral("ListenBtn"));
ListenBtn->setGeometry(QRect(30, 170, 75, 23));
SendBtn = new QPushButton(centralWidget);
SendBtn->setObjectName(QStringLiteral("SendBtn"));
SendBtn->setGeometry(QRect(330, 170, 75, 23));
ConnectTxt = new QLabel(centralWidget);
ConnectTxt->setObjectName(QStringLiteral("ConnectTxt"));
ConnectTxt->setGeometry(QRect(120, 175, 61, 16));
QtServerClass->setCentralWidget(centralWidget);
statusBar = new QStatusBar(QtServerClass);
statusBar->setObjectName(QStringLiteral("statusBar"));
QtServerClass->setStatusBar(statusBar);
retranslateUi(QtServerClass);
QMetaObject::connectSlotsByName(QtServerClass);
} // setupUi
void retranslateUi(QMainWindow *QtServerClass)
{
QtServerClass->setWindowTitle(QApplication::translate("QtServerClass", "QtServer", nullptr));
label->setText(QApplication::translate("QtServerClass", "Send File:", nullptr));
FileBtn->setText(QApplication::translate("QtServerClass", "...", nullptr));
label_2->setText(QApplication::translate("QtServerClass", "File Size:", nullptr));
label_3->setText(QApplication::translate("QtServerClass", "bytes", nullptr));
label_4->setText(QApplication::translate("QtServerClass", "local IP:", nullptr));
ListenBtn->setText(QApplication::translate("QtServerClass", "StratListen", nullptr));
SendBtn->setText(QApplication::translate("QtServerClass", "End Listen", nullptr));
ConnectTxt->setText(QApplication::translate("QtServerClass", "not start", nullptr));
} // retranslateUi
};
namespace Ui {
class QtServerClass: public Ui_QtServerClass {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_QTSERVER_H
|
[
"wuranvv@outlook.com"
] |
wuranvv@outlook.com
|
c899a41cf1110cb288699adde50ec9bc7e7835f3
|
24f47d5f74c15361a2e2d1cb839f6af55face138
|
/ControLeo2/examples/ReflowWizard/Settings.ino
|
bba78b412d871273e9dea48745b823d8b20dd90c
|
[] |
no_license
|
felixekman/ControLeo2
|
8dc2e557a9c202a08ac2342171082a18dbb1f34b
|
6458a8ae54a6e96d6ac9f5906ca7ab0797e5a7a8
|
refs/heads/master
| 2021-01-17T22:50:07.086391
| 2016-03-30T01:56:00
| 2016-03-30T01:56:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,061
|
ino
|
// The ATMEGA32U4 has 1024 bytes of EEPROM. We use some of it to store settings so that
// the oven doesn't need to be reconfigured every time it is turned on. Uninitialzed
// EEPROM is set to 0xFF (255). One of the first things done when powering up is to
// see if the EEPROM is uninitialized - and initialize it if that is the case.
//
// All settings are stored as bytes (unsigned 8-bit values). This presents a problem
// for the maximum temperature which can be as high as 280C - which doesn't fit in a
// 8-bit variable. With the goal of making getSetting/setSetting as simple as possible,
// we could've saved all values as 16-bit values, using consecutive EEPROM locations. We
// instead chose to just offset the temperature by 150C, making the range 25 to 130 instead
// of 175 to 280.
#include <EEPROM.h>
// Get the setting from EEPROM
int getSetting(int settingNum) {
int val = EEPROM.read(settingNum);
// The maximum temperature has an offset to allow it to be saved in 8-bits (0 - 255)
if (settingNum == SETTING_MAX_TEMPERATURE)
return val + SETTING_TEMPERATURE_OFFSET;
// Bake temperature is modified before saving
if (settingNum == SETTING_BAKE_TEMPERATURE)
return val * SETTING_BAKE_TEMPERATURE_STEP;
return val;
}
// Save the setting to EEPROM. EEPROM has limited write cycles, so don't save it if the
// value hasn't changed.
void setSetting(int settingNum, int value) {
// Do nothing if the value hasn't changed (don't wear out the EEPROM)
if (getSetting(settingNum) == value)
return;
switch (settingNum) {
case SETTING_D4_TYPE:
case SETTING_D5_TYPE:
case SETTING_D6_TYPE:
case SETTING_D7_TYPE:
// The element has been reconfigured so reset the duty cycles and restart learning
EEPROM.write(SETTING_SETTINGS_CHANGED, true);
EEPROM.write(SETTING_LEARNING_MODE, true);
EEPROM.write(settingNum, value);
Serial.println(F("Settings changed! Duty cycles have been reset and learning mode has been enabled"));
break;
case SETTING_MAX_TEMPERATURE:
// Enable learning mode if the maximum temperature has changed a lot
if (abs(getSetting(settingNum) - value) > 5)
EEPROM.write(SETTING_LEARNING_MODE, true);
// Write the new maximum temperature
EEPROM.write(settingNum, value - SETTING_TEMPERATURE_OFFSET);
break;
case SETTING_BAKE_TEMPERATURE:
EEPROM.write(settingNum, value / SETTING_BAKE_TEMPERATURE_STEP);
break;
default:
EEPROM.write(settingNum, value);
break;
}
}
void InitializeSettingsIfNeccessary() {
// Does the EEPROM need to be initialized?
if (getSetting(SETTING_EEPROM_NEEDS_INIT)) {
// Initialize all the settings to 0 (false)
for (int i=0; i<1024; i++)
EEPROM.write(i, 0);
// Set a reasonable max temperature
setSetting(SETTING_MAX_TEMPERATURE, 240);
// Set the servos to neutral positions (90 degrees)
setSetting(SETTING_SERVO_CLOSED_DEGREES, 90);
setSetting(SETTING_SERVO_OPEN_DEGREES, 90);
// Set default baking temperature
setSetting(SETTING_BAKE_TEMPERATURE, 40);
}
// Legacy support - Initialize the rest of EEPROM for upgrade from 1.x to 1.4
if (getSetting(SETTING_SERVO_OPEN_DEGREES) > 180) {
for (int i=SETTING_SERVO_OPEN_DEGREES; i<1024; i++)
EEPROM.write(i, 0);
setSetting(SETTING_SERVO_CLOSED_DEGREES, 90);
setSetting(SETTING_SERVO_OPEN_DEGREES, 90);
setSetting(SETTING_BAKE_TEMPERATURE, 40);
}
}
// Returns the bake duration, in seconds (max 65536 = 18 hours)
uint16_t getBakeSeconds(int duration)
{
uint16_t minutes = 0;
// Sanity check on the parameter
if (duration >= SETTING_BAKE_MAX_DURATION)
return 0;
// 5 to 60 minutes, at 1 minute increments
if (duration <= 55)
minutes = duration + 5;
// 1 hour to 4 hours at 5 minute increments
else if (duration <= 91)
minutes = (duration - 55) * 5 + 60;
// 4+ hours in 10 minute increments
else
minutes = (duration - 91) * 10 + 240;
return minutes * 60;
}
|
[
"apple@Peters-Mac-mini.local"
] |
apple@Peters-Mac-mini.local
|
533e5b42ad78ae80b9ef0ca1198cf2e338e4f9ea
|
8a498a7fed84d4f2df885697d96a31b2bc326945
|
/src/float3.cpp
|
39a4ed628a187b55d74b81d8027463d767a9280b
|
[] |
no_license
|
samkottler/OpenCl-Renderer
|
eebb4a4ebfbab01f77538cd258110f5986295b42
|
67d880092bd1a8201ac3d6e4fed288616cfbfdd5
|
refs/heads/master
| 2020-05-31T21:46:39.961648
| 2019-10-23T17:51:09
| 2019-10-23T17:51:09
| 190,506,432
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 357
|
cpp
|
#include "float3.h"
float dot(float3 a, float3 b){
return a.x*b.x + a.y*b.y + a.z*b.z;
}
float3 cross(float3 a, float3 b){
return {a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x};
}
float3 operator*(float s, float3 v){
return {s*v.x, s*v.y, s*v.z};
}
float3 operator+(float3 a, float3 b){
return {a.x+b.x, a.y+b.y, a.z+b.z};
}
|
[
"samkottler@users.noreply.github.com"
] |
samkottler@users.noreply.github.com
|
51ef0747800a5fc41ba7f1ef0ada9dd1cef11658
|
e495c411f6186f481dd98ea9927fffcc72b8cb5c
|
/Lexical_Analyser/analyzer/src/SymbolTable.cpp
|
829e8b4f7849d76c945bbd0b10ae1817ce136210
|
[] |
no_license
|
ramananurag/Compiler
|
9020a092370661e4efdbd664543e83677d72b434
|
2ad27dac346594948cd096a36b92a0221417a08e
|
refs/heads/master
| 2021-01-17T21:31:12.627098
| 2012-04-10T15:43:21
| 2012-04-10T15:43:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,317
|
cpp
|
#include <SymbolTable.h>
#include <cctype>
SymbolTableElement::SymbolTableElement(string lexeme, string token, unsigned int row, unsigned int col)
{
this->lexeme = lexeme;
this->token = token;
this->addPosition (row, col);
}
void SymbolTableElement::addPosition (unsigned int row, unsigned int col)
{
Position tmp_position;
tmp_position.row = row;
tmp_position.col = col;
positions.push_back (tmp_position);
}
string SymbolTableElement::getToken () const
{
return this->token;
}
string SymbolTableElement::getLexeme () const
{
return this->lexeme;
}
static inline unsigned int tableIndex (const string& lexeme)
{
return (tolower(lexeme[0] - 'a'));
}
SymbolTableElement * SymbolTable::findLexeme (const string lexeme)
{
unsigned int n = tableIndex(lexeme);
list <SymbolTableElement>::iterator iter, iter_end;
for ( iter = index[n].begin(), iter_end = index[n].end(); iter != iter_end; iter++)
{
if ( iter->lexeme == lexeme)
{
return &(*iter);
}
}
return NULL;
}
void SymbolTable::insert (const string lexeme, const string token, unsigned int row, unsigned int col)
{
SymbolTableElement * element = findLexeme (lexeme);
if (element != NULL)
{
element->addPosition (row, col);
}
else
{
index[tableIndex(lexeme)].push_back (SymbolTableElement(lexeme, token, row, col));
}
}
|
[
"raman@raman-Inspiron-N5010.(none)"
] |
raman@raman-Inspiron-N5010.(none)
|
2852fc1d663cf446bac5055f17689c3aba1c904e
|
c033d3980df311e33cb1577a13a66ae13d25b37a
|
/include/Expression/DivideExpression.hpp
|
ec560fa0f46af9b56fe6c2fdd09ff7f54007c41a
|
[] |
no_license
|
Dgame/Ikarus
|
67f109391317d922394d331687b5692b1fbf0d2a
|
fed0ddbaf0523e4c824034dca0a1de78e719c8c9
|
refs/heads/master
| 2021-01-10T17:06:56.483072
| 2016-04-10T20:53:20
| 2016-04-10T20:53:20
| 53,231,066
| 0
| 0
| null | 2016-03-16T21:41:58
| 2016-03-06T01:02:33
|
C++
|
UTF-8
|
C++
| false
| false
| 479
|
hpp
|
#ifndef IKARUS_DIV_EXPRESSION_HPP
#define IKARUS_DIV_EXPRESSION_HPP
#include "BinaryExpression.hpp"
class DivideExpression : public BinaryExpression {
public:
using BinaryExpression::BinaryExpression;
DivideExpression* clone() const override {
return new DivideExpression(this->getLeftExpression()->clone(), this->getRightExpression()->clone());
}
void accept(Visitor& v) override {
v.visit(this);
}
};
#endif //IKARUS_DIV_EXPRESSION_HPP
|
[
"rswhite4@googlemail.com"
] |
rswhite4@googlemail.com
|
06c333cc3322a865535741770d11a89274264a3e
|
2dc4ca3fdad00e13f616325cf2a1d32bbd987591
|
/HugeCTR/src/cpu/layers/reshape_layer_cpu.cpp
|
a3a0fa357c74e9e4d5fab46093a72e2377d72cf4
|
[
"Apache-2.0"
] |
permissive
|
TianhaoFu/HugeCTR
|
d86134da3bbf9f4388dcc432be707a53e54f6932
|
16587742a388d1d4442740ffcc8a9b52faf734cc
|
refs/heads/master
| 2023-05-30T04:49:41.375224
| 2021-06-15T09:01:04
| 2021-06-15T09:01:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,779
|
cpp
|
/*
* Copyright (c) 2020, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <common.hpp>
#include <utils.hpp>
#include <cpu/layers/reshape_layer_cpu.hpp>
#ifndef NDEBUG
#include <iostream>
#endif
namespace HugeCTR {
namespace {
template <typename T>
void reshape_fprop_cpu(int batch_size, int n_slot, int vector_length, size_t num_elements,
std::vector<int> selected, T* h_in, T* h_ref) {
int n_active_slot = selected.empty() ? n_slot : int(selected.size());
if (selected.empty()) {
for (size_t i = 0; i < num_elements; i++) {
h_ref[i] = h_in[i];
}
} else {
for (int i = 0; i < batch_size; i++) {
for (int j = 0; j < n_active_slot; j++) {
for (int k = 0; k < vector_length; k++) {
int in_idx = i * (n_slot * vector_length) + selected[j] * vector_length + k;
int out_idx = i * (n_active_slot * vector_length) + j * vector_length + k;
h_ref[out_idx] = h_in[in_idx];
}
}
}
}
}
} // anonymous namespace
template <typename T>
ReshapeLayerCPU<T>::ReshapeLayerCPU(const Tensor2<T>& in_tensor, Tensor2<T>& out_tensor,
const std::shared_ptr<GeneralBuffer2<HostAllocator>>& blobs_buff,
size_t leading_dim)
: LayerCPU(),
in_place_(true),
batch_size_(0),
n_slot_(0),
vector_length_(0),
n_active_slot_(0) {
try {
const std::vector<size_t>& in_dims = in_tensor.get_dimensions();
int im_idx = in_dims.size() - 1;
if (leading_dim < in_dims[im_idx] || leading_dim % in_dims[im_idx] != 0) {
CK_THROW_(Error_t::WrongInput,
"leading_dim < in_dims[im_idx] or leading_dim % in_dims[2] != 0");
}
size_t n_in_elems = in_tensor.get_num_elements();
if (leading_dim > n_in_elems) {
CK_THROW_(Error_t::WrongInput, "leading_dim cannot be bigger than n_in_elems");
}
if (n_in_elems % leading_dim != 0) {
CK_THROW_(Error_t::WrongInput, "n_in_elems % leading_dim != 0");
}
size_t trailing_dim = n_in_elems / leading_dim;
std::vector<size_t> out_dims = {trailing_dim, leading_dim};
blobs_buff->reserve(out_dims, &out_tensor);
in_tensors_.push_back(in_tensor);
out_tensors_.push_back(out_tensor);
} catch (const std::runtime_error& rt_err) {
std::cerr << rt_err.what() << std::endl;
throw;
}
}
template <typename T>
ReshapeLayerCPU<T>::ReshapeLayerCPU(const Tensor2<T>& in_tensor, Tensor2<T>& out_tensor,
const std::shared_ptr<GeneralBuffer2<HostAllocator>>& blobs_buff,
std::vector<int>& selected)
: LayerCPU(),
in_place_(selected.empty()),
batch_size_(0),
n_slot_(0),
vector_length_(0),
n_active_slot_(selected.size()),
selected_(selected) {
try {
const std::vector<size_t>& in_dims = in_tensor.get_dimensions();
if (in_dims[1] < n_active_slot_) {
CK_THROW_(Error_t::WrongInput, "selected is invalid");
}
size_t in_dims_1 = selected.empty() ? in_dims[1] : n_active_slot_;
std::vector<size_t> out_dims = {in_dims[0], in_dims_1 * in_dims[2]};
blobs_buff->reserve(out_dims, &out_tensor);
if (!in_place_) {
unsigned int i = 0;
for (; i < in_dims.size() - 2; i++) batch_size_ += in_dims[i];
n_slot_ = in_dims[i++];
vector_length_ = in_dims[i];
blobs_buff->reserve({n_active_slot_}, &selected_tensor_);
}
in_tensors_.push_back(in_tensor);
out_tensors_.push_back(out_tensor);
} catch (const std::runtime_error& rt_err) {
std::cerr << rt_err.what() << std::endl;
throw;
}
}
template <typename T>
void ReshapeLayerCPU<T>::fprop(bool is_train) {
T* h_in = in_tensors_[0].get_ptr();
T* h_out = out_tensors_[0].get_ptr();
size_t num_elements = in_tensors_[0].get_num_elements();
if (in_place_) {
for (size_t i = 0; i < num_elements; i++) {
h_out[i] = h_in[i];
}
} else {
reshape_fprop_cpu(batch_size_, n_slot_, vector_length_, num_elements, selected_, h_in, h_out);
}
}
template <typename T>
void ReshapeLayerCPU<T>::bprop() {}
template class ReshapeLayerCPU<float>;
template class ReshapeLayerCPU<__half>;
} // namespace HugeCTR
|
[
"zehuanw@nvidia.com"
] |
zehuanw@nvidia.com
|
68f3a6d32d8e575c1b10aabc6d04356a841f96c6
|
044e4d45f197cfa5685f54d939df540f04ce2ac1
|
/hw_02/include/BoardView.h
|
c1619b48c48487d16a21e08c9f606e2c9f0de4ce
|
[] |
no_license
|
XamLua/CPP2016
|
65fe90f0f6b397bdf0f7d63c4138490258e66291
|
2163e1c3714ded8dcbeea970701ef2257052c746
|
refs/heads/master
| 2021-06-11T01:23:10.916050
| 2016-12-25T22:49:03
| 2016-12-25T22:49:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 309
|
h
|
#pragma once
#include "Board.h"
class View {
private:
Board & b;
bool show; //Переменная, отвечающая за то, нужно ли выводить поле после каждого хода.
public:
View(Board& board);
void Show(bool f);
void showBoard();
void doGameCycle();
};
|
[
"black.hornetnikita@gmail.com"
] |
black.hornetnikita@gmail.com
|
cf523520dbfa8cabae2126693252931c02fb89c8
|
f0a26ec6b779e86a62deaf3f405b7a83868bc743
|
/Engine/Source/Runtime/Slate/Public/SWrapBox.h
|
43be27db91e47dfdcb6c654d16515efccb79bd56
|
[] |
no_license
|
Tigrouzen/UnrealEngine-4
|
0f15a56176439aef787b29d7c80e13bfe5c89237
|
f81fe535e53ac69602bb62c5857bcdd6e9a245ed
|
refs/heads/master
| 2021-01-15T13:29:57.883294
| 2014-03-20T15:12:46
| 2014-03-20T15:12:46
| 18,375,899
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,425
|
h
|
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
#pragma once
/** A slot that support alignment of content and padding */
class SLATE_API FWrapSlot : public TSupportsOneChildMixin<SWidget, FWrapSlot>, public TSupportsContentAlignmentMixin<FWrapSlot>, public TSupportsContentPaddingMixin<FWrapSlot>
{
public:
FWrapSlot()
: TSupportsContentAlignmentMixin<FWrapSlot>( HAlign_Fill, VAlign_Fill )
, bSlotFillEmptySpace( false )
{
}
/** If the total available space in the wrap panel drops below this threshold, this slot will attempt to fill an entire line. */
FWrapSlot& FillLineWhenWidthLessThan( TOptional<float> InFillLineWhenWidthLessThan )
{
SlotFillLineWhenWidthLessThan = InFillLineWhenWidthLessThan;
return *( static_cast<FWrapSlot*>( this ) );
}
/** Should this slot fill the remaining space on the line? */
FWrapSlot& FillEmptySpace( bool bInFillEmptySpace )
{
bSlotFillEmptySpace = bInFillEmptySpace;
return *( static_cast<FWrapSlot*>( this ) );
}
TOptional<float> SlotFillLineWhenWidthLessThan;
bool bSlotFillEmptySpace;
};
/**
* Arranges widgets left-to-right.
* When the widgets exceed the PreferredWidth
* the SWrapBox will place widgets on the next line.
*
* Illustration:
* +-----Preferred Width
* |
* [-----------][-|-]
* [--][------[--]|
* [--------------|]
* [---] |
*/
class SLATE_API SWrapBox : public SPanel
{
public:
SLATE_BEGIN_ARGS(SWrapBox)
: _PreferredWidth( 100.f )
, _InnerSlotPadding( FVector2D::ZeroVector )
, _UseAllottedWidth( false )
{
_Visibility = EVisibility::SelfHitTestInvisible;
}
/** The slot supported by this panel */
SLATE_SUPPORTS_SLOT( FWrapSlot )
/** The preferred width, if not set will fill the space */
SLATE_ATTRIBUTE( float, PreferredWidth )
/** The inner slot padding goes between slots sharing borders */
SLATE_ARGUMENT( FVector2D, InnerSlotPadding )
/** if true, the PreferredWidth will always match the room available to the SWrapBox */
SLATE_ARGUMENT( bool, UseAllottedWidth )
SLATE_END_ARGS()
static FWrapSlot& Slot();
FWrapSlot& AddSlot();
/** Removes a slot from this box panel which contains the specified SWidget
*
* @param SlotWidget The widget to match when searching through the slots
* @returns The index in the children array where the slot was removed and -1 if no slot was found matching the widget
*/
int32 RemoveSlot( const TSharedRef<SWidget>& SlotWidget );
void Construct( const FArguments & InArgs );
virtual void Tick( const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime ) OVERRIDE;
virtual void ArrangeChildren( const FGeometry& AllottedGeometry, FArrangedChildren& ArrangedChildren ) const OVERRIDE;
void ClearChildren();
virtual FVector2D ComputeDesiredSize() const OVERRIDE;
virtual FChildren* GetChildren() OVERRIDE;
private:
/** How wide this panel should appear to be. Any widgets past this line will be wrapped onto the next line. */
TAttribute<float> PreferredWidth;
/** The slots that contain this panel's children. */
TPanelChildren<FWrapSlot> Slots;
/** When two slots end up sharing a border, this will put that much padding between then, but otherwise wont. */
FVector2D InnerSlotPadding;
/** If true the box will have a preferred width equal to its alloted width */
bool bUseAllottedWidth;
};
|
[
"michaellam430@gmail.com"
] |
michaellam430@gmail.com
|
869159d9114cef504859f7f377d90fd6154b1669
|
97d5fd283bffe0f6a030d300d5317c4936956f1d
|
/c++/listasEnlazadas.cpp
|
02481e4c2ab20da8bc1ba75aeca6e319b84240c2
|
[] |
no_license
|
fjsaca2001/proyectosPersonales
|
13efe4bede10a55e595ea16c2d7d17cff4075bc9
|
a2cdb77611b5b4d4bba2b545a1359e4eb3a2634c
|
refs/heads/master
| 2023-03-05T01:48:12.125686
| 2021-02-21T01:47:25
| 2021-02-21T01:47:25
| 254,977,450
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,910
|
cpp
|
#include <iostream>
#include <stdlib.h>
using namespace std;
// Estructura de un nodo
struct Nodo
{
int dato;
Nodo *sig;
};
// Prototipo de funciones
void insertar(Nodo *&, int);
void mostrar(Nodo *);
void buscar(Nodo *&, int);
void eliminar(Nodo *&, int);
void vaciar(Nodo *&, int &);
int main()
{
int dato, op, exit;
Nodo *lista = NULL;
do
{
cout << "-----------------------------\n";
cout << "|| 1. Insertar a lista ||\n";
cout << "|| 2. Mostrar lista ||\n";
cout << "|| 3. Buscar en lista ||\n";
cout << "|| 4. Eliminar en lista ||\n";
cout << "|| 5. Vaciar lista ||\n";
cout << "|| 6. Salir ||\n";
cout << "-----------------------------\n";
cout << "Ingrese: ";
cin >> op;
switch (op)
{
case 1:
// Llenar lista
do
{
cout << "Dijite un numero: ";
cin >> dato;
insertar(lista, dato);
cout << "¿Desea agregar otro valor?(si:1/no: 0): ";
cin >> exit;
} while (exit != 0);
break;
case 2:
// Presentar lista
cout << "\nPresentar datos.\n";
mostrar(lista);
break;
case 3:
// buscar en lista
cout << "Ingrese un valor a buscar: ";
cin >> dato;
buscar(lista, dato);
break;
case 4:
// Eliminar en lista
cout << "Ingrese un valor a eliminar: ";
cin >> dato;
eliminar(lista, dato);
break;
case 5:
// Vaciar lista
while (lista != NULL)
{
vaciar(lista, dato);
cout << dato << " Eliminado\n";
}
break;
case 6:
// Salida del programa
cout << "Gracias :D\n";
break;
// Mensaje por defecto
default:
cout << "Verifique su ingreso....\n";
break;
}
} while (op != 6);
return 0;
}
void insertar(Nodo *&lista, int n)
{
Nodo *nuevo = new Nodo();
nuevo->dato = n;
Nodo *aux1 = lista;
Nodo *aux2;
// Recorrer la lista y agregar de manera ordenada
while ((aux1 != NULL) && (aux1->dato < n))
{
aux2 = aux1;
aux1 = aux1->sig;
}
if (lista == aux1)
{
lista = nuevo;
}
else
{
aux2->sig = nuevo;
}
nuevo->sig = aux1;
cout << "Elemento " << n << " agregado.\n";
}
void mostrar(Nodo *lista)
{
Nodo *nuevo = new Nodo();
// almacenar la lista
nuevo = lista;
// recorrer la lista
while (nuevo != NULL)
{
//Presentar el dato
cout << nuevo->dato << " ";
//Pasar al siguiente nodo
nuevo = nuevo->sig;
}
cout << "\n";
}
void buscar(Nodo *&lista, int dato)
{
Nodo *nuevo = new Nodo();
// Almacenar la lista
nuevo = lista;
// Bandera
bool b = false;
// Recorrer la lista
while ((nuevo != NULL) && (nuevo->dato <= dato))
{
// Si se encontro el dato asigne a bandera
b = (nuevo->dato == dato) ? true : false;
// Siguinte nodo
nuevo = nuevo->sig;
}
// Presentar mensaje en caso de que exista o no
b ? cout << "\nEl elemento " << dato << " si existe\n" : cout << "\nEl elemento " << dato << " no existe\n";
}
void eliminar(Nodo *&lista, int dato)
{
// Preguntar si la lista tiene valores
if (lista != NULL)
{
// Nodos auxiliares
Nodo *aux;
Nodo *anterior = NULL;
// Almacenar la lista
aux = lista;
// Recorrer la lista y preguntar si se encontro el valor
while ((aux != NULL) && (aux->dato != dato))
{
// Guardar el valor
anterior = aux;
// Paso al siguiente nodo
aux = aux->sig;
}
// Si no existe el dato
if (aux == NULL)
{
cout << "El elemento no existe.";
}
// Si el dato esta en el primer nodo
else if (anterior == NULL)
{
// Paso al siguiente nodo
lista = lista->sig;
// Eliminar el nodo
delete aux;
}
// Si el dato no esta en el primer nodo
else
{
// Mover posicion en e nodo
anterior->sig = aux->sig;
// Eliminar el nodo
delete aux;
}
}
else
// No existe valores en la lista
{
cout << "La lista esta vacia.\n";
}
}
void vaciar(Nodo *&lista, int &dato)
{
// Guardar la lista
Nodo *aux = lista;
// Guardar el dato
dato = lista->dato;
// Pasar al siguiente
lista = lista->sig;
// Eliminar el nodo
delete aux;
}
|
[
"sacafrank2@gmail.com"
] |
sacafrank2@gmail.com
|
baa39f71e223284215cd3809c6d6183b3deccc1c
|
a8923d2125b3be9ecc9d2d7669fe4c3938f3d432
|
/SEMS/SEM2/linked_list/printing_elements.cpp
|
9ed28bd34b9622811e2ebd71ce0987bfc57ba7f3
|
[] |
no_license
|
RavicharanN/Essentials-IIITA-
|
8361a18be29fccf754da6b7a900997cb64c25ee5
|
a67c3a0e2315f414baec43b57eba2079bc710afb
|
refs/heads/master
| 2021-01-11T18:48:08.856260
| 2017-04-28T14:37:22
| 2017-04-28T14:37:22
| 79,629,289
| 0
| 2
| null | 2017-01-26T11:30:08
| 2017-01-21T06:48:13
|
C
|
UTF-8
|
C++
| false
| false
| 539
|
cpp
|
struct Node{
int data;
struct Node* next;
};
void Print(struct Node* head) //Passing the head from the main function
{
struct Node* p;
if(head==NULL)
return;
p = head;
/*Note that head can't be iterated directly as it defines the
start of the linked list. So, it is assignes to another variable p which
iterates throuch the list */
while(p!=NULL)
{
cout<< p->data <<endl;
p= p->next; // Iteration of p. It ends when p==NULL.
}
return;
}
|
[
"ravicharan.vsp@gmail.com"
] |
ravicharan.vsp@gmail.com
|
3804baee94cc497f71a5bd2d4e1cb340dd503c54
|
55d128c0eceb566d4005971b4b540865dc79e25e
|
/Client/win-system/PipeClient.cpp
|
166fb1528f20668f7e8daa4f9694bf12c2a28ab1
|
[] |
no_license
|
radtek/PandaRC
|
bed7f1fb68bbd0a40eea74de1bbf6bed712eef9e
|
c98b333ac77ac20aa536f203e4dc795754450f02
|
refs/heads/master
| 2021-02-17T03:35:36.074874
| 2019-06-05T05:57:37
| 2019-06-05T05:57:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,831
|
cpp
|
//// Copyright (C) 2009,2010,2011,2012 GlavSoft LLC.
//// All rights reserved.
////
////-------------------------------------------------------------------------
//// This file is part of the TightVNC software. Please visit our Web site:
////
//// http://www.tightvnc.com/
////
//// This program is free software; you can redistribute it and/or modify
//// it under the terms of the GNU General Public License as published by
//// the Free Software Foundation; either version 2 of the License, or
//// (at your option) any later version.
////
//// This program is distributed in the hope that it will be useful,
//// but WITHOUT ANY WARRANTY; without even the implied warranty of
//// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//// GNU General Public License for more details.
////
//// You should have received a copy of the GNU General Public License along
//// with this program; if not, write to the Free Software Foundation, Inc.,
//// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
////-------------------------------------------------------------------------
////
//
//#include "PipeClient.h"
//#include "util/Exception.h"
//
//PipeClient::PipeClient()
//{
//}
//
//NamedPipe *PipeClient::connect(const TCHAR *name, unsigned int maxPortionSize)
//{
// StringStorage pipeName;
// pipeName.format(_T("\\\\.\\pipe\\%s"), name);
//
// HANDLE hPipe;
// hPipe = CreateFile(pipeName.getString(), // pipe name
// GENERIC_READ | // read and write access
// GENERIC_WRITE,
// 0, // no sharing
// NULL, // default security attributes
// OPEN_EXISTING, // opens existing pipe
// FILE_FLAG_OVERLAPPED, // asynchronous mode
// NULL); // no template file
//
// if (hPipe == INVALID_HANDLE_VALUE) {
// int errCode = GetLastError();
// StringStorage errMess;
// errMess.format(_T("Connect to pipe server failed, error code = %d"), errCode);
// throw Exception(errMess.getString());
// }
//
// DWORD dwMode = PIPE_READMODE_BYTE;
// if (!SetNamedPipeHandleState(hPipe, // pipe handle
// &dwMode, // new pipe mode
// NULL, // don't set maximum bytes
// NULL) // don't set maximum time
// ) {
// int errCode = GetLastError();
// StringStorage errMess;
// errMess.format(_T("SetNamedPipeHandleState failed, error code = %d"), errCode);
// throw Exception(errMess.getString());
// }
//
// return new NamedPipe(hPipe, maxPortionSize, false);
//}
|
[
"415893943@qq.com"
] |
415893943@qq.com
|
7f7b319933b1adb1c181be8bb1c75950576d79ce
|
5cd670d08b7d2bcd6514405ed2f465b8289fd9b2
|
/src/rpcnet.cpp
|
3052eae3382bb4f5205c8657191ced06c6801a62
|
[
"MIT"
] |
permissive
|
ipsum-network/ips
|
00511c0a58a4070b8efe0f62030bb397cf531e21
|
fd4a6304bfae2e741654272fee9dcdf38cd83016
|
refs/heads/master
| 2020-03-16T11:57:02.273337
| 2018-07-09T01:53:14
| 2018-07-09T01:53:14
| 132,657,160
| 7
| 16
|
MIT
| 2018-07-09T01:53:15
| 2018-05-08T19:47:00
|
C++
|
UTF-8
|
C++
| false
| false
| 17,231
|
cpp
|
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 IPSUM Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcserver.h"
#include "clientversion.h"
#include "main.h"
#include "net.h"
#include "netbase.h"
#include "protocol.h"
#include "sync.h"
#include "timedata.h"
#include "util.h"
#include "version.h"
#include <boost/foreach.hpp>
#include "json/json_spirit_value.h"
using namespace json_spirit;
using namespace std;
Value getconnectioncount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getconnectioncount\n"
"\nReturns the number of connections to other nodes.\n"
"\nbResult:\n"
"n (numeric) The connection count\n"
"\nExamples:\n" +
HelpExampleCli("getconnectioncount", "") + HelpExampleRpc("getconnectioncount", ""));
LOCK(cs_vNodes);
return (int)vNodes.size();
}
Value ping(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"ping\n"
"\nRequests that a ping be sent to all other nodes, to measure ping time.\n"
"Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n"
"Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.\n"
"\nExamples:\n" +
HelpExampleCli("ping", "") + HelpExampleRpc("ping", ""));
// Request that each node send a ping during next message processing pass
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pNode, vNodes) {
pNode->fPingQueued = true;
}
return Value::null;
}
static void CopyNodeStats(std::vector<CNodeStats>& vstats)
{
vstats.clear();
LOCK(cs_vNodes);
vstats.reserve(vNodes.size());
BOOST_FOREACH (CNode* pnode, vNodes) {
CNodeStats stats;
pnode->copyStats(stats);
vstats.push_back(stats);
}
}
Value getpeerinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getpeerinfo\n"
"\nReturns data about each connected network node as a json array of objects.\n"
"\nbResult:\n"
"[\n"
" {\n"
" \"id\": n, (numeric) Peer index\n"
" \"addr\":\"host:port\", (string) The ip address and port of the peer\n"
" \"addrlocal\":\"ip:port\", (string) local address\n"
" \"services\":\"xxxxxxxxxxxxxxxx\", (string) The services offered\n"
" \"lastsend\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last send\n"
" \"lastrecv\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last receive\n"
" \"bytessent\": n, (numeric) The total bytes sent\n"
" \"bytesrecv\": n, (numeric) The total bytes received\n"
" \"conntime\": ttt, (numeric) The connection time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"pingtime\": n, (numeric) ping time\n"
" \"pingwait\": n, (numeric) ping wait\n"
" \"version\": v, (numeric) The peer version, such as 7001\n"
" \"subver\": \"/Ips:x.x.x.x/\", (string) The string version\n"
" \"inbound\": true|false, (boolean) Inbound (true) or Outbound (false)\n"
" \"startingheight\": n, (numeric) The starting height (block) of the peer\n"
" \"banscore\": n, (numeric) The ban score\n"
" \"synced_headers\": n, (numeric) The last header we have in common with this peer\n"
" \"synced_blocks\": n, (numeric) The last block we have in common with this peer\n"
" \"inflight\": [\n"
" n, (numeric) The heights of blocks we're currently asking from this peer\n"
" ...\n"
" ]\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("getpeerinfo", "") + HelpExampleRpc("getpeerinfo", ""));
vector<CNodeStats> vstats;
CopyNodeStats(vstats);
Array ret;
BOOST_FOREACH (const CNodeStats& stats, vstats) {
Object obj;
CNodeStateStats statestats;
bool fStateStats = GetNodeStateStats(stats.nodeid, statestats);
obj.push_back(Pair("id", stats.nodeid));
obj.push_back(Pair("addr", stats.addrName));
if (!(stats.addrLocal.empty()))
obj.push_back(Pair("addrlocal", stats.addrLocal));
obj.push_back(Pair("services", strprintf("%016x", stats.nServices)));
obj.push_back(Pair("lastsend", stats.nLastSend));
obj.push_back(Pair("lastrecv", stats.nLastRecv));
obj.push_back(Pair("bytessent", stats.nSendBytes));
obj.push_back(Pair("bytesrecv", stats.nRecvBytes));
obj.push_back(Pair("conntime", stats.nTimeConnected));
obj.push_back(Pair("pingtime", stats.dPingTime));
if (stats.dPingWait > 0.0)
obj.push_back(Pair("pingwait", stats.dPingWait));
obj.push_back(Pair("version", stats.nVersion));
// Use the sanitized form of subver here, to avoid tricksy remote peers from
// corrupting or modifiying the JSON output by putting special characters in
// their ver message.
obj.push_back(Pair("subver", stats.cleanSubVer));
obj.push_back(Pair("inbound", stats.fInbound));
obj.push_back(Pair("startingheight", stats.nStartingHeight));
if (fStateStats) {
obj.push_back(Pair("banscore", statestats.nMisbehavior));
obj.push_back(Pair("synced_headers", statestats.nSyncHeight));
obj.push_back(Pair("synced_blocks", statestats.nCommonHeight));
Array heights;
BOOST_FOREACH (int height, statestats.vHeightInFlight) {
heights.push_back(height);
}
obj.push_back(Pair("inflight", heights));
}
obj.push_back(Pair("whitelisted", stats.fWhitelisted));
ret.push_back(obj);
}
return ret;
}
Value addnode(const Array& params, bool fHelp)
{
string strCommand;
if (params.size() == 2)
strCommand = params[1].get_str();
if (fHelp || params.size() != 2 ||
(strCommand != "onetry" && strCommand != "add" && strCommand != "remove"))
throw runtime_error(
"addnode \"node\" \"add|remove|onetry\"\n"
"\nAttempts add or remove a node from the addnode list.\n"
"Or try a connection to a node once.\n"
"\nArguments:\n"
"1. \"node\" (string, required) The node (see getpeerinfo for nodes)\n"
"2. \"command\" (string, required) 'add' to add a node to the list, 'remove' to remove a node from the list, 'onetry' to try a connection to the node once\n"
"\nExamples:\n" +
HelpExampleCli("addnode", "\"192.168.0.6:22331\" \"onetry\"") + HelpExampleRpc("addnode", "\"192.168.0.6:22331\", \"onetry\""));
string strNode = params[0].get_str();
if (strCommand == "onetry") {
CAddress addr;
OpenNetworkConnection(addr, NULL, strNode.c_str());
return Value::null;
}
LOCK(cs_vAddedNodes);
vector<string>::iterator it = vAddedNodes.begin();
for (; it != vAddedNodes.end(); it++)
if (strNode == *it)
break;
if (strCommand == "add") {
if (it != vAddedNodes.end())
throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: Node already added");
vAddedNodes.push_back(strNode);
} else if (strCommand == "remove") {
if (it == vAddedNodes.end())
throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added.");
vAddedNodes.erase(it);
}
return Value::null;
}
Value getaddednodeinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getaddednodeinfo dns ( \"node\" )\n"
"\nReturns information about the given added node, or all added nodes\n"
"(note that onetry addnodes are not listed here)\n"
"If dns is false, only a list of added nodes will be provided,\n"
"otherwise connected information will also be available.\n"
"\nArguments:\n"
"1. dns (boolean, required) If false, only a list of added nodes will be provided, otherwise connected information will also be available.\n"
"2. \"node\" (string, optional) If provided, return information about this specific node, otherwise all nodes are returned.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"addednode\" : \"192.168.0.201\", (string) The node ip address\n"
" \"connected\" : true|false, (boolean) If connected\n"
" \"addresses\" : [\n"
" {\n"
" \"address\" : \"192.168.0.201:22331\", (string) The ips server host and port\n"
" \"connected\" : \"outbound\" (string) connection, inbound or outbound\n"
" }\n"
" ,...\n"
" ]\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("getaddednodeinfo", "true") + HelpExampleCli("getaddednodeinfo", "true \"192.168.0.201\"") + HelpExampleRpc("getaddednodeinfo", "true, \"192.168.0.201\""));
bool fDns = params[0].get_bool();
list<string> laddedNodes(0);
if (params.size() == 1) {
LOCK(cs_vAddedNodes);
BOOST_FOREACH (string& strAddNode, vAddedNodes)
laddedNodes.push_back(strAddNode);
} else {
string strNode = params[1].get_str();
LOCK(cs_vAddedNodes);
BOOST_FOREACH (string& strAddNode, vAddedNodes)
if (strAddNode == strNode) {
laddedNodes.push_back(strAddNode);
break;
}
if (laddedNodes.size() == 0)
throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added.");
}
Array ret;
if (!fDns) {
BOOST_FOREACH (string& strAddNode, laddedNodes) {
Object obj;
obj.push_back(Pair("addednode", strAddNode));
ret.push_back(obj);
}
return ret;
}
list<pair<string, vector<CService> > > laddedAddreses(0);
BOOST_FOREACH (string& strAddNode, laddedNodes) {
vector<CService> vservNode(0);
if (Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0))
laddedAddreses.push_back(make_pair(strAddNode, vservNode));
else {
Object obj;
obj.push_back(Pair("addednode", strAddNode));
obj.push_back(Pair("connected", false));
Array addresses;
obj.push_back(Pair("addresses", addresses));
}
}
LOCK(cs_vNodes);
for (list<pair<string, vector<CService> > >::iterator it = laddedAddreses.begin(); it != laddedAddreses.end(); it++) {
Object obj;
obj.push_back(Pair("addednode", it->first));
Array addresses;
bool fConnected = false;
BOOST_FOREACH (CService& addrNode, it->second) {
bool fFound = false;
Object node;
node.push_back(Pair("address", addrNode.ToString()));
BOOST_FOREACH (CNode* pnode, vNodes)
if (pnode->addr == addrNode) {
fFound = true;
fConnected = true;
node.push_back(Pair("connected", pnode->fInbound ? "inbound" : "outbound"));
break;
}
if (!fFound)
node.push_back(Pair("connected", "false"));
addresses.push_back(node);
}
obj.push_back(Pair("connected", fConnected));
obj.push_back(Pair("addresses", addresses));
ret.push_back(obj);
}
return ret;
}
Value getnettotals(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"getnettotals\n"
"\nReturns information about network traffic, including bytes in, bytes out,\n"
"and current time.\n"
"\nResult:\n"
"{\n"
" \"totalbytesrecv\": n, (numeric) Total bytes received\n"
" \"totalbytessent\": n, (numeric) Total bytes sent\n"
" \"timemillis\": t (numeric) Total cpu time\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getnettotals", "") + HelpExampleRpc("getnettotals", ""));
Object obj;
obj.push_back(Pair("totalbytesrecv", CNode::GetTotalBytesRecv()));
obj.push_back(Pair("totalbytessent", CNode::GetTotalBytesSent()));
obj.push_back(Pair("timemillis", GetTimeMillis()));
return obj;
}
static Array GetNetworksInfo()
{
Array networks;
for (int n = 0; n < NET_MAX; ++n) {
enum Network network = static_cast<enum Network>(n);
if (network == NET_UNROUTABLE)
continue;
proxyType proxy;
Object obj;
GetProxy(network, proxy);
obj.push_back(Pair("name", GetNetworkName(network)));
obj.push_back(Pair("limited", IsLimited(network)));
obj.push_back(Pair("reachable", IsReachable(network)));
obj.push_back(Pair("proxy", proxy.IsValid() ? proxy.ToStringIPPort() : string()));
networks.push_back(obj);
}
return networks;
}
Value getnetworkinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getnetworkinfo\n"
"Returns an object containing various state info regarding P2P networking.\n"
"\nResult:\n"
"{\n"
" \"version\": xxxxx, (numeric) the server version\n"
" \"subversion\": \"/Ips:x.x.x.x/\", (string) the server subversion string\n"
" \"protocolversion\": xxxxx, (numeric) the protocol version\n"
" \"localservices\": \"xxxxxxxxxxxxxxxx\", (string) the services we offer to the network\n"
" \"timeoffset\": xxxxx, (numeric) the time offset\n"
" \"connections\": xxxxx, (numeric) the number of connections\n"
" \"networks\": [ (array) information per network\n"
" {\n"
" \"name\": \"xxx\", (string) network (ipv4, ipv6 or onion)\n"
" \"limited\": true|false, (boolean) is the network limited using -onlynet?\n"
" \"reachable\": true|false, (boolean) is the network reachable?\n"
" \"proxy\": \"host:port\" (string) the proxy that is used for this network, or empty if none\n"
" }\n"
" ,...\n"
" ],\n"
" \"relayfee\": x.xxxxxxxx, (numeric) minimum relay fee for non-free transactions in ips/kb\n"
" \"localaddresses\": [ (array) list of local addresses\n"
" {\n"
" \"address\": \"xxxx\", (string) network address\n"
" \"port\": xxx, (numeric) network port\n"
" \"score\": xxx (numeric) relative score\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getnetworkinfo", "") + HelpExampleRpc("getnetworkinfo", ""));
Object obj;
obj.push_back(Pair("version", CLIENT_VERSION));
obj.push_back(Pair("subversion",
FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>())));
obj.push_back(Pair("protocolversion", PROTOCOL_VERSION));
obj.push_back(Pair("localservices", strprintf("%016x", nLocalServices)));
obj.push_back(Pair("timeoffset", GetTimeOffset()));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("networks", GetNetworksInfo()));
obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
Array localAddresses;
{
LOCK(cs_mapLocalHost);
BOOST_FOREACH (const PAIRTYPE(CNetAddr, LocalServiceInfo) & item, mapLocalHost) {
Object rec;
rec.push_back(Pair("address", item.first.ToString()));
rec.push_back(Pair("port", item.second.nPort));
rec.push_back(Pair("score", item.second.nScore));
localAddresses.push_back(rec);
}
}
obj.push_back(Pair("localaddresses", localAddresses));
return obj;
}
|
[
"dev@home33.io"
] |
dev@home33.io
|
92809540f868a1395a2e58e8f99a9f20fd9e87be
|
8a213f015fe67169e3e885ab12baf8c638d98b71
|
/lab_hash/hashtable.h
|
7b80e99004dee76eb5952dd0836ffe25f29bc8c8
|
[] |
no_license
|
mshah12/cs225-sp20
|
bf749bd6d84a07bbb34432e56b0d4b9811d8c299
|
21a949eb61eadbfe7e89c8aeea63cf3fe6322907
|
refs/heads/master
| 2022-11-19T13:30:25.461014
| 2020-07-20T18:06:29
| 2020-07-20T18:06:29
| 267,644,695
| 2
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,545
|
h
|
/**
* @file hashtable.h
* Definition of an abstract HashTable interface.
*/
#pragma once
#include <vector>
#include <cstddef>
#include <algorithm>
#include "hashes.h"
/**
* A templated class that implements the Dictionary ADT by using
* a hash table.
*/
template <class K, class V>
class HashTable
{
public:
/**
* Iterator for iterating over a hashtable.
*
* This example will print out all of the key, value pairs in the
* HashTable variable `ht`:
*
* for( HashTabe::iterator it = ht.begin(); it != ht.end(); ++it )
* cout << "key: " << it->first << " value: " << it->second << endl;
*/
class iterator; // forward declare our iterator
/**
* Destructor for a HashTable: made virtual to allow overloading in
* derived classes.
*/
virtual ~HashTable()
{
/* nothing */
};
/**
* Inserts the given key, value pair into the HashTable.
*
* @param key The key to be inserted.
* @param value The value to be inserted.
*/
virtual void insert(const K& key, const V& value) = 0;
/**
* Removes the given key (and its associated data) from the
* HashTable.
*
* @param key The key to be removed.
*/
virtual void remove(const K& key) = 0;
/**
* Finds the value associated with a given key.
*
* @param key The key whose data we want to find.
* @return The value associated with this key, or the default value
* (V()) if it was not found.
*/
virtual V find(const K& key) const = 0;
/**
* Determines if the given key exists in the HashTable.
*
* @param key The key we want to find.
* @return A boolean value indicating whether the key was found in
* the HashTable.
*/
virtual bool keyExists(const K& key) const = 0;
/**
* Empties the HashTable (that is, all keys and values are
* removed).
*/
virtual void clear() = 0;
/**
* Determines if the HashTable is empty. O(1).
*
* @note This depends on elems being set properly in derived
* classes.
*
* @return A boolean value indicating whether the HashTable is
* empty.
*/
virtual bool isEmpty() const
{
return elems == 0;
}
/**
* Used to determine the total size of the HashTable. Used for
* grading purposes.
*
* @return The size of the HashTable (that is, the total number of
* available cells, not the number of elements the table
* contains).
*/
virtual size_t tableSize() const
{
return size;
}
/**
* Access operator: Returns a reference to a value in the
* HashTable, so that it may be modified. If the key you are
* searching for is not found in the table, this method inserts it
* with the default value V() (which you then may modify).
*
* Examples:
*
* hashtable["mykey"]; // returns the value for "mykey", or the
* // default value if "mykey" is not in
* // the table
*
* hashtable["myOtherKey"] = "myNewValue";
*
* @param key The key to be found in the HashTable.
* @return A reference to the value for this key contained in the
* table.
*/
virtual V& operator[](const K& key) = 0;
/**
* Returns an iterator to the beginning of the HashTable.
*
* @return An iterator to the beginning of the HashTable.
*/
virtual iterator begin() const = 0;
/**
* Returns an iterator to the end of the HashTable. Note that this
* is essentially like returning an index to one past the final
* element in an array (that is, end() itself gives an iterator to
* one past the last thing in the HashTable).
*
* @return An iterator to the end of the HashTable.
*/
virtual iterator end() const = 0;
protected:
size_t elems; /**< The current number of elements stored in the HashTable. */
size_t size; /**< The current size of the HashTable (total cells). */
class HTIteratorImpl; /**< Implementation for our iterator. You
don't have to worry about this. */
/**
* Helper function to create an iterator. You shouldn't have to
* invoke this: instead, use the begin() and end() functions on
* your particular HashTable implementation to get iterators to the
* beginning and ending of the HashTable, respectively.
*
* @return An iterator for this HashTable.
*/
iterator makeIterator(HTIteratorImpl* impl) const
{
return iterator(impl);
}
/**
* Determines if the HashTable should resize.
* @return Whether the HashTable should resize.
*/
inline bool shouldResize() const
{
return static_cast<double>(elems) / size >= 0.7;
}
/**
* List of primes for resizing.
*/
static const size_t primes[];
/**
* Finds the closest prime in our list to the given number.
*
* @param num The number to find the closest prime to in our list.
* @return The closest prime we have to num in our list of primes.
*/
size_t findPrime(size_t num);
private:
/**
* Private helper function to resize the HashTable. This should be
* called when the load factor is >= 0.7 (this is somewhat
* arbitrary, but used for grading).
*/
virtual void resizeTable() = 0;
};
/**
* List of primes for resizing. "borrowed" from boost::unordered.
*/
template <class K, class V>
const size_t HashTable<K, V>::primes[]
= {17ul, 29ul, 37ul, 53ul, 67ul,
79ul, 97ul, 131ul, 193ul, 257ul,
389ul, 521ul, 769ul, 1031ul, 1543ul,
2053ul, 3079ul, 6151ul, 12289ul, 24593ul,
49157ul, 98317ul, 196613ul, 393241ul, 786433ul,
1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul,
50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul,
1610612741ul, 3221225473ul, 4294967291ul};
template <class K, class V>
size_t HashTable<K, V>::findPrime(size_t num)
{
size_t len = sizeof(primes) / sizeof(size_t);
const size_t* first = primes;
const size_t* last = primes + len;
const size_t* prime = std::upper_bound(first, last, num);
if (prime == last)
--prime;
return *prime;
}
#include "htiterator.h"
|
[
"megh5000@gmail.com"
] |
megh5000@gmail.com
|
daa82e4f01e0765c77b4c7afdb3936baa05d82b0
|
8ad491bda5b098edd019ba24a34300f123ddf2de
|
/RainbowSnake/State.h
|
40424846f264e30e0c1de08fd6800e4024e9eee6
|
[
"MIT"
] |
permissive
|
pietrzakacper/RainbowSnake
|
cecef1576c8290091ac1116d3895fd3b0a9eca6b
|
5068c73d3a4298dbcb510df0db5085118eb9a344
|
refs/heads/master
| 2021-01-21T04:51:03.599896
| 2017-09-03T09:11:15
| 2017-09-03T09:11:15
| 51,362,178
| 4
| 5
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 398
|
h
|
#pragma once
#include <SFML\Graphics.hpp>
using namespace sf;
using namespace std;
class State
{
public:
State(int STATE_ID, RenderWindow&, Font& font);
virtual ~State();
virtual void init() = 0;
virtual void update() = 0;
virtual int handleEvents(Event&) = 0;
virtual void render() = 0;
int getSTATE_ID() const;
protected:
Font* _font;
RenderWindow* _window;
const int STATE_ID;
};
|
[
"kacpietrzak@gmail.com"
] |
kacpietrzak@gmail.com
|
437a4bc4e0731c524b697c7387b38a9f6277294d
|
17b1a813203d9e60b0761f9aa5b6a5c505ed91ec
|
/Actions/CutAction.h
|
12cfdbbe71608264ffdf8949fd03f15c5fe42fa7
|
[] |
no_license
|
Happysword/Paint-For-Kids
|
1009a84f7e1ce0e922ef21df1a63640949a928f3
|
ad1c11b616bbe31a6c5969d4738ca7ebafd487d9
|
refs/heads/master
| 2021-10-09T09:55:12.071069
| 2018-12-25T21:23:58
| 2018-12-25T21:23:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 312
|
h
|
#pragma once
#include "action.h"
#include "../ApplicationManager.h"
#include "CopyAction.h"
class CutAction : public CopyAction
{
private:
Point P1; //Point of selection
public:
CutAction(ApplicationManager *pApp);
~CutAction();
virtual void ReadActionParameters();
virtual void Execute() ;
};
|
[
"bahaaeldeen1999@gmail.com"
] |
bahaaeldeen1999@gmail.com
|
5280e1962910280cddf481e2b1f973cecff9deb3
|
aa9c84037b54c1efec0ba79c84c60d82f3a9f0d9
|
/TableViewController.h
|
a60d40a6fcf83c93fc18606710ca7677f2880004
|
[] |
no_license
|
mipt-proglang-2015/proglangs_bochkarev
|
e45b587658239463a671b26d176de4062a6a3a9e
|
049a3b68ad78ebe80a18031f94106433ce1eee6e
|
refs/heads/master
| 2018-12-28T00:24:29.432556
| 2015-12-14T17:46:17
| 2015-12-14T17:46:17
| 42,154,826
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 937
|
h
|
#ifndef STANDARTMODELWRAPPER_H
#define STANDARTMODELWRAPPER_H
#include <QObject>
#include <QStandardItemModel>
#include <QtWidgets/QTableView>
#include <QItemSelectionModel>
#include "CellData.h"
const int RowsCount = 255;
const int ColsCount = 26;
class TableViewController : public QObject
{
Q_OBJECT
public:
explicit TableViewController(QObject *parent = 0);
explicit TableViewController(QTableView *tableView);
Q_SIGNALS:
void tableViewCellDidEndEditing(const QString& value);
void tableViewDidSelectCell(const QString& cellValue);
private Q_SLOTS:
void onTableViewItemChanged(QStandardItem* item);
void onTableViewDidSelectCell(const QItemSelection& selected, const QItemSelection& deselected);
private:
QStandardItemModel* createStandartItemModel();
QStandardItemModel* _model;
QTableView* _tableView;
CellData _gridData[RowsCount][ColsCount];
};
#endif // STANDARTMODELWRAPPER_H
|
[
"otnasa@gmail.com"
] |
otnasa@gmail.com
|
197188cf86070e8ace777883a9ad7bab1f148d34
|
2da28852b8e688aefb7a5c34090ba4f6d4d918d6
|
/Brandisher/include/nana/gui/filebox.hpp
|
1800eb9fe2fb8ac3e59055160351508cef7c7125
|
[
"Apache-2.0"
] |
permissive
|
winksaville/lava
|
9e09b09f30ca7b26e17043506db1b5960a341a5d
|
13fbb442407e24360664263f56af41b77ca6bdf0
|
refs/heads/master
| 2020-03-21T11:22:14.483669
| 2018-06-15T14:23:38
| 2018-06-15T14:23:38
| 138,503,348
| 0
| 1
|
Apache-2.0
| 2018-06-24T17:48:51
| 2018-06-24T17:48:51
| null |
UTF-8
|
C++
| false
| false
| 2,603
|
hpp
|
/**
* Filebox
* Nana C++ Library(http://www.nanapro.org)
* Copyright(C) 2003-2017 Jinhao(cnjinhao@hotmail.com)
*
* 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)
*
* @file nana/gui/filebox.hpp
* @author Jinhao
* @brief a dialog to chose file(s), implemented "native" in windows but using nana for X11
*/
#ifndef NANA_GUI_FILEBOX_HPP
#define NANA_GUI_FILEBOX_HPP
#include <nana/gui/basis.hpp>
#include <vector>
#include <utility>
namespace nana
{ /// Create an Open or Save dialog box to let user select the name of a file.
class filebox
{
struct implement;
filebox(filebox&&) = delete;
filebox& operator=(filebox&&) = delete;
public:
using filters = std::vector<std::pair< ::std::string, ::std::string>>;
filebox(bool is_open_mode);
filebox(window owner, bool is_open_mode);
filebox(const filebox&);
~filebox();
filebox& operator=(const filebox&);
/// Change owner window
void owner(window);
/// Set a new title for the dialog
/// @param string a text for title
/// @return the old title.
::std::string title( ::std::string new_title);
/** @brief Suggest initial path used to locate a directory when the filebox starts.
* @param string initial_directory a path of initial directory
* @note the behavior of init_path is different between Win7 and Win2K/XP/Vista, but its behavior under Linux is conformed with Win7.
*/
filebox& init_path(const ::std::string& initial_directory);
filebox& init_file(const ::std::string&); ///< Init file, if it contains a path, the init path is replaced by the path of init file.
/// \brief Add a filetype filter.
/// To specify multiple filter in a single description, use a semicolon to separate the patterns(for example,"*.TXT;*.DOC;*.BAK").
filebox& add_filter(const ::std::string& description, ///< for example. "Text File"
const ::std::string& filetype ///< filter pattern(for example, "*.TXT")
);
filebox& add_filter(const filters &ftres)
{
for (auto &f : ftres)
add_filter(f.first, f.second);
return *this;
};
::std::string path() const;
::std::string file() const;
/// Display the filebox dialog
bool show() const;
/// a function object method alternative to show() to display the filebox dialog,
bool operator()() const
{
return show();
}
private:
implement * impl_;
};
}//end namespace nana
#endif
|
[
"lava@shinespark.io"
] |
lava@shinespark.io
|
bf44403637dae1e2ed91249bb12176d4b1256fd8
|
87028ddef5fed445997c116f1a9e521cf027f6ad
|
/sdk/c_game_event_manager.h
|
187aae5e110b91ec66d52ee428e2b5324e9df0c6
|
[] |
no_license
|
Akatsyk/sequency-hvh
|
41557a290f8013d6a4e797e8897c93ca1abeeb97
|
e6ec9bd218e40612f262792dff79f8b4f64a64a3
|
refs/heads/main
| 2023-08-06T00:34:06.516525
| 2021-10-01T12:16:02
| 2021-10-01T12:16:02
| 412,454,180
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,563
|
h
|
#pragma once
#include <cstdint>
#include "macros.h"
#include "c_client_state.h"
class c_game_event
{
public:
/*virtual ~c_game_event() = default;
virtual const char* get_name() const = 0;
virtual bool is_reliable() const = 0;
virtual bool is_local() const = 0;
virtual bool is_empty(const char* keyname = nullptr) = 0;
virtual bool get_bool(const char* keyname = nullptr, bool default_value = false) = 0;
virtual int GetInt(const char* keyname = nullptr, int default_value = 0) = 0;
virtual uint64_t get_uint64(const char* keyname = nullptr, uint64_t default_value = 0) = 0;
virtual float get_float(const char* keyname = nullptr, float default_value = 0.0f) = 0;
virtual const char* get_string(const char* keyname = nullptr, const char* default_value = _("")) = 0;*/
virtual ~c_game_event() {};
virtual const char* GetName() const = 0; // get event name
virtual bool IsReliable() const = 0; // if event handled reliable
virtual bool IsLocal() const = 0; // if event is never networked
virtual bool IsEmpty(const char* keyName = NULL) = 0; // check if data field exists
// Data access
virtual bool GetBool(const char* keyName = NULL, bool defaultValue = false) = 0;
virtual int GetInt(const char* keyName = NULL, int defaultValue = 0) = 0;
virtual unsigned long long GetUint64(char const* keyName = NULL, unsigned long long defaultValue = 0) = 0;
virtual float GetFloat(const char* keyName = NULL, float defaultValue = 0.0f) = 0;
virtual const char* GetString(const char* keyName = NULL, const char* defaultValue = "") = 0;
virtual const wchar_t* GetWString(char const* keyName = NULL, const wchar_t* defaultValue = L"") = 0;
virtual void SetBool(const char* keyName, bool value) = 0;
virtual void SetInt(const char* keyName, int value) = 0;
virtual void SetUInt64(const char* keyName, unsigned long long value) = 0;
virtual void SetFloat(const char* keyName, float value) = 0;
virtual void SetString(const char* keyName, const char* value) = 0;
virtual void SetWString(const char* keyName, const wchar_t* value) = 0;
};
class c_game_event_listener
{
public:
virtual ~c_game_event_listener() {}
virtual void fire_game_event(c_game_event* Event) = 0;
virtual int GetEventDebugID()
{
return 42;
}
};
class c_game_event_manager
{
public:
/*virtual ~c_game_event_manager() = 0;
virtual int load_events_from_file(const char* filename) = 0;
virtual void reset() = 0;
virtual bool add_listener(c_game_event_listener* listener, const char* name, bool serverside) = 0;
virtual bool find_listener(c_game_event_listener* listener, const char* name) = 0;
virtual void remove_listener(c_game_event_listener* listener) = 0;
virtual void add_listener_global(c_game_event_listener* listener, bool serverside) = 0;*/
virtual int __Unknown_1(int* dwUnknown) = 0;
// load game event descriptions from a file eg "resource\gameevents.res"
virtual int LoadEventsFromFile(const char* filename) = 0;
// removes all and anything
virtual void Reset() = 0;
// adds a listener for a particular event
virtual bool AddListener(c_game_event_listener* listener, const char* name, bool bServerSide) = 0;
// returns true if this listener is listens to given event
virtual bool FindListener(c_game_event_listener* listener, const char* name) = 0;
// removes a listener
virtual int RemoveListener(c_game_event_listener* listener) = 0;
// create an event by name, but doesn't fire it. returns NULL is event is not
// known or no listener is registered for it. bForce forces the creation even if no listener is active
virtual c_game_event* CreateEvent(const char* name, bool bForce, unsigned int dwUnknown) = 0;
// fires a server event created earlier, if bDontBroadcast is set, event is not send to clients
virtual bool FireEvent(c_game_event* event, bool bDontBroadcast = false) = 0;
// fires an event for the local client only, should be used only by client code
virtual bool FireEventClientSide(c_game_event* event) = 0;
// create a new copy of this event, must be free later
virtual c_game_event* DuplicateEvent(c_game_event* event) = 0;
// if an event was created but not fired for some reason, it has to bee freed, same UnserializeEvent
virtual void FreeEvent(c_game_event* event) = 0;
// write/read event to/from bitbuffer
virtual bool SerializeEvent(c_game_event* event, bf_write* buf) = 0;
// create new KeyValues, must be deleted
virtual c_game_event* UnserializeEvent(bf_read* buf) = 0;
};
interface_var(c_game_event_manager, game_event_manager, "engine.dll", "GAMEEVENTSMANAGER")
|
[
"48151096+Akatsyk@users.noreply.github.com"
] |
48151096+Akatsyk@users.noreply.github.com
|
52502bd6a97e864373339db42991aa505047771f
|
6d796ee865e1c79582a024bb38cc64fa15b8b8de
|
/cs8Backup/zipper.h
|
80cdaab031924624e909e394cee3f027e433ea64
|
[] |
no_license
|
pyrokar1993/cs8Tools
|
8f82a7e223f5b1529b02fe388cb81018a6cc401f
|
d6d2c37c404c093e9900e6d2dd1f65c520ed45e8
|
refs/heads/master
| 2022-11-23T16:43:30.093698
| 2020-05-16T17:07:24
| 2020-05-16T17:07:24
| 183,562,748
| 0
| 0
| null | 2019-04-26T05:27:36
| 2019-04-26T05:27:34
| null |
UTF-8
|
C++
| false
| false
| 2,139
|
h
|
/**************************************************************************
* Copyright (C) 2006 by Volker Drewer-Gutland *
* volker.drewer@gmx.de *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef ZIPPER_H
#define ZIPPER_H
#include <QMainWindow>
#include <zip/quazip.h>
#include <zip/quazipfile.h>
class QDir;
class QString;
class QStringList;
class zipper : public QWidget, QuaZip
{
Q_OBJECT
public:
zipper();
~zipper();
void compressDir(const QDir &dirInfo, const QString &fileName, bool deleteFiles = false);
protected:
QStringList getFileList(const QDir &dirInfo);
QStringList getDirList(const QDir &dirInfo);
bool deleteDir(QString dirName);
private:
signals:
void compressingFile(const QString fileName, int index, int count);
void completed(bool result);
};
#endif // ZIPPER_H
|
[
"volker.drewer@gmail.com"
] |
volker.drewer@gmail.com
|
d994574a7d9ad4691c64e66b3211f1079f0d72c8
|
28869ba91fcd52c281ed88e6dc0dba96c35ffe07
|
/include/ThickArrow.hpp
|
dfb41dcf0fd2758420c69196e8c38240f1addbc9
|
[] |
no_license
|
elro444/SFML-Linear-Algebra
|
e677ec3f380035a4f072732aa8a5a8dfed2ad1f5
|
83e8b0856b119cc1c4204b5f2cc79c06e7d921af
|
refs/heads/master
| 2023-07-15T06:37:57.663486
| 2021-08-15T21:18:47
| 2021-08-16T06:25:25
| 395,536,013
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 826
|
hpp
|
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/RectangleShape.hpp>
#include <SFML/Graphics/ConvexShape.hpp>
class ThickArrow
: public sf::Drawable
{
private:
mutable sf::RectangleShape m_line;
mutable sf::ConvexShape m_tip;
sf::Vector2f m_head;
sf::Vector2f m_tail;
sf::Color m_color;
float m_thickness;
float m_tipRadius;
bool m_should_invalidate;
public:
ThickArrow(float thickness, float tipRadius);
ThickArrow(sf::Vector2f tail, sf::Vector2f head, float thickness, sf::Color color, float tipRadius);
void setHeadPos(sf::Vector2f pos);
void setTailPos(sf::Vector2f pos);
void setColor(sf::Color color);
protected:
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const override;
private:
void invalidate() const;
};
|
[
"elro444@gmail.com"
] |
elro444@gmail.com
|
15e8f1c7bb08ef25ddbab7a1d98fc8ac5a901709
|
3871c5adec9880d6ef7e4d60c079d8f3f23fa8a2
|
/VCECore/gpuz_info.cpp
|
4767887153e409c6465fac1740c30816e071995b
|
[
"MIT",
"Zlib",
"BSD-2-Clause"
] |
permissive
|
rigaya/VCEEnc
|
5bc4878383a37c18a83c4aed1047a311e1c12c70
|
101a1b3dcd16e0bf951f2897187396ba64be3e09
|
refs/heads/master
| 2023-07-06T10:06:44.198622
| 2023-06-23T23:49:05
| 2023-06-23T23:50:41
| 79,711,619
| 192
| 31
|
NOASSERTION
| 2023-09-11T14:48:14
| 2017-01-22T10:45:01
|
C++
|
UTF-8
|
C++
| false
| false
| 3,535
|
cpp
|
// -----------------------------------------------------------------------------------------
// QSVEnc by rigaya
// -----------------------------------------------------------------------------------------
// The MIT License
//
// Copyright (c) 2011-2016 rigaya
//
// 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.
//
// --------------------------------------------------------------------------------------------
#if (defined(_WIN32) || defined(_WIN64))
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>
#include "gpuz_info.h"
//大文字小文字を無視して、1文字検索
static inline const WCHAR *wcsichr(const WCHAR *str, int c) {
c = tolower(c);
for (; *str; str++)
if (c == tolower(*str))
return str;
return NULL;
}
//大文字小文字を無視して、文字列を検索
static inline const WCHAR *wcsistr(const WCHAR *str, const WCHAR *substr) {
size_t len = 0;
if (substr && (len = wcslen(substr)) != NULL)
for (; (str = wcsichr(str, substr[0])) != NULL; str++)
if (_wcsnicmp(str, substr, len) == NULL)
return str;
return NULL;
}
int get_gpuz_info(GPUZ_SH_MEM *data) {
HANDLE memmap = OpenFileMapping(FILE_MAP_READ, FALSE, SHMEM_NAME);
if (NULL == memmap) {
return 1;
}
GPUZ_SH_MEM *ptr = (GPUZ_SH_MEM *)MapViewOfFile(memmap, FILE_MAP_READ, 0, 0, 0);
if (ptr == nullptr) {
CloseHandle(memmap);
return 1;
}
memcpy(data, ptr, sizeof(data[0]));
UnmapViewOfFile(ptr);
CloseHandle(memmap);
return 0;
}
double gpu_core_clock(GPUZ_SH_MEM *data) {
for (int i = 0; i < MAX_RECORDS; i++) {
if ( wcsistr(data->sensors[i].name, L"Core")
&& wcsistr(data->sensors[i].name, L"Clock")) {
return data->sensors[i].value;
}
}
return 0.0;
}
double gpu_load(GPUZ_SH_MEM *data) {
for (int i = 0; i < MAX_RECORDS; i++) {
if (wcsistr(data->sensors[i].name, L"GPU Load")) {
return data->sensors[i].value;
}
}
return 0.0;
}
double video_engine_load(GPUZ_SH_MEM *data, bool *pbVideoEngineUsage) {
for (int i = 0; i < MAX_RECORDS; i++) {
if (wcsistr(data->sensors[i].name, L"Video Engine Load")) {
if (pbVideoEngineUsage) *pbVideoEngineUsage = true;
return data->sensors[i].value;
}
}
if (pbVideoEngineUsage) *pbVideoEngineUsage = false;
return 0.0;
}
#endif //#if (defined(_WIN32) || defined(_WIN64))
|
[
"rigaya34589@live.jp"
] |
rigaya34589@live.jp
|
5f849c65f5a2e03ce9c56144b714851922fef126
|
0f60164f06f2a8880cb817bde2e964b8ab50d680
|
/executor.h
|
9b3e41059462858a55dc10231132009541d56036
|
[] |
no_license
|
NuarkNoir/pcs_word
|
f764a7fadbe7f2cf3da960c9192dfc982a1e27f2
|
ceec66e97f928b670901383141b925e300d10e4b
|
refs/heads/master
| 2023-08-22T18:15:13.046443
| 2021-10-21T04:06:18
| 2021-10-21T04:06:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,559
|
h
|
#ifndef EXECUTOR_GUARD_H
#define EXECUTOR_GUARD_H
#include <map>
#include <omp.h>
#include <vector>
namespace nuworks {
typedef std::map<std::pair<int, int>, double> LUT;
struct Way {
std::vector<int> nodes;
double fitness = 0.0;
};
struct Node {
int id, x, y;
double distanceTo(const Node &node) const;
};
class Executor {
private:
Way _best_population{};
int citiesCount;
int populationCount;
double mutationChance = 0.2;
std::vector<Node> _cities;
std::vector<Way> _population;
LUT _dist_lut;
public:
Executor(int citiesCount, int populationCount) {
this->citiesCount = citiesCount;
this->populationCount = populationCount;
_cities.reserve(citiesCount);
_population.reserve(populationCount);
}
void generate_cities();
void generate_lut();
void generate_first_population();
void load_map();
void write_map();
void init();
double get_way_length(const Way &way);
void calc_fitness();
std::pair<int, int> find_two_best();
void next_generation();
std::pair<Way, Way> cross_over(const Way &p1, const Way &p2);
void mutate(Way &w);
void print_lut();
void print_stats();
int getCitiesCount();
int getPopulationCount();
};
} // namespace nuworks
#endif // EXECUTOR_GUARD_H
|
[
"me@nuark.xyz"
] |
me@nuark.xyz
|
edd8b3fc920613f253973e40955c619102a7ad34
|
b6685174b5babe2ec8f6eb0c4b9521d8728e8bc3
|
/cs4550/assignments/Scanner/Scanner/Nodes/IfStatementNode.cpp
|
3b611ed7913177bc3f28d8cc28a825493d600a9d
|
[] |
no_license
|
armstrongnate/school
|
127f52a4e5d8f506ecca7c44d4eaebd139884690
|
44f640356a9369eaf96cd98722979c953b0e39cf
|
refs/heads/master
| 2021-03-16T08:58:12.118685
| 2015-12-21T21:10:49
| 2015-12-21T21:10:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,681
|
cpp
|
//
// IfStatementNode.cpp
// Scanner
//
// Created by Nate Armstrong on 4/7/15.
// Copyright (c) 2015 Nate Armstrong. All rights reserved.
//
#include "Node.h"
IfStatementNode::IfStatementNode(ExpressionNode *en, StatementNode *sn, StatementNode *elseStatementNode)
: mExpressionNode(en), mStatementNode(sn), mElseStatementNode(elseStatementNode) {
MSG("IfStatementNode initializer");
}
IfStatementNode::~IfStatementNode() {
delete mExpressionNode;
delete mStatementNode;
delete mElseStatementNode;
}
void IfStatementNode::Interpret() {
if (mExpressionNode->Evaluate()) {
mStatementNode->Interpret();
}
else {
if (mElseStatementNode) {
mElseStatementNode->Interpret();
}
}
}
void IfStatementNode::Code(InstructionsClass &machineCode) {
if (mElseStatementNode) {
mExpressionNode->CodeEvaluate(machineCode);
unsigned char *offset1 = machineCode.SkipIfZeroStack();
unsigned char *address1 = machineCode.GetAddress();
mStatementNode->Code(machineCode);
unsigned char *offset2 = machineCode.Jump();
unsigned char *address2 = machineCode.GetAddress();
mElseStatementNode->Code(machineCode);
unsigned char *address3 = machineCode.GetAddress();
machineCode.SetOffset(offset1, (int)(address2-address1));
machineCode.SetOffset(offset2, (int)(address3-address2));
} else {
mExpressionNode->CodeEvaluate(machineCode);
unsigned char *offset1 = machineCode.SkipIfZeroStack();
unsigned char *address1 = machineCode.GetAddress();
mStatementNode->Code(machineCode);
unsigned char *address2 = machineCode.GetAddress();
machineCode.SetOffset(offset1, (int)(address2-address1));
}
}
|
[
"natearmstrong2@gmail.com"
] |
natearmstrong2@gmail.com
|
6b90578f89224165a5f96fb630c33ff5385fddd3
|
2091e1fdd6b69a1f3475824ebc90798f949fa647
|
/Pixel.h
|
286f03f378abe0f3582063215c0b163a6529bcb0
|
[] |
no_license
|
KekKekovich/PIXELEND
|
dfc7ea3845bd7d15906aec1ec08835bee2ce135d
|
69c79d0fb2742127ff8cb4dbc72347b82a7979e2
|
refs/heads/master
| 2021-05-06T02:34:32.754300
| 2017-12-17T21:18:10
| 2017-12-17T21:18:10
| 114,569,328
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 608
|
h
|
//
// Created by idalov on 24.10.2017.
//
#ifndef DGW_MOOP_1_PIXEL_H
#define DGW_MOOP_1_PIXEL_H
class Pixel{
private:
int X,Y;
int R,G,B;
public:
int getX() const {
return X;
}
int getY() const {
return Y;
}
int getR() const {
return R;
}
int getG() const {
return G;
}
int getB() const {
return B;
}
public:
Pixel(int X, int Y, int R, int G, int B);
protected:
void setX(int X);
void setY(int Y);
void setR(int R);
void setG(int G);
void setB(int B);
};
#endif //DGW_MOOP_1_PIXEL_H
|
[
"Ilyavikt-95@mail.ru"
] |
Ilyavikt-95@mail.ru
|
eb40dda9c6bb24670d9f82c2ebf1027ae7f95694
|
4e09dc649d946c5ed6bc32aafb87d49ed400eb06
|
/rig/technique.cpp
|
76a583275f2c6666d72e48971368ffda066a8a71
|
[] |
no_license
|
remibasaru/rigged-hand
|
ac8ecee6cf1c177ab0235fc11c2cf33639b70b3d
|
bf9ec88c6e9063c1c5b3e8309ce0e66fbe9703b1
|
refs/heads/master
| 2022-10-26T22:20:03.340391
| 2020-06-18T14:05:59
| 2020-06-18T14:05:59
| 273,246,438
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,473
|
cpp
|
#include <stdio.h>
#include <string.h>
#include "util.h"
#include "technique.h"
Technique::Technique()
{
m_shaderProg = 0;
}
Technique::~Technique()
{
// Delete the intermediate shader objects that have been added to the program
// The list will only contain something if shaders were compiled but the object itself
// was destroyed prior to linking.
for (ShaderObjList::iterator it = m_shaderObjList.begin() ; it != m_shaderObjList.end() ; it++)
{
glDeleteShader(*it);
}
if (m_shaderProg != 0)
{
glDeleteProgram(m_shaderProg);
m_shaderProg = 0;
}
}
bool Technique::Init()
{
m_shaderProg = glCreateProgram();
if (m_shaderProg == 0)
{
fprintf(stderr, "Error creating shader program\n");
return false;
}
return true;
}
// Use this method to add shaders to the program. When finished - call finalize()
bool Technique::AddShader(GLenum ShaderType,const char* pFilename)
{
string s;
if (!ReadFile(pFilename, s))
{
return false;
}
GLuint ShaderObj = glCreateShader(ShaderType);
if (ShaderObj == 0)
{
fprintf(stderr, "Error creating shader type %d\n", ShaderType);
return false;
}
// Save the shader object - will be deleted in the destructor
m_shaderObjList.push_back(ShaderObj);
const GLchar* p[1];
p[0] = s.c_str();
GLint Lengths[1];
Lengths[0] = (GLint)s.size();
glShaderSource(ShaderObj, 1, p, Lengths);
glCompileShader(ShaderObj);
GLint success;
glGetShaderiv(ShaderObj, GL_COMPILE_STATUS, &success);
if (!success)
{
GLchar InfoLog[1024];
glGetShaderInfoLog(ShaderObj, 1024, NULL, InfoLog);
fprintf(stderr, "Error compiling shader type %d: '%s'\n", ShaderType, InfoLog);
return false;
}
glAttachShader(m_shaderProg, ShaderObj);
return true;
}
// After all the shaders have been added to the program call this function
// to link and validate the program.
bool Technique::Finalize()
{
GLint Success = 0;
GLchar ErrorLog[1024] = { 0 };
glLinkProgram(m_shaderProg);
glGetProgramiv(m_shaderProg, GL_LINK_STATUS, &Success);
if (Success == 0)
{
glGetProgramInfoLog(m_shaderProg, sizeof(ErrorLog), NULL, ErrorLog);
fprintf(stderr, "Error linking shader program: '%s'\n", ErrorLog);
return false;
}
glValidateProgram(m_shaderProg);
glGetProgramiv(m_shaderProg, GL_VALIDATE_STATUS, &Success);
if (!Success)
{
glGetProgramInfoLog(m_shaderProg, sizeof(ErrorLog), NULL, ErrorLog);
fprintf(stderr, "Invalid shader program: '%s'\n", ErrorLog);
return false;
}
// Delete the intermediate shader objects that have been added to the program
for (ShaderObjList::iterator it = m_shaderObjList.begin() ; it != m_shaderObjList.end() ; it++)
{
glDeleteShader(*it);
}
m_shaderObjList.clear();
return true;
}
void Technique::Enable()
{
glUseProgram(m_shaderProg);
}
GLint Technique::GetUniformLocation(const char* pUniformName)
{
GLint Location = glGetUniformLocation(m_shaderProg, pUniformName);
if (Location == 0xFFFFFFFF)
{
fprintf(stderr, "Warning! Unable to get the location of uniform '%s'\n", pUniformName);
}
return Location;
}
|
[
"remi.basaru@aol.com"
] |
remi.basaru@aol.com
|
899627f19baf6b20682b57b3df7b422c7038e5cc
|
f2d028a01206b38e4fbf61e3a6f4c211ca169076
|
/BGV-Adder/Algorithms/CKKS Complex Matrix Product/ckks_complex_matrix_product.cpp
|
20075ca93cb8b1a603f3b9fad96c0ccbc8d4e5d8
|
[
"MIT"
] |
permissive
|
bbqgonewrong/fhe-toolkit-macos-algorithms
|
8e84970389d4f93bfe7b27ef27f05629ce3f77bf
|
6b65ac00c2a3cb64c487eadfc504eb17108ffd80
|
refs/heads/master
| 2023-03-20T13:22:06.207812
| 2020-10-29T21:53:11
| 2020-10-29T21:53:11
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,522
|
cpp
|
//
// ckks_complex_matrix_product.cpp
// BGV-Adder
//
// Created by Hindrik Stegenga on 29/10/2020.
// Copyright © 2020 RUG. All rights reserved.
//
#include "ckks_complex_matrix_product.hpp"
#include <helib/norms.h>
using helib::Context;
using helib::Ctxt;
using helib::SecKey;
using helib::PubKey;
using std::vector;
using std::complex;
array<array<complex<double>, MATRIX_SIZE>, MATRIX_SIZE> compute_complex_matrix_product(array<array<complex<double>, MATRIX_SIZE>, MATRIX_SIZE> lhs, array<array<complex<double>, MATRIX_SIZE>, MATRIX_SIZE> rhs) {
long m = 128; //Zm*
long r = 20; //bit precision
long L = 150; //number of bits for the mod chain
// Setting up the context. p needs to be -1 for CKKS.
auto context = Context(m, -1, r);
// We need to change the scale of the internally used distribution.
context.scale = 4;
// Build modulus chain
helib::buildModChain(context, L, 2);
//Initialize secret key
auto secretKey = SecKey(context);
// Generate secret key
secretKey.GenSecKey();
// We need to generate some internal matrices for the ckks scheme.
helib::addSome1DMatrices(secretKey);
// Obtain the secret key
auto pubKey = PubKey(secretKey);
// Obtain encrypted array, Cx variant is specifically for approximate numbers.
auto encryptedArray = context.ea->getCx();
// Encrypt our float values as complex number into our ciphertext
vector<vector<Ctxt>> lhs_ctxts, rhs_ctxts, result_ctxt;
Ctxt zero(pubKey);
vector<complex<double>> zerov = { complex<double>() };
encryptedArray.encrypt(zero, pubKey, zerov);
//Encrypt the values into vectors of ctxt's.
//Left hand side
for (auto& row : lhs) {
vector<Ctxt> new_row;
for (auto& elem : row) {
auto ctxt = Ctxt(pubKey);
vector<complex<double>> v = {elem};
encryptedArray.encrypt(ctxt, pubKey, v);
new_row.emplace_back(ctxt);
}
lhs_ctxts.emplace_back(new_row);
}
//Right hand side
for (auto& row : rhs) {
vector<Ctxt> new_row;
for (auto& elem : row) {
auto ctxt = Ctxt(pubKey);
vector<complex<double>> v = {elem};
encryptedArray.encrypt(ctxt, pubKey, v);
new_row.emplace_back(ctxt);
}
rhs_ctxts.emplace_back(new_row);
}
// Intialize resulting ctxts with empty
for (const auto& row : lhs) {
vector<Ctxt> new_row;
for (const auto& _ : row) {
new_row.emplace_back(zero);
}
result_ctxt.emplace_back(new_row);
}
// Computing the dot product
for (size_t x = 0; x < MATRIX_SIZE; x++) {
for (size_t y = 0; y < MATRIX_SIZE; y++) {
result_ctxt[x][y] = zero;
for (size_t z = 0; z < MATRIX_SIZE; z++) {
auto temp = Ctxt(lhs_ctxts[x][z]);
temp *= rhs_ctxts[z][y];
result_ctxt[x][y] += temp;
}
}
}
// Decryption
array<array<complex<double>, MATRIX_SIZE>, MATRIX_SIZE> return_value = {};
for (size_t i = 0; i < result_ctxt.size(); ++i) {
auto& row = result_ctxt[i];
for (size_t j = 0; j < row.size(); ++j) {
vector<complex<double>> result;
encryptedArray.decrypt(row[j], secretKey, result);
return_value[i][j] = result[0];
}
}
return return_value;
}
|
[
"hindrik1997@hotmail.com"
] |
hindrik1997@hotmail.com
|
8cae734683f5d3c3d72521b47c15fa026302f46f
|
96961c8f7e96ce7a8a2d37f245f50d44c4941cb1
|
/C++/matXvect.cpp
|
6ad60e4aacc2dfcbd65ec2c147c4a52217df5680
|
[] |
no_license
|
EALH/Prog_Paralela
|
a82beff37962ddbb1357a280d0aba97bd07c03c5
|
3eb6ac439524a7e4d91e8206396932e8d13ec9a2
|
refs/heads/master
| 2022-09-14T02:29:49.264709
| 2020-06-03T00:12:00
| 2020-06-03T00:12:00
| 268,922,250
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,512
|
cpp
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <pthread.h>
#include <sys/time.h>
int NUM_OF_THREADS, M, N;
float* A;
float* x;
float* y;
float* y_serial;
int _check_results(float x[], float y[])
{
int i;
for(int i = 0; i < M; i++)
if(abs(x[i] - y[i]) > 0.01) return 1;
return 0;
}
long _calc_time_secs(timeval start, timeval end)
{
long seconds, useconds;
seconds = end.tv_sec - start.tv_sec;
useconds = end.tv_usec - start.tv_usec;
return ((seconds) * 1000 + useconds/1000.0) + 0.5;
}
void Fill_Matrix(float A[], int rows, int cols);
void Fill_Vector(float x[], int rows);
void Print_Matrix(float A[], int rows, int cols);
void Print_Vector(float x[], int rows);
void *_math_vec_prod(void* rank);
void _math_vec_prod(void);
int main(int argc, char* argv[]){
timeval start;
timeval end;
long final_par, final_serial;
if(argc != 4)
{
fputs("Debe colocar M, N y el número de hilos\n", stdout);
return EXIT_FAILURE;
}
else
{
M = atoi(argv[1]);
N = atoi(argv[2]);
NUM_OF_THREADS = atoi(argv[3]);
}
srand(time(NULL));
int i, _error;
pthread_t* threads = (pthread_t *)malloc(NUM_OF_THREADS * sizeof(pthread_t));
A = (float *) malloc(M * N * sizeof(float));
x = (float *) malloc(N * sizeof(float));
y = (float *) malloc(M * sizeof(float));
y_serial = (float *) malloc(M * sizeof(float));
Fill_Matrix(A, M, N);
Fill_Vector(x, N);
gettimeofday(&start, 0);
for(i = 0; i < NUM_OF_THREADS; i++)
{
_error = pthread_create(&threads[i], NULL,
_math_vec_prod, &i);
if (_error){
fprintf(stderr, "error: pthread_create, rc: %d\n", _error);
return EXIT_FAILURE;
}
}
for (i = 0; i < NUM_OF_THREADS; i++)
pthread_join(threads[i], NULL);
gettimeofday(&end, 0);
final_par = _calc_time_secs(start, end);
gettimeofday(&start, 0);
_math_vec_prod();
gettimeofday(&end, 0);
final_serial = _calc_time_secs(start, end);
if(!_check_results(y, y_serial))
fputs("Prueba exitosa\n", stdout);
else
fputs("Prueba fallida\n", stdout);
fprintf(stdout, "TAMAÑO: %d x %d E %d THREADS\n", M, N, NUM_OF_THREADS);
fprintf(stdout, "TIEMPO CONC.:%d mseg\n", (int)final_par);
fprintf(stdout, "TIEMPO SERIAL:%d mseg\n", (int)final_serial);
if(M < 6 && N < 6)
{
puts("RES PARALELO:\n");
Print_Vector(y, M);
puts("RES SERIAL:\n");
Print_Vector(y_serial, M);
}
free(A);
free(x);
free(y);
free(y_serial);
free(threads);
}
void Fill_Matrix(float A[], int rows, int cols)
{
int i, j;
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
A[i * cols + j] = rand() % 1;
}
void Fill_Vector(float x[], int rows)
{
int i;
for (i = 0; i < rows; i++)
x[i] = rand() % 1;
}
void Print_Matrix(float A[], int rows, int cols) {
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++)
printf("%.2f ", A[i*cols + j]);
printf("\n");
}
}
void Print_Vector(float x[], int rows) {
int i;
for (i = 0; i < rows; i++)
printf("%.5f ", x[i]*1000);
printf("\n");
}
void *_math_vec_prod(void* rank) {
int whoami = *(int *) rank;
int from = whoami * M / NUM_OF_THREADS;
int to = from + (M / NUM_OF_THREADS) - 1;
int i, j;
for (i = from; i <= to; i++) {
y[i] = 0.0f;
for (j = 0; j < M; j++)
y[i] += A[i*M+j]*x[j];
}
return NULL;
}
void _math_vec_prod(void)
{
int i,j;
for(i = 0; i < M; i++)
{
y_serial[i] = 0.0f;
for(j = 0; j < N; j++)
y_serial[i] += A[i * N + j] * x[j];
}
}
|
[
"eduardoalh02@gmail.com"
] |
eduardoalh02@gmail.com
|
c2a42a3b3454a0ce997e8519681851bacba230bc
|
4e006837ed7b91e877ec0fc9bd1c9b6e43131901
|
/oxygine-framework/oxygine/src/oxygine/UpdateState.h
|
8b5a5998bc76ff4fdf41c3a6a62f3fc440493151
|
[
"MIT"
] |
permissive
|
Poscowekh/Project
|
52be9104b0ab16c9a504b4295e0a23cadd72ac7a
|
3385c24646c951e37097b8ec1cfc29e9c5f44e05
|
refs/heads/master
| 2022-09-18T13:33:37.504605
| 2020-06-02T19:03:08
| 2020-06-02T19:03:08
| 259,675,760
| 0
| 0
| null | 2020-05-01T08:58:11
| 2020-04-28T15:24:50
|
C
|
UTF-8
|
C++
| false
| false
| 379
|
h
|
#pragma once
#include "oxygine-include.h"
namespace oxygine
{
class UpdateState
{
public:
UpdateState(): time(0), dt(0), iteration(0) {}
/**local time*/
timeMS time;
/**delta time since last update*/
timeMS dt;
/**current iteration, used with fixed Clock update */
int iteration;
};
}
|
[
"ziuwari@ya.ru"
] |
ziuwari@ya.ru
|
f25edfb3f50fed1fc24bb022e5be4c0a3e2fa6eb
|
2f557f60fc609c03fbb42badf2c4f41ef2e60227
|
/CommonTools/Utils/test/testSelectIterator.cc
|
4a42cc4641825cb65d9c47380281613f011abda2
|
[
"Apache-2.0"
] |
permissive
|
CMS-TMTT/cmssw
|
91d70fc40a7110832a2ceb2dc08c15b5a299bd3b
|
80cb3a25c0d63594fe6455b837f7c3cbe3cf42d7
|
refs/heads/TMTT_1060
| 2020-03-24T07:49:39.440996
| 2020-03-04T17:21:36
| 2020-03-04T17:21:36
| 142,576,342
| 3
| 5
|
Apache-2.0
| 2019-12-05T21:16:34
| 2018-07-27T12:48:13
|
C++
|
UTF-8
|
C++
| false
| false
| 1,452
|
cc
|
#include <cppunit/extensions/HelperMacros.h>
#include "CommonTools/Utils/interface/PtMinSelector.h"
#include "CommonTools/Utils/interface/Selection.h"
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
class testSelectIterator : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(testSelectIterator);
CPPUNIT_TEST(checkAll);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {}
void tearDown() {}
void checkAll();
};
CPPUNIT_TEST_SUITE_REGISTRATION( testSelectIterator );
namespace test {
struct A {
explicit A( double x ) : x_( x ) { }
double pt() const { return x_; }
private:
double x_;
};
}
void testSelectIterator::checkAll() {
using namespace test;
using namespace std;
vector<A> v;
for( double x = 0; x < 10.1; ++ x )
v.push_back(A(x));
CPPUNIT_ASSERT( v.size() == 11 );
PtMinSelector select( 3.5 );
Selection<vector<A>, PtMinSelector> sel( v, select );
CPPUNIT_ASSERT( sel.size() == 7 );
for( size_t i = 0; i < sel.size(); ++ i ) {
CPPUNIT_ASSERT( select( sel[i]) );
}
for( Selection<vector<A>, PtMinSelector>::const_iterator i = sel.begin();
i != sel.end(); ++ i ) {
CPPUNIT_ASSERT( select( * i ) );
}
vector<A> selected;
copy( sel.begin(), sel.end(), back_inserter( selected ) );
CPPUNIT_ASSERT( sel.size() == selected.size() );
for( size_t i = 0; i < selected.size(); ++ i ) {
CPPUNIT_ASSERT( select( selected[i]) );
}
}
|
[
"giulio.eulisse@gmail.com"
] |
giulio.eulisse@gmail.com
|
621534295a21e2b5f05cee43ce3d77d61686eb8e
|
63a1ac98260e0aa78034e70b13ca4ca8c1596c16
|
/Tree/Binary_Search_Tree_BTS.cpp
|
44016b459dd904ea626e572926e03166317c2437
|
[] |
no_license
|
Hi-Pete/leetcode
|
d49f2fa935b0ebb62d4666036e7dd24c6e9307f1
|
f103c5179b5485471a3958d01253ba2b5a70b594
|
refs/heads/main
| 2023-07-31T23:43:35.414865
| 2021-09-27T16:51:53
| 2021-09-27T16:51:53
| 349,070,195
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,627
|
cpp
|
// 二叉查找树(Binary Search Tree, BST) 是一种特殊的二叉树:
// 对于每个父节点,其左子节点的值小于等于父结点的值,其右子节点的值大于等于父结点的值
// 因此对于一个二叉查找树,我们可以在 O(nlogn) 的时间内查找一个值是否存在:
// 从根节点开始: 若当前节点的值大于查找值则向左下走,
// 若当前节点的值小于查找值则向右下走
// 同时因为二叉查找树是有序的,对其中序遍历的结果即为排好序的数组
template <class T>
class BST{
struct Node {
T data;
Node* left;
Node* right;
};
Node* root;
Node* makeEmpty(Node* t) {
if (t == nullptr)
return nullptr;
makeEmpty(t->left);
makeEmpty(t->right);
// 后需遍历删除节点
delete t;
return nullptr;
}
Node* insert(Node* t, T x) {
if (t == nullptr) {
t = new Node;
t->data = x;
t->left = t->right = nullptr;
}
else if (x < t->data)
t->left = insert(t->left, x);
else if (x > t->data)
t->right = insert(t->right, x);
return t;
}
Node* find(Node* t, T x) {
if (t == nullptr)
return nullptr;
if (x < t->data)
return find(t->left, x);
if (x > t->data)
return find(t->right, x);
return t;
}
Node* findMin(Node* t) {
if (t == nullptr || t->left == nullptr)
return t;
return findMin(t->left);
}
Node* findMax(Node* t) {
if (t == nullptr || t->right == nullptr)
return t;
return findMax(t->right);
}
Node* remove(Node* t, T x) {
Node* temp;
if (t == nullptr)
return nullptr;
else if (x < t->data)
t->left = remove(t->left, x);
else if (x > t->data)
t->right = remove(t->right, x);
else if (t->left && t->right) {
temp = findMin(t->right);
t->data = temp->data;
t->right = remove(t->right, t->data);
}
else {
temp = t;
if (t->left == nullptr)
t = t->right;
else if (t->right == nullptr)
t = t->left;
delete temp;
}
return t;
}
public:
BST(): root(nullptr) {}
~BST() {
root = makeEmpty(root);
}
void insert(T x) {
insert(root, x);
}
void remove(T x) {
remove(root, x);
}
};
|
[
"525527051@qq.com"
] |
525527051@qq.com
|
0cc86a56805a3ed9d435a3b7f5f2467efcbdd7bf
|
2f24e6293051ef412481351e9788a05dc5438260
|
/cpp/test/method_add.cpp
|
b2f3991633a7cf09340a797640c448c5c68810d5
|
[] |
no_license
|
erich0929/programming
|
672392e977d5687ecd8db3fd7eeaa6e65195fc15
|
3f2c6641b1538aa6b12bb665636bde58a226fc2a
|
refs/heads/master
| 2021-01-22T11:58:20.451378
| 2014-08-23T08:13:36
| 2014-08-23T08:13:36
| 22,387,139
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 321
|
cpp
|
#include <iostream>
#include <stdio.h>
using namespace std;
class CTest {
public :
int i;
public :
virtual void do_something () { };
};
int main(void)
{
CTest temp1, temp2;
printf ("temp1 method address : %p\n", &temp1.do_something);
printf ("temp2 method address : %p\n", &temp2.do_something);
return 0;
}
|
[
"erich0929@erich0929-A505-UE30K.(none)"
] |
erich0929@erich0929-A505-UE30K.(none)
|
8c702619a2d741dcbbfffc8b28b7b60a769ab626
|
63926f6bc3dd5b3573d4e22c7d5ac0bc1a5e253c
|
/Plugins/Voxel/Source/VoxelEditor/Private/Details/VoxelLandscapeImporterDetails.h
|
e5f1c73dffb2c42f1fa73e4baab4d450cf2ee89a
|
[] |
no_license
|
chaiyuntian/MPlugins
|
8c024cf3cb815614aa4c5eaf7d6d1e0f5af9eb6b
|
9050f15e0ac92657dbf63b403d873e87485892d2
|
refs/heads/main
| 2023-01-10T23:07:38.428583
| 2020-11-10T04:02:52
| 2020-11-10T04:02:52
| 309,244,097
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 535
|
h
|
// Copyright 2020 Phyronnaz
#pragma once
#include "CoreMinimal.h"
#include "Input/Reply.h"
#include "IDetailCustomization.h"
// See sky light details in the engine code
class AVoxelLandscapeImporter;
class FVoxelLandscapeImporterDetails : public IDetailCustomization
{
public:
/** IDetailCustomization interface */
virtual void CustomizeDetails(IDetailLayoutBuilder& DetailLayout) override;
FReply OnCreateFromLandscape();
private:
/** The selected landscape modifier */
TWeakObjectPtr<AVoxelLandscapeImporter> Importer;
};
|
[
"tianyunchai@126.com"
] |
tianyunchai@126.com
|
44039d691d603a4d0f1f2deac9f328d86bbcb1da
|
1f41b828fb652795482cdeaac1a877e2f19c252a
|
/maya_plugins/inLocus/3dGroup/sgRigAdditionalNodes/sgRigAdditionalNodes/CollisionJointNode.cpp
|
79c62fa26e63ecfbcb92086bb4f60727cc5b46d6
|
[] |
no_license
|
jonntd/mayadev-1
|
e315efe582ea433dcf18d7f1e900920f5590b293
|
f76aeecb592df766d05a4e10fa2c2496f0310ca4
|
refs/heads/master
| 2021-05-02T07:16:17.941007
| 2018-02-05T03:55:12
| 2018-02-05T03:55:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,471
|
cpp
|
//
// Copyright (C) locus
//
// File: CollisionJointNode.cpp
//
// Dependency Graph Node: CollisionJoint
//
// Author: Maya Plug-in Wizard 2.0
//
#include "CollisionJointNode.h"
#include <maya/MPlug.h>
#include <maya/MDataBlock.h>
#include <maya/MDataHandle.h>
#include <maya/MGlobal.h>
MTypeId CollisionJoint::id( 0x00001 );
// Example attributes
//
MObject CollisionJoint::aInputMatrix;
MObject CollisionJoint::aMesh;
MObject CollisionJoint::aMeshMatrix;
MObject CollisionJoint::aAimAxis;
MObject CollisionJoint::aUpAxis;
MObject CollisionJoint::aAngleLockRate;
MObject CollisionJoint::aOutputMatrix;
CollisionJoint::CollisionJoint()
{
m_dirtyMatrix = true;
m_dirtyMesh = true;
m_dirtyMeshMatrix = true;
m_dirtyAxis = true;
m_dirtyAngleLockRate = true;
}
CollisionJoint::~CollisionJoint() {}
MStatus CollisionJoint::compute( const MPlug& plug, MDataBlock& data )
{
MStatus returnStatus;
clearMatrix( data );
clearMeshMatrix( data );
clearMesh( data );
clearAxis( data );
clearLockRate( data );
m_dirtyMatrix = false;
m_dirtyMesh = false;
m_dirtyMeshMatrix = false;
m_dirtyAxis = false;
m_dirtyAngleLockRate = false;
return MS::kSuccess;
}
void* CollisionJoint::creator()
{
return new CollisionJoint();
}
MStatus CollisionJoint::initialize()
{
MStatus status;
MFnNumericAttribute nAttr;
MFnMatrixAttribute mAttr;
MFnTypedAttribute tAttr;
MFnEnumAttribute eAttr;
aInputMatrix = mAttr.create( "inputMatrix", "inputMatrix" );
mAttr.setArray( true );
CHECK_MSTATUS_AND_RETURN_IT( addAttribute( aInputMatrix ) );
aMesh = tAttr.create( "mesh", "mesh", MFnData::kMesh );
CHECK_MSTATUS_AND_RETURN_IT( addAttribute( aMesh ) );
aMeshMatrix = mAttr.create( "meshMatrix", "meshMatrix" );
CHECK_MSTATUS_AND_RETURN_IT( addAttribute( aMeshMatrix ) );
aAimAxis = eAttr.create( "aimAxis", "aimAxis" );
eAttr.addField( "X", 0 ), eAttr.addField( "Y", 1 ), eAttr.addField( "Z", 2 );
eAttr.addField( "-X", 3 ), eAttr.addField( "-Y", 4 ), eAttr.addField( "-Z", 5 );
CHECK_MSTATUS_AND_RETURN_IT( addAttribute( aAimAxis ) );
aUpAxis = eAttr.create( "upAxis", "upAxis" );
eAttr.addField( "X", 0 ), eAttr.addField( "Y", 1 ), eAttr.addField( "Z", 2 );
eAttr.addField( "-X", 3 ), eAttr.addField( "-Y", 4 ), eAttr.addField( "-Z", 5 );
CHECK_MSTATUS_AND_RETURN_IT( addAttribute( aUpAxis ) );
aAngleLockRate = nAttr.create( "angleLockRate", "angleLockRate", MFnNumericData::kFloat, 0.0 );
CHECK_MSTATUS_AND_RETURN_IT( addAttribute( aAngleLockRate ) );
aOutputMatrix = mAttr.create( "outputMatrix", "outputMatrix" );
mAttr.setArray( true );
CHECK_MSTATUS_AND_RETURN_IT ( addAttribute( aOutputMatrix ) );
CHECK_MSTATUS_AND_RETURN_IT( attributeAffects( aInputMatrix, aOutputMatrix ) );
CHECK_MSTATUS_AND_RETURN_IT( attributeAffects( aMesh, aOutputMatrix ) );
CHECK_MSTATUS_AND_RETURN_IT( attributeAffects( aAimAxis, aOutputMatrix ) );
CHECK_MSTATUS_AND_RETURN_IT( attributeAffects( aUpAxis, aOutputMatrix ) );
return MS::kSuccess;
}
MStatus CollisionJoint::setDependentsDirty( const MPlug& plug, MPlugArray& plugArr )
{
MStatus status;
if( plug == aInputMatrix )
{
m_dirtyMatrix = true;
}
else if( plug == aMeshMatrix )
{
m_dirtyMeshMatrix = true;
}
else if( plug == aMesh )
{
m_dirtyMesh = true;
}
else if( plug == aAimAxis || plug == aUpAxis )
{
m_dirtyAxis = true;
}
else if( plug == aAngleLockRate )
{
m_dirtyAngleLockRate = true;
}
return status;
}
|
[
"kimsung9k@naver.com"
] |
kimsung9k@naver.com
|
a8b39438c10801b1faf4dc9987b98a58b33bf10d
|
9d188a41ec9cf5526f79bfaab0338a629234bb13
|
/src/Gmail_AddressBook.cpp
|
288abebd42f165da9632e73602b84cf1f8b6963f
|
[] |
no_license
|
manjunathcs405/addressbook
|
304dac72a2cf102d39790abff1209f532baa4e0e
|
f4656f6b29af13b49d67034ebefd21a780ee6db1
|
refs/heads/master
| 2020-05-29T19:26:47.383065
| 2014-11-05T06:56:00
| 2014-11-05T06:56:00
| 26,103,850
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 385
|
cpp
|
#include<iostream>
#include "Gmail_AddressBook.h"
Gmail_AddressBook::Gmail_AddressBook()
{
}
Gmail_AddressBook::~Gmail_AddressBook()
{
}
bool Gmail_AddressBook::addContact()
{
return true;
}
bool Gmail_AddressBook::removeContact()
{
return true;
}
bool Gmail_AddressBook::modifyContact()
{
return true;
}
bool Gmail_AddressBook::searchContact()
{
return true;
}
|
[
"manjunatha.s@lge.com"
] |
manjunatha.s@lge.com
|
f7380f1df4ead82a5c9428f14faa560330625b47
|
e8ecc5a25be493d2bed7df4305fa4b9933342d7e
|
/src/_resources/menu_logo.png.cpp
|
0515a6b49a6c34ebae817435bf089b374409aa6f
|
[
"MIT"
] |
permissive
|
friedcroc/tizen_spacerace
|
a3b01ff8797d6664984d2c7ba99706349d508451
|
08550b8ce4432f502da243522de375b52fdf5925
|
refs/heads/master
| 2020-06-05T02:30:25.322206
| 2018-04-28T21:45:54
| 2018-04-28T21:56:51
| 18,323,542
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 35,269
|
cpp
|
#include <cstddef>
extern const size_t file_menu_logo_png_size = 6985;
extern const unsigned char file_menu_logo_png[] = {
0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A,0x00,0x00,0x00,0x0D,0x49,0x48,0x44,0x52,0x00,0x00,0x02,0x31,0x00,0x00,0x00,0x9D,0x08,0x06,0x00,0x00,0x00,0x45,0x2E,0x29,
0x48,0x00,0x00,0x00,0x09,0x70,0x48,0x59,0x73,0x00,0x00,0x0B,0x13,0x00,0x00,0x0B,0x13,0x01,0x00,0x9A,0x9C,0x18,0x00,0x00,0x0A,0x4F,0x69,0x43,0x43,0x50,0x50,0x68,
0x6F,0x74,0x6F,0x73,0x68,0x6F,0x70,0x20,0x49,0x43,0x43,0x20,0x70,0x72,0x6F,0x66,0x69,0x6C,0x65,0x00,0x00,0x78,0xDA,0x9D,0x53,0x67,0x54,0x53,0xE9,0x16,0x3D,0xF7,
0xDE,0xF4,0x42,0x4B,0x88,0x80,0x94,0x4B,0x6F,0x52,0x15,0x08,0x20,0x52,0x42,0x8B,0x80,0x14,0x91,0x26,0x2A,0x21,0x09,0x10,0x4A,0x88,0x21,0xA1,0xD9,0x15,0x51,0xC1,
0x11,0x45,0x45,0x04,0x1B,0xC8,0xA0,0x88,0x03,0x8E,0x8E,0x80,0x8C,0x15,0x51,0x2C,0x0C,0x8A,0x0A,0xD8,0x07,0xE4,0x21,0xA2,0x8E,0x83,0xA3,0x88,0x8A,0xCA,0xFB,0xE1,
0x7B,0xA3,0x6B,0xD6,0xBC,0xF7,0xE6,0xCD,0xFE,0xB5,0xD7,0x3E,0xE7,0xAC,0xF3,0x9D,0xB3,0xCF,0x07,0xC0,0x08,0x0C,0x96,0x48,0x33,0x51,0x35,0x80,0x0C,0xA9,0x42,0x1E,
0x11,0xE0,0x83,0xC7,0xC4,0xC6,0xE1,0xE4,0x2E,0x40,0x81,0x0A,0x24,0x70,0x00,0x10,0x08,0xB3,0x64,0x21,0x73,0xFD,0x23,0x01,0x00,0xF8,0x7E,0x3C,0x3C,0x2B,0x22,0xC0,
0x07,0xBE,0x00,0x01,0x78,0xD3,0x0B,0x08,0x00,0xC0,0x4D,0x9B,0xC0,0x30,0x1C,0x87,0xFF,0x0F,0xEA,0x42,0x99,0x5C,0x01,0x80,0x84,0x01,0xC0,0x74,0x91,0x38,0x4B,0x08,
0x80,0x14,0x00,0x40,0x7A,0x8E,0x42,0xA6,0x00,0x40,0x46,0x01,0x80,0x9D,0x98,0x26,0x53,0x00,0xA0,0x04,0x00,0x60,0xCB,0x63,0x62,0xE3,0x00,0x50,0x2D,0x00,0x60,0x27,
0x7F,0xE6,0xD3,0x00,0x80,0x9D,0xF8,0x99,0x7B,0x01,0x00,0x5B,0x94,0x21,0x15,0x01,0xA0,0x91,0x00,0x20,0x13,0x65,0x88,0x44,0x00,0x68,0x3B,0x00,0xAC,0xCF,0x56,0x8A,
0x45,0x00,0x58,0x30,0x00,0x14,0x66,0x4B,0xC4,0x39,0x00,0xD8,0x2D,0x00,0x30,0x49,0x57,0x66,0x48,0x00,0xB0,0xB7,0x00,0xC0,0xCE,0x10,0x0B,0xB2,0x00,0x08,0x0C,0x00,
0x30,0x51,0x88,0x85,0x29,0x00,0x04,0x7B,0x00,0x60,0xC8,0x23,0x23,0x78,0x00,0x84,0x99,0x00,0x14,0x46,0xF2,0x57,0x3C,0xF1,0x2B,0xAE,0x10,0xE7,0x2A,0x00,0x00,0x78,
0x99,0xB2,0x3C,0xB9,0x24,0x39,0x45,0x81,0x5B,0x08,0x2D,0x71,0x07,0x57,0x57,0x2E,0x1E,0x28,0xCE,0x49,0x17,0x2B,0x14,0x36,0x61,0x02,0x61,0x9A,0x40,0x2E,0xC2,0x79,
0x99,0x19,0x32,0x81,0x34,0x0F,0xE0,0xF3,0xCC,0x00,0x00,0xA0,0x91,0x15,0x11,0xE0,0x83,0xF3,0xFD,0x78,0xCE,0x0E,0xAE,0xCE,0xCE,0x36,0x8E,0xB6,0x0E,0x5F,0x2D,0xEA,
0xBF,0x06,0xFF,0x22,0x62,0x62,0xE3,0xFE,0xE5,0xCF,0xAB,0x70,0x40,0x00,0x00,0xE1,0x74,0x7E,0xD1,0xFE,0x2C,0x2F,0xB3,0x1A,0x80,0x3B,0x06,0x80,0x6D,0xFE,0xA2,0x25,
0xEE,0x04,0x68,0x5E,0x0B,0xA0,0x75,0xF7,0x8B,0x66,0xB2,0x0F,0x40,0xB5,0x00,0xA0,0xE9,0xDA,0x57,0xF3,0x70,0xF8,0x7E,0x3C,0x3C,0x45,0xA1,0x90,0xB9,0xD9,0xD9,0xE5,
0xE4,0xE4,0xD8,0x4A,0xC4,0x42,0x5B,0x61,0xCA,0x57,0x7D,0xFE,0x67,0xC2,0x5F,0xC0,0x57,0xFD,0x6C,0xF9,0x7E,0x3C,0xFC,0xF7,0xF5,0xE0,0xBE,0xE2,0x24,0x81,0x32,0x5D,
0x81,0x47,0x04,0xF8,0xE0,0xC2,0xCC,0xF4,0x4C,0xA5,0x1C,0xCF,0x92,0x09,0x84,0x62,0xDC,0xE6,0x8F,0x47,0xFC,0xB7,0x0B,0xFF,0xFC,0x1D,0xD3,0x22,0xC4,0x49,0x62,0xB9,
0x58,0x2A,0x14,0xE3,0x51,0x12,0x71,0x8E,0x44,0x9A,0x8C,0xF3,0x32,0xA5,0x22,0x89,0x42,0x92,0x29,0xC5,0x25,0xD2,0xFF,0x64,0xE2,0xDF,0x2C,0xFB,0x03,0x3E,0xDF,0x35,
0x00,0xB0,0x6A,0x3E,0x01,0x7B,0x91,0x2D,0xA8,0x5D,0x63,0x03,0xF6,0x4B,0x27,0x10,0x58,0x74,0xC0,0xE2,0xF7,0x00,0x00,0xF2,0xBB,0x6F,0xC1,0xD4,0x28,0x08,0x03,0x80,
0x68,0x83,0xE1,0xCF,0x77,0xFF,0xEF,0x3F,0xFD,0x47,0xA0,0x25,0x00,0x80,0x66,0x49,0x92,0x71,0x00,0x00,0x5E,0x44,0x24,0x2E,0x54,0xCA,0xB3,0x3F,0xC7,0x08,0x00,0x00,
0x44,0xA0,0x81,0x2A,0xB0,0x41,0x1B,0xF4,0xC1,0x18,0x2C,0xC0,0x06,0x1C,0xC1,0x05,0xDC,0xC1,0x0B,0xFC,0x60,0x36,0x84,0x42,0x24,0xC4,0xC2,0x42,0x10,0x42,0x0A,0x64,
0x80,0x1C,0x72,0x60,0x29,0xAC,0x82,0x42,0x28,0x86,0xCD,0xB0,0x1D,0x2A,0x60,0x2F,0xD4,0x40,0x1D,0x34,0xC0,0x51,0x68,0x86,0x93,0x70,0x0E,0x2E,0xC2,0x55,0xB8,0x0E,
0x3D,0x70,0x0F,0xFA,0x61,0x08,0x9E,0xC1,0x28,0xBC,0x81,0x09,0x04,0x41,0xC8,0x08,0x13,0x61,0x21,0xDA,0x88,0x01,0x62,0x8A,0x58,0x23,0x8E,0x08,0x17,0x99,0x85,0xF8,
0x21,0xC1,0x48,0x04,0x12,0x8B,0x24,0x20,0xC9,0x88,0x14,0x51,0x22,0x4B,0x91,0x35,0x48,0x31,0x52,0x8A,0x54,0x20,0x55,0x48,0x1D,0xF2,0x3D,0x72,0x02,0x39,0x87,0x5C,
0x46,0xBA,0x91,0x3B,0xC8,0x00,0x32,0x82,0xFC,0x86,0xBC,0x47,0x31,0x94,0x81,0xB2,0x51,0x3D,0xD4,0x0C,0xB5,0x43,0xB9,0xA8,0x37,0x1A,0x84,0x46,0xA2,0x0B,0xD0,0x64,
0x74,0x31,0x9A,0x8F,0x16,0xA0,0x9B,0xD0,0x72,0xB4,0x1A,0x3D,0x8C,0x36,0xA1,0xE7,0xD0,0xAB,0x68,0x0F,0xDA,0x8F,0x3E,0x43,0xC7,0x30,0xC0,0xE8,0x18,0x07,0x33,0xC4,
0x6C,0x30,0x2E,0xC6,0xC3,0x42,0xB1,0x38,0x2C,0x09,0x93,0x63,0xCB,0xB1,0x22,0xAC,0x0C,0xAB,0xC6,0x1A,0xB0,0x56,0xAC,0x03,0xBB,0x89,0xF5,0x63,0xCF,0xB1,0x77,0x04,
0x12,0x81,0x45,0xC0,0x09,0x36,0x04,0x77,0x42,0x20,0x61,0x1E,0x41,0x48,0x58,0x4C,0x58,0x4E,0xD8,0x48,0xA8,0x20,0x1C,0x24,0x34,0x11,0xDA,0x09,0x37,0x09,0x03,0x84,
0x51,0xC2,0x27,0x22,0x93,0xA8,0x4B,0xB4,0x26,0xBA,0x11,0xF9,0xC4,0x18,0x62,0x32,0x31,0x87,0x58,0x48,0x2C,0x23,0xD6,0x12,0x8F,0x13,0x2F,0x10,0x7B,0x88,0x43,0xC4,
0x37,0x24,0x12,0x89,0x43,0x32,0x27,0xB9,0x90,0x02,0x49,0xB1,0xA4,0x54,0xD2,0x12,0xD2,0x46,0xD2,0x6E,0x52,0x23,0xE9,0x2C,0xA9,0x9B,0x34,0x48,0x1A,0x23,0x93,0xC9,
0xDA,0x64,0x6B,0xB2,0x07,0x39,0x94,0x2C,0x20,0x2B,0xC8,0x85,0xE4,0x9D,0xE4,0xC3,0xE4,0x33,0xE4,0x1B,0xE4,0x21,0xF2,0x5B,0x0A,0x9D,0x62,0x40,0x71,0xA4,0xF8,0x53,
0xE2,0x28,0x52,0xCA,0x6A,0x4A,0x19,0xE5,0x10,0xE5,0x34,0xE5,0x06,0x65,0x98,0x32,0x41,0x55,0xA3,0x9A,0x52,0xDD,0xA8,0xA1,0x54,0x11,0x35,0x8F,0x5A,0x42,0xAD,0xA1,
0xB6,0x52,0xAF,0x51,0x87,0xA8,0x13,0x34,0x75,0x9A,0x39,0xCD,0x83,0x16,0x49,0x4B,0xA5,0xAD,0xA2,0x95,0xD3,0x1A,0x68,0x17,0x68,0xF7,0x69,0xAF,0xE8,0x74,0xBA,0x11,
0xDD,0x95,0x1E,0x4E,0x97,0xD0,0x57,0xD2,0xCB,0xE9,0x47,0xE8,0x97,0xE8,0x03,0xF4,0x77,0x0C,0x0D,0x86,0x15,0x83,0xC7,0x88,0x67,0x28,0x19,0x9B,0x18,0x07,0x18,0x67,
0x19,0x77,0x18,0xAF,0x98,0x4C,0xA6,0x19,0xD3,0x8B,0x19,0xC7,0x54,0x30,0x37,0x31,0xEB,0x98,0xE7,0x99,0x0F,0x99,0x6F,0x55,0x58,0x2A,0xB6,0x2A,0x7C,0x15,0x91,0xCA,
0x0A,0x95,0x4A,0x95,0x26,0x95,0x1B,0x2A,0x2F,0x54,0xA9,0xAA,0xA6,0xAA,0xDE,0xAA,0x0B,0x55,0xF3,0x55,0xCB,0x54,0x8F,0xA9,0x5E,0x53,0x7D,0xAE,0x46,0x55,0x33,0x53,
0xE3,0xA9,0x09,0xD4,0x96,0xAB,0x55,0xAA,0x9D,0x50,0xEB,0x53,0x1B,0x53,0x67,0xA9,0x3B,0xA8,0x87,0xAA,0x67,0xA8,0x6F,0x54,0x3F,0xA4,0x7E,0x59,0xFD,0x89,0x06,0x59,
0xC3,0x4C,0xC3,0x4F,0x43,0xA4,0x51,0xA0,0xB1,0x5F,0xE3,0xBC,0xC6,0x20,0x0B,0x63,0x19,0xB3,0x78,0x2C,0x21,0x6B,0x0D,0xAB,0x86,0x75,0x81,0x35,0xC4,0x26,0xB1,0xCD,
0xD9,0x7C,0x76,0x2A,0xBB,0x98,0xFD,0x1D,0xBB,0x8B,0x3D,0xAA,0xA9,0xA1,0x39,0x43,0x33,0x4A,0x33,0x57,0xB3,0x52,0xF3,0x94,0x66,0x3F,0x07,0xE3,0x98,0x71,0xF8,0x9C,
0x74,0x4E,0x09,0xE7,0x28,0xA7,0x97,0xF3,0x7E,0x8A,0xDE,0x14,0xEF,0x29,0xE2,0x29,0x1B,0xA6,0x34,0x4C,0xB9,0x31,0x65,0x5C,0x6B,0xAA,0x96,0x97,0x96,0x58,0xAB,0x48,
0xAB,0x51,0xAB,0x47,0xEB,0xBD,0x36,0xAE,0xED,0xA7,0x9D,0xA6,0xBD,0x45,0xBB,0x59,0xFB,0x81,0x0E,0x41,0xC7,0x4A,0x27,0x5C,0x27,0x47,0x67,0x8F,0xCE,0x05,0x9D,0xE7,
0x53,0xD9,0x53,0xDD,0xA7,0x0A,0xA7,0x16,0x4D,0x3D,0x3A,0xF5,0xAE,0x2E,0xAA,0x6B,0xA5,0x1B,0xA1,0xBB,0x44,0x77,0xBF,0x6E,0xA7,0xEE,0x98,0x9E,0xBE,0x5E,0x80,0x9E,
0x4C,0x6F,0xA7,0xDE,0x79,0xBD,0xE7,0xFA,0x1C,0x7D,0x2F,0xFD,0x54,0xFD,0x6D,0xFA,0xA7,0xF5,0x47,0x0C,0x58,0x06,0xB3,0x0C,0x24,0x06,0xDB,0x0C,0xCE,0x18,0x3C,0xC5,
0x35,0x71,0x6F,0x3C,0x1D,0x2F,0xC7,0xDB,0xF1,0x51,0x43,0x5D,0xC3,0x40,0x43,0xA5,0x61,0x95,0x61,0x97,0xE1,0x84,0x91,0xB9,0xD1,0x3C,0xA3,0xD5,0x46,0x8D,0x46,0x0F,
0x8C,0x69,0xC6,0x5C,0xE3,0x24,0xE3,0x6D,0xC6,0x6D,0xC6,0xA3,0x26,0x06,0x26,0x21,0x26,0x4B,0x4D,0xEA,0x4D,0xEE,0x9A,0x52,0x4D,0xB9,0xA6,0x29,0xA6,0x3B,0x4C,0x3B,
0x4C,0xC7,0xCD,0xCC,0xCD,0xA2,0xCD,0xD6,0x99,0x35,0x9B,0x3D,0x31,0xD7,0x32,0xE7,0x9B,0xE7,0x9B,0xD7,0x9B,0xDF,0xB7,0x60,0x5A,0x78,0x5A,0x2C,0xB6,0xA8,0xB6,0xB8,
0x65,0x49,0xB2,0xE4,0x5A,0xA6,0x59,0xEE,0xB6,0xBC,0x6E,0x85,0x5A,0x39,0x59,0xA5,0x58,0x55,0x5A,0x5D,0xB3,0x46,0xAD,0x9D,0xAD,0x25,0xD6,0xBB,0xAD,0xBB,0xA7,0x11,
0xA7,0xB9,0x4E,0x93,0x4E,0xAB,0x9E,0xD6,0x67,0xC3,0xB0,0xF1,0xB6,0xC9,0xB6,0xA9,0xB7,0x19,0xB0,0xE5,0xD8,0x06,0xDB,0xAE,0xB6,0x6D,0xB6,0x7D,0x61,0x67,0x62,0x17,
0x67,0xB7,0xC5,0xAE,0xC3,0xEE,0x93,0xBD,0x93,0x7D,0xBA,0x7D,0x8D,0xFD,0x3D,0x07,0x0D,0x87,0xD9,0x0E,0xAB,0x1D,0x5A,0x1D,0x7E,0x73,0xB4,0x72,0x14,0x3A,0x56,0x3A,
0xDE,0x9A,0xCE,0x9C,0xEE,0x3F,0x7D,0xC5,0xF4,0x96,0xE9,0x2F,0x67,0x58,0xCF,0x10,0xCF,0xD8,0x33,0xE3,0xB6,0x13,0xCB,0x29,0xC4,0x69,0x9D,0x53,0x9B,0xD3,0x47,0x67,
0x17,0x67,0xB9,0x73,0x83,0xF3,0x88,0x8B,0x89,0x4B,0x82,0xCB,0x2E,0x97,0x3E,0x2E,0x9B,0x1B,0xC6,0xDD,0xC8,0xBD,0xE4,0x4A,0x74,0xF5,0x71,0x5D,0xE1,0x7A,0xD2,0xF5,
0x9D,0x9B,0xB3,0x9B,0xC2,0xED,0xA8,0xDB,0xAF,0xEE,0x36,0xEE,0x69,0xEE,0x87,0xDC,0x9F,0xCC,0x34,0x9F,0x29,0x9E,0x59,0x33,0x73,0xD0,0xC3,0xC8,0x43,0xE0,0x51,0xE5,
0xD1,0x3F,0x0B,0x9F,0x95,0x30,0x6B,0xDF,0xAC,0x7E,0x4F,0x43,0x4F,0x81,0x67,0xB5,0xE7,0x23,0x2F,0x63,0x2F,0x91,0x57,0xAD,0xD7,0xB0,0xB7,0xA5,0x77,0xAA,0xF7,0x61,
0xEF,0x17,0x3E,0xF6,0x3E,0x72,0x9F,0xE3,0x3E,0xE3,0x3C,0x37,0xDE,0x32,0xDE,0x59,0x5F,0xCC,0x37,0xC0,0xB7,0xC8,0xB7,0xCB,0x4F,0xC3,0x6F,0x9E,0x5F,0x85,0xDF,0x43,
0x7F,0x23,0xFF,0x64,0xFF,0x7A,0xFF,0xD1,0x00,0xA7,0x80,0x25,0x01,0x67,0x03,0x89,0x81,0x41,0x81,0x5B,0x02,0xFB,0xF8,0x7A,0x7C,0x21,0xBF,0x8E,0x3F,0x3A,0xDB,0x65,
0xF6,0xB2,0xD9,0xED,0x41,0x8C,0xA0,0xB9,0x41,0x15,0x41,0x8F,0x82,0xAD,0x82,0xE5,0xC1,0xAD,0x21,0x68,0xC8,0xEC,0x90,0xAD,0x21,0xF7,0xE7,0x98,0xCE,0x91,0xCE,0x69,
0x0E,0x85,0x50,0x7E,0xE8,0xD6,0xD0,0x07,0x61,0xE6,0x61,0x8B,0xC3,0x7E,0x0C,0x27,0x85,0x87,0x85,0x57,0x86,0x3F,0x8E,0x70,0x88,0x58,0x1A,0xD1,0x31,0x97,0x35,0x77,
0xD1,0xDC,0x43,0x73,0xDF,0x44,0xFA,0x44,0x96,0x44,0xDE,0x9B,0x67,0x31,0x4F,0x39,0xAF,0x2D,0x4A,0x35,0x2A,0x3E,0xAA,0x2E,0x6A,0x3C,0xDA,0x37,0xBA,0x34,0xBA,0x3F,
0xC6,0x2E,0x66,0x59,0xCC,0xD5,0x58,0x9D,0x58,0x49,0x6C,0x4B,0x1C,0x39,0x2E,0x2A,0xAE,0x36,0x6E,0x6C,0xBE,0xDF,0xFC,0xED,0xF3,0x87,0xE2,0x9D,0xE2,0x0B,0xE3,0x7B,
0x17,0x98,0x2F,0xC8,0x5D,0x70,0x79,0xA1,0xCE,0xC2,0xF4,0x85,0xA7,0x16,0xA9,0x2E,0x12,0x2C,0x3A,0x96,0x40,0x4C,0x88,0x4E,0x38,0x94,0xF0,0x41,0x10,0x2A,0xA8,0x16,
0x8C,0x25,0xF2,0x13,0x77,0x25,0x8E,0x0A,0x79,0xC2,0x1D,0xC2,0x67,0x22,0x2F,0xD1,0x36,0xD1,0x88,0xD8,0x43,0x5C,0x2A,0x1E,0x4E,0xF2,0x48,0x2A,0x4D,0x7A,0x92,0xEC,
0x91,0xBC,0x35,0x79,0x24,0xC5,0x33,0xA5,0x2C,0xE5,0xB9,0x84,0x27,0xA9,0x90,0xBC,0x4C,0x0D,0x4C,0xDD,0x9B,0x3A,0x9E,0x16,0x9A,0x76,0x20,0x6D,0x32,0x3D,0x3A,0xBD,
0x31,0x83,0x92,0x91,0x90,0x71,0x42,0xAA,0x21,0x4D,0x93,0xB6,0x67,0xEA,0x67,0xE6,0x66,0x76,0xCB,0xAC,0x65,0x85,0xB2,0xFE,0xC5,0x6E,0x8B,0xB7,0x2F,0x1E,0x95,0x07,
0xC9,0x6B,0xB3,0x90,0xAC,0x05,0x59,0x2D,0x0A,0xB6,0x42,0xA6,0xE8,0x54,0x5A,0x28,0xD7,0x2A,0x07,0xB2,0x67,0x65,0x57,0x66,0xBF,0xCD,0x89,0xCA,0x39,0x96,0xAB,0x9E,
0x2B,0xCD,0xED,0xCC,0xB3,0xCA,0xDB,0x90,0x37,0x9C,0xEF,0x9F,0xFF,0xED,0x12,0xC2,0x12,0xE1,0x92,0xB6,0xA5,0x86,0x4B,0x57,0x2D,0x1D,0x58,0xE6,0xBD,0xAC,0x6A,0x39,
0xB2,0x3C,0x71,0x79,0xDB,0x0A,0xE3,0x15,0x05,0x2B,0x86,0x56,0x06,0xAC,0x3C,0xB8,0x8A,0xB6,0x2A,0x6D,0xD5,0x4F,0xAB,0xED,0x57,0x97,0xAE,0x7E,0xBD,0x26,0x7A,0x4D,
0x6B,0x81,0x5E,0xC1,0xCA,0x82,0xC1,0xB5,0x01,0x6B,0xEB,0x0B,0x55,0x0A,0xE5,0x85,0x7D,0xEB,0xDC,0xD7,0xED,0x5D,0x4F,0x58,0x2F,0x59,0xDF,0xB5,0x61,0xFA,0x86,0x9D,
0x1B,0x3E,0x15,0x89,0x8A,0xAE,0x14,0xDB,0x17,0x97,0x15,0x7F,0xD8,0x28,0xDC,0x78,0xE5,0x1B,0x87,0x6F,0xCA,0xBF,0x99,0xDC,0x94,0xB4,0xA9,0xAB,0xC4,0xB9,0x64,0xCF,
0x66,0xD2,0x66,0xE9,0xE6,0xDE,0x2D,0x9E,0x5B,0x0E,0x96,0xAA,0x97,0xE6,0x97,0x0E,0x6E,0x0D,0xD9,0xDA,0xB4,0x0D,0xDF,0x56,0xB4,0xED,0xF5,0xF6,0x45,0xDB,0x2F,0x97,
0xCD,0x28,0xDB,0xBB,0x83,0xB6,0x43,0xB9,0xA3,0xBF,0x3C,0xB8,0xBC,0x65,0xA7,0xC9,0xCE,0xCD,0x3B,0x3F,0x54,0xA4,0x54,0xF4,0x54,0xFA,0x54,0x36,0xEE,0xD2,0xDD,0xB5,
0x61,0xD7,0xF8,0x6E,0xD1,0xEE,0x1B,0x7B,0xBC,0xF6,0x34,0xEC,0xD5,0xDB,0x5B,0xBC,0xF7,0xFD,0x3E,0xC9,0xBE,0xDB,0x55,0x01,0x55,0x4D,0xD5,0x66,0xD5,0x65,0xFB,0x49,
0xFB,0xB3,0xF7,0x3F,0xAE,0x89,0xAA,0xE9,0xF8,0x96,0xFB,0x6D,0x5D,0xAD,0x4E,0x6D,0x71,0xED,0xC7,0x03,0xD2,0x03,0xFD,0x07,0x23,0x0E,0xB6,0xD7,0xB9,0xD4,0xD5,0x1D,
0xD2,0x3D,0x54,0x52,0x8F,0xD6,0x2B,0xEB,0x47,0x0E,0xC7,0x1F,0xBE,0xFE,0x9D,0xEF,0x77,0x2D,0x0D,0x36,0x0D,0x55,0x8D,0x9C,0xC6,0xE2,0x23,0x70,0x44,0x79,0xE4,0xE9,
0xF7,0x09,0xDF,0xF7,0x1E,0x0D,0x3A,0xDA,0x76,0x8C,0x7B,0xAC,0xE1,0x07,0xD3,0x1F,0x76,0x1D,0x67,0x1D,0x2F,0x6A,0x42,0x9A,0xF2,0x9A,0x46,0x9B,0x53,0x9A,0xFB,0x5B,
0x62,0x5B,0xBA,0x4F,0xCC,0x3E,0xD1,0xD6,0xEA,0xDE,0x7A,0xFC,0x47,0xDB,0x1F,0x0F,0x9C,0x34,0x3C,0x59,0x79,0x4A,0xF3,0x54,0xC9,0x69,0xDA,0xE9,0x82,0xD3,0x93,0x67,
0xF2,0xCF,0x8C,0x9D,0x95,0x9D,0x7D,0x7E,0x2E,0xF9,0xDC,0x60,0xDB,0xA2,0xB6,0x7B,0xE7,0x63,0xCE,0xDF,0x6A,0x0F,0x6F,0xEF,0xBA,0x10,0x74,0xE1,0xD2,0x45,0xFF,0x8B,
0xE7,0x3B,0xBC,0x3B,0xCE,0x5C,0xF2,0xB8,0x74,0xF2,0xB2,0xDB,0xE5,0x13,0x57,0xB8,0x57,0x9A,0xAF,0x3A,0x5F,0x6D,0xEA,0x74,0xEA,0x3C,0xFE,0x93,0xD3,0x4F,0xC7,0xBB,
0x9C,0xBB,0x9A,0xAE,0xB9,0x5C,0x6B,0xB9,0xEE,0x7A,0xBD,0xB5,0x7B,0x66,0xF7,0xE9,0x1B,0x9E,0x37,0xCE,0xDD,0xF4,0xBD,0x79,0xF1,0x16,0xFF,0xD6,0xD5,0x9E,0x39,0x3D,
0xDD,0xBD,0xF3,0x7A,0x6F,0xF7,0xC5,0xF7,0xF5,0xDF,0x16,0xDD,0x7E,0x72,0x27,0xFD,0xCE,0xCB,0xBB,0xD9,0x77,0x27,0xEE,0xAD,0xBC,0x4F,0xBC,0x5F,0xF4,0x40,0xED,0x41,
0xD9,0x43,0xDD,0x87,0xD5,0x3F,0x5B,0xFE,0xDC,0xD8,0xEF,0xDC,0x7F,0x6A,0xC0,0x77,0xA0,0xF3,0xD1,0xDC,0x47,0xF7,0x06,0x85,0x83,0xCF,0xFE,0x91,0xF5,0x8F,0x0F,0x43,
0x05,0x8F,0x99,0x8F,0xCB,0x86,0x0D,0x86,0xEB,0x9E,0x38,0x3E,0x39,0x39,0xE2,0x3F,0x72,0xFD,0xE9,0xFC,0xA7,0x43,0xCF,0x64,0xCF,0x26,0x9E,0x17,0xFE,0xA2,0xFE,0xCB,
0xAE,0x17,0x16,0x2F,0x7E,0xF8,0xD5,0xEB,0xD7,0xCE,0xD1,0x98,0xD1,0xA1,0x97,0xF2,0x97,0x93,0xBF,0x6D,0x7C,0xA5,0xFD,0xEA,0xC0,0xEB,0x19,0xAF,0xDB,0xC6,0xC2,0xC6,
0x1E,0xBE,0xC9,0x78,0x33,0x31,0x5E,0xF4,0x56,0xFB,0xED,0xC1,0x77,0xDC,0x77,0x1D,0xEF,0xA3,0xDF,0x0F,0x4F,0xE4,0x7C,0x20,0x7F,0x28,0xFF,0x68,0xF9,0xB1,0xF5,0x53,
0xD0,0xA7,0xFB,0x93,0x19,0x93,0x93,0xFF,0x04,0x03,0x98,0xF3,0xFC,0x63,0x33,0x2D,0xDB,0x00,0x00,0x00,0x20,0x63,0x48,0x52,0x4D,0x00,0x00,0x7A,0x25,0x00,0x00,0x80,
0x83,0x00,0x00,0xF9,0xFF,0x00,0x00,0x80,0xE9,0x00,0x00,0x75,0x30,0x00,0x00,0xEA,0x60,0x00,0x00,0x3A,0x98,0x00,0x00,0x17,0x6F,0x92,0x5F,0xC5,0x46,0x00,0x00,0x10,
0x74,0x49,0x44,0x41,0x54,0x78,0xDA,0xEC,0xDD,0xE1,0x71,0xA3,0x38,0x1B,0x00,0x60,0xDD,0xCD,0x35,0xE0,0xAF,0x04,0x5F,0x09,0xDE,0x12,0xD8,0x12,0x7C,0x25,0x78,0x4B,
0xF0,0x96,0x90,0x94,0x10,0x97,0xB0,0x29,0xC1,0x2E,0x21,0x2E,0x21,0x29,0x21,0x2E,0x81,0xEF,0x47,0xF0,0xAC,0xCF,0x67,0x1B,0x09,0x24,0x0C,0xC9,0xF3,0xCC,0x30,0x37,
0x37,0xEB,0xC0,0x8B,0x24,0xC4,0x8B,0x00,0xF1,0x47,0x5D,0xD7,0x01,0x00,0x60,0x6A,0xFE,0x54,0x04,0x00,0x80,0x24,0x06,0x00,0x40,0x12,0x03,0x00,0x20,0x89,0x01,0x00,
0x24,0x31,0x00,0x00,0x92,0x18,0x00,0x00,0x49,0x0C,0x00,0x20,0x89,0x01,0x00,0x90,0xC4,0x00,0x00,0x48,0x62,0x00,0x00,0x24,0x31,0x00,0x80,0x24,0x06,0x00,0x40,0x12,
0x03,0x00,0x20,0x89,0x01,0x00,0x24,0x31,0x00,0x00,0x92,0x18,0x00,0x00,0x49,0x0C,0x00,0x20,0x89,0x01,0x00,0x90,0xC4,0x00,0x00,0x48,0x62,0x00,0x00,0x24,0x31,0x00,
0x80,0x24,0x06,0x00,0x40,0x12,0x03,0x00,0x20,0x89,0x01,0x00,0x24,0x31,0x00,0x00,0x92,0x18,0x00,0x00,0x49,0x0C,0x00,0x20,0x89,0x01,0x00,0x90,0xC4,0x00,0x00,0x48,
0x62,0x00,0x00,0x24,0x31,0x00,0x80,0x24,0x06,0x00,0x40,0x12,0x03,0x00,0x20,0x89,0x01,0x00,0x24,0x31,0x00,0x00,0x92,0x18,0x00,0x00,0x49,0x0C,0x00,0x20,0x89,0x01,
0x00,0x90,0xC4,0x00,0x00,0x48,0x62,0x00,0x00,0x24,0x31,0x00,0x80,0x24,0x06,0x00,0x40,0x12,0x03,0x00,0x20,0x89,0x01,0x00,0x24,0x31,0x00,0x00,0x92,0x18,0x00,0x00,
0x49,0x0C,0x00,0x20,0x89,0x01,0x00,0x90,0xC4,0x00,0x00,0x48,0x62,0x00,0x00,0x24,0x31,0x00,0x80,0x24,0x06,0x68,0xB3,0x0C,0x21,0xFC,0x0A,0x21,0xD4,0xCD,0xF2,0x1A,
0x42,0x58,0x87,0x10,0x66,0x5F,0xB8,0x4C,0x66,0x4D,0x19,0xBC,0x36,0x65,0xF2,0x1E,0x42,0x78,0xFA,0xE2,0x65,0x02,0x74,0xF4,0x47,0x5D,0xD7,0x4A,0x01,0xF2,0x7B,0x0A,
0x21,0xAC,0xAE,0xFC,0xDB,0x3E,0x84,0xF0,0x3D,0x84,0x70,0xF8,0x82,0xE5,0xB2,0x0D,0x21,0x54,0xCA,0x04,0x90,0xC4,0xC0,0x38,0xAD,0x43,0x08,0x0F,0x2D,0xBF,0xD9,0x35,
0x27,0xED,0xAF,0xA4,0x6A,0x92,0x98,0x6B,0x7E,0x86,0x10,0x1E,0x0B,0x6E,0xFB,0x52,0xE2,0x24,0x69,0x02,0x49,0x0C,0x64,0x37,0x0F,0x1F,0xB7,0x63,0x16,0xA1,0xFB,0xAD,
0x86,0x7D,0x08,0xE1,0x2D,0x84,0xF0,0x3C,0xF0,0xC9,0xEA,0x3D,0x32,0xE6,0x6F,0x4D,0x8C,0x5F,0xC5,0xAD,0xD1,0xA9,0xD0,0xD4,0xD5,0xDF,0x99,0xDB,0x4E,0x15,0x51,0x17,
0xBB,0x93,0x65,0xEF,0xD0,0x03,0x49,0x0C,0xF4,0xF1,0x10,0x3E,0x46,0x33,0x72,0x39,0x34,0x57,0xF9,0x9B,0x01,0x62,0x5F,0x84,0x10,0x5E,0x22,0x7F,0x5B,0x72,0xE4,0x61,
0x8C,0x5E,0x9A,0xF2,0xB9,0xE5,0x7F,0x3D,0x12,0xCE,0xAA,0x69,0x37,0x55,0x8F,0x18,0x77,0x4D,0x9D,0xEC,0x1C,0x86,0x30,0x7E,0x1E,0xEC,0x65,0x6C,0x56,0x99,0x13,0x98,
0xD0,0x5C,0x89,0x3F,0xF5,0x3C,0xB9,0xA5,0x6C,0x8B,0xEB,0x09,0x5E,0x8E,0xDF,0x9C,0x9B,0x87,0x8F,0xDB,0x54,0xDB,0x0C,0x75,0x7C,0xBC,0xE5,0xE5,0x61,0x63,0x90,0xC4,
0x40,0xA7,0x24,0x66,0x8A,0xEB,0x3E,0x7A,0x4B,0xF8,0xAD,0xE7,0x31,0xF2,0xD4,0xE9,0x4B,0x81,0x04,0x75,0x15,0x6E,0x3F,0xBF,0x03,0x48,0x62,0x20,0xCB,0x95,0x78,0xAC,
0x21,0xAE,0xAC,0xDF,0x12,0x12,0x19,0xB7,0x2C,0xFA,0x79,0x0A,0x65,0x47,0x4C,0x16,0x21,0xFF,0xA8,0x20,0x20,0x89,0xE1,0x93,0xAA,0x3E,0xC9,0x7E,0xFC,0x8C,0xF8,0xCD,
0x63,0x48,0x1B,0xB5,0xE1,0xBF,0x09,0xCC,0x4A,0x9B,0x04,0x49,0x0C,0x7C,0x15,0x43,0x8D,0x7C,0x3C,0x87,0x10,0x7E,0xDC,0xF8,0xF7,0x4D,0x64,0xA2,0xC3,0x65,0xEB,0x81,
0x12,0x18,0x60,0xE4,0xFE,0x52,0x04,0x7C,0x11,0x9B,0x30,0xEC,0x9B,0x40,0x9B,0x26,0x69,0x5A,0x9E,0x5C,0xCD,0x1F,0x5F,0xF7,0x76,0x1B,0xA9,0xBB,0x65,0x68,0x9F,0x83,
0x27,0x27,0xA3,0x65,0x30,0x62,0x5E,0xB1,0x66,0x4C,0xDA,0x26,0x43,0x4B,0xB5,0x6F,0x16,0x89,0xC3,0x38,0xC4,0x74,0x36,0xDF,0x6F,0xD4,0xD5,0x2C,0x7C,0x7C,0xAE,0x20,
0xF5,0x19,0x98,0x43,0xD3,0x0E,0x4E,0xD7,0x3B,0x0F,0x1F,0xCF,0xBC,0x2C,0x5A,0xFE,0xEE,0x9B,0x44,0x06,0xC6,0xCB,0x48,0x0C,0x53,0xF4,0x5D,0x52,0xF2,0x9F,0xE4,0xEF,
0x3C,0x79,0x1B,0xF2,0xCD,0xA7,0xD9,0x59,0x32,0x50,0x6A,0xFB,0x0F,0x89,0x09,0xCC,0x5B,0xF8,0x18,0x7D,0xDB,0xB4,0xC4,0xBE,0x0A,0xBF,0x27,0xC7,0x3B,0xFD,0xDB,0x7F,
0x46,0x9E,0xC0,0x54,0x17,0xF6,0xF7,0x1E,0xF1,0x9E,0x4F,0x48,0x79,0x4C,0x1A,0xC7,0xE6,0x1E,0x71,0x8E,0xA5,0x8E,0x24,0x31,0x91,0x8E,0x9D,0xC1,0xB1,0x23,0xDB,0x74,
0xAC,0xB0,0x55,0xF8,0x3D,0xD3,0x66,0xAE,0xF5,0x5C,0x1A,0xCA,0x9F,0x5A,0xBC,0x53,0x8D,0x79,0x0A,0x49,0xC0,0xB2,0xB9,0x3A,0x3F,0x34,0xF1,0x6F,0xAE,0x74,0x82,0x55,
0x88,0xBF,0x3D,0x34,0x3B,0x29,0x9F,0xBE,0xF5,0x75,0x6A,0x79,0x12,0xC7,0xFC,0xC6,0x09,0xFC,0x38,0x0B,0xED,0x73,0xC1,0x32,0x5B,0x5E,0x49,0x2C,0x8E,0x65,0x93,0x63,
0x7F,0x8F,0x23,0x27,0x29,0xCF,0xC1,0x1C,0x9F,0x3B,0x6A,0x4B,0xA6,0x0E,0x4D,0xA2,0xF3,0x78,0x92,0x8C,0xC5,0x9E,0xDC,0x4A,0xB5,0x9B,0xB6,0xED,0xDD,0xAA,0xF7,0x70,
0x56,0xEF,0x25,0x4E,0x98,0x31,0xED,0x6F,0x88,0x36,0x38,0xC6,0x38,0x87,0xAE,0xA3,0xAA,0x39,0x2E,0x66,0x2D,0x6D,0x70,0x7E,0xD2,0x56,0xE7,0x17,0x92,0xAA,0x94,0xD9,
0xAA,0xAB,0xF0,0x7B,0x14,0x73,0x76,0xB6,0x4F,0x87,0x30,0xF4,0x0C,0xE9,0x75,0x5D,0xE7,0x58,0x66,0x75,0x5D,0xBF,0xD4,0xFF,0xF5,0x5E,0xD7,0xF5,0x22,0x71,0x5D,0x4F,
0x05,0xD7,0x53,0xD7,0x75,0xBD,0x9E,0x60,0xBC,0x61,0xA2,0x31,0xA7,0x2E,0x55,0x1D,0xA7,0xCA,0xD4,0x6E,0x43,0x5D,0xD7,0xAB,0x2B,0xDB,0x78,0x69,0xCA,0xFC,0x58,0xF6,
0xBF,0x6E,0xC4,0xF3,0x94,0x78,0x4C,0x74,0x8D,0x7F,0x59,0xD7,0xF5,0x6B,0x9D,0xEE,0xB5,0xD9,0xCF,0x1C,0xE5,0xB5,0xA8,0xEB,0x7A,0x9B,0xB8,0xFD,0x87,0xE6,0x6F,0xFB,
0xD4,0xED,0x53,0xC2,0xF6,0x7E,0x65,0x6C,0x1F,0x43,0xB7,0x9B,0x9C,0xF5,0x7E,0xDC,0xC6,0x3C,0xD3,0x3E,0xAF,0x7B,0xC4,0xF1,0xDA,0xEC,0x47,0x18,0x60,0xB9,0x47,0x9C,
0xF7,0xA8,0xA3,0x87,0x2B,0xEB,0xDB,0x9E,0xB4,0xC1,0x79,0xC2,0xB1,0xF3,0xD2,0xB2,0xEF,0x29,0xE5,0xFA,0x74,0x12,0x43,0xD1,0x25,0xD7,0x8A,0x6E,0x15,0xD2,0x7B,0xC2,
0xCE,0xAC,0x5A,0x1A,0x57,0x8E,0xF5,0xD4,0x2D,0x9D,0xF0,0x18,0xE3,0x9D,0x4F,0xB0,0x8C,0xBB,0x1C,0x94,0x43,0x27,0x31,0xF3,0x88,0x93,0xE1,0xA2,0x29,0xDF,0x36,0xEB,
0x84,0x63,0xE2,0xB5,0xC3,0x45,0xC2,0xAF,0xBA,0xBF,0x6D,0xCF,0x8E,0x65,0xD5,0x63,0xDB,0xAF,0x3D,0xEA,0x76,0x96,0xB8,0x9D,0xD2,0x9D,0x67,0xC9,0x76,0x73,0xBE,0xDF,
0xDB,0x3A,0x8F,0x75,0xDD,0x2F,0x71,0x7D,0x19,0x41,0x1C,0x63,0x8C,0xF3,0x5E,0x75,0xB4,0x88,0x48,0x22,0x62,0xDB,0xE0,0xA5,0xF6,0x3B,0x3B,0xDB,0x56,0x97,0x04,0xAD,
0xCB,0x85,0xF1,0x5D,0x92,0x98,0x59,0xC6,0xCA,0x69,0x6B,0x80,0xB1,0x57,0x93,0xAF,0x03,0x35,0xA6,0xA1,0xE2,0x5D,0x4F,0x34,0xE6,0xB1,0x27,0x31,0x0F,0x91,0x07,0x62,
0xEC,0x01,0x9B,0x72,0x4C,0x2C,0xEF,0xD0,0x31,0xF7,0xE9,0x58,0x56,0xF5,0x30,0xAA,0x9E,0xDB,0x1E,0xE2,0x6A,0xBF,0x54,0xBB,0x09,0x19,0x4E,0x1C,0x6D,0x27,0xB6,0x2E,
0xF5,0xFE,0x3E,0x40,0x1D,0xE7,0x18,0x19,0x1B,0x3A,0xCE,0x7B,0xD6,0x51,0xCE,0x36,0x78,0x6B,0x44,0xB1,0x6F,0xB9,0xBE,0x67,0x1C,0x09,0xBC,0xB8,0xE4,0x98,0x27,0x26,
0x66,0x86,0xD5,0x55,0xE4,0x3D,0xEF,0x45,0xC4,0x3D,0xCE,0x98,0xF5,0xCC,0x33,0x3C,0xDB,0x33,0xA6,0x78,0xD7,0x13,0x8C,0x79,0x11,0xC6,0x2F,0x26,0xC6,0xD8,0x07,0x49,
0x67,0x27,0x65,0xB2,0x88,0x2C,0xC3,0x98,0x75,0x6E,0x33,0x97,0x65,0x97,0x75,0xAE,0xC2,0xC7,0xE4,0x72,0x63,0x79,0x80,0xF5,0xD6,0xB3,0x0D,0xCF,0x13,0x6E,0x37,0xA7,
0xEB,0xDF,0x66,0xE8,0xC7,0xFA,0xD6,0xE3,0x32,0x94,0x99,0x11,0x39,0xF7,0x1C,0x3F,0xF7,0x88,0xF3,0xDE,0x75,0x94,0xB3,0x0D,0xDE,0xDA,0xBF,0xBE,0xE5,0x3A,0x2B,0xDD,
0x77,0x0C,0x35,0xD9,0x5D,0xCC,0xC9,0x33,0xA6,0xA3,0xAA,0x22,0x1B,0xF4,0x67,0x8B,0xF7,0xF0,0x49,0x63,0x1E,0xC3,0x03,0xBD,0x39,0xBD,0x25,0x74,0x30,0x55,0xC4,0xC1,
0xBF,0x0D,0x65,0xA6,0xD4,0x9F,0x25,0x74,0xC0,0x8B,0x3B,0x27,0x30,0x29,0xF5,0xB4,0x99,0x78,0xBB,0x39,0xED,0xF4,0x4B,0x7D,0x4A,0x21,0xF6,0x03,0xAB,0x25,0xEB,0x3D,
0xE7,0xBE,0xDD,0x23,0xCE,0x31,0xD4,0xD1,0x10,0x33,0x49,0x2F,0x32,0x1E,0x2F,0xC5,0xE2,0xCD,0xF1,0x76,0xD2,0x2E,0x61,0x47,0xF6,0x3D,0xAF,0x4C,0x8F,0xEB,0xD9,0x0D,
0x54,0xF0,0x63,0x89,0x77,0x13,0xE2,0x26,0xF8,0x1A,0x53,0xCC,0x25,0x5F,0x23,0x5C,0x46,0xC4,0x70,0x9C,0x23,0x66,0xA8,0x64,0x2A,0xF7,0x1B,0x59,0xEB,0x50,0xFE,0x3B,
0x52,0xBF,0xC2,0xC7,0x3C,0x28,0xB7,0xFC,0xBA,0x73,0x02,0x33,0x4F,0x38,0x59,0x3C,0x87,0xE9,0x39,0x6F,0x37,0x4F,0xA1,0xFC,0x28,0xE6,0x43,0xF8,0xEF,0xBC,0x39,0xE1,
0x42,0x1C,0x53,0xF8,0x8A,0xF7,0x3D,0xE2,0x1C,0x4B,0x1D,0x4D,0xC9,0xAA,0xD4,0xBE,0xE4,0x7A,0xC5,0x7A,0x13,0xDA,0x87,0x08,0xAB,0x70,0x7B,0xC6,0xD4,0xD8,0x4C,0x6D,
0xD1,0x52,0x18,0xCB,0xC8,0x8E,0xA3,0x9A,0x50,0xBC,0xCF,0x21,0xEE,0x15,0xD3,0xB1,0xC5,0x5C,0xF2,0x80,0x48,0x39,0x49,0xFC,0x28,0x9C,0x54,0xED,0xC3,0xC7,0x9C,0x22,
0x39,0xAF,0xF4,0xD7,0x09,0xFB,0x77,0xFA,0x7A,0xE4,0xF1,0x55,0xCA,0x2A,0xB2,0x9E,0xD7,0x37,0xDA,0xCC,0x3A,0xE4,0x1F,0x2E,0xEF,0x92,0xC4,0xC4,0x8E,0x66,0x4C,0x6D,
0xFE,0x8D,0xF3,0x76,0x53,0x85,0x3C,0x23,0xC9,0xB1,0x27,0xC9,0x6F,0x77,0x4A,0xA0,0x73,0x9D,0xCC,0xEE,0x11,0xE7,0x58,0xEA,0x68,0x6A,0x8A,0x8D,0xC4,0xE4,0x9A,0xB1,
0x77,0x19,0x79,0xC5,0xF6,0xBF,0x2B,0x57,0xC6,0xB3,0x10,0xC2,0x7B,0x42,0xC3,0xFA,0xDE,0x23,0x8E,0x7D,0xD3,0x69,0x4F,0x29,0xDE,0x6F,0x13,0x2C,0xE3,0x6F,0x1D,0x1B,
0xFA,0xB6,0x40,0x3B,0xBF,0x36,0xF3,0x6A,0xDF,0xC6,0xFF,0xD6,0x24,0xF0,0x9B,0xB3,0x32,0x5F,0x87,0xF6,0x91,0xB3,0x5B,0x65,0xBC,0x8D,0x3C,0xE8,0x7F,0x84,0xEB,0xB7,
0x50,0xAA,0xA6,0x9E,0x66,0x11,0x65,0xF3,0xF7,0x95,0x36,0xF3,0x9E,0x78,0x95,0xFB,0x7C,0x96,0x4C,0xB5,0xCD,0x95,0x71,0xC9,0xF9,0x44,0x86,0xB1,0xCF,0x08,0xDC,0x2A,
0xCF,0xDC,0x4A,0xB5,0x9B,0xD8,0x7A,0x3F,0x4F,0x60,0xBB,0x96,0xF7,0xB5,0xF6,0x93,0x5A,0xEF,0xFB,0xB3,0x8B,0x96,0xE3,0xBC,0x38,0xB3,0x8C,0x7D,0x43,0x18,0x49,0x9C,
0x63,0xA9,0xA3,0xBA,0x43,0x7B,0xDB,0x9F,0xF4,0x0D,0xAB,0xD0,0x6D,0xE6,0xEB,0xCD,0xC9,0xFE,0xA4,0xAE,0xE7,0x5B,0x28,0x31,0xB9,0x60,0xC6,0xA7,0x84,0x63,0x9E,0x60,
0x5E,0xDD,0x78,0xC7,0x3E,0x45,0x9F,0x27,0xB6,0x57,0x13,0x8D,0x77,0xAA,0x31,0x97,0x78,0x3B,0xA9,0x8B,0x87,0x0B,0xDB,0xEB,0xFA,0xB4,0xFD,0x53,0xCB,0x1B,0x3E,0x31,
0x6F,0x93,0x6D,0x3B,0xBE,0x3A,0x99,0x52,0xC6,0x7D,0xD6,0x95,0xF2,0x46,0xD0,0xF6,0xC6,0x1B,0x08,0xA9,0x6F,0x37,0x54,0x1D,0xCA,0xB2,0xF4,0xAB,0xBB,0x43,0xB4,0x9B,
0x94,0xB6,0xFF,0x72,0xA3,0xBC,0xD7,0x89,0xEB,0xE9,0x53,0xEF,0x2F,0x2D,0x6F,0x9E,0x2C,0x9A,0x78,0xB6,0xCD,0x92,0xB3,0x8E,0xEE,0x11,0xE7,0x58,0xEA,0x28,0x24,0xFE,
0xFD,0xAC,0x47,0xDF,0xD0,0xF6,0x96,0x51,0xCA,0x6B,0xDC,0x45,0xDE,0x1C,0xCC,0xF9,0x60,0x6F,0xCC,0xED,0x83,0x45,0xCF,0x21,0xE3,0xB6,0xA1,0xA9,0x94,0xDB,0x1C,0x53,
0x8B,0x77,0xAA,0x31,0x8F,0x45,0xDF,0x61,0xE7,0x43,0x73,0x55,0xF4,0x77,0xF3,0xDF,0x52,0xD3,0x95,0xAF,0x22,0xCB,0x37,0xE6,0x21,0xD6,0x7D,0xE4,0xEF,0xAA,0x1E,0xC3,
0xBF,0xFB,0x66,0x04,0xE4,0xDA,0xAD,0x9C,0xCD,0x80,0x23,0x24,0x63,0x14,0xDB,0x6E,0x96,0x99,0xCA,0xFB,0x31,0xC4,0x7F,0x21,0x7D,0x71,0xA1,0x5F,0xC8,0x55,0xEF,0xA7,
0xA3,0xDE,0xDF,0x9B,0x25,0xE7,0x07,0x58,0xEF,0x11,0xE7,0x58,0xEA,0x28,0xC5,0x3F,0x57,0x46,0x59,0xF7,0x89,0xF5,0xF1,0xF3,0xCA,0xFE,0xA4,0xAC,0xA7,0xC8,0xAD,0xE9,
0x9C,0x49,0x4C,0x4C,0x67,0xB9,0xCC,0x74,0xBF,0x6C,0x71,0xA5,0x80,0xDA,0x0A,0xE9,0x74,0x3A,0xE4,0xA9,0xC5,0x3B,0xD5,0x98,0x3F,0x83,0x7D,0x73,0x12,0xDA,0x0C,0xB0,
0x6F,0x55,0xA6,0x63,0xAD,0x6F,0x9B,0x89,0xED,0xB0,0xFF,0x89,0x2C,0xBF,0x4D,0xF8,0x7A,0x52,0xDA,0x4D,0x95,0x50,0xDE,0x6D,0xEB,0x7A,0x0C,0xF1,0xCF,0x9D,0x2C,0x7B,
0xD4,0xFB,0x3D,0x8F,0xF3,0x7B,0xC4,0x39,0x96,0x3A,0x4A,0x19,0x58,0x78,0xCB,0x70,0xB1,0x79,0x68,0x39,0x7E,0xEF,0xFA,0xF0,0xF1,0x9F,0x99,0x0F,0xD8,0xB6,0x07,0xEB,
0x66,0x57,0x4E,0x8E,0x55,0x86,0xC6,0x14,0xB3,0x8E,0xDD,0x84,0xE3,0x9D,0x6A,0xCC,0x63,0xD1,0x35,0xAE,0x43,0x73,0x55,0x35,0x44,0x87,0x9D,0x32,0xC7,0x51,0x15,0xB9,
0xC4,0xDE,0xAF,0x5E,0xB4,0x24,0xB0,0xD7,0x12,0xA4,0xB7,0xC2,0xE5,0x3F,0xE5,0x11,0x98,0xD8,0x76,0x13,0x5B,0xEF,0x29,0xE5,0xDD,0xE5,0xEA,0xB8,0x44,0xBD,0x97,0x70,
0x8F,0x38,0xC7,0x52,0x47,0xA9,0xE7,0xE4,0x3E,0xFF,0x9E,0x7B,0x3D,0xA3,0x4F,0x62,0x62,0xAF,0xFA,0xAA,0xC8,0x13,0xE3,0xF1,0x61,0xCC,0x9C,0x27,0xD8,0xE7,0x89,0xC7,
0x3B,0xD5,0x98,0xC7,0x70,0x45,0xBC,0xE9,0xF1,0xB7,0x43,0x5D,0x71,0xC6,0x76,0x56,0xDB,0xC4,0x25,0xC6,0xAC,0x43,0x1C,0x29,0x89,0x49,0xE9,0x24,0x66,0x36,0xC2,0x36,
0x77,0xC8,0x5C,0xEF,0xFB,0xC4,0xF2,0x7E,0x4B,0xDC,0xF6,0x7C,0x24,0x75,0x99,0xAB,0xBC,0x76,0x77,0xD8,0x66,0xE9,0x3A,0xCA,0x99,0xC4,0xC4,0x96,0xD1,0x6E,0xCC,0x6D,
0x22,0x77,0x12,0x13,0x73,0x02,0x5B,0x46,0x66,0xD5,0xBB,0x96,0x8E,0x60,0x99,0x78,0x82,0xBD,0x74,0x9B,0x63,0x6A,0xF1,0x4E,0x35,0xE6,0x7B,0x9E,0x48,0x7E,0x36,0x89,
0x5A,0xD7,0xB8,0x86,0x3C,0x38,0xC7,0x32,0xCB,0x71,0x89,0x0E,0xFB,0xD0,0xA3,0x0E,0xA7,0x54,0x76,0x5D,0xDA,0xCD,0xA2,0x50,0x5B,0x8C,0xFD,0x12,0x77,0xC9,0x7A,0x9F,
0x4A,0xFB,0x9C,0x4A,0x1D,0x51,0x38,0x89,0x79,0x8B,0xA8,0x94,0xF3,0xCF,0x77,0x2F,0x5A,0x2A,0x77,0x17,0xD1,0xA8,0x62,0x86,0xCD,0x9F,0x3F,0x41,0xBC,0x53,0x8D,0x39,
0xB7,0x9F,0xE1,0xF7,0x43,0x78,0xD7,0x96,0x3F,0x9A,0xE4,0xE5,0xD1,0x61,0x5E,0xAC,0xC3,0x1F,0xD3,0xBC,0x2C,0x8B,0x2F,0x50,0x47,0x6F,0x03,0xD4,0xE9,0xD4,0xEA,0x7D,
0x6C,0x71,0x8E,0xA5,0x8E,0x24,0x31,0x3D,0xA4,0x8E,0x14,0x54,0x2D,0x95,0xBB,0x8F,0xC8,0x4E,0xDB,0x32,0xD5,0xC3,0x8D,0xB8,0xA6,0x16,0xEF,0x54,0x63,0xCE,0x7D,0xC2,
0xDD,0xB5,0x2C,0xC4,0x1B,0xE2,0x81,0xE5,0xD2,0x23,0x1A,0xB3,0x2F,0x92,0xC8,0x00,0x85,0x93,0x98,0x98,0x67,0x0F,0x16,0x57,0x46,0x0C,0x2E,0x75,0x5E,0xFB,0x88,0xD1,
0x86,0x98,0xDB,0x1C,0x9F,0x25,0xDE,0xA9,0xC6,0xCC,0x78,0x93,0x84,0x9F,0x23,0x8F,0x31,0xF6,0x6A,0x75,0xA9,0x3A,0x41,0x12,0xD3,0x57,0xCC,0x15,0xF9,0xF2,0xEC,0x44,
0x7B,0xEB,0xEA,0xEB,0xD6,0x95,0x58,0x15,0x79,0x05,0xB6,0xFB,0x44,0xF1,0x4E,0x35,0x66,0xE2,0x8E,0x9D,0xD8,0xC4,0xA3,0xEF,0x72,0x3A,0x2F,0xC6,0xF9,0x76,0x63,0x87,
0xC4,0x53,0xEE,0xD5,0xF7,0x19,0x25,0x89,0x6D,0x5B,0x5D,0x66,0x21,0x9D,0x92,0x1C,0xD3,0x24,0xDC,0x6A,0x73,0x87,0x42,0x71,0xDC,0xEB,0x38,0xA9,0x3E,0x61,0x1D,0x71,
0xE6,0xAF,0x42,0xEB,0xDD,0xB5,0x5C,0x15,0x1D,0x4F,0x8A,0x6D,0xCF,0x6A,0x9C,0xAE,0xAF,0x6A,0x19,0x29,0xE8,0x73,0xC2,0x9F,0x5A,0xBC,0x53,0x8D,0x99,0xDB,0x62,0x93,
0x87,0xD2,0xDF,0x82,0x4A,0x49,0x62,0x62,0x13,0x8C,0x3E,0x49,0xCC,0x73,0x88,0xFB,0x96,0xD4,0xAC,0xF9,0xDD,0xCF,0x89,0xD5,0x7B,0xCA,0xC3,0xCB,0x29,0x17,0x0B,0x55,
0xE2,0xB6,0x4B,0xD4,0xFB,0x54,0xDA,0xE7,0x54,0xEA,0x88,0x01,0x46,0x62,0x42,0x88,0x9F,0xDC,0xA9,0x8A,0xAC,0xB4,0xDD,0x8D,0x75,0xB4,0x75,0x8E,0xCF,0x9F,0x30,0xDE,
0xA9,0xC6,0x4C,0x9E,0xCE,0xAA,0x1A,0x49,0x1C,0x29,0x23,0x1F,0xCB,0x9E,0xF1,0xC4,0x9E,0xB8,0xD6,0x21,0xED,0x03,0xA1,0x53,0xAA,0xF7,0x94,0xFD,0x5A,0x46,0xD6,0xCD,
0x5B,0xE1,0x7A,0x9F,0x4A,0xFB,0x9C,0x4A,0x1D,0x31,0x50,0x12,0x13,0x73,0x62,0x5B,0x86,0xEB,0xAF,0xCA,0xED,0x22,0x1B,0xD0,0x22,0xA2,0x73,0xDC,0x7C,0xD2,0x78,0xA7,
0x12,0xF3,0x2C,0xA4,0x4F,0xBC,0xF6,0x55,0x1D,0x22,0x3B,0xCB,0x75,0x8F,0xB2,0x3C,0x7E,0xB9,0x7A,0xDD,0x52,0xAF,0x31,0x89,0xE9,0x2C,0x72,0x84,0x64,0x95,0x21,0xF1,
0x4A,0x39,0x2E,0x9E,0x7A,0x24,0x32,0xCB,0x93,0x44,0x68,0x36,0x60,0xBD,0xC7,0xCE,0x17,0x12,0xFB,0x75,0xF3,0xD8,0xDF,0xED,0x3B,0xB4,0xBF,0x59,0x68,0xFF,0xC0,0x69,
0x57,0x31,0xFD,0xC5,0x3D,0xE2,0x1C,0x4B,0x1D,0x31,0x60,0x12,0xD3,0x36,0xA4,0x76,0xEB,0x36,0xC7,0x21,0xA1,0x12,0x67,0x2D,0x19,0xEC,0xFE,0x93,0xC6,0x3B,0xF6,0x98,
0xE7,0xE1,0x63,0xA2,0xB5,0xF7,0xF0,0x7B,0xD2,0xB5,0xF7,0xE6,0x04,0x23,0x99,0xE9,0x97,0x3C,0xCC,0x3B,0x74,0xCE,0xAB,0x10,0xC2,0x4B,0xB3,0x3C,0x34,0xCB,0xAF,0x70,
0xFD,0x0B,0xD1,0xB1,0x43,0xE2,0xEB,0x96,0xCE,0x38,0xF6,0x2B,0xD4,0x31,0x49,0x4C,0xCA,0xB3,0x01,0x4F,0xCD,0x12,0x33,0xA7,0xC8,0xA2,0xF9,0xED,0x7B,0x53,0x26,0x0F,
0xCD,0xFF,0xBF,0x84,0x42,0xDF,0x7B,0xE9,0x58,0xEF,0xC7,0xF2,0x5E,0x44,0xEC,0xFB,0xA2,0xE3,0x76,0x9F,0x13,0xDA,0x53,0xCC,0xB1,0xBC,0x68,0x7E,0xBB,0x6E,0x29,0xCB,
0xD4,0xFE,0xE2,0x1E,0x71,0x8E,0xA5,0x8E,0x38,0x55,0xF8,0x6B,0xAF,0xAF,0x1D,0xBE,0xF6,0xFA,0x74,0x65,0x5D,0x2F,0x99,0xBE,0x5C,0xFC,0x99,0xE2,0x1D,0x6B,0xCC,0x6D,
0x5F,0x36,0xBD,0xF6,0x65,0xD5,0xD8,0xAF,0xC4,0x56,0x03,0x7E,0x8D,0xB8,0xCB,0x97,0x77,0xFB,0x7C,0xC5,0x7A,0x96,0xF0,0x55,0xD8,0x97,0x96,0xB2,0x98,0x37,0xB1,0xBC,
0x77,0x2C,0xCF,0xD7,0xC4,0xAF,0xE5,0xAE,0x9B,0x75,0x55,0x27,0x5F,0x05,0x4E,0x55,0x65,0xFA,0x72,0xF1,0xA9,0x5F,0x67,0xB1,0x55,0xCD,0xBA,0x1E,0x22,0xF6,0x71,0x3B,
0x50,0xBB,0x99,0x27,0x7E,0x51,0x78,0x7D,0x65,0x1D,0xBF,0x12,0xCB,0xA5,0x4F,0x1C,0xC7,0x58,0x1E,0x9A,0x2F,0x14,0xC7,0x94,0x6D,0xAE,0xFE,0xE2,0x1E,0x71,0x8E,0xA5,
0x8E,0x42,0xC6,0x7E,0x72,0x9B,0xA9,0x2D,0x6F,0x0B,0xF5,0xA5,0xAD,0xCB,0x5F,0x03,0x5C,0x5D,0xAC,0x13,0xFF,0x66,0x7F,0xE3,0xCA,0x70,0x51,0xE8,0xEA,0x66,0xAA,0xF1,
0x8E,0x35,0xE6,0xB6,0x2B,0x9F,0x45,0x73,0xB5,0xFB,0xC3,0x65,0xC4,0xC5,0x61,0xEB,0xC7,0xC8,0x91,0x96,0x45,0x73,0xC5,0xFA,0x16,0xFE,0x3D,0x85,0xF9,0xBC,0x19,0x8E,
0x8F,0x1D,0x45,0xB8,0xF6,0x30,0xE2,0x63,0xC2,0x28,0xCA,0x22,0x94,0x9F,0xA7,0x65,0xD3,0xDC,0xEE,0x49,0xBD,0x35,0xB5,0x0C,0xDD,0x9F,0xC9,0x39,0x3E,0x13,0x56,0x7A,
0x48,0xFF,0x58,0x87,0x31,0xFB,0x36,0x3B,0x19,0x4D,0xDB,0x9D,0xD4,0xF9,0xBC,0x43,0x79,0x5E,0x8A,0x63,0x13,0xE2,0x6F,0xC7,0xCD,0x12,0xFB,0x9F,0x75,0xF8,0xEF,0x5C,
0x4E,0x5D,0xFA,0x8B,0x7B,0xC4,0x39,0x96,0x3A,0x62,0xA0,0xDB,0x49,0x5D,0x4F,0xCA,0xBB,0xC4,0x13,0x6F,0xAE,0x5B,0x33,0x53,0x8C,0x77,0x8C,0x31,0xC7,0x3C,0x08,0x1C,
0xC2,0xF4,0x1E,0xBE,0x1C,0x52,0xEA,0x87,0xEB,0xE6,0x4D,0x79,0x1E,0x3B,0xCD,0x55,0xA6,0xDB,0x20,0x9B,0x30,0xBE,0xFB,0xF1,0xF7,0xF8,0x7A,0xF2,0x50,0xB7,0x3F,0xBB,
0x24,0xF5,0x55,0x62,0xC2,0x7A,0xDA,0x07,0x5C,0xEB,0x07,0x1E,0x0B,0x97,0xF1,0x2A,0x53,0x7F,0x31,0x64,0x9C,0x63,0xAB,0x23,0x06,0x4A,0x62,0xF6,0x21,0xFD,0xFB,0x2A,
0x6F,0x89,0x27,0xDE,0x9C,0x19,0xEC,0xD4,0xE2,0x1D,0x63,0xCC,0x8B,0xC4,0x83,0x9B,0xCB,0x75,0x34,0xE4,0x28,0xD5,0x2E,0xF3,0x89,0xB5,0x74,0xD9,0x0C,0xF5,0x55,0xF1,
0xA1,0xBD,0x85,0x61,0x5E,0x0F,0x6F,0x6B,0x5F,0xA5,0xE3,0x98,0x65,0xEA,0x2F,0x86,0x8C,0x73,0x6C,0x75,0xC4,0x40,0x49,0x4C,0xEA,0x48,0x41,0xDB,0xA4,0x74,0x6F,0x85,
0xB6,0x3B,0xE5,0x78,0xA7,0x1A,0xF3,0xB5,0xED,0xE7,0xFC,0xDD,0x50,0xEB,0x29,0xB1,0xED,0xDD,0x40,0x9D,0xD8,0x73,0x4B,0x12,0xBC,0x1F,0xB8,0x33,0x8D,0xA9,0x93,0xFD,
0x80,0x89,0xCC,0xDB,0x85,0x63,0xA6,0xE4,0x76,0x1F,0x43,0xF9,0x07,0x39,0x63,0xE6,0x19,0xDA,0x84,0x72,0xB7,0x32,0x72,0xBE,0x32,0x7C,0x8F,0x38,0xC7,0x50,0x47,0x87,
0x4C,0xC7,0xD2,0xE4,0xFB,0xD2,0xB1,0x25,0x31,0x6D,0x23,0x0A,0xB1,0x23,0x05,0xBB,0x1E,0x07,0xCA,0xD4,0xE2,0x1D,0x5B,0xCC,0x6F,0x3D,0x62,0xD9,0x67,0xDA,0x87,0x90,
0x71,0x3D,0xFB,0x3B,0xAE,0x77,0x53,0x38,0x81,0x88,0x4D,0x50,0x36,0x61,0xB8,0x09,0xE4,0x52,0xDA,0xC0,0xF7,0x50,0x7E,0x0E,0x8D,0x7F,0x06,0x6C,0x37,0xA7,0x27,0xB0,
0x52,0xB7,0xF1,0x7E,0x24,0xF4,0x17,0x3F,0x0A,0x25,0x08,0x9B,0x4C,0xFD,0xC5,0x90,0x71,0x8E,0xAD,0x8E,0x72,0xB5,0xC1,0xB1,0xFD,0x66,0x94,0x49,0xCC,0x5B,0x88,0xFF,
0x92,0x70,0x8E,0x6F,0x06,0x85,0x9E,0x0D,0x7A,0x6A,0xF1,0x8E,0x2D,0xE6,0x5D,0x64,0x56,0x7E,0xED,0x77,0xCF,0x3D,0xE3,0x4F,0x11,0xF3,0x79,0x87,0x5D,0xC7,0xF5,0x1E,
0x7A,0x6E,0xFB,0xB4,0x9C,0x4B,0x3C,0x07,0xF2,0x9C,0x38,0x9A,0xF1,0xD8,0x33,0xA1,0x8A,0x29,0xCB,0xD4,0xBA,0xDD,0x87,0x72,0x5F,0x2A,0x3F,0x34,0xE5,0xBE,0x1F,0xB0,
0xDD,0x9C,0xFE,0xFD,0xF7,0x02,0x57,0xFB,0x5D,0x4E,0xF6,0x3F,0x32,0x27,0xB0,0xE7,0x27,0xFF,0xBE,0xFD,0xC5,0x50,0x71,0x8E,0xAD,0x8E,0x72,0x1D,0x4B,0xB9,0xDA,0x72,
0xE9,0x63,0xE2,0xBA,0xC2,0xAF,0x58,0x9F,0xBE,0x36,0xFA,0x92,0xE9,0xF5,0xAB,0x87,0x8E,0xAF,0xA4,0x7D,0xE6,0x78,0xC7,0x16,0xF3,0x32,0xE2,0xF5,0xC3,0xF9,0x95,0xBF,
0xAD,0x32,0xBC,0x36,0x98,0x52,0x66,0xEF,0x85,0x5E,0x09,0x5C,0x77,0x78,0xBD,0xBA,0xED,0x15,0xDC,0x2E,0xAF,0x2C,0x9F,0x7B,0x6D,0x5E,0x2D,0xED,0xBA,0x5F,0x55,0x87,
0xD7,0xFA,0x5F,0x9B,0xD7,0x68,0xE7,0x2D,0xE5,0xDD,0xA7,0x6E,0x17,0x89,0xAF,0xAE,0xB6,0xBD,0x56,0x3D,0xBF,0x53,0xBB,0xB9,0xD4,0x8E,0xDE,0x7B,0xEE,0xCF,0x4B,0x53,
0x3E,0xA1,0x67,0xBD,0xBF,0x14,0x8A,0xA1,0x4F,0x7F,0x31,0x64,0x9C,0x63,0xAA,0xA3,0x59,0xC6,0x63,0x69,0x9B,0xA9,0x2D,0x6F,0x07,0x3A,0x26,0xFE,0xB5,0x0C,0x95,0xC4,
0x1C,0x0B,0x7D,0x9B,0x69,0x7E,0x94,0x87,0x1B,0xF3,0x9F,0xCC,0xBE,0x68,0xBC,0x63,0x8B,0x79,0x79,0xE5,0x20,0x8B,0x39,0x58,0xAF,0xCD,0x07,0xB2,0x2A,0xD0,0x2E,0xAF,
0xCD,0x51,0xF1,0x94,0x61,0xDD,0x4F,0x57,0xF6,0x7F,0xDE,0xF3,0x64,0xF2,0xD4,0x61,0x8E,0x8C,0xA7,0xA6,0x4E,0x72,0x95,0xDB,0x2A,0xE2,0x64,0xF1,0xDA,0x74,0x5E,0xB3,
0xB3,0xF2,0x7E,0x2D,0xD8,0xC9,0xCD,0x3B,0xCE,0x51,0xF3,0xDA,0xB4,0xF9,0xC5,0x08,0xDA,0xCD,0xA5,0x7D,0x7A,0xEA,0x70,0xA2,0x7C,0x2D,0x70,0xCC,0x54,0x4D,0xB2,0x18,
0x1B,0xCB,0xAF,0xC8,0x18,0xFA,0xF4,0x17,0x43,0xC6,0x39,0xA6,0x3A,0xBA,0xD6,0x06,0x1F,0x3A,0xC4,0xFE,0x92,0xE1,0x02,0x7B,0x7E,0xE5,0xD8,0x7E,0x2A,0x99,0x5B,0xFC,
0x51,0xD7,0x75,0x18,0xD8,0x22,0xFC,0x7E,0xCA,0xFC,0xD0,0xE3,0x79,0x90,0x79,0xF8,0xF7,0xDC,0x0F,0xBB,0x42,0xF7,0xDC,0xA6,0x16,0xEF,0x98,0x62,0x3E,0x4E,0x21,0x3E,
0x3F,0x19,0xFE,0xDF,0x75,0xDC,0xF6,0x73,0xC1,0xE7,0x1F,0x66,0xE1,0xDF,0xDF,0x31,0xC9,0x59,0x37,0xA7,0x75,0xF1,0x96,0x71,0xF8,0xF9,0xB4,0x6C,0x2F,0xCD,0x3F,0xB1,
0x1B,0xA0,0x9D,0x85,0x93,0x6D,0x2F,0xCE,0x86,0x8E,0x6F,0xBD,0x35,0x77,0x5E,0xDE,0x25,0xEB,0xB6,0x3A,0xA9,0x87,0x4B,0xB7,0x61,0x8F,0xB1,0x1E,0x46,0xD6,0x6E,0x6E,
0x6D,0x6F,0x11,0x7E,0xCF,0x05,0x74,0xBE,0x3F,0xC7,0x07,0x91,0x4B,0xC7,0x12,0x4E,0xE2,0x98,0x5F,0x29,0xD7,0x5D,0x8F,0x36,0x9D,0xDA,0x5F,0x0C,0x19,0xE7,0x98,0xEA,
0x28,0xE7,0xB1,0x74,0xFA,0x99,0x9A,0x3E,0xB1,0xE5,0x5A,0x4F,0x94,0x7B,0x24,0x31,0x00,0x00,0xBD,0xFD,0xA9,0x08,0x00,0x00,0x49,0x0C,0x00,0x80,0x24,0x06,0x00,0x40,
0x12,0x03,0x00,0x48,0x62,0x00,0x00,0x24,0x31,0x00,0x00,0x92,0x18,0x00,0x40,0x12,0x03,0x00,0x20,0x89,0x01,0x00,0x90,0xC4,0x00,0x00,0x48,0x62,0x00,0x00,0x49,0x0C,
0x00,0x80,0x24,0x06,0x00,0x40,0x12,0x03,0x00,0x48,0x62,0x00,0x00,0x24,0x31,0x00,0x00,0x92,0x18,0x00,0x40,0x12,0x03,0x00,0x20,0x89,0x01,0x00,0x90,0xC4,0x00,0x00,
0x48,0x62,0x00,0x00,0x49,0x0C,0x00,0x80,0x24,0x06,0x00,0x40,0x12,0x03,0x00,0x48,0x62,0x00,0x00,0x24,0x31,0x00,0x00,0x92,0x18,0x00,0x40,0x12,0x03,0x00,0x20,0x89,
0x01,0x00,0x90,0xC4,0x00,0x00,0x48,0x62,0x00,0x00,0x49,0x0C,0x00,0x80,0x24,0x06,0x00,0x40,0x12,0x03,0x00,0x48,0x62,0x00,0x00,0x24,0x31,0x00,0x00,0x92,0x18,0x00,
0x40,0x12,0x03,0x00,0x20,0x89,0x01,0x00,0x90,0xC4,0x00,0x00,0x48,0x62,0x00,0x00,0x49,0x0C,0x00,0x80,0x24,0x06,0x00,0x40,0x12,0x03,0x00,0x48,0x62,0x00,0x00,0x24,
0x31,0x00,0x00,0x92,0x18,0x00,0x40,0x12,0x03,0x00,0x20,0x89,0x01,0x00,0x90,0xC4,0x00,0x00,0x48,0x62,0x00,0x00,0x49,0x0C,0x00,0x80,0x24,0x06,0x00,0x40,0x12,0x03,
0x00,0x48,0x62,0x00,0x00,0x24,0x31,0x00,0x00,0x92,0x18,0x00,0x40,0x12,0x03,0x00,0x30,0x39,0xFF,0x1F,0x00,0x11,0x06,0x61,0x07,0xDC,0x0A,0xFB,0xD0,0x00,0x00,0x00,
0x00,0x49,0x45,0x4E,0x44,0xAE,0x42,0x60,0x82,};
|
[
"zapolnov@gmail.com"
] |
zapolnov@gmail.com
|
8ba9a0ae10efa0199ba553bd629f1efd76d19a1d
|
95eb3fa6c829cbd7bbc64ced21e3f84c090192a7
|
/KURSHACHI/SUPER_KERSACH/CONSOLE/Project_Tetris/Project_Tetris/Field.h
|
0bb40029de51262df71857c1f22ddb3d26aa3b27
|
[] |
no_license
|
TheTOXIN/STUDENT
|
f9693e5e053cf86aa2b559a79168a306ec2561da
|
163eb3497897773f9d692574552b0e13046bc765
|
refs/heads/master
| 2020-03-23T18:38:17.554458
| 2018-07-26T08:20:45
| 2018-07-26T08:20:45
| 141,921,781
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 414
|
h
|
#pragma once
class CField
{
public:
CField(int width_c, int height_c);
int width;
int height;
int matrix[20][10];
int getWidth();
int getHeight();
int addScore(int countLine);
void getMatrix(int tmp[20][10]);
int getValue(int x, int y);
void setValue(int x, int y, int value);
void clearField();
int remove();
int countHeight();
int countLines();
int countHoles();
int countMonoton();
private:
};
|
[
"thetoksin@mail.ru"
] |
thetoksin@mail.ru
|
080e725d2266fe043f6f6f699614f82cf1318c1a
|
1040a492b7312e4085cc67cf789c6750865aad26
|
/ReaderWriter.h
|
2df40265c2d0a804ec766fbdebc9b994478422a4
|
[] |
no_license
|
thalesaguiar21/MultiThreadingMatrixProduct
|
480d2acd807c3d55e725f56753a12b4bf310a957
|
38e87f5608892b19f119c9a0daa0686a7f49942e
|
refs/heads/master
| 2020-12-11T09:04:35.151228
| 2016-09-16T00:31:15
| 2016-09-16T00:31:15
| 68,341,799
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 558
|
h
|
#ifndef READERWRITER_H
#define READERWRITER_H
#include <iostream>
#include <string>
class ReaderWriter
{
private:
std::string pathToReadFile;
std::string pathToSaveFile;
public:
ReaderWriter();
ReaderWriter(std::string pathToReadFile, std::string pathToSaveFile);
void readMatrixFrom(const std::string& fileName);
void saveMatrixAt(std::string pathToSave, std::string fileName);
//Setters
void setPathToSaveFile(std::string path){pathToReadFile = path;};
void setPathToReadFile(std::string path){pathToSaveFile = path;};
};
#endif
|
[
"thalesaguiar21@gmail.com"
] |
thalesaguiar21@gmail.com
|
bec823a2cd62eb03543cb7662655270cf8adc883
|
48d4de83d911acabbe6935fe6fdedac244ba38ea
|
/SDK/PUBG_WeapCrossbow_2_parameters.hpp
|
9c6fbf3cddf56b834a701893172d32346bacbb80
|
[] |
no_license
|
yuaom/PUBG-SDK-1
|
af9c18e7d69a05074d4e6596f5f6ac1761192e7d
|
5958d6039aabe8a42d40c2f6a6978af0fffcb87b
|
refs/heads/master
| 2023-06-10T12:42:33.106376
| 2018-02-24T04:38:15
| 2018-02-24T04:38:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,330
|
hpp
|
#pragma once
// PLAYERUNKNOWN'S BATTLEGROUNDS (3.6.13.14) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace Classes
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function WeapCrossbow_2.WeapCrossbow_1_C.UserConstructionScript
struct AWeapCrossbow_1_C_UserConstructionScript_Params
{
};
// Function WeapCrossbow_2.WeapCrossbow_1_C.ReceiveTick
struct AWeapCrossbow_1_C_ReceiveTick_Params
{
float* DeltaSeconds; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function WeapCrossbow_2.WeapCrossbow_1_C.ServerSetAmmoState
struct AWeapCrossbow_1_C_ServerSetAmmoState_Params
{
TEnumAsByte<ENUM_CrossbowState> NewAmmoState; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function WeapCrossbow_2.WeapCrossbow_1_C.ExecuteUbergraph_WeapCrossbow_2
struct AWeapCrossbow_1_C_ExecuteUbergraph_WeapCrossbow_2_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
[
"mtz007@x.y.z"
] |
mtz007@x.y.z
|
3fb62a8bcedb86e96b6039ae0a7a1fdcc5a9afc7
|
598842e1bbb0a7e50c6fea85d3b4a427bb8d5c2d
|
/Target Tracking/Tracking/Track.h
|
4454cb38b8f76b572d9e0350e973976073663e62
|
[] |
no_license
|
aaabbbcccdddeeef/Digital-Image-Process
|
b587e1ff031c0a580c0d21c7bff4e6c2141ed2d4
|
0b83954fad418a2587a8d3e3fe25fa003256359d
|
refs/heads/master
| 2023-08-21T23:47:53.480320
| 2018-05-21T01:31:59
| 2018-05-21T01:31:59
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 681
|
h
|
#pragma once
#include <iostream>
#include <opencv2\opencv.hpp>
#include <opencv2\tracking\tracker.hpp>
#include <opencv2\xfeatures2d\nonfree.hpp>
#include "kcf\kcftracker.hpp"
using namespace std;
using namespace cv;
class Track
{
public:
Track();
~Track();
int PlayVideo(CString filename);
void GSMDetection(CString filename);
void FDiffDetection(CString filename);
void KCF(CString filename);
Rect FaceDetect(Mat Image);
void TragetTracker(CString filename, cv::String trackerType);
void MultiTrackerCompare(CString filename);
Rect GSMDetectionAre(Mat image01, Mat image02);
void WriteFPSToFile(cv::String trackertype, float fps);
};
|
[
"448435279@qq.com"
] |
448435279@qq.com
|
df0e071326ae141947e1e3a4992e81323ceca3e7
|
231d755f50889734283f1673c1d33f86633865b3
|
/temperature.h
|
599e71c195c49e74ad83a928741c8c1a2502189f
|
[] |
no_license
|
jasonivey/testcpp
|
bcb90295fa910764cfe3562d93a3230df2004de9
|
754af9093a0c652b3f6bdd8d80545f318dd65f22
|
refs/heads/master
| 2023-08-28T11:31:51.227070
| 2021-10-29T08:08:12
| 2021-10-29T08:08:12
| 261,923,993
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 472
|
h
|
#pragma once
#include <string>
namespace mmotd::temperature {
double GetCpuTemperature();
double GetGpuTemperature();
double ConvertCelciusToFahrenheit(double celcius_temperature) noexcept;
enum class Scale { Unknown, Low, Medium, High };
Scale GetScaleFromTemperature(double celcius_temperature) noexcept;
std::string GetTemperatureIcon(double celcius_temperature) noexcept;
std::string GetTemperatureIcon(Scale scale) noexcept;
} // namespace mmotd::temperature
|
[
"jasonivey@gmail.com"
] |
jasonivey@gmail.com
|
cdc7939a49b8e5b26147c17d10ad5fed9bf1e593
|
8afb5afd38548c631f6f9536846039ef6cb297b9
|
/MY_REPOS/misc-experiments/_FIREBFIRE/firebase-cpp-sdk/auth/src/user.cc
|
1328002df6a21939bc2890eb7f62dcce945a1ec5
|
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
bgoonz/UsefulResourceRepo2.0
|
d87588ffd668bb498f7787b896cc7b20d83ce0ad
|
2cb4b45dd14a230aa0e800042e893f8dfb23beda
|
refs/heads/master
| 2023-03-17T01:22:05.254751
| 2022-08-11T03:18:22
| 2022-08-11T03:18:22
| 382,628,698
| 10
| 12
|
MIT
| 2022-10-10T14:13:54
| 2021-07-03T13:58:52
| null |
UTF-8
|
C++
| false
| false
| 2,037
|
cc
|
/*
* Copyright 2016 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
namespace firebase {
namespace auth {
AUTH_RESULT_FN(User, GetToken, std::string)
AUTH_RESULT_FN(User, UpdateEmail, void)
AUTH_RESULT_FN(User, UpdatePassword, void)
AUTH_RESULT_FN(User, Reauthenticate, void)
AUTH_RESULT_FN(User, ReauthenticateAndRetrieveData, SignInResult)
AUTH_RESULT_FN(User, SendEmailVerification, void)
AUTH_RESULT_FN(User, UpdateUserProfile, void)
AUTH_RESULT_FN(User, LinkWithCredential, User*)
AUTH_RESULT_FN(User, LinkAndRetrieveDataWithCredential, SignInResult)
AUTH_RESULT_FN(User, Unlink, User*)
AUTH_RESULT_FN(User, UpdatePhoneNumberCredential, User*)
AUTH_RESULT_FN(User, Reload, void)
AUTH_RESULT_FN(User, Delete, void)
#if defined(INTERNAL_EXPERIMENTAL)
// I'd like to change all the above functions to use LastResultProxy, as it
// makes multi-threaded situations more deterministic. However, LastResult
// functions are public in the C++ SDK. And even while they are
// non-deterministic in multi-threaded situations, someone might rely on their
// current behavior. So for now, we only use it in Unity, and only for
// GetToken where there is a real, reproductible issue.
Future<std::string> User::GetTokenThreadSafe(bool force_refresh) {
Future<std::string> future = GetToken(force_refresh);
if (future.status() != kFutureStatusPending) {
return future;
} else {
FutureBase base = auth_data_->future_impl.LastResultProxy(kUserFn_GetToken);
const FutureBase& rFuture = base;
return static_cast<const Future<std::string>&>(rFuture);
}
}
#endif // defined(INTERNAL_EXPERIMENTAL)
// Non-inline implementation of UserInfoInterface's virtual destructor
// to prevent its vtable being emitted in each translation unit.
UserInfoInterface::~UserInfoInterface() {}
} // namespace auth
} // namespace firebase
|
[
"bryan.guner@gmail.com"
] |
bryan.guner@gmail.com
|
fb4bca19daee9435906def8b18cae9ed82b11312
|
5cd8d6efd159f55e53ff39b2764bb4d447a25699
|
/Back-tracking/RatInMaze.cpp
|
839aec725015f25f693b92738aee7bf68265c64d
|
[] |
no_license
|
Shaswat-2203/DataStructures-Algorithms
|
9181c285f0114496395ed50ea015e150b6dc6a10
|
5e110d1245382794eba75eb574ff7c1fbfc69476
|
refs/heads/main
| 2023-08-21T21:44:19.349768
| 2021-10-03T19:42:55
| 2021-10-03T19:42:55
| 413,178,924
| 1
| 0
| null | 2021-10-03T19:38:23
| 2021-10-03T19:38:23
| null |
UTF-8
|
C++
| false
| false
| 1,432
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
bool isSafe (int **arr, int x, int y, int n){
if (x < n && y < n && arr[x][y] == 1){
return true;
}
return false;
}
bool ratInMaze(int **arr, int x, int y, int n, int **resultArr){
if (x == n-1 && y == n-1){
resultArr[x][y] = 1;
return true;
}
if (isSafe(arr, x, y, n)){
resultArr[x][y] = 1;
if (ratInMaze (arr, x+1, y, n, resultArr)){
return true;
}
if (ratInMaze (arr, x, y+1, n, resultArr)){
return true;
}
resultArr[x][y] = 0; //Backtracking
return false;
}
return false;
}
int main() {
int n; cin >> n;
int** arr = new int*[n];
for (int i = 0; i < n; i++){
arr[i] = new int[n];
}
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
cin >> arr[i][j];
}
}
cout << "\n";
int **resultArr = new int*[n];
for (int i = 0; i < n; i++){
resultArr[i] = new int[n];
for (int j = 0; j < n; j++){
resultArr[i][j] = 0;
}
}
if(ratInMaze(arr, 0, 0, n, resultArr)){
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
cout << resultArr[i][j] <<" ";
}
cout << "\n";
}
}
return 0;
}
/*
1 0 1 0 1
1 1 1 1 1
0 1 0 1 0
1 0 0 1 1
1 1 1 0 1
*/
|
[
"rahulranjan25.RR@gmail.com"
] |
rahulranjan25.RR@gmail.com
|
081133ced64d6faf1560f06ee4e9e094340b512e
|
327a0fd1d791a2d928200d9e1e29a68937e9f031
|
/redist/deps/fmstream/fmstream.h
|
addcc6d8b959590d7b45ac01304f3eba93ca68d4
|
[
"Zlib",
"BSD-3-Clause",
"MIT"
] |
permissive
|
Meowhax/apathy
|
aa29254a07b583c90c5d09d53cd5451232844ae4
|
5273e14f29e3705f09df48cb813e4ec6e3a4e619
|
refs/heads/master
| 2020-04-13T17:44:09.443385
| 2015-06-12T17:42:17
| 2015-06-13T09:42:01
| 43,214,773
| 1
| 0
| null | 2015-09-26T17:12:17
| 2015-09-26T17:12:17
| null |
UTF-8
|
C++
| false
| false
| 29,221
|
h
|
/*
* Copyright (c) 2013, Benichou Software
* 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 author 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 AUTHOR 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.
*
* Purpose: Provide read-write access to memory-mapped files on Windows and POSIX systems.
*
* $Id: fmstream.h 4 2013-09-24 14:03:10Z benichou $
*/
#ifndef FILE_MAPPING_STREAM_H_
#define FILE_MAPPING_STREAM_H_
#include <istream>
/**
* At this time, move constructor and move assignment for streams are only implements in Microsoft Visual Studio 2010 and Intel C++ Compiler 12
*/
#if ((__cplusplus > 199711L) || (_HAS_CPP0X > 0)) && ((_MSC_VER >= 1600) || (__INTEL_COMPILER >= 1200))
#define _HAS_CPP11_ 1
#endif
/**
* File mapping utility class.
*/
class filemapping
{
public:
/**
* Get memory offset granularity.
* Return the offset granularity of the system.
* @return Return the offset granularity of the system.
* @see filemappingbuf::open()
* @see ifmstream::open()
* @see fmstream::open()
*/
static std::streamoff offset_granularity();
};
/**
* File mapping stream buffer.
* This class applies the functionality of the std::streambuf class to read and write from/to memory-mapped files.
* By calling member open, a physical file is associated to the file buffer as its associated character sequence.
* Depending on the mode used in this operation, the access to the controlled input sequence or the controlled output sequence may be restricted.
* The state of the filemappingbuf object -i.e. whether a file is open or not- may be tested by calling member function is_open.
* Internally, filemappingbuf objects operate as defined in the std::streambuf class.
* The class overrides some virtual members inherited from streambuf to provide a specific functionality for memory-mapped files.
*/
class filemappingbuf : public std::streambuf
{
public:
/**
* Construct object.
* A filemappingbuf object is constructed, initializing all its pointers to null pointers and initializing the object's locale.
*/
filemappingbuf();
/**
* Destructs the filemappingbuf object.
*/
virtual ~filemappingbuf();
#ifdef _HAS_CPP11_
/** @name C++11
* The following methods requires some features introduced by the latest revision of the C++ standard (2011). Older compilers may not support it.
*/
///@{
/**
* Move constructor (requires C++11).
* Acquires the contents of rhs_buf, by move-assigning its members and base classes.
* @param rhs_buf filemappingbuf to move. rhs_buf becomes of invalid state after the operation.
* @see swap()
* @see operator=()
*/
filemappingbuf(filemappingbuf&& rhs_buf);
/**
* Move assignment (requires C++11).
* Closes the source filemappingbuf (as if member close was called), and then acquires the contents of rhs_buf.
* @param rhs_buf filemappingbuf to move. rhs_buf becomes of invalid state after the operation.
* @return *this.
* @see swap()
*/
filemappingbuf& operator=(filemappingbuf&& rhs_buf);
/**
* Swap internals (requires C++11).
* Exchanges the state of the filemappingbuf with those of other.
* @param buf filemappingbuf to exchange the state with.
* @see operator=()
*/
void swap(filemappingbuf& buf);
///@}
#endif // _HAS_CPP11_
/**
* Check if a file is open.
* The function returns true if a previous call to open succeeded and there have been no calls to the member close since,
* meaning that the filemappingbuf object is currently associated with a file.
* @return true if a file is open, i.e. associated to this stream buffer object. false otherwise.
* @see open()
* @see close()
*/
bool is_open() const;
/**
* Open file.
* Opens a file, associating its content with the stream buffer object to perform input/output operations on it.
* The operations allowed and some operating details depend on parameter mode.
* If the object already has a file associated (open), this function fails.
* If the i/o mode is input only and the file do not exist, this function fails.
* If the i/o mode is output and the file do not exist, the file is created with the 'offset + max_length' size.
* If the size of the opened file is less than 'offset + max_length', the file growing.
* If the size of the opened file is greater than max_length, the file is not truncated.
* An attempt to map a file with a length of 0 fails.
* @param path_name C-string contains the name of the file to be opened.
* @param mode Flags describing the requested i/o mode for the file. This is an object of type std::ios_base::openmode.
* It consists of a combination of the following member constants:
* - std::ios_base::ate (at end) Set the stream's position indicator to the end of the file on opening.
* - std::ios_base::in (input) Allow input operations on the stream.
* - std::ios_base::out (output) Allow output operations on the stream.
* @param max_length Maximum length of the file mapping. If this parameter is 0, the mapping extends from the specified offset to the end of the file.
* @param offset File offset where the mapping begins. They must also match the memory allocation granularity of the system.
* That is, the offset must be a multiple of the allocation granularity. To obtain the offset granularity of the system, use filemapping::offset_granularity().
* @return The function returns this if successful. In case of failure, close is called and a null pointer is returned.
* @see is_open()
* @see close()
* @see filemapping::offset_granularity()
*/
filemappingbuf* open(const char* path_name, std::ios_base::openmode mode, std::streamsize max_length = 0, std::streamoff offset = 0);
/**
* Close file.
* Closes the file currently associated with the object and disassociates it.
* The function fails if no file is currently open (associated) with this object.
* @return In case of success, the function returns this. In case of failure, a null pointer is returned.
* @see open()
* @see is_open()
*/
filemappingbuf* close();
/**
* Set internal position pointer to absolute position.
* Calls protected virtual member seekptr, which sets a new position value for one or both of the internal position pointers.
* The parameter which determines which of the position pointers is affected: either the get pointer or the put pointer, or both.
* The function fails if no file is currently open (associated) with this object.
* @param ptr New absolute position for the position pointer.
* @param which Determines which of the internal position pointers shall be modified: the input pointer, the output pointer, or both. This is an object of type std::ios_base::openmode.
* @return In case of success, return the new position value of the modified position pointer. In case of failure, a null pointer is returned.
* @see std::streambuf::pubseekpos()
* @see std::streambuf::pubseekoff()
*/
void* pubseekptr(void* ptr, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out);
/**
* Get the read-only base address of the mapping.
* The function fails if no file is currently open (associated) with this object.
* @return In case of success, returns the constant base address of the mapping. In case of failure, a null pointer is returned.
* @see size()
*/
const void* data() const;
/**
* Get the base address of the mapping.
* The function fails if no file is currently open (associated) with this object.
* @return In case of success, returns the base address of the mapping. In case of failure, a null pointer is returned.
* @see size()
*/
void* data();
/**
* Get the maximum byte length of the mapping.
* The function fails if no file is currently open (associated) with this object.
* @return In case of success, returns the length of the mapping. In case of failure, 0 is returned.
* @see data()
*/
std::streamsize size() const;
protected:
virtual int sync();
virtual std::streampos seekoff(std::streamoff off, std::ios_base::seekdir way, std::ios_base::openmode which);
virtual std::streampos seekpos(std::streampos sp, std::ios_base::openmode which);
virtual void* seekptr(void* ptr, std::ios_base::openmode which);
private:
/**
* Copy constructor is private: this class is not copyable.
*/
filemappingbuf(const filemappingbuf&);
/**
* Copy operator is private: this class is not copyable.
*/
filemappingbuf& operator=(const filemappingbuf&);
private:
char* m_pAddress; //!< Base address of the mapping
std::streamsize m_MapLength; //!< Length of the mapping
#ifdef _WIN32
void* m_pFile; //!< Windows handle to the file mapping object
void* m_pFileMapping; //!< Windows handle to the opened file
#else // If not Windows, this is a POSIX system !
int m_fd; //!< File descriptor to the opened file
#endif
};
/**
* ifmstream provides an interface to read data from memory-mapped files as input streams.
* The objects of this class maintain internally a pointer to a filemappingbuf object that can be obtained by calling member rdbuf.
* The file to be associated with the stream can be specified either as a parameter in the constructor or by calling member open.
* After all necessary operations on a file have been performed, it can be closed (or disassociated) by calling member close. Once closed, the same file stream object may be used to open another file.
* The member function is_open can be used to determine whether the stream object is currently associated with a file.
* ifmstream can be used in place of std::ifstream.
*/
class ifmstream : public std::istream
{
public:
/**
* Construct object.
* Constructs an object of the ifstream class.
* This implies the initialization of the associated filemappingbuf object and the call to the constructor of its base class with the filemappingbuf object as parameter.
*/
ifmstream();
/**
* Construct object and open a file.
* Constructs an object of the ifstream class.
* This implies the initialization of the associated filemappingbuf object and the call to the constructor of its base class with the filemappingbuf object as parameter.
* The stream is associated with a physical file as if a call to the member function open with the same parameters was made.
* If the constructor is not successful in opening the file, the object is still created although no file is associated to the stream buffer and the stream's failbit is set (which can be checked with inherited member fail).
* @param path_name C-string contains the name of the file to be opened.
* @param max_length Maximum length of the file mapping. If this parameter are 0, the maximum length of the file mapping object is equal to the current size of the file.
* @param offset File offset where the mapping begins. They must also match the memory allocation granularity of the system.
* That is, the offset must be a multiple of the allocation granularity. To obtain the offset granularity of the system, use filemapping::offset_granularity().
* @see open()
* @see is_open()
* @see close()
* @see filemapping::offset_granularity()
*/
explicit ifmstream(const char* path_name, std::streamsize max_length = 0, std::streamoff offset = 0);
/**
* Destructs the ifmstream object.
*/
virtual ~ifmstream() {}
#ifdef _HAS_CPP11_
/** @name C++11
* The following methods requires some features introduced by the latest revision of the C++ standard (2011). Older compilers may not support it.
*/
///@{
/**
* Move constructor (requires C++11).
* Acquires the contents of rhs_stream, by move-assigning its members and base classes.
* @param rhs_stream File stream to move. rhs_stream becomes of invalid state after the operation.
* @see swap()
* @see operator=()
*/
ifmstream(ifmstream&& rhs_stream);
/**
* Move assignment (requires C++11).
* Closes the source stream (as if member close was called), and then acquires the contents of rhs_stream.
* @param rhs_stream File stream to move. rhs_stream becomes of invalid state after the operation.
* @return *this.
* @see swap()
*/
ifmstream& operator=(ifmstream&& rhs_stream);
/**
* Swap internals (requires C++11).
* Exchanges the state of the stream with those of other.
* @param stream ifmstream to exchange the state with.
* @see operator=()
*/
void swap(ifmstream& stream);
///@}
#endif // _HAS_CPP11_
/**
* Get the associated filemappingbuf object.
* Returns a pointer to the filemappingbuf object associated with the stream.
* @return A pointer to the filemappingbuf object associated with the stream.
* Notice that for any successfully constructed ifmstream object this pointer is never a null pointer, even if no files have been opened or if the stream is unbuffered.
*/
filemappingbuf* rdbuf() const;
/**
* Check if a file is open.
* Returns true if the stream is currently associated with a file, and false otherwise.
* The stream is associated with a file if either a previous call to member open succeeded or if the object was successfully constructed using the parameterized constructor, and close has not been called since.
* @return true if a file is open, i.e. associated to this stream object. false otherwise.
* @see open()
* @see close()
*/
bool is_open() const;
/**
* Open file.
* Opens a file whose name is path_name, associating its content with the stream object to perform input/output operations on it.
* The operations allowed and some operating details depend on parameter mode.
* If the object already has a file associated (open), this function fails.
* If the file do not exist, this function fails.
* An attempt to map a file with a length of 0 fails.
* On failure, the failbit flag is set (which can be checked with member fail), and depending on the value set with exceptions an exception may be thrown.
* @param path_name C-string contains the name of the file to be opened.
* @param max_length Maximum length of the file mapping. If this parameter are 0, the maximum length of the file mapping object is equal to the current size of the file.
* @param offset File offset where the mapping begins. They must also match the memory allocation granularity of the system.
* That is, the offset must be a multiple of the allocation granularity. To obtain the offset granularity of the system, use filemapping::offset_granularity().
* @see is_open()
* @see close()
* @see filemapping::offset_granularity()
*/
void open(const char* path_name, std::streamsize max_length = 0, std::streamoff offset = 0);
/**
* Close file.
* Closes the file currently associated with the object and disassociates it.
* The function fails if no file is currently open (associated) with this object.
* On failure, the failbit flag is set (which can be checked with member fail), and depending on the value set with exceptions an exception may be thrown.
* @see open()
* @see is_open()
*/
void close();
/**
* Get position of the get pointer.
* The get pointer determines the next location in the input sequence to be read by the next input operation.
* The function fails if no file is currently open (associated) with this object.
* @return Return the address of the get pointer. In case of failure, a null pointer is returned.
* @see pseekg()
* @see std::istream::tellg()
*/
const void* ptellg();
/**
* Sets the position of the get pointer.
* The get pointer determines the next location to be read in the source associated to the stream.
* The function fails if no file is currently open (associated) with this object.
* On failure, the failbit flag is set (which can be checked with member fail), and depending on the value set with exceptions an exception may be thrown.
* @param ptr New absolute position for the input pointer.
* @return The function returns *this.
* @see ptellg()
* @see std::istream::seekg()
*/
std::istream& pseekg(const void* ptr);
/**
* Get the read-only base address of the mapping.
* The function fails if no file is currently open (associated) with this object.
* @return In case of success, returns the constant base address of the mapping. In case of failure, a null pointer is returned.
* @see size()
*/
const void* data() const;
/**
* Get the maximum byte length of the mapping.
* The function fails if no file is currently open (associated) with this object.
* @return In case of success, returns the length of the mapping. In case of failure, 0 is returned.
* @see data()
*/
std::streamsize size() const;
private:
/**
* Copy constructor is private: this class is not copyable.
*/
ifmstream(const ifmstream&);
/**
* Copy operator is private: this class is not copyable.
*/
ifmstream& operator=(const ifmstream&);
private:
filemappingbuf m_rdbuf; //!< filemappingbuf object
};
/**
* fmstream provides an interface to read/write data from/to memory-mapped files as input/output streams.
* The objects of this class maintain internally a pointer to a filemappingbuf object that can be obtained by calling member rdbuf.
* The file to be associated with the stream can be specified either as a parameter in the constructor or by calling member open.
* After all necessary operations on a file have been performed, it can be closed (or disassociated) by calling member close.
* Once closed, the same file stream object may be used to open another file.
* The member function is_open can be used to determine whether the stream object is currently associated with a file.
* fmstream can be used in place of std::fstream.
*/
class fmstream : public std::iostream
{
public:
/**
* Construct object.
* Constructs an object of the fstream class.
* This implies the initialization of the associated filemappingbuf object and the call to the constructor of its base class with the filemappingbuf object as parameter.
*/
fmstream();
/**
* Construct object and open or create a file.
* Constructs an object of the fstream class.
* This implies the initialization of the associated filemappingbuf object and the call to the constructor of its base class with the filemappingbuf object as parameter.
* The stream is associated with a physical file as if a call to the member function open with the same parameters was made.
* If the constructor is not successful in opening the file, the object is still created although no file is associated to the stream buffer and the stream's failbit is set (which can be checked with inherited member fail).
* @param path_name C-string contains the name of the file to be opened or created.
* @param max_length Maximum length of the file mapping. If this parameter are 0, the maximum length of the file mapping object is equal to the current size of the file.
* @param offset File offset where the mapping begins. They must also match the memory allocation granularity of the system.
* That is, the offset must be a multiple of the allocation granularity. To obtain the offset granularity of the system, use filemapping::offset_granularity().
* @see open()
* @see is_open()
* @see close()
* @see filemapping::offset_granularity()
*/
explicit fmstream(const char* path_name, std::streamsize max_length = 0, std::streamoff offset = 0);
/**
* Destructs the fmstream object.
*/
virtual ~fmstream() {}
#ifdef _HAS_CPP11_
/** @name C++11
* The following methods requires some features introduced by the latest revision of the C++ standard (2011). Older compilers may not support it.
*/
///@{
/**
* Move constructor (requires C++11).
* Acquires the contents of rhs_stream, by move-assigning its members and base classes.
* @param rhs_stream File stream to move. rhs_stream becomes of invalid state after the operation.
* @see swap()
* @see operator=()
*/
fmstream(fmstream&& rhs_stream);
/**
* Move assignment (requires C++11).
* Closes the source stream (as if member close was called), and then acquires the contents of rhs_stream.
* @param rhs_stream File stream to move. rhs_stream becomes of invalid state after the operation.
* @return *this.
* @see swap()
*/
fmstream& operator=(fmstream&& rhs_stream);
/**
* Swap internals (requires C++11).
* Exchanges the state of the stream with those of other.
* @param stream fmstream to exchange the state with.
* @see operator=()
*/
void swap(fmstream& stream);
///@}
#endif // _HAS_CPP11_
/**
* Get the associated filemappingbuf object.
* Returns a pointer to the filemappingbuf object associated with the stream.
* @return A pointer to the filemappingbuf object associated with the stream.
* Notice that for any successfully constructed fmstream object this pointer is never a null pointer, even if no files have been opened or if the stream is unbuffered.
*/
filemappingbuf* rdbuf() const;
/**
* Check if a file is open.
* Returns true if the stream is currently associated with a file, and false otherwise.
* The stream is associated with a file if either a previous call to member open succeeded or if the object was successfully constructed using the parameterized constructor, and close has not been called since.
* @return true if a file is open, i.e. associated to this stream object. false otherwise.
* @see open()
* @see close()
*/
bool is_open() const;
/**
* Open file.
* Opens a file whose name is path_name, associating its content with the stream object to perform input/output operations on it.
* The operations allowed and some operating details depend on parameter mode.
* If the object already has a file associated (open), this function fails.
* If the file do not exist, the file is created with the 'offset + max_length' size.
* If the size of the opened file is less than 'offset + max_length', the file growing.
* If the size of the opened file is greater than 'offset + max_length', the file is not truncated.
* An attempt to map a file with a length of 0 fails.
* On failure, the failbit flag is set (which can be checked with member fail), and depending on the value set with exceptions an exception may be thrown.
* @param path_name C-string contains the name of the file to be opened.
* @param max_length Maximum length of the file mapping. If this parameter are 0, the maximum length of the file mapping object is equal to the current size of the file.
* @param offset File offset where the mapping begins. They must also match the memory allocation granularity of the system.
* That is, the offset must be a multiple of the allocation granularity. To obtain the offset granularity of the system, use filemapping::offset_granularity().
* @see is_open()
* @see close()
* @see filemapping::offset_granularity()
*/
void open(const char* path_name, std::streamsize max_length = 0, std::streamoff offset = 0);
/**
* Close file.
* Closes the file currently associated with the object and disassociates it.
* The function fails if no file is currently open (associated) with this object.
* On failure, the failbit flag is set (which can be checked with member fail), and depending on the value set with exceptions an exception may be thrown.
* @see open()
* @see is_open()
*/
void close();
/**
* Get position of the get pointer.
* The get pointer determines the next location in the input sequence to be read by the next input operation.
* The function fails if no file is currently open (associated) with this object.
* @return Return the address of the get pointer. In case of failure, a null pointer is returned.
* @see ptellp()
* @see pseekg()
* @see std::istream::tellg()
*/
const void* ptellg();
/**
* Get position of the put pointer.
* The put pointer determines the location in the output sequence where the next output operation is going to take place.
* The function fails if no file is currently open (associated) with this object.
* @return Return the address of the put pointer. In case of failure, a null pointer is returned.
* @see ptellg()
* @see pseekp()
* @see std::istream::tellp()
*/
void* ptellp();
/**
* Sets the position of the get pointer.
* The get pointer determines the next location to be read in the source associated to the stream.
* The function fails if no file is currently open (associated) with this object.
* On failure, the failbit flag is set (which can be checked with member fail), and depending on the value set with exceptions an exception may be thrown.
* @param ptr New absolute position for the input pointer.
* @return The function returns *this.
* @see pseekp()
* @see ptellg()
* @see std::istream::seekg()
*/
std::istream& pseekg(const void* ptr);
/**
* Sets the position of the put pointer.
* The put pointer determines the location in the output sequence where the next output operation is going to take place.
* The function fails if no file is currently open (associated) with this object.
* On failure, the failbit flag is set (which can be checked with member fail), and depending on the value set with exceptions an exception may be thrown.
* @param ptr New absolute position for the output pointer.
* @return The function returns *this.
* @see pseekg()
* @see ptellp()
* @see std::istream::seekp()
*/
std::ostream& pseekp(void* ptr);
/**
* Get the read-only base address of the mapping.
* The function fails if no file is currently open (associated) with this object.
* @return In case of success, returns the constant base address of the mapping. In case of failure, a null pointer is returned.
* @see size()
*/
const void* data() const;
/**
* Get the base address of the mapping.
* The function fails if no file is currently open (associated) with this object.
* @return In case of success, returns the base address of the mapping. In case of failure, a null pointer is returned.
* @see size()
*/
void* data();
/**
* Get the maximum byte length of the mapping.
* The function fails if no file is currently open (associated) with this object.
* @return In case of success, returns the length of the mapping. In case of failure, 0 is returned.
* @see data()
*/
std::streamsize size() const;
private:
/**
* Copy constructor is private: this class is not copyable.
*/
fmstream(const fmstream&);
/**
* Copy operator is private: this class is not copyable.
*/
fmstream& operator=(const fmstream&);
private:
filemappingbuf m_rdbuf; //!< filemappingbuf object
};
#ifdef _HAS_CPP11_
/** @name C++11
* The following methods requires some features introduced by the latest revision of the C++ standard (2011). Older compilers may not support it.
*/
///@{
/**
* Swap two filemappingbuf (requires C++11).
* Overloads the std::swap algorithm for filemappingbuf. Exchanges the state of lhs with that of rhs.
* Effectively calls lhs.swap(rhs).
* @param lhs filemappingbuf to exchange the state with.
* @param rhs filemappingbuf to exchange the state with.
*/
void swap(filemappingbuf& lhs, filemappingbuf& rhs);
/**
* Swap two ifmstream (requires C++11).
* Overloads the std::swap algorithm for ifmstream. Exchanges the state of lhs with that of rhs.
* Effectively calls lhs.swap(rhs).
* @param lhs ifmstream to exchange the state with.
* @param rhs ifmstream to exchange the state with.
*/
void swap(ifmstream& lhs, ifmstream& rhs);
/**
* Swap two fmstream (requires C++11).
* Overloads the std::swap algorithm for fmstream. Exchanges the state of lhs with that of rhs.
* Effectively calls lhs.swap(rhs).
* @param lhs fmstream to exchange the state with.
* @param rhs fmstream to exchange the state with.
*/
void swap(fmstream& lhs, fmstream& rhs);
///@}
#endif // _HAS_CPP11_
#endif /* FILE_MAPPING_STREAM_H_ */
|
[
"r-lyeh"
] |
r-lyeh
|
98613a386173a0a1614f5851ff00684fa65330ee
|
258b680977ededde8716d026e705999b53257f0b
|
/ActorDemo/Actor1/Date.h
|
dff493170105775f5c10a70183b8e04389c26336
|
[] |
no_license
|
EmiPark/ActorDemo
|
5ee040134daf1d3632d06248823ac082b4609c97
|
410055f2ec8cd8aaf059cadd986cb1cc41b11807
|
refs/heads/master
| 2021-06-26T21:22:04.943570
| 2017-09-17T03:36:12
| 2017-09-17T03:36:12
| 103,265,626
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 704
|
h
|
#pragma once
#ifndef _DATE_H_
#define _DATE_H_
class Date
{
public:
Date::Date() {};
Date(int y, int m, int d);
int getYear() const
{
return year;
}
int getMonth() const
{
return month;
}
int getDay() const
{
return day;
}
void setYear(int y)
{
year = y;
}
void setMonth(int m)
{
month = m;
}
void setDay(int d)
{
day = d;
}
private:
int year;
int month;
int day;
};
Date::Date(int y, int m, int d)
{
year = y;
month = m;
day = d;
}
bool operator ==(const Date& d1, const Date& d2)
{
return (d1.getYear() == d2.getYear()) && (d1.getMonth() == d2.getMonth()) && (d1.getDay() == d2.getDay());
}
#endif // !_DATE_H_
|
[
"362308457@qq.com"
] |
362308457@qq.com
|
822db19547b44baa2e05494dc2fbd6eec30d887a
|
5e55f52b4d7c1819a44a6599c6b383afb658d19a
|
/NatsuLib/natCryptography.cpp
|
bd2201e923ef4e80ea335365e2264ca4b9e133b8
|
[] |
no_license
|
akemimadoka/NatsuLib
|
40428d096e5e40d83c33421078871e55d4019871
|
e95ca605c6519220acef3af860bfbc5458f3acb0
|
refs/heads/master
| 2020-04-12T06:38:36.141989
| 2018-11-18T10:02:51
| 2018-11-18T10:02:51
| 61,736,666
| 44
| 2
| null | 2017-03-26T03:01:55
| 2016-06-22T17:02:35
|
C++
|
UTF-8
|
C++
| false
| false
| 16,753
|
cpp
|
#include "stdafx.h"
#include "natCryptography.h"
#include "gzguts.h"
#include <random>
using namespace NatsuLib;
namespace NatsuLib
{
namespace detail_
{
constexpr nuInt Crc32One(const nuInt* crc32Table, nuInt c, nuInt b) noexcept
{
return ((crc32Table[((c ^ b) & 0xff)]) ^ (c >> 8));
}
constexpr nuInt DecryptByte(const nuInt* pKeys) noexcept
{
const auto temp = (pKeys[2] & 0xffff) | 2;
return ((temp * (temp ^ 1)) >> 8) & 0xff;
}
constexpr void UpdateKeys(nuInt* pKeys, const nuInt* crc32Table, nuInt c) noexcept
{
pKeys[0] = Crc32One(crc32Table, pKeys[0], c);
pKeys[1] += pKeys[0] & 0xff;
pKeys[1] = pKeys[1] * 134775813u + 1;
pKeys[2] = Crc32One(crc32Table, pKeys[2], pKeys[1] >> 24);
}
constexpr void InitKeys(ncData password, size_t passwordLength, nuInt* pKeys, const nuInt* crc32Table) noexcept
{
pKeys[0] = 305419896u;
pKeys[1] = 591751049u;
pKeys[2] = 878082192u;
const auto pRead = password;
const auto pEnd = password + passwordLength;
for (const auto item : make_range(pRead, pEnd))
{
UpdateKeys(pKeys, crc32Table, item);
}
}
constexpr nuInt DecodeOne(nuInt* pKeys, const nuInt* crc32Table, nuInt c) noexcept
{
UpdateKeys(pKeys, crc32Table, c ^= DecryptByte(pKeys));
return c;
}
constexpr nuInt EncodeOne(nuInt* pKeys, const nuInt* crc32Table, nuInt c) noexcept
{
const auto t = DecryptByte(pKeys) ^ c;
UpdateKeys(pKeys, crc32Table, c);
return t;
}
// 不检查缓存大小,直接生成,调用者需保证调用时buf的大小不小于PKzipWeakProcessor::HeaderSize
void UncheckedCryptHead(nData buf, nuInt* pKeys, const nuInt* crc32Table, nuInt crcForCrypting) noexcept
{
std::random_device randomDevice;
std::generate_n(buf, PKzipWeakProcessor::HeaderSize - 2, [&]()
{
return static_cast<nByte>(EncodeOne(pKeys, crc32Table, static_cast<nuInt>(randomDevice() & 0xff)));
});
buf[PKzipWeakProcessor::HeaderSize - 2] = static_cast<nByte>(EncodeOne(pKeys, crc32Table, (crcForCrypting >> 16) & 0xff));
buf[PKzipWeakProcessor::HeaderSize - 1] = static_cast<nByte>(EncodeOne(pKeys, crc32Table, (crcForCrypting >> 24) & 0xff));
}
nBool CryptHead(ncData password, size_t passwordLength, nData buf, size_t bufSize, nuInt* pKeys, const nuInt* crc32Table, nuInt crcForCrypting) noexcept
{
if (bufSize < PKzipWeakProcessor::HeaderSize)
{
return false;
}
InitKeys(password, passwordLength, pKeys, crc32Table);
UncheckedCryptHead(buf, pKeys, crc32Table, crcForCrypting);
return true;
}
}
}
ICryptoProcessor::~ICryptoProcessor()
{
}
ICryptoAlgorithm::~ICryptoAlgorithm()
{
}
PKzipWeakProcessor::PKzipWeakProcessor(CryptoType cryptoType)
: m_IsCrypt{ cryptoType == CryptoType::Crypt }
{
}
PKzipWeakProcessor::~PKzipWeakProcessor()
{
}
void PKzipWeakProcessor::InitCipher(ncData password, nLen passwordLength)
{
m_Keys.emplace();
detail_::InitKeys(password, static_cast<size_t>(passwordLength), m_Keys.value().data(), get_crc_table());
}
void PKzipWeakProcessor::InitHeaderFrom(ncData buffer, nLen bufferLength)
{
assert(!m_IsCrypt && "No need to initialize header in crypt mode.");
if (!m_Keys)
{
nat_Throw(natErrException, NatErr_InternalErr, "Keys not initialized."_nv);
}
if (!m_Header)
{
m_Header.emplace();
}
auto& header = m_Header.value();
std::memmove(header.data(), buffer, static_cast<size_t>(bufferLength));
decryptHeader();
}
void PKzipWeakProcessor::InitHeaderFrom(natRefPointer<natStream> const& stream)
{
assert(!m_IsCrypt && "No need to initialize header in crypt mode.");
if (!m_Keys)
{
nat_Throw(natErrException, NatErr_InternalErr, "Keys not initialized."_nv);
}
if (!m_Header)
{
m_Header.emplace();
}
auto& header = m_Header.value();
stream->ReadBytes(header.data(), sizeof header);
decryptHeader();
}
nBool PKzipWeakProcessor::GetHeader(nData buffer, nLen bufferLength)
{
if (!m_IsCrypt || !m_Header || bufferLength < HeaderSize)
{
return false;
}
std::memmove(buffer, m_Header.value().data(), HeaderSize);
m_Header.reset();
return true;
}
nBool PKzipWeakProcessor::CheckHeaderWithCrc32(nuInt crc32) const
{
if (m_IsCrypt)
{
nat_Throw(natErrException, NatErr_IllegalState, "Processor is not in decrypt mode."_nv);
}
if (!m_Header)
{
nat_Throw(natErrException, NatErr_IllegalState, "Header not prepared."_nv);
}
if (!m_Keys)
{
nat_Throw(natErrException, NatErr_IllegalState, "Keys not prepared, header may not be decrypted."_nv);
}
const auto& header = m_Header.value();
return header[HeaderSize - 2] == static_cast<nByte>((crc32 >> 16) & 0xff) && header[HeaderSize - 1] == static_cast<nByte>((crc32 >> 24) & 0xff);
}
void PKzipWeakProcessor::GenerateHeaderWithCrc32(nuInt crc32)
{
if (!m_IsCrypt)
{
nat_Throw(natErrException, NatErr_IllegalState, "Processor is not in crypt mode."_nv);
}
if (!m_Keys)
{
nat_Throw(natErrException, NatErr_IllegalState, "Keys not prepared."_nv);
}
const auto crc32Table = get_crc_table();
m_Header.emplace();
auto& header = m_Header.value();
auto& keys = m_Keys.value();
detail_::UncheckedCryptHead(header.data(), keys.data(), crc32Table, crc32);
}
CryptoType PKzipWeakProcessor::GetCryptoType() const noexcept
{
return m_IsCrypt ? CryptoType::Crypt : CryptoType::Decrypt;
}
nLen PKzipWeakProcessor::GetInputBlockSize() const noexcept
{
return InputBlockSize;
}
nLen PKzipWeakProcessor::GetOutputBlockSize() const noexcept
{
return OutputBlockSize;
}
nBool PKzipWeakProcessor::CanProcessMultiBlocks() const noexcept
{
return true;
}
nBool PKzipWeakProcessor::CanReuseProcessor() const noexcept
{
return true;
}
std::pair<nLen, nLen> PKzipWeakProcessor::Process(ncData inputData, nLen inputDataLength, nData outputData, nLen outputDataLength)
{
if (!m_Keys)
{
nat_Throw(natErrException, NatErr_IllegalState, "Processor has not initialized. (Have you called InitCipher first?)"_nv);
}
if (outputDataLength < inputDataLength)
{
nat_Throw(OutOfRange, "outputData is too small."_nv);
}
uncheckedProcess(inputData, inputDataLength, outputData);
return { inputDataLength, inputDataLength };
}
std::pair<nLen, std::vector<nByte>> PKzipWeakProcessor::ProcessFinal(ncData inputData, nLen inputDataLength)
{
std::vector<nByte> outputBuffer(static_cast<size_t>(inputDataLength));
const auto ret = Process(inputData, inputDataLength, outputBuffer.data(), outputBuffer.size());
m_Keys.reset();
return { ret.first, move(outputBuffer) };
}
void PKzipWeakProcessor::uncheckedProcess(ncData inputData, nLen inputDataLength, nData outputData)
{
assert(m_Keys);
auto keys = m_Keys.value().data();
for (nLen i = 0; i < inputDataLength; ++i)
{
outputData[i] = static_cast<nByte>((m_IsCrypt ? detail_::EncodeOne : detail_::DecodeOne)(keys, get_crc_table(), inputData[i]));
}
}
void PKzipWeakProcessor::decryptHeader()
{
assert(m_Header);
const auto header = m_Header.value().data();
uncheckedProcess(header, HeaderSize, header);
}
natRefPointer<ICryptoProcessor> PKzipWeakAlgorithm::CreateEncryptor()
{
return make_ref<PKzipWeakProcessor>(CryptoType::Crypt);
}
natRefPointer<ICryptoProcessor> PKzipWeakAlgorithm::CreateDecryptor()
{
return make_ref<PKzipWeakProcessor>(CryptoType::Decrypt);
}
natCryptoStream::natCryptoStream(natRefPointer<natStream> stream, natRefPointer<ICryptoProcessor> cryptoProcessor, CryptoStreamMode mode)
: natRefObjImpl{ std::move(stream) },
m_Processor{ std::move(cryptoProcessor) },
m_InputBlockSize{ static_cast<size_t>(m_Processor->GetInputBlockSize()) }, m_OutputBlockSize{ static_cast<size_t>(m_Processor->GetOutputBlockSize()) },
m_IsReadMode{ mode == CryptoStreamMode::Read },
m_InputBufferSize{}, m_OutputBufferSize{},
m_InputBuffer(m_InputBlockSize), m_OutputBuffer(m_OutputBlockSize),
m_FinalBlockProcessed{ false }
{
if (!m_InternalStream)
{
nat_Throw(natErrException, NatErr_InvalidArg, "stream is nullptr."_nv);
}
if (!m_Processor)
{
nat_Throw(natErrException, NatErr_InvalidArg, "cryptoProcessor is nullptr."_nv);
}
if (m_IsReadMode && !m_InternalStream->CanRead())
{
nat_Throw(natErrException, NatErr_InvalidArg, "stream should be readable in read mode."_nv);
}
if (!m_IsReadMode && !m_InternalStream->CanWrite())
{
nat_Throw(natErrException, NatErr_InvalidArg, "stream should be writable in write mode."_nv);
}
}
natCryptoStream::~natCryptoStream()
{
if (!m_FinalBlockProcessed)
{
FlushFinalBlock();
}
}
natRefPointer<ICryptoProcessor> natCryptoStream::GetProcessor() const noexcept
{
return m_Processor;
}
nBool natCryptoStream::CanWrite() const
{
return !m_IsReadMode;
}
nBool natCryptoStream::CanRead() const
{
return m_IsReadMode;
}
nBool natCryptoStream::CanResize() const
{
return false;
}
nBool natCryptoStream::CanSeek() const
{
return false;
}
nLen natCryptoStream::GetSize() const
{
nat_Throw(natErrException, NatErr_NotSupport, "The type of this stream does not support this operation."_nv);
}
void natCryptoStream::SetSize(nLen Size)
{
nat_Throw(natErrException, NatErr_NotSupport, "The type of this stream does not support this operation."_nv);
}
nLen natCryptoStream::GetPosition() const
{
nat_Throw(natErrException, NatErr_NotSupport, "The type of this stream does not support this operation."_nv);
}
void natCryptoStream::SetPosition(NatSeek, nLong)
{
nat_Throw(natErrException, NatErr_NotSupport, "The type of this stream does not support this operation."_nv);
}
nLen natCryptoStream::ReadBytes(nData pData, nLen Length)
{
if (!m_IsReadMode)
{
nat_Throw(natErrException, NatErr_IllegalState, "This stream cannot be read."_nv);
}
auto bytesToRead = static_cast<size_t>(Length);
auto pWrite = pData;
if (m_OutputBufferSize)
{
if (m_OutputBufferSize < bytesToRead)
{
std::memmove(pWrite, m_OutputBuffer.data(), m_OutputBufferSize);
bytesToRead -= m_OutputBufferSize;
pWrite += m_OutputBufferSize;
m_OutputBufferSize = 0;
}
else
{
std::memmove(pWrite, m_OutputBuffer.data(), bytesToRead);
std::memmove(m_OutputBuffer.data(), m_OutputBuffer.data() + bytesToRead, m_OutputBufferSize - bytesToRead);
m_OutputBufferSize -= bytesToRead;
return bytesToRead;
}
}
if (m_FinalBlockProcessed)
{
return Length - bytesToRead;
}
nLen amountRead;
nLen outputBytes;
if (bytesToRead > m_OutputBlockSize)
{
if (m_Processor->CanProcessMultiBlocks())
{
const auto blocksToProcess = bytesToRead / m_OutputBlockSize;
const auto inputSize = static_cast<size_t>(blocksToProcess * m_InputBlockSize);
std::vector<nByte> tmpInputBuffer(inputSize);
std::memmove(tmpInputBuffer.data(), m_InputBuffer.data(), m_InputBufferSize);
amountRead = m_InputBufferSize;
amountRead += m_InternalStream->ReadBytes(tmpInputBuffer.data() + m_InputBufferSize, inputSize - m_InputBufferSize);
m_InputBufferSize = 0;
if (amountRead <= m_InputBlockSize)
{
m_InputBuffer = move(tmpInputBuffer);
m_InputBufferSize = static_cast<size_t>(amountRead);
goto Normal;
}
const auto totalInputSize = amountRead - amountRead % m_InputBlockSize;
const auto ignoredBytes = amountRead - totalInputSize;
if (ignoredBytes)
{
std::memmove(m_InputBuffer.data(), tmpInputBuffer.data() + totalInputSize, static_cast<size_t>(ignoredBytes));
m_InputBufferSize = static_cast<size_t>(ignoredBytes);
}
std::vector<nByte> tmpOutputBuffer(static_cast<size_t>(totalInputSize / m_InputBlockSize * m_OutputBlockSize));
tie(std::ignore, outputBytes) = m_Processor->Process(tmpInputBuffer.data(), totalInputSize, tmpOutputBuffer.data(), tmpOutputBuffer.size());
std::memmove(pWrite, tmpOutputBuffer.data(), static_cast<size_t>(outputBytes));
bytesToRead -= static_cast<size_t>(outputBytes);
pWrite += outputBytes;
}
}
Normal:
while (bytesToRead)
{
while (m_InputBufferSize < m_InputBlockSize)
{
amountRead = m_InternalStream->ReadBytes(m_InputBuffer.data() + m_InputBufferSize, m_InputBlockSize - m_InputBufferSize);
if (!amountRead || m_InternalStream->IsEndOfStream())
{
goto ProcessFinalBlock;
}
m_InputBufferSize += static_cast<size_t>(amountRead);
}
tie(std::ignore, outputBytes) = m_Processor->Process(m_InputBuffer.data(), m_InputBlockSize, m_OutputBuffer.data(), m_OutputBuffer.size());
m_InputBufferSize = 0;
if (bytesToRead >= outputBytes)
{
std::memmove(pWrite, m_OutputBuffer.data(), static_cast<size_t>(outputBytes));
bytesToRead -= static_cast<size_t>(outputBytes);
pWrite += outputBytes;
}
else
{
std::memmove(pWrite, m_OutputBuffer.data(), static_cast<size_t>(bytesToRead));
m_OutputBufferSize -= static_cast<size_t>(outputBytes - bytesToRead);
std::memmove(m_OutputBuffer.data(), m_OutputBuffer.data() + bytesToRead, m_OutputBufferSize);
return Length;
}
}
return Length;
ProcessFinalBlock:
tie(std::ignore, m_OutputBuffer) = m_Processor->ProcessFinal(m_InputBuffer.data(), m_InputBufferSize);
m_OutputBufferSize = m_OutputBuffer.size();
m_FinalBlockProcessed = true;
if (bytesToRead < m_OutputBufferSize)
{
std::memmove(pWrite, m_OutputBuffer.data(), static_cast<size_t>(bytesToRead));
m_OutputBufferSize -= static_cast<size_t>(bytesToRead);
std::memmove(m_OutputBuffer.data(), m_OutputBuffer.data() + bytesToRead, m_OutputBufferSize);
return Length;
}
std::memmove(pWrite, m_OutputBuffer.data(), m_OutputBufferSize);
bytesToRead -= m_OutputBufferSize;
m_OutputBufferSize = 0;
return Length - bytesToRead;
}
nLen natCryptoStream::WriteBytes(ncData pData, nLen Length)
{
assert(!m_InputBufferSize || m_InputBlockSize <= m_InputBufferSize);
if (m_IsReadMode)
{
nat_Throw(natErrException, NatErr_IllegalState, "This stream cannot be written."_nv);
}
auto bytesToWrite = Length;
auto pRead = pData;
if (m_InputBufferSize)
{
if (bytesToWrite > m_InputBlockSize - m_InputBufferSize)
{
const auto needBytes = m_InputBlockSize - m_InputBufferSize;
std::memmove(m_InputBuffer.data() + m_InputBufferSize, pRead, needBytes);
pRead += needBytes;
bytesToWrite -= needBytes;
}
else
{
std::memmove(m_InputBuffer.data() + m_InputBufferSize, pRead, static_cast<size_t>(bytesToWrite));
m_InputBufferSize += static_cast<size_t>(bytesToWrite);
return bytesToWrite;
}
}
nLen writtenBytes = 0, currentWrittenBytes;
if (m_OutputBufferSize)
{
writtenBytes += m_InternalStream->WriteBytes(m_OutputBuffer.data(), m_OutputBufferSize);
m_OutputBufferSize = 0;
}
if (m_InputBlockSize == m_InputBufferSize)
{
tie(std::ignore, currentWrittenBytes) = m_Processor->Process(m_InputBuffer.data(), m_InputBlockSize, m_OutputBuffer.data(), m_OutputBuffer.size());
writtenBytes += m_InternalStream->WriteBytes(m_OutputBuffer.data(), currentWrittenBytes);
m_InputBufferSize = 0;
}
const auto canProcessMultiBlocks = m_Processor->CanProcessMultiBlocks();
while (bytesToWrite)
{
if (bytesToWrite > m_InputBlockSize)
{
if (canProcessMultiBlocks)
{
const auto blocksToProcess = bytesToWrite / m_InputBlockSize;
const auto inputSize = blocksToProcess * m_InputBlockSize;
std::vector<nByte> tmpOutputBuffer(static_cast<size_t>(blocksToProcess * m_OutputBlockSize));
tie(std::ignore, currentWrittenBytes) = m_Processor->Process(pRead, inputSize, tmpOutputBuffer.data(), tmpOutputBuffer.size());
writtenBytes += m_InternalStream->WriteBytes(tmpOutputBuffer.data(), currentWrittenBytes);
pRead += inputSize;
bytesToWrite -= inputSize;
}
else
{
tie(std::ignore, currentWrittenBytes) = m_Processor->Process(pRead, m_InputBlockSize, m_OutputBuffer.data(), m_OutputBuffer.size());
writtenBytes += m_InternalStream->WriteBytes(m_OutputBuffer.data(), currentWrittenBytes);
pRead += m_InputBlockSize;
bytesToWrite -= m_InputBlockSize;
}
}
else
{
std::memmove(m_InputBuffer.data(), pRead, static_cast<size_t>(bytesToWrite));
m_InputBufferSize += static_cast<size_t>(bytesToWrite);
break;
}
}
return writtenBytes;
}
void natCryptoStream::FlushFinalBlock()
{
if (m_FinalBlockProcessed)
{
nat_Throw(natErrException, NatErr_IllegalState, "Final block has been processed."_nv);
}
const auto finalBytes = m_Processor->ProcessFinal(m_InputBuffer.data(), m_InputBufferSize).second;
m_FinalBlockProcessed = true;
if (!m_IsReadMode)
{
if (m_OutputBufferSize)
{
m_InternalStream->WriteBytes(m_OutputBuffer.data(), m_OutputBufferSize);
m_OutputBufferSize = 0;
}
m_InternalStream->WriteBytes(finalBytes.data(), finalBytes.size());
}
const auto innerCryptoStream = m_InternalStream.Cast<natCryptoStream>();
if (innerCryptoStream)
{
if (!innerCryptoStream->m_FinalBlockProcessed)
{
innerCryptoStream->FlushFinalBlock();
}
}
else
{
m_InternalStream->Flush();
}
}
|
[
"jxhzq1996@126.com"
] |
jxhzq1996@126.com
|
fbc852048916ca37eeb2d163a72993ea3e31c7cb
|
40e326893d52d8741630e1d3176d24207bd8e1d3
|
/matcher.cpp
|
f5cedfce458505f472f3b8c9ed56c67ee920a0f6
|
[] |
no_license
|
zinglax/dylan-openCV
|
372f88f60b8bd371783b8388e0111d0d98c6a98f
|
9a2d4f43085769c3fb182f636ba5ebcdcb8a14b3
|
refs/heads/master
| 2021-01-22T06:54:31.552675
| 2014-10-06T01:14:58
| 2014-10-06T01:14:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 925
|
cpp
|
#include "opencv2/core/core.hpp"
Mat img1 = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE);
Mat img2 = imread(argv[2], CV_LOAD_IMAGE_GRAYSCALE);
if(img1.empty() || img2.empty())
{
printf("Can't read one of the images\n");
return -1;
}
// detecting keypoints
SurfFeatureDetector detector(400);
vector<KeyPoint> keypoints1, keypoints2;
detector.detect(img1, keypoints1);
detector.detect(img2, keypoints2);
// computing descriptors
SurfDescriptorExtractor extractor;
Mat descriptors1, descriptors2;
extractor.compute(img1, keypoints1, descriptors1);
extractor.compute(img2, keypoints2, descriptors2);
// matching descriptors
BruteForceMatcher<L2<float> > matcher;
vector<DMatch> matches;
matcher.match(descriptors1, descriptors2, matches);
// drawing the results
namedWindow("matches", 1);
Mat img_matches;
drawMatches(img1, keypoints1, img2, keypoints2, matches, img_matches);
imshow("matches", img_matches);
waitKey(0);
|
[
"dylanzingler@gmail.com"
] |
dylanzingler@gmail.com
|
f70d4e94e953b24add8959f8ba066071fc1f38a0
|
1e59bd4634b0eae8de5fa55fd29ced21e7054dab
|
/server/tcpserver.hpp
|
90616b8eb71a28bf78a4cde6ccfabfccf18a3663
|
[
"MIT"
] |
permissive
|
KeltorHD/Client-Server-Application-Design-Patterns-Teaching
|
472528210d275347812e9ddb40e58977983c9aba
|
7461234f828ebfa900366f5a5f965b4aa0d02ce6
|
refs/heads/main
| 2023-05-09T02:00:28.590666
| 2021-05-12T10:18:19
| 2021-05-12T10:18:19
| 359,933,510
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,225
|
hpp
|
#pragma once
#pragma comment(lib, "ws2_32.lib")
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include <Winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <functional>
#include <thread>
#include <mutex>
#include <list>
#include <string>
#include <vector>
#include <algorithm>
class TCPServer
{
public:
class TCPClient;
TCPServer(unsigned port, std::function<void(TCPClient&)> callback);
~TCPServer();
void start();
private:
unsigned port;
SOCKET S; //дескриптор прослушивающего сокета
SOCKET NS;
sockaddr_in serv_addr;
WSADATA wsadata;
std::function<void(TCPClient&)> callback;
std::list<std::thread> threads;
std::list<std::shared_ptr<TCPClient>> clients;
std::mutex print_mutex;
std::mutex vec_mutex;
std::vector<size_t> del;
void client_loop(std::shared_ptr<TCPClient> client);
};
class TCPServer::TCPClient
{
public:
TCPClient(SOCKET S, sockaddr_in cli_addr);
~TCPClient();
const std::string& get_data();
void send_data(const std::string& text);
friend class TCPServer;
private:
SOCKET S; //сокет клиента
sockaddr_in cli_addr;
std::string data;
const std::string& get_data(bool& err);
};
|
[
"keltorplaylife@gmail.com"
] |
keltorplaylife@gmail.com
|
0beb07aadc5150d444d1146bc80f206beaa43a23
|
93e87a15e6a3f249179b8e700b54ebdbb47c3bb7
|
/SerialRelais16.h
|
eecc10d1225f88c93189156d6331367c8e3e8e9c
|
[] |
no_license
|
sylvainpasquiet/FilPilote
|
3cbff87aa6470414331007a62a4455c2931c44ec
|
1e41a819b4de960e089750a24e4cacf83e38624c
|
refs/heads/master
| 2020-04-14T13:00:41.913932
| 2019-01-12T14:14:25
| 2019-01-12T14:14:25
| 163,856,966
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 517
|
h
|
#ifndef SerialRelais16_h
#define SerialRelais16_h
#include "Arduino.h"
enum EtatRelai {
INCONNU,
OUVERT,
FERME
};
class SERIAL_RELAIS_16
{
public:
SERIAL_RELAIS_16(int _latchPin,int _dataPin,int _clockPin);
EtatRelai GetRelai(char index);
void SetRelai(char index,EtatRelai Valeur);
void SetAllRelai(EtatRelai Valeur);
void Refresh();
private:
EtatRelai Relais[16];
int latchPin;
int dataPin;
int clockPin;
};
#endif
|
[
"sylvain.pasquiet80@gmail.com"
] |
sylvain.pasquiet80@gmail.com
|
fda39371509dfc674e6e446c81822d015ed949ac
|
ca1400d67b5c38c440f188da7628252618430d40
|
/QuickSearch/searchManage.cpp
|
953bd3da73d8ebfa8a27882184de69dff01b1210
|
[] |
no_license
|
ykerit/QuickSearch
|
638231a246bf018e2aea79fa1e894ca9659be56a
|
e82d0deb5849cb515a441cb91434adbb8d6a9516
|
refs/heads/master
| 2020-06-26T01:15:16.147554
| 2019-07-29T15:30:33
| 2019-07-29T15:30:33
| 199,478,950
| 1
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 5,952
|
cpp
|
#include "searchManage.h"
namespace quicksearch
{
using namespace util;
// 监控间隔
#define INTERVAL 10
void SearchManage::InitSearch()
{
// 初始化数据库
db_ = new DataBase("record.db");
db_->Init();
// 初始化USN日志
usn_ = new UsnManage("E:");
usn_->Init();
std::thread work(&SearchManage::BGDataService, this);
work.detach();
}
void SearchManage::Search()
{
while (true)
{
std::string input;
std::cout << "请输入想搜索的文件或目录" << std::endl;
std::cin >> input;
std::string pinyin = Util::ChineseConvertPy(input);
std::string pinyinAbbr = Util::ChineseConvertPyAbbre(input);
std::vector<FRInfo> result;
db_->QueryRecord(pinyin, pinyinAbbr, result);
displayResult(result, input, pinyin, pinyinAbbr);
}
}
void SearchManage::stopBGDataService()
{
isShutDown_ = true;
}
// 文件系统监控
void SearchManage::BGDataService()
{
// 第一次检索
if (db_->isEmpty())
{
usn_->GetRecord(records_);
// 之后批量插入
db_->BatchInsert(records_);
}
else
{
while (!isShutDown_)
{
// 检查文件系统变化
std::vector<util::ChangeInfo> record;
usn_->ChangeRecord(record);
// 获取后对数据库更新
if (!record.empty())
{
updateDB(record);
}
std::this_thread::sleep_for(std::chrono::seconds(INTERVAL));
}
}
}
void SearchManage::displayResult(const std::vector<FRInfo>& result,
std::string& input,
std::string& pinyin,
std::string& pinyinAbbr)
{
int pos;
for (auto& res : result)
{
std::string filename = res.filename_;
int len = filename.size();
// 如果直接模糊匹配 直接找到字串高亮;
if ((pos = res.filename_.find(input)) != std::string::npos)
{
std::cout << filename.substr(0, pos);
Util::HighLight(filename.substr(pos, input.size()).c_str());
std::cout << filename.substr(pos + input.size()) << std::endl;
std::cout << " ";
std::cout << res.path_ << std::endl;
}
else
{
// 如果是全拼或者拼音首字母
// 先转拼音和首字母
std::string pinyinR = Util::ChineseConvertPy(res.filename_);
std::string pinyinAbbrR = Util::ChineseConvertPyAbbre(res.filename_);
if ((pos = pinyinR.find(pinyin)) != std::string::npos)
{
int count = 0;
// 前缀
int i;
for (i = 0; i < len;)
{
// 如果头部就是找到的, 就没有前缀
if (count == pos)
{
break;
}
// 如果是字母
if (filename[i] >= 0 && filename[i] <= 128)
{
++i;
count++;
continue;
}
// 如果是汉字
std::string temp; // 保存单个汉字
temp.push_back(filename[i]);
temp.push_back(filename[i + 1]);
temp = Util::ChineseConvertPy(temp);
count += temp.size(); // 拼音长度
i += 2;
if (count >= pos)
{
break;
}
}
int j;
count = 0;
// 高亮部分
for (j = i; j < len;)
{
if (filename[j] >= 0 && filename[j] <= 128)
{
++j;
count++;
continue;
}
// 如果是汉字
std::string temp; // 保存单个汉字
temp.push_back(filename[j]);
temp.push_back(filename[j + 1]);
temp = Util::ChineseConvertPy(temp);
count += temp.size(); // 拼音长度
j += 2;
if (count == pinyin.size())
{
break;
}
}
// 输出
std::cout << filename.substr(0, i);
Util::HighLight(filename.substr(i, j - i).c_str());
std::cout << filename.substr(j);
//std::cout << " ";
printf("%50s\n", res.path_.c_str());
// std::cout << res.path_ << std::endl;
std::cout << std::endl;
}
else if ((pos = pinyinAbbrR.find(pinyinAbbr)) != std::string::npos) // 首字母
{
int count = 0;
// 前缀
int i;
for (i = 0; i < len;)
{
// 如果头部就是找到的, 就没有前缀
if (count == pos)
{
break;
}
// 如果是字母
if (filename[i] >= 0 && filename[i] <= 128)
{
++i;
count++;
continue;
}
// 如果是汉字
std::string temp; // 保存单个汉字
temp.push_back(filename[i]);
temp.push_back(filename[i + 1]);
temp = Util::ChineseConvertPyAbbre(temp);
count += temp.size(); // 拼音长度
i += 2;
if (count >= pos)
{
break;
}
}
int j;
count = 0;
// 高亮部分
for (j = i; j < len;)
{
if (filename[j] >= 0 && filename[j] <= 128)
{
++j;
count++;
continue;
}
// 如果是汉字
std::string temp; // 保存单个汉字
temp.push_back(filename[j]);
temp.push_back(filename[j + 1]);
temp = Util::ChineseConvertPyAbbre(temp);
count += temp.size(); // 拼音长度
j += 2;
if (count == pinyin.size())
{
break;
}
}
// 输出
std::cout << filename.substr(0, i);
Util::HighLight(filename.substr(i, j - i).c_str());
std::cout << filename.substr(j);
/*std::cout << " ";
std::cout << res.path_ << std::endl;*/
printf("%50s\n", res.path_.c_str());
std::cout << std::endl;
}
}
}
}
void SearchManage::updateDB(std::vector<util::ChangeInfo>& record)
{
for (auto& e : record)
{
// 如果文件不存在了 删除文件
if (!e.isExist_ && e.oldName_.size() > 0)
{
db_->DelRecord(e.oldName_);
}
else
{
// 新创建文件
if (e.isNew_)
{
FRInfo info;
info.filename_ = e.filename_;
info.path_ = e.path_;
info.py_ = Util::ChineseConvertPy(e.filename_);
info.py_Abbreviation_ = Util::ChineseConvertPyAbbre(e.filename_);
db_->insert(info);
}
// 更名
else if (e.oldName_ != e.newName_)
{
db_->UpdateRecord(e);
}
}
}
}
}
|
[
"ykerforit@gmail.com"
] |
ykerforit@gmail.com
|
8bb8779e78080001124b2babb5975022cbe25a10
|
c5980a4b6317c499f871fdfd9a40ce030c0c53bc
|
/devel/include/geographic_msgs/UpdateGeographicMapRequest.h
|
b2c16745b198c1d16e3b7b588bdbcd215ff99391
|
[] |
no_license
|
lizhiwei0304/udp_comm
|
28475a66e599375ed54a203f7679ad48842a4201
|
5490e1e84be13a1e98fc7589f56ae8925731d432
|
refs/heads/master
| 2022-11-09T12:05:01.963363
| 2020-06-23T14:59:33
| 2020-06-23T14:59:33
| 274,434,920
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,558
|
h
|
// Generated by gencpp from file geographic_msgs/UpdateGeographicMapRequest.msg
// DO NOT EDIT!
#ifndef GEOGRAPHIC_MSGS_MESSAGE_UPDATEGEOGRAPHICMAPREQUEST_H
#define GEOGRAPHIC_MSGS_MESSAGE_UPDATEGEOGRAPHICMAPREQUEST_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
#include <geographic_msgs/GeographicMapChanges.h>
namespace geographic_msgs
{
template <class ContainerAllocator>
struct UpdateGeographicMapRequest_
{
typedef UpdateGeographicMapRequest_<ContainerAllocator> Type;
UpdateGeographicMapRequest_()
: updates() {
}
UpdateGeographicMapRequest_(const ContainerAllocator& _alloc)
: updates(_alloc) {
(void)_alloc;
}
typedef ::geographic_msgs::GeographicMapChanges_<ContainerAllocator> _updates_type;
_updates_type updates;
typedef boost::shared_ptr< ::geographic_msgs::UpdateGeographicMapRequest_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::geographic_msgs::UpdateGeographicMapRequest_<ContainerAllocator> const> ConstPtr;
}; // struct UpdateGeographicMapRequest_
typedef ::geographic_msgs::UpdateGeographicMapRequest_<std::allocator<void> > UpdateGeographicMapRequest;
typedef boost::shared_ptr< ::geographic_msgs::UpdateGeographicMapRequest > UpdateGeographicMapRequestPtr;
typedef boost::shared_ptr< ::geographic_msgs::UpdateGeographicMapRequest const> UpdateGeographicMapRequestConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::geographic_msgs::UpdateGeographicMapRequest_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::geographic_msgs::UpdateGeographicMapRequest_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace geographic_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'geographic_msgs': ['/home/lizhiwei/Desktop/udp_comm/src/msgs/geographic_msgs/msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'uuid_msgs': ['/home/lizhiwei/Desktop/udp_comm/src/msgs/uuid_msgs/msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::geographic_msgs::UpdateGeographicMapRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::geographic_msgs::UpdateGeographicMapRequest_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::geographic_msgs::UpdateGeographicMapRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::geographic_msgs::UpdateGeographicMapRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::geographic_msgs::UpdateGeographicMapRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::geographic_msgs::UpdateGeographicMapRequest_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::geographic_msgs::UpdateGeographicMapRequest_<ContainerAllocator> >
{
static const char* value()
{
return "8d8da723a1fadc5f7621a18b4e72fc3b";
}
static const char* value(const ::geographic_msgs::UpdateGeographicMapRequest_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x8d8da723a1fadc5fULL;
static const uint64_t static_value2 = 0x7621a18b4e72fc3bULL;
};
template<class ContainerAllocator>
struct DataType< ::geographic_msgs::UpdateGeographicMapRequest_<ContainerAllocator> >
{
static const char* value()
{
return "geographic_msgs/UpdateGeographicMapRequest";
}
static const char* value(const ::geographic_msgs::UpdateGeographicMapRequest_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::geographic_msgs::UpdateGeographicMapRequest_<ContainerAllocator> >
{
static const char* value()
{
return "\n\
\n\
\n\
GeographicMapChanges updates\n\
\n\
\n\
================================================================================\n\
MSG: geographic_msgs/GeographicMapChanges\n\
# A list of geographic map changes.\n\
\n\
Header header # stamp specifies time of change\n\
# frame_id (normally /map)\n\
\n\
GeographicMap diffs # new and changed points and features\n\
uuid_msgs/UniqueID[] deletes # deleted map components\n\
\n\
================================================================================\n\
MSG: std_msgs/Header\n\
# Standard metadata for higher-level stamped data types.\n\
# This is generally used to communicate timestamped data \n\
# in a particular coordinate frame.\n\
# \n\
# sequence ID: consecutively increasing ID \n\
uint32 seq\n\
#Two-integer timestamp that is expressed as:\n\
# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\
# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\
# time-handling sugar is provided by the client library\n\
time stamp\n\
#Frame this data is associated with\n\
# 0: no frame\n\
# 1: global frame\n\
string frame_id\n\
\n\
================================================================================\n\
MSG: geographic_msgs/GeographicMap\n\
# Geographic map for a specified region.\n\
\n\
Header header # stamp specifies time\n\
# frame_id (normally /map)\n\
\n\
uuid_msgs/UniqueID id # identifier for this map\n\
BoundingBox bounds # 2D bounding box containing map\n\
\n\
WayPoint[] points # way-points\n\
MapFeature[] features # map features\n\
KeyValue[] props # map properties\n\
\n\
================================================================================\n\
MSG: uuid_msgs/UniqueID\n\
# A universally unique identifier (UUID).\n\
#\n\
# http://en.wikipedia.org/wiki/Universally_unique_identifier\n\
# http://tools.ietf.org/html/rfc4122.html\n\
\n\
uint8[16] uuid\n\
\n\
================================================================================\n\
MSG: geographic_msgs/BoundingBox\n\
# Geographic map bounding box. \n\
#\n\
# The two GeoPoints denote diagonally opposite corners of the box.\n\
#\n\
# If min_pt.latitude is NaN, the bounding box is \"global\", matching\n\
# any valid latitude, longitude and altitude.\n\
#\n\
# If min_pt.altitude is NaN, the bounding box is two-dimensional and\n\
# matches any altitude within the specified latitude and longitude\n\
# range.\n\
\n\
GeoPoint min_pt # lowest and most Southwestern corner\n\
GeoPoint max_pt # highest and most Northeastern corner\n\
\n\
================================================================================\n\
MSG: geographic_msgs/GeoPoint\n\
# Geographic point, using the WGS 84 reference ellipsoid.\n\
\n\
# Latitude [degrees]. Positive is north of equator; negative is south\n\
# (-90 <= latitude <= +90).\n\
float64 latitude\n\
\n\
# Longitude [degrees]. Positive is east of prime meridian; negative is\n\
# west (-180 <= longitude <= +180). At the poles, latitude is -90 or\n\
# +90, and longitude is irrelevant, but must be in range.\n\
float64 longitude\n\
\n\
# Altitude [m]. Positive is above the WGS 84 ellipsoid (NaN if unspecified).\n\
float64 altitude\n\
\n\
================================================================================\n\
MSG: geographic_msgs/WayPoint\n\
# Way-point element for a geographic map.\n\
\n\
uuid_msgs/UniqueID id # Unique way-point identifier\n\
GeoPoint position # Position relative to WGS 84 ellipsoid\n\
KeyValue[] props # Key/value properties for this point\n\
\n\
================================================================================\n\
MSG: geographic_msgs/KeyValue\n\
# Geographic map tag (key, value) pair\n\
#\n\
# This is equivalent to diagnostic_msgs/KeyValue, repeated here to\n\
# avoid introducing a trivial stack dependency.\n\
\n\
string key # tag label\n\
string value # corresponding value\n\
\n\
================================================================================\n\
MSG: geographic_msgs/MapFeature\n\
# Geographic map feature.\n\
#\n\
# A list of WayPoint IDs for features like streets, highways, hiking\n\
# trails, the outlines of buildings and parking lots in sequential\n\
# order.\n\
#\n\
# Feature lists may also contain other feature lists as members.\n\
\n\
uuid_msgs/UniqueID id # Unique feature identifier\n\
uuid_msgs/UniqueID[] components # Sequence of feature components\n\
KeyValue[] props # Key/value properties for this feature\n\
";
}
static const char* value(const ::geographic_msgs::UpdateGeographicMapRequest_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::geographic_msgs::UpdateGeographicMapRequest_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.updates);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct UpdateGeographicMapRequest_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::geographic_msgs::UpdateGeographicMapRequest_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::geographic_msgs::UpdateGeographicMapRequest_<ContainerAllocator>& v)
{
s << indent << "updates: ";
s << std::endl;
Printer< ::geographic_msgs::GeographicMapChanges_<ContainerAllocator> >::stream(s, indent + " ", v.updates);
}
};
} // namespace message_operations
} // namespace ros
#endif // GEOGRAPHIC_MSGS_MESSAGE_UPDATEGEOGRAPHICMAPREQUEST_H
|
[
"lizw_0304@163.com"
] |
lizw_0304@163.com
|
5c24def8b3a47376cd9342d14b8f3009e2474cff
|
c9c27f4c1595c5d1d9ad433765be15899afc394f
|
/src/macierzC.cpp
|
528a2eb369c38937518ee8dc5d5c805a4eac7519
|
[] |
no_license
|
filip452/dron
|
a9ae1d12ac84db50305529201b3b52b14a61f465
|
f1f84a8f0b4434e8b7ca21297800891a4bd51161
|
refs/heads/master
| 2022-10-13T14:41:35.193609
| 2020-06-08T09:21:13
| 2020-06-08T09:21:13
| 263,037,454
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 301
|
cpp
|
#include "macierz.cpp"
template class macierz<double,3>;
template std::istream & operator>>(std::istream & strm,macierz<double,3> & M);
template std::ostream & operator<<(std::ostream & strm, const macierz<double,3> & M);
template macierz<double,3> operator*(double l2,const macierz<double,3> & M);
|
[
"253983@student.pwr.edu.pl"
] |
253983@student.pwr.edu.pl
|
ae4428879968469801ce4ba181c44f8042b34705
|
909b6b8e930b01f0fb8e2cc74f4e061da18552e0
|
/raygame/Game.cpp
|
4b0a05c5c2b519e9f93495b5e53da06ec73bca5e
|
[
"MIT"
] |
permissive
|
SamuelDaman/Custom-Phys-Assessment-Cpp
|
70014f4833a6d3e917428da5b0273420666dac65
|
41d69d9963398be6983474e2b7fff610f333241c
|
refs/heads/master
| 2022-12-12T14:26:40.079486
| 2020-09-17T05:15:15
| 2020-09-17T05:15:15
| 294,776,159
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,997
|
cpp
|
#include "Game.h"
#include <iostream>
#include <ctime>
#include <cstdlib>
#include "Raylib.h"
#include "enumUtils.h"
collisionMap setupCollisionChecks()
{
collisionMap map;
map[(collisionPair)(ShapeType::CIRCLE | ShapeType::CIRCLE)] = checkCircleCircle;
map[(collisionPair)(ShapeType::CIRCLE | ShapeType::AABB)] = checkCircleBox;
map[(collisionPair)(ShapeType::AABB | ShapeType::AABB)] = checkBoxBox;
return map;
}
depenetrationMap setupDepenetrationFuncs()
{
depenetrationMap map;
map[(collisionPair)(ShapeType::CIRCLE | ShapeType::CIRCLE)] = depenetrateCircleCircle;
map[(collisionPair)(ShapeType::CIRCLE | ShapeType::AABB)] = depenetrateCircleBox;
map[(collisionPair)(ShapeType::AABB | ShapeType::AABB)] = depenetrateBoxBox;
return map;
}
collisionMap Game::collisionCheckers = setupCollisionChecks();
depenetrationMap Game::depenetrationFuncs = setupDepenetrationFuncs();
Game::Game()
{
accumulatedDeltaTime = 0.0f;
fixedTimeStep = 1.0f / 30.0f;
srand(time(0));
}
void Game::init()
{
int screenWidth = 800;
int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - basic window");
SetTargetFPS(60);
}
bool Game::tick()
{
accumulatedDeltaTime += GetFrameTime();
if (IsMouseButtonPressed(0))
{
auto cursorPos = GetMousePosition();
PhysObject spawn;
spawn.pos = { cursorPos.x, cursorPos.y };
spawn.mass = (rand() % 10) + 5;
if (rand() % 2 == 0)
{
spawn.shape.circleData.radius = spawn.mass + 4;
}
else
{
spawn.shape.colliderShape = ShapeType::AABB;
spawn.shape.boxData.bounds = { spawn.mass + 4, spawn.mass + 4 };
}
spawn.addImpulse({ (rand() % 501) - 250, (rand() % 501) - 250 });
PhysObjects.push_back(spawn);
}
if (IsMouseButtonPressed(1))
{
auto cursorPos = GetMousePosition();
for (auto& obj : PhysObjects)
{
auto * object = &obj;
if (glm::length(vec2(cursorPos.x, cursorPos.y) - object->pos) < 100)
{
obj.addImpulse(glm::normalize(object->pos - vec2(cursorPos.x, cursorPos.y)) * 5000.0f);
}
}
}
return !WindowShouldClose();
}
void Game::tickPhysics()
{
accumulatedDeltaTime -= fixedTimeStep;
for (auto& obj : PhysObjects)
{
obj.addAccel(vec2(0, 98));
glm::clamp(obj.vel.x, -10.0f, 10.0f);
glm::clamp(obj.vel.y, -10.0f, 10.0f);
}
for (auto& lhs : PhysObjects)
{
for (auto& rhs : PhysObjects)
{
if (&lhs == &rhs) { continue; }
auto * first = &lhs;
auto * second = &rhs;
if (static_cast<uint8_t>(lhs.shape.colliderShape) > static_cast<uint8_t>(rhs.shape.colliderShape))
{
first = &rhs;
second = &lhs;
}
collisionPair pairType = (collisionPair)(lhs.shape.colliderShape | rhs.shape.colliderShape);
bool collision = collisionCheckers[pairType](first->pos, first->shape, second->pos, second->shape);
if (collision)
{
float pen = 0.0f;
vec2 normal = depenetrationFuncs[pairType](first->pos, first->shape, second->pos, second->shape, pen);
vec2 resImpulses[2];
resolveCollision(first->pos, first->vel, first->mass, second->pos, second->vel, second->mass, 1.0f, normal, resImpulses);
first->pos += normal * pen;
second->pos -= normal * pen;
first->vel = resImpulses[0];
second->vel = resImpulses[1];
}
}
}
for (auto& obj : PhysObjects)
{
obj.tickPhysics(fixedTimeStep);
}
for (auto& obj : PhysObjects)
{
auto * object = &obj;
int scrWidth = GetScreenWidth();
int scrHeight = GetScreenHeight();
if (object->pos.x < -10)
{
object->pos.x = scrWidth + 10;
}
if (object->pos.x > scrWidth + 10)
{
object->pos.x = -10;
}
if (object->pos.y < -10)
{
object->pos.y = scrHeight + 10;
}
if (object->pos.y > scrHeight + 10)
{
object->pos.y = -10;
}
}
}
bool Game::shouldTickPhysics() const
{
return accumulatedDeltaTime >= fixedTimeStep;
}
void Game::draw() const
{
BeginDrawing();
ClearBackground(RAYWHITE);
for (auto& obj : PhysObjects)
{
obj.draw();
}
EndDrawing();
}
void Game::exit()
{
CloseWindow();
}
|
[
"54036673+SamuelDaman@users.noreply.github.com"
] |
54036673+SamuelDaman@users.noreply.github.com
|
4e0e6bde863706f7f52788aa781270226d9c8c08
|
70898884dda5659a93f544c0bea4a18fcd05f444
|
/OBJECT ORIENTED C++/Workshop6/athome/w6_p2.cpp
|
af647eaede7d2398f555f28d29e19805d6fe726b
|
[] |
no_license
|
pmahida1/BTP305
|
4d7acd3e3bd60f3cf978906d623b941468d1037c
|
1c49b6ebda5a67619e715b922b440d916a39691e
|
refs/heads/master
| 2023-03-04T01:47:13.209270
| 2021-01-22T01:13:48
| 2021-01-22T01:13:48
| 331,798,276
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,330
|
cpp
|
// Name: Parth Mahida
// Seneca Student ID: 140 172 180
// Seneca email: pmahida1@myseneca.ca
// Date of completion: November 2nd, 2020
//
// I confirm that I am the only author of this file
// and the content was created entirely by me.
#include <iostream>
#include <iomanip>
#include <fstream>
#include "Autoshop.h"
#include "Autoshop.h"
#include "Utilities.h"
#include "Utilities.h"
#include "Autoshop.h"
void loadData(const char* filename, sdds::Autoshop& as)
{
std::ifstream file(filename);
if (!file)
{
std::cerr << "ERROR: Cannot open file [" << filename << "].\n";
return;
}
while (file)
{
// TODO: This code can throw errors to signal that something went wrong while
// extracting data. Write code to catch and handle the following errors:
// - the type of vehicle is not recognized: the first non-empty character
// on the line is not 'c', 'C', 'r', or 'R'. In this case print
// "Unrecognized record type: [TAG]<endl>"
// - one of the fields in the record contains invalid data. In this case print
// "Invalid record!<endl>"
try {
sdds::Vehicle* aVehicle = sdds::createInstance(file);
if (aVehicle)
as += aVehicle;
}
catch (char dummy) {
std::cout << "Unrecognized record type: [" << dummy << "]" << std::endl;
}
catch (const char* msg) {
std::wcout << msg << std::endl;
}
}
}
// ws dataClean.txt dataMessy.txt
int main(int argc, char** argv)
{
std::cout << "Command Line:\n";
std::cout << "--------------------------\n";
for (int i = 0; i < argc; i++)
std::cout << std::setw(3) << i + 1 << ": " << argv[i] << '\n';
std::cout << "--------------------------\n\n";
sdds::Autoshop as;
loadData(argv[1], as);
as.display(std::cout);
std::cout << "\n";
loadData(argv[2], as);
as.display(std::cout);
std::cout << std::endl;
std::list<const sdds::Vehicle*> vehicles;
{
// TODO: Create a lambda expression that receives as parameter `const sdds::Vehicle*`
// and returns true if the vehicle has a top speed >300km/h
auto fastVehicles = [](const sdds::Vehicle* v)->bool
{
bool flag = false;
if (v->topSpeed() > 300.00)
flag = true;
return flag;
};
as.select(fastVehicles, vehicles);
std::cout << "--------------------------------\n";
std::cout << "| Fast Vehicles |\n";
std::cout << "--------------------------------\n";
for (auto it = vehicles.begin(); it != vehicles.end(); ++it)
{
(*it)->display(std::cout);
std::cout << std::endl;
}
std::cout << "--------------------------------\n";
}
vehicles.clear();
std::cout << std::endl;
{
// TODO: Create a lambda expression that receives as parameter `const sdds::Vehicle*`
// and returns true if the vehicle is broken and needs repairs.
auto brokenVehicles = [](const sdds::Vehicle* v)->bool
{
bool flag = false;
if (v->condition() == "broken")
flag = true;
return flag;
};
as.select(brokenVehicles, vehicles);
std::cout << "--------------------------------\n";
std::cout << "| Vehicles in need of repair |\n";
std::cout << "--------------------------------\n";
for (const auto vehicle : vehicles)
{
vehicle->display(std::cout);
std::cout << std::endl;
}
std::cout << "--------------------------------\n";
}
return 0;
}
|
[
"mahida.parth566@gmail.com"
] |
mahida.parth566@gmail.com
|
b951ba69315ebf7e0aebb5faf715c64fab0418e1
|
d0fb46aecc3b69983e7f6244331a81dff42d9595
|
/sgw/include/alibabacloud/sgw/model/ValidateGatewayNameResult.h
|
6feae7dd819a37d43ac9d81028c0043e7f1ee8db
|
[
"Apache-2.0"
] |
permissive
|
aliyun/aliyun-openapi-cpp-sdk
|
3d8d051d44ad00753a429817dd03957614c0c66a
|
e862bd03c844bcb7ccaa90571bceaa2802c7f135
|
refs/heads/master
| 2023-08-29T11:54:00.525102
| 2023-08-29T03:32:48
| 2023-08-29T03:32:48
| 115,379,460
| 104
| 82
|
NOASSERTION
| 2023-09-14T06:13:33
| 2017-12-26T02:53:27
|
C++
|
UTF-8
|
C++
| false
| false
| 1,549
|
h
|
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_SGW_MODEL_VALIDATEGATEWAYNAMERESULT_H_
#define ALIBABACLOUD_SGW_MODEL_VALIDATEGATEWAYNAMERESULT_H_
#include <string>
#include <vector>
#include <utility>
#include <alibabacloud/core/ServiceResult.h>
#include <alibabacloud/sgw/SgwExport.h>
namespace AlibabaCloud
{
namespace Sgw
{
namespace Model
{
class ALIBABACLOUD_SGW_EXPORT ValidateGatewayNameResult : public ServiceResult
{
public:
ValidateGatewayNameResult();
explicit ValidateGatewayNameResult(const std::string &payload);
~ValidateGatewayNameResult();
std::string getMessage()const;
std::string getCode()const;
bool getSuccess()const;
bool getIsValid()const;
protected:
void parse(const std::string &payload);
private:
std::string message_;
std::string code_;
bool success_;
bool isValid_;
};
}
}
}
#endif // !ALIBABACLOUD_SGW_MODEL_VALIDATEGATEWAYNAMERESULT_H_
|
[
"sdk-team@alibabacloud.com"
] |
sdk-team@alibabacloud.com
|
d5bebb9f1239f9b0e8440e92adedc429d4cc10ec
|
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
|
/generated/src/aws-cpp-sdk-ec2/include/aws/ec2/model/TransitGatewayRouteState.h
|
e813e590e4941398b270a8182004fd727ea58230
|
[
"Apache-2.0",
"MIT",
"JSON"
] |
permissive
|
aws/aws-sdk-cpp
|
aff116ddf9ca2b41e45c47dba1c2b7754935c585
|
9a7606a6c98e13c759032c2e920c7c64a6a35264
|
refs/heads/main
| 2023-08-25T11:16:55.982089
| 2023-08-24T18:14:53
| 2023-08-24T18:14:53
| 35,440,404
| 1,681
| 1,133
|
Apache-2.0
| 2023-09-12T15:59:33
| 2015-05-11T17:57:32
| null |
UTF-8
|
C++
| false
| false
| 734
|
h
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace EC2
{
namespace Model
{
enum class TransitGatewayRouteState
{
NOT_SET,
pending,
active,
blackhole,
deleting,
deleted
};
namespace TransitGatewayRouteStateMapper
{
AWS_EC2_API TransitGatewayRouteState GetTransitGatewayRouteStateForName(const Aws::String& name);
AWS_EC2_API Aws::String GetNameForTransitGatewayRouteState(TransitGatewayRouteState value);
} // namespace TransitGatewayRouteStateMapper
} // namespace Model
} // namespace EC2
} // namespace Aws
|
[
"sdavtaker@users.noreply.github.com"
] |
sdavtaker@users.noreply.github.com
|
89a570c5aa5cf71af96b4dd7ea66412b55233e10
|
18e9db71a0e207dbc7654135123bceaa7b3339e4
|
/7.代码练习/noip入门组/207评奖2.cpp
|
a142c4ccb710873c0ee086d1047dc8d9f280ae08
|
[] |
no_license
|
TheIslland/learning-in-collegelife
|
358490cc74914b87d4d626a6485c2fe1ff06462f
|
1794e18addfd05e32cf8108895ac1585586394e1
|
refs/heads/master
| 2021-07-08T00:51:00.908370
| 2020-07-11T01:04:35
| 2020-07-11T01:04:35
| 144,252,958
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,144
|
cpp
|
/*************************************************************************
> File Name: 207评奖2.cpp
> Author: TheIslland
> Mail: voidland@163.com, 861436930@qq.com
> Created Time: Wed Nov 6 19:55:51 2019
************************************************************************/
#include<iostream>
#include<algorithm>
#include<iomanip>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
typedef long long ll;
using namespace std;
struct student {
string name;
int grade;
};
bool cmp(struct student &a, struct student &b) {
return a.grade > b.grade;
}
int main() {
int n, max = -1, min = 1000;
string name;
struct student a[35];
cin >> n;
for(int i = 0; i < n; i++) {
cin >> name;
int sum = 0, m;
for (int i = 0; i < 4; i++) {
cin >> m;
m > max && (max = m);
m < min && (min = m);
sum += m;
}
cout << sum << endl;
struct student temp = {name, sum};
a[i] = temp;
}
sort(a, a + n, cmp);
cout << a[0].name << endl;
cout << max << " " << min << endl;
return 0;
}
|
[
"861436930@qq.com"
] |
861436930@qq.com
|
50f3debc5380d08da1fe1531ee7697be7ac90cd3
|
37867f639363ab2f188028dc158b483b6e6b81f3
|
/Src/AI/LAInteractSO.cpp
|
2fc64e32dd7d9c0849b3168c5b98f66e35e0841b
|
[] |
no_license
|
ailuoxz/BadPrincess-Game
|
704143bcafe1205a2ccdd7dbd68ed284c6fa1d76
|
47caae1a03fdfe8058260e44add25fd8e89f99c3
|
refs/heads/master
| 2021-12-14T15:13:50.974644
| 2017-05-04T16:31:22
| 2017-05-04T16:31:22
| null | 0
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 12,216
|
cpp
|
#include "LAInteractSO.h"
#include "Server.h"
#include "AI/EntityManager.h"
#include "Logic\Entity\Entity.h"
#include "Logic/Entity/Components/WorkmanState.h"
#include "Logic\UnitMessages.h"
#include "Logic\MovementMessages.h"
#include "Logic\AudioMessages.h"
#include "Logic\SmartObjectMessages.h"
#include "Logic\WorkmanMessages.h"
#include "Logic/RouteCalculationMessages.h"
namespace AI
{
bool CLAInteractSO::acceptN(const std::shared_ptr<NMessage> &message)
{
return (message->type.compare("AvatarMoveToEntity") == 0) || (message->type.compare("SmartDataAction") == 0) || (message->type.compare("ResourceAutoDestroy") == 0) || (message->type.compare("AvatarRouteTo") == 0) || (message->type.compare("AvatarFinishedRoute") == 0);
}
void CLAInteractSO::processN(const std::shared_ptr<NMessage> &message)
{
if(message->type.compare("AvatarMoveToEntity") == 0)
{
// Cuando el usuario indica que la unidad debe mover hacia una nueva smartEntity...
std::shared_ptr<AvatarMoveToEntity> m = std::static_pointer_cast<AvatarMoveToEntity>(message);
// Si la smartEntity no es la que actualmente se está utilizando...
if(stateComponent != nullptr && m->target != stateComponent->getSmartEntity())
{
// Se elimina a la unidad como usuario de la smartEntity que se actualmente se está utilizando.
auto removeMessage = std::make_shared<removeFromWorkmanList>();
removeMessage->sender = _entity;
stateComponent->getSmartEntity()->emitMessageN(removeMessage);
// Se libera la smartPosition que se estaba utilizando.
freeSmartPosition();
// Se almacena que la nueva smartEntity es la que se está utilizando.
stateComponent->setSmartEntity(m->target);
currentTimeGather = 0;
// La acción latente fracasa.
this->abort();
}
}
else if(message->type.compare("SmartDataAction") == 0)
{
// Cuando se recibe la forma de interacción...
std::shared_ptr<SmartDataAction> m = std::static_pointer_cast<SmartDataAction>(message);
// Se apunta el tipo de recurso que se estaba recolectando.
ResourceType lastType = stateComponent->getResourceType();
// Se actualiza la acción a realizar en el stateComponent.
stateComponent->setAction(static_cast<Logic::CWorkmanState::WorkmanAction>(m->actionType));
// Se guarda la animación que corresponde a la acción a realizar.
animation = m->animation;
if(stateComponent->getAction() != Logic::CWorkmanState::storeResource && stateComponent->getAction() != Logic::CWorkmanState::gatherFull)
{
// Se actualiza el tipo de recurso que se va a recolectar en el stateComponent.
switch(stateComponent->getAction())
{
case Logic::CWorkmanState::gatherWood:
stateComponent->setResourceType(ResourceType::Wood);
break;
case Logic::CWorkmanState::gatherIron:
stateComponent->setResourceType(ResourceType::Iron);
break;
case Logic::CWorkmanState::gatherStone:
stateComponent->setResourceType(ResourceType::Stone);
break;
default:
//stateComponent->setResourceType(ResourceType::none);
break;
}
// Si el nuevo tipo de recurso a recolectar es distinto del tipo que ya se estaba recolectando,
// la unidad se deshace de los recursos que estaba cargando.
if(lastType != stateComponent->getResourceType())
{
stateComponent->setCurrentCharge(0);
// Se modifica la velocidad de movimiento por la velocidad por defecto.
auto modidySpeedMessage= std::make_shared<ModifyMaxLinearSpeed>();
modidySpeedMessage->speed = stateComponent->getSpeed();
_entity->emitMessageN(modidySpeedMessage);
}
}
// Se reanuda la acción latente.
this->resume();
}
else if(message->type.compare("ResourceAutoDestroy") == 0)
{
// Cuando la smartEntity que se está utilizando resulta destruida...
//std::cout << "DESTROYED" << std::endl;
std::shared_ptr<ResourceAutoDestroy> m = std::static_pointer_cast<ResourceAutoDestroy>(message);
// Si hay una smartEntity "siguiente", se almacena en el stateComponent de la unidad.
if(stateComponent != nullptr && m->nextItem != nullptr)
{
stateComponent->setSmartEntity(m->nextItem);
stateComponent->setLastResource(m->nextItem);
// Si la unidad estaba recolectando, se aborta la acción latente para que continúe recolectando en el recurso más cercano.
if(stateComponent->getAction() == Logic::CWorkmanState::gatherWood|| stateComponent->getAction() == Logic::CWorkmanState::gatherIron || stateComponent->getAction() == Logic::CWorkmanState::gatherStone)
this->abort();
// Si NO hay una smartEntity "siguiente", se almacena "nullptr".
}else if(stateComponent != nullptr && m->nextItem == nullptr)
{
stateComponent->setSmartEntity(nullptr);
stateComponent->setLastResource(nullptr);
// Si la unidad estaba recolectando, como no existe un recurso cercano,
// la unidad considera que no puede recolectar más.
if(stateComponent->getAction() == Logic::CWorkmanState::gatherWood|| stateComponent->getAction() == Logic::CWorkmanState::gatherIron || stateComponent->getAction() == Logic::CWorkmanState::gatherStone)
{
stateComponent->setAction(Logic::CWorkmanState::gatherFull);
this->resume();
}
}
}
else if (message->type.compare("AvatarRouteTo") == 0)
{
// Cuando la unidad recibe un mensaje de ruta externo...
// Se libera la smartPosition que la unidad estaba utilizando.
freeSmartPosition();
currentTimeGather = 0;
// Se deja de utilizar la smartEntity actual.
stateComponent->setSmartEntity(nullptr);
}else if (message->type.compare("AvatarFinishedRoute") == 0)
{
sendAnimationMessage("Idle");
}
}
CLatentAction::LAStatus CLAInteractSO::OnStart()
{
// Si no se ha recuperado aún el stateComponent de la unidad, entonces se recupera.
if(_entity != nullptr)
{
if(stateComponent == nullptr)
{
Logic::IComponent *iComponent = _entity->getComponent("CWorkmanState");
if(iComponent != nullptr)
stateComponent = static_cast<Logic::CWorkmanState*>(iComponent);
}
}
// La unidad mira hacia la smartEntity.
lookAtSmartObject();
// Se le indica a la smartEntity que la unidad está en la smartPosition, lista para recibir la forma de interacción.
if(stateComponent->getSmartEntity() != nullptr)
{
auto m = std::make_shared<SmartDataAvatarReady>();
m->entity = _entity;
stateComponent->getSmartEntity()->emitMessageN(m);
auto playAudioMessage = std::make_shared<PlayAudio>();
playAudioMessage->eventName = "default";
stateComponent->getSmartEntity()->emitMessageN(playAudioMessage);
}
// se suspende la ejecución de la acción latente a la espera de que la smartEntity envíe la forma de interacción.
return SUSPENDED;
}
CLatentAction::LAStatus CLAInteractSO::OnRun(unsigned int msecs)
{
if(stateComponent->getCurrentCharge() > stateComponent->getGatherMax())
{
// El obrero nunca debe llevar recursos por encima de su carga máxima.
stateComponent->setCurrentCharge(stateComponent->getGatherMax());
}
// Según sea la acción a realizar...
switch (stateComponent->getAction())
{
// Si se trata de recolectar algún tipo de recurso:
case Logic::CWorkmanState::gatherWood:
case Logic::CWorkmanState::gatherIron:
case Logic::CWorkmanState::gatherStone:
{
// Si el recurso fue destruido la acción latente fracasa.
if(stateComponent->getSmartEntity() == nullptr)
this->abort();
// Si la unidad ha llegado a su capacidad máxima de carga, no podrá seguir recolectando.
if(stateComponent->getCurrentCharge() >= stateComponent->getGatherMax())
{
stateComponent->setAction(Logic::CWorkmanState::gatherFull);
currentTimeGather = 0;
auto stopAudioMessage = std::make_shared<StopAudio>();
stateComponent->getSmartEntity()->emitMessageN(stopAudioMessage);
break;
}
// Se activa la animación que concuerda con la forma de interacción del recurso.
sendAnimationMessage(animation);
// Se incrementa el tiempo que la unidad lleva recolectando.
currentTimeGather += stateComponent->getTime();
// Cuando se llega al tiempo que tarda en recolectar la unidad.
if(currentTimeGather >= stateComponent->getGatherTime())
{
if(stateComponent->getCurrentCharge() > 0) // Evita división por cero.
{
// Se modifica la velocidad de movimiento, para reducirla en función de la carga actual.
auto modidySpeedMessage= std::make_shared<ModifyMaxLinearSpeed>();
modidySpeedMessage->speed = stateComponent->getSpeed() - (stateComponent->getSpeed() * 0.07f /* Sacar a MAP!! */ * (stateComponent->getCurrentCharge() / stateComponent->getGatherUnit()));
_entity->emitMessageN(modidySpeedMessage);
}
// Se aumenta la carga actual de la unidad en su stateComponent.
stateComponent->setCurrentCharge(stateComponent->getCurrentCharge() + stateComponent->getGatherUnit());
// Se reinicia la cuenta del tiempo que lleva recolectando.
currentTimeGather = 0; //-= stateComponent->getGatherTime();
// Se le restan recursos a la smartEntity que se está utilizando.
auto m = std::make_shared<GatherMessage>();
m->quantity = stateComponent->getGatherUnit();
stateComponent->getSmartEntity()->emitMessageN(m);
}
break;
}
// Si se trata de almacenar algún tipo de recurso:
case Logic::CWorkmanState::storeResource:
{
// Se libera la smarPosition que se estaba utilizando (la del cofre).
freeSmartPosition();
// Se suman los recursos del tipo recolectado al contador corresponiendte.
AI::ResourceServer::getInstance()->addResource(stateComponent->getResourceType(),stateComponent->getCurrentCharge());
// Se libera a la unidad de su carga, actualizando su stateComponent.
stateComponent->setCurrentCharge(0);
// Se modifica la velocidad de movimiento por la velocidad por defecto.
auto modidySpeedMessage= std::make_shared<ModifyMaxLinearSpeed>();
modidySpeedMessage->speed = stateComponent->getSpeed();
_entity->emitMessageN(modidySpeedMessage);
// Se recupera el último recurso utilizado, para regresar a él.
stateComponent->setSmartEntity(stateComponent->getLastResource());
// La acción latente finaliza con éxito.
return SUCCESS;
break;
}
// Si se ha alcanzado el máximo de capacidad de la unidad.
case Logic::CWorkmanState::gatherFull:
{
// Se libera la smarPosition que se estaba utilizando (la del recurso).
freeSmartPosition();
// Se busca le cofre más cercano.
Logic::CEntity* closestChest = AI::CServer::getSingletonPtr()->getEntityManager()->getClosestEntity(AI::CEntityManager::EntityType::Chest,_entity->getPosition());
// Se apunta cúal ha sido el último recurso (smartEntity) utilizado, para regresar más tarde.
stateComponent->setLastResource(stateComponent->getSmartEntity());
// Se pone como smartEntity en uso el cofre.
stateComponent->setSmartEntity(closestChest);
//La acción latente finaliza con éxito.
return SUCCESS;
break;
}
default:
break;
}
// La acción latente se continúa ejecutando.
return RUNNING;
}
CLatentAction::LAStatus CLAInteractSO::OnAbort()
{
return FAIL;
}
void CLAInteractSO::lookAtSmartObject()
{
auto rotationMessage = std::make_shared<AvatarControl>();
rotationMessage->controlType = "turn";
Vector3 direction = stateComponent->getSmartEntity()->getPosition() - _entity->getPosition();
double rotation = AI::CServer::correctAngle(atan2(-direction.x, -direction.z) - _entity->getYaw());
rotationMessage->attribute = (float) rotation;
_entity->emitMessageN(rotationMessage);
}
void CLAInteractSO::freeSmartPosition()
{
auto freeMessage = std::make_shared<SmartDataFreePosition>();
freeMessage->entity=_entity;
freeMessage->position=stateComponent->getPosition();
if(stateComponent->getSmartEntity() != nullptr)
{
stateComponent->getSmartEntity()->emitMessageN(freeMessage);
}
}
} //namespace AI
|
[
"raycosanchezgarcia@gmail.com"
] |
raycosanchezgarcia@gmail.com
|
c996cab86d732cd6eb175e03f094008babd77978
|
2c6221df607e3e41571e552ce6966acd5e8accab
|
/Timer.h
|
2c8e8eb2f91c5d3fe2bd3a5773b7fea4edefda4a
|
[] |
no_license
|
Charlyhash/GakkiNet
|
1a66adaa5ea82116c001943c9f5faa433fbf17ed
|
2d1c8ac4cb4c65875223a88627da8075129f92f7
|
refs/heads/master
| 2021-07-02T21:48:20.950842
| 2017-09-25T01:04:00
| 2017-09-25T01:04:00
| 104,687,870
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 817
|
h
|
#ifndef __TIMER_H__
#define __TIMER_H__
#include <unistd.h>
#include <stdint.h>
#include <sys/time.h>
#include <functional>
#include <memory>
using namespace std;
/*
Timer是对事件类事件的封装,包含一个到期时间和处理函数
*/
namespace GakkiNet
{
class Timer
{
public:
Timer(uint32_t interval, const function<void()> & funcHandle);
struct timeval getTimeOut();
uint64_t getTimeOutMSecond();
struct timespec getTimeInterval();
void update();
void setHandle(const function<void()> &);
static uint64_t getNowTimeMSecond();
static std::string getNowTimeDate();
void timerHandle();
private:
uint32_t intervalMs; //定时时间
struct timeval now; //当前时间
function<void()> handle; //时间到后的处理函数
};
}
#endif
|
[
"1062403542@qq.com"
] |
1062403542@qq.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.