hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
77k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
39f2e3009dc60767bc21fd301b10c4e591572eea
1,139
cpp
C++
src/leetcode/q0101_0200/q0102.cpp
jielyu/leetcode
ce5327f5e5ceaa867ea2ddd58a93bfb02b427810
[ "MIT" ]
9
2020-04-09T12:37:50.000Z
2021-04-01T14:01:14.000Z
src/leetcode/q0101_0200/q0102.cpp
jielyu/leetcode
ce5327f5e5ceaa867ea2ddd58a93bfb02b427810
[ "MIT" ]
3
2020-05-05T02:43:54.000Z
2020-05-20T11:12:16.000Z
src/leetcode/q0101_0200/q0102.cpp
jielyu/leetcode
ce5327f5e5ceaa867ea2ddd58a93bfb02b427810
[ "MIT" ]
5
2020-04-17T02:32:10.000Z
2020-05-20T10:12:26.000Z
/* #面试刷题# 第0113期 #Leetcode# Q0102 按层次顺序遍历二叉树 难度:中 给定一个二叉树,返回其节点值的级别顺序遍历。即,从左到右,逐级递进)。 示例: Input: [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]] */ #include "leetcode.h" namespace q0102 { template<typename T> bool run_testcases() { T slt; } // Runtime: 4 ms, faster than 94.38% // Memory Usage: 12.5 MB, less than 100.00% class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> ret; if (!root) {return ret;} vector<int> mid; // create a queue to store children nodes queue<TreeNode*> buff; buff.push(root); while (buff.size() > 0) { mid.clear(); // traversal nodes with the same level for (int i = buff.size(); i > 0; --i) { auto * node = buff.front(); buff.pop(); mid.push_back(node->val); // add child nodes to the buff if (node->left) {buff.push(node->left);} if (node->right) {buff.push(node->right);} } ret.push_back(mid); } return ret; } }; } // namespace q0102
23.729167
58
0.535558
39f474ef79a775e7cae39e502c4f1fcf981e7cf3
1,528
cpp
C++
dev_esp/lib/GasValue/GasValue.cpp
Granyy/SensAir
f56458322975a67793c6be92944e370cbd0117b2
[ "MIT" ]
2
2021-08-12T14:37:43.000Z
2021-08-17T13:59:35.000Z
dev_esp/lib/GasValue/GasValue.cpp
Granyy/SensAir
f56458322975a67793c6be92944e370cbd0117b2
[ "MIT" ]
null
null
null
dev_esp/lib/GasValue/GasValue.cpp
Granyy/SensAir
f56458322975a67793c6be92944e370cbd0117b2
[ "MIT" ]
2
2021-08-17T13:59:36.000Z
2021-11-05T03:46:12.000Z
/******************************************************************************/ /* @TITLE : GasValue.cpp */ /* @VERSION : 1.0 */ /* @CREATION : dec 27, 2017 */ /* @MODIFICATION : dec 27, 2017 */ /* @AUTHOR : Leo GRANIER */ /******************************************************************************/ #include "GasValue.h" GasValue::GasValue() { gasSemaphore = xSemaphoreCreateBinary(); xSemaphoreGive(gasSemaphore); gasValue = {0,0,0,0}; gasRawValue = {0,0,0,0}; } struct gasRaw GasValue::get_gasRawValue() { struct gasRaw _gasRawValue; if(xSemaphoreTake(gasSemaphore,portMAX_DELAY) == pdTRUE) { _gasRawValue = gasRawValue; xSemaphoreGive(gasSemaphore); } return _gasRawValue; } struct gas GasValue::get_gasValue() { struct gas _gasValue; if(xSemaphoreTake(gasSemaphore,portMAX_DELAY) == pdTRUE) { _gasValue = gasValue; xSemaphoreGive(gasSemaphore); } return _gasValue; } void GasValue::set_gasValue(struct gas _gasValue) { if(xSemaphoreTake(gasSemaphore,portMAX_DELAY) == pdTRUE) { gasValue = _gasValue; xSemaphoreGive(gasSemaphore); } } void GasValue::set_gasRawValue(struct gasRaw _gasRawValue) { if(xSemaphoreTake(gasSemaphore,portMAX_DELAY) == pdTRUE) { gasRawValue = _gasRawValue; xSemaphoreGive(gasSemaphore); } }
29.960784
80
0.524869
39f491a0815135ec3d8aff68d39ff960d16fa93f
25,050
cpp
C++
c-transactions-extractor/code/main.cpp
rodrigo-brito/co-change-analysis
298bb5437371ab29fb94a9e2f9012d3a5cf033f7
[ "MIT" ]
1
2019-04-15T22:27:52.000Z
2019-04-15T22:27:52.000Z
c-transactions-extractor/code/main.cpp
rodrigo-brito/co-change-analysis
298bb5437371ab29fb94a9e2f9012d3a5cf033f7
[ "MIT" ]
1
2019-05-09T01:55:12.000Z
2019-05-09T02:14:41.000Z
c-transactions-extractor/code/main.cpp
rodrigo-brito/co-change-analysis
298bb5437371ab29fb94a9e2f9012d3a5cf033f7
[ "MIT" ]
2
2019-05-09T01:41:29.000Z
2019-06-12T18:59:45.000Z
#include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #define assert(x) #define STB_LEAKCHECK_IMPLEMENTATION #include "stb_leakcheck.h" #include "dd_array.cpp" #define min(a, b) (a < b ? a:b) #define max(a, b) (a > b ? a:b) #include "Memory.h" #include "Array.cpp" #include "EntireFile.cpp" #include "FileReader.cpp" #include "FileWriter.cpp" #include "String.cpp" #include "string_utils.cpp" #define ANSI_COLOR_YELLOW(text) "\x1b[33m" text "\x1b[0m" #define LOOP_SIZE 50 enum TokenType { TokenTypeNone, TokenTypeLeftBrace, TokenTypeRightBrace, TokenTypeLeftParentesis, TokenTypeRightParentesis, TokenTypeLineComment, TokenTypeBlockComment, TokenTypeEOF, TokenTypeUnknown, TokenTypeCount }; struct Token { TokenType type; char* string; int charIndex; int line; }; struct ChangeInfo { int oldFileLine; int oldFileCount; int newFileLine; int newFileCount; }; struct DiffChunk { char oldFile[256]; char newFile[256]; ChangeInfo* changes; //char** functionsChanged; }; struct CommitInfo { char hash[256]; DiffChunk* chunks; char** functionsChanged; }; struct FunctionInFile { char name[256]; int firstLine; int lastLine; bool changed; }; Token readNextToken(FileReader& reader) { //while (isWhiteSpace(reader.content[reader.at]) || startWithReader(reader, "//") || startWithReader(reader, "#define") || startWithReader(reader, "/*")) { while (isWhiteSpace(reader.content[reader.at]) || startWithReader(reader, "/*") || startWithReader(reader, "//") || startWithReader(reader, "#define") || (startWithReader(reader, "\"") && *(reader.content+reader.at-1) != '\\')) { while (isWhiteSpace(reader.content[reader.at])) { skipWhiteSpace(&reader); } while (startWithReader(reader, "//")) { //printf("line comment\n"); readUntilCharIsReached(&reader, '\n'); } while (startWithReader(reader, "\"") && *(reader.content+reader.at-1) != '\\') { //printf("string literal\n"); advance(&reader); FileReader r = readUntilCharIsReached(&reader, '\"'); while (*(reader.content+reader.at-1) == '\\') { advance(&reader); readUntilCharIsReached(&reader, '\"'); } advance(&reader); } while (startWithReader(reader, "#define")) { //printf("define start %d\n", reader.line); FileReader defineLine = readUntilCharIsReached(&reader, '\n'); advance(&reader); char* c = at(&reader); while (isWhiteSpace(*c)) --c; while (*c == '\\') { defineLine = readUntilCharIsReached(&reader, '\n'); advance(&reader); c = at(&reader); while (isWhiteSpace(*c)) --c; } //printf("define end %d\n", reader.line); } while (startWithReader(reader, "/*")) { //printf("block comment %d\n", reader.line); advance(&reader, 2); FileReader r = readUntilCharIsReached(&reader, '*'); //printf("%.*s\n", r.size, at(&r)); while (peek(&reader) != '/') { advance(&reader); readUntilCharIsReached(&reader, '*'); if (eof(reader)) break; } if (eof(reader)) break; //printf("end %d\n", reader.line); advance(&reader, 2); } if (eof(reader)) break; } if (reader.at >= reader.size || reader.content[reader.at] == 0) return {TokenTypeEOF, 0, reader.at, reader.line}; Token token = {}; token.line = reader.line; if (reader.content[reader.at] == '{') { token.type = TokenTypeLeftBrace; } else if (reader.content[reader.at] == '}') { token.type = TokenTypeRightBrace; } else if (reader.content[reader.at] == '(') { token.type = TokenTypeLeftParentesis; } else if (reader.content[reader.at] == ')') { token.type = TokenTypeRightParentesis; } else { advance(&reader); return {}; //printf("Unexpected character %c\n", reader.content[reader.at]); //assert(0); } token.charIndex = reader.at; advance(&reader); return token; } int loadProcessOutput(char* buffer, const char* formatString, ...) { char path[1024]; va_list argList; va_start(argList, formatString); vsprintf(path, formatString, argList); va_end(argList); FILE* f = popen(path, "r"); if (f == nullptr) { printf("Failed to load process %s\n", path); return false; } char* at = buffer; char lineBuffer[2048]; while (fgets(lineBuffer, 2048, f)) { int len = strlen(lineBuffer); memcpy(at, lineBuffer, len); at += len; } pclose(f); return at-buffer; } FunctionInFile* getFunctionsInFile(EntireFile entireFile) { FunctionInFile* functions = arralloc(FunctionInFile, 50); FileReader reader = {entireFile.content, entireFile.size, 0, 1}; Token token1 = readNextToken(reader); while (!eof(reader)) { Token token2 = readNextToken(reader); if (token1.type == TokenTypeRightParentesis && token2.type == TokenTypeLeftBrace) { FunctionInFile function = {}; char* c = &entireFile.content[token1.charIndex]; int scope = 0; while (1) { --c; if (*c == ')') ++scope; else if (*c == '(' && scope > 0) --scope; else if (*c == '(' && scope == 0) break; } char* nameEnd = --c; while (isAlphaNum(*c) || *c == '_') --c; char* nameBegin = ++c; sprintf(function.name, "%.*s", (int) (nameEnd-nameBegin+1), nameBegin); function.firstLine = reader.line; int scopeLevel = 0; while (!eof(reader)) { Token tk = readNextToken(reader); if (tk.type == TokenTypeRightBrace) { if (scopeLevel == 0) { break; } else { --scopeLevel; } } else if (tk.type == TokenTypeLeftBrace) { ++scopeLevel; } } function.lastLine = reader.line; arradd(functions, function); //printf("%s{%d, %d}\n", function.name, function.firstLine, function.lastLine); } token1 = token2; } return functions; } void writeCommit(FileWriter* writer, CommitInfo commit) { writeTextInFile(writer, " ["); writeTextInFile(writer, "\"%s\"", commit.functionsChanged[0]); for (int f = 1; f < arrcount(commit.functionsChanged); ++f) { writeTextInFile(writer, ", \"%s\"", commit.functionsChanged[f]); } writeTextInFile(writer, "]"); } int main(int argc, char* argv[]) { #if 1 if (argc < 4) { printf("Usage: %s <git_repo_path> <output_path> <num_commits>", argv[0]); return 0; } char repositoryPath[512]; sprintf(repositoryPath, "%s/.git", argv[1]); char outputPath[512]; sprintf(outputPath, "%s", argv[2]); int maxNumberOfCommitsToAnalyse = atoi(argv[3]); FILE* outputFile = fopen(outputPath, "w"); fwrite("[\n", 1, 2, outputFile); char totalCommitCountString[12]; loadProcessOutput(totalCommitCountString, "git --git-dir=\"%s\" rev-list --count master", repositoryPath); int totalCommitCount = atoi(totalCommitCountString); FileReader commitHashesOutput = {(char*) malloc(MEGA_BYTES(40))}; commitHashesOutput.size = loadProcessOutput(commitHashesOutput.content, "git --git-dir=\"%s\" log --oneline --pretty=tformat:\"%%H\"", repositoryPath); char** commitHashes = arralloc(char*, totalCommitCount); while (!eof(commitHashesOutput)) { char* commitHash = (char*) malloc(64); readUntilCharIsReached(commitHash, &commitHashesOutput, '\n'); advance(&commitHashesOutput); arradd(commitHashes, commitHash); } free(commitHashesOutput.content); int numberOfCommitsToAnalyse = min(totalCommitCount, maxNumberOfCommitsToAnalyse); EntireFile ef = {}; ef.content = (char*) malloc(MEGA_BYTES(500)); CommitInfo* commits = (CommitInfo*) malloc(numberOfCommitsToAnalyse*sizeof(CommitInfo)); int commitCount = 0; int upToCommit = 0; int sinceCommit = min(numberOfCommitsToAnalyse-1, LOOP_SIZE); while (sinceCommit <= numberOfCommitsToAnalyse) { ef.size = loadProcessOutput( ef.content, "git --git-dir=\"%s\" log ^%s^..^%s^ --diff-filter=M -p --unified=0", repositoryPath, commitHashes[sinceCommit], commitHashes[upToCommit] ); printf(ANSI_COLOR_YELLOW("Analysing log from %.*s to %.*s (size: %.2fmb)\n"), 6, commitHashes[sinceCommit], 6, commitHashes[upToCommit], (float)ef.size/MEGA_BYTES(1) ); CommitInfo* currentCommit = 0; DiffChunk* currentChunk = 0; int newCommits = 0; FileReader reader = {ef.content, ef.size, 0, 1}; while (!eof(reader)) { FileReader line = readUntilCharIsReached(&reader, '\n'); if (startsWith(line.content, "commit")) { advance(&line, sizeof("commit")); currentCommit = &commits[commitCount++]; readUntilCharIsReached(currentCommit->hash, &line, '\n'); printf("%6d: %s\n", commitCount, currentCommit->hash); currentCommit->chunks = arralloc(DiffChunk, 10); ++newCommits; } else if (startsWith(line.content, "---")) { advance(&line, sizeof("--- a")); DiffChunk chunk = {}; readUntilCharIsReached(chunk.oldFile, &line, '\n'); chunk.changes = arralloc(ChangeInfo, 10); //chunk.functionsChanged = 0; arradd(currentCommit->chunks, chunk); currentChunk = &arrlast(currentCommit->chunks); } else if (startsWith(line.content, "+++")) { advance(&line, sizeof("+++ b")); readUntilCharIsReached(currentChunk->newFile, &line, '\n'); } else if (startsWith(line.content, "@@")) { advance(&line, sizeof("@@ ")); char sourceLine[32]; char sourceCount[32]; char targetLine[32]; char targetCount[32]; FileReader sourceInfo = readUntilCharIsReached(&line, ' '); readUntilCharIsReached(sourceLine, &sourceInfo, ','); advance(&sourceInfo); if (!eof(sourceInfo)) { readRemainder(sourceCount, &sourceInfo); } advance(&line, 2); FileReader targetInfo = readUntilCharIsReached(&line, ' '); readUntilCharIsReached(targetLine, &targetInfo, ','); advance(&targetInfo); if (!eof(targetInfo)) { readRemainder(targetCount, &targetInfo); } ChangeInfo change = {}; change.oldFileLine = atoi(sourceLine); change.oldFileCount = atoi(sourceCount); change.newFileLine = atoi(targetLine); change.newFileCount = atoi(targetCount); arradd(currentChunk->changes, change); } advance(&reader); } for (int i = commitCount - newCommits; i < commitCount; ++i) { //printf("%s\n", commits[i].hash); char** functionsChanged = arralloc(char*, 10); for (int j = 0; j < arrcount(commits[i].chunks); ++j) { DiffChunk& chunk = commits[i].chunks[j]; if (endsWith(chunk.newFile, ".cpp") || endsWith(chunk.newFile, ".hpp") || endsWith(chunk.newFile, ".c") || endsWith(chunk.newFile, ".h")) { EntireFile file = {}; file.content = (char*) malloc(MEGA_BYTES(64)); file.size = loadProcessOutput(file.content, "git --git-dir=%s/.git show %s:%s", argv[1], commits[i].hash, chunk.newFile); FunctionInFile* functions = getFunctionsInFile(file); for (int k = 0; k < arrcount(chunk.changes); ++k) { ChangeInfo change = chunk.changes[k]; for (int f = 0; f < arrcount(functions); ++f) { FunctionInFile& function = functions[f]; if (change.newFileLine >= function.firstLine && change.newFileLine <= function.lastLine) { function.changed = true; } } } for (int f = 0; f < arrcount(functions); ++f) { FunctionInFile& function = functions[f]; if (function.changed) { char* functionName = (char*) malloc(256); sprintf(functionName, "[%s] %s", chunk.newFile, function.name); arradd(functionsChanged, functionName); } } arrfree(functions); free(file.content); } } commits[i].functionsChanged = functionsChanged; } FileWriter writer = {(char*) malloc(MEGA_BYTES(100))}; if (newCommits) { for (int i = commitCount - newCommits; i < commitCount; ++i) { writeCommit(&writer, commits[i]); writeTextInFile(&writer, ",\n"); } } appendFile(writer, outputFile); free(writer.buffer); for (int i = commitCount-newCommits; i < commitCount; ++i) { for (int j = 0; j < arrcount(commits[i].chunks); ++j) { arrfree(commits[i].chunks[j].changes); } for (int f = 0; f < arrcount(commits[i].functionsChanged); ++f) { free(commits[i].functionsChanged[f]); } arrfree(commits[i].functionsChanged); arrfree(commits[i].chunks); } upToCommit = sinceCommit; sinceCommit += LOOP_SIZE; sinceCommit = min(sinceCommit, numberOfCommitsToAnalyse); if (sinceCommit == upToCommit) break; } fseek(outputFile, -3, SEEK_CUR); fwrite("\n]", 1, 2, outputFile); printf("Done!\n"); free(ef.content); for (int i = 0; i < arrcount(commitHashes); ++i) { free(commitHashes[i]); } arrfree(commitHashes); arrfree(commits); stb_leakcheck_dumpmem(); return 0; #elif 0 const char* repos[] = { "php/php-src" }; for (unsigned int repoIndex = 0; repoIndex < sizeof(repos); ++repoIndex) { system("rd /s /q \"../../temp-clone\""); system("mkdir \"../../temp-clone\""); printf("%s\n", repos[repoIndex]); char commandLine[512]; sprintf(commandLine, "git clone https://github.com/%s.git ../../temp-clone", repos[repoIndex]); system(commandLine); char repositoryPath[512]; sprintf(repositoryPath, "../../temp-clone/.git"); char outputPath[512]; sprintf(outputPath, "../../transactions/"); FileReader rd = {}; rd.content = (char*) repos[repoIndex]; rd.size = strlen(repos[repoIndex]); readUntilCharIsReached(outputPath + strlen(outputPath), &rd, '/'); advance(&rd); rd = readRemainder(&rd); sprintf(outputPath + strlen(outputPath), "_%.*s.txt", rd.size, rd.content); printf("Output path: %s\n", outputPath); int maxNumberOfCommitsToAnalyse = 10000; FILE* outputFile = fopen(outputPath, "w"); fwrite("[\n", 1, 2, outputFile); char branchName[128]; loadProcessOutput(branchName, "git --git-dir=\"%s\" branch | grep \\* | cut -d ' ' -f2", repositoryPath); branchName[strlen(branchName)-1] = 0; char totalCommitCountString[12]; loadProcessOutput(totalCommitCountString, "git --git-dir=\"%s\" rev-list --count %s", repositoryPath, branchName); int totalCommitCount = atoi(totalCommitCountString); FileReader commitHashesOutput = {(char*) malloc(MEGA_BYTES(40))}; commitHashesOutput.size = loadProcessOutput(commitHashesOutput.content, "git --git-dir=\"%s\" log --oneline --pretty=tformat:\"%%H\"", repositoryPath); char** commitHashes = arralloc(char*, totalCommitCount); while (!eof(commitHashesOutput)) { char* commitHash = (char*) malloc(64); readUntilCharIsReached(commitHash, &commitHashesOutput, '\n'); advance(&commitHashesOutput); arradd(commitHashes, commitHash); } free(commitHashesOutput.content); int numberOfCommitsToAnalyse = min(totalCommitCount, maxNumberOfCommitsToAnalyse); EntireFile ef = {}; ef.content = (char*) malloc(MEGA_BYTES(500)); CommitInfo* commits = arralloc(CommitInfo, numberOfCommitsToAnalyse); int commitCount = 0; int upToCommit = 0; int sinceCommit = min(numberOfCommitsToAnalyse-1, LOOP_SIZE); for (int commitIndex = 0; commitIndex < numberOfCommitsToAnalyse; ++commitIndex) { ef.size = loadProcessOutput( ef.content, "git --git-dir=\"%s\" log %s --diff-filter=M -p --unified=0 -1", repositoryPath, commitHashes[commitIndex] ); CommitInfo* currentCommit = 0; DiffChunk* currentChunk = 0; int newCommits = 0; FileReader reader = {ef.content, ef.size, 0, 1}; while (!eof(reader)) { FileReader line = readUntilCharIsReached(&reader, '\n'); if (startsWith(line.content, "commit")) { advance(&line, sizeof("commit")); currentCommit = &commits[commitCount++]; readUntilCharIsReached(currentCommit->hash, &line, '\n'); printf(ANSI_COLOR_YELLOW("%6d: ") "%s\n", commitCount, currentCommit->hash); currentCommit->chunks = arralloc(DiffChunk, 10); ++newCommits; } else if (startsWith(line.content, "---")) { advance(&line, sizeof("--- a")); DiffChunk chunk = {}; readUntilCharIsReached(chunk.oldFile, &line, '\n'); chunk.changes = arralloc(ChangeInfo, 10); //chunk.functionsChanged = 0; arradd(currentCommit->chunks, chunk); currentChunk = &arrlast(currentCommit->chunks); } else if (startsWith(line.content, "+++")) { advance(&line, sizeof("+++ b")); readUntilCharIsReached(currentChunk->newFile, &line, '\n'); } else if (startsWith(line.content, "@@")) { advance(&line, sizeof("@@ ")); char sourceLine[32]; char sourceCount[32]; char targetLine[32]; char targetCount[32]; FileReader sourceInfo = readUntilCharIsReached(&line, ' '); readUntilCharIsReached(sourceLine, &sourceInfo, ','); advance(&sourceInfo); if (!eof(sourceInfo)) { readRemainder(sourceCount, &sourceInfo); } advance(&line, 2); FileReader targetInfo = readUntilCharIsReached(&line, ' '); readUntilCharIsReached(targetLine, &targetInfo, ','); advance(&targetInfo); if (!eof(targetInfo)) { readRemainder(targetCount, &targetInfo); } ChangeInfo change = {}; change.oldFileLine = atoi(sourceLine); change.oldFileCount = atoi(sourceCount); change.newFileLine = atoi(targetLine); change.newFileCount = atoi(targetCount); arradd(currentChunk->changes, change); } advance(&reader); } for (int i = commitCount - newCommits; i < commitCount; ++i) { //printf("%s\n", commits[i].hash); char** functionsChanged = arralloc(char*, 10); for (int j = 0; j < arrcount(commits[i].chunks); ++j) { DiffChunk& chunk = commits[i].chunks[j]; if (endsWith(chunk.newFile, ".cpp") || endsWith(chunk.newFile, ".hpp") || endsWith(chunk.newFile, ".c") || endsWith(chunk.newFile, ".h")) { EntireFile file = {}; file.content = (char*) malloc(MEGA_BYTES(64)); file.size = loadProcessOutput(file.content, "git --git-dir=../../temp-clone/.git show %s:%s", commits[i].hash, chunk.newFile); FunctionInFile* functions = getFunctionsInFile(file); for (int k = 0; k < arrcount(chunk.changes); ++k) { ChangeInfo change = chunk.changes[k]; for (int f = 0; f < arrcount(functions); ++f) { FunctionInFile& function = functions[f]; if (change.newFileLine >= function.firstLine && change.newFileLine <= function.lastLine) { function.changed = true; } } } for (int f = 0; f < arrcount(functions); ++f) { FunctionInFile& function = functions[f]; if (function.changed) { char* functionName = (char*) malloc(256); sprintf(functionName, "[%s] %s", chunk.newFile, function.name); arradd(functionsChanged, functionName); } } arrfree(functions); free(file.content); } } commits[i].functionsChanged = functionsChanged; } FileWriter writer = {(char*) malloc(MEGA_BYTES(100))}; if (newCommits) { for (int i = commitCount - newCommits; i < commitCount; ++i) { if (arrcount(commits[i].functionsChanged)) { writeCommit(&writer, commits[i]); writeTextInFile(&writer, ",\n"); } } } appendFile(writer, outputFile); free(writer.buffer); for (int i = commitCount-newCommits; i < commitCount; ++i) { for (int j = 0; j < arrcount(commits[i].chunks); ++j) { arrfree(commits[i].chunks[j].changes); } for (int f = 0; f < arrcount(commits[i].functionsChanged); ++f) { free(commits[i].functionsChanged[f]); } arrfree(commits[i].functionsChanged); arrfree(commits[i].chunks); } } fseek(outputFile, -3, SEEK_CUR); fwrite("\n]", 1, 2, outputFile); fclose(outputFile); printf("Done!\n"); free(ef.content); for (int i = 0; i < arrcount(commitHashes); ++i) { free(commitHashes[i]); } arrfree(commitHashes); arrfree(commits); //stb_leakcheck_dumpmem(); } return 0; #endif }
35.582386
160
0.506028
39f821f32de24e02de68f7ffda67b4a5d03b2338
3,062
cpp
C++
svntrunk/src/untabbed/BlueMatter/analysis/src/bootstrap.cpp
Bhaskers-Blu-Org1/BlueMatter
1ab2c41af870c19e2e1b1095edd1d5c85eeb9b5e
[ "BSD-2-Clause" ]
7
2020-02-25T15:46:18.000Z
2022-02-25T07:04:47.000Z
svntrunk/src/untabbed/BlueMatter/analysis/src/bootstrap.cpp
IBM/BlueMatter
5243c0ef119e599fc3e9b7c4213ecfe837de59f3
[ "BSD-2-Clause" ]
null
null
null
svntrunk/src/untabbed/BlueMatter/analysis/src/bootstrap.cpp
IBM/BlueMatter
5243c0ef119e599fc3e9b7c4213ecfe837de59f3
[ "BSD-2-Clause" ]
5
2019-06-06T16:30:21.000Z
2020-11-16T19:43:01.000Z
/* Copyright 2001, 2019 IBM Corporation * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // ********************************************************************** // File: bootstrap.cpp // Author: RSG // Date: April 17, 2002 // Class: Bootstrap // Template Parameter: TDerived (function object taking a const reference // to a vector<double> as an argument and // returning a double // Description: class encapsulating the operations associated with the // "bootstrap" procedure used to estimate uncertainties // of a function defined on a set of iid values. // ********************************************************************** #include <BlueMatter/bootstrap.hpp> #include <BlueMatter/rmsd.hpp> #include <algorithm> Bootstrap::Bootstrap(const std::vector<double>& data) : d_data(data) {} Bootstrap::~Bootstrap() {} const std::vector<double>& Bootstrap::eval(int size) { Rmsd derived; time_t foo; foo = time(&foo); unsigned int seed = foo; unsigned int length = d_data.size(); char state[256]; initstate(seed, state, 256); std::vector<double> syntheticValue; syntheticValue.reserve(d_data.size()); d_syntheticDerived.clear(); d_syntheticDerived.reserve(size); for (int j = 0; j < size; ++j) { // generate the synthetic data set by random selection from the // real dataset with replacement for (int i = 0; i < d_data.size(); ++i) { int index = random() % d_data.size(); syntheticValue.push_back(d_data[index]); } // compute the derived quantity for the synthetic dataset d_syntheticDerived.push_back(derived(syntheticValue)); syntheticValue.clear(); } std::sort(d_syntheticDerived.begin(), d_syntheticDerived.end()); return(d_syntheticDerived); }
39.25641
118
0.6855
39f94e132ec565178e4dd922c8930ca532840825
1,854
cc
C++
chrome/browser/ash/power/auto_screen_brightness/model_config.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/ash/power/auto_screen_brightness/model_config.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/ash/power/auto_screen_brightness/model_config.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2019 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. #include <cmath> #include "chrome/browser/ash/power/auto_screen_brightness/model_config.h" namespace ash { namespace power { namespace auto_screen_brightness { ModelConfig::ModelConfig() = default; ModelConfig::ModelConfig(const ModelConfig& config) = default; ModelConfig::~ModelConfig() = default; bool ModelConfig::operator==(const ModelConfig& config) const { const double kTol = 1e-10; if (std::abs(auto_brightness_als_horizon_seconds - config.auto_brightness_als_horizon_seconds) >= kTol) return false; if (enabled != config.enabled) return false; if (log_lux.size() != config.log_lux.size()) return false; for (size_t i = 0; i < log_lux.size(); ++i) { if (std::abs(log_lux[i] - config.log_lux[i]) >= kTol) return false; } if (brightness.size() != config.brightness.size()) return false; for (size_t i = 0; i < brightness.size(); ++i) { if (std::abs(brightness[i] - config.brightness[i]) >= kTol) return false; } if (metrics_key != config.metrics_key) return false; if (std::abs(model_als_horizon_seconds - config.model_als_horizon_seconds) >= kTol) return false; return true; } bool IsValidModelConfig(const ModelConfig& model_config) { if (model_config.auto_brightness_als_horizon_seconds <= 0) return false; if (model_config.log_lux.size() != model_config.brightness.size() || model_config.brightness.size() < 2) return false; if (model_config.metrics_key.empty()) return false; if (model_config.model_als_horizon_seconds <= 0) return false; return true; } } // namespace auto_screen_brightness } // namespace power } // namespace ash
25.054054
79
0.696332
39f9a1535130f5c46084c4e29bf8877c8ddc2cdd
12,330
cpp
C++
small-and-simple-programs-in-qt/computer-assembly-qt/computer-assembly/mainwindow.cpp
gusenov/examples-qt
083a51feedf6cefe82b6de79d701da23d1da2a2f
[ "MIT" ]
2
2020-09-01T18:37:30.000Z
2021-11-28T16:25:04.000Z
small-and-simple-programs-in-qt/computer-assembly-qt/computer-assembly/mainwindow.cpp
gusenov/examples-qt
083a51feedf6cefe82b6de79d701da23d1da2a2f
[ "MIT" ]
null
null
null
small-and-simple-programs-in-qt/computer-assembly-qt/computer-assembly/mainwindow.cpp
gusenov/examples-qt
083a51feedf6cefe82b6de79d701da23d1da2a2f
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug> #include <QDesktopServices> #include <QUrl> #include <QDir> #include <QMessageBox> // Конструктор: MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), // вызов родительского конструктора. ui(new Ui::MainWindow) { // Приложение пока ещё не инциализировано: isInitialized = false; ui->setupUi(this); // Установить фиксированный размер окна: this->setFixedSize(QSize(width(), height())); // Установка иконки для окна программы: setWindowIcon(QIcon("://Home-Server-icon.png")); // Создание экземпляра окна в котором отображается информация о программе: about = new About(this); // Делаем окно О программе… модальным: about->setWindowFlags(Qt::Dialog); about->setWindowModality(Qt::WindowModal); // Окно для печати: print = new Print(this); // Делаем окно для печати модальным: print->setWindowFlags(Qt::Dialog); print->setWindowModality(Qt::WindowModal); // Настройка моделей для выпадающих списков: setupModels(); isInitialized = true; // приложение инициализировано. checkCompatibility(); // проверка совместимости выбранных компонентов. connect(ui->widgetSelectVideoCard, SIGNAL(checkCompatibilitySignal()), this, SLOT(checkCompatibility())); connect(ui->widgetSelectHDD, SIGNAL(checkCompatibilitySignal()), this, SLOT(checkCompatibility())); } // Настройка моделей данных для выпадающих списков: void MainWindow::setupModels() { // Создаем модель данных приложения: appDataModel = new AppModel("://data.csv"); // Создаем и устанавливаем модели данных для выпадающих списков: modelVideoCard = new QStringListModel(appDataModel->getVideoCardStringList()); ui->widgetSelectVideoCard->config(modelVideoCard, appDataModel, DeviceType::VideoCard); modelMotherboard = new QStringListModel(appDataModel->getMotherboardStringList()); ui->comboBoxMotherboardChoice->setModel(modelMotherboard); modelHDD = new QStringListModel(appDataModel->getHddStringList()); ui->widgetSelectHDD->config(modelHDD, appDataModel, DeviceType::HDD); modelCPU = new QStringListModel(appDataModel->getCpuStringList()); ui->comboBoxCPUChoice->setModel(modelCPU); modelPowerSupply = new QStringListModel(appDataModel->getPowerSupplyStringList()); ui->comboBoxPowerSupplyChoice->setModel(modelPowerSupply); modelRAM = new QStringListModel(appDataModel->getRamStringList()); ui->comboBoxRAMChoice->setModel(modelRAM); } // Деструктор: MainWindow::~MainWindow() { delete ui; // Удаление экземпляра окна в котором отображается информация о программе: if (about) delete about; // Удаление окна печати: if (print) delete print; // Удаление модели данных программы: if (appDataModel) delete appDataModel; // Удаление моделей данных выпадающих списков: if (modelVideoCard) delete modelVideoCard; if (modelMotherboard) delete modelMotherboard; if (modelHDD) delete modelHDD; if (modelCPU) delete modelCPU; if (modelPowerSupply) delete modelPowerSupply; if (modelRAM) delete modelRAM; // Удаление временного файла в котором хранится информация о проекте: if (filePathProjectInfo != nullptr) { if (QFile(*filePathProjectInfo).remove()) { qDebug() << "Файл" << *filePathProjectInfo << "удален"; } else { qDebug() << "Проблемы при удалении файла" << *filePathProjectInfo; } delete filePathProjectInfo; } } // Выход из программы: void MainWindow::on_actionExit_triggered() { QApplication::quit(); // выход. } // Обработчик события выбора пункта главного меню Справка → О программе Сборка ПК…: void MainWindow::on_actionAbout_triggered() { about->show(); // показать окно. } // Обработчик события смены материнской платы: void MainWindow::on_comboBoxMotherboardChoice_currentIndexChanged(int index) { // Показать характеристики выбранного компонента: ui->plainTextEditMotherboardSpecifications->setPlainText( appDataModel->getSpecificationsByIndex(DeviceType::Motherboard, index) ); // Пересчитать цену в завимисости от количества: priceMotherboard = appDataModel->getPriceByIndex(DeviceType::Motherboard, index); ui->labelMotherboardPriceValue->setText( QString::number(priceMotherboard) + " ₽" ); // Проверить совместимость: checkCompatibility(); } // Обработчик события смены процессора: void MainWindow::on_comboBoxCPUChoice_currentIndexChanged(int index) { // Показать характеристики выбранного компонента: ui->plainTextEditCPUSpecifications->setPlainText( appDataModel->getSpecificationsByIndex(DeviceType::CPU, index) ); // Пересчитать цену в завимисости от количества: priceCPU = appDataModel->getPriceByIndex(DeviceType::CPU, index); // qDebug() << priceCPU; ui->labelCPUPriceValue->setText( QString::number(priceCPU) + " ₽" ); // Проверить совместимость: checkCompatibility(); } // Обработчик события смены блока питания: void MainWindow::on_comboBoxPowerSupplyChoice_currentIndexChanged(int index) { // Показать характеристики выбранного компонента: ui->plainTextEditPowerSupplySpecifications->setPlainText( appDataModel->getSpecificationsByIndex(DeviceType::PowerSupply, index) ); // Пересчитать цену в завимисости от количества: pricePowerSupply = appDataModel->getPriceByIndex(DeviceType::PowerSupply, index); ui->labelPowerSupplyPriceValue->setText( QString::number(pricePowerSupply) + " ₽" ); // Проверить совместимость: checkCompatibility(); } // Обработчик события смены оперативной памяти: void MainWindow::on_comboBoxRAMChoice_currentIndexChanged(int index) { // Показать характеристики выбранного компонента: ui->plainTextEditRAMSpecifications->setPlainText( appDataModel->getSpecificationsByIndex(DeviceType::RAM, index) ); // Пересчитать цену в завимисости от количества: priceRAM = ui->spinBoxRAMQuantityValue->value(); on_spinBoxRAMQuantityValue_valueChanged(priceRAM); // Проверить совместимость: checkCompatibility(); } // Обработчик события смены количества оперативной памяти: void MainWindow::on_spinBoxRAMQuantityValue_valueChanged(int arg1) { int currentRAMIndex = ui->comboBoxRAMChoice->currentIndex(); if (currentRAMIndex == -1) return; // Пересчитать цену в завимисости от количества: priceRAM = appDataModel->getPriceByIndex(DeviceType::RAM, currentRAMIndex) * arg1; ui->labelRAMPriceValue->setText( QString::number(priceRAM) + " ₽" ); } // Метод для получения итоговой цены: int MainWindow::getTotalPrice() { // qDebug() << "Видеокарты = " << ui->widgetSelectVideoCard->getPrice(); // qDebug() << "Мат. плата = " << priceMotherboard; // qDebug() << "Диски = " << ui->widgetSelectHDD->getPrice(); // qDebug() << "ЦП = " << priceCPU; // qDebug() << "Питание = " << pricePowerSupply; // qDebug() << "ОЗУ = " << priceRAM; return ui->widgetSelectVideoCard->getPrice() + priceMotherboard + ui->widgetSelectHDD->getPrice() + priceCPU + pricePowerSupply + priceRAM; } // Обработчик нажатия на кнопку // "Собрать готовое решение персонального компьютера и вывести цену": void MainWindow::on_pushButtonBuild_clicked() { // Форматируем текст по шаблону: QString result = QString("%1" "%2 = %3\n%4\n\n" "%5" "%6 = %7\n%8\n\n" "%9 = %10\n%11\n\n" "%12 x%13 = %14\n%15\n\n\n" "ИТОГО: %16 ₽").arg( ui->widgetSelectVideoCard->getText(), ui->comboBoxMotherboardChoice->currentText(), ui->labelMotherboardPriceValue->text(), ui->plainTextEditMotherboardSpecifications->toPlainText(), ui->widgetSelectHDD->getText() ).arg( ui->comboBoxCPUChoice->currentText(), ui->labelCPUPriceValue->text(), ui->plainTextEditCPUSpecifications->toPlainText() ).arg( ui->comboBoxPowerSupplyChoice->currentText(), ui->labelPowerSupplyPriceValue->text(), ui->plainTextEditPowerSupplySpecifications->toPlainText(), ui->comboBoxRAMChoice->currentText(), QString::number(ui->spinBoxRAMQuantityValue->value()), ui->labelRAMPriceValue->text(), ui->plainTextEditRAMSpecifications->toPlainText(), QString::number(getTotalPrice()) ); print->setResultText(result); print->show(); } // Метод для открытия файла из ресурсов приложения // (этот метод нужен для того чтобы скопировать файл из // ресурсов программы во временную папку, а потом уже из // временной папки открыть его внешней программой): void MainWindow::openFileFromRes(QString filePathInRes, QString* output_path) { // Путь к папке с программой: qDebug() << "applicationDirPath =" << QCoreApplication::applicationDirPath(); // Путь к временной папке: qDebug() << "tempPath =" << QDir::tempPath(); // Файл и его путь: QFile input_file(filePathInRes); // Открытие файла: if (!input_file.open(QFile::ReadOnly | QFile::Text)) { qDebug() << "Невозможно открыть файл для чтения"; return; } // Чтение содежимого файла: QTextStream in(&input_file); QString myText = in.readAll(); // Закрытие файла: input_file.close(); // Путь к временному файлу во временной папке: *output_path = QDir::temp().filePath(QFileInfo(input_file).fileName()); // Выходной временный файл: QFile output_file(*output_path); // Открытие временного файла: if (!output_file.open(QIODevice::WriteOnly)) { // Закрытие временного файла: output_file.close(); return; } else { // Копирование входного файла во временный файл: QTextStream out(&output_file); out << myText; // Закрытие временного файла: output_file.close(); } // Запуск на открытие временного в операционной системе // (для *.html файлов откроётся браузер): QDesktopServices::openUrl(QUrl("file:///" + *output_path)); } // Обработчик события выбора пункта главного меню Справка → Информация о проекте: void MainWindow::on_actionInfo_triggered() { openFileFromRes(":/info.html", filePathProjectInfo); } // Метод для проверки совместимости выбранных устройств: void MainWindow::checkCompatibility() { if (!isInitialized) return; // Получаем текстовую информацию о результатах совместимости: QString compatibilityInfo = appDataModel->getCompatibilityInfo( ui->widgetSelectVideoCard->getDeviceIndexes(), ui->comboBoxMotherboardChoice->currentIndex(), ui->widgetSelectHDD->getDeviceIndexes(), ui->comboBoxCPUChoice->currentIndex(), ui->comboBoxPowerSupplyChoice->currentIndex(), ui->comboBoxRAMChoice->currentIndex() ); // Отображаем текстовую информацию о результатах совместимости: ui->plainTextEditCompatibilityInfo->setPlainText(compatibilityInfo); // Палитра цветов: QPalette p = ui->plainTextEditCompatibilityInfo->palette(); // Если есть какая-то несовместимость: if (compatibilityInfo.contains("не совместим")) { p.setColor(QPalette::Base, Qt::white); // делаем текст красным. p.setColor(QPalette::Text, Qt::red); ui->pushButtonBuild->setEnabled(false); // выключить кнопку сборки. // Иначе: } else { p.setColor(QPalette::Base, Qt::white); p.setColor(QPalette::Text, Qt::black); ui->pushButtonBuild->setEnabled(true); // включить кнопку сборки. } ui->plainTextEditCompatibilityInfo->setPalette(p); }
32.88
110
0.66253
39f9e16fdc0f4ff2f6f202000875bfcb3f0960f3
15,736
cpp
C++
oblibtest/testclot.cpp
uesp/tes4lib
7b426c9209ff7996d3d763e6d4e217abfefae406
[ "MIT" ]
1
2021-02-07T07:32:14.000Z
2021-02-07T07:32:14.000Z
oblibtest/testclot.cpp
uesp/tes4lib
7b426c9209ff7996d3d763e6d4e217abfefae406
[ "MIT" ]
null
null
null
oblibtest/testclot.cpp
uesp/tes4lib
7b426c9209ff7996d3d763e6d4e217abfefae406
[ "MIT" ]
null
null
null
/*=========================================================================== * * File: TestClot.CPP * Author: Dave Humphrey (uesp@sympatico.ca) * Created On: April 17, 2006 * * Description * *=========================================================================*/ /* Include Files */ #include "testclot.h" /*=========================================================================== * * Begin Local Definitions * *=========================================================================*/ testclot_t g_TestData = { 0x00170000, { 1, 2.3f }, OB_CLOTFLAG_HIDEAMULET, 120, 0x00170001, "cloth_test", "Clothing Name", "model1.nif", "model2.nif", "model3.nif", "model4.nif", "icon1.dds", "icon2.dds", 0x00170002 }; static testclot_t g_TestValues[] = { { 0x00170000, { 1, 2.3f }, 0, 120, 0x00123, "cloth_test", "Clothing Name", "model1.nif", "model2.nif", "model3.nif", "model4.nif", "icon1.dds", "icon2.dds", 0x00040002 }, { 0x00170002, { 1, 2 }, OB_BIPEDFLAG_HEAD, 5, 0, "cloth_head", "Clothing Test", "model1.nif", NULL, NULL, NULL, "icon1.dds", NULL, 0 }, { 0x00170003, { 1, 2 }, OB_BIPEDFLAG_HAIR, 5, 0, "cloth_hair", "Clothing Test", "model1.nif", NULL, NULL, NULL, "icon1.dds", NULL, 0 }, { 0x00170004, { 1, 2 }, OB_BIPEDFLAG_UPPERBODY, 5, 0, "cloth_upperbody", "Clothing Test", "model1.nif", NULL, NULL, NULL, "icon1.dds", NULL, 0 }, { 0x00170005, { 1, 2 }, OB_BIPEDFLAG_LOWERBODY, 5, 0, "cloth_lowerbody", "Clothing Test", "model1.nif", NULL, NULL, NULL, "icon1.dds", NULL, 0 }, { 0x00170006, { 1, 2 }, OB_BIPEDFLAG_HAND, 5, 0, "cloth_hand", "Clothing Test", "model1.nif", NULL, NULL, NULL, "icon1.dds", NULL, 0 }, { 0x00170007, { 1, 2 }, OB_BIPEDFLAG_FOOT, 5, 0, "cloth_foot", "Clothing Test", "model1.nif", NULL, NULL, NULL, "icon1.dds", NULL, 0 }, { 0x00170008, { 1, 2 }, OB_BIPEDFLAG_RIGHTRING, 5, 0, "cloth_rightring", "Clothing Test", "model1.nif", NULL, NULL, NULL, "icon1.dds", NULL, 0 }, { 0x00170009, { 1, 2 }, OB_BIPEDFLAG_LEFTRING, 5, 0, "cloth_leftring", "Clothing Test", "model1.nif", NULL, NULL, NULL, "icon1.dds", NULL, 0 }, { 0x0017000A, { 1, 2 }, OB_BIPEDFLAG_AMULET, 5, 0, "cloth_amulet", "Clothing Test", "model1.nif", NULL, NULL, NULL, "icon1.dds", NULL, 0 }, { 0x0017000B, { 1, 2 }, OB_BIPEDFLAG_WEAPON, 5, 0, "cloth_weapon", "Clothing Test", "model1.nif", NULL, NULL, NULL, "icon1.dds", NULL, 0 }, { 0x0017000C, { 1, 2 }, OB_BIPEDFLAG_BACKWEAPON, 5, 0, "cloth_backweapon", "Clothing Test", "model1.nif", NULL, NULL, NULL, "icon1.dds", NULL, 0 }, { 0x0017000D, { 1, 2 }, OB_BIPEDFLAG_SIDEWEAPON, 5, 0, "cloth_sideweapon", "Clothing Test", "model1.nif", NULL, NULL, NULL, "icon1.dds", NULL, 0 }, { 0x0017000E, { 1, 2 }, OB_BIPEDFLAG_QUIVER, 5, 0, "cloth_quiver", "Clothing Test", "model1.nif", NULL, NULL, NULL, "icon1.dds", NULL, 0 }, { 0x0017000F, { 1, 2 }, OB_BIPEDFLAG_SHIELD, 5, 0, "cloth_shield", "Clothing Test", "model1.nif", NULL, NULL, NULL, "icon1.dds", NULL, 0 }, { 0x00170010, { 1, 2 }, OB_BIPEDFLAG_TORCH, 5, 0, "cloth_torch", "Clothing Test", "model1.nif", NULL, NULL, NULL, "icon1.dds", NULL, 0 }, { 0x00170011, { 1, 2 }, OB_BIPEDFLAG_TAIL, 5, 0, "cloth_tail", "Clothing Test", "model1.nif", NULL, NULL, NULL, "icon1.dds", NULL, 0 }, { 0x00170012, { 1, 2 }, OB_CLOTFLAG_HIDEAMULET, 5, 0, "cloth_hideamulet", "Clothing Test", "model1.nif", NULL, NULL, NULL, "icon1.dds", NULL, 0 }, { 0x00170013, { 1, 2 }, OB_CLOTFLAG_HIDERINGS, 5, 0, "cloth_hiderings", "Clothing Test", "model1.nif", NULL, NULL, NULL, "icon1.dds", NULL, 0 }, { 0x00170014, { 1, 2 }, OB_CLOTFLAG_NONPLAYABLE, 5, 0, "cloth_nonplayable", "Clothing Test", "model1.nif", NULL, NULL, NULL, "icon1.dds", NULL, 0 }, { 0x00170014, { 0, 0 }, 0, 5, 0, "cloth_null", NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0 }, { 0, { 0, 0 }, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0 } }; /*=========================================================================== * End of Local Definitions *=========================================================================*/ /*=========================================================================== * * Function - bool TestClot_SetGet (void); * * Tests basic set/get methods of an CLOT record. * *=========================================================================*/ bool TestClot_SetGet (void) { CObClotRecord Record; OBTEST_LEVEL("CLOT Set/Get") Record.InitializeNew(); OBTEST_START_TEST("Editor ID") Record.SetEditorID(g_TestData.pEditorID); OBTEST_DOSTRCOMPARE(Record.GetEditorID(), ==, g_TestData.pEditorID) OBTEST_END_TEST() OBTEST_START_TEST("Form ID") Record.SetFormID(g_TestData.FormID); OBTEST_DOINTCOMPARE(Record.GetFormID(), ==, g_TestData.FormID) OBTEST_END_TEST() OBTEST_START_TEST("Item Name") Record.SetItemName(g_TestData.pItemName); OBTEST_DOSTRCOMPARE(Record.GetItemName(), ==, g_TestData.pItemName) OBTEST_END_TEST() OBTEST_START_TEST("Model1") Record.SetModel(g_TestData.pModel1); OBTEST_DOSTRCOMPARE(Record.GetModel(), ==, g_TestData.pModel1) OBTEST_END_TEST() OBTEST_START_TEST("Model2") Record.SetModel2(g_TestData.pModel2); OBTEST_DOSTRCOMPARE(Record.GetModel2(), ==, g_TestData.pModel2) OBTEST_END_TEST() OBTEST_START_TEST("Model3") Record.SetModel3(g_TestData.pModel3); OBTEST_DOSTRCOMPARE(Record.GetModel3(), ==, g_TestData.pModel3) OBTEST_END_TEST() OBTEST_START_TEST("Model4") Record.SetModel4(g_TestData.pModel4); OBTEST_DOSTRCOMPARE(Record.GetModel4(), ==, g_TestData.pModel4) OBTEST_END_TEST() OBTEST_START_TEST("Icon1") Record.SetIcon(g_TestData.pIcon1); OBTEST_DOSTRCOMPARE(Record.GetIcon(), ==, g_TestData.pIcon1) OBTEST_END_TEST() OBTEST_START_TEST("Icon2") Record.SetIcon2(g_TestData.pIcon2); OBTEST_DOSTRCOMPARE(Record.GetIcon2(), ==, g_TestData.pIcon2) OBTEST_END_TEST() OBTEST_START_TEST("Value") Record.SetValue(g_TestData.Data.Value); OBTEST_DOINTCOMPARE(Record.GetValue(), ==, g_TestData.Data.Value) OBTEST_END_TEST() OBTEST_START_TEST("Weight") Record.SetWeight(g_TestData.Data.Weight); OBTEST_DOFLTCOMPARE(Record.GetWeight(), ==, g_TestData.Data.Weight) OBTEST_END_TEST() OBTEST_START_TEST("Set Hide Amulet (true)") Record.SetHideAmulet(true); OBTEST_DOINTCOMPARE(Record.IsHideAmulet(), ==, true) OBTEST_END_TEST() OBTEST_START_TEST("Set Hide Amulet (false)") Record.SetHideAmulet(false); OBTEST_DOINTCOMPARE(Record.IsHideAmulet(), ==, false) OBTEST_END_TEST() OBTEST_START_TEST("Set Hide Rings (true)") Record.SetHideRings(true); OBTEST_DOINTCOMPARE(Record.IsHideRings(), ==, true) OBTEST_END_TEST() OBTEST_START_TEST("Set Hide Rings (false)") Record.SetHideRings(false); OBTEST_DOINTCOMPARE(Record.IsHideRings(), ==, false) OBTEST_END_TEST() OBTEST_START_TEST("Set Playable (true)") Record.SetPlayable(true); OBTEST_DOINTCOMPARE(Record.IsPlayable(), ==, true) OBTEST_END_TEST() OBTEST_START_TEST("Set Playable (false)") Record.SetPlayable(false); OBTEST_DOINTCOMPARE(Record.IsPlayable(), ==, false) OBTEST_END_TEST() OBTEST_START_TEST("Set Biped Flags") Record.SetBipedFlags(OB_BIPEDFLAG_HEAD); OBTEST_DOINTCOMPARE(Record.GetBipedFlags(), ==, OB_BIPEDFLAG_HEAD) OBTEST_END_TEST() OBTEST_START_TEST("Clear Biped Flags") Record.ClearBipedFlags(); OBTEST_DOINTCOMPARE(Record.GetBipedFlags(), ==, 0) OBTEST_END_TEST() OBTEST_START_TEST("Set Biped Flags (all)") Record.SetBipedFlags(OB_BIPEDFLAG_MASK); OBTEST_DOINTCOMPARE(Record.GetBipedFlags(), ==, OB_BIPEDFLAG_MASK) OBTEST_END_TEST() OBTEST_START_TEST("Check Script (0)") OBTEST_DOINTCOMPARE(Record.GetScript(), ==, OB_FORMID_NULL) OBTEST_END_TEST() OBTEST_START_TEST("Set Script") Record.SetScript(0x1234); OBTEST_DOINTCOMPARE(Record.GetScript(), ==, 0x1234) OBTEST_END_TEST() OBTEST_START_TEST("Check Enchantment") OBTEST_DOINTCOMPARE(Record.GetEnchantment(), ==, OB_FORMID_NULL) OBTEST_END_TEST() OBTEST_START_TEST("Set Enchantment") Record.SetEnchantment(0x55668); OBTEST_DOINTCOMPARE(Record.GetEnchantment(), ==, 0x55668) OBTEST_END_TEST() OBTEST_START_TEST("Set Enchantment Points") Record.SetEnchantPoints(101); OBTEST_DOINTCOMPARE(Record.GetEnchantPoints(), ==, 101) OBTEST_END_TEST() return (true); } /*=========================================================================== * End of Function TestClot_SetGet() *=========================================================================*/ /*=========================================================================== * * Function - bool TestClot_Output (File); * * Outputs basic CLOT records to the given file. * *=========================================================================*/ bool TestClot_Output (CObEspFile& File) { CObClotRecord* pRecord; CObBaseRecord* pBase; dword Index; OBTEST_LEVEL("CLOT Output") for (Index = 0; g_TestValues[Index].pItemName != NULL; ++Index) { OBTEST_START_TEST("Create new record") pBase = File.AddNewRecord(OB_NAME_CLOT); OBTEST_DOCOMPARE(pBase, !=, NULL) OBTEST_END_TEST() OBTEST_START_TEST("Check class") pRecord = ObCastClass(CObClotRecord, pBase); OBTEST_DOCOMPARE(pRecord, !=, NULL) OBTEST_END_TEST() if (pRecord == NULL) continue; pRecord->SetFormID(g_TestValues[Index].FormID); if (g_TestValues[Index].pItemName != NULL) pRecord->SetItemName(g_TestValues[Index].pItemName); if (g_TestValues[Index].pEditorID != NULL) pRecord->SetEditorID(g_TestValues[Index].pEditorID); if (g_TestValues[Index].pModel1 != NULL) pRecord->SetModel(g_TestValues[Index].pModel1); if (g_TestValues[Index].pModel2 != NULL) pRecord->SetModel2(g_TestValues[Index].pModel2); if (g_TestValues[Index].pModel3 != NULL) pRecord->SetModel3(g_TestValues[Index].pModel3); if (g_TestValues[Index].pModel4 != NULL) pRecord->SetModel4(g_TestValues[Index].pModel4); if (g_TestValues[Index].pIcon1 != NULL) pRecord->SetIcon(g_TestValues[Index].pIcon1); if (g_TestValues[Index].pIcon2 != NULL) pRecord->SetIcon2(g_TestValues[Index].pIcon2); if (g_TestValues[Index].ScriptFormID != 0) pRecord->SetScript(g_TestValues[Index].ScriptFormID); if (g_TestValues[Index].EnchantFormID != 0) pRecord->SetEnchantment(g_TestValues[Index].EnchantFormID); if (g_TestValues[Index].EnchantPts != 0) pRecord->SetEnchantPoints(g_TestValues[Index].EnchantPts); pRecord->SetValue(g_TestValues[Index].Data.Value); pRecord->SetWeight(g_TestValues[Index].Data.Weight); pRecord->SetHideRings((g_TestValues[Index].Flags & OB_CLOTFLAG_HIDERINGS) != 0); pRecord->SetHideAmulet((g_TestValues[Index].Flags & OB_CLOTFLAG_HIDEAMULET) != 0); pRecord->SetPlayable((g_TestValues[Index].Flags & OB_CLOTFLAG_NONPLAYABLE) == 0); pRecord->ClearBipedFlags(); pRecord->SetBipedFlags(g_TestValues[Index].Flags & OB_BIPEDFLAG_MASK); } return (true); } /*=========================================================================== * End of Function TestClot_Output() *=========================================================================*/ /*=========================================================================== * * Function - bool TestClot_Input (File); * * Checks the values of CLOT records in the given file and ensures they * match those previously output. * *=========================================================================*/ bool TestClot_Input (CObEspFile& File) { CObBaseRecord* pBase; CObClotRecord* pRecord; dword Index; OBTEST_LEVEL("CLOT Input") for (Index = 0; g_TestValues[Index].pItemName != NULL; ++Index) { OnTestOutputNote("Testing Record (%d, '%s')", g_TestValues[Index].FormID, g_TestValues[Index].pEditorID); OBTEST_START_TEST("Find record by formID") pBase = File.FindFormID(g_TestValues[Index].FormID); OBTEST_DOCOMPARE(pBase, !=, NULL) OBTEST_END_TEST() if (pBase == NULL) continue; OBTEST_START_TEST("Check record type") OBTEST_DOCOMPARE(pBase->IsRecord(), ==, true) OBTEST_END_TEST() if (!pBase->IsRecord()) continue; OBTEST_START_TEST("Check record name") OBTEST_DOCOMPARE(pBase->GetName(), ==, OB_NAME_CLOT) OBTEST_END_TEST() if (pBase->GetName() != OB_NAME_CLOT) continue; OBTEST_START_TEST("Check class") pRecord = ObCastClass(CObClotRecord, pBase); OBTEST_DOCOMPARE(pRecord, !=, NULL) OBTEST_END_TEST() if (pRecord == NULL) continue; OBTEST_START_TEST("Check item name") OBTEST_DOSTRCOMPARE1(pRecord->GetItemName(), ==, g_TestValues[Index].pItemName); OBTEST_END_TEST() OBTEST_START_TEST("Check editor ID name") OBTEST_DOSTRCOMPARE1(pRecord->GetEditorID(), ==, g_TestValues[Index].pEditorID); OBTEST_END_TEST() OBTEST_START_TEST("Check model1") OBTEST_DOSTRCOMPARE1(pRecord->GetModel(), ==, g_TestValues[Index].pModel1); OBTEST_END_TEST() OBTEST_START_TEST("Check model2") OBTEST_DOSTRCOMPARE1(pRecord->GetModel2(), ==, g_TestValues[Index].pModel2); OBTEST_END_TEST() OBTEST_START_TEST("Check model3") OBTEST_DOSTRCOMPARE1(pRecord->GetModel3(), ==, g_TestValues[Index].pModel3); OBTEST_END_TEST() OBTEST_START_TEST("Check model4") OBTEST_DOSTRCOMPARE1(pRecord->GetModel4(), ==, g_TestValues[Index].pModel4); OBTEST_END_TEST() OBTEST_START_TEST("Check icon1") OBTEST_DOSTRCOMPARE1(pRecord->GetIcon(), ==, g_TestValues[Index].pIcon1); OBTEST_END_TEST() OBTEST_START_TEST("Check icon2") OBTEST_DOSTRCOMPARE1(pRecord->GetIcon2(), ==, g_TestValues[Index].pIcon2); OBTEST_END_TEST() OBTEST_START_TEST("Check weight") OBTEST_DOINTCOMPARE(pRecord->GetWeight(), ==, g_TestValues[Index].Data.Weight); OBTEST_END_TEST() OBTEST_START_TEST("Check value") OBTEST_DOINTCOMPARE(pRecord->GetValue(), ==, g_TestValues[Index].Data.Value); OBTEST_END_TEST() OBTEST_START_TEST("Check Biped Flags") OBTEST_DOINTCOMPARE(pRecord->GetBipedFlags(), ==, (g_TestValues[Index].Flags & OB_BIPEDFLAG_MASK)); OBTEST_END_TEST() OBTEST_START_TEST("Check hide amulet") OBTEST_DOINTCOMPARE(pRecord->IsHideAmulet(), ==, ((g_TestValues[Index].Flags & OB_CLOTFLAG_HIDEAMULET) != 0)); OBTEST_END_TEST() OBTEST_START_TEST("Check hide rings") OBTEST_DOINTCOMPARE(pRecord->IsHideRings(), ==, ((g_TestValues[Index].Flags & OB_CLOTFLAG_HIDERINGS) != 0)); OBTEST_END_TEST() OBTEST_START_TEST("Check playable") OBTEST_DOINTCOMPARE(pRecord->IsPlayable(), ==, ((g_TestValues[Index].Flags & OB_CLOTFLAG_NONPLAYABLE) == 0)); OBTEST_END_TEST() OBTEST_START_TEST("Check script formID") OBTEST_DOINTCOMPARE(pRecord->GetScript(), ==, g_TestValues[Index].ScriptFormID); OBTEST_END_TEST() OBTEST_START_TEST("Check enchantment formID") OBTEST_DOINTCOMPARE(pRecord->GetEnchantment(), ==, g_TestValues[Index].EnchantFormID); OBTEST_END_TEST() OBTEST_START_TEST("Check enchant points") OBTEST_DOINTCOMPARE(pRecord->GetEnchantPoints(), ==, g_TestValues[Index].EnchantPts); OBTEST_END_TEST() } return (true); } /*=========================================================================== * End of Function TestClot_Input() *=========================================================================*/
36.766355
129
0.626843
39f9e5213e4adc4f7734c8c8558c63ef5473e7b3
189,255
cpp
C++
src/parser/flex_lexer.cpp
ankushrayabhari/sql-parser
004408f43d0c96a017087bc89823d44a72f3f201
[ "MIT" ]
null
null
null
src/parser/flex_lexer.cpp
ankushrayabhari/sql-parser
004408f43d0c96a017087bc89823d44a72f3f201
[ "MIT" ]
null
null
null
src/parser/flex_lexer.cpp
ankushrayabhari/sql-parser
004408f43d0c96a017087bc89823d44a72f3f201
[ "MIT" ]
null
null
null
#line 2 "flex_lexer.cpp" #line 4 "flex_lexer.cpp" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 4 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif #ifdef yy_create_buffer #define hsql__create_buffer_ALREADY_DEFINED #else #define yy_create_buffer hsql__create_buffer #endif #ifdef yy_delete_buffer #define hsql__delete_buffer_ALREADY_DEFINED #else #define yy_delete_buffer hsql__delete_buffer #endif #ifdef yy_scan_buffer #define hsql__scan_buffer_ALREADY_DEFINED #else #define yy_scan_buffer hsql__scan_buffer #endif #ifdef yy_scan_string #define hsql__scan_string_ALREADY_DEFINED #else #define yy_scan_string hsql__scan_string #endif #ifdef yy_scan_bytes #define hsql__scan_bytes_ALREADY_DEFINED #else #define yy_scan_bytes hsql__scan_bytes #endif #ifdef yy_init_buffer #define hsql__init_buffer_ALREADY_DEFINED #else #define yy_init_buffer hsql__init_buffer #endif #ifdef yy_flush_buffer #define hsql__flush_buffer_ALREADY_DEFINED #else #define yy_flush_buffer hsql__flush_buffer #endif #ifdef yy_load_buffer_state #define hsql__load_buffer_state_ALREADY_DEFINED #else #define yy_load_buffer_state hsql__load_buffer_state #endif #ifdef yy_switch_to_buffer #define hsql__switch_to_buffer_ALREADY_DEFINED #else #define yy_switch_to_buffer hsql__switch_to_buffer #endif #ifdef yypush_buffer_state #define hsql_push_buffer_state_ALREADY_DEFINED #else #define yypush_buffer_state hsql_push_buffer_state #endif #ifdef yypop_buffer_state #define hsql_pop_buffer_state_ALREADY_DEFINED #else #define yypop_buffer_state hsql_pop_buffer_state #endif #ifdef yyensure_buffer_stack #define hsql_ensure_buffer_stack_ALREADY_DEFINED #else #define yyensure_buffer_stack hsql_ensure_buffer_stack #endif #ifdef yylex #define hsql_lex_ALREADY_DEFINED #else #define yylex hsql_lex #endif #ifdef yyrestart #define hsql_restart_ALREADY_DEFINED #else #define yyrestart hsql_restart #endif #ifdef yylex_init #define hsql_lex_init_ALREADY_DEFINED #else #define yylex_init hsql_lex_init #endif #ifdef yylex_init_extra #define hsql_lex_init_extra_ALREADY_DEFINED #else #define yylex_init_extra hsql_lex_init_extra #endif #ifdef yylex_destroy #define hsql_lex_destroy_ALREADY_DEFINED #else #define yylex_destroy hsql_lex_destroy #endif #ifdef yyget_debug #define hsql_get_debug_ALREADY_DEFINED #else #define yyget_debug hsql_get_debug #endif #ifdef yyset_debug #define hsql_set_debug_ALREADY_DEFINED #else #define yyset_debug hsql_set_debug #endif #ifdef yyget_extra #define hsql_get_extra_ALREADY_DEFINED #else #define yyget_extra hsql_get_extra #endif #ifdef yyset_extra #define hsql_set_extra_ALREADY_DEFINED #else #define yyset_extra hsql_set_extra #endif #ifdef yyget_in #define hsql_get_in_ALREADY_DEFINED #else #define yyget_in hsql_get_in #endif #ifdef yyset_in #define hsql_set_in_ALREADY_DEFINED #else #define yyset_in hsql_set_in #endif #ifdef yyget_out #define hsql_get_out_ALREADY_DEFINED #else #define yyget_out hsql_get_out #endif #ifdef yyset_out #define hsql_set_out_ALREADY_DEFINED #else #define yyset_out hsql_set_out #endif #ifdef yyget_leng #define hsql_get_leng_ALREADY_DEFINED #else #define yyget_leng hsql_get_leng #endif #ifdef yyget_text #define hsql_get_text_ALREADY_DEFINED #else #define yyget_text hsql_get_text #endif #ifdef yyget_lineno #define hsql_get_lineno_ALREADY_DEFINED #else #define yyget_lineno hsql_get_lineno #endif #ifdef yyset_lineno #define hsql_set_lineno_ALREADY_DEFINED #else #define yyset_lineno hsql_set_lineno #endif #ifdef yyget_column #define hsql_get_column_ALREADY_DEFINED #else #define yyget_column hsql_get_column #endif #ifdef yyset_column #define hsql_set_column_ALREADY_DEFINED #else #define yyset_column hsql_set_column #endif #ifdef yywrap #define hsql_wrap_ALREADY_DEFINED #else #define yywrap hsql_wrap #endif #ifdef yyget_lval #define hsql_get_lval_ALREADY_DEFINED #else #define yyget_lval hsql_get_lval #endif #ifdef yyset_lval #define hsql_set_lval_ALREADY_DEFINED #else #define yyset_lval hsql_set_lval #endif #ifdef yyget_lloc #define hsql_get_lloc_ALREADY_DEFINED #else #define yyget_lloc hsql_get_lloc #endif #ifdef yyset_lloc #define hsql_set_lloc_ALREADY_DEFINED #else #define yyset_lloc hsql_set_lloc #endif #ifdef yyalloc #define hsql_alloc_ALREADY_DEFINED #else #define yyalloc hsql_alloc #endif #ifdef yyrealloc #define hsql_realloc_ALREADY_DEFINED #else #define yyrealloc hsql_realloc #endif #ifdef yyfree #define hsql_free_ALREADY_DEFINED #else #define yyfree hsql_free #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #ifndef SIZE_MAX #define SIZE_MAX (~(size_t)0) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ /* begin standard C++ headers. */ /* TODO: this is always defined, so inline it */ #define yyconst const #if defined(__GNUC__) && __GNUC__ >= 3 #define yynoreturn __attribute__((__noreturn__)) #else #define yynoreturn #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an * integer in range [0..255] for use as an array index. */ #define YY_SC_TO_UI(c) ((YY_CHAR) (c)) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE yyrestart( yyin , yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 #define YY_LESS_LINENO(n) #define YY_LINENO_REWIND_TO(ptr) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ int yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ int yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void yyrestart ( FILE *input_file , yyscan_t yyscanner ); void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner ); YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size , yyscan_t yyscanner ); void yy_delete_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner ); void yy_flush_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner ); void yypush_buffer_state ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner ); void yypop_buffer_state ( yyscan_t yyscanner ); static void yyensure_buffer_stack ( yyscan_t yyscanner ); static void yy_load_buffer_state ( yyscan_t yyscanner ); static void yy_init_buffer ( YY_BUFFER_STATE b, FILE *file , yyscan_t yyscanner ); #define YY_FLUSH_BUFFER yy_flush_buffer( YY_CURRENT_BUFFER , yyscanner) YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size , yyscan_t yyscanner ); YY_BUFFER_STATE yy_scan_string ( const char *yy_str , yyscan_t yyscanner ); YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len , yyscan_t yyscanner ); void *yyalloc ( yy_size_t , yyscan_t yyscanner ); void *yyrealloc ( void *, yy_size_t , yyscan_t yyscanner ); void yyfree ( void * , yyscan_t yyscanner ); #define yy_new_buffer yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define hsql_wrap(yyscanner) (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP typedef flex_uint8_t YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state ( yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans ( yy_state_type current_state , yyscan_t yyscanner); static int yy_get_next_buffer ( yyscan_t yyscanner ); static void yynoreturn yy_fatal_error ( const char* msg , yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (int) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 163 #define YY_END_OF_BUFFER 164 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static const flex_int16_t yy_accept[1144] = { 0, 0, 0, 160, 160, 2, 2, 164, 162, 4, 4, 162, 162, 152, 158, 152, 152, 155, 152, 152, 152, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 152, 160, 161, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 147, 0, 1, 155, 154, 153, 149, 148, 146, 150, 157, 157, 157, 157, 157, 125, 157, 157, 157, 126, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 127, 157, 157, 128, 129, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 130, 131, 132, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 133, 157, 157, 157, 157, 157, 157, 157, 157, 157, 151, 160, 159, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 156, 153, 113, 157, 114, 157, 157, 115, 116, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 137, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 117, 157, 157, 157, 157, 157, 157, 157, 157, 157, 118, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 119, 157, 157, 120, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 121, 157, 157, 122, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 123, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 124, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 157, 157, 157, 157, 157, 157, 157, 157, 83, 157, 84, 47, 85, 157, 157, 157, 86, 157, 157, 87, 157, 157, 157, 157, 157, 89, 157, 157, 157, 90, 91, 157, 157, 157, 157, 157, 157, 157, 92, 157, 157, 93, 94, 157, 157, 95, 157, 136, 157, 157, 157, 157, 157, 157, 96, 157, 97, 98, 99, 157, 101, 157, 102, 157, 157, 157, 157, 104, 157, 157, 157, 157, 157, 105, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 106, 157, 157, 157, 157, 157, 107, 108, 109, 157, 157, 140, 157, 157, 157, 157, 157, 157, 157, 157, 110, 157, 111, 157, 112, 139, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 64, 65, 157, 157, 143, 157, 157, 157, 157, 157, 157, 157, 157, 66, 157, 157, 157, 157, 157, 67, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 141, 68, 157, 157, 69, 157, 100, 157, 70, 71, 157, 157, 157, 157, 72, 73, 74, 75, 157, 138, 157, 157, 157, 76, 77, 157, 157, 157, 157, 157, 157, 78, 157, 157, 157, 157, 157, 157, 157, 79, 157, 157, 157, 157, 157, 80, 157, 157, 157, 81, 157, 157, 157, 82, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 157, 37, 157, 103, 157, 157, 38, 145, 157, 39, 157, 157, 157, 157, 40, 157, 41, 157, 42, 43, 44, 157, 45, 157, 157, 48, 49, 50, 51, 52, 157, 157, 157, 53, 135, 157, 157, 54, 157, 157, 157, 157, 55, 157, 157, 56, 134, 57, 157, 58, 157, 59, 157, 157, 157, 157, 157, 60, 61, 62, 63, 157, 157, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 17, 29, 18, 19, 20, 157, 157, 23, 21, 157, 157, 22, 24, 46, 25, 157, 157, 30, 157, 157, 31, 32, 26, 157, 157, 33, 157, 34, 157, 157, 27, 157, 157, 35, 36, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 88, 157, 11, 12, 157, 10, 13, 157, 14, 144, 28, 157, 157, 157, 15, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 157, 7, 157, 8, 9, 157, 2, 2, 2, 2, 2, 2, 5, 6, 157, 2, 2, 2, 142, 2, 0 } ; static const YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 5, 1, 1, 6, 1, 7, 6, 6, 6, 6, 6, 8, 9, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 6, 11, 12, 13, 6, 1, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 6, 1, 6, 6, 40, 1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 6, 67, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static const YY_CHAR yy_meta[68] = { 0, 1, 1, 2, 1, 3, 1, 4, 1, 1, 5, 1, 1, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 } ; static const flex_int16_t yy_base[1151] = { 0, 0, 0, 384, 380, 67, 0, 380, 7305, 133, 135, 359, 0, 7305, 7305, 131, 356, 133, 132, 318, 309, 129, 129, 138, 154, 165, 216, 146, 173, 181, 125, 144, 203, 204, 228, 245, 229, 130, 233, 291, 334, 268, 196, 245, 0, 228, 251, 0, 303, 0, 147, 213, 280, 281, 0, 0, 150, 270, 275, 289, 263, 227, 392, 459, 513, 565, 613, 665, 312, 392, 708, 394, 323, 451, 456, 759, 808, 508, 277, 510, 854, 906, 389, 560, 605, 462, 567, 169, 311, 7305, 218, 7305, 306, 210, 201, 7305, 7305, 7305, 7305, 0, 281, 272, 317, 340, 333, 553, 338, 331, 0, 450, 349, 402, 470, 374, 623, 454, 376, 402, 448, 474, 476, 676, 498, 505, 509, 509, 514, 518, 525, 549, 562, 550, 0, 568, 569, 656, 575, 585, 605, 625, 623, 714, 626, 653, 654, 652, 658, 670, 683, 683, 0, 687, 678, 706, 725, 725, 728, 717, 728, 725, 730, 763, 728, 744, 728, 751, 766, 773, 764, 771, 755, 799, 779, 772, 769, 807, 816, 785, 786, 827, 7305, 0, 7305, 0, 326, 0, 200, 0, 364, 160, 155, 0, 0, 0, 0, 849, 867, 903, 913, 957, 965, 1005, 956, 1012, 1013, 854, 1014, 1048, 1060, 1061, 1113, 1059, 1103, 1113, 957, 1149, 1155, 1204, 1191, 1202, 1166, 1217, 1252, 1240, 1265, 1267, 1286, 1300, 1310, 1321, 1345, 1394, 1328, 1357, 1375, 1398, 1441, 1489, 1416, 1430, 1452, 1488, 1506, 1499, 1540, 1538, 1543, 1556, 1588, 1589, 1597, 1635, 1623, 1633, 1642, 1661, 1681, 1724, 1690, 1732, 1738, 1744, 1780, 1778, 1791, 1818, 1822, 1859, 1867, 1871, 1830, 1897, 1914, 1915, 1940, 1926, 0, 7305, 153, 0, 833, 0, 855, 863, 0, 0, 862, 874, 890, 907, 905, 908, 1130, 904, 905, 916, 910, 942, 977, 960, 977, 0, 979, 1007, 1016, 1110, 1021, 1031, 1048, 1072, 1063, 1075, 0, 1083, 1115, 1126, 1120, 1158, 1154, 1165, 1207, 1216, 1209, 1215, 1221, 1264, 1247, 1261, 1266, 1267, 1300, 1307, 1324, 1339, 1354, 1360, 1343, 1354, 0, 1356, 1373, 1374, 1390, 1395, 1394, 1408, 1405, 1409, 1417, 0, 1438, 1442, 1450, 1467, 1483, 1497, 1487, 1488, 1492, 1498, 1541, 1526, 1555, 1553, 1561, 1557, 1591, 0, 1577, 1604, 1599, 1606, 1616, 1643, 1643, 1656, 1687, 1669, 0, 1681, 1696, 1734, 1688, 1703, 1700, 1694, 1731, 1734, 1738, 1917, 1779, 1775, 0, 145, 1962, 1964, 1969, 1993, 1998, 2012, 2028, 2018, 2023, 2057, 2072, 2059, 2072, 2112, 2111, 2116, 2152, 2154, 2171, 2176, 2196, 2207, 2219, 2217, 2245, 2261, 2273, 2299, 2275, 2313, 2321, 2343, 2357, 2362, 2346, 2375, 2403, 2391, 2407, 2439, 2410, 2454, 2465, 2474, 2490, 2503, 2509, 2525, 2544, 2532, 2570, 2579, 2591, 2586, 2595, 2620, 2625, 2637, 2662, 2673, 2678, 2707, 2715, 2729, 2727, 2767, 2769, 2772, 2801, 2810, 2812, 2813, 2855, 2851, 2857, 2862, 2900, 2893, 2907, 2942, 2956, 2961, 2972, 2994, 2996, 3016, 3018, 3019, 3044, 3058, 3060, 3073, 3103, 3114, 3127, 3155, 3168, 3120, 3180, 3188, 3209, 3222, 3220, 3234, 3266, 3263, 3274, 3307, 3306, 3285, 3317, 3345, 3356, 1776, 1781, 1776, 1795, 1830, 1846, 1856, 1893, 0, 1898, 0, 0, 0, 1924, 1977, 1970, 0, 1973, 1984, 1994, 2007, 2021, 2047, 2056, 2105, 2098, 2117, 2116, 2115, 0, 0, 2119, 2120, 2119, 2131, 2170, 2178, 2177, 0, 2170, 2218, 0, 0, 2224, 2210, 0, 2216, 0, 2233, 2222, 2221, 2230, 2246, 2267, 0, 2271, 0, 0, 0, 2266, 0, 2280, 0, 2289, 2323, 2348, 2378, 0, 2413, 2420, 2420, 2423, 2431, 0, 2449, 2469, 2452, 2472, 2495, 2504, 2524, 2516, 2520, 2533, 0, 2557, 2570, 2567, 2576, 2617, 0, 0, 2620, 2633, 2625, 0, 2643, 2634, 2633, 2662, 2654, 2679, 2683, 2692, 0, 2681, 0, 2699, 0, 0, 3360, 3368, 3384, 3396, 3394, 3425, 3411, 3428, 3440, 3470, 3478, 3482, 3486, 3517, 3524, 3533, 3535, 3564, 3569, 3577, 3588, 3618, 3627, 3629, 3665, 3670, 3681, 3699, 3706, 3715, 3724, 3748, 3757, 3772, 3798, 3806, 3814, 3835, 3848, 3849, 3860, 3864, 3896, 3902, 3907, 3911, 3922, 3948, 3959, 3959, 3964, 3976, 4002, 4012, 4023, 4051, 4055, 4064, 4095, 4104, 4108, 4144, 4148, 4156, 4190, 4178, 4204, 4210, 4232, 4239, 4250, 4255, 4271, 4286, 4297, 4302, 4318, 4344, 4333, 4365, 4380, 4386, 4378, 4420, 4421, 4424, 4432, 4464, 4472, 4473, 4486, 4498, 4507, 4524, 4523, 4549, 4567, 4553, 4596, 4597, 4608, 4639, 4643, 4648, 4679, 4682, 4692, 4703, 4711, 4729, 0, 0, 2683, 2732, 0, 2741, 2732, 2752, 2752, 2782, 2788, 2814, 2836, 0, 2838, 2864, 2882, 2872, 2881, 0, 2886, 2896, 2906, 2919, 2920, 2913, 2916, 2919, 2931, 2938, 0, 0, 2939, 2958, 0, 2965, 0, 2957, 0, 0, 2958, 3006, 3056, 3001, 0, 0, 0, 0, 3013, 0, 3029, 3054, 3044, 0, 0, 3072, 3064, 3085, 3102, 3108, 3112, 0, 3130, 3131, 3132, 3117, 3148, 3157, 3170, 3158, 3163, 3163, 3176, 3190, 3198, 0, 3206, 3211, 3226, 0, 3225, 3250, 3268, 0, 4737, 4751, 4759, 4773, 4781, 4795, 4809, 4820, 4835, 4846, 4868, 4875, 4887, 4899, 4913, 4921, 4932, 4913, 4953, 4961, 4966, 4979, 4968, 4991, 5015, 5029, 5030, 5034, 5027, 5081, 5078, 5083, 5107, 5085, 5126, 5134, 5150, 5164, 5178, 5194, 5202, 5222, 5220, 5238, 5251, 5264, 5282, 5295, 5307, 5315, 5330, 5353, 5362, 5361, 5384, 5369, 5407, 5409, 5423, 5425, 5438, 5451, 5463, 5471, 5496, 5514, 5521, 5535, 5547, 5560, 5568, 5580, 5566, 5601, 5613, 5622, 5629, 5647, 5644, 5679, 5673, 5690, 5692, 5708, 3284, 0, 3276, 0, 3329, 3340, 3348, 0, 3367, 0, 3379, 3418, 3434, 3427, 0, 3452, 0, 3459, 0, 0, 0, 3463, 0, 3461, 3464, 0, 0, 0, 0, 0, 3481, 3514, 3536, 0, 0, 3528, 3541, 0, 3524, 3542, 3533, 3568, 0, 3584, 3587, 3575, 0, 0, 3581, 0, 3586, 0, 3618, 3625, 3616, 3635, 3620, 0, 0, 0, 0, 3634, 3642, 5724, 5733, 5733, 5749, 5768, 5788, 5777, 5798, 5817, 5831, 5840, 5859, 5873, 5882, 5901, 5920, 5924, 5943, 5962, 5966, 5985, 5991, 6005, 6020, 6026, 6039, 6050, 6069, 6080, 6083, 6110, 6108, 6131, 6146, 6150, 6158, 6178, 6193, 6197, 6209, 6221, 6232, 6247, 6251, 6282, 6287, 6290, 6301, 6320, 6331, 6334, 6350, 6375, 6380, 6391, 6413, 6422, 6431, 6453, 6462, 6464, 6485, 6477, 0, 0, 0, 0, 0, 0, 3681, 3689, 0, 0, 3687, 3674, 0, 0, 0, 0, 3692, 3689, 0, 3688, 3727, 0, 0, 0, 3730, 3742, 0, 3735, 0, 3740, 3755, 0, 3754, 3774, 0, 0, 6498, 6507, 6521, 6540, 6549, 6563, 6569, 6588, 6607, 6609, 6623, 6638, 6641, 6663, 6677, 6682, 6691, 6698, 6716, 6730, 6727, 6741, 6755, 6769, 6783, 6791, 6809, 6817, 6831, 6847, 6873, 6869, 6892, 6894, 6916, 6935, 0, 3763, 0, 0, 3764, 0, 0, 3791, 0, 0, 0, 3800, 3812, 3826, 0, 6938, 6964, 6940, 6976, 6989, 6988, 6990, 7036, 7037, 7038, 7042, 7080, 7081, 7083, 7095, 3861, 0, 3867, 0, 0, 3874, 7121, 7129, 7131, 7150, 7164, 7143, 0, 0, 3880, 7175, 7189, 7194, 0, 7210, 7305, 7274, 7279, 135, 7284, 7289, 7294, 7299 } ; static const flex_int16_t yy_def[1151] = { 0, 1143, 1, 1144, 1144, 1143, 5, 1143, 1143, 1143, 1143, 1143, 1145, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1143, 1147, 1143, 1148, 1148, 1143, 1148, 1149, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1150, 1150, 63, 63, 63, 64, 64, 64, 66, 64, 63, 63, 63, 64, 64, 64, 76, 63, 63, 64, 66, 64, 64, 64, 63, 1148, 1143, 1143, 1145, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1143, 1147, 1143, 1148, 1148, 1148, 1149, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 63, 63, 63, 66, 64, 64, 76, 76, 64, 64, 66, 64, 66, 63, 63, 66, 66, 76, 63, 66, 66, 66, 63, 66, 66, 63, 76, 63, 66, 63, 63, 66, 76, 76, 63, 63, 66, 66, 63, 63, 76, 76, 76, 76, 76, 76, 76, 76, 66, 64, 76, 76, 76, 76, 76, 64, 63, 64, 66, 66, 66, 64, 66, 64, 64, 64, 64, 64, 66, 63, 66, 66, 64, 66, 66, 63, 66, 63, 63, 63, 64, 1148, 1143, 1143, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1148, 1148, 64, 63, 63, 63, 66, 66, 66, 63, 63, 63, 63, 66, 66, 217, 64, 76, 76, 76, 63, 64, 66, 63, 63, 66, 63, 64, 63, 63, 63, 63, 63, 63, 63, 63, 64, 63, 63, 66, 66, 64, 66, 63, 64, 64, 64, 66, 66, 76, 64, 63, 64, 64, 64, 63, 63, 63, 63, 76, 76, 76, 76, 63, 63, 63, 64, 64, 64, 76, 76, 76, 76, 66, 76, 66, 63, 63, 64, 66, 66, 66, 64, 64, 64, 64, 66, 63, 63, 63, 63, 63, 66, 66, 66, 66, 66, 66, 66, 63, 63, 63, 66, 66, 63, 63, 64, 66, 76, 76, 76, 76, 76, 64, 64, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 64, 64, 63, 64, 76, 63, 76, 63, 63, 64, 64, 64, 64, 64, 63, 64, 64, 64, 66, 66, 66, 66, 76, 76, 64, 64, 64, 63, 66, 66, 66, 66, 66, 76, 76, 64, 64, 63, 63, 63, 64, 64, 64, 64, 64, 64, 76, 76, 63, 76, 66, 76, 76, 76, 76, 66, 66, 66, 66, 66, 66, 66, 66, 63, 66, 64, 64, 64, 64, 63, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 66, 66, 66, 66, 63, 63, 63, 63, 63, 63, 66, 63, 66, 66, 66, 66, 76, 64, 64, 64, 63, 64, 64, 76, 76, 63, 63, 63, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 63, 63, 63, 63, 63, 63, 63, 64, 64, 76, 76, 64, 63, 63, 63, 63, 64, 66, 63, 63, 63, 63, 66, 63, 63, 63, 63, 66, 63, 63, 63, 63, 63, 66, 66, 66, 66, 66, 66, 66, 66, 63, 66, 66, 66, 66, 66, 66, 63, 63, 64, 64, 64, 64, 64, 63, 64, 64, 63, 63, 63, 63, 64, 64, 64, 64, 63, 63, 64, 66, 64, 64, 66, 64, 64, 64, 63, 63, 63, 63, 66, 64, 64, 64, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 63, 63, 66, 66, 66, 63, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 63, 63, 66, 66, 66, 66, 66, 66, 66, 64, 63, 64, 64, 64, 66, 64, 64, 64, 63, 63, 64, 64, 64, 64, 66, 66, 66, 66, 66, 66, 66, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 66, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 66, 66, 66, 66, 66, 66, 63, 64, 64, 64, 63, 63, 63, 63, 63, 63, 63, 66, 66, 64, 63, 63, 63, 63, 63, 63, 63, 63, 63, 64, 64, 64, 64, 63, 63, 63, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 1146, 63, 63, 63, 63, 63, 63, 63, 64, 64, 64, 64, 63, 63, 63, 63, 1146, 1146, 1146, 1146, 1146, 1146, 63, 63, 66, 66, 66, 63, 1146, 1146, 1146, 63, 63, 66, 1146, 66, 0, 1143, 1143, 1143, 1143, 1143, 1143, 1143 } ; static const flex_int16_t yy_nxt[7373] = { 0, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 44, 8, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 44, 46, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 85, 49, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 85, 87, 88, 88, 88, 88, 91, 99, 92, 94, 92, 95, 96, 100, 105, 101, 184, 88, 106, 109, 137, 102, 393, 103, 107, 187, 110, 188, 104, 138, 278, 156, 393, 111, 108, 113, 112, 189, 128, 114, 100, 105, 101, 115, 129, 106, 109, 137, 102, 116, 103, 107, 117, 110, 130, 104, 138, 118, 156, 119, 111, 108, 113, 112, 120, 128, 114, 132, 131, 121, 115, 129, 392, 133, 134, 135, 116, 175, 278, 117, 136, 130, 88, 88, 118, 176, 119, 93, 139, 142, 277, 120, 140, 143, 132, 131, 121, 122, 141, 144, 133, 134, 135, 276, 175, 123, 194, 136, 124, 145, 153, 125, 176, 179, 126, 139, 142, 127, 157, 140, 143, 154, 158, 146, 122, 141, 144, 155, 159, 147, 148, 149, 123, 177, 178, 124, 145, 153, 125, 150, 179, 126, 193, 151, 127, 157, 152, 189, 154, 158, 146, 190, 188, 183, 155, 159, 147, 148, 149, 185, 177, 178, 172, 195, 173, 279, 150, 174, 191, 192, 151, 195, 280, 152, 160, 195, 161, 182, 252, 162, 88, 88, 94, 92, 163, 180, 164, 165, 98, 172, 195, 173, 279, 195, 174, 184, 88, 97, 195, 280, 195, 160, 195, 161, 224, 252, 162, 195, 234, 281, 225, 163, 195, 164, 165, 166, 285, 282, 195, 167, 195, 283, 168, 169, 284, 289, 290, 195, 195, 170, 293, 224, 171, 93, 195, 234, 281, 225, 89, 195, 190, 188, 166, 285, 282, 195, 167, 1143, 283, 168, 169, 284, 289, 290, 48, 195, 170, 293, 48, 171, 183, 183, 1143, 183, 183, 183, 183, 183, 183, 1143, 183, 183, 183, 226, 300, 195, 196, 309, 197, 301, 195, 195, 195, 268, 198, 269, 199, 227, 270, 233, 195, 200, 195, 195, 294, 295, 296, 310, 297, 1143, 226, 300, 195, 196, 309, 197, 301, 195, 195, 195, 268, 198, 269, 199, 227, 270, 233, 195, 200, 195, 195, 294, 295, 296, 310, 297, 183, 183, 183, 1143, 183, 183, 183, 183, 183, 183, 235, 183, 183, 183, 236, 238, 291, 195, 201, 239, 237, 311, 202, 292, 195, 240, 307, 308, 203, 298, 195, 195, 312, 313, 195, 195, 1143, 235, 204, 299, 1143, 236, 238, 291, 195, 201, 239, 237, 311, 202, 292, 195, 240, 307, 308, 203, 298, 195, 195, 312, 313, 195, 195, 249, 319, 204, 299, 183, 205, 253, 195, 320, 195, 254, 250, 206, 195, 195, 321, 255, 251, 322, 207, 323, 324, 208, 1143, 1143, 1143, 195, 249, 319, 195, 1143, 325, 205, 253, 195, 320, 195, 254, 250, 206, 195, 195, 321, 255, 251, 322, 207, 323, 324, 208, 286, 287, 271, 195, 1143, 326, 195, 209, 325, 195, 272, 210, 329, 275, 288, 211, 195, 195, 330, 195, 1143, 212, 327, 195, 213, 328, 331, 286, 287, 271, 336, 195, 326, 195, 209, 337, 195, 272, 210, 329, 275, 288, 211, 195, 195, 330, 195, 195, 212, 327, 195, 213, 328, 331, 273, 274, 1143, 336, 195, 195, 195, 195, 337, 195, 195, 302, 214, 303, 215, 195, 304, 338, 339, 216, 195, 340, 305, 341, 217, 195, 1143, 273, 274, 306, 1143, 345, 195, 1143, 195, 1143, 195, 195, 302, 214, 303, 215, 195, 304, 338, 339, 216, 332, 340, 305, 341, 217, 195, 218, 346, 347, 306, 333, 345, 348, 195, 219, 334, 335, 220, 349, 314, 221, 315, 350, 222, 351, 316, 223, 332, 1143, 352, 1143, 353, 317, 218, 346, 347, 318, 333, 354, 348, 195, 219, 334, 335, 220, 349, 314, 221, 315, 350, 222, 351, 316, 223, 228, 342, 352, 343, 353, 317, 229, 230, 231, 318, 355, 354, 356, 232, 344, 359, 357, 360, 195, 1143, 358, 362, 361, 363, 364, 1143, 1143, 228, 342, 368, 343, 369, 370, 229, 230, 231, 1143, 355, 371, 356, 232, 344, 359, 357, 360, 195, 241, 358, 362, 361, 363, 364, 365, 195, 372, 375, 368, 378, 369, 370, 242, 366, 383, 195, 384, 371, 243, 244, 1143, 367, 376, 377, 373, 241, 381, 1143, 389, 382, 1143, 365, 195, 372, 375, 374, 378, 1143, 379, 242, 366, 383, 195, 384, 390, 243, 244, 195, 367, 376, 377, 373, 245, 381, 195, 389, 382, 385, 380, 387, 246, 195, 374, 386, 247, 379, 391, 248, 1143, 1143, 1143, 390, 388, 1143, 195, 1143, 507, 1143, 1143, 245, 1143, 195, 1143, 1143, 385, 380, 387, 246, 195, 1143, 386, 247, 195, 391, 248, 256, 195, 257, 508, 388, 258, 195, 195, 507, 406, 259, 195, 260, 261, 394, 195, 407, 195, 509, 195, 510, 195, 195, 1143, 195, 195, 511, 256, 195, 257, 508, 1143, 258, 195, 195, 195, 406, 259, 195, 260, 261, 394, 195, 407, 195, 509, 195, 510, 195, 195, 262, 195, 195, 511, 263, 195, 512, 264, 265, 513, 514, 195, 195, 515, 266, 519, 395, 267, 396, 520, 195, 195, 521, 522, 1143, 195, 397, 262, 195, 1143, 195, 263, 195, 512, 264, 265, 513, 514, 195, 1143, 515, 266, 519, 395, 267, 396, 520, 195, 195, 521, 522, 398, 195, 397, 399, 195, 404, 195, 195, 195, 523, 400, 195, 195, 195, 195, 195, 195, 195, 426, 195, 524, 525, 195, 195, 526, 195, 1143, 398, 1143, 1143, 399, 195, 404, 527, 195, 195, 523, 400, 195, 195, 195, 195, 195, 195, 195, 426, 195, 524, 525, 195, 195, 526, 195, 401, 402, 195, 195, 408, 528, 529, 527, 195, 195, 195, 195, 195, 532, 403, 195, 405, 195, 195, 195, 195, 195, 1143, 1143, 1143, 533, 1143, 401, 402, 195, 195, 408, 528, 529, 1143, 195, 195, 195, 195, 195, 532, 403, 195, 405, 195, 195, 195, 195, 195, 409, 410, 411, 533, 412, 413, 195, 195, 534, 195, 195, 195, 195, 195, 535, 414, 195, 422, 423, 536, 537, 415, 1143, 195, 538, 195, 416, 409, 410, 411, 1143, 412, 413, 195, 195, 534, 195, 195, 195, 195, 195, 535, 414, 195, 422, 423, 536, 537, 415, 195, 195, 538, 195, 416, 417, 530, 418, 195, 195, 419, 539, 195, 195, 1143, 424, 420, 1143, 195, 425, 540, 531, 1143, 421, 516, 1143, 517, 195, 195, 195, 541, 1143, 417, 530, 418, 195, 195, 419, 539, 195, 195, 518, 424, 420, 427, 195, 425, 540, 531, 428, 421, 516, 195, 517, 195, 195, 195, 541, 195, 195, 195, 542, 195, 543, 195, 195, 195, 1143, 518, 1143, 195, 427, 436, 1143, 1143, 544, 428, 1143, 1143, 195, 1143, 195, 195, 1143, 1143, 195, 195, 195, 542, 195, 543, 195, 195, 195, 434, 1143, 195, 195, 429, 436, 430, 195, 544, 545, 431, 435, 195, 195, 546, 195, 195, 432, 195, 547, 195, 433, 1143, 195, 1143, 548, 195, 434, 195, 195, 549, 429, 437, 430, 195, 195, 545, 431, 435, 195, 195, 546, 1143, 195, 432, 195, 547, 195, 433, 439, 195, 195, 548, 195, 195, 195, 195, 549, 195, 437, 1143, 195, 195, 550, 438, 551, 552, 195, 1143, 195, 1143, 195, 553, 195, 195, 1143, 439, 440, 195, 441, 1143, 195, 554, 195, 1143, 195, 1143, 195, 195, 195, 550, 438, 551, 552, 195, 195, 195, 195, 195, 553, 195, 195, 442, 195, 440, 443, 441, 195, 555, 554, 1143, 195, 1143, 195, 195, 195, 195, 1143, 444, 556, 1143, 195, 195, 195, 195, 195, 557, 445, 195, 442, 195, 1143, 443, 195, 195, 555, 1143, 195, 195, 451, 195, 558, 195, 195, 195, 444, 556, 195, 195, 195, 195, 195, 195, 557, 445, 195, 559, 195, 446, 195, 195, 562, 560, 452, 195, 563, 451, 195, 558, 195, 195, 195, 561, 564, 195, 565, 195, 195, 195, 195, 566, 195, 1143, 559, 195, 446, 195, 195, 562, 560, 452, 567, 563, 568, 195, 447, 195, 453, 569, 561, 564, 454, 565, 195, 195, 448, 195, 566, 195, 195, 449, 450, 570, 195, 195, 195, 195, 1143, 567, 195, 568, 1143, 447, 571, 453, 569, 572, 195, 454, 1143, 195, 460, 448, 195, 195, 573, 195, 449, 450, 570, 195, 461, 195, 195, 195, 195, 195, 574, 195, 455, 571, 456, 195, 572, 195, 195, 195, 575, 460, 195, 195, 195, 573, 462, 1143, 1143, 576, 195, 461, 577, 195, 195, 195, 1143, 574, 195, 455, 1143, 456, 195, 1143, 1143, 195, 195, 575, 578, 195, 457, 1143, 458, 462, 195, 195, 576, 195, 579, 577, 195, 580, 195, 459, 581, 582, 195, 195, 463, 195, 195, 465, 195, 195, 1143, 578, 583, 457, 195, 458, 195, 195, 195, 195, 195, 579, 464, 195, 580, 195, 459, 581, 582, 195, 195, 463, 195, 195, 465, 195, 195, 466, 584, 583, 467, 195, 585, 195, 195, 195, 195, 195, 195, 464, 195, 195, 195, 195, 195, 195, 468, 195, 195, 586, 195, 587, 588, 1143, 466, 584, 195, 467, 589, 585, 195, 195, 195, 195, 1143, 195, 1143, 1143, 195, 195, 195, 195, 195, 468, 195, 195, 586, 195, 587, 588, 195, 195, 590, 195, 471, 589, 591, 195, 195, 195, 195, 195, 195, 470, 469, 195, 195, 1143, 195, 1143, 1143, 195, 592, 1143, 1143, 593, 1143, 195, 195, 590, 474, 471, 594, 591, 595, 195, 195, 195, 195, 195, 470, 469, 195, 195, 195, 195, 472, 195, 195, 592, 473, 195, 593, 475, 1143, 477, 195, 474, 476, 594, 195, 595, 195, 195, 195, 596, 195, 195, 1143, 597, 1143, 195, 195, 472, 195, 1143, 598, 473, 195, 478, 475, 195, 477, 195, 1143, 476, 195, 195, 195, 195, 195, 195, 596, 195, 195, 479, 597, 195, 599, 195, 600, 601, 195, 598, 195, 195, 478, 602, 195, 606, 607, 483, 1143, 195, 195, 195, 603, 1143, 195, 1143, 608, 609, 479, 1143, 195, 599, 1143, 600, 601, 195, 1143, 195, 195, 480, 602, 1143, 606, 607, 483, 484, 610, 195, 481, 603, 195, 195, 195, 608, 609, 195, 482, 486, 195, 195, 195, 604, 195, 605, 195, 195, 480, 1143, 485, 611, 612, 195, 484, 610, 195, 481, 1143, 195, 195, 195, 1143, 1143, 195, 482, 486, 195, 195, 195, 604, 195, 605, 195, 195, 195, 487, 485, 611, 612, 195, 615, 195, 195, 195, 488, 195, 616, 727, 195, 490, 195, 195, 728, 195, 729, 489, 1143, 1143, 1143, 195, 1143, 195, 487, 1143, 1143, 1143, 730, 615, 195, 195, 195, 488, 195, 616, 727, 195, 490, 195, 195, 728, 195, 729, 489, 195, 491, 492, 195, 195, 195, 195, 195, 493, 499, 730, 195, 195, 195, 731, 195, 195, 1143, 1143, 1143, 1143, 732, 1143, 1143, 1143, 195, 1143, 195, 491, 492, 494, 195, 195, 195, 195, 493, 499, 195, 195, 195, 733, 731, 195, 195, 195, 498, 496, 195, 732, 497, 495, 195, 195, 195, 1143, 195, 195, 494, 1143, 1143, 195, 195, 1143, 1143, 195, 195, 1143, 733, 734, 735, 1143, 195, 498, 496, 195, 1143, 497, 495, 195, 500, 195, 195, 195, 195, 1143, 501, 195, 195, 195, 502, 504, 195, 195, 195, 195, 734, 735, 506, 1143, 195, 195, 613, 503, 1143, 195, 614, 500, 736, 195, 195, 195, 195, 501, 195, 195, 195, 502, 504, 195, 195, 195, 195, 1143, 1143, 506, 195, 195, 195, 613, 503, 505, 195, 614, 195, 736, 195, 195, 195, 195, 617, 195, 195, 195, 195, 195, 1143, 195, 195, 195, 195, 195, 1143, 195, 1143, 195, 1143, 737, 505, 738, 195, 195, 1143, 195, 739, 195, 1143, 617, 195, 618, 1143, 195, 195, 195, 740, 195, 195, 195, 195, 195, 1143, 619, 195, 195, 737, 741, 738, 195, 195, 195, 742, 739, 195, 195, 195, 195, 618, 195, 195, 195, 195, 740, 195, 621, 620, 743, 195, 195, 619, 195, 195, 195, 741, 195, 195, 195, 195, 742, 195, 195, 195, 195, 195, 195, 195, 195, 195, 1143, 1143, 195, 621, 620, 743, 195, 195, 1143, 195, 195, 195, 744, 195, 195, 624, 195, 195, 195, 195, 745, 195, 195, 195, 622, 623, 195, 195, 625, 1143, 195, 195, 1143, 195, 1143, 195, 1143, 195, 1143, 744, 195, 195, 624, 195, 195, 1143, 1143, 745, 195, 195, 746, 622, 623, 195, 195, 625, 195, 195, 195, 626, 747, 627, 195, 195, 748, 195, 195, 195, 195, 749, 195, 750, 195, 629, 195, 1143, 628, 746, 195, 751, 752, 630, 1143, 195, 753, 1143, 626, 747, 627, 1143, 195, 748, 195, 195, 1143, 754, 749, 195, 750, 195, 629, 195, 195, 628, 195, 195, 751, 752, 630, 631, 195, 753, 195, 1143, 195, 755, 195, 195, 632, 195, 195, 634, 754, 756, 195, 1143, 757, 1143, 195, 195, 195, 195, 1143, 1143, 758, 195, 631, 195, 195, 195, 633, 195, 755, 195, 195, 632, 195, 195, 634, 1143, 756, 195, 195, 757, 195, 195, 636, 195, 1143, 635, 195, 758, 195, 759, 195, 195, 195, 633, 195, 760, 761, 1143, 195, 637, 762, 195, 195, 1143, 195, 195, 195, 195, 763, 636, 764, 195, 635, 195, 195, 765, 759, 195, 766, 195, 195, 195, 760, 761, 638, 195, 637, 762, 195, 195, 195, 195, 639, 195, 767, 763, 1143, 764, 195, 195, 195, 195, 765, 1143, 768, 766, 195, 195, 640, 195, 643, 638, 195, 770, 195, 769, 771, 195, 195, 639, 195, 767, 772, 641, 773, 1143, 195, 195, 195, 1143, 195, 768, 642, 195, 195, 640, 195, 643, 195, 195, 770, 195, 769, 771, 195, 195, 1143, 195, 195, 772, 641, 773, 195, 645, 195, 195, 195, 195, 195, 642, 195, 195, 1143, 644, 1143, 195, 195, 1143, 195, 1143, 1143, 195, 774, 775, 1143, 195, 195, 648, 195, 195, 645, 195, 195, 195, 195, 195, 776, 195, 195, 646, 644, 195, 647, 195, 195, 195, 195, 195, 195, 774, 775, 195, 195, 195, 648, 195, 1143, 195, 1143, 195, 649, 195, 195, 776, 195, 195, 646, 195, 195, 647, 195, 195, 1143, 195, 195, 195, 777, 1143, 195, 195, 195, 1143, 1143, 195, 195, 195, 650, 649, 195, 195, 651, 195, 195, 1143, 195, 195, 778, 195, 195, 652, 1143, 195, 195, 777, 195, 779, 195, 195, 195, 654, 195, 195, 195, 650, 195, 195, 1143, 651, 780, 195, 195, 781, 195, 778, 782, 195, 652, 195, 195, 195, 783, 195, 779, 195, 195, 195, 654, 653, 195, 655, 1143, 195, 1143, 195, 1143, 780, 656, 195, 781, 195, 784, 782, 785, 195, 195, 195, 1143, 783, 1143, 195, 195, 195, 195, 195, 653, 786, 655, 657, 1143, 195, 195, 195, 195, 656, 1143, 1143, 195, 784, 195, 785, 195, 1143, 195, 658, 1143, 195, 195, 195, 195, 195, 195, 660, 786, 787, 657, 659, 195, 195, 195, 195, 1143, 195, 195, 195, 788, 195, 789, 195, 195, 790, 658, 195, 195, 195, 791, 195, 792, 195, 660, 195, 787, 663, 659, 195, 195, 195, 661, 195, 195, 195, 195, 788, 662, 789, 195, 195, 790, 195, 195, 195, 195, 791, 195, 792, 195, 1143, 195, 1143, 663, 793, 195, 195, 195, 661, 195, 794, 795, 1143, 195, 662, 195, 796, 1143, 1143, 195, 195, 195, 195, 664, 195, 665, 667, 195, 1143, 195, 195, 793, 195, 195, 195, 668, 195, 794, 795, 195, 195, 666, 195, 796, 195, 195, 195, 195, 1143, 195, 664, 1143, 665, 667, 195, 195, 195, 195, 1143, 195, 669, 195, 668, 195, 195, 670, 195, 797, 666, 195, 195, 195, 195, 195, 798, 671, 1143, 799, 195, 800, 195, 801, 195, 802, 1143, 195, 195, 669, 1143, 803, 195, 195, 670, 672, 797, 1143, 195, 195, 804, 1143, 1143, 798, 671, 195, 799, 195, 800, 195, 801, 805, 802, 673, 195, 195, 195, 195, 803, 195, 195, 195, 672, 806, 195, 807, 1143, 804, 195, 195, 1143, 195, 195, 195, 1143, 674, 195, 808, 805, 809, 673, 810, 1143, 195, 195, 1143, 895, 195, 195, 675, 806, 195, 807, 195, 1143, 195, 195, 195, 195, 195, 195, 676, 674, 195, 808, 678, 809, 195, 810, 195, 677, 195, 195, 895, 896, 195, 675, 195, 1143, 195, 195, 195, 195, 897, 195, 1143, 195, 1143, 676, 898, 899, 195, 678, 900, 195, 1143, 195, 677, 195, 195, 1143, 896, 195, 1143, 195, 195, 195, 195, 195, 195, 897, 679, 195, 680, 195, 195, 898, 899, 195, 195, 900, 195, 195, 195, 195, 1143, 1143, 195, 1143, 1143, 681, 1143, 195, 901, 195, 1143, 1143, 1143, 679, 195, 680, 195, 195, 1143, 195, 902, 195, 1143, 195, 195, 195, 195, 195, 195, 195, 195, 195, 681, 682, 195, 901, 195, 684, 195, 195, 195, 903, 195, 683, 195, 195, 195, 902, 1143, 195, 1143, 1143, 1143, 904, 195, 195, 1143, 195, 195, 905, 682, 195, 1143, 195, 684, 195, 195, 195, 903, 195, 683, 195, 195, 195, 687, 195, 195, 195, 195, 688, 904, 195, 686, 195, 195, 685, 905, 195, 195, 195, 1143, 906, 1143, 1143, 195, 907, 908, 1143, 909, 195, 195, 687, 195, 1143, 195, 195, 688, 910, 195, 686, 195, 195, 685, 689, 195, 195, 195, 195, 906, 690, 195, 195, 907, 908, 195, 909, 195, 195, 911, 195, 195, 195, 912, 195, 910, 691, 913, 914, 195, 1143, 689, 1143, 1143, 195, 195, 915, 690, 195, 916, 1143, 917, 195, 918, 919, 195, 911, 195, 195, 195, 912, 195, 1143, 691, 913, 914, 195, 195, 692, 195, 195, 195, 920, 915, 195, 694, 916, 195, 917, 195, 918, 919, 195, 921, 195, 922, 195, 693, 1143, 195, 923, 924, 195, 195, 195, 692, 195, 195, 1143, 920, 195, 195, 694, 195, 195, 695, 195, 1143, 195, 195, 921, 195, 922, 195, 693, 696, 195, 923, 924, 195, 195, 697, 195, 195, 925, 195, 928, 195, 195, 1143, 195, 929, 695, 195, 698, 195, 195, 700, 195, 1143, 195, 195, 696, 930, 195, 1143, 699, 195, 697, 195, 195, 925, 195, 928, 195, 195, 195, 195, 929, 1143, 195, 698, 195, 195, 700, 195, 195, 195, 195, 1143, 930, 195, 195, 699, 195, 931, 195, 932, 1143, 1143, 195, 195, 195, 195, 195, 702, 195, 195, 926, 195, 933, 927, 195, 195, 701, 934, 195, 195, 195, 195, 195, 1143, 931, 195, 932, 195, 703, 195, 1143, 195, 195, 1143, 702, 195, 195, 926, 935, 933, 927, 195, 936, 701, 934, 195, 195, 195, 937, 195, 195, 1143, 195, 1143, 195, 703, 938, 195, 704, 195, 709, 705, 195, 195, 195, 935, 939, 940, 195, 936, 195, 941, 942, 195, 195, 937, 195, 195, 706, 195, 195, 195, 1143, 938, 195, 704, 195, 709, 705, 195, 195, 195, 943, 939, 940, 195, 944, 195, 941, 942, 195, 195, 195, 195, 195, 706, 945, 195, 195, 195, 707, 1143, 946, 195, 195, 195, 947, 708, 948, 943, 195, 1143, 195, 944, 195, 949, 950, 195, 195, 195, 195, 195, 195, 945, 951, 1143, 195, 707, 195, 946, 710, 195, 195, 947, 708, 948, 952, 195, 195, 195, 953, 195, 949, 950, 195, 195, 195, 195, 711, 195, 195, 951, 712, 195, 195, 195, 954, 710, 195, 195, 714, 713, 715, 952, 195, 195, 195, 953, 195, 955, 195, 195, 1143, 195, 716, 711, 956, 195, 1143, 712, 195, 195, 1143, 954, 195, 195, 195, 714, 713, 715, 1143, 195, 717, 195, 957, 195, 955, 195, 195, 195, 195, 716, 718, 956, 1143, 195, 195, 195, 1143, 195, 1143, 195, 195, 195, 1021, 1022, 195, 195, 1143, 717, 719, 957, 1143, 1143, 195, 1143, 195, 195, 195, 718, 722, 195, 195, 195, 195, 720, 195, 195, 195, 195, 195, 1021, 1022, 195, 195, 195, 195, 719, 195, 195, 195, 195, 195, 195, 721, 195, 723, 722, 195, 1143, 724, 1143, 720, 195, 195, 195, 1143, 1143, 1023, 1143, 1024, 195, 195, 195, 1143, 195, 195, 195, 725, 195, 195, 721, 195, 723, 1143, 195, 195, 724, 195, 195, 195, 1143, 1025, 195, 195, 1023, 195, 1024, 195, 726, 195, 195, 1143, 811, 1026, 725, 1143, 1143, 195, 195, 1143, 812, 195, 195, 195, 195, 195, 1027, 195, 1025, 195, 195, 195, 195, 195, 195, 726, 195, 195, 195, 811, 1026, 1143, 815, 813, 195, 195, 195, 812, 814, 195, 195, 195, 1143, 1027, 195, 1028, 1143, 1143, 195, 817, 195, 195, 1143, 195, 816, 195, 195, 818, 195, 815, 813, 195, 195, 195, 195, 814, 195, 195, 195, 195, 1029, 1030, 1028, 195, 195, 1143, 817, 195, 1031, 195, 195, 816, 1143, 195, 818, 195, 1032, 1143, 195, 195, 1143, 195, 1033, 1143, 195, 819, 195, 1029, 1030, 1034, 195, 195, 195, 195, 195, 1031, 195, 195, 1035, 195, 195, 195, 195, 1032, 195, 1143, 195, 195, 195, 1033, 195, 195, 819, 1036, 195, 195, 1034, 1143, 195, 195, 195, 1143, 1143, 1143, 195, 1035, 195, 195, 195, 195, 1143, 195, 195, 1037, 195, 195, 1143, 195, 195, 195, 1036, 195, 195, 195, 820, 195, 195, 821, 195, 195, 195, 1038, 1143, 195, 1039, 195, 1040, 195, 1041, 195, 1037, 1042, 195, 195, 195, 822, 195, 195, 1143, 1143, 195, 820, 1043, 195, 821, 195, 195, 195, 1038, 195, 195, 1039, 195, 1040, 195, 1041, 195, 1143, 1042, 195, 195, 195, 822, 195, 195, 195, 195, 195, 823, 1043, 1044, 1045, 824, 195, 1046, 195, 195, 195, 1047, 1048, 195, 825, 1049, 195, 826, 195, 195, 1143, 1143, 1143, 195, 195, 195, 195, 195, 823, 195, 1044, 1045, 824, 195, 1046, 195, 1050, 195, 1047, 1048, 195, 825, 1049, 1051, 826, 195, 195, 195, 827, 195, 195, 195, 195, 1052, 195, 1053, 195, 1054, 195, 195, 195, 1143, 195, 1050, 195, 828, 829, 195, 1143, 1055, 1051, 1056, 1143, 1143, 195, 827, 195, 195, 1143, 195, 1052, 195, 1053, 830, 1054, 195, 195, 195, 195, 195, 195, 195, 828, 829, 195, 195, 1055, 195, 1056, 195, 195, 832, 195, 1093, 1143, 831, 195, 1094, 1143, 1095, 830, 1096, 1097, 195, 1143, 195, 195, 195, 1098, 1143, 1143, 195, 195, 1099, 195, 833, 195, 195, 832, 195, 1093, 195, 831, 195, 1094, 834, 1095, 195, 1096, 1097, 195, 195, 195, 195, 195, 1098, 195, 195, 195, 1100, 1099, 195, 833, 195, 1143, 195, 195, 1143, 195, 1143, 195, 1143, 834, 1143, 195, 195, 1143, 1101, 195, 195, 1102, 195, 1103, 195, 195, 1104, 1100, 195, 195, 195, 195, 835, 195, 195, 195, 1105, 195, 195, 195, 195, 836, 1106, 195, 195, 1101, 195, 1107, 1102, 195, 1103, 1123, 1124, 1104, 195, 195, 1143, 195, 195, 835, 1143, 837, 195, 1105, 195, 1143, 195, 195, 836, 1106, 1143, 195, 195, 195, 1107, 839, 195, 1125, 1123, 1124, 195, 195, 195, 840, 195, 195, 838, 195, 837, 195, 195, 1143, 195, 1126, 1143, 1143, 1127, 195, 1143, 195, 195, 1143, 839, 1128, 1125, 1143, 1143, 195, 841, 195, 840, 195, 195, 838, 195, 1143, 195, 195, 195, 195, 1126, 195, 195, 1127, 195, 195, 195, 195, 195, 843, 1128, 195, 195, 195, 1135, 841, 195, 842, 1143, 195, 195, 195, 195, 195, 1143, 195, 195, 195, 195, 195, 195, 1143, 195, 195, 1136, 195, 843, 1137, 195, 195, 195, 1135, 1141, 195, 842, 195, 1143, 195, 195, 195, 195, 844, 195, 195, 195, 1143, 195, 195, 195, 195, 195, 1136, 195, 195, 1137, 195, 1143, 195, 195, 1141, 195, 845, 195, 195, 195, 1143, 195, 195, 844, 195, 1143, 1143, 1143, 195, 846, 195, 195, 195, 195, 195, 195, 195, 195, 1143, 195, 195, 1143, 195, 845, 1143, 195, 195, 195, 195, 195, 1143, 1143, 1143, 1143, 1143, 195, 846, 847, 195, 195, 195, 195, 195, 195, 1143, 1143, 195, 195, 1143, 195, 848, 195, 1143, 195, 195, 195, 195, 195, 1143, 1143, 1143, 849, 195, 195, 847, 195, 195, 850, 195, 195, 195, 1143, 1143, 195, 195, 1143, 195, 848, 195, 1143, 195, 195, 195, 195, 195, 1143, 1143, 1143, 849, 195, 195, 195, 852, 851, 850, 1143, 195, 195, 1143, 195, 1143, 1143, 195, 853, 1143, 1143, 195, 1143, 195, 1143, 195, 1143, 1143, 1143, 195, 1143, 195, 195, 195, 852, 851, 1143, 1143, 195, 1143, 1143, 195, 1143, 1143, 195, 853, 1143, 1143, 195, 1143, 1143, 854, 195, 195, 1143, 195, 195, 195, 195, 195, 1143, 1143, 195, 195, 195, 1143, 195, 195, 1143, 1143, 1143, 195, 1143, 1143, 1143, 1143, 195, 1143, 854, 1143, 195, 1143, 195, 1143, 195, 195, 1143, 1143, 1143, 195, 195, 195, 1143, 195, 195, 195, 1143, 195, 195, 1143, 1143, 1143, 195, 195, 195, 1143, 195, 195, 195, 1143, 195, 195, 855, 1143, 1143, 195, 195, 1143, 1143, 1143, 195, 1143, 195, 1143, 195, 1143, 1143, 1143, 1143, 195, 1143, 195, 1143, 195, 195, 195, 1143, 195, 195, 855, 1143, 1143, 195, 195, 856, 1143, 195, 195, 195, 857, 195, 195, 1143, 195, 1143, 195, 195, 1143, 1143, 195, 195, 1143, 1143, 1143, 1143, 1143, 1143, 195, 1143, 195, 1143, 856, 1143, 195, 860, 195, 857, 195, 195, 1143, 195, 195, 195, 195, 195, 1143, 195, 195, 1143, 1143, 195, 1143, 195, 195, 195, 1143, 195, 858, 859, 195, 195, 860, 195, 1143, 1143, 1143, 195, 195, 195, 1143, 861, 195, 1143, 195, 1143, 1143, 195, 195, 1143, 195, 195, 195, 1143, 862, 858, 859, 195, 195, 195, 195, 1143, 1143, 863, 195, 195, 195, 195, 861, 195, 195, 195, 1143, 195, 195, 195, 1143, 195, 1143, 195, 1143, 862, 195, 195, 195, 1143, 195, 864, 1143, 195, 863, 195, 865, 195, 195, 1143, 195, 195, 195, 1143, 195, 1143, 195, 866, 195, 195, 195, 1143, 195, 195, 195, 195, 1143, 195, 864, 1143, 195, 867, 195, 865, 195, 1143, 868, 195, 195, 195, 1143, 1143, 1143, 195, 866, 195, 195, 195, 195, 195, 195, 1143, 195, 195, 195, 1143, 1143, 1143, 867, 195, 1143, 195, 1143, 868, 195, 195, 195, 195, 1143, 195, 195, 869, 195, 1143, 195, 195, 1143, 195, 195, 195, 195, 195, 1143, 1143, 871, 195, 195, 1143, 1143, 1143, 870, 1143, 195, 195, 195, 195, 195, 1143, 869, 195, 1143, 195, 1143, 1143, 1143, 195, 195, 1143, 195, 1143, 1143, 871, 195, 195, 195, 873, 195, 870, 872, 195, 195, 195, 195, 195, 1143, 875, 195, 195, 195, 1143, 195, 195, 874, 195, 195, 195, 1143, 195, 1143, 1143, 195, 195, 873, 195, 1143, 872, 1143, 195, 195, 1143, 195, 1143, 875, 1143, 195, 195, 876, 195, 195, 874, 1143, 195, 195, 1143, 195, 195, 195, 195, 195, 877, 878, 195, 195, 195, 195, 1143, 195, 195, 195, 1143, 195, 195, 1143, 876, 1143, 1143, 1143, 1143, 1143, 1143, 195, 1143, 195, 195, 195, 195, 877, 878, 195, 195, 195, 195, 195, 195, 195, 195, 879, 195, 195, 1143, 880, 195, 195, 1143, 195, 195, 1143, 195, 1143, 1143, 195, 881, 195, 1143, 195, 1143, 1143, 1143, 195, 195, 195, 195, 1143, 879, 195, 1143, 195, 880, 195, 195, 195, 195, 195, 1143, 195, 1143, 195, 195, 881, 195, 1143, 195, 195, 1143, 195, 195, 195, 195, 195, 882, 1143, 195, 195, 195, 195, 1143, 883, 195, 195, 1143, 195, 195, 195, 195, 1143, 884, 1143, 1143, 1143, 195, 195, 195, 195, 195, 1143, 1143, 882, 1143, 1143, 195, 1143, 195, 1143, 883, 195, 195, 195, 195, 195, 195, 886, 195, 884, 885, 1143, 195, 195, 195, 1143, 195, 195, 1143, 195, 1143, 195, 1143, 1143, 1143, 1143, 195, 1143, 195, 1143, 195, 195, 195, 1143, 886, 195, 1143, 885, 888, 195, 195, 1143, 195, 1143, 195, 195, 195, 1143, 195, 195, 195, 1143, 195, 195, 195, 195, 195, 887, 195, 1143, 1143, 1143, 1143, 195, 1143, 888, 195, 1143, 889, 195, 1143, 1143, 195, 1143, 1143, 1143, 195, 195, 1143, 195, 195, 195, 195, 195, 887, 1143, 890, 195, 891, 195, 195, 1143, 195, 195, 195, 889, 892, 195, 195, 1143, 1143, 1143, 1143, 195, 1143, 1143, 195, 195, 195, 1143, 1143, 1143, 1143, 890, 195, 891, 195, 1143, 1143, 195, 195, 195, 1143, 892, 195, 195, 1143, 195, 195, 1143, 195, 1143, 1143, 195, 195, 195, 195, 195, 195, 1143, 195, 1143, 1143, 893, 1143, 1143, 195, 195, 894, 1143, 195, 1143, 195, 195, 195, 195, 195, 1143, 195, 1143, 195, 195, 1143, 195, 195, 195, 195, 195, 195, 1143, 893, 1143, 1143, 195, 195, 894, 195, 195, 195, 195, 195, 1143, 195, 195, 195, 195, 195, 195, 1143, 1143, 1143, 1143, 195, 195, 195, 195, 195, 1143, 1143, 1143, 195, 195, 195, 195, 195, 195, 195, 1143, 195, 195, 1143, 195, 1143, 195, 195, 1143, 195, 1143, 959, 195, 1143, 195, 195, 195, 195, 958, 195, 195, 195, 195, 195, 195, 1143, 195, 1143, 195, 195, 1143, 195, 1143, 960, 195, 1143, 195, 195, 959, 195, 1143, 1143, 195, 195, 195, 958, 195, 195, 195, 1143, 195, 195, 1143, 195, 962, 1143, 195, 195, 195, 1143, 960, 195, 961, 1143, 195, 1143, 195, 195, 195, 195, 195, 195, 963, 1143, 195, 1143, 195, 1143, 195, 1143, 195, 962, 1143, 195, 195, 195, 195, 1143, 195, 961, 1143, 1143, 1143, 964, 195, 195, 195, 195, 195, 963, 195, 1143, 1143, 195, 1143, 1143, 1143, 195, 1143, 195, 195, 1143, 195, 195, 1143, 195, 195, 1143, 1143, 195, 964, 965, 195, 966, 195, 967, 195, 195, 1143, 195, 1143, 1143, 1143, 1143, 195, 195, 195, 195, 1143, 1143, 1143, 195, 195, 195, 1143, 195, 195, 195, 965, 195, 966, 195, 967, 195, 1143, 968, 195, 195, 971, 195, 195, 195, 195, 195, 195, 195, 970, 1143, 195, 969, 195, 195, 195, 195, 195, 1143, 1143, 1143, 195, 195, 195, 1143, 968, 195, 195, 971, 195, 195, 195, 1143, 195, 972, 195, 970, 1143, 195, 969, 195, 195, 195, 195, 195, 1143, 195, 195, 1143, 195, 195, 973, 195, 195, 195, 1143, 195, 195, 975, 1143, 195, 972, 195, 195, 195, 195, 1143, 195, 195, 195, 195, 195, 976, 195, 195, 974, 195, 1143, 973, 195, 195, 195, 195, 195, 195, 975, 1143, 195, 1143, 195, 195, 195, 195, 1143, 195, 195, 977, 195, 1143, 976, 195, 1143, 974, 195, 1143, 1143, 195, 195, 195, 195, 195, 195, 981, 1143, 195, 195, 195, 1143, 195, 195, 195, 195, 195, 977, 195, 978, 979, 195, 195, 980, 195, 195, 1143, 195, 195, 195, 1143, 195, 195, 981, 1143, 195, 195, 195, 1143, 195, 1143, 195, 195, 195, 1143, 195, 978, 979, 1143, 195, 980, 195, 195, 195, 982, 195, 195, 195, 195, 1143, 195, 1143, 195, 195, 1143, 1143, 195, 984, 195, 195, 1143, 1143, 1143, 195, 195, 1143, 195, 1143, 195, 195, 195, 982, 195, 195, 195, 195, 195, 195, 1143, 195, 195, 1143, 195, 195, 984, 195, 195, 983, 1143, 1143, 195, 195, 195, 195, 1143, 195, 195, 1143, 195, 195, 195, 985, 1143, 195, 1143, 195, 195, 1143, 195, 195, 195, 1143, 1143, 195, 983, 1143, 1143, 1143, 195, 195, 1143, 1143, 195, 1143, 195, 195, 1143, 195, 985, 195, 1143, 1143, 195, 195, 195, 195, 195, 195, 195, 1143, 195, 1143, 1143, 195, 986, 195, 1143, 1143, 195, 195, 195, 195, 195, 1143, 1143, 1143, 195, 195, 1143, 1143, 1143, 195, 195, 195, 1143, 195, 195, 1143, 195, 1143, 195, 986, 1143, 195, 195, 195, 195, 195, 195, 195, 1143, 195, 987, 1143, 195, 1143, 195, 988, 1143, 195, 1143, 195, 195, 195, 195, 195, 1143, 195, 1143, 989, 195, 195, 990, 195, 195, 195, 1143, 195, 195, 987, 991, 1143, 195, 195, 988, 1143, 1143, 195, 195, 195, 1143, 195, 195, 195, 195, 195, 989, 1143, 1143, 990, 195, 195, 1143, 1143, 195, 195, 195, 991, 195, 195, 1143, 1143, 1143, 195, 195, 1143, 1143, 1143, 195, 195, 195, 1143, 195, 1143, 195, 1143, 195, 195, 1143, 1143, 1143, 195, 195, 195, 1143, 195, 195, 195, 1143, 195, 195, 1143, 992, 1143, 195, 195, 195, 1143, 1143, 195, 195, 195, 195, 195, 195, 1143, 1143, 1143, 195, 1143, 195, 993, 195, 195, 195, 1143, 195, 1143, 195, 992, 195, 195, 1143, 195, 1143, 195, 195, 195, 195, 195, 1143, 195, 1143, 1143, 195, 1143, 1143, 195, 993, 195, 1143, 994, 195, 195, 1143, 195, 1143, 195, 195, 195, 195, 195, 195, 1143, 996, 195, 195, 195, 195, 195, 195, 195, 995, 1143, 195, 195, 1143, 1143, 994, 195, 195, 1143, 195, 1143, 195, 195, 195, 195, 195, 195, 1143, 996, 195, 195, 195, 195, 195, 195, 195, 995, 195, 195, 195, 1143, 1143, 195, 1143, 195, 1143, 195, 1143, 195, 195, 1143, 195, 997, 195, 998, 999, 195, 1000, 1143, 195, 1143, 195, 195, 1143, 195, 195, 1143, 195, 1143, 195, 195, 195, 1143, 1143, 1001, 195, 195, 195, 195, 997, 195, 998, 999, 195, 1000, 1143, 195, 195, 195, 1143, 195, 1002, 195, 195, 195, 1143, 1143, 195, 195, 1003, 1143, 1001, 195, 195, 195, 195, 195, 195, 195, 1143, 195, 1143, 1143, 195, 195, 1143, 195, 195, 1002, 1143, 195, 1143, 1143, 1143, 195, 195, 1003, 1004, 1143, 1143, 195, 195, 195, 195, 1143, 195, 1143, 1143, 195, 1143, 195, 195, 195, 195, 1143, 1143, 1143, 1143, 1143, 195, 1143, 195, 1143, 195, 1004, 1143, 195, 1006, 195, 195, 1143, 1005, 1143, 195, 1143, 195, 1007, 195, 195, 195, 1143, 195, 1143, 195, 1143, 1008, 195, 195, 1143, 1143, 195, 1143, 195, 195, 1006, 1143, 195, 195, 1005, 195, 195, 1143, 195, 1007, 195, 1143, 195, 1143, 195, 195, 195, 195, 1008, 195, 195, 195, 1009, 1012, 195, 195, 195, 195, 195, 1010, 195, 195, 195, 195, 1143, 195, 1143, 1143, 195, 195, 1143, 195, 195, 1011, 195, 1013, 195, 1143, 195, 1009, 1012, 195, 195, 195, 195, 195, 1010, 1014, 195, 195, 195, 1143, 195, 1143, 195, 195, 195, 1143, 195, 1143, 1011, 195, 1013, 195, 195, 1143, 1143, 1015, 1143, 195, 195, 195, 1143, 195, 1014, 1143, 195, 195, 1143, 195, 1143, 195, 1017, 195, 1016, 195, 195, 195, 195, 195, 195, 195, 195, 1143, 1015, 195, 1143, 195, 195, 1143, 195, 1143, 195, 1143, 195, 195, 1143, 1143, 1143, 1017, 1143, 1016, 195, 195, 195, 1143, 195, 195, 195, 195, 195, 195, 195, 1143, 1019, 1018, 1020, 195, 1143, 195, 195, 195, 195, 195, 1143, 1143, 1143, 195, 195, 1143, 195, 195, 195, 195, 195, 195, 1143, 195, 195, 195, 1143, 1019, 1018, 1020, 195, 1143, 195, 195, 195, 195, 195, 1143, 1057, 1143, 195, 195, 195, 195, 195, 195, 195, 195, 195, 1143, 1143, 195, 195, 1143, 195, 1143, 1058, 195, 195, 195, 1143, 195, 195, 1143, 1143, 1057, 195, 195, 1143, 195, 195, 1143, 195, 1143, 195, 195, 1143, 195, 195, 1143, 1143, 195, 195, 1058, 195, 195, 1143, 1143, 195, 195, 1143, 1059, 1143, 195, 195, 1143, 195, 195, 195, 195, 195, 195, 1060, 1143, 195, 1061, 195, 1143, 1143, 195, 195, 1143, 195, 1143, 1143, 1143, 195, 1143, 1059, 195, 1143, 195, 195, 195, 1143, 195, 195, 195, 195, 1060, 1143, 195, 1061, 195, 1143, 1143, 1143, 195, 1062, 195, 195, 1143, 1143, 1143, 1143, 195, 195, 1143, 195, 195, 195, 1143, 195, 195, 195, 1143, 1143, 1143, 195, 195, 1143, 195, 1063, 195, 195, 1062, 1143, 195, 195, 1143, 1143, 1064, 195, 195, 1143, 1143, 1143, 195, 1143, 195, 195, 195, 195, 1143, 1143, 1143, 195, 195, 195, 1063, 195, 195, 195, 1143, 1065, 195, 195, 1143, 1064, 1143, 195, 195, 1143, 195, 1143, 195, 195, 195, 1143, 195, 195, 1066, 1143, 1143, 195, 195, 1143, 1143, 1143, 195, 1143, 1065, 195, 195, 195, 1143, 1143, 1143, 195, 195, 195, 1067, 195, 195, 195, 1143, 1143, 195, 1066, 1143, 1143, 195, 195, 195, 1143, 195, 1143, 195, 195, 195, 1143, 195, 195, 195, 1143, 1068, 195, 195, 1067, 1143, 1143, 195, 1143, 1143, 195, 1143, 195, 1143, 195, 1143, 195, 195, 195, 1143, 195, 195, 195, 1143, 1143, 195, 195, 1143, 1068, 195, 195, 195, 1143, 195, 1143, 195, 195, 195, 1143, 195, 195, 195, 1143, 1143, 195, 195, 1143, 1143, 1143, 195, 1143, 1069, 195, 1143, 195, 195, 195, 1143, 195, 195, 195, 195, 195, 195, 195, 195, 1143, 195, 195, 195, 1143, 195, 195, 1143, 1143, 195, 1143, 1143, 1069, 195, 1143, 195, 195, 1143, 1143, 195, 195, 195, 195, 1070, 1143, 195, 195, 195, 195, 195, 195, 1143, 195, 195, 195, 1071, 195, 1143, 1143, 195, 195, 1143, 195, 1143, 1143, 1143, 195, 195, 195, 1143, 1070, 195, 195, 195, 195, 195, 195, 1143, 195, 1143, 195, 195, 1071, 195, 1143, 1143, 195, 195, 1143, 195, 195, 1143, 195, 1143, 195, 1143, 1143, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 1143, 195, 1143, 195, 195, 1143, 195, 1143, 1143, 195, 195, 1143, 195, 195, 1143, 1073, 1143, 195, 1143, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 1143, 1072, 195, 1143, 195, 1074, 195, 195, 1143, 1143, 1143, 195, 195, 1073, 1143, 1143, 1143, 195, 195, 195, 195, 1143, 195, 195, 195, 195, 1143, 195, 1072, 1143, 1143, 195, 1074, 195, 195, 1143, 1143, 195, 195, 195, 1143, 195, 1143, 1075, 1143, 195, 195, 195, 1143, 195, 195, 195, 1076, 1143, 195, 195, 1143, 1143, 195, 195, 1143, 195, 1143, 1143, 195, 195, 195, 195, 195, 195, 1075, 195, 195, 1143, 195, 1143, 1143, 195, 195, 1076, 1143, 195, 195, 1143, 195, 195, 195, 1078, 195, 1143, 1077, 195, 1143, 195, 195, 1143, 195, 195, 195, 195, 1143, 195, 1143, 195, 1143, 195, 195, 195, 195, 195, 1143, 195, 195, 195, 1078, 195, 1143, 1077, 195, 1079, 195, 195, 1143, 1080, 195, 195, 195, 1081, 195, 1143, 195, 1143, 195, 195, 195, 195, 195, 1143, 195, 195, 195, 1143, 195, 1143, 1143, 1143, 1079, 195, 195, 1143, 1080, 1143, 195, 1143, 1081, 195, 195, 1143, 1082, 195, 1143, 1143, 195, 195, 1143, 195, 195, 1143, 1143, 195, 195, 1143, 195, 195, 195, 195, 1143, 195, 1143, 1083, 1143, 1143, 195, 195, 195, 1082, 195, 195, 195, 1143, 195, 1143, 1143, 195, 1143, 1143, 1143, 195, 195, 195, 195, 195, 195, 1143, 195, 195, 1083, 1084, 1143, 195, 1143, 195, 195, 195, 195, 195, 195, 195, 195, 1085, 195, 195, 1143, 195, 1143, 195, 195, 1143, 195, 1143, 1143, 195, 195, 1143, 1084, 195, 1143, 195, 1143, 195, 1143, 1143, 195, 195, 195, 195, 1085, 195, 195, 1086, 195, 1143, 1143, 195, 1087, 195, 195, 1143, 195, 1143, 1143, 195, 195, 195, 195, 195, 195, 1143, 195, 195, 1143, 195, 195, 1143, 195, 1143, 1086, 1143, 1143, 195, 1143, 1087, 195, 195, 1088, 1143, 1143, 195, 195, 1089, 195, 1143, 195, 195, 195, 195, 195, 1143, 195, 195, 1143, 195, 1143, 195, 195, 195, 195, 1143, 1143, 195, 195, 1088, 195, 195, 195, 1090, 1089, 1143, 1143, 195, 1143, 195, 195, 195, 1143, 1143, 1143, 195, 195, 1143, 195, 195, 195, 1143, 195, 1143, 195, 195, 195, 195, 195, 195, 1090, 195, 195, 195, 195, 1143, 1143, 195, 195, 1143, 195, 195, 195, 195, 1143, 1143, 1143, 195, 1143, 195, 1092, 195, 195, 195, 195, 1143, 195, 195, 195, 195, 195, 195, 195, 1143, 1091, 195, 1143, 195, 195, 1143, 195, 195, 1143, 195, 195, 1143, 1143, 1092, 195, 195, 195, 195, 195, 195, 195, 1143, 1143, 195, 195, 195, 1143, 1091, 195, 1143, 195, 1143, 195, 1143, 195, 1143, 195, 195, 1143, 1143, 1143, 195, 195, 195, 1143, 195, 195, 1143, 1143, 195, 195, 195, 1143, 1143, 1143, 195, 195, 195, 195, 195, 195, 195, 1143, 1143, 195, 195, 1143, 1143, 1143, 195, 195, 1108, 195, 1143, 195, 195, 195, 1143, 195, 195, 1143, 195, 1143, 195, 195, 195, 1109, 195, 195, 1143, 1143, 195, 195, 195, 1143, 1143, 1143, 195, 1108, 195, 195, 195, 195, 195, 1143, 195, 195, 195, 195, 1143, 1143, 195, 195, 1109, 195, 1143, 1143, 1143, 195, 195, 195, 195, 195, 1143, 195, 1110, 1143, 195, 1143, 195, 195, 1143, 195, 1143, 195, 195, 1143, 1143, 1143, 195, 195, 195, 1143, 195, 195, 195, 195, 195, 195, 195, 195, 195, 1110, 195, 1143, 1111, 195, 1143, 1143, 1143, 195, 1143, 195, 195, 1143, 195, 1143, 195, 1143, 195, 195, 195, 195, 1143, 195, 195, 1143, 195, 1143, 195, 195, 1143, 1111, 195, 195, 195, 1143, 195, 195, 195, 195, 1112, 195, 195, 195, 1143, 195, 195, 1143, 195, 1143, 1143, 195, 195, 195, 1143, 195, 1113, 1143, 195, 195, 195, 195, 195, 195, 195, 195, 1143, 1112, 195, 195, 195, 1143, 1143, 195, 195, 195, 195, 195, 1115, 195, 195, 195, 195, 1113, 195, 195, 195, 1143, 195, 195, 195, 195, 195, 1143, 1114, 195, 195, 1143, 195, 1143, 1143, 195, 195, 195, 195, 1115, 195, 1143, 195, 195, 195, 195, 195, 195, 1143, 195, 195, 1143, 195, 195, 195, 1114, 1143, 195, 195, 195, 195, 1143, 1143, 195, 195, 1143, 1143, 195, 195, 1143, 1143, 195, 195, 195, 195, 1143, 195, 195, 195, 1143, 195, 195, 1117, 1116, 1143, 195, 195, 195, 195, 1143, 1143, 195, 1143, 1143, 195, 195, 195, 1143, 195, 195, 1143, 195, 195, 195, 195, 195, 195, 195, 1143, 1117, 1116, 1143, 195, 195, 195, 195, 195, 1118, 1143, 1143, 195, 195, 195, 195, 1143, 195, 195, 1143, 195, 195, 1143, 195, 1143, 195, 1143, 195, 195, 1143, 1143, 195, 1143, 195, 195, 195, 1118, 1119, 1143, 195, 1143, 195, 195, 1143, 1143, 195, 195, 195, 1143, 195, 1143, 1143, 1143, 195, 195, 195, 195, 1143, 1120, 195, 195, 195, 1143, 195, 1119, 195, 1143, 1143, 1143, 195, 1143, 1122, 195, 195, 1143, 195, 195, 1143, 1143, 195, 195, 195, 195, 195, 1121, 1120, 195, 195, 1143, 1143, 195, 195, 195, 195, 1143, 1143, 1143, 195, 1122, 195, 1143, 1143, 195, 195, 1143, 1143, 195, 1143, 195, 195, 1143, 1121, 195, 195, 1143, 195, 195, 195, 195, 195, 195, 195, 195, 1143, 195, 195, 1143, 195, 1143, 1143, 195, 1143, 195, 1143, 1143, 195, 1143, 195, 1143, 195, 195, 195, 195, 195, 195, 195, 195, 1143, 195, 195, 1143, 195, 195, 195, 195, 1143, 1129, 195, 1143, 195, 1143, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 1143, 195, 195, 195, 195, 1143, 195, 1130, 1143, 1129, 195, 195, 195, 195, 195, 1143, 195, 1143, 195, 195, 195, 1143, 195, 195, 195, 1143, 195, 1143, 195, 195, 195, 1143, 1143, 1143, 1130, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 1143, 1143, 1143, 195, 195, 195, 195, 1131, 195, 195, 195, 1143, 1143, 195, 1143, 1143, 1143, 195, 195, 195, 1143, 1143, 1143, 195, 195, 195, 195, 1143, 1143, 1143, 195, 195, 195, 195, 1131, 195, 195, 195, 195, 195, 195, 195, 195, 195, 1143, 1134, 1143, 1143, 195, 195, 1133, 195, 1143, 195, 1143, 1143, 1143, 195, 1132, 195, 1143, 195, 1143, 195, 1143, 195, 195, 1143, 195, 195, 195, 1143, 1134, 195, 1143, 195, 195, 1133, 195, 1138, 195, 1143, 1143, 195, 195, 1132, 195, 195, 195, 195, 195, 195, 1143, 1143, 1143, 1143, 195, 195, 195, 195, 195, 195, 1143, 1139, 1143, 195, 1138, 195, 195, 1143, 195, 1140, 1143, 1143, 195, 195, 195, 195, 195, 1143, 1143, 195, 195, 195, 195, 195, 195, 195, 195, 195, 1139, 195, 195, 195, 195, 195, 195, 195, 1140, 1143, 1143, 195, 195, 195, 195, 1143, 1143, 195, 195, 195, 1143, 195, 1143, 195, 195, 1143, 195, 195, 195, 195, 195, 1142, 1143, 195, 195, 1143, 195, 195, 195, 1143, 195, 195, 1143, 1143, 195, 195, 1143, 195, 195, 1143, 195, 1143, 195, 1143, 195, 1143, 195, 195, 1142, 1143, 1143, 1143, 1143, 195, 195, 1143, 1143, 1143, 195, 1143, 1143, 1143, 195, 1143, 195, 1143, 1143, 1143, 1143, 195, 1143, 1143, 1143, 1143, 195, 47, 47, 47, 47, 47, 90, 1143, 1143, 90, 90, 181, 181, 181, 1143, 181, 183, 1143, 183, 183, 183, 186, 1143, 186, 186, 186, 195, 1143, 195, 195, 195, 7, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143 } ; static const flex_int16_t yy_chk[7373] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 9, 9, 10, 10, 15, 1146, 15, 17, 17, 18, 18, 21, 22, 21, 50, 50, 22, 23, 30, 21, 393, 21, 22, 56, 23, 56, 21, 31, 278, 37, 190, 23, 22, 24, 23, 189, 27, 24, 21, 22, 21, 24, 27, 22, 23, 30, 21, 24, 21, 22, 24, 23, 28, 21, 31, 25, 37, 25, 23, 22, 24, 23, 25, 27, 24, 29, 28, 25, 24, 27, 186, 29, 29, 29, 24, 42, 94, 24, 29, 28, 51, 51, 25, 42, 25, 93, 32, 33, 90, 25, 32, 33, 29, 28, 25, 26, 32, 33, 29, 29, 29, 87, 42, 26, 61, 29, 26, 34, 36, 26, 42, 45, 26, 32, 33, 26, 38, 32, 33, 36, 38, 34, 26, 32, 33, 36, 38, 34, 34, 35, 26, 43, 43, 26, 34, 36, 26, 35, 45, 26, 60, 35, 26, 38, 35, 57, 36, 38, 34, 58, 58, 53, 36, 38, 34, 34, 35, 52, 43, 43, 41, 78, 41, 100, 35, 41, 59, 59, 35, 78, 101, 35, 39, 78, 39, 48, 78, 39, 88, 88, 92, 92, 39, 46, 39, 39, 20, 41, 78, 41, 100, 68, 41, 184, 184, 19, 78, 101, 68, 39, 78, 39, 68, 78, 39, 68, 72, 102, 68, 39, 72, 39, 39, 40, 104, 102, 72, 40, 68, 103, 40, 40, 103, 106, 107, 68, 72, 40, 110, 68, 40, 16, 68, 72, 102, 68, 11, 72, 188, 188, 40, 104, 102, 72, 40, 7, 103, 40, 40, 103, 106, 107, 4, 72, 40, 110, 3, 40, 62, 62, 0, 62, 62, 62, 62, 62, 62, 0, 62, 62, 62, 69, 113, 71, 62, 116, 62, 113, 69, 82, 71, 82, 62, 82, 62, 69, 82, 71, 69, 62, 71, 82, 111, 111, 111, 117, 111, 0, 69, 113, 71, 62, 116, 62, 113, 69, 82, 71, 82, 62, 82, 62, 69, 82, 71, 69, 62, 71, 82, 111, 111, 111, 117, 111, 62, 63, 63, 0, 63, 63, 63, 63, 63, 63, 73, 63, 63, 63, 73, 74, 109, 85, 63, 74, 73, 118, 63, 109, 85, 74, 115, 115, 63, 112, 73, 85, 119, 120, 85, 74, 0, 73, 63, 112, 0, 73, 74, 109, 85, 63, 74, 73, 118, 63, 109, 85, 74, 115, 115, 63, 112, 73, 85, 119, 120, 85, 74, 77, 122, 63, 112, 63, 64, 79, 77, 123, 64, 79, 77, 64, 64, 77, 124, 79, 77, 125, 64, 126, 127, 64, 0, 0, 0, 79, 77, 122, 64, 0, 128, 64, 79, 77, 123, 64, 79, 77, 64, 64, 77, 124, 79, 77, 125, 64, 126, 127, 64, 105, 105, 83, 79, 0, 129, 64, 65, 128, 83, 83, 65, 131, 86, 105, 65, 83, 86, 133, 83, 0, 65, 130, 86, 65, 130, 134, 105, 105, 83, 136, 65, 129, 86, 65, 137, 83, 83, 65, 131, 86, 105, 65, 83, 86, 133, 83, 84, 65, 130, 86, 65, 130, 134, 84, 84, 0, 136, 65, 66, 86, 84, 137, 66, 84, 114, 66, 114, 66, 66, 114, 138, 139, 66, 84, 140, 114, 140, 66, 66, 0, 84, 84, 114, 0, 142, 66, 0, 84, 0, 66, 84, 114, 66, 114, 66, 66, 114, 138, 139, 66, 135, 140, 114, 140, 66, 66, 67, 143, 144, 114, 135, 142, 145, 67, 67, 135, 135, 67, 146, 121, 67, 121, 147, 67, 148, 121, 67, 135, 0, 149, 0, 151, 121, 67, 143, 144, 121, 135, 152, 145, 67, 67, 135, 135, 67, 146, 121, 67, 121, 147, 67, 148, 121, 67, 70, 141, 149, 141, 151, 121, 70, 70, 70, 121, 153, 152, 154, 70, 141, 156, 155, 157, 70, 0, 155, 158, 157, 159, 160, 0, 0, 70, 141, 162, 141, 163, 164, 70, 70, 70, 0, 153, 165, 154, 70, 141, 156, 155, 157, 70, 75, 155, 158, 157, 159, 160, 161, 75, 166, 168, 162, 170, 163, 164, 75, 161, 173, 75, 174, 165, 75, 75, 0, 161, 169, 169, 167, 75, 172, 0, 177, 172, 0, 161, 75, 166, 168, 167, 170, 0, 171, 75, 161, 173, 75, 174, 178, 75, 75, 76, 161, 169, 169, 167, 76, 172, 76, 177, 172, 175, 171, 176, 76, 76, 167, 175, 76, 171, 179, 76, 0, 0, 0, 178, 176, 0, 76, 0, 280, 0, 0, 76, 0, 76, 0, 0, 175, 171, 176, 76, 76, 0, 175, 76, 195, 179, 76, 80, 195, 80, 282, 176, 80, 80, 195, 280, 205, 80, 205, 80, 80, 196, 196, 205, 195, 283, 196, 286, 205, 80, 0, 195, 196, 287, 80, 195, 80, 282, 0, 80, 80, 195, 196, 205, 80, 205, 80, 80, 196, 196, 205, 195, 283, 196, 286, 205, 80, 81, 197, 196, 287, 81, 197, 288, 81, 81, 289, 290, 197, 196, 291, 81, 293, 197, 81, 198, 294, 198, 197, 295, 296, 0, 198, 198, 81, 197, 0, 198, 81, 197, 288, 81, 81, 289, 290, 197, 0, 291, 81, 293, 197, 81, 198, 294, 198, 197, 295, 296, 199, 198, 198, 199, 202, 202, 198, 199, 200, 297, 200, 214, 202, 214, 199, 200, 202, 199, 214, 202, 298, 299, 200, 214, 300, 200, 0, 199, 0, 0, 199, 202, 202, 302, 199, 200, 297, 200, 214, 202, 214, 199, 200, 202, 199, 214, 202, 298, 299, 200, 214, 300, 200, 201, 201, 203, 204, 206, 303, 304, 302, 201, 203, 204, 206, 201, 306, 201, 201, 203, 204, 206, 203, 204, 206, 0, 0, 0, 307, 0, 201, 201, 203, 204, 206, 303, 304, 0, 201, 203, 204, 206, 201, 306, 201, 201, 203, 204, 206, 203, 204, 206, 207, 207, 207, 307, 207, 208, 209, 207, 308, 208, 209, 211, 207, 211, 309, 208, 209, 211, 211, 310, 311, 209, 0, 211, 313, 208, 209, 207, 207, 207, 0, 207, 208, 209, 207, 308, 208, 209, 211, 207, 211, 309, 208, 209, 211, 211, 310, 311, 209, 212, 211, 313, 208, 209, 210, 305, 210, 212, 213, 210, 314, 212, 213, 0, 212, 210, 0, 210, 213, 315, 305, 0, 210, 292, 0, 292, 212, 210, 213, 316, 0, 210, 305, 210, 212, 213, 210, 314, 212, 213, 292, 212, 210, 215, 210, 213, 315, 305, 216, 210, 292, 215, 292, 215, 210, 213, 316, 216, 215, 216, 317, 220, 318, 215, 216, 220, 0, 292, 0, 216, 215, 220, 0, 0, 319, 216, 0, 0, 215, 0, 215, 220, 0, 0, 216, 215, 216, 317, 220, 318, 215, 216, 220, 218, 0, 218, 216, 217, 220, 217, 218, 319, 320, 217, 219, 218, 219, 321, 220, 217, 217, 219, 322, 221, 217, 0, 219, 0, 323, 217, 218, 221, 218, 324, 217, 221, 217, 218, 221, 320, 217, 219, 218, 219, 321, 0, 217, 217, 219, 322, 221, 217, 223, 219, 223, 323, 217, 222, 221, 223, 324, 222, 221, 0, 223, 221, 325, 222, 326, 327, 224, 0, 225, 0, 224, 328, 225, 222, 0, 223, 224, 223, 225, 0, 222, 329, 223, 0, 222, 0, 224, 223, 225, 325, 222, 326, 327, 224, 226, 225, 226, 224, 328, 225, 222, 226, 227, 224, 226, 225, 226, 330, 329, 0, 227, 0, 228, 224, 227, 225, 0, 227, 331, 0, 228, 226, 229, 226, 228, 332, 229, 228, 226, 227, 0, 226, 229, 226, 330, 0, 232, 227, 232, 228, 333, 227, 229, 232, 227, 331, 230, 228, 232, 229, 230, 228, 332, 229, 228, 334, 230, 230, 233, 229, 336, 335, 233, 232, 337, 232, 230, 333, 233, 229, 232, 335, 339, 230, 340, 232, 234, 230, 233, 341, 234, 0, 334, 230, 230, 233, 234, 336, 335, 233, 342, 337, 343, 230, 231, 233, 234, 344, 335, 339, 235, 340, 231, 234, 231, 233, 341, 234, 235, 231, 231, 345, 235, 234, 231, 235, 0, 342, 238, 343, 0, 231, 346, 234, 344, 347, 238, 235, 0, 231, 238, 231, 239, 238, 348, 235, 231, 231, 345, 235, 239, 231, 235, 236, 239, 238, 350, 239, 236, 346, 236, 236, 347, 238, 240, 236, 351, 238, 236, 239, 238, 348, 240, 0, 0, 352, 240, 239, 353, 240, 236, 239, 0, 350, 239, 236, 0, 236, 236, 0, 0, 240, 236, 351, 354, 236, 237, 0, 237, 240, 241, 237, 352, 240, 355, 353, 240, 356, 241, 237, 357, 358, 241, 237, 241, 241, 237, 243, 242, 243, 0, 354, 359, 237, 243, 237, 242, 241, 237, 243, 242, 355, 242, 242, 356, 241, 237, 357, 358, 241, 237, 241, 241, 237, 243, 242, 243, 244, 360, 359, 245, 243, 361, 242, 244, 246, 243, 242, 245, 242, 242, 244, 245, 246, 244, 245, 247, 246, 247, 362, 246, 363, 364, 0, 244, 360, 247, 245, 365, 361, 247, 244, 246, 247, 0, 245, 0, 0, 244, 245, 246, 244, 245, 247, 246, 247, 362, 246, 363, 364, 248, 249, 366, 247, 250, 365, 368, 247, 248, 249, 247, 250, 248, 249, 248, 248, 249, 0, 250, 0, 0, 250, 369, 0, 0, 370, 0, 248, 249, 366, 252, 250, 371, 368, 372, 248, 249, 252, 250, 248, 249, 248, 248, 249, 252, 250, 251, 252, 250, 369, 251, 253, 370, 253, 0, 254, 251, 252, 253, 371, 254, 372, 254, 253, 252, 373, 251, 254, 0, 374, 0, 252, 254, 251, 252, 0, 375, 251, 253, 255, 253, 255, 254, 251, 0, 253, 255, 254, 256, 254, 253, 255, 373, 251, 254, 256, 374, 258, 376, 254, 377, 379, 256, 375, 258, 256, 255, 380, 255, 382, 383, 258, 0, 255, 258, 256, 380, 0, 255, 0, 384, 385, 256, 0, 258, 376, 0, 377, 379, 256, 0, 258, 256, 257, 380, 0, 382, 383, 258, 259, 386, 258, 257, 380, 257, 260, 259, 384, 385, 257, 257, 261, 260, 259, 257, 381, 259, 381, 261, 260, 257, 0, 260, 387, 388, 261, 259, 386, 261, 257, 0, 257, 260, 259, 0, 0, 257, 257, 261, 260, 259, 257, 381, 259, 381, 261, 260, 262, 262, 260, 387, 388, 261, 390, 262, 261, 263, 263, 263, 391, 507, 262, 264, 263, 262, 508, 264, 509, 263, 0, 0, 0, 264, 0, 262, 262, 0, 0, 0, 510, 390, 262, 264, 263, 263, 263, 391, 507, 262, 264, 263, 262, 508, 264, 509, 263, 265, 265, 265, 264, 266, 270, 266, 265, 266, 270, 510, 266, 265, 264, 511, 270, 266, 0, 0, 0, 0, 512, 0, 0, 0, 270, 0, 265, 265, 265, 267, 266, 270, 266, 265, 266, 270, 267, 266, 265, 513, 511, 270, 266, 267, 269, 268, 267, 512, 268, 267, 268, 270, 269, 0, 269, 268, 267, 0, 0, 269, 268, 0, 0, 267, 269, 0, 513, 514, 516, 0, 267, 269, 268, 267, 0, 268, 267, 268, 271, 269, 271, 269, 268, 0, 271, 271, 269, 268, 272, 273, 271, 269, 272, 273, 514, 516, 275, 0, 272, 273, 389, 272, 0, 275, 389, 271, 520, 271, 272, 273, 275, 271, 271, 275, 274, 272, 273, 271, 274, 272, 273, 0, 0, 275, 274, 272, 273, 389, 272, 274, 275, 389, 394, 520, 274, 272, 273, 275, 395, 394, 275, 274, 395, 396, 0, 274, 394, 396, 395, 394, 0, 274, 0, 396, 0, 521, 274, 522, 395, 394, 0, 274, 524, 396, 0, 395, 394, 397, 0, 395, 396, 397, 525, 394, 396, 395, 394, 397, 0, 398, 396, 398, 521, 526, 522, 395, 398, 397, 527, 524, 396, 398, 401, 399, 397, 399, 401, 402, 397, 525, 399, 402, 401, 528, 397, 399, 398, 402, 398, 400, 526, 400, 401, 398, 397, 527, 400, 402, 398, 401, 399, 400, 399, 401, 402, 0, 0, 399, 402, 401, 528, 403, 399, 0, 402, 403, 400, 529, 400, 401, 405, 403, 405, 400, 402, 530, 404, 405, 400, 403, 404, 403, 405, 406, 0, 406, 404, 0, 403, 0, 406, 0, 403, 0, 529, 406, 404, 405, 403, 405, 0, 0, 530, 404, 405, 531, 403, 404, 403, 405, 406, 408, 406, 404, 407, 532, 407, 406, 408, 533, 407, 409, 406, 404, 534, 408, 535, 407, 408, 409, 0, 407, 531, 409, 538, 539, 409, 0, 408, 540, 0, 407, 532, 407, 0, 408, 533, 407, 409, 0, 541, 534, 408, 535, 407, 408, 409, 410, 407, 411, 409, 538, 539, 409, 410, 410, 540, 411, 0, 410, 542, 411, 410, 411, 411, 412, 413, 541, 543, 412, 0, 544, 0, 413, 410, 412, 411, 0, 0, 546, 413, 410, 410, 413, 411, 412, 410, 542, 411, 410, 411, 411, 412, 413, 0, 543, 412, 414, 544, 414, 413, 415, 412, 0, 414, 415, 546, 413, 547, 414, 413, 415, 412, 416, 550, 551, 0, 416, 417, 553, 417, 415, 0, 416, 414, 417, 414, 555, 415, 556, 417, 414, 415, 416, 557, 547, 414, 558, 415, 418, 416, 550, 551, 418, 416, 417, 553, 417, 415, 418, 416, 419, 417, 559, 555, 0, 556, 417, 419, 418, 416, 557, 0, 560, 558, 419, 418, 420, 419, 422, 418, 420, 562, 422, 560, 566, 418, 420, 419, 422, 559, 568, 420, 570, 0, 419, 418, 420, 0, 422, 560, 421, 419, 421, 420, 419, 422, 421, 420, 562, 422, 560, 566, 421, 420, 0, 422, 423, 568, 420, 570, 423, 424, 421, 420, 424, 422, 423, 421, 424, 421, 0, 423, 0, 421, 424, 0, 423, 0, 0, 421, 571, 571, 0, 423, 424, 428, 425, 423, 424, 421, 425, 424, 428, 423, 572, 424, 425, 425, 423, 428, 426, 424, 428, 423, 426, 427, 425, 571, 571, 427, 426, 424, 428, 425, 0, 427, 0, 425, 429, 428, 426, 572, 429, 425, 425, 427, 428, 426, 429, 428, 0, 426, 427, 425, 573, 0, 427, 426, 429, 0, 0, 431, 427, 431, 430, 429, 430, 426, 431, 429, 430, 0, 427, 431, 575, 429, 430, 432, 0, 432, 434, 573, 434, 576, 432, 429, 430, 434, 431, 432, 431, 430, 434, 430, 0, 431, 577, 430, 433, 578, 431, 575, 579, 430, 432, 433, 432, 434, 581, 434, 576, 432, 433, 430, 434, 433, 432, 435, 0, 434, 0, 435, 0, 577, 436, 433, 578, 435, 582, 579, 583, 436, 433, 437, 0, 581, 0, 435, 436, 433, 437, 436, 433, 584, 435, 437, 0, 437, 435, 438, 437, 436, 0, 0, 435, 582, 438, 583, 436, 0, 437, 438, 0, 438, 435, 436, 438, 437, 436, 440, 584, 585, 437, 439, 437, 439, 438, 437, 0, 440, 439, 440, 586, 438, 587, 439, 440, 588, 438, 441, 438, 440, 589, 438, 590, 443, 440, 441, 585, 443, 439, 441, 439, 442, 441, 443, 440, 439, 440, 586, 442, 587, 439, 440, 588, 443, 441, 442, 440, 589, 442, 590, 443, 0, 441, 0, 443, 592, 441, 444, 442, 441, 443, 593, 594, 0, 444, 442, 445, 595, 0, 0, 443, 444, 442, 445, 444, 442, 445, 447, 446, 0, 445, 447, 592, 445, 444, 446, 448, 447, 593, 594, 448, 444, 446, 445, 595, 446, 448, 447, 444, 0, 445, 444, 0, 445, 447, 446, 448, 445, 447, 0, 445, 449, 446, 448, 447, 449, 450, 448, 596, 446, 450, 449, 446, 448, 447, 599, 450, 0, 600, 451, 601, 449, 603, 448, 604, 0, 450, 451, 449, 0, 605, 451, 449, 450, 451, 596, 0, 450, 449, 606, 0, 0, 599, 450, 452, 600, 451, 601, 449, 603, 607, 604, 452, 450, 451, 453, 452, 605, 451, 452, 454, 451, 608, 453, 609, 0, 606, 453, 454, 0, 453, 452, 454, 0, 454, 454, 610, 607, 612, 452, 614, 0, 453, 452, 0, 729, 452, 454, 455, 608, 453, 609, 455, 0, 453, 454, 456, 453, 455, 454, 456, 454, 454, 610, 458, 612, 456, 614, 455, 457, 457, 458, 729, 730, 457, 455, 456, 0, 458, 455, 457, 458, 732, 456, 0, 455, 0, 456, 733, 734, 457, 458, 735, 456, 0, 455, 457, 457, 458, 0, 730, 457, 0, 456, 459, 458, 460, 457, 458, 732, 459, 459, 460, 460, 461, 733, 734, 457, 459, 735, 460, 459, 461, 460, 0, 0, 461, 0, 0, 461, 0, 459, 736, 460, 0, 0, 0, 459, 459, 460, 460, 461, 0, 462, 737, 459, 0, 460, 459, 461, 460, 462, 463, 461, 464, 462, 461, 462, 462, 736, 463, 465, 464, 465, 463, 738, 464, 463, 465, 464, 462, 737, 0, 465, 0, 0, 0, 739, 462, 463, 0, 464, 462, 741, 462, 462, 0, 463, 465, 464, 465, 463, 738, 464, 463, 465, 464, 466, 468, 467, 465, 467, 468, 469, 739, 466, 467, 469, 468, 466, 741, 467, 466, 469, 0, 742, 0, 0, 468, 743, 744, 0, 745, 469, 466, 468, 467, 0, 467, 468, 469, 747, 466, 467, 469, 468, 466, 470, 467, 466, 469, 471, 742, 471, 470, 468, 743, 744, 471, 745, 469, 470, 748, 471, 470, 472, 749, 472, 747, 472, 750, 751, 472, 0, 470, 0, 0, 472, 471, 752, 471, 470, 753, 0, 754, 471, 755, 756, 470, 748, 471, 470, 472, 749, 472, 0, 472, 750, 751, 472, 473, 473, 473, 474, 472, 759, 752, 473, 475, 753, 474, 754, 473, 755, 756, 475, 760, 474, 762, 476, 474, 0, 475, 764, 767, 475, 476, 473, 473, 473, 474, 0, 759, 476, 473, 475, 476, 474, 476, 473, 0, 477, 475, 760, 474, 762, 476, 474, 477, 475, 764, 767, 475, 476, 478, 477, 478, 768, 477, 770, 476, 478, 0, 476, 775, 476, 478, 479, 477, 480, 481, 479, 0, 480, 481, 477, 777, 479, 0, 480, 481, 478, 477, 478, 768, 477, 770, 479, 478, 480, 481, 775, 0, 478, 479, 482, 480, 481, 479, 482, 480, 481, 0, 777, 479, 482, 480, 481, 778, 483, 779, 0, 0, 483, 479, 482, 480, 481, 484, 483, 484, 769, 482, 782, 769, 484, 482, 483, 783, 483, 484, 485, 482, 485, 0, 778, 483, 779, 485, 485, 483, 0, 482, 485, 0, 484, 483, 484, 769, 784, 782, 769, 484, 785, 483, 783, 483, 484, 485, 786, 485, 486, 0, 486, 0, 485, 485, 787, 486, 486, 485, 491, 487, 486, 487, 491, 784, 789, 790, 487, 785, 491, 791, 792, 487, 488, 786, 488, 486, 488, 486, 491, 488, 0, 787, 486, 486, 488, 491, 487, 486, 487, 491, 793, 789, 790, 487, 794, 491, 791, 792, 487, 488, 489, 488, 489, 488, 795, 491, 488, 489, 489, 0, 796, 488, 489, 490, 797, 490, 798, 793, 492, 0, 490, 794, 492, 799, 800, 490, 493, 489, 492, 489, 493, 795, 801, 0, 489, 489, 493, 796, 492, 489, 490, 797, 490, 798, 803, 492, 493, 490, 804, 492, 799, 800, 490, 493, 494, 492, 494, 493, 496, 801, 495, 494, 496, 493, 805, 492, 494, 495, 496, 495, 496, 803, 497, 493, 495, 804, 497, 807, 496, 495, 0, 494, 497, 494, 808, 496, 0, 495, 494, 496, 0, 805, 497, 494, 495, 496, 495, 496, 0, 497, 498, 495, 809, 497, 807, 496, 495, 498, 499, 497, 499, 808, 0, 500, 498, 499, 0, 498, 0, 497, 499, 500, 895, 897, 503, 500, 0, 498, 500, 809, 0, 0, 503, 0, 498, 499, 503, 499, 503, 503, 500, 498, 499, 501, 498, 502, 501, 499, 500, 895, 897, 503, 500, 502, 501, 500, 504, 502, 501, 503, 502, 501, 502, 503, 504, 503, 503, 0, 504, 0, 501, 504, 502, 501, 0, 0, 899, 0, 900, 505, 502, 501, 0, 504, 502, 501, 505, 502, 501, 502, 506, 504, 0, 505, 617, 504, 505, 506, 504, 0, 901, 617, 618, 899, 506, 900, 505, 506, 617, 618, 0, 617, 903, 505, 0, 0, 618, 506, 0, 618, 505, 617, 619, 505, 506, 905, 619, 901, 617, 618, 620, 506, 619, 621, 506, 617, 618, 620, 617, 903, 0, 621, 619, 618, 620, 621, 618, 620, 621, 619, 623, 0, 905, 619, 906, 0, 0, 620, 623, 619, 621, 0, 623, 622, 620, 623, 624, 622, 621, 619, 624, 620, 621, 622, 620, 621, 624, 623, 625, 907, 908, 906, 625, 622, 0, 623, 624, 910, 625, 623, 622, 0, 623, 624, 622, 912, 0, 624, 625, 0, 622, 916, 0, 624, 626, 625, 907, 908, 918, 625, 622, 626, 627, 624, 910, 625, 628, 919, 626, 627, 629, 626, 912, 628, 0, 625, 627, 629, 916, 627, 628, 626, 925, 628, 629, 918, 0, 629, 626, 627, 0, 0, 0, 628, 919, 626, 627, 629, 626, 0, 628, 630, 926, 627, 629, 0, 627, 628, 630, 925, 628, 629, 631, 630, 629, 630, 631, 632, 630, 633, 927, 0, 631, 930, 632, 931, 633, 933, 630, 926, 934, 632, 631, 633, 632, 630, 633, 0, 0, 631, 630, 935, 630, 631, 632, 630, 633, 927, 634, 631, 930, 632, 931, 633, 933, 634, 0, 934, 632, 631, 633, 632, 634, 633, 635, 634, 635, 634, 935, 936, 938, 635, 636, 939, 636, 634, 635, 940, 943, 636, 636, 945, 634, 637, 636, 637, 0, 0, 0, 634, 637, 635, 634, 635, 634, 637, 936, 938, 635, 636, 939, 636, 947, 635, 940, 943, 636, 636, 945, 948, 637, 636, 637, 638, 638, 638, 639, 637, 640, 949, 638, 950, 637, 951, 639, 638, 640, 0, 639, 947, 640, 639, 640, 640, 0, 956, 948, 957, 0, 0, 638, 638, 638, 639, 0, 640, 949, 638, 950, 641, 951, 639, 638, 640, 642, 639, 641, 640, 639, 640, 640, 642, 956, 641, 957, 643, 641, 643, 642, 1027, 0, 642, 643, 1028, 0, 1031, 641, 1032, 1037, 643, 0, 642, 643, 641, 1038, 0, 0, 644, 642, 1040, 641, 644, 643, 641, 643, 642, 1027, 644, 642, 643, 1028, 645, 1031, 645, 1032, 1037, 643, 644, 645, 643, 646, 1038, 646, 645, 644, 1041, 1040, 646, 644, 647, 0, 647, 646, 0, 644, 0, 647, 0, 645, 0, 645, 647, 0, 1045, 644, 645, 1046, 646, 1048, 646, 645, 1050, 1041, 648, 646, 648, 647, 648, 647, 646, 648, 1051, 649, 647, 649, 648, 649, 1053, 647, 649, 1045, 650, 1054, 1046, 649, 1048, 1094, 1097, 1050, 650, 648, 0, 648, 650, 648, 0, 650, 648, 1051, 649, 0, 649, 648, 649, 1053, 0, 649, 651, 650, 1054, 652, 649, 1100, 1094, 1097, 651, 650, 652, 653, 651, 650, 651, 651, 650, 652, 653, 0, 652, 1104, 0, 0, 1105, 653, 0, 651, 653, 0, 652, 1106, 1100, 0, 0, 651, 654, 652, 653, 651, 654, 651, 651, 0, 652, 653, 654, 652, 1104, 655, 656, 1105, 653, 655, 656, 653, 654, 657, 1106, 655, 656, 658, 1123, 654, 657, 656, 0, 654, 658, 655, 656, 657, 0, 654, 657, 658, 655, 656, 658, 0, 655, 656, 1125, 654, 657, 1128, 655, 656, 658, 1123, 1137, 657, 656, 659, 0, 658, 655, 656, 657, 660, 659, 657, 658, 0, 661, 658, 660, 659, 662, 1125, 659, 661, 1128, 660, 0, 662, 660, 1137, 661, 661, 659, 661, 662, 0, 663, 662, 660, 659, 0, 0, 0, 661, 663, 660, 659, 662, 663, 659, 661, 663, 660, 0, 662, 660, 0, 661, 661, 0, 661, 662, 664, 663, 662, 0, 0, 0, 0, 0, 664, 663, 665, 666, 664, 663, 665, 664, 663, 0, 0, 666, 665, 0, 667, 666, 667, 0, 666, 664, 668, 667, 665, 0, 0, 0, 667, 664, 668, 665, 666, 664, 668, 665, 664, 668, 0, 0, 666, 665, 0, 667, 666, 667, 0, 666, 669, 668, 667, 665, 0, 0, 0, 667, 669, 668, 670, 670, 669, 668, 0, 669, 668, 0, 670, 0, 0, 671, 670, 0, 0, 670, 0, 669, 0, 671, 0, 0, 0, 671, 0, 669, 671, 670, 670, 669, 0, 0, 669, 0, 0, 670, 0, 0, 671, 670, 0, 0, 670, 0, 0, 672, 671, 672, 0, 673, 671, 673, 672, 671, 0, 0, 673, 672, 674, 0, 674, 673, 0, 0, 0, 674, 0, 0, 0, 0, 674, 0, 672, 0, 672, 0, 673, 0, 673, 672, 0, 0, 0, 673, 672, 674, 0, 674, 673, 675, 0, 675, 674, 0, 0, 0, 675, 674, 676, 0, 676, 675, 677, 0, 677, 676, 676, 0, 0, 677, 676, 0, 0, 0, 677, 0, 675, 0, 675, 0, 0, 0, 0, 675, 0, 676, 0, 676, 675, 677, 0, 677, 676, 676, 0, 0, 677, 676, 678, 0, 678, 677, 679, 680, 679, 678, 0, 680, 0, 679, 678, 0, 0, 680, 679, 0, 0, 0, 0, 0, 0, 682, 0, 680, 0, 678, 0, 678, 682, 679, 680, 679, 678, 0, 680, 682, 679, 678, 682, 0, 680, 679, 0, 0, 681, 0, 681, 683, 682, 0, 680, 681, 681, 684, 683, 682, 681, 0, 0, 0, 684, 683, 682, 0, 683, 682, 0, 684, 0, 0, 684, 681, 0, 681, 683, 685, 0, 685, 681, 681, 684, 683, 685, 681, 0, 0, 686, 684, 683, 685, 686, 683, 685, 687, 684, 0, 686, 684, 688, 0, 687, 0, 685, 0, 685, 688, 686, 687, 0, 685, 687, 0, 688, 686, 689, 688, 685, 686, 0, 685, 687, 689, 0, 686, 0, 688, 689, 687, 689, 690, 0, 689, 688, 686, 687, 0, 690, 687, 0, 688, 691, 689, 688, 690, 0, 692, 690, 691, 689, 0, 0, 0, 692, 689, 691, 689, 690, 691, 689, 692, 0, 693, 692, 690, 0, 0, 0, 691, 693, 0, 690, 0, 692, 690, 691, 693, 695, 0, 693, 692, 693, 691, 0, 695, 691, 0, 692, 694, 693, 692, 695, 0, 0, 695, 694, 693, 0, 0, 0, 694, 0, 694, 693, 695, 694, 693, 0, 693, 696, 0, 695, 0, 0, 0, 694, 696, 0, 695, 0, 0, 695, 694, 696, 697, 697, 696, 694, 696, 694, 698, 697, 694, 699, 0, 699, 696, 698, 697, 0, 699, 697, 698, 696, 698, 699, 0, 698, 0, 0, 696, 697, 697, 696, 0, 696, 0, 698, 697, 0, 699, 0, 699, 0, 698, 697, 700, 699, 697, 698, 0, 698, 699, 0, 698, 700, 701, 700, 701, 702, 703, 702, 700, 701, 703, 0, 702, 700, 701, 0, 703, 702, 0, 700, 0, 0, 0, 0, 0, 0, 703, 0, 700, 701, 700, 701, 702, 703, 702, 700, 701, 703, 704, 702, 700, 701, 704, 703, 702, 0, 705, 706, 704, 0, 705, 706, 0, 703, 0, 0, 705, 706, 704, 0, 707, 0, 0, 0, 707, 704, 705, 706, 0, 704, 707, 0, 708, 705, 706, 704, 708, 705, 706, 0, 707, 0, 708, 705, 706, 704, 0, 707, 709, 0, 709, 707, 708, 705, 706, 709, 0, 707, 710, 708, 709, 0, 710, 708, 711, 0, 711, 707, 710, 708, 0, 711, 0, 0, 0, 709, 711, 709, 710, 708, 0, 0, 709, 0, 0, 710, 0, 709, 0, 710, 712, 711, 712, 711, 714, 710, 714, 712, 711, 713, 0, 714, 712, 711, 0, 710, 714, 0, 713, 0, 713, 0, 0, 0, 0, 713, 0, 712, 0, 712, 713, 714, 0, 714, 712, 0, 713, 716, 714, 712, 0, 715, 0, 714, 716, 713, 0, 713, 717, 715, 0, 716, 713, 715, 716, 717, 715, 713, 0, 0, 0, 0, 717, 0, 716, 717, 0, 717, 715, 0, 0, 716, 0, 0, 0, 717, 715, 0, 716, 718, 715, 716, 717, 715, 0, 718, 718, 719, 720, 717, 0, 719, 717, 718, 717, 720, 718, 719, 0, 0, 0, 0, 720, 0, 0, 720, 718, 719, 0, 0, 0, 0, 718, 718, 719, 720, 0, 0, 719, 721, 718, 0, 720, 718, 719, 0, 721, 722, 0, 720, 0, 0, 720, 721, 719, 722, 721, 723, 0, 722, 0, 0, 722, 0, 0, 723, 721, 724, 0, 723, 0, 724, 723, 721, 722, 725, 0, 724, 0, 725, 721, 0, 722, 721, 723, 725, 722, 724, 0, 722, 0, 0, 723, 726, 724, 725, 723, 726, 724, 723, 0, 811, 725, 726, 724, 811, 725, 0, 0, 0, 0, 811, 725, 726, 724, 812, 0, 0, 0, 812, 726, 811, 725, 813, 726, 812, 0, 813, 811, 0, 726, 0, 811, 813, 0, 812, 0, 814, 811, 0, 726, 814, 812, 813, 813, 815, 812, 814, 811, 815, 813, 0, 812, 0, 813, 815, 0, 814, 0, 816, 813, 0, 812, 816, 814, 815, 0, 0, 814, 816, 813, 813, 815, 817, 814, 0, 815, 817, 0, 816, 818, 0, 815, 817, 814, 0, 816, 818, 817, 0, 816, 0, 815, 817, 818, 819, 816, 818, 819, 0, 817, 0, 819, 0, 817, 0, 816, 818, 0, 819, 817, 820, 819, 0, 818, 817, 0, 0, 0, 820, 817, 818, 819, 820, 818, 819, 820, 0, 0, 819, 0, 0, 0, 821, 0, 822, 819, 0, 820, 819, 0, 821, 822, 0, 0, 821, 820, 821, 821, 822, 820, 823, 822, 820, 0, 823, 0, 0, 0, 0, 821, 823, 822, 824, 0, 0, 0, 824, 821, 822, 0, 823, 821, 824, 821, 821, 822, 825, 823, 822, 0, 825, 823, 824, 828, 826, 828, 825, 823, 826, 824, 828, 827, 0, 824, 826, 828, 825, 823, 827, 824, 0, 0, 0, 825, 826, 827, 0, 825, 827, 824, 828, 826, 828, 825, 0, 826, 829, 828, 827, 0, 829, 826, 828, 825, 830, 827, 829, 0, 830, 831, 0, 826, 827, 831, 830, 827, 829, 0, 833, 831, 833, 0, 832, 829, 830, 833, 832, 829, 0, 831, 833, 830, 832, 829, 834, 830, 831, 832, 834, 0, 831, 830, 832, 829, 834, 833, 831, 833, 0, 832, 0, 830, 833, 832, 834, 0, 831, 833, 835, 832, 0, 834, 835, 0, 832, 834, 0, 0, 835, 832, 839, 834, 836, 837, 839, 0, 836, 837, 835, 0, 839, 834, 836, 837, 838, 835, 838, 836, 837, 835, 839, 838, 836, 837, 0, 835, 838, 839, 0, 836, 837, 839, 0, 836, 837, 835, 0, 839, 0, 836, 837, 838, 0, 838, 836, 837, 0, 839, 838, 836, 837, 841, 840, 838, 840, 841, 842, 0, 840, 0, 842, 841, 0, 0, 840, 844, 842, 844, 0, 0, 0, 841, 844, 0, 840, 0, 842, 844, 841, 840, 843, 840, 841, 842, 843, 840, 0, 842, 841, 0, 843, 840, 844, 842, 844, 843, 0, 0, 841, 844, 843, 840, 0, 842, 844, 0, 845, 843, 845, 846, 0, 843, 0, 845, 846, 0, 846, 843, 845, 0, 0, 846, 843, 0, 0, 0, 846, 843, 0, 0, 847, 0, 847, 845, 0, 845, 846, 847, 0, 0, 845, 846, 847, 846, 848, 845, 848, 0, 846, 0, 0, 848, 848, 846, 0, 0, 848, 847, 849, 847, 849, 0, 0, 0, 847, 849, 0, 0, 0, 847, 849, 848, 0, 848, 850, 0, 850, 0, 848, 848, 0, 850, 851, 848, 851, 849, 850, 849, 0, 851, 851, 0, 849, 0, 851, 852, 0, 849, 0, 852, 853, 850, 853, 850, 0, 852, 0, 853, 850, 851, 853, 851, 853, 850, 0, 852, 851, 851, 854, 0, 854, 851, 852, 0, 0, 854, 852, 853, 0, 853, 854, 855, 852, 855, 853, 0, 0, 853, 855, 853, 0, 0, 852, 855, 856, 854, 856, 854, 0, 0, 0, 856, 854, 0, 0, 0, 856, 854, 855, 0, 855, 0, 857, 0, 857, 855, 0, 0, 0, 857, 855, 856, 0, 856, 857, 858, 0, 858, 856, 0, 859, 0, 858, 856, 859, 0, 0, 858, 860, 857, 859, 857, 860, 0, 0, 0, 857, 0, 860, 861, 859, 857, 858, 0, 858, 0, 861, 859, 860, 858, 0, 859, 0, 861, 858, 860, 861, 859, 0, 860, 0, 0, 862, 0, 0, 860, 861, 859, 0, 862, 864, 863, 0, 861, 0, 860, 862, 864, 863, 862, 861, 0, 866, 861, 864, 863, 866, 864, 863, 862, 863, 0, 866, 865, 0, 0, 862, 864, 863, 0, 865, 0, 866, 862, 864, 863, 862, 865, 0, 866, 865, 864, 863, 866, 864, 863, 867, 863, 868, 866, 865, 0, 0, 867, 0, 868, 0, 865, 0, 866, 867, 0, 868, 867, 865, 868, 869, 865, 870, 0, 869, 0, 870, 867, 0, 868, 869, 0, 870, 0, 867, 871, 868, 0, 0, 871, 869, 867, 870, 868, 867, 871, 868, 869, 872, 870, 0, 869, 872, 870, 0, 871, 873, 869, 872, 870, 0, 0, 871, 873, 874, 0, 871, 869, 872, 870, 873, 874, 871, 873, 0, 872, 0, 0, 874, 872, 0, 874, 871, 873, 0, 872, 0, 0, 0, 875, 873, 874, 875, 0, 0, 872, 875, 873, 874, 0, 873, 0, 0, 875, 0, 874, 875, 876, 874, 0, 0, 0, 0, 0, 876, 0, 875, 0, 877, 875, 0, 876, 877, 875, 876, 0, 876, 0, 877, 0, 875, 878, 878, 875, 876, 0, 878, 0, 877, 0, 879, 876, 878, 0, 0, 877, 0, 879, 876, 877, 0, 876, 878, 876, 879, 877, 0, 879, 878, 878, 0, 881, 0, 878, 880, 877, 880, 879, 881, 878, 883, 880, 883, 882, 879, 881, 880, 883, 881, 878, 882, 879, 883, 0, 879, 0, 0, 882, 881, 0, 882, 880, 882, 880, 884, 881, 0, 883, 880, 883, 882, 884, 881, 880, 883, 881, 885, 882, 884, 883, 0, 884, 0, 885, 882, 886, 0, 882, 0, 882, 885, 884, 886, 885, 0, 0, 887, 0, 884, 886, 887, 0, 886, 885, 0, 884, 887, 0, 884, 0, 885, 889, 886, 888, 888, 889, 887, 885, 888, 886, 885, 889, 0, 887, 888, 0, 886, 887, 0, 886, 0, 889, 0, 887, 888, 0, 0, 0, 889, 0, 888, 888, 889, 887, 0, 888, 890, 891, 889, 891, 890, 888, 0, 892, 891, 893, 890, 0, 889, 891, 892, 888, 893, 0, 0, 0, 890, 892, 0, 893, 892, 894, 893, 890, 891, 0, 891, 890, 894, 0, 892, 891, 893, 890, 0, 894, 891, 892, 894, 893, 0, 958, 0, 890, 892, 958, 893, 892, 894, 893, 959, 958, 0, 0, 959, 894, 0, 960, 0, 960, 959, 958, 894, 0, 960, 894, 0, 0, 958, 960, 959, 0, 958, 961, 0, 961, 0, 959, 958, 0, 961, 959, 0, 0, 960, 961, 960, 959, 958, 0, 0, 960, 962, 0, 962, 0, 960, 959, 0, 962, 961, 964, 961, 964, 962, 963, 0, 961, 964, 963, 0, 0, 961, 964, 0, 963, 0, 0, 0, 962, 0, 962, 965, 0, 965, 963, 962, 0, 964, 965, 964, 962, 963, 0, 965, 964, 963, 0, 0, 0, 964, 966, 963, 966, 0, 0, 0, 0, 966, 965, 0, 965, 963, 966, 0, 967, 965, 967, 0, 0, 0, 965, 967, 0, 968, 968, 968, 967, 966, 0, 966, 968, 0, 0, 969, 966, 968, 0, 0, 0, 966, 0, 967, 969, 967, 969, 0, 0, 0, 967, 969, 968, 968, 968, 967, 969, 0, 970, 968, 970, 0, 969, 0, 968, 970, 0, 971, 0, 971, 970, 969, 0, 969, 971, 971, 0, 0, 969, 971, 0, 0, 0, 969, 0, 970, 972, 970, 972, 0, 0, 0, 970, 972, 971, 973, 971, 970, 972, 0, 0, 971, 971, 0, 0, 973, 971, 973, 0, 974, 0, 974, 973, 972, 0, 972, 974, 973, 0, 975, 972, 974, 973, 0, 0, 972, 0, 0, 975, 0, 975, 0, 973, 0, 973, 975, 974, 0, 974, 973, 975, 0, 0, 974, 973, 0, 975, 976, 974, 976, 0, 977, 0, 977, 976, 975, 0, 975, 977, 976, 0, 0, 975, 977, 0, 0, 0, 975, 0, 979, 978, 0, 978, 979, 976, 0, 976, 978, 977, 979, 977, 976, 978, 980, 0, 977, 976, 980, 0, 979, 977, 0, 0, 980, 0, 0, 979, 978, 0, 978, 979, 0, 0, 980, 978, 981, 979, 981, 0, 978, 980, 982, 981, 982, 980, 0, 979, 981, 982, 982, 980, 0, 0, 982, 983, 0, 983, 0, 0, 0, 980, 983, 981, 0, 981, 984, 983, 984, 982, 981, 982, 0, 984, 0, 981, 982, 982, 984, 0, 0, 982, 983, 0, 983, 985, 0, 985, 0, 983, 0, 0, 985, 984, 983, 984, 986, 985, 986, 987, 984, 987, 0, 986, 0, 984, 987, 0, 986, 0, 0, 987, 985, 0, 985, 988, 0, 989, 0, 985, 0, 989, 988, 986, 985, 986, 987, 989, 987, 988, 986, 0, 988, 987, 0, 986, 990, 989, 987, 0, 0, 0, 988, 990, 989, 0, 0, 0, 989, 988, 990, 991, 0, 990, 989, 992, 988, 0, 991, 988, 0, 0, 992, 990, 989, 991, 0, 0, 991, 992, 990, 0, 992, 0, 993, 0, 993, 990, 991, 0, 990, 993, 992, 994, 0, 991, 993, 0, 0, 992, 994, 0, 991, 0, 0, 991, 992, 994, 995, 992, 994, 993, 996, 993, 0, 995, 0, 0, 993, 996, 994, 0, 995, 993, 0, 995, 996, 994, 997, 996, 0, 996, 997, 0, 994, 995, 0, 994, 997, 996, 998, 0, 995, 0, 998, 0, 996, 999, 997, 995, 998, 0, 995, 996, 999, 997, 996, 0, 996, 997, 998, 999, 1000, 0, 999, 997, 1001, 998, 1001, 1000, 0, 998, 0, 1001, 999, 997, 1000, 998, 0, 1000, 1001, 999, 0, 1001, 0, 0, 0, 998, 999, 1000, 0, 999, 0, 1001, 0, 1001, 1000, 1002, 0, 1002, 1001, 0, 0, 1000, 1002, 0, 1000, 1001, 0, 0, 1001, 1002, 0, 1003, 1002, 1003, 1004, 0, 1004, 0, 1003, 0, 0, 1004, 1002, 1003, 1002, 1005, 1004, 1005, 0, 1002, 0, 0, 1005, 0, 0, 0, 1002, 1005, 1003, 1002, 1003, 1004, 0, 1004, 1006, 1003, 1006, 0, 1004, 0, 1003, 1006, 1005, 1004, 1005, 1007, 1006, 1007, 1008, 1005, 1008, 0, 1007, 0, 1005, 1008, 0, 1007, 0, 0, 1008, 1006, 0, 1006, 1009, 0, 1009, 0, 1006, 0, 0, 1009, 1007, 1006, 1007, 1008, 1009, 1008, 1010, 1007, 0, 0, 1008, 1011, 1007, 1010, 0, 1008, 0, 0, 1011, 1009, 1010, 1009, 1012, 1010, 0, 1011, 1009, 0, 1011, 1012, 0, 1009, 0, 1010, 0, 0, 1012, 0, 1011, 1012, 1010, 1012, 0, 0, 1013, 1011, 1013, 1010, 0, 1012, 1010, 1013, 1011, 1014, 0, 1011, 1012, 0, 1013, 0, 1014, 1013, 1015, 1012, 0, 0, 1012, 1014, 1012, 1015, 1014, 1013, 1014, 1013, 0, 0, 1015, 0, 1013, 1015, 1014, 0, 0, 0, 1016, 1013, 0, 1014, 1013, 1015, 0, 1016, 0, 1017, 1014, 1018, 1015, 1014, 1016, 1014, 1017, 1016, 1018, 1015, 0, 0, 1015, 1017, 0, 1018, 1017, 1016, 1018, 0, 0, 0, 1019, 0, 1016, 1020, 1017, 1020, 1018, 1019, 0, 1016, 1020, 1017, 1016, 1018, 1019, 1020, 0, 1019, 1017, 0, 1018, 1017, 0, 1018, 1057, 0, 1057, 1019, 0, 0, 1020, 1057, 1020, 1058, 1019, 1058, 1057, 1020, 0, 0, 1058, 1019, 1020, 0, 1019, 1058, 0, 1059, 0, 1059, 0, 1057, 0, 1057, 1059, 0, 0, 0, 1057, 1059, 1058, 0, 1058, 1057, 0, 0, 1060, 1058, 1060, 0, 0, 0, 1058, 1060, 1059, 1061, 1059, 1061, 1060, 0, 0, 1059, 1061, 0, 0, 0, 1059, 1061, 1063, 1062, 0, 1062, 1063, 1060, 0, 1060, 1062, 0, 1063, 0, 1060, 1062, 1061, 1064, 1061, 1060, 0, 0, 1063, 1061, 1064, 0, 0, 0, 1061, 1063, 1062, 1064, 1062, 1063, 1064, 0, 1065, 1062, 1066, 1063, 0, 0, 1062, 1065, 1064, 1066, 0, 0, 0, 1063, 1065, 1064, 1066, 1065, 0, 1066, 1067, 0, 1064, 0, 1067, 1064, 0, 1065, 0, 1066, 1067, 0, 0, 0, 1065, 1068, 1066, 0, 1069, 1068, 1067, 1065, 1069, 1066, 1065, 1068, 1066, 1067, 1069, 0, 1068, 1067, 0, 0, 0, 1068, 0, 1067, 1069, 0, 1070, 0, 1068, 0, 1070, 1069, 1068, 1067, 0, 1069, 1070, 0, 1068, 0, 1071, 1069, 0, 1068, 1071, 1072, 1070, 0, 1068, 1072, 1071, 1069, 1073, 1070, 1073, 1072, 0, 1070, 1073, 0, 1071, 0, 0, 1070, 1073, 1072, 0, 1071, 1074, 0, 1074, 1071, 1072, 1070, 1073, 1074, 1072, 1071, 0, 1073, 1074, 1073, 1072, 0, 0, 1073, 1075, 1071, 1075, 1076, 1077, 1073, 1072, 1075, 1077, 1074, 1076, 1074, 1075, 0, 1077, 1073, 1074, 1076, 1078, 0, 1076, 1074, 1078, 0, 1077, 0, 0, 1075, 1078, 1075, 1076, 1077, 1079, 0, 1075, 1077, 1079, 1076, 1078, 1075, 0, 1077, 1079, 0, 1076, 1078, 1080, 1076, 0, 1078, 1080, 1077, 1079, 0, 0, 1078, 1080, 0, 0, 1079, 1081, 0, 0, 1079, 1081, 1078, 1080, 0, 1082, 1079, 1081, 0, 1082, 1080, 1082, 1081, 0, 1080, 1082, 1079, 1081, 0, 0, 1080, 0, 0, 1083, 1081, 1082, 0, 1083, 1081, 0, 1080, 1084, 1082, 1083, 1081, 1084, 1082, 0, 1082, 1081, 0, 1084, 1082, 1083, 1081, 1085, 1084, 0, 0, 1085, 1083, 1084, 1082, 0, 1083, 1085, 0, 1086, 1084, 0, 1083, 0, 1084, 0, 1086, 1085, 0, 0, 1084, 0, 1083, 1086, 1085, 1084, 1086, 0, 1085, 0, 1084, 1088, 0, 0, 1085, 1087, 1086, 0, 1088, 0, 0, 0, 1087, 1086, 1085, 1088, 0, 1087, 1088, 1087, 1086, 0, 1087, 1086, 1089, 0, 0, 0, 1088, 0, 1090, 1089, 1087, 0, 1090, 1088, 0, 0, 1089, 1087, 1090, 1089, 1088, 1089, 1087, 1088, 1087, 0, 0, 1087, 1090, 1089, 1091, 0, 0, 0, 1091, 1090, 1089, 0, 0, 1090, 1091, 0, 0, 1089, 0, 1090, 1089, 0, 1089, 1092, 1091, 0, 1108, 1092, 1110, 1090, 1108, 1091, 1110, 1092, 0, 1091, 1108, 0, 1110, 0, 0, 1091, 0, 1092, 0, 0, 1108, 0, 1110, 0, 1092, 1091, 1109, 1108, 1092, 1110, 1109, 1108, 0, 1110, 1092, 0, 1109, 1108, 1111, 1110, 0, 1109, 1111, 0, 1092, 0, 1109, 1108, 1111, 1110, 1113, 1112, 1114, 1109, 1113, 1112, 1114, 1109, 1111, 0, 1113, 1112, 1114, 1109, 0, 1111, 1112, 0, 1109, 1111, 1113, 1112, 1114, 1109, 0, 1111, 0, 1113, 1112, 1114, 0, 1113, 1112, 1114, 0, 1111, 0, 1113, 1112, 1114, 0, 0, 0, 1112, 1115, 1116, 1117, 1113, 1112, 1114, 1118, 1115, 1116, 1117, 0, 0, 0, 1118, 1115, 1116, 1117, 1115, 1116, 1117, 1118, 0, 0, 1118, 0, 0, 0, 1115, 1116, 1117, 0, 0, 0, 1118, 1115, 1116, 1117, 0, 0, 0, 1118, 1115, 1116, 1117, 1115, 1116, 1117, 1118, 1119, 1120, 1118, 1121, 1119, 1120, 0, 1121, 0, 0, 1119, 1120, 1120, 1121, 0, 1122, 0, 0, 0, 1122, 1119, 1120, 0, 1121, 0, 1122, 0, 1119, 1120, 0, 1121, 1119, 1120, 0, 1121, 1122, 0, 1119, 1120, 1120, 1121, 1129, 1122, 0, 0, 1129, 1122, 1119, 1120, 1130, 1121, 1129, 1122, 1130, 0, 0, 0, 0, 1131, 1130, 1131, 1129, 1122, 1134, 0, 1131, 0, 1134, 1129, 1130, 1131, 0, 1129, 1134, 0, 0, 1130, 1132, 1129, 1132, 1130, 0, 0, 1134, 1132, 1131, 1130, 1131, 1129, 1132, 1134, 1133, 1131, 1133, 1134, 1138, 1130, 1131, 1133, 1138, 1134, 0, 0, 1133, 1132, 1138, 1132, 0, 0, 1139, 1134, 1132, 0, 1139, 0, 1138, 1132, 0, 1133, 1139, 1133, 1140, 1138, 1140, 0, 1133, 1138, 0, 1140, 1139, 1133, 0, 1138, 1140, 0, 0, 1139, 1142, 0, 1142, 1139, 0, 1138, 0, 1142, 0, 1139, 0, 1140, 1142, 1140, 0, 0, 0, 0, 1140, 1139, 0, 0, 0, 1140, 0, 0, 0, 1142, 0, 1142, 0, 0, 0, 0, 1142, 0, 0, 0, 0, 1142, 1144, 1144, 1144, 1144, 1144, 1145, 0, 0, 1145, 1145, 1147, 1147, 1147, 0, 1147, 1148, 0, 1148, 1148, 1148, 1149, 0, 1149, 1149, 1149, 1150, 0, 1150, 1150, 1150, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143, 1143 } ; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "flex_lexer.l" /** * lexer * * */ /*************************** ** Section 1: Definitions ***************************/ #line 12 "flex_lexer.l" #include "../sql/Expr.h" #include "bison_parser.h" #include <stdio.h> #include <sstream> #define TOKEN(name) { return SQL_##name; } static thread_local std::stringstream strbuf; #line 2676 "flex_lexer.cpp" /*************************** ** Section 2: Rules ***************************/ /* Define the output files */ /* Make reentrant */ /* performance tweeks */ /* other flags */ /* %option nodefault */ /*************************** ** Section 3: Rules ***************************/ #line 2690 "flex_lexer.cpp" #define INITIAL 0 #define singlequotedstring 1 #define COMMENT 2 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; int yy_n_chars; int yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; YYLTYPE * yylloc_r; }; /* end struct yyguts_t */ static int yy_init_globals ( yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r # define yylloc yyg->yylloc_r int yylex_init (yyscan_t* scanner); int yylex_init_extra ( YY_EXTRA_TYPE user_defined, yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int yylex_destroy ( yyscan_t yyscanner ); int yyget_debug ( yyscan_t yyscanner ); void yyset_debug ( int debug_flag , yyscan_t yyscanner ); YY_EXTRA_TYPE yyget_extra ( yyscan_t yyscanner ); void yyset_extra ( YY_EXTRA_TYPE user_defined , yyscan_t yyscanner ); FILE *yyget_in ( yyscan_t yyscanner ); void yyset_in ( FILE * _in_str , yyscan_t yyscanner ); FILE *yyget_out ( yyscan_t yyscanner ); void yyset_out ( FILE * _out_str , yyscan_t yyscanner ); int yyget_leng ( yyscan_t yyscanner ); char *yyget_text ( yyscan_t yyscanner ); int yyget_lineno ( yyscan_t yyscanner ); void yyset_lineno ( int _line_number , yyscan_t yyscanner ); int yyget_column ( yyscan_t yyscanner ); void yyset_column ( int _column_no , yyscan_t yyscanner ); YYSTYPE * yyget_lval ( yyscan_t yyscanner ); void yyset_lval ( YYSTYPE * yylval_param , yyscan_t yyscanner ); YYLTYPE *yyget_lloc ( yyscan_t yyscanner ); void yyset_lloc ( YYLTYPE * yylloc_param , yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int yywrap ( yyscan_t yyscanner ); #else extern int yywrap ( yyscan_t yyscanner ); #endif #endif #ifndef YY_NO_UNPUT #endif #ifndef yytext_ptr static void yy_flex_strncpy ( char *, const char *, int , yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen ( const char * , yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput ( yyscan_t yyscanner ); #else static int input ( yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, (size_t) yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ int n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = (int) fread(buf, 1, (yy_size_t) max_size, yyin)) == 0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int yylex \ (YYSTYPE * yylval_param, YYLTYPE * yylloc_param , yyscan_t yyscanner); #define YY_DECL int yylex \ (YYSTYPE * yylval_param, YYLTYPE * yylloc_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; yylloc = yylloc_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); } yy_load_buffer_state( yyscanner ); } { #line 58 "flex_lexer.l" #line 2977 "flex_lexer.cpp" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 1144 ) yy_c = yy_meta[yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; ++yy_cp; } while ( yy_current_state != 1143 ); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 60 "flex_lexer.l" BEGIN(COMMENT); YY_BREAK case 2: YY_RULE_SETUP #line 61 "flex_lexer.l" /* skipping comment content until a end of line is read */; YY_BREAK case 3: /* rule 3 can match eol */ YY_RULE_SETUP #line 62 "flex_lexer.l" BEGIN(INITIAL); YY_BREAK case 4: /* rule 4 can match eol */ YY_RULE_SETUP #line 64 "flex_lexer.l" /* skip whitespace */; YY_BREAK case 5: YY_RULE_SETUP #line 66 "flex_lexer.l" TOKEN(DEALLOCATE) YY_BREAK case 6: YY_RULE_SETUP #line 67 "flex_lexer.l" TOKEN(PARAMETERS) YY_BREAK case 7: YY_RULE_SETUP #line 68 "flex_lexer.l" TOKEN(INTERSECT) YY_BREAK case 8: YY_RULE_SETUP #line 69 "flex_lexer.l" TOKEN(TEMPORARY) YY_BREAK case 9: YY_RULE_SETUP #line 70 "flex_lexer.l" TOKEN(TIMESTAMP) YY_BREAK case 10: YY_RULE_SETUP #line 71 "flex_lexer.l" TOKEN(INTERVAL) YY_BREAK case 11: YY_RULE_SETUP #line 72 "flex_lexer.l" TOKEN(DESCRIBE) YY_BREAK case 12: YY_RULE_SETUP #line 73 "flex_lexer.l" TOKEN(DISTINCT) YY_BREAK case 13: YY_RULE_SETUP #line 74 "flex_lexer.l" TOKEN(NVARCHAR) YY_BREAK case 14: YY_RULE_SETUP #line 75 "flex_lexer.l" TOKEN(RESTRICT) YY_BREAK case 15: YY_RULE_SETUP #line 76 "flex_lexer.l" TOKEN(TRUNCATE) YY_BREAK case 16: YY_RULE_SETUP #line 77 "flex_lexer.l" TOKEN(ANALYZE) YY_BREAK case 17: YY_RULE_SETUP #line 78 "flex_lexer.l" TOKEN(BETWEEN) YY_BREAK case 18: YY_RULE_SETUP #line 79 "flex_lexer.l" TOKEN(CASCADE) YY_BREAK case 19: YY_RULE_SETUP #line 80 "flex_lexer.l" TOKEN(COLUMNS) YY_BREAK case 20: YY_RULE_SETUP #line 81 "flex_lexer.l" TOKEN(CONTROL) YY_BREAK case 21: YY_RULE_SETUP #line 82 "flex_lexer.l" TOKEN(DEFAULT) YY_BREAK case 22: YY_RULE_SETUP #line 83 "flex_lexer.l" TOKEN(EXECUTE) YY_BREAK case 23: YY_RULE_SETUP #line 84 "flex_lexer.l" TOKEN(DECIMAL) YY_BREAK case 24: YY_RULE_SETUP #line 85 "flex_lexer.l" TOKEN(EXPLAIN) YY_BREAK case 25: YY_RULE_SETUP #line 86 "flex_lexer.l" TOKEN(INT) YY_BREAK case 26: YY_RULE_SETUP #line 87 "flex_lexer.l" TOKEN(QUARTER) YY_BREAK case 27: YY_RULE_SETUP #line 88 "flex_lexer.l" TOKEN(TINYINT) YY_BREAK case 28: YY_RULE_SETUP #line 89 "flex_lexer.l" TOKEN(SMALLINT) YY_BREAK case 29: YY_RULE_SETUP #line 90 "flex_lexer.l" TOKEN(BOOLEAN) YY_BREAK case 30: YY_RULE_SETUP #line 91 "flex_lexer.l" TOKEN(NATURAL) YY_BREAK case 31: YY_RULE_SETUP #line 92 "flex_lexer.l" TOKEN(PREPARE) YY_BREAK case 32: YY_RULE_SETUP #line 93 "flex_lexer.l" TOKEN(PRIMARY) YY_BREAK case 33: YY_RULE_SETUP #line 94 "flex_lexer.l" TOKEN(SCHEMAS) YY_BREAK case 34: YY_RULE_SETUP #line 95 "flex_lexer.l" TOKEN(SPATIAL) YY_BREAK case 35: YY_RULE_SETUP #line 96 "flex_lexer.l" TOKEN(VARCHAR) YY_BREAK case 36: YY_RULE_SETUP #line 97 "flex_lexer.l" TOKEN(VIRTUAL) YY_BREAK case 37: YY_RULE_SETUP #line 98 "flex_lexer.l" TOKEN(BEFORE) YY_BREAK case 38: YY_RULE_SETUP #line 99 "flex_lexer.l" TOKEN(COLUMN) YY_BREAK case 39: YY_RULE_SETUP #line 100 "flex_lexer.l" TOKEN(CREATE) YY_BREAK case 40: YY_RULE_SETUP #line 101 "flex_lexer.l" TOKEN(DELETE) YY_BREAK case 41: YY_RULE_SETUP #line 102 "flex_lexer.l" TOKEN(DIRECT) YY_BREAK case 42: YY_RULE_SETUP #line 103 "flex_lexer.l" TOKEN(DOUBLE) YY_BREAK case 43: YY_RULE_SETUP #line 104 "flex_lexer.l" TOKEN(ESCAPE) YY_BREAK case 44: YY_RULE_SETUP #line 105 "flex_lexer.l" TOKEN(EXCEPT) YY_BREAK case 45: YY_RULE_SETUP #line 106 "flex_lexer.l" TOKEN(EXISTS) YY_BREAK case 46: YY_RULE_SETUP #line 107 "flex_lexer.l" TOKEN(EXTRACT) YY_BREAK case 47: YY_RULE_SETUP #line 108 "flex_lexer.l" TOKEN(CAST) YY_BREAK case 48: YY_RULE_SETUP #line 109 "flex_lexer.l" TOKEN(FORMAT) YY_BREAK case 49: YY_RULE_SETUP #line 110 "flex_lexer.l" TOKEN(GLOBAL) YY_BREAK case 50: YY_RULE_SETUP #line 111 "flex_lexer.l" TOKEN(HAVING) YY_BREAK case 51: YY_RULE_SETUP #line 112 "flex_lexer.l" TOKEN(IMPORT) YY_BREAK case 52: YY_RULE_SETUP #line 113 "flex_lexer.l" TOKEN(INSERT) YY_BREAK case 53: YY_RULE_SETUP #line 114 "flex_lexer.l" TOKEN(ISNULL) YY_BREAK case 54: YY_RULE_SETUP #line 115 "flex_lexer.l" TOKEN(OFFSET) YY_BREAK case 55: YY_RULE_SETUP #line 116 "flex_lexer.l" TOKEN(RENAME) YY_BREAK case 56: YY_RULE_SETUP #line 117 "flex_lexer.l" TOKEN(SCHEMA) YY_BREAK case 57: YY_RULE_SETUP #line 118 "flex_lexer.l" TOKEN(SELECT) YY_BREAK case 58: YY_RULE_SETUP #line 119 "flex_lexer.l" TOKEN(SORTED) YY_BREAK case 59: YY_RULE_SETUP #line 120 "flex_lexer.l" TOKEN(TABLES) YY_BREAK case 60: YY_RULE_SETUP #line 121 "flex_lexer.l" TOKEN(UNIQUE) YY_BREAK case 61: YY_RULE_SETUP #line 122 "flex_lexer.l" TOKEN(UNLOAD) YY_BREAK case 62: YY_RULE_SETUP #line 123 "flex_lexer.l" TOKEN(UPDATE) YY_BREAK case 63: YY_RULE_SETUP #line 124 "flex_lexer.l" TOKEN(VALUES) YY_BREAK case 64: YY_RULE_SETUP #line 125 "flex_lexer.l" TOKEN(AFTER) YY_BREAK case 65: YY_RULE_SETUP #line 126 "flex_lexer.l" TOKEN(ALTER) YY_BREAK case 66: YY_RULE_SETUP #line 127 "flex_lexer.l" TOKEN(CROSS) YY_BREAK case 67: YY_RULE_SETUP #line 128 "flex_lexer.l" TOKEN(DELTA) YY_BREAK case 68: YY_RULE_SETUP #line 129 "flex_lexer.l" TOKEN(FLOAT) YY_BREAK case 69: YY_RULE_SETUP #line 130 "flex_lexer.l" TOKEN(GROUP) YY_BREAK case 70: YY_RULE_SETUP #line 131 "flex_lexer.l" TOKEN(INDEX) YY_BREAK case 71: YY_RULE_SETUP #line 132 "flex_lexer.l" TOKEN(INNER) YY_BREAK case 72: YY_RULE_SETUP #line 133 "flex_lexer.l" TOKEN(LIMIT) YY_BREAK case 73: YY_RULE_SETUP #line 134 "flex_lexer.l" TOKEN(LOCAL) YY_BREAK case 74: YY_RULE_SETUP #line 135 "flex_lexer.l" TOKEN(MERGE) YY_BREAK case 75: YY_RULE_SETUP #line 136 "flex_lexer.l" TOKEN(MINUS) YY_BREAK case 76: YY_RULE_SETUP #line 137 "flex_lexer.l" TOKEN(ORDER) YY_BREAK case 77: YY_RULE_SETUP #line 138 "flex_lexer.l" TOKEN(OUTER) YY_BREAK case 78: YY_RULE_SETUP #line 139 "flex_lexer.l" TOKEN(RIGHT) YY_BREAK case 79: YY_RULE_SETUP #line 140 "flex_lexer.l" TOKEN(TABLE) YY_BREAK case 80: YY_RULE_SETUP #line 141 "flex_lexer.l" TOKEN(UNION) YY_BREAK case 81: YY_RULE_SETUP #line 142 "flex_lexer.l" TOKEN(USING) YY_BREAK case 82: YY_RULE_SETUP #line 143 "flex_lexer.l" TOKEN(WHERE) YY_BREAK case 83: YY_RULE_SETUP #line 144 "flex_lexer.l" TOKEN(CALL) YY_BREAK case 84: YY_RULE_SETUP #line 145 "flex_lexer.l" TOKEN(CASE) YY_BREAK case 85: YY_RULE_SETUP #line 146 "flex_lexer.l" TOKEN(CHAR) YY_BREAK case 86: YY_RULE_SETUP #line 147 "flex_lexer.l" TOKEN(COPY) YY_BREAK case 87: YY_RULE_SETUP #line 148 "flex_lexer.l" TOKEN(DATE) YY_BREAK case 88: YY_RULE_SETUP #line 149 "flex_lexer.l" TOKEN(DATETIME) YY_BREAK case 89: YY_RULE_SETUP #line 150 "flex_lexer.l" TOKEN(DESC) YY_BREAK case 90: YY_RULE_SETUP #line 151 "flex_lexer.l" TOKEN(DROP) YY_BREAK case 91: YY_RULE_SETUP #line 152 "flex_lexer.l" TOKEN(ELSE) YY_BREAK case 92: YY_RULE_SETUP #line 153 "flex_lexer.l" TOKEN(FILE) YY_BREAK case 93: YY_RULE_SETUP #line 154 "flex_lexer.l" TOKEN(FROM) YY_BREAK case 94: YY_RULE_SETUP #line 155 "flex_lexer.l" TOKEN(FULL) YY_BREAK case 95: YY_RULE_SETUP #line 156 "flex_lexer.l" TOKEN(HASH) YY_BREAK case 96: YY_RULE_SETUP #line 157 "flex_lexer.l" TOKEN(INTO) YY_BREAK case 97: YY_RULE_SETUP #line 158 "flex_lexer.l" TOKEN(JOIN) YY_BREAK case 98: YY_RULE_SETUP #line 159 "flex_lexer.l" TOKEN(LEFT) YY_BREAK case 99: YY_RULE_SETUP #line 160 "flex_lexer.l" TOKEN(LIKE) YY_BREAK case 100: YY_RULE_SETUP #line 161 "flex_lexer.l" TOKEN(ILIKE) YY_BREAK case 101: YY_RULE_SETUP #line 162 "flex_lexer.l" TOKEN(LOAD) YY_BREAK case 102: YY_RULE_SETUP #line 163 "flex_lexer.l" TOKEN(LONG) YY_BREAK case 103: YY_RULE_SETUP #line 164 "flex_lexer.l" TOKEN(LONG) YY_BREAK case 104: YY_RULE_SETUP #line 165 "flex_lexer.l" TOKEN(NULL) YY_BREAK case 105: YY_RULE_SETUP #line 166 "flex_lexer.l" TOKEN(PLAN) YY_BREAK case 106: YY_RULE_SETUP #line 167 "flex_lexer.l" TOKEN(SHOW) YY_BREAK case 107: YY_RULE_SETUP #line 168 "flex_lexer.l" TOKEN(TEXT) YY_BREAK case 108: YY_RULE_SETUP #line 169 "flex_lexer.l" TOKEN(THEN) YY_BREAK case 109: YY_RULE_SETUP #line 170 "flex_lexer.l" TOKEN(TIME) YY_BREAK case 110: YY_RULE_SETUP #line 171 "flex_lexer.l" TOKEN(VIEW) YY_BREAK case 111: YY_RULE_SETUP #line 172 "flex_lexer.l" TOKEN(WHEN) YY_BREAK case 112: YY_RULE_SETUP #line 173 "flex_lexer.l" TOKEN(WITH) YY_BREAK case 113: YY_RULE_SETUP #line 174 "flex_lexer.l" TOKEN(ADD) YY_BREAK case 114: YY_RULE_SETUP #line 175 "flex_lexer.l" TOKEN(ALL) YY_BREAK case 115: YY_RULE_SETUP #line 176 "flex_lexer.l" TOKEN(AND) YY_BREAK case 116: YY_RULE_SETUP #line 177 "flex_lexer.l" TOKEN(ASC) YY_BREAK case 117: YY_RULE_SETUP #line 178 "flex_lexer.l" TOKEN(END) YY_BREAK case 118: YY_RULE_SETUP #line 179 "flex_lexer.l" TOKEN(FOR) YY_BREAK case 119: YY_RULE_SETUP #line 180 "flex_lexer.l" TOKEN(INT) YY_BREAK case 120: YY_RULE_SETUP #line 181 "flex_lexer.l" TOKEN(KEY) YY_BREAK case 121: YY_RULE_SETUP #line 182 "flex_lexer.l" TOKEN(NOT) YY_BREAK case 122: YY_RULE_SETUP #line 183 "flex_lexer.l" TOKEN(OFF) YY_BREAK case 123: YY_RULE_SETUP #line 184 "flex_lexer.l" TOKEN(SET) YY_BREAK case 124: YY_RULE_SETUP #line 185 "flex_lexer.l" TOKEN(TOP) YY_BREAK case 125: YY_RULE_SETUP #line 186 "flex_lexer.l" TOKEN(AS) YY_BREAK case 126: YY_RULE_SETUP #line 187 "flex_lexer.l" TOKEN(BY) YY_BREAK case 127: YY_RULE_SETUP #line 188 "flex_lexer.l" TOKEN(IF) YY_BREAK case 128: YY_RULE_SETUP #line 189 "flex_lexer.l" TOKEN(IN) YY_BREAK case 129: YY_RULE_SETUP #line 190 "flex_lexer.l" TOKEN(IS) YY_BREAK case 130: YY_RULE_SETUP #line 191 "flex_lexer.l" TOKEN(OF) YY_BREAK case 131: YY_RULE_SETUP #line 192 "flex_lexer.l" TOKEN(ON) YY_BREAK case 132: YY_RULE_SETUP #line 193 "flex_lexer.l" TOKEN(OR) YY_BREAK case 133: YY_RULE_SETUP #line 194 "flex_lexer.l" TOKEN(TO) YY_BREAK case 134: YY_RULE_SETUP #line 195 "flex_lexer.l" TOKEN(SECOND) YY_BREAK case 135: YY_RULE_SETUP #line 196 "flex_lexer.l" TOKEN(MINUTE) YY_BREAK case 136: YY_RULE_SETUP #line 197 "flex_lexer.l" TOKEN(HOUR) YY_BREAK case 137: YY_RULE_SETUP #line 198 "flex_lexer.l" TOKEN(DAY) YY_BREAK case 138: YY_RULE_SETUP #line 199 "flex_lexer.l" TOKEN(MONTH) YY_BREAK case 139: YY_RULE_SETUP #line 200 "flex_lexer.l" TOKEN(YEAR) YY_BREAK case 140: YY_RULE_SETUP #line 201 "flex_lexer.l" TOKEN(TRUE) YY_BREAK case 141: YY_RULE_SETUP #line 202 "flex_lexer.l" TOKEN(FALSE) YY_BREAK case 142: YY_RULE_SETUP #line 203 "flex_lexer.l" TOKEN(TRANSACTION) YY_BREAK case 143: YY_RULE_SETUP #line 204 "flex_lexer.l" TOKEN(BEGIN) YY_BREAK case 144: YY_RULE_SETUP #line 205 "flex_lexer.l" TOKEN(ROLLBACK) YY_BREAK case 145: YY_RULE_SETUP #line 206 "flex_lexer.l" TOKEN(COMMIT) YY_BREAK /* Allow =/== see https://sqlite.org/lang_expr.html#collateop */ case 146: YY_RULE_SETUP #line 209 "flex_lexer.l" TOKEN(EQUALS) YY_BREAK case 147: YY_RULE_SETUP #line 210 "flex_lexer.l" TOKEN(NOTEQUALS) YY_BREAK case 148: YY_RULE_SETUP #line 211 "flex_lexer.l" TOKEN(NOTEQUALS) YY_BREAK case 149: YY_RULE_SETUP #line 212 "flex_lexer.l" TOKEN(LESSEQ) YY_BREAK case 150: YY_RULE_SETUP #line 213 "flex_lexer.l" TOKEN(GREATEREQ) YY_BREAK case 151: YY_RULE_SETUP #line 214 "flex_lexer.l" TOKEN(CONCAT) YY_BREAK case 152: YY_RULE_SETUP #line 216 "flex_lexer.l" { return yytext[0]; } YY_BREAK case 153: #line 219 "flex_lexer.l" case 154: YY_RULE_SETUP #line 219 "flex_lexer.l" { yylval->sval = strdup(yytext); return SQL_FLOATVAL; } YY_BREAK case 155: YY_RULE_SETUP #line 224 "flex_lexer.l" { yylval->sval = strdup(yytext); return SQL_INTVAL; } YY_BREAK case 156: YY_RULE_SETUP #line 229 "flex_lexer.l" { // Crop the leading and trailing quote char yylval->sval = hsql::substr(yytext, 1, strlen(yytext)-1); return SQL_IDENTIFIER; } YY_BREAK case 157: YY_RULE_SETUP #line 235 "flex_lexer.l" { yylval->sval = strdup(yytext); return SQL_IDENTIFIER; } YY_BREAK case 158: YY_RULE_SETUP #line 240 "flex_lexer.l" { BEGIN singlequotedstring; strbuf = std::stringstream{}; } YY_BREAK case 159: YY_RULE_SETUP #line 241 "flex_lexer.l" { strbuf << '\''; } YY_BREAK case 160: /* rule 160 can match eol */ YY_RULE_SETUP #line 242 "flex_lexer.l" { strbuf << yytext; } YY_BREAK case 161: YY_RULE_SETUP #line 243 "flex_lexer.l" { BEGIN 0; yylval->sval = strdup(strbuf.str().c_str()); return SQL_STRING; } YY_BREAK case YY_STATE_EOF(singlequotedstring): #line 244 "flex_lexer.l" { fprintf(stderr, "[SQL-Lexer-Error] Unterminated string\n"); return 0; } YY_BREAK case 162: YY_RULE_SETUP #line 246 "flex_lexer.l" { fprintf(stderr, "[SQL-Lexer-Error] Unknown Character: %c\n", yytext[0]); return 0; } YY_BREAK case 163: YY_RULE_SETUP #line 249 "flex_lexer.l" ECHO; YY_BREAK #line 3863 "flex_lexer.cpp" case YY_STATE_EOF(INITIAL): case YY_STATE_EOF(COMMENT): yyterminate(); case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( yywrap( yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = yyg->yytext_ptr; int number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr - 1); for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { int num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { int new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ yyrealloc( (void *) b->yy_ch_buf, (yy_size_t) (b->yy_buf_size + 2) , yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = NULL; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; yyrestart( yyin , yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ int new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc( (void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, (yy_size_t) new_size , yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); /* "- 2" to take care of EOB's */ YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int) (new_size - 2); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { yy_state_type yy_current_state; char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 1144 ) yy_c = yy_meta[yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ char *yy_cp = yyg->yy_c_buf_p; YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 1144 ) yy_c = yy_meta[yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; yy_is_jam = (yy_current_state == 1143); (void)yyg; return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ int offset = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr); ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ yyrestart( yyin , yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( yywrap( yyscanner ) ) return 0; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); } yy_init_buffer( YY_CURRENT_BUFFER, input_file , yyscanner); yy_load_buffer_state( yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * yypop_buffer_state(); * yypush_buffer_state(new_buffer); */ yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; yy_load_buffer_state( yyscanner ); /* We don't actually know whether we did this switch during * EOF (yywrap()) processing, but the only time this flag * is looked at is after yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) , yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) yyalloc( (yy_size_t) (b->yy_buf_size + 2) , yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_is_our_buffer = 1; yy_init_buffer( b, file , yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with yy_create_buffer() * @param yyscanner The scanner object. */ void yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) yyfree( (void *) b->yy_ch_buf , yyscanner ); yyfree( (void *) b , yyscanner ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a yyrestart() or at EOF. */ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flush_buffer( b , yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then yy_init_buffer was _probably_ * called from yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) yy_load_buffer_state( yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; yyensure_buffer_stack(yyscanner); /* This block is copied from yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from yy_switch_to_buffer. */ yy_load_buffer_state( yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; yy_delete_buffer(YY_CURRENT_BUFFER , yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { yy_load_buffer_state( yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */ yyg->yy_buffer_stack = (struct yy_buffer_state**)yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return NULL; b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) , yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); b->yy_buf_size = (int) (size - 2); /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = NULL; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; yy_switch_to_buffer( b , yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * yy_scan_bytes() instead. */ YY_BUFFER_STATE yy_scan_string (const char * yystr , yyscan_t yyscanner) { return yy_scan_bytes( yystr, (int) strlen(yystr) , yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_bytes (const char * yybytes, int _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n; int i; /* Get memory for full buffer, including space for trailing EOB's. */ n = (yy_size_t) (_yybytes_len + 2); buf = (char *) yyalloc( n , yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = yy_scan_buffer( buf, n , yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yynoreturn yy_fatal_error (const char* msg , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ int yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param _line_number line number * @param yyscanner The scanner object. */ void yyset_lineno (int _line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "yyset_lineno called with no buffer" ); yylineno = _line_number; } /** Set the current column. * @param _column_no column number * @param yyscanner The scanner object. */ void yyset_column (int _column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "yyset_column called with no buffer" ); yycolumn = _column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * @param yyscanner The scanner object. * @see yy_switch_to_buffer */ void yyset_in (FILE * _in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = _in_str ; } void yyset_out (FILE * _out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = _out_str ; } int yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void yyset_debug (int _bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = _bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } YYLTYPE *yyget_lloc (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylloc; } void yyset_lloc (YYLTYPE * yylloc_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylloc = yylloc_param; } /* User-visible API */ /* yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* yylex_init_extra has the same functionality as yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to yyalloc in * the yyextra field. */ int yylex_init_extra( YY_EXTRA_TYPE yy_user_defined, yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = NULL; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = NULL; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = NULL; yyout = NULL; #endif /* For future reference: Set errno on error, since we are called by * yylex_init() */ return 0; } /* yylex_destroy is for both reentrant and non-reentrant scanners. */ int yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ yy_delete_buffer( YY_CURRENT_BUFFER , yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ yyfree(yyg->yy_buffer_stack , yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ yyfree( yyg->yy_start_stack , yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, const char * s2, int n , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (const char * s , yyscan_t yyscanner) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *yyalloc (yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; return malloc(size); } void *yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return realloc(ptr, size); } void yyfree (void * ptr , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 249 "flex_lexer.l" /*************************** ** Section 3: User code ***************************/ int yyerror(const char *msg) { fprintf(stderr, "[SQL-Lexer-Error] %s\n",msg); return 0; }
37.63273
109
0.541264
39fa8414a7efdd1a3993b0b3a31cad00cf0e31c9
10,880
hpp
C++
include/ripple/utility/memory.hpp
robclu/ripple
734dfa77e100a86b3c60589d41ca627e41d4a783
[ "MIT" ]
4
2021-04-25T16:38:12.000Z
2021-12-23T08:32:15.000Z
include/ripple/utility/memory.hpp
robclu/ripple
734dfa77e100a86b3c60589d41ca627e41d4a783
[ "MIT" ]
null
null
null
include/ripple/utility/memory.hpp
robclu/ripple
734dfa77e100a86b3c60589d41ca627e41d4a783
[ "MIT" ]
null
null
null
/**=--- ripple/utility/memory.hpp -------------------------- -*- C++ -*- ---==** * * Ripple * * Copyright (c) 2019 - 2021 Rob Clucas. * * This file is distributed under the MIT License. See LICENSE for details. * *==-------------------------------------------------------------------------==* * * \file memory.hpp * \brief This file defines a utility functions for memory related operations. * *==------------------------------------------------------------------------==*/ #ifndef RIPPLE_UTILITY_MEMORY_HPP #define RIPPLE_UTILITY_MEMORY_HPP #include "portability.hpp" #include <cassert> #include <cstdint> namespace ripple { /** * Gets a new ptr offset by the given amount from the ptr. * * \note This does __not__ ensure alignemt. If the pointer needs to be aligned, * then pass the result to `align()`. * * \sa align * * \param ptr The pointer to offset. * \param amount The amount to offset ptr by. * \return A new pointer at the offset location. */ ripple_all static inline auto offset_ptr(const void* ptr, uint32_t amount) noexcept -> void* { return reinterpret_cast<void*>(uintptr_t(ptr) + amount); } /** * Gets a pointer with an address aligned to the goven alignment. * * \note In debug, this will assert at runtime if the alignemnt is not a power * of two, in release, the behaviour is undefined. * * \param ptr The pointer to align. * \param alignment The alignment to ensure. */ ripple_all static inline auto align_ptr(const void* ptr, size_t alignment) noexcept -> void* { assert( !(alignment & (alignment - 1)) && "Alignment must be a power of two for linear allocation!"); return reinterpret_cast<void*>( (uintptr_t(ptr) + alignment - 1) & ~(alignment - 1)); } namespace gpu { /*==--- [device to device]--------------------------------------------------==*/ /** * Copies the given bytes of data from one device pointer to the other. * * \note This will block on the host until the copy is complete. * * \param dev_ptr_in The device pointer to copy from. * \param dev_ptr_out The device pointer to copy to. * \param bytes The number of bytes to copy. * \tparam DevPtr The type of the device pointer. */ template <typename DevPtr> static inline auto memcpy_device_to_device( DevPtr* dev_ptr_out, const DevPtr* dev_ptr_in, size_t bytes) -> void { ripple_check_cuda_result(ripple_if_cuda( cudaMemcpy(dev_ptr_out, dev_ptr_in, bytes, cudaMemcpyDeviceToDevice))); } /** * Copies given number of bytes of data from the one device pointer to the * other device ptr, asynchronously. * * \note This will not block on the host, and will likely return before the * copy is complete. * * \param dev_ptr_in The device pointer to copy from. * \param dev_ptr_out The device pointer to copy to. * \param bytes The number of bytes to copy. * \tparam DevPtr The type of the device pointer. */ template <typename DevPtr> static inline auto memcpy_device_to_device_async( DevPtr* dev_ptr_out, const DevPtr* dev_ptr_in, size_t bytes) -> void { ripple_check_cuda_result(ripple_if_cuda( cudaMemcpyAsync(dev_ptr_out, dev_ptr_in, bytes, cudaMemcpyDeviceToDevice))); } /** * Copies given number of bytes of data from the one device pointer to the * other device ptr, asynchronously on the given stream. * * \note This will not block on the host, and will likely return before the * copy is complete. * * \param dev_ptr_in The device pointer to copy from. * \param dev_ptr_out The device pointer to copy to. * \param bytes The number of bytes to copy. * \param stream The stream to perform the copy on. * \tparam DevPtr The type of the device pointer. */ template <typename DevPtr> static inline auto memcpy_device_to_device_async( DevPtr* dev_ptr_out, const DevPtr* dev_ptr_in, size_t bytes, GpuStream stream) -> void { ripple_check_cuda_result(ripple_if_cuda(cudaMemcpyAsync( dev_ptr_out, dev_ptr_in, bytes, cudaMemcpyDeviceToDevice, stream))); } /*==--- [host to device] ---------------------------------------------------==*/ /** * Copies the given number of bytes of data from the host pointer to the device * pointer. * * \note This will block on the host until the copy completes. * * \param dev_ptr The device pointer to copy to. * \param host_ptr The host pointer to copy from. * \param bytes The number of bytes to copy. * \tparam DevPtr The type of the device pointer. * \tparam HostPtr The type of the host pointer. */ template <typename DevPtr, typename HostPtr> static inline auto memcpy_host_to_device(DevPtr* dev_ptr, const HostPtr* host_ptr, size_t bytes) -> void { ripple_check_cuda_result(ripple_if_cuda( cudaMemcpy(dev_ptr, host_ptr, bytes, cudaMemcpyHostToDevice))); } /** * Copies the given number of bytes of data from the host pointer to the device * pointer, asynchronously. * * \note This will not block on the host until the copy completes. * * \param dev_ptr The device pointer to copy to. * \param host_ptr The host pointer to copy from. * \param bytes The number of bytes to copy. * \tparam DevPtr The type of the device pointer. * \tparam HostPtr The type of the host pointer. */ template <typename DevPtr, typename HostPtr> static inline auto memcpy_host_to_device_async( DevPtr* dev_ptr, const HostPtr* host_ptr, size_t bytes) -> void { ripple_check_cuda_result(ripple_if_cuda( cudaMemcpyAsync(dev_ptr, host_ptr, bytes, cudaMemcpyHostToDevice))); } /** * Copies the given number of bytes of data from the host pointer to the device * pointer, asynchronously. * * \note This will not block on the host until the copy completes. * * \note This requires that the \p host_ptr data be page locked, which should * have been allocated with alloc_pinned(). This overload alows the * stream to be specified, which will allow the copy operation to be * overlapped with operations in other streams, and possibly computation * in the same stream, if suppored. * * \param dev_ptr The device pointer to copy to. * \param host_ptr The host pointer to copy from. * \param bytes The number of bytes to copy. * \param stream The stream to perform the copy on. * \tparam DevPtr The type of the device pointer. * \tparam HostPtr The type of the host pointer. */ template <typename DevPtr, typename HostPtr> static inline auto memcpy_host_to_device_async( DevPtr* dev_ptr, const HostPtr* host_ptr, size_t bytes, GpuStream stream) -> void { ripple_check_cuda_result(ripple_if_cuda( cudaMemcpyAsync(dev_ptr, host_ptr, bytes, cudaMemcpyHostToDevice, stream))); } /*==--- [device to host] ---------------------------------------------------==*/ /** * Copies the given number of bytes of data from the device pointer to the * host pointer. * * \note This will block on the host until the copy is complete. * * \param host_ptr The host pointer to copy from. * \param dev_ptr The device pointer to copy to. * \param bytes The number of bytes to copy. * \tparam HostPtr The type of the host pointer. * \tparam DevPtr The type of the device pointer. */ template <typename HostPtr, typename DevPtr> static inline auto memcpy_device_to_host(HostPtr* host_ptr, const DevPtr* dev_ptr, size_t bytes) -> void { ripple_check_cuda_result(ripple_if_cuda( cudaMemcpy(host_ptr, dev_ptr, bytes, cudaMemcpyDeviceToHost))); } /** * Copies the given number of bytes of data from the device pointer to the * host pointer. asynchronously. * * \note This will not block on the host until the copy is complete. * * \param host_ptr The host pointer to copy from. * \param dev_ptr The device pointer to copy to. * \param bytes The number of bytes to copy. * \tparam HostPtr The type of the host pointer. * \tparam DevPtr The type of the device pointer. */ template <typename HostPtr, typename DevPtr> static inline auto memcpy_device_to_host_async( HostPtr* host_ptr, const DevPtr* dev_ptr, size_t bytes) -> void { ripple_check_cuda_result(ripple_if_cuda( cudaMemcpyAsync(host_ptr, dev_ptr, bytes, cudaMemcpyDeviceToHost))); } /** * Copies the given number of bytes of data from the device pointer to the * host pointer. asynchronously, on the given stream. * * \note This will not block on the host until the copy is complete. * * \param host_ptr The host pointer to copy from. * \param dev_ptr The device pointer to copy to. * \param bytes The number of bytes to copy. * \param stream The stream to perform the copy on. * \tparam HostPtr The type of the host pointer. * \tparam DevPtr The type of the device pointer. */ template <typename HostPtr, typename DevPtr> static inline auto memcpy_device_to_host_async( HostPtr* host_ptr, const DevPtr* dev_ptr, size_t bytes, const GpuStream& stream) -> void { ripple_check_cuda_result(ripple_if_cuda( cudaMemcpyAsync(host_ptr, dev_ptr, bytes, cudaMemcpyDeviceToHost, stream))); } /*==--- [allocation device] ------------------------------------------------==*/ /** * Allocates the given number of bytes of memory on the device at the location * pointed to by the pointer. * \param dev_ptr The device pointer to allocate memory for. * \param bytes The number of bytes to allocate. * \tparam Ptr The type of the pointer. */ template <typename Ptr> static inline auto allocate_device(Ptr** dev_ptr, size_t bytes) -> void { ripple_check_cuda_result(ripple_if_cuda(cudaMalloc((void**)dev_ptr, bytes))); } /** * Frees the pointer. * \param ptr The pointer to free. * \tparam Ptr The type of the pointer to free. */ template <typename Ptr> static inline auto free_device(Ptr* ptr) -> void { ripple_check_cuda_result(ripple_if_cuda(cudaFree(ptr))); } } // namespace gpu namespace cpu { /** * Allocates the given number of bytes of page locked (pinned) memory at the * location of the host pointer. * * \todo Add support for pinned allocation if no cuda. * * \param host_ptr The host pointer for the allocated memory. * \param bytes The number of bytes to allocate. * \tparam Ptr The type of the pointer. */ template <typename Ptr> static inline auto allocate_host_pinned(Ptr** host_ptr, size_t bytes) -> void { ripple_check_cuda_result(ripple_if_cuda( cudaHostAlloc((void**)host_ptr, bytes, cudaHostAllocPortable))); } /** * Frees the pointer which was allocated as pinned memory. * * \param ptr The pointer to free. * \tparam Ptr The type of the pointer to free. */ template <typename Ptr> static inline auto free_host_pinned(Ptr* ptr) -> void { ripple_check_cuda_result(ripple_if_cuda(cudaFreeHost(ptr))); } } // namespace cpu } // namespace ripple #endif // RIPPLE_UTILITY_MEMORY_HPP
34.983923
80
0.688879
39fcd126f2f7b60511a4fffe5052e76a511f9731
7,477
cpp
C++
trunk/win/Source/BT_ThreadableUnit.cpp
dyzmapl/BumpTop
1329ea41411c7368516b942d19add694af3d602f
[ "Apache-2.0" ]
460
2016-01-13T12:49:34.000Z
2022-02-20T04:10:40.000Z
trunk/win/Source/BT_ThreadableUnit.cpp
dyzmapl/BumpTop
1329ea41411c7368516b942d19add694af3d602f
[ "Apache-2.0" ]
24
2016-11-07T04:59:49.000Z
2022-03-14T06:34:12.000Z
trunk/win/Source/BT_ThreadableUnit.cpp
dyzmapl/BumpTop
1329ea41411c7368516b942d19add694af3d602f
[ "Apache-2.0" ]
148
2016-01-17T03:16:43.000Z
2022-03-17T12:20:36.000Z
// Copyright 2012 Google 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 "BT_Common.h" #include "BT_ThreadableUnit.h" #include "BT_Util.h" ThreadableUnit::ThreadableUnit() : _state(Queued) , _thread(NULL) , _result(false) , _repeated(false) , _repeatedDelay(0) , _threadDebugIdentifier(0) {} ThreadableUnit::~ThreadableUnit() { // force kill the thread join(512); } unsigned int __stdcall ThreadableUnit::pRunFunc(LPVOID lpParameter) { ThreadableUnit * unit = (ThreadableUnit *) lpParameter; unit->_mutex.lock(); unit->_state = Processing; bool repeated = unit->_repeated; unit->_mutex.unlock(); bool res = true; // if we are repeating, then run the runOnce func if (repeated) res = unit->_runRepeatedOnceFunc(); // if not repeating or repeating and runOnce succeeds, then runFunc() do { if (res) unit->_runFunc(); unit->_mutex.lock(); if (!repeated || !res) { // thread has completed, just return unit->_result = res; unit->_state = ThreadableUnit::Complete; CloseHandle(unit->_thread); unit->_thread = NULL; unit->_mutex.unlock(); break; } else { int delay = unit->_repeatedDelay; // run the thread again after the specified delay unit->_state = ProcessingIdle; unit->_mutex.unlock(); // sleep _after_ unlocking the mutex Sleep(delay); } } while (repeated); return 0; } void ThreadableUnit::run(boost::function<bool ()> runFunc, int threadDebugIdentifier) { _mutex.lock(); // create a new thread which calls the runFunc _state = Queued; _repeated = false; _result = false; _runFunc = runFunc; _threadDebugIdentifier = threadDebugIdentifier; _thread = (HANDLE) _beginthreadex(NULL, 0, &pRunFunc, (LPVOID) this, 0, NULL); _mutex.unlock(); } void ThreadableUnit::reRun() { _mutex.lock(); // create a new thread which calls the previous runFunc _state = Queued; _repeated = false; _result = false; _thread = (HANDLE) _beginthreadex(NULL, 0, &pRunFunc, (LPVOID) this, 0, NULL); _mutex.unlock(); } void ThreadableUnit::runRepeated( boost::function<bool ()> runRepeatedOnceFunc, boost::function<bool ()> runFunc, int delay, int threadDebugIdentifier ) { assert(delay > 0); _mutex.lock(); // create a new thread which calls the runFunc over and over again until // the thread either joins or runFunc returns false _state = Queued; _repeated = true; _repeatedDelay = delay; _result = false; _runFunc = runFunc; _runRepeatedOnceFunc = runRepeatedOnceFunc; _threadDebugIdentifier = threadDebugIdentifier; _thread = (HANDLE) _beginthreadex(NULL, 0, &pRunFunc, (LPVOID) this, 0, NULL); _mutex.unlock(); } void ThreadableUnit::join(int killAfterMillis) { // wait until it is safe to terminate int count = 0; while ((getState() == Processing) && ((count < killAfterMillis) || (killAfterMillis < 0))) { Sleep(32); count += 32; } if (getState() == ProcessingIdle || killAfterMillis > -1) { _mutex.lock(); if (_thread) { TerminateThread(_thread, 0); CloseHandle(_thread); } _thread = NULL; _state = Complete; _mutex.unlock(); } } ThreadableUnit::State ThreadableUnit::getState() { if (_mutex.tryLock()) { State s = _state; _mutex.unlock(); return s; } else return ThreadableUnit::Processing; } bool ThreadableUnit::getResult() { // XXX: Note that it is expected that this is only called when the state is complete if (getState() == ThreadableUnit::Complete) return _result; else return false; } void ThreadableUnit::markAsSafeToJoin(bool safeToTerminate) { _mutex.lock(); _state = (safeToTerminate ? ProcessingIdle : Processing); _mutex.unlock(); } void ThreadableUnit::setRepeatDelay( int delay ) { _mutex.lock(); _repeatedDelay = delay; _mutex.unlock(); } // ------------------------------------------------------------------------------------------------ ThreadableTextureUnit::ThreadableTextureUnit(const GLTextureObject& param, int maxRuntime) : _state(Queued) , _thread(NULL) , _result(false) , _param(param) { _runtimeTimer.setTimerDuration(maxRuntime); _runtimeTimer.setTimerEventHandler(boost::bind(&ThreadableTextureUnit::joinNow, this)); } ThreadableTextureUnit::ThreadableTextureUnit(const GLTextureObject& param) : _state(Queued) , _thread(NULL) , _result(false) , _param(param) {} ThreadableTextureUnit::~ThreadableTextureUnit() { // force kill the thread join(512); } unsigned int __stdcall ThreadableTextureUnit::pRunFunc(LPVOID lpParameter) { ThreadableTextureUnit * unit = (ThreadableTextureUnit *) lpParameter; unit->_mutex.lock(); unit->_state = Processing; unit->_mutex.unlock(); int res = unit->_runFunc(unit->_param); unit->_mutex.lock(); // thread has completed, just return unit->_result = res; unit->_state = ThreadableTextureUnit::Complete; CloseHandle(unit->_thread); unit->_thread = NULL; unit->_mutex.unlock(); return 0; } void ThreadableTextureUnit::run(boost::function<int (GLTextureObject)> runFunc, int threadDebugIdentifier) { _mutex.lock(); // create a new thread which calls the runFunc _result = -1; _runFunc = runFunc; _threadDebugIdentifier = threadDebugIdentifier; if (_runtimeTimer.getDuration() > 0) _runtimeTimer.start(); _thread = (HANDLE) _beginthreadex(NULL, 0, &pRunFunc, (LPVOID) this, 0, NULL); _mutex.unlock(); } void ThreadableTextureUnit::join(int killAfterMillis) { // wait until it is safe to terminate int count = 0; while (getState() == Processing && count < killAfterMillis) { Sleep(32); count += 32; } if (getState() == ProcessingIdle || killAfterMillis > -1) { _mutex.lock(); if (_thread) { TerminateThread(_thread, 0); CloseHandle(_thread); } _thread = NULL; _state = Complete; _mutex.unlock(); } } ThreadableTextureUnit::State ThreadableTextureUnit::getState() const { if (_mutex.tryLock()) { State s = _state; _mutex.unlock(); return s; } else return ThreadableTextureUnit::Processing; } int ThreadableTextureUnit::getResult() const { // XXX: Note that it is expected that this is only called when the state is complete if (getState() == ThreadableTextureUnit::Complete) return _result; else return -1; } void ThreadableTextureUnit::markAsSafeToJoin(bool safeToTerminate) { _mutex.lock(); _state = (safeToTerminate ? ProcessingIdle : Processing); _mutex.unlock(); } GLTextureObject ThreadableTextureUnit::getParam() { // NOTE: since this is a read-only variable, we don't have to synchronize access to it return _param; } void ThreadableTextureUnit::joinNow() { join(0); _mutex.lock(); _state = Expired; _mutex.unlock(); }
24.923333
153
0.671927
2603f24fa10bb207b89b226b36885e6a30549682
5,911
hpp
C++
include/graphics.hpp
a276me/MilSim
b3ba8ef8cc46b6ae9cc7befece6cd00b016038ea
[ "MIT" ]
null
null
null
include/graphics.hpp
a276me/MilSim
b3ba8ef8cc46b6ae9cc7befece6cd00b016038ea
[ "MIT" ]
null
null
null
include/graphics.hpp
a276me/MilSim
b3ba8ef8cc46b6ae9cc7befece6cd00b016038ea
[ "MIT" ]
null
null
null
#pragma once #include "raylib.h" #include "main.hpp" #include "Division.hpp" const int SCREEN_WIDTH = 1280*1.5; const int SCREEN_HEIGHT = 960*1.2; Texture2D natoTest; Texture2D natoInf; Texture2D natoArmor; Texture2D natoMechInf; Texture2D hostileInf; Texture2D hostileArmor; Texture2D hostileMechInf; void initRL(); void endRL(); void drawUI(); void drawDivision(); void drawCamera(); void drawScreen(); void loadResources(); void updateVariables(); Camera2D camera = { 0 }; void updateVariables(){ int t = 1; if(IsKeyDown(KEY_LEFT_SHIFT)) t = 3; int s = 10; if (IsKeyDown(KEY_A)) camera.target.x -= t*s; else if (IsKeyDown(KEY_D)) camera.target.x += t*s; if (IsKeyDown(KEY_W)) camera.target.y -= t*s; else if (IsKeyDown(KEY_S)) camera.target.y += t*s; // Camera zoom controls camera.zoom += ((float)GetMouseWheelMove()*t*0.02f); if (camera.zoom > 3.f) camera.zoom = 3.f; else if (camera.zoom < .01f) camera.zoom = .01f; // Camera reset (zoom and rotation) if (IsKeyPressed(KEY_R)) { camera.zoom = 1.0f; camera.rotation = 0.0f; camera.target = (Vector2){0,0}; } } void loadResources(){ natoTest = LoadTexture("nato.png"); natoInf = LoadTexture("./assets/NATO/friendly_infantry.png"); natoMechInf = LoadTexture("./assets/NATO/friendly_mech_infantry.png"); natoArmor = LoadTexture("./assets/NATO/friendly_armor.png"); hostileInf = LoadTexture("./assets/HOSTILE/hostile_inf.png"); hostileMechInf = LoadTexture("./assets/HOSTILE/hostile_mech_inf.png"); hostileArmor = LoadTexture("./assets/HOSTILE/hostile_armor.png"); } void initRL(){ InitWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [core] example - basic window"); SetTargetFPS(60); // Set our game to run at 60 frames-per-second loadResources(); camera.target = (Vector2){ 0,0 }; camera.offset = (Vector2){ SCREEN_WIDTH/2.0f, SCREEN_HEIGHT/2.0f }; camera.rotation = 0.0f; camera.zoom = 1.0f; MaximizeWindow(); } void endRL(){ UnloadTexture(natoTest); UnloadTexture(natoInf); UnloadTexture(natoArmor); UnloadTexture(natoMechInf); UnloadTexture(hostileInf); UnloadTexture(hostileArmor); UnloadTexture(hostileMechInf); CloseWindow(); } void drawUI(){ ClearBackground((Color){ 245, 245, 245, 255 }); DrawFPS(10,10); } void drawDivision(){ float s = 0.7f; float ss = 100.f; for(int i=0; i<divisions.size(); i++){ DrawCircleV((Vector2){divisions[i].position.x*ss, -divisions[i].position.y*ss}, ss*divisions[i].getBD()/2.f, (Color){ 100, 100, 100, 100 }); if(divisions[i].moving) DrawLineEx((Vector2){divisions[i].position.x*ss,-divisions[i].position.y*ss}, (Vector2){divisions[i].getTarget().x*ss, -divisions[i].getTarget().y*ss}, 20, (Color){0,0,0,255}); } for(int i=0; i<divisions.size(); i++){ if(divisions[i].team == 0){ if(divisions[i].getType() == INFANTRY_DIV){ DrawTextureEx(natoInf, (Vector2){ss*divisions[i].getPos().x-(natoInf.width/2)*s,ss*-divisions[i].getPos().y-(natoInf.height/2)*s}, 0, s,(Color){ 255, 255, 255, 255 }); } else if(divisions[i].getType() == ARMORED_DIV){ DrawTextureEx(natoArmor, (Vector2){ss*divisions[i].getPos().x-(natoArmor.width/2)*s,ss*-divisions[i].getPos().y-(natoArmor.height/2)*s}, 0, s,(Color){ 255, 255, 255, 255 }); } else if(divisions[i].getType() == MECH_INFANTRY_DIV){ DrawTextureEx(natoMechInf, (Vector2){ss*divisions[i].getPos().x-(natoMechInf.width/2)*s,ss*-divisions[i].getPos().y-(natoMechInf.height/2)*s}, 0, s,(Color){ 255, 255, 255, 255 }); } }else if(divisions[i].team == 1){ if(divisions[i].getType() == INFANTRY_DIV){ DrawTextureEx(hostileInf, (Vector2){ss*divisions[i].getPos().x-(hostileInf.width/2)*s,ss*-divisions[i].getPos().y-(hostileInf.height/2)*s}, 0, s,(Color){ 255, 255, 255, 255 }); } else if(divisions[i].getType() == ARMORED_DIV){ DrawTextureEx(hostileArmor, (Vector2){ss*divisions[i].getPos().x-(hostileArmor.width/2)*s,ss*-divisions[i].getPos().y-(hostileArmor.height/2)*s}, 0, s,(Color){ 255, 255, 255, 255 }); } else if(divisions[i].getType() == MECH_INFANTRY_DIV){ DrawTextureEx(hostileMechInf, (Vector2){ss*divisions[i].getPos().x-(hostileMechInf.width/2)*s,ss*-divisions[i].getPos().y-(hostileMechInf.height/2)*s}, 0, s,(Color){ 255, 255, 255, 255 }); } } DrawText(divisions[i].getName().c_str(),ss*divisions[i].getPos().x-(MeasureText(divisions[i].getName().c_str(), 200)/2), ss*-divisions[i].getPos().y-(hostileInf.height/2)*s-220,200,(Color){ 0, 0, 0, 255 }); DrawText(std::to_string((int)divisions[i].getOrg()).c_str(),ss*divisions[i].getPos().x+(natoInf.width/2)*s+20, ss*-divisions[i].getPos().y-210,200,(Color){ 0, 0, 0, 255 }); DrawText(std::to_string((int)divisions[i].getStrength()).c_str(),ss*divisions[i].getPos().x+(natoInf.width/2)*s+20, ss*-divisions[i].getPos().y,200,(Color){ 0, 0, 0, 255 }); DrawText(std::to_string((int)divisions[i].getBV()).c_str(),ss*divisions[i].getPos().x-(natoInf.width/2)*s-MeasureText(std::to_string((int)divisions[i].getBV()).c_str(),200)-30, ss*-divisions[i].getPos().y-200,200,(Color){ 0, 0, 0, 255 }); DrawText(std::to_string((int)divisions[i].getDV()).c_str(),ss*divisions[i].getPos().x-(natoInf.width/2)*s-MeasureText(std::to_string((int)divisions[i].getDV()).c_str(),200)-30, ss*-divisions[i].getPos().y+20,200,(Color){ 0, 0, 0, 255 }); } } void drawCamera(){ updateVariables(); BeginMode2D(camera); drawDivision(); EndMode2D(); } void drawScreen(){ BeginDrawing(); drawUI(); drawCamera(); EndDrawing(); }
34.366279
246
0.630012
26060c9cd453f6eb01ded7d869aafb8e9c4fb67d
997
hpp
C++
RayTracer/core/source/RTweekend.hpp
ZFhuang/AmbiRenderer
d223e1c4d947872c9011c1cba6a8f498ebbaf3b7
[ "Apache-2.0" ]
null
null
null
RayTracer/core/source/RTweekend.hpp
ZFhuang/AmbiRenderer
d223e1c4d947872c9011c1cba6a8f498ebbaf3b7
[ "Apache-2.0" ]
null
null
null
RayTracer/core/source/RTweekend.hpp
ZFhuang/AmbiRenderer
d223e1c4d947872c9011c1cba6a8f498ebbaf3b7
[ "Apache-2.0" ]
null
null
null
#pragma once #include <cmath> #include <limits> #include <memory> #include <random> // 保存Ray Tracing in One Weekend项目所需的基本常量和函数 using std::shared_ptr; using std::make_shared; using std::sqrt; const double infinity = std::numeric_limits<double>::infinity(); const double pi = 3.1415926535897932385; // 角度转弧度 inline double degrees_to_radians(double degrees) { return degrees * pi / 180.0; } // 生成范围内的double均匀分布随机数 inline double random_double(double min = 0.0, double max = 1.0) { // 生成种子 static std::random_device rd; // 调用生成器 static std::mt19937 generator(rd()); // 注意这个该死的生成器只能生成非负数 static std::uniform_real_distribution<double> distribution(0.0, 1.0); // 移动分布范围 return min + (max - min) * distribution(generator); } inline int random_int(int min = 0, int max = 1) { return static_cast<int>(random_double(min, max + 1)); } // 按照min和max对值进行截断 inline double clamp(double x, double min, double max) { if (x < min) { return min; } if (x > max) { return max; } return x; }
20.346939
70
0.706118
2609c25feca6969e8f9c31b3be4f6301848dc8dc
3,645
cpp
C++
2017-09-10-practice/E.cpp
tangjz/Three-Investigators
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
[ "MIT" ]
3
2018-04-02T06:00:51.000Z
2018-05-29T04:46:29.000Z
2017-09-10-practice/E.cpp
tangjz/Three-Investigators
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
[ "MIT" ]
2
2018-03-31T17:54:30.000Z
2018-05-02T11:31:06.000Z
2017-09-10-practice/E.cpp
tangjz/Three-Investigators
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
[ "MIT" ]
2
2018-10-07T00:08:06.000Z
2021-06-28T11:02:59.000Z
#include <bits/stdc++.h> using namespace std; typedef long long LL; typedef long double DB; const int maxn = 500001, INF = 0x3f3f3f3f; int rad, n, totL, totR; struct Query { int typ, x, y; } que[maxn]; struct Fraction { LL x, y; Fraction() {} Fraction(LL _x, LL _y) { // _y > 0 LL r = __gcd(abs(_x), _y); x = _x / r; y = _y / r; } bool operator == (Fraction const &t) const { return x == t.x && y == t.y; } bool operator < (Fraction const &t) const { return (DB)x * t.y < (DB)t.x * y; } } pL[maxn], pR[maxn], seqL[maxn], seqR[maxn]; int cnt, idx[maxn], ord[maxn], pos[maxn], seg[maxn << 1 | 1]; inline int seg_idx(int L, int R) { return (L + R) | (L < R); } void seg_upd(int L, int R, int x, int v) { int rt = seg_idx(L, R); if(L == R) { seg[rt] = v; return; } int M = (L + R) >> 1, lch = seg_idx(L, M), rch = seg_idx(M + 1, R); if(x <= M) seg_upd(L, M, x, v); else seg_upd(M + 1, R, x, v); seg[rt] = min(seg[lch], seg[rch]); } int seg_que(int L, int R, int l, int r) { if(l <= L && R <= r) return seg[seg_idx(L, R)]; int M = (L + R) >> 1, ret = INF; if(l <= M) ret = min(ret, seg_que(L, M, l, r)); if(M < r) ret = min(ret, seg_que(M + 1, R, l, r)); return ret; } inline int sgn(int x) { return (x > 0) - (x < 0); } inline LL sqr(int x) { return (LL)x * x; } bool cmp(int const &u, int const &v) { return que[u].x < que[v].x; } int main() { scanf("%d%d", &rad, &n); for(int i = 1; i <= n; ++i) { int &typ = que[i].typ, &x = que[i].x, &y = que[i].y; scanf("%d%d", &typ, &x); if(typ != 2) scanf("%d", &y); if(typ != 1) continue; LL A = sqr(rad + x), B = sqr(rad - x), C = sqr(y); seqL[++totL] = pL[i] = Fraction(sgn(rad + x) * A, A + C); seqR[++totR] = pR[i] = Fraction(sgn(rad - x) * B, B + C); } sort(seqL + 1, seqL + totL + 1); totL = unique(seqL + 1, seqL + totL + 1) - seqL - 1; sort(seqR + 1, seqR + totR + 1); totR = unique(seqR + 1, seqR + totR + 1) - seqR - 1; for(int i = 1; i <= n; ++i) { int &typ = que[i].typ, &x = que[i].x, &y = que[i].y; if(typ == 1) { int px = x, py = y; x = lower_bound(seqL + 1, seqL + totL + 1, pL[i]) - seqL; y = lower_bound(seqR + 1, seqR + totR + 1, pR[i]) - seqR; pL[i] = px >= -rad ? Fraction(sqr(px + rad) - sqr(py), sqr(px + rad) + sqr(py)) : Fraction(-1, 1); pR[i] = px <= rad ? Fraction(sqr(py) - sqr(px - rad), sqr(px - rad) + sqr(py)) : Fraction(1, 1); ord[++cnt] = i; idx[cnt] = i; } } sort(ord + 1, ord + cnt + 1, cmp); for(int i = 1; i <= cnt; ++i) pos[ord[i]] = i; static bool vis[maxn] = {}; memset(seg + 1, 0x3f, (cnt << 1) * sizeof(int)); for(int i = 1; i <= n; ++i) { int &typ = que[i].typ, &x = que[i].x, &y = que[i].y; if(typ == 1) { vis[i] = 1; // printf("ins %d: %d %d\n", pos[i], que[i].x, que[i].y); seg_upd(1, cnt, pos[i], que[i].y); } else if(typ == 2) { x = idx[x]; assert(vis[x] == 1); // printf("rem %d: %d %d\n", pos[x], que[x].x, que[x].y); seg_upd(1, cnt, pos[x], INF); vis[x] = 0; } else { x = idx[x], y = idx[y]; assert(vis[x] == 1 && vis[y] == 1); // printf("ask (%d, %d) (%d, %d)\n", que[x].x, que[x].y, que[y].x, que[y].y); if(min(pR[x], pR[y]) < max(pL[x], pL[y])) { puts("NO"); continue; } int A = max(que[x].x, que[y].x), B = max(que[x].y, que[y].y); seg_upd(1, cnt, pos[x], INF); seg_upd(1, cnt, pos[y], INF); que[0] = (Query){0, A}; int id = upper_bound(ord + 1, ord + cnt + 1, 0, cmp) - ord - 1; // printf("query [%d, %d]\n", 1, id); puts(seg_que(1, cnt, 1, id) > B ? "YES" : "NO"); seg_upd(1, cnt, pos[x], que[x].y); seg_upd(1, cnt, pos[y], que[y].y); } } return 0; }
28.476563
101
0.494925
260e864a1f93c48554bc7ee15e6a536d28c1bc43
5,340
hpp
C++
include/GTGE/Editor/ParticleEditor/ParticleEditor.hpp
mackron/GTGameEngine
380d1e01774fe6bc2940979e4e5983deef0bf082
[ "BSD-3-Clause" ]
31
2015-03-19T08:44:48.000Z
2021-12-15T20:52:31.000Z
include/GTGE/Editor/ParticleEditor/ParticleEditor.hpp
mackron/GTGameEngine
380d1e01774fe6bc2940979e4e5983deef0bf082
[ "BSD-3-Clause" ]
19
2015-07-09T09:02:44.000Z
2016-06-09T03:51:03.000Z
include/GTGE/Editor/ParticleEditor/ParticleEditor.hpp
mackron/GTGameEngine
380d1e01774fe6bc2940979e4e5983deef0bf082
[ "BSD-3-Clause" ]
3
2017-10-04T23:38:18.000Z
2022-03-07T08:27:13.000Z
// Copyright (C) 2011 - 2014 David Reid. See included LICENCE. #ifndef GT_ParticleEditor #define GT_ParticleEditor #include "../SubEditor.hpp" #include "../Editor3DViewportEventHandler.hpp" #include "../EditorGrid.hpp" #include "../EditorAxisArrows.hpp" #include "../../ParticleSystem.hpp" #include "../../Scene.hpp" namespace GT { /// Class representing the particle system editor. class ParticleEditor : public SubEditor { public: /// Constructor. ParticleEditor(Editor &ownerEditor, const char* absolutePath, const char* relativePath); /// Destructor. ~ParticleEditor(); /// Resets the camera. void ResetCamera(); /// Retrieves a reference tothe camera scene node. SceneNode & GetCameraSceneNode() { return this->camera; } const SceneNode & GetCameraSceneNode() const { return this->camera; } /// Retrieves a reference to the particle system definition being editted. ParticleSystemDefinition & GetParticleSystemDefinition(); /// Refreshes the viewport so that it shows the current state of the particle system being editted. /// /// @remarks /// This should be called whenever the particle definition has been modified. void RefreshViewport(); /// Sets the orientation of the preview particle system. void SetOrientation(const glm::quat &orientation); /// Shows the grid. void ShowGrid(); /// Hides the grid. void HideGrid(); /// Determines whether or not the grid is showing. bool IsShowingGrid() const; /// Shows the axis arrows. void ShowAxisArrows(); /// Hides the axis arrows. void HideAxisArrows(); /// Determines whether or not the axis arrows is showing. bool IsShowingAxisArrows() const; /////////////////////////////////////////////////// // GUI Events. // // These events are received in response to certain GUI events. /// Called when the main viewport is resized. void OnViewportSize(); /////////////////////////////////////////////////// // Virtual Methods. /// SubEditor::GetMainElement() GUIElement* GetMainElement() { return this->mainElement; } const GUIElement* GetMainElement() const { return this->mainElement; } /// SubEditor::Show() void Show(); /// SubEditor::Hide() void Hide(); /// SubEditor::Save() bool Save(); /// SubEditor::Update() void OnUpdate(double deltaTimeInSeconds); /// SubEditor::OnFileUpdate() void OnFileUpdate(const char* absolutePath); private: private: /// The particle system definition that is being editted. This is not instantiated by the particle system library. ParticleSystemDefinition particleSystemDefinition; /// The particle system to use in the preview window. ParticleSystem particleSystem; /// The scene for the preview window. Scene scene; /// The scene node acting as the camera for the preview window viewport. SceneNode camera; /// The scene node containing the particle system. SceneNode particleNode; /// The main container element. GUIElement* mainElement; /// The viewport element. GUIElement* viewportElement; /// The viewport event handler to we can detect when it is resized. struct ViewportEventHandler : public Editor3DViewportEventHandler { /// Constructor. ViewportEventHandler(ParticleEditor &ownerIn, Context &context, SceneViewport &viewport) : Editor3DViewportEventHandler(context, viewport), owner(ownerIn) { } /// Called after the element has been resized. void OnSize(GUIElement &element) { Editor3DViewportEventHandler::OnSize(element); owner.OnViewportSize(); } /// The owner of the viewport. ParticleEditor &owner; }viewportEventHandler; float cameraXRotation; ///< The camera's current X rotation. float cameraYRotation; ///< The camera's current Y rotation. /// The grid. EditorGrid grid; /// The axis arrows. EditorAxisArrows axisArrows; /// Keeps track of whether or not the editor is in the middle of saving. We use this in determining whether or not the settings should be /// set when it detects a modification to the file on disk. bool isSaving; /// Keeps track of whether or not we are handling a reload. We use this in keeping track of whether or not to mark the file as modified /// when the settings are changed. bool isReloading; /// Keeps track of whether or not the grid is visible. bool isShowingGrid; /// Keeps track of whether or not the axis arrows are visible. bool isShowingAxisArrows; private: // No copying. ParticleEditor(const ParticleEditor &); ParticleEditor & operator=(const ParticleEditor &); }; } #endif
27.525773
145
0.603933
260fbcac89d9c171b877e48c878a90c4994a737c
1,586
hpp
C++
legacy/galaxy/meta/UniqueId.hpp
reworks/rework
90508252c9a4c77e45a38e7ce63cfd99f533f42b
[ "Apache-2.0" ]
6
2018-07-21T20:37:01.000Z
2018-10-31T01:49:35.000Z
legacy/galaxy/meta/UniqueId.hpp
reworks/rework
90508252c9a4c77e45a38e7ce63cfd99f533f42b
[ "Apache-2.0" ]
null
null
null
legacy/galaxy/meta/UniqueId.hpp
reworks/rework
90508252c9a4c77e45a38e7ce63cfd99f533f42b
[ "Apache-2.0" ]
null
null
null
/// /// UniqueId.hpp /// galaxy /// /// Refer to LICENSE.txt for more details. /// #ifndef GALAXY_META_UNIQUEID_HPP_ #define GALAXY_META_UNIQUEID_HPP_ #include "galaxy/meta/Concepts.hpp" namespace galaxy { namespace meta { /// /// Generates a unique id for a type for each type of specialization. /// And the id is kept as a compile time constant. /// template<is_class Specialization> class UniqueId final { public: /// /// Destructor. /// ~UniqueId() noexcept = default; /// /// Use this function to retrieve the ID. /// Will generate a new id if it is called for the first time. /// /// \return Unique ID for the specialization of that type. /// template<typename Type> [[nodiscard]] static std::size_t get() noexcept; private: /// /// Constructor. /// UniqueId() noexcept = default; /// /// Copy constructor. /// UniqueId(const UniqueId&) = delete; /// /// Move constructor. /// UniqueId(UniqueId&&) = delete; /// /// Copy assignment operator. /// UniqueId& operator=(const UniqueId&) = delete; /// /// Move assignment operator. /// UniqueId& operator=(UniqueId&&) = delete; private: /// /// Internal counter to keep track of allocated ids. /// inline static std::size_t s_counter = 0; }; template<is_class Specialization> template<typename Type> [[nodiscard]] inline std::size_t UniqueId<Specialization>::get() noexcept { static std::size_t id = s_counter++; return id; } } // namespace meta } // namespace galaxy #endif
19.341463
75
0.628625
2613106580d834e6f6c23229ec8e14b28bab861e
1,837
cpp
C++
cpp/Maya Calendar/Maya Calendar.cpp
xuzishan/Algorithm-learning-through-Problems
4aee347af6fd7fd935838e1cbea57c197e88705c
[ "MIT" ]
27
2016-11-04T09:18:25.000Z
2022-02-12T12:34:01.000Z
cpp/Maya Calendar/Maya Calendar.cpp
Der1128/Algorithm-learning-through-Problems
4aee347af6fd7fd935838e1cbea57c197e88705c
[ "MIT" ]
1
2016-11-05T02:30:24.000Z
2016-11-16T10:21:09.000Z
cpp/Maya Calendar/Maya Calendar.cpp
Der1128/Algorithm-learning-through-Problems
4aee347af6fd7fd935838e1cbea57c197e88705c
[ "MIT" ]
20
2016-11-04T10:26:02.000Z
2021-09-25T05:41:21.000Z
// // Maya Calendar.cpp // laboratory // // Created by 徐子珊 on 16/4/4. // Copyright (c) 2016年 xu_zishan. All rights reserved. // #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <string> #include <hash_map> using namespace std; pair<string, int> a[]={make_pair("pop", 0), make_pair("no", 1), make_pair("zip", 2), make_pair("zotz", 3), make_pair("tzec", 4), make_pair("xul", 5), make_pair("yoxkin", 6), make_pair("mol", 7), make_pair("chen", 8), make_pair("yax", 9), make_pair("zac", 10), make_pair("ceh", 11), make_pair("mac", 12), make_pair("kankin", 13), make_pair("muan", 14), make_pair("pax", 15), make_pair("koyab", 16), make_pair("cumhu", 17), make_pair("uayet", 18)}; hash_map<string, int> Haab(a, a+19); string Tzolkin[]={"imix", "ik", "akbal", "kan", "chicchan", "cimi", "manik", "lamat", "muluk", "ok", "chuen", "eb", "ben", "ix", "mem", "cib", "caban", "eznab", "canac", "ahau"}; string mayaCalendar(string &haab){ istringstream s(haab); int NumberOfTheDay, Year; string Month; char dot; s>>NumberOfTheDay>>dot>>Month>>Year; int days=365*Year+20*Haab[Month]+NumberOfTheDay; Year=days/260; int r=days%260; int Number=(r%13)+1; string NameOfTheDay=Tzolkin[r%20]; ostringstream os; os<<Number<<" "<<NameOfTheDay<<" "<<Year; return os.str(); } int main(){ ifstream inputdata("Maya Calendar/inputdata.txt"); ofstream outputdata("Maya Calendar/outputdata.txt"); int n; inputdata>>n; outputdata<<n<<endl; cout<<n<<endl; string haab; getline(inputdata, haab); for(int i=0; i<n; i++){ getline(inputdata, haab); string tzolkin=mayaCalendar(haab); outputdata<<tzolkin<<endl; cout<<tzolkin<<endl; } inputdata.close(); outputdata.close(); return 0; }
32.22807
107
0.62221
2613699c22b337a40d0a7955cf85646d1082af29
549
cc
C++
test/lattice/parameter.cc
Alexhuszagh/funxx
9f6c1fae92d96a84282fc62be272f4dc1e1dba9b
[ "MIT", "BSD-3-Clause" ]
1
2017-07-21T22:58:38.000Z
2017-07-21T22:58:38.000Z
test/lattice/parameter.cc
Alexhuszagh/funxx
9f6c1fae92d96a84282fc62be272f4dc1e1dba9b
[ "MIT", "BSD-3-Clause" ]
null
null
null
test/lattice/parameter.cc
Alexhuszagh/funxx
9f6c1fae92d96a84282fc62be272f4dc1e1dba9b
[ "MIT", "BSD-3-Clause" ]
null
null
null
// :copyright: (c) 2017 Alex Huszagh. // :license: MIT, see LICENSE.md for more details. #include <pycpp/lattice/parameter.h> #include <gtest/gtest.h> PYCPP_USING_NAMESPACE // TESTS // ----- TEST(parameters_t, get) { parameters_t parameters = { {"name", "value"}, }; EXPECT_EQ(parameters.get(), "?name=value"); } TEST(parameters_t, add) { parameters_t parameters = { {"name", "value"}, }; parameters.add(parameter_t("name2", "value2")); EXPECT_EQ(parameters.get(), "?name=value&name2=value2"); }
18.3
60
0.622951
26138d64ec152d2b5f041c77ae3b068cfb7a950c
1,254
cpp
C++
LeetCode/187. Repeated DNA Sequences.cpp
Joon7891/Competitive-Programming
d860b7ad932cd5a6fb91fdc8c53101da57f4a408
[ "MIT" ]
2
2021-04-13T00:19:56.000Z
2021-04-13T01:19:45.000Z
LeetCode/187. Repeated DNA Sequences.cpp
Joon7891/Competitive-Programming
d860b7ad932cd5a6fb91fdc8c53101da57f4a408
[ "MIT" ]
null
null
null
LeetCode/187. Repeated DNA Sequences.cpp
Joon7891/Competitive-Programming
d860b7ad932cd5a6fb91fdc8c53101da57f4a408
[ "MIT" ]
1
2020-08-26T12:36:08.000Z
2020-08-26T12:36:08.000Z
class Solution { public: vector<string> findRepeatedDnaSequences(string s) { map<char, int> charToBit; charToBit['A'] = 0b00; charToBit['C'] = 0b01; charToBit['G'] = 0b10; charToBit['T'] = 0b11; map<int, char> bitToChar; bitToChar[0b00] = 'A'; bitToChar[0b01] = 'C'; bitToChar[0b10] = 'G'; bitToChar[0b11] = 'T'; int cur = 0; vector<int> seen; map<int, int> freq; for (int i = 0; i < s.length(); i++){ cur = ((cur << 2) | charToBit[s[i]]); if (i >= 9){ cur &= 0b11111111111111111111; if (freq[cur] == 0) seen.push_back(cur); freq[cur]++; } } vector<string> ans; for (int x : seen){ if (freq[x] >= 2){ string dna = ""; for (int i = 0; i < 10; i++){ int bit = (x >> (2 * i)) & 0b11; dna = bitToChar[bit] + dna; } ans.push_back(dna); } } return ans; } };
27.866667
56
0.360447
261cdd21729796c74dc94d854f918e1929207d29
3,081
cpp
C++
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qttools/src/assistant/qhelpconverter/pathpage.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qttools/src/assistant/qhelpconverter/pathpage.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qttools/src/assistant/qhelpconverter/pathpage.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the Qt Assistant of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:GPL-EXCEPT$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtWidgets/QFileDialog> #include "pathpage.h" QT_BEGIN_NAMESPACE PathPage::PathPage(QWidget *parent) : QWizardPage(parent) { setTitle(tr("Source File Paths")); setSubTitle(tr("Specify the paths where the sources files " "are located. By default, all files in those directories " "matched by the file filter will be included.")); m_ui.setupUi(this); connect(m_ui.addButton, &QAbstractButton::clicked, this, &PathPage::addPath); connect(m_ui.removeButton, &QAbstractButton::clicked, this, &PathPage::removePath); m_ui.filterLineEdit->setText(QLatin1String("*.html, *.htm, *.png, *.jpg, *.css")); registerField(QLatin1String("sourcePathList"), m_ui.pathListWidget); m_firstTime = true; } void PathPage::setPath(const QString &path) { if (!m_firstTime) return; m_ui.pathListWidget->addItem(path); m_firstTime = false; m_ui.pathListWidget->setCurrentRow(0); } QStringList PathPage::paths() const { QStringList lst; for (int i = 0; i < m_ui.pathListWidget->count(); ++i) lst.append(m_ui.pathListWidget->item(i)->text()); return lst; } QStringList PathPage::filters() const { QStringList lst; for (const QString &s : m_ui.filterLineEdit->text().split(QLatin1Char(','))) { lst.append(s.trimmed()); } return lst; } void PathPage::addPath() { QString dir = QFileDialog::getExistingDirectory(this, tr("Source File Path")); if (!dir.isEmpty()) m_ui.pathListWidget->addItem(dir); } void PathPage::removePath() { QListWidgetItem *i = m_ui.pathListWidget ->takeItem(m_ui.pathListWidget->currentRow()); delete i; if (!m_ui.pathListWidget->count()) m_ui.removeButton->setEnabled(false); } QT_END_NAMESPACE
30.81
86
0.66407
261f35817fc8033d8bbf94f018bb61bac851283a
37,455
cpp
C++
src/libraries/dynamicMesh/dynamicMesh/meshCut/meshModifiers/meshCutAndRemove/meshCutAndRemove.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/dynamicMesh/dynamicMesh/meshCut/meshModifiers/meshCutAndRemove/meshCutAndRemove.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/dynamicMesh/dynamicMesh/meshCut/meshModifiers/meshCutAndRemove/meshCutAndRemove.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011-2012 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "meshCutAndRemove.hpp" #include "polyMesh.hpp" #include "polyTopoChange.hpp" #include "polyAddFace.hpp" #include "polyAddPoint.hpp" #include "polyRemovePoint.hpp" #include "polyRemoveFace.hpp" #include "polyModifyFace.hpp" #include "cellCuts.hpp" #include "mapPolyMesh.hpp" #include "meshTools.hpp" // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // namespace CML { defineTypeNameAndDebug(meshCutAndRemove, 0); } // * * * * * * * * * * * * * Private Static Functions * * * * * * * * * * * // // Returns -1 or index in elems1 of first shared element. CML::label CML::meshCutAndRemove::firstCommon ( const labelList& elems1, const labelList& elems2 ) { forAll(elems1, elemI) { label index1 = findIndex(elems2, elems1[elemI]); if (index1 != -1) { return index1; } } return -1; } // Check if twoCuts at two consecutive position in cuts. bool CML::meshCutAndRemove::isIn ( const edge& twoCuts, const labelList& cuts ) { label index = findIndex(cuts, twoCuts[0]); if (index == -1) { return false; } return ( cuts[cuts.fcIndex(index)] == twoCuts[1] || cuts[cuts.rcIndex(index)] == twoCuts[1] ); } // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // // Returns the cell in cellLabels that is cut. Or -1. CML::label CML::meshCutAndRemove::findCutCell ( const cellCuts& cuts, const labelList& cellLabels ) const { forAll(cellLabels, labelI) { label cellI = cellLabels[labelI]; if (cuts.cellLoops()[cellI].size()) { return cellI; } } return -1; } //- Returns first pointI in pointLabels that uses an internal // face. Used to find point to inflate cell/face from (has to be // connected to internal face). Returns -1 (so inflate from nothing) if // none found. CML::label CML::meshCutAndRemove::findInternalFacePoint ( const labelList& pointLabels ) const { forAll(pointLabels, labelI) { label pointI = pointLabels[labelI]; const labelList& pFaces = mesh().pointFaces()[pointI]; forAll(pFaces, pFaceI) { label faceI = pFaces[pFaceI]; if (mesh().isInternalFace(faceI)) { return pointI; } } } if (pointLabels.empty()) { FatalErrorInFunction << "Empty pointLabels" << abort(FatalError); } return -1; } // Find point on face that is part of original mesh and that is point connected // to the patch CML::label CML::meshCutAndRemove::findPatchFacePoint ( const face& f, const label exposedPatchI ) const { const labelListList& pointFaces = mesh().pointFaces(); const polyBoundaryMesh& patches = mesh().boundaryMesh(); forAll(f, fp) { label pointI = f[fp]; if (pointI < mesh().nPoints()) { const labelList& pFaces = pointFaces[pointI]; forAll(pFaces, i) { if (patches.whichPatch(pFaces[i]) == exposedPatchI) { return pointI; } } } } return -1; } // Get new owner and neighbour of face. Checks anchor points to see if // cells have been removed. void CML::meshCutAndRemove::faceCells ( const cellCuts& cuts, const label exposedPatchI, const label faceI, label& own, label& nei, label& patchID ) const { const labelListList& anchorPts = cuts.cellAnchorPoints(); const labelListList& cellLoops = cuts.cellLoops(); const face& f = mesh().faces()[faceI]; own = mesh().faceOwner()[faceI]; if (cellLoops[own].size() && firstCommon(f, anchorPts[own]) == -1) { // owner has been split and this is the removed part. own = -1; } nei = -1; if (mesh().isInternalFace(faceI)) { nei = mesh().faceNeighbour()[faceI]; if (cellLoops[nei].size() && firstCommon(f, anchorPts[nei]) == -1) { nei = -1; } } patchID = mesh().boundaryMesh().whichPatch(faceI); if (patchID == -1 && (own == -1 || nei == -1)) { // Face was internal but becomes external patchID = exposedPatchI; } } void CML::meshCutAndRemove::getZoneInfo ( const label faceI, label& zoneID, bool& zoneFlip ) const { zoneID = mesh().faceZones().whichZone(faceI); zoneFlip = false; if (zoneID >= 0) { const faceZone& fZone = mesh().faceZones()[zoneID]; zoneFlip = fZone.flipMap()[fZone.whichFace(faceI)]; } } // Adds a face from point. void CML::meshCutAndRemove::addFace ( polyTopoChange& meshMod, const label faceI, const label masterPointI, const face& newFace, const label own, const label nei, const label patchID ) { label zoneID; bool zoneFlip; getZoneInfo(faceI, zoneID, zoneFlip); if ((nei == -1) || (own != -1 && own < nei)) { // Ordering ok. if (debug & 2) { Pout<< "Adding face " << newFace << " with new owner:" << own << " with new neighbour:" << nei << " patchID:" << patchID << " anchor:" << masterPointI << " zoneID:" << zoneID << " zoneFlip:" << zoneFlip << endl; } meshMod.setAction ( polyAddFace ( newFace, // face own, // owner nei, // neighbour masterPointI, // master point -1, // master edge -1, // master face for addition false, // flux flip patchID, // patch for face zoneID, // zone for face zoneFlip // face zone flip ) ); } else { // Reverse owner/neighbour if (debug & 2) { Pout<< "Adding (reversed) face " << newFace.reverseFace() << " with new owner:" << nei << " with new neighbour:" << own << " patchID:" << patchID << " anchor:" << masterPointI << " zoneID:" << zoneID << " zoneFlip:" << zoneFlip << endl; } meshMod.setAction ( polyAddFace ( newFace.reverseFace(), // face nei, // owner own, // neighbour masterPointI, // master point -1, // master edge -1, // master face for addition false, // flux flip patchID, // patch for face zoneID, // zone for face zoneFlip // face zone flip ) ); } } // Modifies existing faceI for either new owner/neighbour or new face points. void CML::meshCutAndRemove::modFace ( polyTopoChange& meshMod, const label faceI, const face& newFace, const label own, const label nei, const label patchID ) { label zoneID; bool zoneFlip; getZoneInfo(faceI, zoneID, zoneFlip); if ( (own != mesh().faceOwner()[faceI]) || ( mesh().isInternalFace(faceI) && (nei != mesh().faceNeighbour()[faceI]) ) || (newFace != mesh().faces()[faceI]) ) { if (debug & 2) { Pout<< "Modifying face " << faceI << " old vertices:" << mesh().faces()[faceI] << " new vertices:" << newFace << " new owner:" << own << " new neighbour:" << nei << " new patch:" << patchID << " new zoneID:" << zoneID << " new zoneFlip:" << zoneFlip << endl; } if ((nei == -1) || (own != -1 && own < nei)) { meshMod.setAction ( polyModifyFace ( newFace, // modified face faceI, // label of face being modified own, // owner nei, // neighbour false, // face flip patchID, // patch for face false, // remove from zone zoneID, // zone for face zoneFlip // face flip in zone ) ); } else { meshMod.setAction ( polyModifyFace ( newFace.reverseFace(), // modified face faceI, // label of face being modified nei, // owner own, // neighbour false, // face flip patchID, // patch for face false, // remove from zone zoneID, // zone for face zoneFlip // face flip in zone ) ); } } } // Copies face starting from startFp up to and including endFp. void CML::meshCutAndRemove::copyFace ( const face& f, const label startFp, const label endFp, face& newFace ) const { label fp = startFp; label newFp = 0; while (fp != endFp) { newFace[newFp++] = f[fp]; fp = (fp + 1) % f.size(); } newFace[newFp] = f[fp]; } // Actually split face in two along splitEdge v0, v1 (the two vertices in new // vertex numbering). Generates faces in same ordering // as original face. Replaces cutEdges by the points introduced on them // (addedPoints_). void CML::meshCutAndRemove::splitFace ( const face& f, const label v0, const label v1, face& f0, face& f1 ) const { // Check if we find any new vertex which is part of the splitEdge. label startFp = findIndex(f, v0); if (startFp == -1) { FatalErrorInFunction << "Cannot find vertex (new numbering) " << v0 << " on face " << f << abort(FatalError); } label endFp = findIndex(f, v1); if (endFp == -1) { FatalErrorInFunction << "Cannot find vertex (new numbering) " << v1 << " on face " << f << abort(FatalError); } f0.setSize((endFp + 1 + f.size() - startFp) % f.size()); f1.setSize(f.size() - f0.size() + 2); copyFace(f, startFp, endFp, f0); copyFace(f, endFp, startFp, f1); } // Adds additional vertices (from edge cutting) to face. Used for faces which // are not split but still might use edge that has been cut. CML::face CML::meshCutAndRemove::addEdgeCutsToFace(const label faceI) const { const face& f = mesh().faces()[faceI]; face newFace(2 * f.size()); label newFp = 0; forAll(f, fp) { // Duplicate face vertex. newFace[newFp++] = f[fp]; // Check if edge has been cut. label fp1 = f.fcIndex(fp); HashTable<label, edge, Hash<edge> >::const_iterator fnd = addedPoints_.find(edge(f[fp], f[fp1])); if (fnd != addedPoints_.end()) { // edge has been cut. Introduce new vertex. newFace[newFp++] = fnd(); } } newFace.setSize(newFp); return newFace; } // Walk loop (loop of cuts) across circumference of cellI. Returns face in // new vertices. // Note: tricky bit is that it can use existing edges which have been split. CML::face CML::meshCutAndRemove::loopToFace ( const label cellI, const labelList& loop ) const { face newFace(2*loop.size()); label newFaceI = 0; forAll(loop, fp) { label cut = loop[fp]; if (isEdge(cut)) { label edgeI = getEdge(cut); const edge& e = mesh().edges()[edgeI]; label vertI = addedPoints_[e]; newFace[newFaceI++] = vertI; } else { // cut is vertex. label vertI = getVertex(cut); newFace[newFaceI++] = vertI; label nextCut = loop[loop.fcIndex(fp)]; if (!isEdge(nextCut)) { // From vertex to vertex -> cross cut only if no existing edge. label nextVertI = getVertex(nextCut); label edgeI = meshTools::findEdge(mesh(), vertI, nextVertI); if (edgeI != -1) { // Existing edge. Insert split-edge point if any. HashTable<label, edge, Hash<edge> >::const_iterator fnd = addedPoints_.find(mesh().edges()[edgeI]); if (fnd != addedPoints_.end()) { newFace[newFaceI++] = fnd(); } } } } } newFace.setSize(newFaceI); return newFace; } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // // Construct from components CML::meshCutAndRemove::meshCutAndRemove(const polyMesh& mesh) : edgeVertex(mesh), addedFaces_(), addedPoints_() {} // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // void CML::meshCutAndRemove::setRefinement ( const label exposedPatchI, const cellCuts& cuts, const labelList& cutPatch, polyTopoChange& meshMod ) { // Clear and size maps here since mesh size will change. addedFaces_.clear(); addedFaces_.resize(cuts.nLoops()); addedPoints_.clear(); addedPoints_.resize(cuts.nLoops()); if (cuts.nLoops() == 0) { return; } const labelListList& anchorPts = cuts.cellAnchorPoints(); const labelListList& cellLoops = cuts.cellLoops(); const polyBoundaryMesh& patches = mesh().boundaryMesh(); if (exposedPatchI < 0 || exposedPatchI >= patches.size()) { FatalErrorInFunction << "Illegal exposed patch " << exposedPatchI << abort(FatalError); } // // Add new points along cut edges. // forAll(cuts.edgeIsCut(), edgeI) { if (cuts.edgeIsCut()[edgeI]) { const edge& e = mesh().edges()[edgeI]; // Check if there is any cell using this edge. if (debug && findCutCell(cuts, mesh().edgeCells()[edgeI]) == -1) { FatalErrorInFunction << "Problem: cut edge but none of the cells using it is\n" << "edge:" << edgeI << " verts:" << e << abort(FatalError); } // One of the edge end points should be master point of nbCellI. label masterPointI = e.start(); const point& v0 = mesh().points()[e.start()]; const point& v1 = mesh().points()[e.end()]; scalar weight = cuts.edgeWeight()[edgeI]; point newPt = weight*v1 + (1.0-weight)*v0; label addedPointI = meshMod.setAction ( polyAddPoint ( newPt, // point masterPointI, // master point -1, // zone for point true // supports a cell ) ); // Store on (hash of) edge. addedPoints_.insert(e, addedPointI); if (debug & 2) { Pout<< "Added point " << addedPointI << " to vertex " << masterPointI << " of edge " << edgeI << " vertices " << e << endl; } } } // // Remove all points that will not be used anymore // { boolList usedPoint(mesh().nPoints(), false); forAll(cellLoops, cellI) { const labelList& loop = cellLoops[cellI]; if (loop.size()) { // Cell is cut. Uses only anchor points and loop itself. forAll(loop, fp) { label cut = loop[fp]; if (!isEdge(cut)) { usedPoint[getVertex(cut)] = true; } } const labelList& anchors = anchorPts[cellI]; forAll(anchors, i) { usedPoint[anchors[i]] = true; } } else { // Cell is not cut so use all its points const labelList& cPoints = mesh().cellPoints()[cellI]; forAll(cPoints, i) { usedPoint[cPoints[i]] = true; } } } // Check const Map<edge>& faceSplitCut = cuts.faceSplitCut(); forAllConstIter(Map<edge>, faceSplitCut, iter) { const edge& fCut = iter(); forAll(fCut, i) { label cut = fCut[i]; if (!isEdge(cut)) { label pointI = getVertex(cut); if (!usedPoint[pointI]) { FatalErrorInFunction << "Problem: faceSplitCut not used by any loop" << " or cell anchor point" << "face:" << iter.key() << " point:" << pointI << " coord:" << mesh().points()[pointI] << abort(FatalError); } } } } forAll(cuts.pointIsCut(), pointI) { if (cuts.pointIsCut()[pointI]) { if (!usedPoint[pointI]) { FatalErrorInFunction << "Problem: point is marked as cut but" << " not used by any loop" << " or cell anchor point" << "point:" << pointI << " coord:" << mesh().points()[pointI] << abort(FatalError); } } } // Remove unused points. forAll(usedPoint, pointI) { if (!usedPoint[pointI]) { meshMod.setAction(polyRemovePoint(pointI)); if (debug & 2) { Pout<< "Removing unused point " << pointI << endl; } } } } // // For all cut cells add an internal or external face // forAll(cellLoops, cellI) { const labelList& loop = cellLoops[cellI]; if (loop.size()) { if (cutPatch[cellI] < 0 || cutPatch[cellI] >= patches.size()) { FatalErrorInFunction << "Illegal patch " << cutPatch[cellI] << " provided for cut cell " << cellI << abort(FatalError); } // // Convert loop (=list of cuts) into proper face. // cellCuts sets orientation is towards anchor side so reverse. // face newFace(loopToFace(cellI, loop)); reverse(newFace); // Pick any anchor point on cell label masterPointI = findPatchFacePoint(newFace, exposedPatchI); label addedFaceI = meshMod.setAction ( polyAddFace ( newFace, // face cellI, // owner -1, // neighbour masterPointI, // master point -1, // master edge -1, // master face for addition false, // flux flip cutPatch[cellI], // patch for face -1, // zone for face false // face zone flip ) ); addedFaces_.insert(cellI, addedFaceI); if (debug & 2) { Pout<< "Added splitting face " << newFace << " index:" << addedFaceI << " from masterPoint:" << masterPointI << " to owner " << cellI << " with anchors:" << anchorPts[cellI] << " from Loop:"; // Gets edgeweights of loop scalarField weights(loop.size()); forAll(loop, i) { label cut = loop[i]; weights[i] = ( isEdge(cut) ? cuts.edgeWeight()[getEdge(cut)] : -GREAT ); } writeCuts(Pout, loop, weights); Pout<< endl; } } } // // Modify faces to use only anchorpoints and loop points // (so throw away part without anchorpoints) // // Maintain whether face has been updated (for -split edges // -new owner/neighbour) boolList faceUptodate(mesh().nFaces(), false); const Map<edge>& faceSplitCuts = cuts.faceSplitCut(); forAllConstIter(Map<edge>, faceSplitCuts, iter) { label faceI = iter.key(); // Renumber face to include split edges. face newFace(addEdgeCutsToFace(faceI)); // Edge splitting the face. Convert edge to new vertex numbering. const edge& splitEdge = iter(); label cut0 = splitEdge[0]; label v0; if (isEdge(cut0)) { label edgeI = getEdge(cut0); v0 = addedPoints_[mesh().edges()[edgeI]]; } else { v0 = getVertex(cut0); } label cut1 = splitEdge[1]; label v1; if (isEdge(cut1)) { label edgeI = getEdge(cut1); v1 = addedPoints_[mesh().edges()[edgeI]]; } else { v1 = getVertex(cut1); } // Split face along the elements of the splitEdge. face f0, f1; splitFace(newFace, v0, v1, f0, f1); label own = mesh().faceOwner()[faceI]; label nei = -1; if (mesh().isInternalFace(faceI)) { nei = mesh().faceNeighbour()[faceI]; } if (debug & 2) { Pout<< "Split face " << mesh().faces()[faceI] << " own:" << own << " nei:" << nei << " into f0:" << f0 << " and f1:" << f1 << endl; } // Check which cell using face uses anchorPoints (so is kept) // and which one doesn't (gets removed) // Bit tricky. We have to know whether this faceSplit splits owner/ // neighbour or both. Even if cell is cut we have to make sure this is // the one that cuts it (this face cut might not be the one splitting // the cell) // The face f gets split into two parts, f0 and f1. // Each of these can have a different owner and or neighbour. const face& f = mesh().faces()[faceI]; label f0Own = -1; label f1Own = -1; if (cellLoops[own].empty()) { // Owner side is not split so keep both halves. f0Own = own; f1Own = own; } else if (isIn(splitEdge, cellLoops[own])) { // Owner is cut by this splitCut. See which of f0, f1 gets // preserved and becomes owner, and which gets removed. if (firstCommon(f0, anchorPts[own]) != -1) { // f0 preserved so f1 gets deleted f0Own = own; f1Own = -1; } else { f0Own = -1; f1Own = own; } } else { // Owner not cut by this splitCut but by another. // Check on original face whether // use anchorPts. if (firstCommon(f, anchorPts[own]) != -1) { // both f0 and f1 owner side preserved f0Own = own; f1Own = own; } else { // both f0 and f1 owner side removed f0Own = -1; f1Own = -1; } } label f0Nei = -1; label f1Nei = -1; if (nei != -1) { if (cellLoops[nei].empty()) { f0Nei = nei; f1Nei = nei; } else if (isIn(splitEdge, cellLoops[nei])) { // Neighbour is cut by this splitCut. So anchor part of it // gets kept, non-anchor bit gets removed. See which of f0, f1 // connects to which part. if (firstCommon(f0, anchorPts[nei]) != -1) { f0Nei = nei; f1Nei = -1; } else { f0Nei = -1; f1Nei = nei; } } else { // neighbour not cut by this splitCut. Check on original face // whether use anchorPts. if (firstCommon(f, anchorPts[nei]) != -1) { f0Nei = nei; f1Nei = nei; } else { // both f0 and f1 on neighbour side removed f0Nei = -1; f1Nei = -1; } } } if (debug & 2) { Pout<< "f0 own:" << f0Own << " nei:" << f0Nei << " f1 own:" << f1Own << " nei:" << f1Nei << endl; } // If faces were internal but now become external set a patch. // If they were external already keep the patch. label patchID = patches.whichPatch(faceI); if (patchID == -1) { patchID = exposedPatchI; } // Do as much as possible by modifying faceI. Delay any remove // face. Keep track of whether faceI has been used. bool modifiedFaceI = false; if (f0Own == -1) { if (f0Nei != -1) { // f0 becomes external face (note:modFace will reverse face) modFace(meshMod, faceI, f0, f0Own, f0Nei, patchID); modifiedFaceI = true; } } else { if (f0Nei == -1) { // f0 becomes external face modFace(meshMod, faceI, f0, f0Own, f0Nei, patchID); modifiedFaceI = true; } else { // f0 stays internal face. modFace(meshMod, faceI, f0, f0Own, f0Nei, -1); modifiedFaceI = true; } } // f1 is added face (if at all) if (f1Own == -1) { if (f1Nei == -1) { // f1 not needed. } else { // f1 becomes external face (note:modFace will reverse face) if (!modifiedFaceI) { modFace(meshMod, faceI, f1, f1Own, f1Nei, patchID); modifiedFaceI = true; } else { label masterPointI = findPatchFacePoint(f1, patchID); addFace ( meshMod, faceI, // face for zone info masterPointI, // inflation point f1, // vertices of face f1Own, f1Nei, patchID // patch for new face ); } } } else { if (f1Nei == -1) { // f1 becomes external face if (!modifiedFaceI) { modFace(meshMod, faceI, f1, f1Own, f1Nei, patchID); modifiedFaceI = true; } else { label masterPointI = findPatchFacePoint(f1, patchID); addFace ( meshMod, faceI, masterPointI, f1, f1Own, f1Nei, patchID ); } } else { // f1 is internal face. if (!modifiedFaceI) { modFace(meshMod, faceI, f1, f1Own, f1Nei, -1); modifiedFaceI = true; } else { label masterPointI = findPatchFacePoint(f1, -1); addFace(meshMod, faceI, masterPointI, f1, f1Own, f1Nei, -1); } } } if (f0Own == -1 && f0Nei == -1 && !modifiedFaceI) { meshMod.setAction(polyRemoveFace(faceI)); if (debug & 2) { Pout<< "Removed face " << faceI << endl; } } faceUptodate[faceI] = true; } // // Faces that have not been split but just appended to. Are guaranteed // to be reachable from an edgeCut. // const boolList& edgeIsCut = cuts.edgeIsCut(); forAll(edgeIsCut, edgeI) { if (edgeIsCut[edgeI]) { const labelList& eFaces = mesh().edgeFaces()[edgeI]; forAll(eFaces, i) { label faceI = eFaces[i]; if (!faceUptodate[faceI]) { // So the face has not been split itself (i.e. its owner // or neighbour have not been split) so it only // borders by edge a cell which has been split. // Get (new or original) owner and neighbour of faceI label own, nei, patchID; faceCells(cuts, exposedPatchI, faceI, own, nei, patchID); if (own == -1 && nei == -1) { meshMod.setAction(polyRemoveFace(faceI)); if (debug & 2) { Pout<< "Removed face " << faceI << endl; } } else { // Renumber face to include split edges. face newFace(addEdgeCutsToFace(faceI)); if (debug & 2) { Pout<< "Added edge cuts to face " << faceI << " f:" << mesh().faces()[faceI] << " newFace:" << newFace << endl; } modFace ( meshMod, faceI, newFace, own, nei, patchID ); } faceUptodate[faceI] = true; } } } } // // Remove any faces on the non-anchor side of a split cell. // Note: could loop through all cut cells only and check their faces but // looping over all faces is cleaner and probably faster for dense // cut patterns. const faceList& faces = mesh().faces(); forAll(faces, faceI) { if (!faceUptodate[faceI]) { // Get (new or original) owner and neighbour of faceI label own, nei, patchID; faceCells(cuts, exposedPatchI, faceI, own, nei, patchID); if (own == -1 && nei == -1) { meshMod.setAction(polyRemoveFace(faceI)); if (debug & 2) { Pout<< "Removed face " << faceI << endl; } } else { modFace(meshMod, faceI, faces[faceI], own, nei, patchID); } faceUptodate[faceI] = true; } } if (debug) { Pout<< "meshCutAndRemove:" << nl << " cells split:" << cuts.nLoops() << nl << " faces added:" << addedFaces_.size() << nl << " points added on edges:" << addedPoints_.size() << nl << endl; } } void CML::meshCutAndRemove::updateMesh(const mapPolyMesh& map) { // Update stored labels for mesh change. { Map<label> newAddedFaces(addedFaces_.size()); forAllConstIter(Map<label>, addedFaces_, iter) { label cellI = iter.key(); label newCellI = map.reverseCellMap()[cellI]; label addedFaceI = iter(); label newAddedFaceI = map.reverseFaceMap()[addedFaceI]; if ((newCellI >= 0) && (newAddedFaceI >= 0)) { if ( (debug & 2) && (newCellI != cellI || newAddedFaceI != addedFaceI) ) { Pout<< "meshCutAndRemove::updateMesh :" << " updating addedFace for cell " << cellI << " from " << addedFaceI << " to " << newAddedFaceI << endl; } newAddedFaces.insert(newCellI, newAddedFaceI); } } // Copy addedFaces_.transfer(newAddedFaces); } { HashTable<label, edge, Hash<edge> > newAddedPoints(addedPoints_.size()); for ( HashTable<label, edge, Hash<edge> >::const_iterator iter = addedPoints_.begin(); iter != addedPoints_.end(); ++iter ) { const edge& e = iter.key(); label newStart = map.reversePointMap()[e.start()]; label newEnd = map.reversePointMap()[e.end()]; label addedPointI = iter(); label newAddedPointI = map.reversePointMap()[addedPointI]; if ((newStart >= 0) && (newEnd >= 0) && (newAddedPointI >= 0)) { edge newE = edge(newStart, newEnd); if ( (debug & 2) && (e != newE || newAddedPointI != addedPointI) ) { Pout<< "meshCutAndRemove::updateMesh :" << " updating addedPoints for edge " << e << " from " << addedPointI << " to " << newAddedPointI << endl; } newAddedPoints.insert(newE, newAddedPointI); } } // Copy addedPoints_.transfer(newAddedPoints); } } // ************************************************************************* //
27.479824
80
0.435055
2622eab5a23a648711817362a3f70a54c2c7b51c
10,696
hpp
C++
src/core/ArrayTraits.hpp
gyzhangqm/overkit-1
490aa77a79bd9708d7f2af0f3069b86545a2cebc
[ "MIT" ]
null
null
null
src/core/ArrayTraits.hpp
gyzhangqm/overkit-1
490aa77a79bd9708d7f2af0f3069b86545a2cebc
[ "MIT" ]
null
null
null
src/core/ArrayTraits.hpp
gyzhangqm/overkit-1
490aa77a79bd9708d7f2af0f3069b86545a2cebc
[ "MIT" ]
1
2021-07-21T06:48:19.000Z
2021-07-21T06:48:19.000Z
// Copyright (c) 2020 Matthew J. Smith and Overkit contributors // License: MIT (http://opensource.org/licenses/MIT) #ifndef OVK_CORE_ARRAY_TRAITS_HPP_INCLUDED #define OVK_CORE_ARRAY_TRAITS_HPP_INCLUDED #include <ovk/core/ArrayTraitsBase.hpp> #include <ovk/core/Elem.hpp> #include <ovk/core/Global.hpp> #include <ovk/core/IntegerSequence.hpp> #include <ovk/core/Interval.hpp> #include <ovk/core/IteratorTraits.hpp> #include <ovk/core/Requires.hpp> #include <ovk/core/TypeTraits.hpp> #include <array> #include <cstddef> #include <string> #include <type_traits> #include <utility> #include <vector> namespace ovk { // C-style array template <typename T> struct array_traits<T, OVK_SPECIALIZATION_REQUIRES(std::is_array<T>::value)> { using value_type = typename std::remove_all_extents<T>::type; static constexpr int Rank = std::rank<T>::value; static constexpr array_layout Layout = array_layout::ROW_MAJOR; template <int> static constexpr long long ExtentBegin() { return 0; } template <int iDim> static constexpr long long ExtentEnd() { return std::extent<T,iDim>::value; } // Not sure if there's a better way to do this that works for general multidimensional arrays static const value_type *Data(const T &Array) { return reinterpret_cast<const value_type *>(&Array[0]); } static value_type *Data(T &Array) { return reinterpret_cast<value_type *>(&Array[0]); } }; // std::array template <typename T, std::size_t N> struct array_traits<std::array<T,N>> { using value_type = T; static constexpr int Rank = 1; static constexpr array_layout Layout = array_layout::ROW_MAJOR; template <int> static constexpr long long ExtentBegin() { return 0; } template <int> static constexpr long long ExtentEnd() { return N; } static const T *Data(const std::array<T,N> &Array) { return Array.data(); } static T *Data(std::array<T,N> &Array) { return Array.data(); } }; // std::vector template <typename T, typename Allocator> struct array_traits<std::vector<T, Allocator>> { using value_type = T; static constexpr int Rank = 1; static constexpr array_layout Layout = array_layout::ROW_MAJOR; template <int> static long long ExtentBegin(const std::vector<T, Allocator> &) { return 0; } template <int> static long long ExtentEnd(const std::vector<T, Allocator> &Vec) { return Vec.size(); } static const T *Data(const std::vector<T, Allocator> &Vec) { return Vec.data(); } static T *Data(std::vector<T, Allocator> &Vec) { return Vec.data(); } }; // std::basic_string template <typename CharT, typename Traits, typename Allocator> struct array_traits< std::basic_string<CharT, Traits, Allocator>> { using value_type = CharT; static constexpr int Rank = 1; static constexpr array_layout Layout = array_layout::ROW_MAJOR; template <int> static long long ExtentBegin(const std::basic_string<CharT, Traits, Allocator> &) { return 0; } template <int> static long long ExtentEnd(const std::basic_string<CharT, Traits, Allocator> &String) { return String.length(); } static const CharT *Data(const std::basic_string<CharT, Traits, Allocator> &String) { return String.c_str(); } // No non-const Data access }; namespace core { namespace array_value_type_internal { template <typename T, typename=void> struct helper; template <typename T> struct helper<T, OVK_SPECIALIZATION_REQUIRES(IsArray<T>())> { using type = typename array_traits<T>::value_type; }; template <typename T> struct helper<T, OVK_SPECIALIZATION_REQUIRES(!IsArray<T>())> { using type = std::false_type; }; } template <typename T> using array_value_type = typename array_value_type_internal::helper<T>::type; template <typename T, OVK_FUNCTION_REQUIRES(IsArray<T>())> constexpr array_layout ArrayLayout() { return array_traits<T>::Layout; } template <typename T, OVK_FUNCTION_REQUIRES(!IsArray<T>())> constexpr array_layout ArrayLayout() { return array_layout::ROW_MAJOR; } template <typename T, int Rank, array_layout Layout, OVK_FUNCTION_REQUIRES(IsArray<T>())> constexpr bool ArrayHasFootprint() { return ArrayRank<T>() == Rank && (Rank == 1 || ArrayLayout<T>() == Layout); } template <typename T, int Rank, array_layout Layout, OVK_FUNCTION_REQUIRES(!IsArray<T>())> constexpr bool ArrayHasFootprint() { return false; } template <typename T, typename U, OVK_FUNCTION_REQUIRES(IsArray<T>() && IsArray<U>())> constexpr bool ArraysAreCongruent() { return ArrayRank<T>() == ArrayRank<U>() && (ArrayRank<T>() == 1 || ArrayLayout<T>() == ArrayLayout<U>()); } template <typename T, typename U, OVK_FUNCTION_REQUIRES(!IsArray<T>() || !IsArray<U>())> constexpr bool ArraysAreCongruent() { return false; } namespace array_extents_internal { template <typename TupleElementType, typename ArrayType, std::size_t... Indices> constexpr interval<TupleElementType,ArrayRank<ArrayType>()> StaticHelper(core::index_sequence<Indices...>) { return { {TupleElementType(array_traits<ArrayType>::template ExtentBegin<Indices>())...}, {TupleElementType(array_traits<ArrayType>::template ExtentEnd<Indices>())...} }; } template <typename TupleElementType, typename ArrayType, std::size_t... Indices> interval< TupleElementType,ArrayRank<ArrayType>()> RuntimeHelper(core::index_sequence<Indices...>, const ArrayType &Array) { return { {TupleElementType(array_traits<ArrayType>::template ExtentBegin<Indices>(Array))...}, {TupleElementType(array_traits<ArrayType>::template ExtentEnd<Indices>(Array))...} }; } } template <typename TupleElementType=long long, typename ArrayType, OVK_FUNCTION_REQUIRES(IsArray< ArrayType>() && ArrayHasStaticExtents<ArrayType>())> constexpr interval<TupleElementType, ArrayRank<ArrayType>()> ArrayExtents(const ArrayType &) { return array_extents_internal::StaticHelper<TupleElementType, ArrayType>( core::index_sequence_of_size<ArrayRank<ArrayType>()>()); } template <typename TupleElementType=long long, typename ArrayType, OVK_FUNCTION_REQUIRES(IsArray< ArrayType>() && ArrayHasRuntimeExtents<ArrayType>())> interval<TupleElementType,ArrayRank< ArrayType>()> ArrayExtents(const ArrayType &Array) { return array_extents_internal::RuntimeHelper<TupleElementType, ArrayType>( core::index_sequence_of_size<ArrayRank<ArrayType>()>(), Array); } namespace array_size_internal { template <typename TupleElementType, typename ArrayType, std::size_t... Indices> constexpr elem<TupleElementType,ArrayRank<ArrayType>()> StaticHelper(core::index_sequence<Indices...>) { return {TupleElementType(array_traits<ArrayType>::template ExtentEnd<Indices>() - array_traits<ArrayType>::template ExtentBegin<Indices>())...}; } template <typename TupleElementType, typename ArrayType, std::size_t... Indices> elem< TupleElementType,ArrayRank<ArrayType>()> RuntimeHelper(core::index_sequence<Indices...>, const ArrayType &Array) { return {TupleElementType(array_traits<ArrayType>::template ExtentEnd<Indices>(Array) - array_traits<ArrayType>::template ExtentBegin<Indices>(Array))...}; } } template <typename TupleElementType=long long, typename ArrayType, OVK_FUNCTION_REQUIRES(IsArray< ArrayType>() && ArrayHasStaticExtents<ArrayType>())> constexpr elem<TupleElementType,ArrayRank< ArrayType>()> ArraySize(const ArrayType &) { return array_size_internal::StaticHelper<TupleElementType, ArrayType>( core::index_sequence_of_size<ArrayRank<ArrayType>()>()); } template <typename TupleElementType=long long, typename ArrayType, OVK_FUNCTION_REQUIRES(IsArray< ArrayType>() && ArrayHasRuntimeExtents<ArrayType>())> elem<TupleElementType,ArrayRank<ArrayType>() > ArraySize(const ArrayType &Array) { return array_size_internal::RuntimeHelper<TupleElementType, ArrayType>( core::index_sequence_of_size<ArrayRank<ArrayType>()>(), Array); } namespace array_count_internal { template <typename IndexType, typename ArrayType, int Dim, OVK_FUNCTION_REQUIRES(Dim == ArrayRank<ArrayType>()-1)> constexpr IndexType StaticHelper() { return IndexType(array_traits<ArrayType>::template ExtentEnd<Dim>() - array_traits<ArrayType>::template ExtentBegin<Dim>()); } template <typename IndexType, typename ArrayType, int Dim, OVK_FUNCTION_REQUIRES(Dim < ArrayRank<ArrayType>()-1)> constexpr IndexType StaticHelper() { return IndexType(array_traits<ArrayType>::template ExtentEnd<Dim>() - array_traits<ArrayType>:: template ExtentBegin<Dim>()) * StaticHelper<IndexType, ArrayType, Dim+1>(); } template <typename IndexType, typename ArrayType, int Dim, OVK_FUNCTION_REQUIRES(Dim == ArrayRank<ArrayType>()-1)> IndexType RuntimeHelper(const ArrayType &Array) { return IndexType(array_traits<ArrayType>::template ExtentEnd<Dim>(Array) - array_traits<ArrayType>::template ExtentBegin<Dim>(Array)); } template <typename IndexType, typename ArrayType, int Dim, OVK_FUNCTION_REQUIRES(Dim < ArrayRank<ArrayType>()-1)> IndexType RuntimeHelper(const ArrayType &Array) { return IndexType(array_traits<ArrayType>::template ExtentEnd<Dim>(Array) - array_traits< ArrayType>::template ExtentBegin<Dim>(Array)) * RuntimeHelper<IndexType, ArrayType, Dim+1>( Array); } } template <typename IndexType=long long, typename ArrayType, OVK_FUNCTION_REQUIRES(IsArray< ArrayType>() && ArrayHasStaticExtents<ArrayType>())> constexpr IndexType ArrayCount(const ArrayType &) { return array_count_internal::StaticHelper<IndexType, ArrayType, 0>(); } template <typename IndexType=long long, typename ArrayType, OVK_FUNCTION_REQUIRES(IsArray< ArrayType>() && ArrayHasRuntimeExtents<ArrayType>())> IndexType ArrayCount(const ArrayType &Array) { return array_count_internal::RuntimeHelper<IndexType, ArrayType, 0>(Array); } template <typename ArrayRefType, OVK_FUNCTION_REQUIRES(IsArray<remove_cvref<ArrayRefType>>())> auto ArrayData(ArrayRefType &&Array) -> decltype(array_traits<remove_cvref<ArrayRefType>>::Data( std::forward<ArrayRefType>(Array))) { return array_traits<remove_cvref<ArrayRefType>>::Data(std::forward<ArrayRefType>(Array)); } template <typename ArrayRefType, OVK_FUNCTION_REQUIRES(IsArray<remove_cvref<ArrayRefType>>())> auto ArrayBegin(ArrayRefType &&Array) -> decltype(MakeForwardingIterator<array_access_type< ArrayRefType &&>>(ArrayData(Array))) { return MakeForwardingIterator<array_access_type<ArrayRefType &&>>(ArrayData(Array)); } template <typename ArrayRefType, OVK_FUNCTION_REQUIRES(IsArray<remove_cvref<ArrayRefType>>())> auto ArrayEnd(ArrayRefType &&Array) -> decltype(MakeForwardingIterator<array_access_type< ArrayRefType &&>>(core::ArrayData(Array)+ArrayCount(Array))) { return MakeForwardingIterator<array_access_type<ArrayRefType &&>>(ArrayData(Array)+ ArrayCount(Array)); } } } #endif
45.130802
100
0.755984
2626448ee8c472a55023f86a2caaea7f08d76247
158
cpp
C++
old/Codeforces/466/A.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
7
2018-04-14T14:55:51.000Z
2022-01-31T10:49:49.000Z
old/Codeforces/466/A.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
5
2018-04-14T14:28:49.000Z
2019-05-11T02:22:10.000Z
old/Codeforces/466/A.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
null
null
null
#include "template.hpp" int main() { int n, m, a, b; cin >> n >> m >> a >> b; cout << min(n * a, min(n / m * b + n % m * a, n / m * b + b)) << endl; }
19.75
72
0.411392
26290ecf777c44a6fc4b1ab9cd0cbf89918f0d97
1,208
hh
C++
recorder/src/main/cpp/blocking_ring_buffer.hh
Flipkart/fk-prof
ed801c32a8c3704204be670e16c6465297431e1a
[ "Apache-2.0", "MIT" ]
7
2017-01-17T11:29:08.000Z
2021-06-07T10:36:59.000Z
recorder/src/main/cpp/blocking_ring_buffer.hh
Flipkart/fk-prof
ed801c32a8c3704204be670e16c6465297431e1a
[ "Apache-2.0", "MIT" ]
106
2017-01-12T04:38:40.000Z
2017-10-04T11:12:54.000Z
recorder/src/main/cpp/blocking_ring_buffer.hh
Flipkart/fk-prof
ed801c32a8c3704204be670e16c6465297431e1a
[ "Apache-2.0", "MIT" ]
4
2016-12-22T08:56:27.000Z
2018-07-26T17:13:42.000Z
#ifndef BLOCKING_RING_BUFFER_H #define BLOCKING_RING_BUFFER_H #include <thread> #include <mutex> #include <condition_variable> #include "globals.hh" class BlockingRingBuffer { private: std::uint32_t read_idx, write_idx, capacity, available; std::uint8_t *buff; bool allow_writes; std::mutex m; std::condition_variable writable, readable; std::uint32_t write_noblock(const std::uint8_t *from, std::uint32_t& offset, std::uint32_t& sz); std::uint32_t read_noblock(std::uint8_t *to, std::uint32_t& offset, std::uint32_t& sz); metrics::Timer& s_t_write; metrics::Timer& s_t_write_wait; metrics::Hist& s_h_write_sz; metrics::Timer& s_t_read; metrics::Timer& s_t_read_wait; metrics::Hist& s_h_read_sz; public: static constexpr std::uint32_t DEFAULT_RING_SZ = 1024 * 1024; BlockingRingBuffer(std::uint32_t _capacity = DEFAULT_RING_SZ); ~BlockingRingBuffer(); std::uint32_t write(const std::uint8_t *from, std::uint32_t offset, std::uint32_t sz, bool do_block = true); std::uint32_t read(std::uint8_t *to, std::uint32_t offset, std::uint32_t sz, bool do_block = true); std::uint32_t reset(); void readonly(); }; #endif
26.844444
112
0.712748
262cab7befc0663f26883159779c9a7d1d2edb3a
4,246
hpp
C++
include/gamma/basis.hpp
robashaw/gamma
26fba31be640c9bc429f8c22d5c61c0f8e9215e6
[ "MIT" ]
8
2019-09-13T10:35:26.000Z
2022-03-26T13:20:54.000Z
include/gamma/basis.hpp
robashaw/gamma
26fba31be640c9bc429f8c22d5c61c0f8e9215e6
[ "MIT" ]
null
null
null
include/gamma/basis.hpp
robashaw/gamma
26fba31be640c9bc429f8c22d5c61c0f8e9215e6
[ "MIT" ]
null
null
null
/* * * PURPOSE: To define the class Basis representing a * basis set. * * class Basis: * owns: bfs - a set of BFs * data: name - the name of the basis set, needed for file io * charges - a list of atomic numbers corresponding to * each BF in bfs. * shells - a list representing which bfs are in which * shells - i.e. if the first 3 are in one shell, * the next two in another, etc, it would be * 3, 2, ... * lnums - a list with the angular quantum number * of each shell in shells * routines: * findPosition(q) - find the first position in the bfs * array of an atom of atomic number q * findShellPosition(q) - find the first position in the * shells array * getNBFs() - returns the total number of basis functions * getName() - returns the name * getCharges() - returns the vector of charges * getBF(charge, i) - return the ith BF corresponding to * an atom of atomic number charge * getSize(charge) - return how many basis functions an atom * of atomic number charge has * getShellSize(charge) - return how many shells it has * getShells(charge) - return a vector of the correct subset * of shells * getLnums(charge) - return vector of subset of lnums * * * DATE AUTHOR CHANGES * ==================================================================== * 27/08/15 Robert Shaw Original code. * */ #ifndef BASISHEADERDEF #define BASISHEADERDEF // Includes #include "eigen_wrapper.hpp" #include <string> #include <libint2.hpp> #include <vector> #include <map> #include "libecpint/gshell.hpp" // Forward declarations class BF; // Begin class definitions class Basis { private: std::map<int, std::string> names; std::string name; int maxl, nexps; bool ecps; std::vector<std::vector <libint2::Shell::Contraction>> raw_contractions; std::vector<libint2::Shell> intShells; std::vector<libint2::Shell> jkShells; std::vector<libint2::Shell> riShells; std::vector<int> shellAtomList; std::vector<int> jkShellAtomList; std::vector<int> riShellAtomList; public: // Constructors and destructor // Note - no copy constructor, as it doesn't really seem necessary // Need to specify the name of the basis, n, and a list of the // distinct atoms that are needed (as a vector of atomic numbers) Basis() : name("Undefined"), nexps(-1) { } // Default constructor Basis(std::map<int, std::string> ns, bool _ecps = false); // Accessors bool hasECPS() const { return ecps; } std::string getName(int q) const; std::string getName() const { return name; } std::map<int, std::string>& getNames() { return names; } int getShellAtom(int i) const { return shellAtomList[i]; } int getJKShellAtom(int i) const { return jkShellAtomList[i]; } int getRIShellAtom(int i) const { return riShellAtomList[i]; } std::vector<libint2::Shell>& getIntShells() { return intShells; } std::vector<libint2::Shell>& getJKShells() { return jkShells; } std::vector<libint2::Shell>& getRIShells() { return riShells; } std::vector<int>& getShellAtomList() { return shellAtomList; } std::vector<int>& getJKShellAtomList() { return jkShellAtomList; } std::vector<int>& getRIShellAtomList() { return riShellAtomList; } int getNExps(); int getMaxL() const { return maxl; } void setMaxL(int l) { maxl = l; } double getExp(int i) const; void setExp(int i, double value); double extent() const; void addShell(libecpint::GaussianShell& g, int atom, int type = 0); // Overloaded operators Basis& operator=(const Basis& other); }; #endif
38.252252
79
0.567358
262e2c6360952d755e2279fb0b1cfb7972446d70
1,348
cpp
C++
Kattis/Week0/Wk0j_interpreter.cpp
Frodocz/CS2040C
d2e132a2f3cf56eef3f725990c7ffcf71a6a76d5
[ "MIT" ]
null
null
null
Kattis/Week0/Wk0j_interpreter.cpp
Frodocz/CS2040C
d2e132a2f3cf56eef3f725990c7ffcf71a6a76d5
[ "MIT" ]
null
null
null
Kattis/Week0/Wk0j_interpreter.cpp
Frodocz/CS2040C
d2e132a2f3cf56eef3f725990c7ffcf71a6a76d5
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; #define MEMORY_SIZE 1000 #define REGISTER_NUM 10 int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int i, cnt = 0, idx = 0; vector<int> registers(REGISTER_NUM), ram(MEMORY_SIZE); while (cin >> i) { ram[idx++] = i; } idx = 0; while (true) { ++cnt; i = ram[idx]; int op = i / 100, a = (i / 10) % 10, b = i % 10; if (op == 1) { break; } else if (op == 2) { registers[a] = b; } else if (op == 3) { registers[a] = (registers[a] + b) % 1000; } else if (op == 4) { registers[a] = (registers[a] * b) % 1000; } else if (op == 5) { registers[a] = registers[b]; } else if (op == 6) { registers[a] = (registers[a] + registers[b]) % 1000; } else if (op == 7) { registers[a] = (registers[a] * registers[b]) % 1000; } else if (op == 8) { registers[a] = ram[registers[b]]; } else if (i / 100 == 9) { ram[registers[b]] = registers[a]; } else { if (registers[b] != 0) { idx = registers[a]; continue; } } ++idx; } cout << cnt << endl; return 0; }
24.962963
64
0.432493
262e2d197cb7945f4341134e31eac2a8530912dd
1,966
cpp
C++
AMM/multiPage.cpp
CatOfBlades/ArbitraryMemoryMapper
ef49c548b6171ca1b3cac61c5cb6366ca6039abc
[ "MIT" ]
null
null
null
AMM/multiPage.cpp
CatOfBlades/ArbitraryMemoryMapper
ef49c548b6171ca1b3cac61c5cb6366ca6039abc
[ "MIT" ]
null
null
null
AMM/multiPage.cpp
CatOfBlades/ArbitraryMemoryMapper
ef49c548b6171ca1b3cac61c5cb6366ca6039abc
[ "MIT" ]
null
null
null
#include "multiPage.h" #include "../Defines.h" #ifdef WINBUILD #include <windows.h> #endif // WINBUILD unsigned long int multiPage::_size() { if(!bankList.size()){return 0;} return bankList[_bankNum]->_size(); } bool multiPage::_is_free() { if(!bankList.size()){return 0;} return bankList[_bankNum]->_is_free(); } unsigned char* multiPage::_content() { if(!bankList.size()){return 0;} return bankList[_bankNum]->_content(); } unsigned char multiPage::readByte(unsigned long int offset) { if(!bankList.size()){return 0;} return bankList[_bankNum]->readByte(offset); } void multiPage::writeByte(unsigned long int offset,unsigned char Byt) { if(!bankList.size()){return;} bankList[_bankNum]->writeByte(offset, Byt); return; } void multiPage::readMem(unsigned long int offset,unsigned char* buffer ,unsigned long int len) { if(!bankList.size()){return;} bankList[_bankNum]->readMem(offset, buffer, len); return; } void multiPage::writeMem(unsigned long int offset,unsigned char* Byt,unsigned long int len) { if(!bankList.size()){return;} bankList[_bankNum]->writeMem(offset, Byt, len); return; } void multiPage::cleanupAndUnlink() { while(bankList.size()>0) { //bankList.back()->cleanupAndUnlink(); //If we handle the cleanup elsewhere it allows us even more self reference nonsense. bankList.pop_back(); } return; } void multiPage::addBank(addressSpace* AS) { bankList.push_back(AS); } void multiPage::switchBank(int bankNum) { bankNum = bankNum%bankList.size(); _bankNum = bankNum; } void multiPage::removeBank(int bankNum) { bankList.erase(bankList.begin()+bankNum); } void multiPage::removeAndUnlinkBank(int bankNum) { addressSpace* bank = bankList[bankNum]; bankList.erase(bankList.begin()+bankNum); bank->cleanupAndUnlink(); } multiPage::multiPage():addressSpace() { memoryTypeID = "multpage"; _bankNum=0; }
22.860465
96
0.685656
1c79f5bbe1b6b243c5446a39d6116e47b4c0efac
2,049
cpp
C++
ECOO/ECOO '19 R1 P3 - Side Scrolling Simulator.cpp
Joon7891/Competitive-Programming
d860b7ad932cd5a6fb91fdc8c53101da57f4a408
[ "MIT" ]
2
2021-04-13T00:19:56.000Z
2021-04-13T01:19:45.000Z
ECOO/ECOO '19 R1 P3 - Side Scrolling Simulator.cpp
Joon7891/Competitive-Programming
d860b7ad932cd5a6fb91fdc8c53101da57f4a408
[ "MIT" ]
null
null
null
ECOO/ECOO '19 R1 P3 - Side Scrolling Simulator.cpp
Joon7891/Competitive-Programming
d860b7ad932cd5a6fb91fdc8c53101da57f4a408
[ "MIT" ]
1
2020-08-26T12:36:08.000Z
2020-08-26T12:36:08.000Z
#include <bits/stdc++.h> #define MEM(a, b) memset(a, b, sizeof(a)) using namespace std; void solve(){ char a[105][13]; MEM(a,'@'); int j, w, h; cin>> j >> w >> h; string s; int x = 0,y = h - 2; for(int i = 0; i < h; i++) { cin >> s; for(int j = 0; j < w; j++) { a[j][i] = s[j]; if(s[j] == 'L') { x = j; } } } while(1) { if(a[x][y] == 'G'){ cout << "CLEAR" << endl; return; } else if (a[x + 1][y] == '.'|| a[x + 1][y] == 'G') { x++; } else if(a[x + 1][y] != '.') { bool c = 0; for(int i = 1; i <= j; i++) { if(y - i < 0) continue; if(x + 2 >= w) continue; bool l = 1; for(int k = h - 1; k >= y - i; k--) { if(a[x][k] == '@') l = 0; } if(!l) continue; bool n=1; for(int k = h-1; k >= y-i; k--) { if(a[x + 2][k] == '@') n = 0; } if(n==0) continue; if(a[x][y - i] != '.') continue; if(y - i < 0) { if(a[x + 2][y - i] == '.') { x = x + 2; y = y - i; c = 1; break; } } if (a[x + 1][y - i] == '.') { c = 1; x = x+2; break; } } if(!c) { cout << x+2 << endl; return; } } } } int main() { ios_base::sync_with_stdio(NULL); cin.tie(0); cout.tie(0); for(int i = 0; i < 10; i++) { solve(); } }
19.514286
57
0.226452
1c7a23c69da6a8ca7bcfc1c13c3afcd7d8b5ab15
11,114
cpp
C++
src/EBV_Triangulator.cpp
fdebrain/Stereo-Event-Based-Reconstruction-with-Active-Laser-Features
9e63a5d15edffba65d6e6ab521c5f6413832a97c
[ "MIT" ]
4
2021-08-10T17:35:35.000Z
2021-12-06T08:43:07.000Z
src/EBV_Triangulator.cpp
fdebrain/Stereo-Event-Based-Reconstruction-with-Active-Laser-Features
9e63a5d15edffba65d6e6ab521c5f6413832a97c
[ "MIT" ]
null
null
null
src/EBV_Triangulator.cpp
fdebrain/Stereo-Event-Based-Reconstruction-with-Active-Laser-Features
9e63a5d15edffba65d6e6ab521c5f6413832a97c
[ "MIT" ]
null
null
null
#include <EBV_Triangulator.h> #include <EBV_Benchmarking.h> void Triangulator::switchMode() { m_mode = static_cast<Triangulator::StereoPair>((m_mode+1)%3); std::cout << "Switch triangulation mode to: " << stereoPairNames[m_mode] << "\n\r"; } void Triangulator::resetCalibration() { for (auto &k : m_K) { k = cv::Mat(3,3,CV_64FC1); } for (auto &d : m_D) { d = cv::Mat(1,5,CV_32FC1); } for (auto &r : m_R) { r = cv::Mat(3,3,CV_32FC1); } for (auto &t : m_T) { t = cv::Mat(3,1,CV_32FC1); } for (auto &f : m_F) { f = cv::Mat(3,3,CV_32FC1); } for (auto &q : m_Q) { q = cv::Mat(4,4,CV_32FC1); } for (auto &p : m_P) { p[0] = cv::Mat(3,4,CV_32FC1); p[1] = cv::Mat(3,4,CV_32FC1); } for (auto &rect : m_Rect) { rect[0] = cv::Mat(3,3,CV_32FC1); rect[1] = cv::Mat(3,3,CV_32FC1); } m_Pfix = cv::Mat(3,4,CV_32FC1); } void Triangulator::importCalibration() { resetCalibration(); cv::FileStorage fs; // Import camera calibration fs.open(m_path_calib_cam, cv::FileStorage::READ); fs["camera_matrix0"] >> m_K[0]; fs["dist_coeffs0"] >> m_D[0]; fs["camera_matrix1"] >> m_K[1]; fs["dist_coeffs1"] >> m_D[1]; fs["R"] >> m_R[0]; fs["T"] >> m_T[0]; fs["F"] >> m_F[0]; std::cout << "K0: " << m_K[0] << "\n\r"; std::cout << "D0: " << m_D[0] << "\n\r"; std::cout << "K1: " << m_K[1] << "\n\r"; std::cout << "D1: " << m_D[1] << "\n\r"; std::cout << "R: " << m_R[0] << "\n\r"; std::cout << "T: " << m_T[0] << "\n\r"; std::cout << "F: " << m_F[0] << "\n\r"; fs.release(); // Import laser calibration fs.open(m_path_calib_laser, cv::FileStorage::READ); fs["camera_matrix_laser"] >> m_K[2]; fs["dist_coeffs_laser"] >> m_D[2]; fs["R1"] >> m_R[1]; fs["T1"] >> m_T[1]; fs["F1"] >> m_F[1]; fs["R2"] >> m_R[2]; fs["T2"] >> m_T[2]; fs["F2"] >> m_F[2]; std::cout << "KLaser: " << m_K[2] << "\n\r"; std::cout << "DLaser: " << m_D[2] << "\n\r"; std::cout << "R1: " << m_R[1] << "\n\r"; std::cout << "T1: " << m_T[1] << "\n\r"; std::cout << "F1: " << m_F[1] << "\n\r"; std::cout << "R2: " << m_R[2] << "\n\r"; std::cout << "T2: " << m_T[2] << "\n\r"; std::cout << "F2: " << m_F[2] << "\n\r"; fs.release(); // Initialize projection matrices for cam0-cam1 stereo pair if (isValid(0) && isValid(1)) { m_enable = true; cv::stereoRectify(m_K[0],m_D[0], m_K[1],m_D[1], cv::Size(m_cols,m_rows), m_R[0],m_T[0], m_Rect[0][0], m_Rect[0][1], m_P[0][0], m_P[0][1], m_Q[0], cv::CALIB_ZERO_DISPARITY); } else { m_enable = false; printf("Please press C to calibrate the cameras.\n\r"); return; } // Initialize projection matrices for cam0-laser & cam1-laser stereo pairs if (isValid(0) && isValid(1) && isValid(2)) { m_enable = true; // CameraLeft-laser cv::stereoRectify(m_K[0],m_D[0], m_K[2],m_D[2], cv::Size(m_cols,m_rows), m_R[1],m_T[1], m_Rect[1][0], m_Rect[1][1], m_P[1][0], m_P[1][1], m_Q[1], cv::CALIB_ZERO_DISPARITY); //CameraRight-laser cv::stereoRectify(m_K[1],m_D[1], m_K[2],m_D[2], cv::Size(m_cols,m_rows), m_R[2],m_T[2], m_Rect[2][0], m_Rect[2][1], m_P[2][0], m_P[2][1], m_Q[2], cv::CALIB_ZERO_DISPARITY); } else { m_enable = false; printf("Please press C to calibrate the laser.\n\r"); return; } } bool Triangulator::isValid(const int id) const { return m_K[id].rows==3 && m_K[id].cols==3 && m_D[id].rows==1 && m_D[id].cols==5; } Triangulator::Triangulator(Matcher* matcher, LaserController* laser) : m_matcher(matcher), m_laser(laser) { // Initialize datastructures resetCalibration(); // Listen to matcher m_matcher->registerMatcherListener(this); // Recording triangulation if (m_record){ m_recorder.open(m_eventRecordFile); } // Calibration this->importCalibration(); if (m_enable) { m_thread = std::thread(&Triangulator::run,this); } } Triangulator::~Triangulator() { m_matcher->deregisterMatcherListener(this); if (m_record){ m_recorder.close(); } } void Triangulator::run() { bool hasQueueEvent0; bool hasQueueEvent1; DAVIS240CEvent event0; DAVIS240CEvent event1; while(true) { m_queueAccessMutex0.lock(); hasQueueEvent0 =! m_evtQueue0.empty(); m_queueAccessMutex0.unlock(); m_queueAccessMutex1.lock(); hasQueueEvent1 =! m_evtQueue1.empty(); m_queueAccessMutex1.unlock(); // Process only if incoming filtered events in both cameras if(hasQueueEvent0 && hasQueueEvent1) { m_queueAccessMutex0.lock(); event0 = m_evtQueue0.front(); m_evtQueue0.pop_front(); m_queueAccessMutex0.unlock(); m_queueAccessMutex1.lock(); event1 = m_evtQueue1.front(); m_evtQueue1.pop_front(); m_queueAccessMutex1.unlock(); process(event0,event1); } else { std::unique_lock<std::mutex> condLock(m_condWaitMutex); m_condWait.wait(condLock); condLock.unlock(); } } } void Triangulator::receivedNewMatch(const DAVIS240CEvent& event0, const DAVIS240CEvent& event1) { m_queueAccessMutex0.lock(); m_evtQueue0.push_back(event0); m_queueAccessMutex0.unlock(); m_queueAccessMutex1.lock(); m_evtQueue1.push_back(event1); m_queueAccessMutex1.unlock(); std::unique_lock<std::mutex> condLock(m_condWaitMutex); m_condWait.notify_one(); } void Triangulator::process(const DAVIS240CEvent& event0, const DAVIS240CEvent& event1) { //Timer timer; // 0.1ms on average std::vector<cv::Point2d> coords0, coords1; std::vector<cv::Point2d> undistCoords0, undistCoords1; std::vector<cv::Point2d> undistCoordsCorrected0, undistCoordsCorrected1; cv::Vec4d point3D; m_queueAccessMutex0.lock(); const int x0 = event0.m_x; const int y0 = event0.m_y; const int x1 = event1.m_x; const int y1 = event1.m_y; //const int laser_x = 180*(m_laser->getX()-500)/(4000 - 500); //const int laser_y = 240*(m_laser->getY())/(4000); const int laser_x = static_cast<int>(180.*(event0.m_laser_x-500.)/(4000. - 500.)); const int laser_y = static_cast<int>(240.*(event0.m_laser_y)/(4000.)); m_queueAccessMutex0.unlock(); switch (m_mode) { case Cameras: coords0.emplace_back(y0,x0); coords1.emplace_back(y1,x1); cv::undistortPoints(coords0, undistCoords0, m_K[0], m_D[0], m_Rect[m_mode][0], m_P[m_mode][0]); cv::undistortPoints(coords1, undistCoords1, m_K[1], m_D[1], m_Rect[m_mode][1], m_P[m_mode][1]); cv::triangulatePoints(m_P[m_mode][0], m_P[m_mode][1], undistCoords0, //undistCoordsCorrected0 undistCoords1, //undistCoordsCorrected1 point3D); break; case CamLeftLaser: coords0.emplace_back(y0,x0); coords1.emplace_back(laser_y,laser_x); cv::undistortPoints(coords0, undistCoords0, m_K[0], m_D[0], m_Rect[m_mode][0], m_P[m_mode][0]); cv::undistortPoints(coords1, undistCoords1, m_K[2], m_D[2], m_Rect[m_mode][1], m_P[m_mode][1]); // Refine matches coordinates (using epipolar constraint) cv::correctMatches(m_F[m_mode],undistCoords0,undistCoords1, undistCoordsCorrected0, undistCoordsCorrected1); cv::triangulatePoints(m_P[m_mode][0], m_P[m_mode][1], undistCoordsCorrected0, undistCoordsCorrected1, point3D); break; case CamRightLaser: coords0.emplace_back(y1,x1); coords1.emplace_back(laser_y,laser_x); cv::undistortPoints(coords0, undistCoords0, m_K[1], m_D[1], m_Rect[m_mode][0], m_P[m_mode][0]); cv::undistortPoints(coords1, undistCoords1, m_K[2], m_D[2], m_Rect[m_mode][1], m_P[m_mode][1]); // Refine matches coordinates (using epipolar constraint) cv::correctMatches(m_F[m_mode],undistCoords0,undistCoords1, undistCoordsCorrected0, undistCoordsCorrected1); cv::triangulatePoints(m_P[m_mode][0], m_P[m_mode][1], undistCoordsCorrected0, undistCoordsCorrected1, point3D); break; } // Convert to cm + scale double scale = point3D[3]; double X = 100*point3D[0]/scale; double Y = 100*point3D[1]/scale; double Z = 100*point3D[2]/scale; if (m_record) { recordPoint(X,Y,Z); } warnDepth(x0,y0,X,Y,Z); coords0.clear(); coords1.clear(); // DEBUG - CHECK 3D POINT POSITION if (m_debug) { printf("Point at: (%2.1f,%2.1f,%2.1f,%2.1f). \n\r ",X,Y,Z,scale); } // END DEBUG } void Triangulator::recordPoint(double X, double Y, double Z) { m_recorder << X << '\t' << Y << '\t' << Z << '\n'; } void Triangulator::computeProjectionMatrix(cv::Mat K, cv::Mat R, cv::Mat T, cv::Mat& P) { K.convertTo(K,CV_64FC1); cv::hconcat(K*R,K*T,P); } void Triangulator::registerTriangulatorListener(TriangulatorListener* listener) { m_triangulatorListeners.push_back(listener); } void Triangulator::deregisterTriangulatorListener(TriangulatorListener* listener) { m_triangulatorListeners.remove(listener); } void Triangulator::warnDepth(const int u, const int v, const double X, const double Y, const double Z) { std::list<TriangulatorListener*>::iterator it; for(it = m_triangulatorListeners.begin(); it!=m_triangulatorListeners.end(); it++) { (*it)->receivedNewDepth(u,v,X,Y,Z); } }
31.936782
99
0.520875
1c8540e0cc6f5f8955cf146e09cf4feb22d1cf64
9,058
cpp
C++
unittest/testTimer.cpp
airekans/Tpool
2ba21ca68588d90e738f35c6ddcc17bb8b1f3f1d
[ "MIT" ]
13
2015-05-19T11:08:44.000Z
2021-07-11T01:00:35.000Z
unittest/testTimer.cpp
guker/Tpool
2ba21ca68588d90e738f35c6ddcc17bb8b1f3f1d
[ "MIT" ]
17
2015-01-04T15:16:51.000Z
2015-04-16T04:43:38.000Z
unittest/testTimer.cpp
guker/Tpool
2ba21ca68588d90e738f35c6ddcc17bb8b1f3f1d
[ "MIT" ]
11
2015-04-30T09:21:59.000Z
2021-10-04T07:48:34.000Z
#include "Timer.h" #include "Atomic.h" #include "Thread.h" #include "TestUtil.h" #include <gtest/gtest.h> using namespace tpool; using namespace tpool::unittest; namespace { class TimerTestSuite : public ::testing::Test { protected: Atomic<int> counter; TimerTestSuite() : counter(0) {} virtual void SetUp() { counter = 0; } }; struct TestTimerTask : public TimerTask { Atomic<int>& counter; TestTimerTask(Atomic<int>& cnt) : counter(cnt) {} virtual void DoRun() { ++counter; } }; } TEST_F(TimerTestSuite, test_Ctor) { Timer timer; } TEST_F(TimerTestSuite, test_RunLater) { { Timer timer; timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 200); ASSERT_EQ(0, counter); MilliSleep(500); ASSERT_EQ(1, counter); } ASSERT_EQ(1, counter); } TEST_F(TimerTestSuite, test_RunLater_and_cancel_task) { { Timer timer; TimerTask::Ptr task(new TestTimerTask(counter)); timer.RunLater(task, 200); ASSERT_EQ(0, counter); task->Cancel(); ASSERT_EQ(0, counter); } ASSERT_EQ(0, counter); } TEST_F(TimerTestSuite, test_RunLater_and_async_cancel_task) { { Timer timer; TimerTask::Ptr task(new TestTimerTask(counter)); timer.RunLater(task, 200); ASSERT_EQ(0, counter); task->CancelAsync(); ASSERT_EQ(0, counter); } ASSERT_EQ(0, counter); } TEST_F(TimerTestSuite, test_RunLater_with_same_task) { { Timer timer; TimerTask::Ptr task(new TestTimerTask(counter)); ASSERT_TRUE(timer.RunLater(task, 200)); ASSERT_FALSE(timer.RunLater(task, 200)); ASSERT_EQ(0, counter); MilliSleep(300); ASSERT_EQ(1, counter); } ASSERT_EQ(1, counter); } TEST_F(TimerTestSuite, test_RunEvery) { { Timer timer; TimerTask::Ptr task(new TestTimerTask(counter)); timer.RunEvery(task, 500, true); MilliSleep(100); ASSERT_EQ(1, counter); MilliSleep(1100); ASSERT_EQ(3, counter); } ASSERT_EQ(3, counter); } TEST_F(TimerTestSuite, test_RunEvery_with_same_task) { { Timer timer; TimerTask::Ptr task(new TestTimerTask(counter)); ASSERT_TRUE(timer.RunEvery(task, 500, true)); ASSERT_FALSE(timer.RunEvery(task, 500, true)); MilliSleep(100); ASSERT_EQ(1, counter); MilliSleep(1100); ASSERT_EQ(3, counter); } ASSERT_EQ(3, counter); } TEST_F(TimerTestSuite, test_RunEvery_and_not_run_now) { { Timer timer; TimerTask::Ptr task(new TestTimerTask(counter)); timer.RunEvery(task, 500, false); MilliSleep(100); ASSERT_EQ(0, counter); MilliSleep(1100); ASSERT_EQ(2, counter); } ASSERT_EQ(2, counter); } TEST_F(TimerTestSuite, test_RunEvery_and_cancel) { { Timer timer; TimerTask::Ptr task(new TestTimerTask(counter)); timer.RunEvery(task, 500, true); MilliSleep(100); ASSERT_EQ(1, counter); MilliSleep(500); ASSERT_EQ(2, counter); task->Cancel(); MilliSleep(500); ASSERT_EQ(2, counter); } ASSERT_EQ(2, counter); } TEST_F(TimerTestSuite, test_Run_with_multiple_tasks) { { Timer timer; timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 200); timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 100); timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 300); ASSERT_EQ(0, counter); MilliSleep(200); ASSERT_GT(counter, 0); MilliSleep(500); ASSERT_EQ(3, counter); } ASSERT_EQ(3, counter); } namespace { struct TestTimerFunc { Atomic<int>& counter; TestTimerFunc(Atomic<int>& cnt) : counter(cnt) {} void operator()() { ++counter; } }; } TEST_F(TimerTestSuite, test_RunLater_with_functor) { { Timer timer; timer.RunLater(TestTimerFunc(counter), 200); ASSERT_EQ(0, counter); MilliSleep(500); ASSERT_EQ(1, counter); } ASSERT_EQ(1, counter); } namespace { struct RunLaterThread { Timer& m_timer; Atomic<int>& m_counter; TimeValue m_delay; RunLaterThread(Timer& timer, Atomic<int>& counter, TimeValue delay) : m_timer(timer), m_counter(counter), m_delay(delay) {} void operator()() { m_timer.RunLater(TestTimerFunc(m_counter), m_delay); } }; } TEST_F(TimerTestSuite, test_RunLater_with_multiple_threads) { { Timer timer; // create 2 threads to do RunLater Thread thread1(RunLaterThread(timer, counter, 100)); Thread thread2(RunLaterThread(timer, counter, 100)); timer.RunLater(TestTimerFunc(counter), 100); MilliSleep(300); ASSERT_EQ(3, counter); } ASSERT_EQ(3, counter); } TEST_F(TimerTestSuite, test_RunEvery_with_functor) { { Timer timer; timer.RunEvery(TestTimerFunc(counter), 500, false); ASSERT_EQ(0, counter); MilliSleep(600); ASSERT_EQ(1, counter); MilliSleep(500); ASSERT_EQ(2, counter); } ASSERT_EQ(2, counter); } namespace { struct RunEveryThread { Timer& m_timer; Atomic<int>& m_counter; TimeValue m_delay; bool m_is_run_now; RunEveryThread(Timer& timer, Atomic<int>& counter, TimeValue delay, bool is_run_now) : m_timer(timer), m_counter(counter), m_delay(delay), m_is_run_now(is_run_now) {} void operator()() { m_timer.RunEvery(TestTimerFunc(m_counter), m_delay, m_is_run_now); } }; } TEST_F(TimerTestSuite, test_RunEvery_with_multiple_threads) { { Timer timer; // create 2 threads to do RunEvery Thread thread1(RunEveryThread(timer, counter, 200, true)); Thread thread2(RunEveryThread(timer, counter, 200, true)); timer.RunEvery(TestTimerFunc(counter), 200, true); MilliSleep(100); ASSERT_EQ(3, counter); MilliSleep(200); ASSERT_EQ(6, counter); } ASSERT_EQ(6, counter); } namespace { struct SelfCancelTimerTask : public TimerTask { Atomic<int>& counter; const int cancel_count; SelfCancelTimerTask(Atomic<int>& cnt, int cancel_cnt) : counter(cnt), cancel_count(cancel_cnt) {} virtual void DoRun() { ++counter; if (counter == cancel_count) { CancelAsync(); } } }; } TEST_F(TimerTestSuite, test_RunEvery_with_self_cancel_task) { { Timer timer; TimerTask::Ptr task(new SelfCancelTimerTask(counter, 3)); timer.RunEvery(task, 200, false); MilliSleep(100); ASSERT_EQ(0, counter); while (!(task->IsCancelled())) { MilliSleep(200); } ASSERT_EQ(3, counter); } ASSERT_EQ(3, counter); } TEST_F(TimerTestSuite, test_StopAsync) { { Timer timer; timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 500); timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 100); timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 1000); ASSERT_EQ(0, counter); MilliSleep(200); ASSERT_EQ(1, counter); timer.StopAsync(); } ASSERT_EQ(1, counter); } TEST_F(TimerTestSuite, test_RunLater_after_StopAsync) { { Timer timer; TimerTask::Ptr task(new TestTimerTask(counter)); ASSERT_TRUE(timer.RunLater(task, 100)); ASSERT_EQ(0, counter); MilliSleep(300); ASSERT_EQ(1, counter); timer.StopAsync(); TimerTask::Ptr task1(new TestTimerTask(counter)); ASSERT_FALSE(timer.RunLater(task1, 100)); ASSERT_EQ(1, counter); MilliSleep(300); ASSERT_EQ(1, counter); } ASSERT_EQ(1, counter); } TEST_F(TimerTestSuite, test_Stop) { { Timer timer; timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 500); timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 100); timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 1000); ASSERT_EQ(0, counter); MilliSleep(200); ASSERT_EQ(1, counter); timer.Stop(); MilliSleep(500); ASSERT_EQ(1, counter); } ASSERT_EQ(1, counter); } namespace { struct TimerStopThread { Timer& m_timer; TimerStopThread(Timer& timer) : m_timer(timer) {} void operator()() { m_timer.Stop(); } }; } TEST_F(TimerTestSuite, test_Stop_with_multiple_threads) { { Timer timer; timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 500); timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 100); timer.RunLater(TimerTask::Ptr(new TestTimerTask(counter)), 1000); ASSERT_EQ(0, counter); MilliSleep(200); ASSERT_EQ(1, counter); Thread thread1((TimerStopThread(timer))); Thread thread2((TimerStopThread(timer))); timer.Stop(); MilliSleep(500); ASSERT_EQ(1, counter); } ASSERT_EQ(1, counter); } TEST_F(TimerTestSuite, test_RunLater_after_Stop) { { Timer timer; TimerTask::Ptr task(new TestTimerTask(counter)); ASSERT_TRUE(timer.RunLater(task, 100)); ASSERT_EQ(0, counter); MilliSleep(300); ASSERT_EQ(1, counter); timer.Stop(); TimerTask::Ptr task1(new TestTimerTask(counter)); ASSERT_FALSE(timer.RunLater(task1, 100)); ASSERT_EQ(1, counter); MilliSleep(300); ASSERT_EQ(1, counter); } ASSERT_EQ(1, counter); }
19.64859
69
0.659417
1c888ffbcbdae678e1772280f72ea0065ce94d34
3,040
cpp
C++
2018/0804_mujin-pc-2018/E.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
7
2019-03-24T14:06:29.000Z
2020-09-17T21:16:36.000Z
2018/0804_mujin-pc-2018/E.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
null
null
null
2018/0804_mujin-pc-2018/E.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
1
2020-07-22T17:27:09.000Z
2020-07-22T17:27:09.000Z
/** * File : E.cpp * Author : Kazune Takahashi * Created : 2018-8-4 22:09:58 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; const char ds[4] = {'D', 'R', 'U', 'L'}; typedef tuple<ll, int, int> state; // const int C = 1e6+10; const ll infty = 10000000000007; int N, M, K; string D; string S[1010]; ll dist[300010][4]; ll ans[1010][1010]; int main() { cin >> N >> M >> K; cin >> D; D = D + D + D; for (auto i = 0; i < N; i++) { cin >> S[i]; } for (auto k = 0; k < 4; k++) { dist[3 * K][k] = infty; } for (int i = 3 * K - 1; i >= 0; i--) { for (auto k = 0; k < 4; k++) { if (D[i] == ds[k]) { dist[i][k] = 1; } else { dist[i][k] = dist[i + 1][k] + 1; } } } /* for (auto i = 0; i < K; i++) { for (auto k = 0; k < 4; k++) { cerr << "dist[" << i << "][" << k << "] = " << dist[i][k] << endl; } } */ int sx, sy, gx, gy; fill(&ans[0][0], &ans[0][0] + 1010 * 1010, -1); for (auto i = 0; i < N; i++) { for (auto j = 0; j < M; j++) { if (S[i][j] == 'S') { sx = i; sy = j; } else if (S[i][j] == 'G') { gx = i; gy = j; } } } priority_queue<state, vector<state>, greater<state>> Q; Q.push(state(0, sx, sy)); while (!Q.empty()) { ll d = get<0>(Q.top()); int x = get<1>(Q.top()); int y = get<2>(Q.top()); Q.pop(); if (ans[x][y] == -1) { ans[x][y] = d; // cerr << "ans[" << x << "][" << y << "] = " << ans[x][y] << endl; if (x == gx && y == gy) { cout << d << endl; return 0; } for (auto k = 0; k < 4; k++) { int new_x = x + dx[k]; int new_y = y + dy[k]; if (0 <= new_x && new_x < N && 0 <= new_y && new_y < M && S[new_x][new_y] != '#' && ans[new_x][new_y] == -1) { ll new_d = d + dist[d % K][k]; if (new_d < infty) { Q.push(state(new_d, new_x, new_y)); } } } } } cout << -1 << endl; }
22.189781
116
0.464474
1c88b3e9ef72afba9c9d5b45ba8a309c3ef87f97
1,032
hpp
C++
src/emp_dist.hpp
dcjones/isolator
24bafc0a102dce213bfc2b5b9744136ceadaba03
[ "MIT" ]
33
2015-07-13T03:00:01.000Z
2021-03-20T08:49:07.000Z
src/emp_dist.hpp
dcjones/isolator
24bafc0a102dce213bfc2b5b9744136ceadaba03
[ "MIT" ]
9
2016-11-29T00:04:30.000Z
2020-02-10T17:46:01.000Z
src/emp_dist.hpp
dcjones/isolator
24bafc0a102dce213bfc2b5b9744136ceadaba03
[ "MIT" ]
6
2015-09-10T15:49:34.000Z
2017-03-09T05:14:06.000Z
#ifndef ISOLATOR_EMP_DIST #define ISOLATOR_EMP_DIST #include <climits> #include <vector> class EmpDist { public: EmpDist(EmpDist&); /* Construct a emperical distribution from n observations stored in xs. * * Input in run-length encoded samples, which must be in sorted order. * * Args: * vals: An array of unique observations. * lens: Nuber of occurances for each observation. * n: Length of vals and lens. */ EmpDist(const unsigned int* vals, const unsigned int* lens, size_t n); /* Compute the median of the distribution. */ float median() const; /* Probability density function. */ float pdf(unsigned int x) const; /* Comulative p robabability. */ float cdf(unsigned int x) const; private: std::vector<float> pdfvals; std::vector<float> cdfvals; /* Precomputed median */ float med; }; #endif
21.061224
79
0.573643
1c90d631037316fe7681bb0a8018a698d72eeb8c
7,897
cpp
C++
src/toolbar.cpp
alekratz/fiefdom
d0ddb1cc4fe24b57319b3089928c1a576d0c1bbc
[ "0BSD" ]
1
2017-05-19T15:24:51.000Z
2017-05-19T15:24:51.000Z
src/toolbar.cpp
alekratz/fiefdom
d0ddb1cc4fe24b57319b3089928c1a576d0c1bbc
[ "0BSD" ]
null
null
null
src/toolbar.cpp
alekratz/fiefdom
d0ddb1cc4fe24b57319b3089928c1a576d0c1bbc
[ "0BSD" ]
null
null
null
#include "toolbar.hpp" #include "game_scene.hpp" #include "globals.hpp" #include <SDL_ttf.h> #include <SDL.h> #include <cassert> constexpr auto TOOLBAR_HEIGHT = 23; constexpr auto TOOLBAR_ITEM_VPADDING = 3; constexpr auto TOOLBAR_ITEM_HPADDING = 13; //const SDL_Color WHITE { 255, 255, 255, SDL_ALPHA_OPAQUE }; // const SDL_Color BLACK { 0, 0, 0, SDL_ALPHA_OPAQUE }; template<typename CallbackT> Toolbar<CallbackT>::Toolbar(CallbackT& game_state, int32_t y_offset) : m_game_state(game_state) , m_x_offset(TOOLBAR_ITEM_HPADDING) , m_y_offset(y_offset) { } template<typename CallbackT> void Toolbar<CallbackT>::untoggle_all() { for(auto& t : m_items) { t->toggled = false; } } template<typename CallbackT> void Toolbar<CallbackT>::draw() { // Base toolbar SDL_Rect bar { -1, m_y_offset, GAME_WIDTH + 2, TOOLBAR_HEIGHT }; SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE); SDL_RenderFillRect(renderer, &bar); SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderDrawRect(renderer, &bar); // Toolbar items for(auto& t : m_items) { t->draw(); } } template<typename CallbackT> void Toolbar<CallbackT>::update() { for(auto& t : m_items) { t->update(); } } template<typename CallbackT> void Toolbar<CallbackT>::add_item(cstref text, Callback_t callback) { auto new_item = std::make_unique<ToolbarItem<CallbackT>>(m_game_state, m_x_offset, TOOLBAR_ITEM_VPADDING + m_y_offset, text, callback); m_x_offset += new_item->get_width() + TOOLBAR_ITEM_HPADDING; m_items.push_back(std::move(new_item)); } template<typename CallbackT> ToolbarItem<CallbackT>::ToolbarItem(CallbackT& game_state, int32_t x_offset, int32_t y_offset, cstref name, typename Toolbar<CallbackT>::Callback_t callback) : Loggable("ToolbarItem") , name(name) , callback(callback) , hotkey(0) , toggled(false) , x_offset(x_offset) , y_offset(y_offset) , m_game_state(game_state) , m_normal_texture(nullptr) , m_toggled_texture(nullptr) { auto index = name.find("&"); if(index != str::npos) { assert(index <= (name.size() - 2) && "& must come before a character in ToolbarItem"); this->name.erase(index, 1); } // Create textures for this item so we don't have to do these weird calculations every frame TTF_SizeText(regular_font, this->name.c_str(), &m_width, &m_height); m_normal_texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STATIC | SDL_TEXTUREACCESS_TARGET, m_width, m_height); assert(m_normal_texture && "Could not create texture"); m_toggled_texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STATIC | SDL_TEXTUREACCESS_TARGET, m_width, m_height); assert(m_toggled_texture && "Could not create texture"); SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_TRANSPARENT); SDL_SetRenderTarget(renderer, m_normal_texture); SDL_RenderClear(renderer); // Draw the text on each, and highlight the hotkey if necessary SDL_Surface* text_surface = nullptr; SDL_Texture* text_texture = nullptr; if(index != str::npos) { /* normal texture */ text_surface = TTF_RenderText_Blended(regular_font, this->name.c_str(), SDL_Color { 0, 0, 0, SDL_ALPHA_OPAQUE }); text_texture = SDL_CreateTextureFromSurface(renderer, text_surface); SDL_Rect draw_rect { 0, 0, m_width, m_height }; SDL_RenderCopy(renderer, text_texture, nullptr, &draw_rect); assert(text_surface && "Could not render font"); hotkey = this->name[index]; auto hotkey_str = str() + hotkey; /* the way we figure out where to blit the hotkey is to get the length of the string before the hotkey, and then blit starting from there */ auto pre = this->name.substr(0, index); int32_t pre_width; TTF_SizeText(regular_font, pre.c_str(), &pre_width, nullptr); int32_t hotkey_w; TTF_SizeText(regular_font, hotkey_str.c_str(), &hotkey_w, nullptr); draw_rect.x = pre_width; draw_rect.w = hotkey_w; draw_rect.h = m_height; auto hotkey_surface = TTF_RenderText_Shaded(regular_font, (str() + hotkey).c_str(), WHITE_OPAQUE, BLACK_OPAQUE); auto hotkey_texture = SDL_CreateTextureFromSurface(renderer, hotkey_surface); SDL_RenderCopy(renderer, hotkey_texture, nullptr, &draw_rect); SDL_FreeSurface(hotkey_surface); SDL_DestroyTexture(hotkey_texture); /* toggled texture */ SDL_FreeSurface(text_surface); SDL_DestroyTexture(text_texture); text_surface = TTF_RenderText_Shaded(regular_font, this->name.c_str(), WHITE_OPAQUE, BLACK_OPAQUE); SDL_SetRenderTarget(renderer, m_toggled_texture); SDL_RenderClear(renderer); text_texture = SDL_CreateTextureFromSurface(renderer, text_surface); draw_rect = { 0, 0, m_width, m_height }; SDL_RenderCopy(renderer, text_texture, nullptr, &draw_rect); draw_rect.x = pre_width; draw_rect.w = hotkey_w; draw_rect.h = m_height; hotkey_surface = TTF_RenderText_Shaded(regular_font, (str() + hotkey).c_str(), BLACK_OPAQUE, WHITE_OPAQUE); hotkey_texture = SDL_CreateTextureFromSurface(renderer, hotkey_surface); SDL_RenderCopy(renderer, hotkey_texture, nullptr, &draw_rect); SDL_FreeSurface(hotkey_surface); SDL_DestroyTexture(hotkey_texture); } else { text_surface = TTF_RenderText_Blended(regular_font, this->name.c_str(), SDL_Color { 0, 0, 0, SDL_ALPHA_OPAQUE }); assert(text_surface && "Could not render font"); text_texture = SDL_CreateTextureFromSurface(renderer, text_surface); SDL_RenderCopy(renderer, text_texture, nullptr, nullptr); /* toggled texture */ SDL_FreeSurface(text_surface); SDL_DestroyTexture(text_texture); text_surface = TTF_RenderText_Shaded(regular_font, this->name.c_str(), WHITE_OPAQUE, BLACK_OPAQUE); text_texture = SDL_CreateTextureFromSurface(renderer, text_surface); SDL_Rect draw_rect { 0, 0, m_width, m_height }; SDL_RenderCopy(renderer, text_texture, nullptr, &draw_rect); } assert(m_normal_texture && "Default texture was not created"); assert(text_surface); SDL_FreeSurface(text_surface); assert(text_texture); SDL_DestroyTexture(text_texture); SDL_SetRenderTarget(renderer, nullptr); } template<typename CallbackT> ToolbarItem<CallbackT>::~ToolbarItem() { SDL_DestroyTexture(m_normal_texture); SDL_DestroyTexture(m_toggled_texture); } template<typename CallbackT> void ToolbarItem<CallbackT>::draw() { SDL_SetRenderTarget(renderer, nullptr); auto texture = toggled ? m_toggled_texture : m_normal_texture; SDL_Rect rect { x_offset, y_offset, m_width, m_height }; SDL_RenderCopy(renderer, texture, nullptr, &rect); } template<typename CallbackT> void ToolbarItem<CallbackT>::update() { constexpr auto EVENT_SZ = 128; // arbitrary event size static SDL_Event evs[EVENT_SZ]; int count = SDL_PeepEvents(evs, EVENT_SZ, SDL_PEEKEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT); for(int i = 0; i < count; i++) { auto ev = evs[i]; if(hotkey != 0 && ev.type == SDL_KEYDOWN && ev.key.keysym.sym == hotkey && !ev.key.repeat) callback(m_game_state, *this); else if(ev.type == SDL_MOUSEBUTTONDOWN && ev.button.button == SDL_BUTTON_LEFT) { SDL_Rect mouse_rect = { ev.button.x, ev.button.y, 1, 1 }; SDL_Rect text_rect = { x_offset, y_offset, m_width, m_height }; SDL_Rect result; if(SDL_IntersectRect(&mouse_rect, &text_rect, &result) == SDL_TRUE) { callback(m_game_state, *this); } } } }
41.34555
157
0.694314
1c93f82b414d383676dcdfc79956b5141e8135b4
1,104
hxx
C++
tests/cvinvaffine.hxx
zardchim/opencvx
f3727c9be5532f9a41c29f558e72aa19b6db97a4
[ "Unlicense" ]
10
2015-01-29T23:21:06.000Z
2019-07-05T06:27:16.000Z
tests/cvinvaffine.hxx
zardchim/opencvx
f3727c9be5532f9a41c29f558e72aa19b6db97a4
[ "Unlicense" ]
null
null
null
tests/cvinvaffine.hxx
zardchim/opencvx
f3727c9be5532f9a41c29f558e72aa19b6db97a4
[ "Unlicense" ]
13
2015-04-13T20:50:36.000Z
2022-03-20T16:06:05.000Z
#ifdef _MSC_VER #pragma warning(disable:4996) #pragma comment(lib, "cv.lib") #pragma comment(lib, "cxcore.lib") #pragma comment(lib, "cvaux.lib") #pragma comment(lib, "highgui.lib") #endif #include <stdio.h> #include <stdlib.h> #include "cv.h" #include "cvaux.h" #include "cxcore.h" #include "highgui.h" #include "cvcreateaffine.h" #include "cvinvaffine.h" #include <cxxtest/TestSuite.h> class CvInvAffineTest : public CxxTest::TestSuite { public: void testInvAffine() { CvMat* affine = cvCreateMat( 2, 3, CV_64FC1 ); CvMat* invaffine = cvCreateMat( 2, 3, CV_64FC1 ); cvCreateAffine( affine, cvRect32f( 3, 10, 2, 20, 45 ), cvPoint2D32f( 4, 5 ) ); cvInvAffine( affine, invaffine ); double ans[] = { 0.565685, -0.848528, 6.788225, -0.106066, 0.247487, -2.156676, }; CvMat Ans = cvMat( 2, 3, CV_64FC1, ans ); for( int i = 0; i < 2; i++ ) { for( int j = 0; j < 3; j++ ) { TS_ASSERT_DELTA( cvmGet( invaffine, i, j ), cvmGet( &Ans, i, j ), 0.0001 ); } } } };
26.926829
91
0.577899
1c9b1e3e468091ba85c0dae6153ff9f95968ca8b
1,604
hpp
C++
tainthlp.hpp
yqw1212/demovfuscator
d27dd1c87ba6956dae4a3003497fe8760b7299f9
[ "BSD-2-Clause" ]
614
2016-06-19T21:39:02.000Z
2022-03-27T06:07:53.000Z
tainthlp.hpp
yqw1212/demovfuscator
d27dd1c87ba6956dae4a3003497fe8760b7299f9
[ "BSD-2-Clause" ]
20
2016-06-19T21:44:20.000Z
2022-03-31T05:21:34.000Z
tainthlp.hpp
yqw1212/demovfuscator
d27dd1c87ba6956dae4a3003497fe8760b7299f9
[ "BSD-2-Clause" ]
54
2016-06-20T07:01:22.000Z
2021-12-14T13:34:56.000Z
#ifndef TAINTHLP_H #define TAINTHLP_H #include <map> #include <unordered_map> #include <capstone/x86.h> class tainthlp{ public: /** * Adds taint to a specified address and (len - 1) subsequent addresses * @param base base address to taint * @param len length of the area to taint * @param ref the taint reference number (or colour or whatever) * @return 0 if successful, else 1 */ int add_taint(uint64_t base, size_t len, size_t ref); /** * Querys whether an address is tainted * @param addr The Querryed address * @param len The length of the quarryed area * @return true if any of the addresses are tainted, else false */ bool has_taint(uint64_t addr, size_t len); /** * Returns the taint information of an memory cell * @param addr The Memory address * @return the taint reference number */ size_t get_taint(uint64_t addr); /** * Taints a register and the subregisters (tainting ax also taints ah an al, but not eax) * @param reg The register to taint * @param ref The taint reference number * @return 0 on success, 1 on failur */ int add_taint(x86_reg reg, size_t ref); /** * Get the taintness status from the register * @param reg The register * @return true if tainted, false if not */ bool has_taint(x86_reg reg); /** * @param get the taint information off a specific register * @return the taint reference number */ size_t get_taint(x86_reg reg); private: std::map<uint32_t, size_t> mem_taint; std::unordered_map<x86_reg, size_t, std::hash<unsigned int> > reg_taint; } #endif
26.733333
91
0.69015
1c9d69b28786bc646d051ce2fbbde45848874949
312
cpp
C++
codeforces/1337A.cpp
LordRonz/cp-solutions
d95eabbdbf6a04fba912f4e8be203b180af7f46d
[ "WTFPL" ]
2
2021-04-19T06:20:11.000Z
2021-05-04T14:30:00.000Z
codeforces/1337A.cpp
LordRonz/cp-solutions
d95eabbdbf6a04fba912f4e8be203b180af7f46d
[ "WTFPL" ]
2
2022-03-01T09:28:46.000Z
2022-03-02T09:52:33.000Z
codeforces/1337A.cpp
LordRonz/cp-solutions
d95eabbdbf6a04fba912f4e8be203b180af7f46d
[ "WTFPL" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define MAX(a,b,c) max(a,max(b,c)) #define MIN(a,b,c) min(a,min(b,c)) typedef pair<int, int> pii; //0xACCE97ED int main() { int t, a, b, c, d; scanf("%d", &t); while(t--) { scanf("%d %d %d %d", &a, &b, &c, &d); printf("%d %d %d\n", b, c, c); } return 0; }
17.333333
39
0.532051
1ca384e980b06811e0353de766b843292a6a672c
7,384
cpp
C++
ExternalLibraries/NvGameworksFramework/src/NvGLUtils/NvUIGL.cpp
centauroWaRRIor/VulkanSamples
5a7c58de820207cc0931a9db8c90f00453e31631
[ "MIT" ]
175
2018-08-28T14:40:34.000Z
2022-03-19T03:10:02.000Z
ExternalLibraries/NvGameworksFramework/src/NvGLUtils/NvUIGL.cpp
centauroWaRRIor/VulkanSamples
5a7c58de820207cc0931a9db8c90f00453e31631
[ "MIT" ]
null
null
null
ExternalLibraries/NvGameworksFramework/src/NvGLUtils/NvUIGL.cpp
centauroWaRRIor/VulkanSamples
5a7c58de820207cc0931a9db8c90f00453e31631
[ "MIT" ]
11
2019-05-13T12:06:53.000Z
2022-03-18T09:56:37.000Z
//---------------------------------------------------------------------------------- // File: NvGLUtils/NvUIGL.cpp // SDK Version: v3.00 // Email: gameworks@nvidia.com // Site: http://developer.nvidia.com/ // // Copyright (c) 2014-2015, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------------- #include "../../src/NvUI/NvBitFontInternal.h" #include "../../src/NvUI/NvUIInternal.h" #include "NvUIGL.h" #include "NvGLUtils/NvImageGL.h" #include "NV/NvPlatformGL.h" static int32_t TestPrintGLError(const char* str) { int32_t err; err = glGetError(); if (err) VERBOSE_LOG(str, err); return err; } //======================================================================== //======================================================================== #define SAVED_ATTRIBS_MAX 16 /* something for now */ typedef struct { GLboolean enabled; GLint size; GLint stride; GLint type; GLint norm; GLvoid *ptr; } NvUIGLAttribInfo; typedef struct { GLint programBound; NvUIGLAttribInfo attrib[SAVED_ATTRIBS_MAX]; GLboolean depthMaskEnabled; GLboolean depthTestEnabled; GLboolean cullFaceEnabled; GLboolean blendEnabled; //gStateBlock.blendFunc // !!!!TBD //blendFuncSep // tbd GLint vboBound; GLint iboBound; GLint texBound; GLint texActive; // stencil? viewport? // !!!!TBD } NvUIGLStateBlock; static NvUIGLStateBlock gStateBlock; //======================================================================== void NvUISaveStateGL() { int32_t i; int32_t tmpi; TestPrintGLError("Error 0x%x in SaveState @ start...\n"); glGetIntegerv(GL_CURRENT_PROGRAM, &(gStateBlock.programBound)); for (i = 0; i<SAVED_ATTRIBS_MAX; i++) { glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &tmpi); gStateBlock.attrib[i].enabled = (GLboolean)tmpi; if (tmpi) { glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_SIZE, &(gStateBlock.attrib[i].size)); glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &(gStateBlock.attrib[i].stride)); glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_TYPE, &(gStateBlock.attrib[i].type)); glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &(gStateBlock.attrib[i].norm)); glGetVertexAttribPointerv(i, GL_VERTEX_ATTRIB_ARRAY_POINTER, &(gStateBlock.attrib[i].ptr)); } } glGetBooleanv(GL_DEPTH_WRITEMASK, &(gStateBlock.depthMaskEnabled)); gStateBlock.depthTestEnabled = glIsEnabled(GL_DEPTH_TEST); gStateBlock.blendEnabled = glIsEnabled(GL_BLEND); gStateBlock.cullFaceEnabled = glIsEnabled(GL_CULL_FACE); // glGetIntegerv(GL_CULL_FACE_MODE, &(gStateBlock.cullMode)); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &(gStateBlock.vboBound)); glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &(gStateBlock.iboBound)); glGetIntegerv(GL_TEXTURE_BINDING_2D, &(gStateBlock.texBound)); glGetIntegerv(GL_ACTIVE_TEXTURE, &(gStateBlock.texActive)); TestPrintGLError("Error 0x%x in SaveState @ end...\n"); } //======================================================================== void NvUIRestoreStateGL() { int32_t i; // !!!!TBD TODO probably should ensure we can do this still... wasn't before though. // nv_flush_tracked_attribs(); // turn ours off... TestPrintGLError("Error 0x%x in RestoreState @ start...\n"); glUseProgram(gStateBlock.programBound); // set buffers first, in case attribs bound to them... glBindBuffer(GL_ARRAY_BUFFER, gStateBlock.vboBound); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gStateBlock.iboBound); if (gStateBlock.programBound) { // restore program stuff.. for (i = 0; i<SAVED_ATTRIBS_MAX; i++) { if (gStateBlock.attrib[i].enabled) // only restore enabled ones.. ;) { glVertexAttribPointer(i, gStateBlock.attrib[i].size, gStateBlock.attrib[i].type, (GLboolean)(gStateBlock.attrib[i].norm), gStateBlock.attrib[i].stride, gStateBlock.attrib[i].ptr); glEnableVertexAttribArray(i); } else glDisableVertexAttribArray(i); } } if (gStateBlock.depthMaskEnabled) glDepthMask(GL_TRUE); // we turned off. if (gStateBlock.depthTestEnabled) glEnable(GL_DEPTH_TEST); // we turned off. if (!gStateBlock.blendEnabled) glDisable(GL_BLEND); // we turned ON. if (gStateBlock.cullFaceEnabled) glEnable(GL_CULL_FACE); // we turned off. // glGetIntegerv(GL_CULL_FACE_MODE, &(gStateBlock.cullMode)); // restore tex BEFORE switching active state... glBindTexture(GL_TEXTURE_2D, gStateBlock.texBound); if (gStateBlock.texActive != GL_TEXTURE0) glActiveTexture(gStateBlock.texActive); // we set to 0 TestPrintGLError("Error 0x%x in RestoreState @ end...\n"); } extern void NvBitfontUseGL(); static int32_t doNothing() { return 0; } static void doNothingVoid() { /* */ } static bool sIsUsingGL = false; bool NvUIIsGL() { return sIsUsingGL; } void NvUIUseGL() { NvUIRenderFactory::GlobalInit = &doNothing; NvUIRenderFactory::GraphicCreate = &NvUIGraphicRenderGL::Create; NvUIRenderFactory::GraphicFrameCreate = &NvUIGraphicFrameRenderGL::Create; NvUIRenderFactory::TextureRenderCreate = &NvUITextureRenderGL::Create; NvUIRenderFactory::GlobalRenderPrep = &NvUISaveStateGL; NvUIRenderFactory::GlobalRenderDone = &NvUIRestoreStateGL; NvUIRenderFactory::GlobalShutdown = &doNothingVoid; NvBitfontUseGL(); sIsUsingGL = true; }
37.105528
103
0.643418
1cacd2e8237bc3da55355501ac313c2b8d666f59
5,986
cpp
C++
NEST-14.0-FPGA/nestkernel/nest_time.cpp
OpenHEC/SNN-simulator-on-PYNQcluster
14f86a76edf4e8763b58f84960876e95d4efc43a
[ "MIT" ]
45
2019-12-09T06:45:53.000Z
2022-01-29T12:16:41.000Z
NEST-14.0-FPGA/nestkernel/nest_time.cpp
zlchai/SNN-simulator-on-PYNQcluster
14f86a76edf4e8763b58f84960876e95d4efc43a
[ "MIT" ]
2
2020-05-23T05:34:21.000Z
2021-09-08T02:33:46.000Z
NEST-14.0-FPGA/nestkernel/nest_time.cpp
OpenHEC/SNN-simulator-on-PYNQcluster
14f86a76edf4e8763b58f84960876e95d4efc43a
[ "MIT" ]
10
2019-12-09T06:45:59.000Z
2021-03-25T09:32:56.000Z
/* * nest_time.cpp * * This file is part of NEST. * * Copyright (C) 2004 The NEST Initiative * * NEST 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. * * NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>. * */ #include "nest_time.h" // C++ includes: #include <string> // Generated includes: #include "config.h" // Includes from libnestutil: #include "numerics.h" // Includes from sli: #include "doubledatum.h" #include "integerdatum.h" #include "token.h" using namespace nest; /* Obtain time resolution information from configuration variables or use defaults. */ #ifndef CONFIG_TICS_PER_MS #define CONFIG_TICS_PER_MS 1000.0 #endif #ifndef CONFIG_TICS_PER_STEP #define CONFIG_TICS_PER_STEP 100 #endif const double Time::Range::TICS_PER_MS_DEFAULT = CONFIG_TICS_PER_MS; const tic_t Time::Range::TICS_PER_STEP_DEFAULT = CONFIG_TICS_PER_STEP; tic_t Time::Range::TICS_PER_STEP = Time::Range::TICS_PER_STEP_DEFAULT; double Time::Range::TICS_PER_STEP_INV = 1. / static_cast< double >( Time::Range::TICS_PER_STEP ); tic_t Time::Range::TICS_PER_STEP_RND = Time::Range::TICS_PER_STEP - 1; double Time::Range::TICS_PER_MS = Time::Range::TICS_PER_MS_DEFAULT; double Time::Range::MS_PER_TIC = 1 / Time::Range::TICS_PER_MS; double Time::Range::MS_PER_STEP = TICS_PER_STEP / TICS_PER_MS; double Time::Range::STEPS_PER_MS = 1 / Time::Range::MS_PER_STEP; // define for unit -- const'ness is in the header // should only be necessary when not folded away // by the compiler as compile time consts const tic_t Time::LimitPosInf::tics; const delay Time::LimitPosInf::steps; const tic_t Time::LimitNegInf::tics; const delay Time::LimitNegInf::steps; tic_t Time::compute_max() { const long lmax = std::numeric_limits< long >::max(); const tic_t tmax = std::numeric_limits< tic_t >::max(); tic_t tics; if ( lmax < tmax * Range::TICS_PER_STEP_INV ) // step size is limiting factor { tics = Range::TICS_PER_STEP * ( lmax / Range::INF_MARGIN ); } else // tic size is limiting factor { tics = tmax / Range::INF_MARGIN; } // make sure that tics and steps match so that we can have simple range // checking when going back and forth, regardless of limiting factor return tics - ( tics % Range::TICS_PER_STEP ); } Time::Limit::Limit( const tic_t& t ) : tics( t ) , steps( t * Range::TICS_PER_STEP_INV ) , ms( steps * Range::MS_PER_STEP ) { } Time::Limit Time::LIM_MAX( +Time::compute_max() ); Time::Limit Time::LIM_MIN( -Time::compute_max() ); void Time::set_resolution( double ms_per_step ) { assert( ms_per_step > 0 ); Range::TICS_PER_STEP = static_cast< tic_t >( dround( Range::TICS_PER_MS * ms_per_step ) ); Range::TICS_PER_STEP_INV = 1. / static_cast< double >( Range::TICS_PER_STEP ); Range::TICS_PER_STEP_RND = Range::TICS_PER_STEP - 1; // Recalculate ms_per_step to be consistent with rounding above Range::MS_PER_STEP = Range::TICS_PER_STEP / Range::TICS_PER_MS; Range::STEPS_PER_MS = 1 / Range::MS_PER_STEP; const tic_t max = compute_max(); LIM_MAX = +max; LIM_MIN = -max; } void Time::set_resolution( double tics_per_ms, double ms_per_step ) { Range::TICS_PER_MS = tics_per_ms; Range::MS_PER_TIC = 1 / tics_per_ms; set_resolution( ms_per_step ); } void Time::reset_resolution() { Range::TICS_PER_STEP = Range::TICS_PER_STEP_DEFAULT; Range::TICS_PER_STEP_INV = 1. / static_cast< double >( Range::TICS_PER_STEP ); Range::TICS_PER_STEP_RND = Range::TICS_PER_STEP - 1; const tic_t max = compute_max(); LIM_MAX = +max; LIM_MIN = -max; } double Time::ms::fromtoken( const Token& t ) { IntegerDatum* idat = dynamic_cast< IntegerDatum* >( t.datum() ); if ( idat ) { return static_cast< double >( idat->get() ); } DoubleDatum* ddat = dynamic_cast< DoubleDatum* >( t.datum() ); if ( ddat ) { return ddat->get(); } throw TypeMismatch( IntegerDatum().gettypename().toString() + " or " + DoubleDatum().gettypename().toString(), t.datum()->gettypename().toString() ); } tic_t Time::fromstamp( Time::ms_stamp t ) { if ( t.t > LIM_MAX.ms ) { return LIM_POS_INF.tics; } else if ( t.t < LIM_MIN.ms ) { return LIM_NEG_INF.tics; } // why not just fmod STEPS_PER_MS? This gives different // results in corner cases --- and I don't think the // intended ones. tic_t n = static_cast< tic_t >( t.t * Range::TICS_PER_MS ); n -= ( n % Range::TICS_PER_STEP ); const double ms = n * Range::TICS_PER_STEP_INV * Range::MS_PER_STEP; if ( ms < t.t ) { n += Range::TICS_PER_STEP; } return n; } void Time::reset_to_defaults() { // reset the TICS_PER_MS to compiled in default values Range::TICS_PER_MS = Range::TICS_PER_MS_DEFAULT; Range::MS_PER_TIC = 1 / Range::TICS_PER_MS_DEFAULT; // reset TICS_PER_STEP to compiled in default values Range::TICS_PER_STEP = Range::TICS_PER_STEP_DEFAULT; Range::TICS_PER_STEP_INV = 1. / static_cast< double >( Range::TICS_PER_STEP ); Range::TICS_PER_STEP_RND = Range::TICS_PER_STEP - 1; Range::MS_PER_STEP = Range::TICS_PER_STEP / Range::TICS_PER_MS; Range::STEPS_PER_MS = 1 / Range::MS_PER_STEP; } std::ostream& operator<<( std::ostream& strm, const Time& t ) { if ( t.is_neg_inf() ) { strm << "-INF"; } else if ( t.is_pos_inf() ) { strm << "+INF"; } else { strm << t.get_ms() << " ms (= " << t.get_tics() << " tics = " << t.get_steps() << ( t.get_steps() != 1 ? " steps)" : " step)" ); } return strm; }
26.963964
80
0.688607
1cafef81519c467dc4d7a545f84ecbf83849af10
63,947
cpp
C++
src/execution/util/fast_double_parser.cpp
rohanaggarwal7997/terrier2
275d96fdb3f16f94b043230553a8d8d4a26f4168
[ "MIT" ]
null
null
null
src/execution/util/fast_double_parser.cpp
rohanaggarwal7997/terrier2
275d96fdb3f16f94b043230553a8d8d4a26f4168
[ "MIT" ]
2
2020-08-24T16:29:40.000Z
2020-09-08T16:34:51.000Z
src/execution/util/fast_double_parser.cpp
rohanaggarwal7997/terrier2
275d96fdb3f16f94b043230553a8d8d4a26f4168
[ "MIT" ]
null
null
null
#include "execution/util/fast_double_parser.h" namespace terrier::execution::util { const double FastDoubleParser::POWER_OF_TEN[] = {1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22}; const FastDoubleParser::components FastDoubleParser::POWER_OF_TEN_COMPONENTS[] = { {0xa5ced43b7e3e9188L, 7}, {0xcf42894a5dce35eaL, 10}, {0x818995ce7aa0e1b2L, 14}, {0xa1ebfb4219491a1fL, 17}, {0xca66fa129f9b60a6L, 20}, {0xfd00b897478238d0L, 23}, {0x9e20735e8cb16382L, 27}, {0xc5a890362fddbc62L, 30}, {0xf712b443bbd52b7bL, 33}, {0x9a6bb0aa55653b2dL, 37}, {0xc1069cd4eabe89f8L, 40}, {0xf148440a256e2c76L, 43}, {0x96cd2a865764dbcaL, 47}, {0xbc807527ed3e12bcL, 50}, {0xeba09271e88d976bL, 53}, {0x93445b8731587ea3L, 57}, {0xb8157268fdae9e4cL, 60}, {0xe61acf033d1a45dfL, 63}, {0x8fd0c16206306babL, 67}, {0xb3c4f1ba87bc8696L, 70}, {0xe0b62e2929aba83cL, 73}, {0x8c71dcd9ba0b4925L, 77}, {0xaf8e5410288e1b6fL, 80}, {0xdb71e91432b1a24aL, 83}, {0x892731ac9faf056eL, 87}, {0xab70fe17c79ac6caL, 90}, {0xd64d3d9db981787dL, 93}, {0x85f0468293f0eb4eL, 97}, {0xa76c582338ed2621L, 100}, {0xd1476e2c07286faaL, 103}, {0x82cca4db847945caL, 107}, {0xa37fce126597973cL, 110}, {0xcc5fc196fefd7d0cL, 113}, {0xff77b1fcbebcdc4fL, 116}, {0x9faacf3df73609b1L, 120}, {0xc795830d75038c1dL, 123}, {0xf97ae3d0d2446f25L, 126}, {0x9becce62836ac577L, 130}, {0xc2e801fb244576d5L, 133}, {0xf3a20279ed56d48aL, 136}, {0x9845418c345644d6L, 140}, {0xbe5691ef416bd60cL, 143}, {0xedec366b11c6cb8fL, 146}, {0x94b3a202eb1c3f39L, 150}, {0xb9e08a83a5e34f07L, 153}, {0xe858ad248f5c22c9L, 156}, {0x91376c36d99995beL, 160}, {0xb58547448ffffb2dL, 163}, {0xe2e69915b3fff9f9L, 166}, {0x8dd01fad907ffc3bL, 170}, {0xb1442798f49ffb4aL, 173}, {0xdd95317f31c7fa1dL, 176}, {0x8a7d3eef7f1cfc52L, 180}, {0xad1c8eab5ee43b66L, 183}, {0xd863b256369d4a40L, 186}, {0x873e4f75e2224e68L, 190}, {0xa90de3535aaae202L, 193}, {0xd3515c2831559a83L, 196}, {0x8412d9991ed58091L, 200}, {0xa5178fff668ae0b6L, 203}, {0xce5d73ff402d98e3L, 206}, {0x80fa687f881c7f8eL, 210}, {0xa139029f6a239f72L, 213}, {0xc987434744ac874eL, 216}, {0xfbe9141915d7a922L, 219}, {0x9d71ac8fada6c9b5L, 223}, {0xc4ce17b399107c22L, 226}, {0xf6019da07f549b2bL, 229}, {0x99c102844f94e0fbL, 233}, {0xc0314325637a1939L, 236}, {0xf03d93eebc589f88L, 239}, {0x96267c7535b763b5L, 243}, {0xbbb01b9283253ca2L, 246}, {0xea9c227723ee8bcbL, 249}, {0x92a1958a7675175fL, 253}, {0xb749faed14125d36L, 256}, {0xe51c79a85916f484L, 259}, {0x8f31cc0937ae58d2L, 263}, {0xb2fe3f0b8599ef07L, 266}, {0xdfbdcece67006ac9L, 269}, {0x8bd6a141006042bdL, 273}, {0xaecc49914078536dL, 276}, {0xda7f5bf590966848L, 279}, {0x888f99797a5e012dL, 283}, {0xaab37fd7d8f58178L, 286}, {0xd5605fcdcf32e1d6L, 289}, {0x855c3be0a17fcd26L, 293}, {0xa6b34ad8c9dfc06fL, 296}, {0xd0601d8efc57b08bL, 299}, {0x823c12795db6ce57L, 303}, {0xa2cb1717b52481edL, 306}, {0xcb7ddcdda26da268L, 309}, {0xfe5d54150b090b02L, 312}, {0x9efa548d26e5a6e1L, 316}, {0xc6b8e9b0709f109aL, 319}, {0xf867241c8cc6d4c0L, 322}, {0x9b407691d7fc44f8L, 326}, {0xc21094364dfb5636L, 329}, {0xf294b943e17a2bc4L, 332}, {0x979cf3ca6cec5b5aL, 336}, {0xbd8430bd08277231L, 339}, {0xece53cec4a314ebdL, 342}, {0x940f4613ae5ed136L, 346}, {0xb913179899f68584L, 349}, {0xe757dd7ec07426e5L, 352}, {0x9096ea6f3848984fL, 356}, {0xb4bca50b065abe63L, 359}, {0xe1ebce4dc7f16dfbL, 362}, {0x8d3360f09cf6e4bdL, 366}, {0xb080392cc4349decL, 369}, {0xdca04777f541c567L, 372}, {0x89e42caaf9491b60L, 376}, {0xac5d37d5b79b6239L, 379}, {0xd77485cb25823ac7L, 382}, {0x86a8d39ef77164bcL, 386}, {0xa8530886b54dbdebL, 389}, {0xd267caa862a12d66L, 392}, {0x8380dea93da4bc60L, 396}, {0xa46116538d0deb78L, 399}, {0xcd795be870516656L, 402}, {0x806bd9714632dff6L, 406}, {0xa086cfcd97bf97f3L, 409}, {0xc8a883c0fdaf7df0L, 412}, {0xfad2a4b13d1b5d6cL, 415}, {0x9cc3a6eec6311a63L, 419}, {0xc3f490aa77bd60fcL, 422}, {0xf4f1b4d515acb93bL, 425}, {0x991711052d8bf3c5L, 429}, {0xbf5cd54678eef0b6L, 432}, {0xef340a98172aace4L, 435}, {0x9580869f0e7aac0eL, 439}, {0xbae0a846d2195712L, 442}, {0xe998d258869facd7L, 445}, {0x91ff83775423cc06L, 449}, {0xb67f6455292cbf08L, 452}, {0xe41f3d6a7377eecaL, 455}, {0x8e938662882af53eL, 459}, {0xb23867fb2a35b28dL, 462}, {0xdec681f9f4c31f31L, 465}, {0x8b3c113c38f9f37eL, 469}, {0xae0b158b4738705eL, 472}, {0xd98ddaee19068c76L, 475}, {0x87f8a8d4cfa417c9L, 479}, {0xa9f6d30a038d1dbcL, 482}, {0xd47487cc8470652bL, 485}, {0x84c8d4dfd2c63f3bL, 489}, {0xa5fb0a17c777cf09L, 492}, {0xcf79cc9db955c2ccL, 495}, {0x81ac1fe293d599bfL, 499}, {0xa21727db38cb002fL, 502}, {0xca9cf1d206fdc03bL, 505}, {0xfd442e4688bd304aL, 508}, {0x9e4a9cec15763e2eL, 512}, {0xc5dd44271ad3cdbaL, 515}, {0xf7549530e188c128L, 518}, {0x9a94dd3e8cf578b9L, 522}, {0xc13a148e3032d6e7L, 525}, {0xf18899b1bc3f8ca1L, 528}, {0x96f5600f15a7b7e5L, 532}, {0xbcb2b812db11a5deL, 535}, {0xebdf661791d60f56L, 538}, {0x936b9fcebb25c995L, 542}, {0xb84687c269ef3bfbL, 545}, {0xe65829b3046b0afaL, 548}, {0x8ff71a0fe2c2e6dcL, 552}, {0xb3f4e093db73a093L, 555}, {0xe0f218b8d25088b8L, 558}, {0x8c974f7383725573L, 562}, {0xafbd2350644eeacfL, 565}, {0xdbac6c247d62a583L, 568}, {0x894bc396ce5da772L, 572}, {0xab9eb47c81f5114fL, 575}, {0xd686619ba27255a2L, 578}, {0x8613fd0145877585L, 582}, {0xa798fc4196e952e7L, 585}, {0xd17f3b51fca3a7a0L, 588}, {0x82ef85133de648c4L, 592}, {0xa3ab66580d5fdaf5L, 595}, {0xcc963fee10b7d1b3L, 598}, {0xffbbcfe994e5c61fL, 601}, {0x9fd561f1fd0f9bd3L, 605}, {0xc7caba6e7c5382c8L, 608}, {0xf9bd690a1b68637bL, 611}, {0x9c1661a651213e2dL, 615}, {0xc31bfa0fe5698db8L, 618}, {0xf3e2f893dec3f126L, 621}, {0x986ddb5c6b3a76b7L, 625}, {0xbe89523386091465L, 628}, {0xee2ba6c0678b597fL, 631}, {0x94db483840b717efL, 635}, {0xba121a4650e4ddebL, 638}, {0xe896a0d7e51e1566L, 641}, {0x915e2486ef32cd60L, 645}, {0xb5b5ada8aaff80b8L, 648}, {0xe3231912d5bf60e6L, 651}, {0x8df5efabc5979c8fL, 655}, {0xb1736b96b6fd83b3L, 658}, {0xddd0467c64bce4a0L, 661}, {0x8aa22c0dbef60ee4L, 665}, {0xad4ab7112eb3929dL, 668}, {0xd89d64d57a607744L, 671}, {0x87625f056c7c4a8bL, 675}, {0xa93af6c6c79b5d2dL, 678}, {0xd389b47879823479L, 681}, {0x843610cb4bf160cbL, 685}, {0xa54394fe1eedb8feL, 688}, {0xce947a3da6a9273eL, 691}, {0x811ccc668829b887L, 695}, {0xa163ff802a3426a8L, 698}, {0xc9bcff6034c13052L, 701}, {0xfc2c3f3841f17c67L, 704}, {0x9d9ba7832936edc0L, 708}, {0xc5029163f384a931L, 711}, {0xf64335bcf065d37dL, 714}, {0x99ea0196163fa42eL, 718}, {0xc06481fb9bcf8d39L, 721}, {0xf07da27a82c37088L, 724}, {0x964e858c91ba2655L, 728}, {0xbbe226efb628afeaL, 731}, {0xeadab0aba3b2dbe5L, 734}, {0x92c8ae6b464fc96fL, 738}, {0xb77ada0617e3bbcbL, 741}, {0xe55990879ddcaabdL, 744}, {0x8f57fa54c2a9eab6L, 748}, {0xb32df8e9f3546564L, 751}, {0xdff9772470297ebdL, 754}, {0x8bfbea76c619ef36L, 758}, {0xaefae51477a06b03L, 761}, {0xdab99e59958885c4L, 764}, {0x88b402f7fd75539bL, 768}, {0xaae103b5fcd2a881L, 771}, {0xd59944a37c0752a2L, 774}, {0x857fcae62d8493a5L, 778}, {0xa6dfbd9fb8e5b88eL, 781}, {0xd097ad07a71f26b2L, 784}, {0x825ecc24c873782fL, 788}, {0xa2f67f2dfa90563bL, 791}, {0xcbb41ef979346bcaL, 794}, {0xfea126b7d78186bcL, 797}, {0x9f24b832e6b0f436L, 801}, {0xc6ede63fa05d3143L, 804}, {0xf8a95fcf88747d94L, 807}, {0x9b69dbe1b548ce7cL, 811}, {0xc24452da229b021bL, 814}, {0xf2d56790ab41c2a2L, 817}, {0x97c560ba6b0919a5L, 821}, {0xbdb6b8e905cb600fL, 824}, {0xed246723473e3813L, 827}, {0x9436c0760c86e30bL, 831}, {0xb94470938fa89bceL, 834}, {0xe7958cb87392c2c2L, 837}, {0x90bd77f3483bb9b9L, 841}, {0xb4ecd5f01a4aa828L, 844}, {0xe2280b6c20dd5232L, 847}, {0x8d590723948a535fL, 851}, {0xb0af48ec79ace837L, 854}, {0xdcdb1b2798182244L, 857}, {0x8a08f0f8bf0f156bL, 861}, {0xac8b2d36eed2dac5L, 864}, {0xd7adf884aa879177L, 867}, {0x86ccbb52ea94baeaL, 871}, {0xa87fea27a539e9a5L, 874}, {0xd29fe4b18e88640eL, 877}, {0x83a3eeeef9153e89L, 881}, {0xa48ceaaab75a8e2bL, 884}, {0xcdb02555653131b6L, 887}, {0x808e17555f3ebf11L, 891}, {0xa0b19d2ab70e6ed6L, 894}, {0xc8de047564d20a8bL, 897}, {0xfb158592be068d2eL, 900}, {0x9ced737bb6c4183dL, 904}, {0xc428d05aa4751e4cL, 907}, {0xf53304714d9265dfL, 910}, {0x993fe2c6d07b7fabL, 914}, {0xbf8fdb78849a5f96L, 917}, {0xef73d256a5c0f77cL, 920}, {0x95a8637627989aadL, 924}, {0xbb127c53b17ec159L, 927}, {0xe9d71b689dde71afL, 930}, {0x9226712162ab070dL, 934}, {0xb6b00d69bb55c8d1L, 937}, {0xe45c10c42a2b3b05L, 940}, {0x8eb98a7a9a5b04e3L, 944}, {0xb267ed1940f1c61cL, 947}, {0xdf01e85f912e37a3L, 950}, {0x8b61313bbabce2c6L, 954}, {0xae397d8aa96c1b77L, 957}, {0xd9c7dced53c72255L, 960}, {0x881cea14545c7575L, 964}, {0xaa242499697392d2L, 967}, {0xd4ad2dbfc3d07787L, 970}, {0x84ec3c97da624ab4L, 974}, {0xa6274bbdd0fadd61L, 977}, {0xcfb11ead453994baL, 980}, {0x81ceb32c4b43fcf4L, 984}, {0xa2425ff75e14fc31L, 987}, {0xcad2f7f5359a3b3eL, 990}, {0xfd87b5f28300ca0dL, 993}, {0x9e74d1b791e07e48L, 997}, {0xc612062576589ddaL, 1000}, {0xf79687aed3eec551L, 1003}, {0x9abe14cd44753b52L, 1007}, {0xc16d9a0095928a27L, 1010}, {0xf1c90080baf72cb1L, 1013}, {0x971da05074da7beeL, 1017}, {0xbce5086492111aeaL, 1020}, {0xec1e4a7db69561a5L, 1023}, {0x9392ee8e921d5d07L, 1027}, {0xb877aa3236a4b449L, 1030}, {0xe69594bec44de15bL, 1033}, {0x901d7cf73ab0acd9L, 1037}, {0xb424dc35095cd80fL, 1040}, {0xe12e13424bb40e13L, 1043}, {0x8cbccc096f5088cbL, 1047}, {0xafebff0bcb24aafeL, 1050}, {0xdbe6fecebdedd5beL, 1053}, {0x89705f4136b4a597L, 1057}, {0xabcc77118461cefcL, 1060}, {0xd6bf94d5e57a42bcL, 1063}, {0x8637bd05af6c69b5L, 1067}, {0xa7c5ac471b478423L, 1070}, {0xd1b71758e219652bL, 1073}, {0x83126e978d4fdf3bL, 1077}, {0xa3d70a3d70a3d70aL, 1080}, {0xccccccccccccccccL, 1083}, {0x8000000000000000L, 1087}, {0xa000000000000000L, 1090}, {0xc800000000000000L, 1093}, {0xfa00000000000000L, 1096}, {0x9c40000000000000L, 1100}, {0xc350000000000000L, 1103}, {0xf424000000000000L, 1106}, {0x9896800000000000L, 1110}, {0xbebc200000000000L, 1113}, {0xee6b280000000000L, 1116}, {0x9502f90000000000L, 1120}, {0xba43b74000000000L, 1123}, {0xe8d4a51000000000L, 1126}, {0x9184e72a00000000L, 1130}, {0xb5e620f480000000L, 1133}, {0xe35fa931a0000000L, 1136}, {0x8e1bc9bf04000000L, 1140}, {0xb1a2bc2ec5000000L, 1143}, {0xde0b6b3a76400000L, 1146}, {0x8ac7230489e80000L, 1150}, {0xad78ebc5ac620000L, 1153}, {0xd8d726b7177a8000L, 1156}, {0x878678326eac9000L, 1160}, {0xa968163f0a57b400L, 1163}, {0xd3c21bcecceda100L, 1166}, {0x84595161401484a0L, 1170}, {0xa56fa5b99019a5c8L, 1173}, {0xcecb8f27f4200f3aL, 1176}, {0x813f3978f8940984L, 1180}, {0xa18f07d736b90be5L, 1183}, {0xc9f2c9cd04674edeL, 1186}, {0xfc6f7c4045812296L, 1189}, {0x9dc5ada82b70b59dL, 1193}, {0xc5371912364ce305L, 1196}, {0xf684df56c3e01bc6L, 1199}, {0x9a130b963a6c115cL, 1203}, {0xc097ce7bc90715b3L, 1206}, {0xf0bdc21abb48db20L, 1209}, {0x96769950b50d88f4L, 1213}, {0xbc143fa4e250eb31L, 1216}, {0xeb194f8e1ae525fdL, 1219}, {0x92efd1b8d0cf37beL, 1223}, {0xb7abc627050305adL, 1226}, {0xe596b7b0c643c719L, 1229}, {0x8f7e32ce7bea5c6fL, 1233}, {0xb35dbf821ae4f38bL, 1236}, {0xe0352f62a19e306eL, 1239}, {0x8c213d9da502de45L, 1243}, {0xaf298d050e4395d6L, 1246}, {0xdaf3f04651d47b4cL, 1249}, {0x88d8762bf324cd0fL, 1253}, {0xab0e93b6efee0053L, 1256}, {0xd5d238a4abe98068L, 1259}, {0x85a36366eb71f041L, 1263}, {0xa70c3c40a64e6c51L, 1266}, {0xd0cf4b50cfe20765L, 1269}, {0x82818f1281ed449fL, 1273}, {0xa321f2d7226895c7L, 1276}, {0xcbea6f8ceb02bb39L, 1279}, {0xfee50b7025c36a08L, 1282}, {0x9f4f2726179a2245L, 1286}, {0xc722f0ef9d80aad6L, 1289}, {0xf8ebad2b84e0d58bL, 1292}, {0x9b934c3b330c8577L, 1296}, {0xc2781f49ffcfa6d5L, 1299}, {0xf316271c7fc3908aL, 1302}, {0x97edd871cfda3a56L, 1306}, {0xbde94e8e43d0c8ecL, 1309}, {0xed63a231d4c4fb27L, 1312}, {0x945e455f24fb1cf8L, 1316}, {0xb975d6b6ee39e436L, 1319}, {0xe7d34c64a9c85d44L, 1322}, {0x90e40fbeea1d3a4aL, 1326}, {0xb51d13aea4a488ddL, 1329}, {0xe264589a4dcdab14L, 1332}, {0x8d7eb76070a08aecL, 1336}, {0xb0de65388cc8ada8L, 1339}, {0xdd15fe86affad912L, 1342}, {0x8a2dbf142dfcc7abL, 1346}, {0xacb92ed9397bf996L, 1349}, {0xd7e77a8f87daf7fbL, 1352}, {0x86f0ac99b4e8dafdL, 1356}, {0xa8acd7c0222311bcL, 1359}, {0xd2d80db02aabd62bL, 1362}, {0x83c7088e1aab65dbL, 1366}, {0xa4b8cab1a1563f52L, 1369}, {0xcde6fd5e09abcf26L, 1372}, {0x80b05e5ac60b6178L, 1376}, {0xa0dc75f1778e39d6L, 1379}, {0xc913936dd571c84cL, 1382}, {0xfb5878494ace3a5fL, 1385}, {0x9d174b2dcec0e47bL, 1389}, {0xc45d1df942711d9aL, 1392}, {0xf5746577930d6500L, 1395}, {0x9968bf6abbe85f20L, 1399}, {0xbfc2ef456ae276e8L, 1402}, {0xefb3ab16c59b14a2L, 1405}, {0x95d04aee3b80ece5L, 1409}, {0xbb445da9ca61281fL, 1412}, {0xea1575143cf97226L, 1415}, {0x924d692ca61be758L, 1419}, {0xb6e0c377cfa2e12eL, 1422}, {0xe498f455c38b997aL, 1425}, {0x8edf98b59a373fecL, 1429}, {0xb2977ee300c50fe7L, 1432}, {0xdf3d5e9bc0f653e1L, 1435}, {0x8b865b215899f46cL, 1439}, {0xae67f1e9aec07187L, 1442}, {0xda01ee641a708de9L, 1445}, {0x884134fe908658b2L, 1449}, {0xaa51823e34a7eedeL, 1452}, {0xd4e5e2cdc1d1ea96L, 1455}, {0x850fadc09923329eL, 1459}, {0xa6539930bf6bff45L, 1462}, {0xcfe87f7cef46ff16L, 1465}, {0x81f14fae158c5f6eL, 1469}, {0xa26da3999aef7749L, 1472}, {0xcb090c8001ab551cL, 1475}, {0xfdcb4fa002162a63L, 1478}, {0x9e9f11c4014dda7eL, 1482}, {0xc646d63501a1511dL, 1485}, {0xf7d88bc24209a565L, 1488}, {0x9ae757596946075fL, 1492}, {0xc1a12d2fc3978937L, 1495}, {0xf209787bb47d6b84L, 1498}, {0x9745eb4d50ce6332L, 1502}, {0xbd176620a501fbffL, 1505}, {0xec5d3fa8ce427affL, 1508}, {0x93ba47c980e98cdfL, 1512}, {0xb8a8d9bbe123f017L, 1515}, {0xe6d3102ad96cec1dL, 1518}, {0x9043ea1ac7e41392L, 1522}, {0xb454e4a179dd1877L, 1525}, {0xe16a1dc9d8545e94L, 1528}, {0x8ce2529e2734bb1dL, 1532}, {0xb01ae745b101e9e4L, 1535}, {0xdc21a1171d42645dL, 1538}, {0x899504ae72497ebaL, 1542}, {0xabfa45da0edbde69L, 1545}, {0xd6f8d7509292d603L, 1548}, {0x865b86925b9bc5c2L, 1552}, {0xa7f26836f282b732L, 1555}, {0xd1ef0244af2364ffL, 1558}, {0x8335616aed761f1fL, 1562}, {0xa402b9c5a8d3a6e7L, 1565}, {0xcd036837130890a1L, 1568}, {0x802221226be55a64L, 1572}, {0xa02aa96b06deb0fdL, 1575}, {0xc83553c5c8965d3dL, 1578}, {0xfa42a8b73abbf48cL, 1581}, {0x9c69a97284b578d7L, 1585}, {0xc38413cf25e2d70dL, 1588}, {0xf46518c2ef5b8cd1L, 1591}, {0x98bf2f79d5993802L, 1595}, {0xbeeefb584aff8603L, 1598}, {0xeeaaba2e5dbf6784L, 1601}, {0x952ab45cfa97a0b2L, 1605}, {0xba756174393d88dfL, 1608}, {0xe912b9d1478ceb17L, 1611}, {0x91abb422ccb812eeL, 1615}, {0xb616a12b7fe617aaL, 1618}, {0xe39c49765fdf9d94L, 1621}, {0x8e41ade9fbebc27dL, 1625}, {0xb1d219647ae6b31cL, 1628}, {0xde469fbd99a05fe3L, 1631}, {0x8aec23d680043beeL, 1635}, {0xada72ccc20054ae9L, 1638}, {0xd910f7ff28069da4L, 1641}, {0x87aa9aff79042286L, 1645}, {0xa99541bf57452b28L, 1648}, {0xd3fa922f2d1675f2L, 1651}, {0x847c9b5d7c2e09b7L, 1655}, {0xa59bc234db398c25L, 1658}, {0xcf02b2c21207ef2eL, 1661}, {0x8161afb94b44f57dL, 1665}, {0xa1ba1ba79e1632dcL, 1668}, {0xca28a291859bbf93L, 1671}, {0xfcb2cb35e702af78L, 1674}, {0x9defbf01b061adabL, 1678}, {0xc56baec21c7a1916L, 1681}, {0xf6c69a72a3989f5bL, 1684}, {0x9a3c2087a63f6399L, 1688}, {0xc0cb28a98fcf3c7fL, 1691}, {0xf0fdf2d3f3c30b9fL, 1694}, {0x969eb7c47859e743L, 1698}, {0xbc4665b596706114L, 1701}, {0xeb57ff22fc0c7959L, 1704}, {0x9316ff75dd87cbd8L, 1708}, {0xb7dcbf5354e9beceL, 1711}, {0xe5d3ef282a242e81L, 1714}, {0x8fa475791a569d10L, 1718}, {0xb38d92d760ec4455L, 1721}, {0xe070f78d3927556aL, 1724}, {0x8c469ab843b89562L, 1728}, {0xaf58416654a6babbL, 1731}, {0xdb2e51bfe9d0696aL, 1734}, {0x88fcf317f22241e2L, 1738}, {0xab3c2fddeeaad25aL, 1741}, {0xd60b3bd56a5586f1L, 1744}, {0x85c7056562757456L, 1748}, {0xa738c6bebb12d16cL, 1751}, {0xd106f86e69d785c7L, 1754}, {0x82a45b450226b39cL, 1758}, {0xa34d721642b06084L, 1761}, {0xcc20ce9bd35c78a5L, 1764}, {0xff290242c83396ceL, 1767}, {0x9f79a169bd203e41L, 1771}, {0xc75809c42c684dd1L, 1774}, {0xf92e0c3537826145L, 1777}, {0x9bbcc7a142b17ccbL, 1781}, {0xc2abf989935ddbfeL, 1784}, {0xf356f7ebf83552feL, 1787}, {0x98165af37b2153deL, 1791}, {0xbe1bf1b059e9a8d6L, 1794}, {0xeda2ee1c7064130cL, 1797}, {0x9485d4d1c63e8be7L, 1801}, {0xb9a74a0637ce2ee1L, 1804}, {0xe8111c87c5c1ba99L, 1807}, {0x910ab1d4db9914a0L, 1811}, {0xb54d5e4a127f59c8L, 1814}, {0xe2a0b5dc971f303aL, 1817}, {0x8da471a9de737e24L, 1821}, {0xb10d8e1456105dadL, 1824}, {0xdd50f1996b947518L, 1827}, {0x8a5296ffe33cc92fL, 1831}, {0xace73cbfdc0bfb7bL, 1834}, {0xd8210befd30efa5aL, 1837}, {0x8714a775e3e95c78L, 1841}, {0xa8d9d1535ce3b396L, 1844}, {0xd31045a8341ca07cL, 1847}, {0x83ea2b892091e44dL, 1851}, {0xa4e4b66b68b65d60L, 1854}, {0xce1de40642e3f4b9L, 1857}, {0x80d2ae83e9ce78f3L, 1861}, {0xa1075a24e4421730L, 1864}, {0xc94930ae1d529cfcL, 1867}, {0xfb9b7cd9a4a7443cL, 1870}, {0x9d412e0806e88aa5L, 1874}, {0xc491798a08a2ad4eL, 1877}, {0xf5b5d7ec8acb58a2L, 1880}, {0x9991a6f3d6bf1765L, 1884}, {0xbff610b0cc6edd3fL, 1887}, {0xeff394dcff8a948eL, 1890}, {0x95f83d0a1fb69cd9L, 1894}, {0xbb764c4ca7a4440fL, 1897}, {0xea53df5fd18d5513L, 1900}, {0x92746b9be2f8552cL, 1904}, {0xb7118682dbb66a77L, 1907}, {0xe4d5e82392a40515L, 1910}, {0x8f05b1163ba6832dL, 1914}, {0xb2c71d5bca9023f8L, 1917}, {0xdf78e4b2bd342cf6L, 1920}, {0x8bab8eefb6409c1aL, 1924}, {0xae9672aba3d0c320L, 1927}, {0xda3c0f568cc4f3e8L, 1930}, {0x8865899617fb1871L, 1934}, {0xaa7eebfb9df9de8dL, 1937}, {0xd51ea6fa85785631L, 1940}, {0x8533285c936b35deL, 1944}, {0xa67ff273b8460356L, 1947}, {0xd01fef10a657842cL, 1950}, {0x8213f56a67f6b29bL, 1954}, {0xa298f2c501f45f42L, 1957}, {0xcb3f2f7642717713L, 1960}, {0xfe0efb53d30dd4d7L, 1963}, {0x9ec95d1463e8a506L, 1967}, {0xc67bb4597ce2ce48L, 1970}, {0xf81aa16fdc1b81daL, 1973}, {0x9b10a4e5e9913128L, 1977}, {0xc1d4ce1f63f57d72L, 1980}, {0xf24a01a73cf2dccfL, 1983}, {0x976e41088617ca01L, 1987}, {0xbd49d14aa79dbc82L, 1990}, {0xec9c459d51852ba2L, 1993}, {0x93e1ab8252f33b45L, 1997}, {0xb8da1662e7b00a17L, 2000}, {0xe7109bfba19c0c9dL, 2003}, {0x906a617d450187e2L, 2007}, {0xb484f9dc9641e9daL, 2010}, {0xe1a63853bbd26451L, 2013}, {0x8d07e33455637eb2L, 2017}, {0xb049dc016abc5e5fL, 2020}, {0xdc5c5301c56b75f7L, 2023}, {0x89b9b3e11b6329baL, 2027}, {0xac2820d9623bf429L, 2030}, {0xd732290fbacaf133L, 2033}, {0x867f59a9d4bed6c0L, 2037}, {0xa81f301449ee8c70L, 2040}, {0xd226fc195c6a2f8cL, 2043}, {0x83585d8fd9c25db7L, 2047}, {0xa42e74f3d032f525L, 2050}, {0xcd3a1230c43fb26fL, 2053}, {0x80444b5e7aa7cf85L, 2057}, {0xa0555e361951c366L, 2060}, {0xc86ab5c39fa63440L, 2063}, {0xfa856334878fc150L, 2066}, {0x9c935e00d4b9d8d2L, 2070}, {0xc3b8358109e84f07L, 2073}, {0xf4a642e14c6262c8L, 2076}, {0x98e7e9cccfbd7dbdL, 2080}, {0xbf21e44003acdd2cL, 2083}, {0xeeea5d5004981478L, 2086}, {0x95527a5202df0ccbL, 2090}, {0xbaa718e68396cffdL, 2093}, {0xe950df20247c83fdL, 2096}, {0x91d28b7416cdd27eL, 2100}, {0xb6472e511c81471dL, 2103}, {0xe3d8f9e563a198e5L, 2106}, {0x8e679c2f5e44ff8fL, 2110}}; const uint64_t FastDoubleParser::MANTISSA_128[] = {0x419ea3bd35385e2d, 0x52064cac828675b9, 0x7343efebd1940993, 0x1014ebe6c5f90bf8, 0xd41a26e077774ef6, 0x8920b098955522b4, 0x55b46e5f5d5535b0, 0xeb2189f734aa831d, 0xa5e9ec7501d523e4, 0x47b233c92125366e, 0x999ec0bb696e840a, 0xc00670ea43ca250d, 0x380406926a5e5728, 0xc605083704f5ecf2, 0xf7864a44c633682e, 0x7ab3ee6afbe0211d, 0x5960ea05bad82964, 0x6fb92487298e33bd, 0xa5d3b6d479f8e056, 0x8f48a4899877186c, 0x331acdabfe94de87, 0x9ff0c08b7f1d0b14, 0x7ecf0ae5ee44dd9, 0xc9e82cd9f69d6150, 0xbe311c083a225cd2, 0x6dbd630a48aaf406, 0x92cbbccdad5b108, 0x25bbf56008c58ea5, 0xaf2af2b80af6f24e, 0x1af5af660db4aee1, 0x50d98d9fc890ed4d, 0xe50ff107bab528a0, 0x1e53ed49a96272c8, 0x25e8e89c13bb0f7a, 0x77b191618c54e9ac, 0xd59df5b9ef6a2417, 0x4b0573286b44ad1d, 0x4ee367f9430aec32, 0x229c41f793cda73f, 0x6b43527578c1110f, 0x830a13896b78aaa9, 0x23cc986bc656d553, 0x2cbfbe86b7ec8aa8, 0x7bf7d71432f3d6a9, 0xdaf5ccd93fb0cc53, 0xd1b3400f8f9cff68, 0x23100809b9c21fa1, 0xabd40a0c2832a78a, 0x16c90c8f323f516c, 0xae3da7d97f6792e3, 0x99cd11cfdf41779c, 0x40405643d711d583, 0x482835ea666b2572, 0xda3243650005eecf, 0x90bed43e40076a82, 0x5a7744a6e804a291, 0x711515d0a205cb36, 0xd5a5b44ca873e03, 0xe858790afe9486c2, 0x626e974dbe39a872, 0xfb0a3d212dc8128f, 0x7ce66634bc9d0b99, 0x1c1fffc1ebc44e80, 0xa327ffb266b56220, 0x4bf1ff9f0062baa8, 0x6f773fc3603db4a9, 0xcb550fb4384d21d3, 0x7e2a53a146606a48, 0x2eda7444cbfc426d, 0xfa911155fefb5308, 0x793555ab7eba27ca, 0x4bc1558b2f3458de, 0x9eb1aaedfb016f16, 0x465e15a979c1cadc, 0xbfacd89ec191ec9, 0xcef980ec671f667b, 0x82b7e12780e7401a, 0xd1b2ecb8b0908810, 0x861fa7e6dcb4aa15, 0x67a791e093e1d49a, 0xe0c8bb2c5c6d24e0, 0x58fae9f773886e18, 0xaf39a475506a899e, 0x6d8406c952429603, 0xc8e5087ba6d33b83, 0xfb1e4a9a90880a64, 0x5cf2eea09a55067f, 0xf42faa48c0ea481e, 0xf13b94daf124da26, 0x76c53d08d6b70858, 0x54768c4b0c64ca6e, 0xa9942f5dcf7dfd09, 0xd3f93b35435d7c4c, 0xc47bc5014a1a6daf, 0x359ab6419ca1091b, 0xc30163d203c94b62, 0x79e0de63425dcf1d, 0x985915fc12f542e4, 0x3e6f5b7b17b2939d, 0xa705992ceecf9c42, 0x50c6ff782a838353, 0xa4f8bf5635246428, 0x871b7795e136be99, 0x28e2557b59846e3f, 0x331aeada2fe589cf, 0x3ff0d2c85def7621, 0xfed077a756b53a9, 0xd3e8495912c62894, 0x64712dd7abbbd95c, 0xbd8d794d96aacfb3, 0xecf0d7a0fc5583a0, 0xf41686c49db57244, 0x311c2875c522ced5, 0x7d633293366b828b, 0xae5dff9c02033197, 0xd9f57f830283fdfc, 0xd072df63c324fd7b, 0x4247cb9e59f71e6d, 0x52d9be85f074e608, 0x67902e276c921f8b, 0xba1cd8a3db53b6, 0x80e8a40eccd228a4, 0x6122cd128006b2cd, 0x796b805720085f81, 0xcbe3303674053bb0, 0xbedbfc4411068a9c, 0xee92fb5515482d44, 0x751bdd152d4d1c4a, 0xd262d45a78a0635d, 0x86fb897116c87c34, 0xd45d35e6ae3d4da0, 0x8974836059cca109, 0x2bd1a438703fc94b, 0x7b6306a34627ddcf, 0x1a3bc84c17b1d542, 0x20caba5f1d9e4a93, 0x547eb47b7282ee9c, 0xe99e619a4f23aa43, 0x6405fa00e2ec94d4, 0xde83bc408dd3dd04, 0x9624ab50b148d445, 0x3badd624dd9b0957, 0xe54ca5d70a80e5d6, 0x5e9fcf4ccd211f4c, 0x7647c3200069671f, 0x29ecd9f40041e073, 0xf468107100525890, 0x7182148d4066eeb4, 0xc6f14cd848405530, 0xb8ada00e5a506a7c, 0xa6d90811f0e4851c, 0x908f4a166d1da663, 0x9a598e4e043287fe, 0x40eff1e1853f29fd, 0xd12bee59e68ef47c, 0x82bb74f8301958ce, 0xe36a52363c1faf01, 0xdc44e6c3cb279ac1, 0x29ab103a5ef8c0b9, 0x7415d448f6b6f0e7, 0x111b495b3464ad21, 0xcab10dd900beec34, 0x3d5d514f40eea742, 0xcb4a5a3112a5112, 0x47f0e785eaba72ab, 0x59ed216765690f56, 0x306869c13ec3532c, 0x1e414218c73a13fb, 0xe5d1929ef90898fa, 0xdf45f746b74abf39, 0x6b8bba8c328eb783, 0x66ea92f3f326564, 0xc80a537b0efefebd, 0xbd06742ce95f5f36, 0x2c48113823b73704, 0xf75a15862ca504c5, 0x9a984d73dbe722fb, 0xc13e60d0d2e0ebba, 0x318df905079926a8, 0xfdf17746497f7052, 0xfeb6ea8bedefa633, 0xfe64a52ee96b8fc0, 0x3dfdce7aa3c673b0, 0x6bea10ca65c084e, 0x486e494fcff30a62, 0x5a89dba3c3efccfa, 0xf89629465a75e01c, 0xf6bbb397f1135823, 0x746aa07ded582e2c, 0xa8c2a44eb4571cdc, 0x92f34d62616ce413, 0x77b020baf9c81d17, 0xace1474dc1d122e, 0xd819992132456ba, 0x10e1fff697ed6c69, 0xca8d3ffa1ef463c1, 0xbd308ff8a6b17cb2, 0xac7cb3f6d05ddbde, 0x6bcdf07a423aa96b, 0x86c16c98d2c953c6, 0xe871c7bf077ba8b7, 0x11471cd764ad4972, 0xd598e40d3dd89bcf, 0x4aff1d108d4ec2c3, 0xcedf722a585139ba, 0xc2974eb4ee658828, 0x733d226229feea32, 0x806357d5a3f525f, 0xca07c2dcb0cf26f7, 0xfc89b393dd02f0b5, 0xbbac2078d443ace2, 0xd54b944b84aa4c0d, 0xa9e795e65d4df11, 0x4d4617b5ff4a16d5, 0x504bced1bf8e4e45, 0xe45ec2862f71e1d6, 0x5d767327bb4e5a4c, 0x3a6a07f8d510f86f, 0x890489f70a55368b, 0x2b45ac74ccea842e, 0x3b0b8bc90012929d, 0x9ce6ebb40173744, 0xcc420a6a101d0515, 0x9fa946824a12232d, 0x47939822dc96abf9, 0x59787e2b93bc56f7, 0x57eb4edb3c55b65a, 0xede622920b6b23f1, 0xe95fab368e45eced, 0x11dbcb0218ebb414, 0xd652bdc29f26a119, 0x4be76d3346f0495f, 0x6f70a4400c562ddb, 0xcb4ccd500f6bb952, 0x7e2000a41346a7a7, 0x8ed400668c0c28c8, 0x728900802f0f32fa, 0x4f2b40a03ad2ffb9, 0xe2f610c84987bfa8, 0xdd9ca7d2df4d7c9, 0x91503d1c79720dbb, 0x75a44c6397ce912a, 0xc986afbe3ee11aba, 0xfbe85badce996168, 0xfae27299423fb9c3, 0xdccd879fc967d41a, 0x5400e987bbc1c920, 0x290123e9aab23b68, 0xf9a0b6720aaf6521, 0xf808e40e8d5b3e69, 0xb60b1d1230b20e04, 0xb1c6f22b5e6f48c2, 0x1e38aeb6360b1af3, 0x25c6da63c38de1b0, 0x579c487e5a38ad0e, 0x2d835a9df0c6d851, 0xf8e431456cf88e65, 0x1b8e9ecb641b58ff, 0xe272467e3d222f3f, 0x5b0ed81dcc6abb0f, 0x98e947129fc2b4e9, 0x3f2398d747b36224, 0x8eec7f0d19a03aad, 0x1953cf68300424ac, 0x5fa8c3423c052dd7, 0x3792f412cb06794d, 0xe2bbd88bbee40bd0, 0x5b6aceaeae9d0ec4, 0xf245825a5a445275, 0xeed6e2f0f0d56712, 0x55464dd69685606b, 0xaa97e14c3c26b886, 0xd53dd99f4b3066a8, 0xe546a8038efe4029, 0xde98520472bdd033, 0x963e66858f6d4440, 0xdde7001379a44aa8, 0x5560c018580d5d52, 0xaab8f01e6e10b4a6, 0xcab3961304ca70e8, 0x3d607b97c5fd0d22, 0x8cb89a7db77c506a, 0x77f3608e92adb242, 0x55f038b237591ed3, 0x6b6c46dec52f6688, 0x2323ac4b3b3da015, 0xabec975e0a0d081a, 0x96e7bd358c904a21, 0x7e50d64177da2e54, 0xdde50bd1d5d0b9e9, 0x955e4ec64b44e864, 0xbd5af13bef0b113e, 0xecb1ad8aeacdd58e, 0x67de18eda5814af2, 0x80eacf948770ced7, 0xa1258379a94d028d, 0x96ee45813a04330, 0x8bca9d6e188853fc, 0x775ea264cf55347d, 0x95364afe032a819d, 0x3a83ddbd83f52204, 0xc4926a9672793542, 0x75b7053c0f178293, 0x5324c68b12dd6338, 0xd3f6fc16ebca5e03, 0x88f4bb1ca6bcf584, 0x2b31e9e3d06c32e5, 0x3aff322e62439fcf, 0x9befeb9fad487c2, 0x4c2ebe687989a9b3, 0xf9d37014bf60a10, 0x538484c19ef38c94, 0x2865a5f206b06fb9, 0xf93f87b7442e45d3, 0xf78f69a51539d748, 0xb573440e5a884d1b, 0x31680a88f8953030, 0xfdc20d2b36ba7c3d, 0x3d32907604691b4c, 0xa63f9a49c2c1b10f, 0xfcf80dc33721d53, 0xd3c36113404ea4a8, 0x645a1cac083126e9, 0x3d70a3d70a3d70a3, 0xcccccccccccccccc, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4000000000000000, 0x5000000000000000, 0xa400000000000000, 0x4d00000000000000, 0xf020000000000000, 0x6c28000000000000, 0xc732000000000000, 0x3c7f400000000000, 0x4b9f100000000000, 0x1e86d40000000000, 0x1314448000000000, 0x17d955a000000000, 0x5dcfab0800000000, 0x5aa1cae500000000, 0xf14a3d9e40000000, 0x6d9ccd05d0000000, 0xe4820023a2000000, 0xdda2802c8a800000, 0xd50b2037ad200000, 0x4526f422cc340000, 0x9670b12b7f410000, 0x3c0cdd765f114000, 0xa5880a69fb6ac800, 0x8eea0d047a457a00, 0x72a4904598d6d880, 0x47a6da2b7f864750, 0x999090b65f67d924, 0xfff4b4e3f741cf6d, 0xbff8f10e7a8921a4, 0xaff72d52192b6a0d, 0x9bf4f8a69f764490, 0x2f236d04753d5b4, 0x1d762422c946590, 0x424d3ad2b7b97ef5, 0xd2e0898765a7deb2, 0x63cc55f49f88eb2f, 0x3cbf6b71c76b25fb, 0x8bef464e3945ef7a, 0x97758bf0e3cbb5ac, 0x3d52eeed1cbea317, 0x4ca7aaa863ee4bdd, 0x8fe8caa93e74ef6a, 0xb3e2fd538e122b44, 0x60dbbca87196b616, 0xbc8955e946fe31cd, 0x6babab6398bdbe41, 0xc696963c7eed2dd1, 0xfc1e1de5cf543ca2, 0x3b25a55f43294bcb, 0x49ef0eb713f39ebe, 0x6e3569326c784337, 0x49c2c37f07965404, 0xdc33745ec97be906, 0x69a028bb3ded71a3, 0xc40832ea0d68ce0c, 0xf50a3fa490c30190, 0x792667c6da79e0fa, 0x577001b891185938, 0xed4c0226b55e6f86, 0x544f8158315b05b4, 0x696361ae3db1c721, 0x3bc3a19cd1e38e9, 0x4ab48a04065c723, 0x62eb0d64283f9c76, 0x3ba5d0bd324f8394, 0xca8f44ec7ee36479, 0x7e998b13cf4e1ecb, 0x9e3fedd8c321a67e, 0xc5cfe94ef3ea101e, 0xbba1f1d158724a12, 0x2a8a6e45ae8edc97, 0xf52d09d71a3293bd, 0x593c2626705f9c56, 0x6f8b2fb00c77836c, 0xb6dfb9c0f956447, 0x4724bd4189bd5eac, 0x58edec91ec2cb657, 0x2f2967b66737e3ed, 0xbd79e0d20082ee74, 0xecd8590680a3aa11, 0xe80e6f4820cc9495, 0x3109058d147fdcdd, 0xbd4b46f0599fd415, 0x6c9e18ac7007c91a, 0x3e2cf6bc604ddb0, 0x84db8346b786151c, 0xe612641865679a63, 0x4fcb7e8f3f60c07e, 0xe3be5e330f38f09d, 0x5cadf5bfd3072cc5, 0x73d9732fc7c8f7f6, 0x2867e7fddcdd9afa, 0xb281e1fd541501b8, 0x1f225a7ca91a4226, 0x3375788de9b06958, 0x52d6b1641c83ae, 0xc0678c5dbd23a49a, 0xf840b7ba963646e0, 0xb650e5a93bc3d898, 0xa3e51f138ab4cebe, 0xc66f336c36b10137, 0xb80b0047445d4184, 0xa60dc059157491e5, 0x87c89837ad68db2f, 0x29babe4598c311fb, 0xf4296dd6fef3d67a, 0x1899e4a65f58660c, 0x5ec05dcff72e7f8f, 0x76707543f4fa1f73, 0x6a06494a791c53a8, 0x487db9d17636892, 0x45a9d2845d3c42b6, 0xb8a2392ba45a9b2, 0x8e6cac7768d7141e, 0x3207d795430cd926, 0x7f44e6bd49e807b8, 0x5f16206c9c6209a6, 0x36dba887c37a8c0f, 0xc2494954da2c9789, 0xf2db9baa10b7bd6c, 0x6f92829494e5acc7, 0xcb772339ba1f17f9, 0xff2a760414536efb, 0xfef5138519684aba, 0x7eb258665fc25d69, 0xef2f773ffbd97a61, 0xaafb550ffacfd8fa, 0x95ba2a53f983cf38, 0xdd945a747bf26183, 0x94f971119aeef9e4, 0x7a37cd5601aab85d, 0xac62e055c10ab33a, 0x577b986b314d6009, 0xed5a7e85fda0b80b, 0x14588f13be847307, 0x596eb2d8ae258fc8, 0x6fca5f8ed9aef3bb, 0x25de7bb9480d5854, 0xaf561aa79a10ae6a, 0x1b2ba1518094da04, 0x90fb44d2f05d0842, 0x353a1607ac744a53, 0x42889b8997915ce8, 0x69956135febada11, 0x43fab9837e699095, 0x94f967e45e03f4bb, 0x1d1be0eebac278f5, 0x6462d92a69731732, 0x7d7b8f7503cfdcfe, 0x5cda735244c3d43e, 0x3a0888136afa64a7, 0x88aaa1845b8fdd0, 0x8aad549e57273d45, 0x36ac54e2f678864b, 0x84576a1bb416a7dd, 0x656d44a2a11c51d5, 0x9f644ae5a4b1b325, 0x873d5d9f0dde1fee, 0xa90cb506d155a7ea, 0x9a7f12442d588f2, 0xc11ed6d538aeb2f, 0x8f1668c8a86da5fa, 0xf96e017d694487bc, 0x37c981dcc395a9ac, 0x85bbe253f47b1417, 0x93956d7478ccec8e, 0x387ac8d1970027b2, 0x6997b05fcc0319e, 0x441fece3bdf81f03, 0xd527e81cad7626c3, 0x8a71e223d8d3b074, 0xf6872d5667844e49, 0xb428f8ac016561db, 0xe13336d701beba52, 0xecc0024661173473, 0x27f002d7f95d0190, 0x31ec038df7b441f4, 0x7e67047175a15271, 0xf0062c6e984d386, 0x52c07b78a3e60868, 0xa7709a56ccdf8a82, 0x88a66076400bb691, 0x6acff893d00ea435, 0x583f6b8c4124d43, 0xc3727a337a8b704a, 0x744f18c0592e4c5c, 0x1162def06f79df73, 0x8addcb5645ac2ba8, 0x6d953e2bd7173692, 0xc8fa8db6ccdd0437, 0x1d9c9892400a22a2, 0x2503beb6d00cab4b, 0x2e44ae64840fd61d, 0x5ceaecfed289e5d2, 0x7425a83e872c5f47, 0xd12f124e28f77719, 0x82bd6b70d99aaa6f, 0x636cc64d1001550b, 0x3c47f7e05401aa4e, 0x65acfaec34810a71, 0x7f1839a741a14d0d, 0x1ede48111209a050, 0x934aed0aab460432, 0xf81da84d5617853f, 0x36251260ab9d668e, 0xc1d72b7c6b426019, 0xb24cf65b8612f81f, 0xdee033f26797b627, 0x169840ef017da3b1, 0x8e1f289560ee864e, 0xf1a6f2bab92a27e2, 0xae10af696774b1db, 0xacca6da1e0a8ef29, 0x17fd090a58d32af3, 0xddfc4b4cef07f5b0, 0x4abdaf101564f98e, 0x9d6d1ad41abe37f1, 0x84c86189216dc5ed, 0x32fd3cf5b4e49bb4, 0x3fbc8c33221dc2a1, 0xfabaf3feaa5334a, 0x29cb4d87f2a7400e, 0x743e20e9ef511012, 0x914da9246b255416, 0x1ad089b6c2f7548e, 0xa184ac2473b529b1, 0xc9e5d72d90a2741e, 0x7e2fa67c7a658892, 0xddbb901b98feeab7, 0x552a74227f3ea565, 0xd53a88958f87275f, 0x8a892abaf368f137, 0x2d2b7569b0432d85, 0x9c3b29620e29fc73, 0x8349f3ba91b47b8f, 0x241c70a936219a73, 0xed238cd383aa0110, 0xf4363804324a40aa, 0xb143c6053edcd0d5, 0xdd94b7868e94050a, 0xca7cf2b4191c8326, 0xfd1c2f611f63a3f0, 0xbc633b39673c8cec, 0xd5be0503e085d813, 0x4b2d8644d8a74e18, 0xddf8e7d60ed1219e, 0xcabb90e5c942b503, 0x3d6a751f3b936243, 0xcc512670a783ad4, 0x27fb2b80668b24c5, 0xb1f9f660802dedf6, 0x5e7873f8a0396973, 0xdb0b487b6423e1e8, 0x91ce1a9a3d2cda62, 0x7641a140cc7810fb, 0xa9e904c87fcb0a9d, 0x546345fa9fbdcd44, 0xa97c177947ad4095, 0x49ed8eabcccc485d, 0x5c68f256bfff5a74, 0x73832eec6fff3111, 0xc831fd53c5ff7eab, 0xba3e7ca8b77f5e55, 0x28ce1bd2e55f35eb, 0x7980d163cf5b81b3, 0xd7e105bcc332621f, 0x8dd9472bf3fefaa7, 0xb14f98f6f0feb951, 0x6ed1bf9a569f33d3, 0xa862f80ec4700c8, 0xcd27bb612758c0fa, 0x8038d51cb897789c, 0xe0470a63e6bd56c3, 0x1858ccfce06cac74, 0xf37801e0c43ebc8, 0xd30560258f54e6ba, 0x47c6b82ef32a2069, 0x4cdc331d57fa5441, 0xe0133fe4adf8e952, 0x58180fddd97723a6, 0x570f09eaa7ea7648}; } // namespace terrier::execution::util
79.437267
120
0.399315
1cb18eb87cbbd47a02724d9bfd9dcc47a2423df1
17,332
cpp
C++
src/tri-prong.cpp
jinqiangshou/Tri-prong
394913b293b8a94edd9717eab5c6d0cbe11f36db
[ "Apache-2.0" ]
1
2015-11-08T10:36:32.000Z
2015-11-08T10:36:32.000Z
src/tri-prong.cpp
jinqiangshou/Tri-prong
394913b293b8a94edd9717eab5c6d0cbe11f36db
[ "Apache-2.0" ]
null
null
null
src/tri-prong.cpp
jinqiangshou/Tri-prong
394913b293b8a94edd9717eab5c6d0cbe11f36db
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <getopt.h> #include <sys/types.h> #include <sys/epoll.h> #include <sys/time.h> #include <sys/select.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/in.h> #include <netdb.h> #include <pthread.h> #include <time.h> #include <math.h> #include <errno.h> #include <fcntl.h> #include "common_constant.h" #include "common_struct.h" #include "auxiliary_function.h" #include "build_request.h" #include "output.h" #include "version.h" #include "parse_url.h" int fd[2]; //fd用于conn和send之间的通信 int fd2[2]; //fd2用于send和recv之间的通信 static char* tool_name = NULL; //The title of this program //以下三个参数的关系为 press_rate * press_time = press_number //命令行参数中只能指定两个,另一个计算得出 int press_rate = 0; //单位 request per second,每秒请求数 int press_time = 0; //单位 秒,压测的时间 int press_number = 0; //单位 request,压测的次数 double press_interval = 1000000.0; //该数值等于press_rate的倒数,单位为 微秒 static full_url_list url_list = { {NULL}, 0 }; //从参数或文件中读取的完整url列表 const struct linger so_linger = { 1, 0 }; //设置描述符快速回收 static parameters_set parameters = { 0, 0, {NULL}, 0 }; //存储所有的参数信息 static test_connect_ontime connect_ontime = {{0,0}, {0,0}}; //用于计算所有connect的准时率 request_data *test_data; //长度为测试总数的数组,存储每次测试的数据 static final_statistics *overall_stat; //最终将会被输出到屏幕上的数据 static const struct option long_options[] = { {"rate", required_argument, NULL, 'r'}, {"time", required_argument, NULL, 't'}, {"url", required_argument, NULL, 'u'}, {NULL, 0, NULL, 0} }; char http_request[MAX_REQUEST_SIZE] = {0}; /* 计算下一个start_this的值(开始发送的值),存储在第一个参数t中 */ void next_send_time( struct timeval *t, const timeval *start_time, int conn_count ) { int how_many_1s = conn_count / press_rate; int time_within_1s = (int)( (conn_count % press_rate) * press_interval ); if( start_time->tv_usec + time_within_1s > 1000000 ) { t->tv_sec = start_time->tv_sec + how_many_1s + 1; t->tv_usec = start_time->tv_usec + time_within_1s - 1000000; }else { t->tv_sec = start_time->tv_sec + how_many_1s; t->tv_usec = start_time->tv_usec + time_within_1s; } } //返回值int,如果为0,表示sockfd描述符被关闭;如果为1,表示sockfd描述符没有被关闭 int read_socket( int sockfd, char buf[], const int max_buf_len, request_data *reqdata ) { int num = 0; int iret = -1; //用于设置返回值 while( 1 ){ num = recv( sockfd, buf, max_buf_len - 1, 0 ); if( num > 0 ) { //正常接收消息 reqdata->byte_transfered += num; }else if( num == 0 ) { //对端关闭,则本端被动关闭 close( sockfd ); iret = 0; break; }else { //数据读完,后面可能还有数据,暂时不关闭 if ( errno == EAGAIN || errno == EWOULDBLOCK ) { //当前没有数据可读的话,linux出现EAGAIN错误,而EWOULDBLOCK是windows下出现的 //close( sockfd ); iret = 1; break; }else { fprintf( stderr, "ERROR message (from file %s, line %d): recv() error. errno = %d.\n", __FILE__, __LINE__, errno ); exit( 1 ); } } } return iret; } //连接线程 void *thread_conn( void *para ) { int iRet = 0; //用于临时记录connect函数的返回值 int old_option; double timedif; //用于记录dbl_time_diff函数的返回值 struct timeval start_this, start_backup; struct timeval current; struct timespec sleep_time; gettimeofday( &start_this, NULL ); memcpy( &start_backup, &start_this, sizeof(start_this) ); memcpy( &(connect_ontime.test_start), &start_this, sizeof(start_this) ); //用于connect准时率统计 for( int i = 0; i < press_number; i++ ) { /* 新建socket,并connect,然后将socket描述符写入fd[1]管道 */ struct hostent *he; struct sockaddr_in server; if( (he = gethostbyname(parameters.host[0]->host_ip)) == NULL ) { fprintf( stderr, "ERROR message (from file %s, line %d): gethostbyname() error.\n", __FILE__, __LINE__ ); exit( 1 ); } if( (test_data[i].sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) { fprintf( stderr, "ERROR message (from file %s, line %d): socket() error. errno = %d.\n", __FILE__, __LINE__, errno ); exit( 1 ); } bzero( &server, sizeof(server) ); server.sin_family = AF_INET; server.sin_port = htons( parameters.host[0]->port ); server.sin_addr = *( (struct in_addr *)he->h_addr ); //设置socket为非阻塞 old_option = set_nonblock_sock( test_data[i].sockfd ); //设置描述符快速回收 if( setsockopt(test_data[i].sockfd, SOL_SOCKET, SO_LINGER, &so_linger, sizeof(so_linger)) != 0 ) { fprintf( stderr, "ERROR message (from file %s, line %d): setsockopt() error.\n", __FILE__, __LINE__ ); exit( 1 ); } //设置test_data.init_connect字段 gettimeofday( &(test_data[i].init_connect), NULL ); iRet = connect( test_data[i].sockfd, (struct sockaddr *)&server, sizeof(server) ); if( iRet == 0 ) { //连接立即成功,需要处理这种情况 fprintf( stderr, "ERROR message (from file %s, line %d): connect() successes immediately.\n", __FILE__, __LINE__ ); fcntl( test_data[i].sockfd, F_SETFL, old_option ); close( test_data[i].sockfd ); exit( 1 ); }else if( errno != EINPROGRESS ) { //errno不是EINPROGRESS意味着未知错误出现 fprintf( stderr, "ERROR message (from file %s, line %d): connect() error. errno = %d.\n", __FILE__, __LINE__, errno ); exit( 1 ); }else //errno == EINPROGRESS and iRet < 0 { //这种情况是正常现象,将rpp结构体写入管道 request_data *test_data_addr = &( test_data[i] ); write( fd[1], (void *)&test_data_addr, sizeof(void *) ); } gettimeofday( &current, NULL ); timedif = dbl_time_diff( &current, &start_this );//该任务距离理论上开始执行它的时间有多久,即理论上任务执行时间 if( press_interval > timedif ) { //如果还没到发送下一个的时间,则睡眠一会 sleep_time.tv_sec = (int)( floor(press_interval - timedif) + 0.1 ) / 1000000; sleep_time.tv_nsec = ( (int)(floor(press_interval - timedif) + 0.1) % 1000000 ) * 1000; pselect( 0, NULL, NULL, NULL, &sleep_time, NULL); //线程休眠一会 } next_send_time( &start_this, &start_backup, (i+1) ); } gettimeofday( &(connect_ontime.test_end), NULL ); //得到结束时间 close( fd[1] );//关闭管道的写端 return NULL; } //发送线程 void *thread_send( void *para ) { int num, read_count; int time_out_pointer = 0; timeval temptime; //用于临时记录当前时间 request_data *temp_req_data; int epfd_send = epoll_create( MAX_WAIT_EVENT ); addfd_to_epoll2( epfd_send, fd[0], EPOLLIN, (void *)&fd[0] ); int epfd_send_count = 1; //记录epoll中目前监听的文件描述符个数 struct epoll_event events_send[MAX_WAIT_EVENT]; int iret = -1; //用于记录epoll_wait的返回值 int tempfd = -1; //用于临时记录epoll返回的就绪的文件描述符的值 int position = -1; //用于临时记录epoll返回值的就绪文件在test_data数组中的位置 build_http_request( &parameters ); //构造即将要发送的HTTP请求 while( 1 ){ /* 这里的判断是说,epfd_send中是不是已经没有描述符了,如果没有了就退出 */ if( epfd_send_count <= 0 ) { close( fd2[1] ); close( epfd_send ); break; } iret = epoll_wait( epfd_send, events_send, MAX_WAIT_EVENT, MAX_EPOLL_WAIT_TIME ); if( iret > 0 ) { //有东西读到,需要判断是管道事件还是connect事件 for( int i = 0; i < iret; i++ ) { if( (void *)&fd[0] == events_send[i].data.ptr ) { //处理管道可读事件 read_count = read( fd[0], (void *)&temp_req_data, sizeof(void *) ); if( read_count == 0 ) //管道被关闭,所有请求都已经发出了 { delete_from_epoll( epfd_send, fd[0] ); epfd_send_count--; close( fd[0] ); }else if( read_count != sizeof(void *) ) { //读出来的数据不全 fprintf( stderr, "ERROR message (from file %s, line %d): the bytes read from fd[0] is wrong.\n", __FILE__, __LINE__ ); exit( 1 ); }else { //正常读取,将读到的socket加入监听队列 addfd_to_epoll2( epfd_send, temp_req_data->sockfd, EPOLLIN | EPOLLOUT, (void *)temp_req_data ); epfd_send_count++; } }else { //处理socket连接成功事件 gettimeofday( &temptime, NULL );//获得连接成功的时间 temp_req_data = (request_data *)events_send[i].data.ptr; tempfd = temp_req_data->sockfd; if( (events_send[i].events & EPOLLERR) || (events_send[i].events & EPOLLHUP) ) { //epoll出现错误了 temp_req_data->is_connected = -1; //-1表示连接立即出错 delete_from_epoll( epfd_send, tempfd ); epfd_send_count--; close( tempfd ); temp_req_data->sockfd = -1; //表示socket已经关闭 }else if ( (events_send[i].events & EPOLLIN) && (events_send[i].events & EPOLLOUT) ) { //既可读又可写,证明出错了或者已经连接并且有来自服务端的数据,以上情况都认为连接失败 temp_req_data->is_connected = -1; //-1表示连接立即出错 delete_from_epoll( epfd_send, tempfd ); epfd_send_count--; close( tempfd ); temp_req_data->sockfd = -1; //表示socket已经关闭 }else if( events_send[i].events & EPOLLOUT ) { //成功连接,发送请求,然后将描述符从epoll监听队列中删除,并将描述符写入fd2[1] //修改连接成功花费的时间,连接成功标志位,发出请求的时间 temp_req_data->connect_time = uint_time_diff( &temptime, &(temp_req_data->init_connect) ); temp_req_data->is_connected = 1; gettimeofday( &temptime, NULL );//开始发送请求的时间 temp_req_data->start_send_time = uint_time_diff( &temptime, &(temp_req_data->init_connect) ); num = send( tempfd, http_request, strlen(http_request), 0 ); if( num < 0 ) { fprintf( stderr, "ERROR message (from file %s, line %d): send() error. errno = %d.\n", __FILE__, __LINE__, errno ); exit( 1 ); } delete_from_epoll( epfd_send, tempfd ); epfd_send_count--; write( fd2[1], (void *)&temp_req_data, sizeof(void *) ); } } } }else if( iret == 0 ) { //do nothing }else // iret<0 { fprintf( stderr, "ERROR message (from file %s, line %d): epoll_wait() returns negative value. errno = %d.\n", __FILE__, __LINE__, errno ); exit( 1 ); } /* 超时检测环节 */ gettimeofday( &temptime, NULL ); temptime.tv_sec -= REQUEST_TIME_OUT; while( time_out_pointer < press_number && (test_data[time_out_pointer].is_connected == 1 || test_data[time_out_pointer].is_connected == -1) ) { time_out_pointer++; } while( time_out_pointer < press_number && test_data[time_out_pointer].init_connect.tv_sec > 0 && time_compare(&(test_data[time_out_pointer].init_connect), &temptime)>=0 && test_data[time_out_pointer].is_connected == 0 ) { delete_from_epoll( epfd_send, test_data[time_out_pointer].sockfd ); epfd_send_count--; close( test_data[time_out_pointer].sockfd ); test_data[time_out_pointer].sockfd = -1; //表示socket已经关闭 time_out_pointer++; } } return NULL; } //接收线程 void *thread_recv( void *para ) { int read_count; int time_out_pointer = 0; timeval temptime; //用于临时记录时间 unsigned int timedif, timedif2; request_data *temp_req_data; int epfd_recv = epoll_create( MAX_WAIT_EVENT ); addfd_to_epoll2( epfd_recv, fd2[0], EPOLLIN, (void *)&fd2[0] ); int epfd_recv_count = 1; //记录epoll中目前监听的文件描述符个数 struct epoll_event events_recv[MAX_WAIT_EVENT]; char buf[MAX_RECV_SIZE_ONE_TIME]; //用于处理socket可读事件,读取数据 int iret = -1; //用于记录epoll_wait的返回值 int sock_open = -1; //用于记录read_socket的返回值 int tempfd = -1; //用于临时记录epoll返回的就绪的文件描述符的值 int position = -1; //用于临时记录epoll返回值的就绪文件在test_data数组中的位置 while( 1 ){ if( epfd_recv_count <= 0 ) { //epoll监听队列中已经没有描述符了 close( epfd_recv ); //关闭监听队列,直接退出程序 break; } iret = epoll_wait( epfd_recv, events_recv, MAX_WAIT_EVENT, MAX_EPOLL_WAIT_TIME ); if( iret > 0 ) { gettimeofday( &temptime, NULL );//记录下当前时间 for( int i = 0; i < iret; i++ ) { if( ((void *)&fd2[0]) == events_recv[i].data.ptr ) { //处理管道可读事件 read_count = read( fd2[0], (void *)&temp_req_data, sizeof(void *) ); if( read_count == 0 ) //读取到0字节,fd2[1]被关闭 { delete_from_epoll( epfd_recv, fd2[0] ); epfd_recv_count--; close( fd2[0] ); }else if( read_count != sizeof(void *) ) { //读出来的数据不全 fprintf( stderr, "ERROR message (from file %s, line %d): the bytes read from fd2[0] is wrong.\n", __FILE__, __LINE__ ); exit( 1 ); }else { //正常读取,将读到的socket加入监听队列 addfd_to_epoll2( epfd_recv, temp_req_data->sockfd, EPOLLIN, (void *)temp_req_data ); epfd_recv_count++; } }else{ //处理socket可读事件 temp_req_data = (request_data *)events_recv[i].data.ptr; tempfd = temp_req_data->sockfd; if( (events_recv[i].events & EPOLLERR) || (events_recv[i].events & EPOLLHUP) ) { temp_req_data->is_replied = -1; //-1表示连接立即出错 delete_from_epoll( epfd_recv, tempfd ); epfd_recv_count--; close( tempfd ); temp_req_data->sockfd = -1; }else if( events_recv[i].events & EPOLLIN ) { sock_open = read_socket( tempfd, buf, MAX_RECV_SIZE_ONE_TIME, temp_req_data ); //读取socket //记录数据读取完毕的时间,如果已经记录过,不需要重复记录 if(temp_req_data->recv_finish_time == 0) { temp_req_data->recv_finish_time = uint_time_diff( &temptime, &(temp_req_data->init_connect) ); } if( temp_req_data->byte_transfered > 0 ) { //如果读到了数据,证明收到回复了 temp_req_data->is_replied = 1; } if( sock_open == 0 ) { //tempfd已经被关闭 delete_from_epoll( epfd_recv, tempfd ); temp_req_data->sockfd = -1; //-1表示该socket已经关闭 epfd_recv_count--; } } } } }else if( iret == 0 ) { // do nothing }else // iret < 0 { fprintf( stderr, "ERROR message (from file %s, line %d): epoll_wait() returns negative value. errno = %d.\n", __FILE__, __LINE__, errno ); exit( 1 ); } /* 超时检测环节 */ gettimeofday( &temptime, NULL ); while( time_out_pointer < press_number ) { if( test_data[time_out_pointer].init_connect.tv_sec != 0 ) { //该链接已经调用过connect timedif = uint_time_diff( &temptime, &(test_data[time_out_pointer].init_connect) ); timedif2 = uint_time_diff( &temptime, &(test_data[time_out_pointer].init_connect) ) - test_data[time_out_pointer].recv_finish_time; if( test_data[time_out_pointer].is_replied == -1 || test_data[time_out_pointer].sockfd == -1 ) { //已经出错了或者sockfd已经用完被关闭了 time_out_pointer++; }else if( test_data[time_out_pointer].is_replied == 0 && timedif < REQUEST_TIME_OUT * 1000000 ) { //没收到过回复,还没超时 break; }else if( test_data[time_out_pointer].is_replied == 1 && timedif < REQUEST_TIME_OUT * 1000000 && timedif2 < REQUEST_EXPIRE_TIME ) { //收到过回复,还没超时 break; }else if( test_data[time_out_pointer].is_replied == 0 && timedif >= REQUEST_TIME_OUT * 1000000 ) { //没收到过回复,超时间了 delete_from_epoll( epfd_recv, test_data[time_out_pointer].sockfd ); epfd_recv_count--; close( test_data[time_out_pointer].sockfd ); test_data[time_out_pointer].sockfd = -1; //socket已经关闭 time_out_pointer++; }else if( test_data[time_out_pointer].is_replied == 1 && ( timedif >= REQUEST_TIME_OUT * 1000000 || timedif2 >= REQUEST_EXPIRE_TIME ) ) { //收到过回复,超时间了 delete_from_epoll( epfd_recv, test_data[time_out_pointer].sockfd ); epfd_recv_count--; close( test_data[time_out_pointer].sockfd ); test_data[time_out_pointer].sockfd = -1; //socket已经关闭 time_out_pointer++; } }else { break; } } } return NULL; } //初始化系统参数 void init_parameter( int argc, char *argv[] ) { int ch = 0; opterr = 0; unsigned int record = 0; int options_index = 0; while ( (ch = getopt_long(argc, argv, "r:h:p:t:u:", long_options, &options_index)) != -1 ) { switch( ch ) { case 'r': parameters.__press_rate = atoi( optarg ); record += ( 1 << 0 ); break; case 'u': url_list.full_url[0] = optarg; url_list.url_number = 1; record += ( 1 << 1 ); break; case 't': parameters.__press_time = atoi( optarg ); record += ( 1 << 2 ); break; default : usage( tool_name ); } } if ( (record & 0x7) != 0x7 ){ usage( tool_name ); } //将parameters中的内容复制到相应参数中 memcpy( &press_rate, &(parameters.__press_rate), sizeof(press_rate) ); memcpy( &press_time, &(parameters.__press_time), sizeof(press_time) ); parameters.url_number = url_list.url_number; for( int i=0; i<parameters.url_number; i++ ) { parameters.host[i] = begin_parse( url_list.full_url[i] ); if( !parameters.host[i] ) { usage( tool_name ); } } check_setting(); press_number = press_time * press_rate; press_interval = 1000000.0 / press_rate; return ; } //主函数 int main( int argc, char *argv[] ) { tool_name = argv[0]; init_parameter( argc, argv ); print_info(&parameters); //初始化统计所用的struct overall_stat = new final_statistics; memset( overall_stat, 0, sizeof(final_statistics) ); //初始化要发送的请求 memset( http_request, 0 , MAX_REQUEST_SIZE ); //初始化存储每个请求测试数据的空间 test_data = (request_data *)calloc( press_number, sizeof(request_data) ); pipe( fd ); pipe( fd2 ); pthread_t conn_id, send_id, recv_id; pthread_attr_t joinable_attr; if( pthread_attr_init(&joinable_attr) != 0 ) { fprintf( stderr, "ERROR message (from file %s, line %d): pthread_attr_init() error. errno = %d.\n", __FILE__, __LINE__, errno ); exit( 1 ); } if( pthread_attr_setdetachstate(&joinable_attr, PTHREAD_CREATE_JOINABLE) != 0 ) { fprintf( stderr, "ERROR message (from file %s, line %d): pthread_attr_setdetachstate() error. errno = %d.\n", __FILE__, __LINE__, errno ); exit( 1 ); } fprintf( stdout, "Now the host is under test. Please wait a moment ...\n\n" ); sleep( 2 ); //睡眠两秒钟,让用户看清楚上面这句提示 pthread_create( &conn_id, &joinable_attr, thread_conn, NULL ); pthread_create( &send_id, &joinable_attr, thread_send, NULL ); pthread_create( &recv_id, &joinable_attr, thread_recv, NULL ); pthread_join( conn_id, NULL ); pthread_join( send_id, NULL ); pthread_join( recv_id, NULL ); check_connect_ontime( press_number, &connect_ontime ); statistics_calculation( overall_stat, test_data, press_number ); print_statistics( overall_stat ); for( int i=0; i<parameters.url_number; i++ ) { end_parse( parameters.host[i] ); } delete overall_stat; free( test_data ); return 0; }
31.455535
143
0.664667
1cb443b558689eb8476d57651ccbc56b0b20d513
4,703
inl
C++
matlab_code/jjcao_code-head/toolbox/jjcao_mesh/geodesic/mex/gw/gw_core/GW_SmartCounter.inl
joycewangsy/normals_pointnet
fc74a8ed1a009b18785990b1b4c20eda0549721c
[ "MIT" ]
null
null
null
matlab_code/jjcao_code-head/toolbox/jjcao_mesh/geodesic/mex/gw/gw_core/GW_SmartCounter.inl
joycewangsy/normals_pointnet
fc74a8ed1a009b18785990b1b4c20eda0549721c
[ "MIT" ]
null
null
null
matlab_code/jjcao_code-head/toolbox/jjcao_mesh/geodesic/mex/gw/gw_core/GW_SmartCounter.inl
joycewangsy/normals_pointnet
fc74a8ed1a009b18785990b1b4c20eda0549721c
[ "MIT" ]
null
null
null
/*------------------------------------------------------------------------------*/ /** * \file GW_SmartCounter.inl * \brief Inlined methods for \c GW_SmartCounter * \author Gabriel Peyr?2001-09-12 */ /*------------------------------------------------------------------------------*/ #include "GW_SmartCounter.h" namespace GW { /*------------------------------------------------------------------------------*/ /** * Name : GW_SmartCounter constructor * * \author Gabriel Peyr?2001-09-12 */ /*------------------------------------------------------------------------------*/ GW_INLINE GW_SmartCounter::GW_SmartCounter() : nReferenceCounter_ ( 0 ) { /* NOTHING */ } /*------------------------------------------------------------------------------ * Name : GW_SmartCounter constructor * * \param Dup EXPLANATION * \return PUT YOUR RETURN VALUE AND ITS EXPLANATION * \author Antoine Bouthors 2001-11-24 * * PUT YOUR COMMENTS HERE *------------------------------------------------------------------------------*/ GW_INLINE GW_SmartCounter::GW_SmartCounter( const GW_SmartCounter& Dup ) : nReferenceCounter_(0) { /* NOTHING */ } /*------------------------------------------------------------------------------ * Name : GW_SmartCounter::operator * * \param Dup EXPLANATION * \return PUT YOUR RETURN VALUE AND ITS EXPLANATION * \author Antoine Bouthors 2001-11-24 * * PUT YOUR COMMENTS HERE *------------------------------------------------------------------------------*/ GW_INLINE GW_SmartCounter& GW_SmartCounter::operator=( const GW_SmartCounter& Dup ) { nReferenceCounter_ = 0; return (*this); } /*------------------------------------------------------------------------------*/ /** * Name : GW_SmartCounter destructor * * \author Gabriel Peyr?2001-09-12 * * Check that nobody is still using the object. */ /*------------------------------------------------------------------------------*/ GW_INLINE GW_SmartCounter::~GW_SmartCounter() { GW_ASSERT( nReferenceCounter_==0 ); } /*------------------------------------------------------------------------------*/ /** * Name : GW_SmartCounter::UseIt * * \author Gabriel Peyr?2001-09-10 * * Declare that we use this object. We must call \c ReleaseIt when we no longer use this object. */ /*------------------------------------------------------------------------------*/ GW_INLINE void GW_SmartCounter::UseIt() { GW_ASSERT( nReferenceCounter_<=50000 ); nReferenceCounter_++; } /*------------------------------------------------------------------------------*/ /** * Name : GW_SmartCounter::ReleaseIt * * \author Gabriel Peyr?2001-09-10 * * Declare that we no longer use this object. */ /*------------------------------------------------------------------------------*/ GW_INLINE void GW_SmartCounter::ReleaseIt() { GW_ASSERT( nReferenceCounter_>0 ); nReferenceCounter_--; } /*------------------------------------------------------------------------------*/ /** * Name : GW_SmartCounter::NoLongerUsed * * \return true if no one use this object anymore. * \author Gabriel Peyr?2001-09-10 * * We can delete the object only if \c NoLongerUsed return true. */ /*------------------------------------------------------------------------------*/ GW_INLINE bool GW_SmartCounter::NoLongerUsed() { GW_ASSERT( nReferenceCounter_>=0 ); return nReferenceCounter_==0; } /*------------------------------------------------------------------------------ * Name : GW_SmartCounter::GetReferenceCounter * * \return the value of the reference counter * \author Antoine Bouthors 2001-11-30 * *------------------------------------------------------------------------------*/ GW_INLINE GW_I32 GW_SmartCounter::GetReferenceCounter() { return nReferenceCounter_; } } // End namespace GW /////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2000-2001 The Orion3D Rewiew Board // //---------------------------------------------------------------------------// // This file is under the Orion3D licence. // // Refer to orion3d_licence.txt for more details about the Orion3D Licence. // //---------------------------------------------------------------------------// // Ce fichier est soumis a la Licence Orion3D. // // Se reporter a orion3d_licence.txt pour plus de details sur cette licence.// /////////////////////////////////////////////////////////////////////////////// // END OF FILE // ///////////////////////////////////////////////////////////////////////////////
29.21118
96
0.402296
1cb60bcb0a7f2747bb34edc4ffef8a1ae21c6fac
415
cpp
C++
src/1064b/emm.cpp
lifeich1/play-cf
7eb6dbb290fcf7935e88d3f090d4af79e7308773
[ "WTFPL" ]
null
null
null
src/1064b/emm.cpp
lifeich1/play-cf
7eb6dbb290fcf7935e88d3f090d4af79e7308773
[ "WTFPL" ]
8
2018-10-15T06:47:19.000Z
2019-02-15T09:58:02.000Z
src/1064b/emm.cpp
lifeich1/play-cf
7eb6dbb290fcf7935e88d3f090d4af79e7308773
[ "WTFPL" ]
null
null
null
//-[ #include "type.h" //-] namespace licf { namespace emm_1064b { // placeholder } } using namespace licf::emm_1064b; int emm_1064b(const _in_t & in_, _out_t & out_) { int n; while (in_.read(&n)) { LL res = 1; for (; n > 0; n >>= 1) { if (n & 1) { res <<= 1ll; } } in_.put(res); } return 0; }
12.96875
47
0.414458
1cb6b50ac4e909f6822ded0ee163ee38682adb8b
1,093
cpp
C++
src/lib/cert/cvc/cvc_req.cpp
el-forkorama/botan
4ad555977b03cb92dfac0b87a00febe4d8e7ff5e
[ "BSD-2-Clause" ]
null
null
null
src/lib/cert/cvc/cvc_req.cpp
el-forkorama/botan
4ad555977b03cb92dfac0b87a00febe4d8e7ff5e
[ "BSD-2-Clause" ]
null
null
null
src/lib/cert/cvc/cvc_req.cpp
el-forkorama/botan
4ad555977b03cb92dfac0b87a00febe4d8e7ff5e
[ "BSD-2-Clause" ]
null
null
null
/* * (C) 2007 FlexSecure GmbH * 2008-2010 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/cvc_req.h> #include <botan/cvc_cert.h> #include <botan/ber_dec.h> namespace Botan { bool EAC1_1_Req::operator==(EAC1_1_Req const& rhs) const { return (this->tbs_data() == rhs.tbs_data() && this->get_concat_sig() == rhs.get_concat_sig()); } void EAC1_1_Req::force_decode() { std::vector<byte> enc_pk; BER_Decoder tbs_cert(m_tbs_bits); size_t cpi; tbs_cert.decode(cpi, ASN1_Tag(41), APPLICATION) .start_cons(ASN1_Tag(73)) .raw_bytes(enc_pk) .end_cons() .decode(m_chr) .verify_end(); if(cpi != 0) throw Decoding_Error("EAC1_1 requests cpi was not 0"); m_pk = decode_eac1_1_key(enc_pk, m_sig_algo); } EAC1_1_Req::EAC1_1_Req(DataSource& in) { init(in); m_self_signed = true; do_decode(); } EAC1_1_Req::EAC1_1_Req(const std::string& in) { DataSource_Stream stream(in, true); init(stream); m_self_signed = true; do_decode(); } }
20.240741
70
0.651418
1cb80b74074bb26c2036f07218be4c664d9fdd01
560
cpp
C++
parser.test.cpp
stet-stet/facilities
1ebff3a3e546f313c297f3606a1941be519943a0
[ "MIT" ]
null
null
null
parser.test.cpp
stet-stet/facilities
1ebff3a3e546f313c297f3606a1941be519943a0
[ "MIT" ]
null
null
null
parser.test.cpp
stet-stet/facilities
1ebff3a3e546f313c297f3606a1941be519943a0
[ "MIT" ]
null
null
null
#include"parser.hpp" #include"essentials.hpp" #include<iostream> using std::cout, std::endl; using namespace facilities; int main(int argc, char** argv){ PARSE(argc,argv); if( SANITYCHECK(a,b) ){ print("yes, a and b are present"); } if( !SANITYCHECK(c) ){ print("no, c isn't present"); } RETRIEVE(a,to_vector<int>); RETRIEVE(b,csv_to_vector<long double>); for(auto&& x:a) cout << x << ','; cout<<endl; for(auto&& x:b) cout << x << ','; cout<<endl; UNPACK(c); // should throw and exit. }
20.740741
43
0.575
1cc139eda2b6b5a9c47ddadf86860934f1467cea
2,592
hpp
C++
lib/core/test/fakelogger.hpp
DanglingPointer/veridie-native
dd75c92617094d20ae34fa2d26fa9b1b5eab54f1
[ "Apache-2.0" ]
null
null
null
lib/core/test/fakelogger.hpp
DanglingPointer/veridie-native
dd75c92617094d20ae34fa2d26fa9b1b5eab54f1
[ "Apache-2.0" ]
null
null
null
lib/core/test/fakelogger.hpp
DanglingPointer/veridie-native
dd75c92617094d20ae34fa2d26fa9b1b5eab54f1
[ "Apache-2.0" ]
null
null
null
#ifndef TESTS_FAKELOGGER_HPP #define TESTS_FAKELOGGER_HPP #include "utils/log.hpp" #include <algorithm> #include <vector> class FakeLogger { public: enum class Level { DEBUG, INFO, WARNING, ERROR, FATAL }; struct LogLine { Level lvl; std::string tag; std::string text; }; FakeLogger() { s_lines.clear(); Log::s_debugHandler = LogDebug; Log::s_infoHandler = LogInfo; Log::s_warningHandler = LogWarning; Log::s_errorHandler = LogError; Log::s_fatalHandler = LogFatal; } ~FakeLogger() { s_lines.clear(); Log::s_debugHandler = nullptr; Log::s_infoHandler = nullptr; Log::s_warningHandler = nullptr; Log::s_errorHandler = nullptr; Log::s_fatalHandler = nullptr; } std::vector<LogLine> GetEntries() const { return s_lines; } std::string GetLastStateLine() const { auto it = std::find_if(s_lines.crbegin(), s_lines.crend(), [](const LogLine & line) { return line.text.starts_with("New state:"); }); if (it != s_lines.crend()) return it->text; return ""; } bool Empty() const { return s_lines.empty(); } void Clear() { s_lines.clear(); } bool NoWarningsOrErrors() const { for (const auto & line : s_lines) { switch (line.lvl) { case Level::ERROR: case Level::WARNING: case Level::FATAL: return false; default: break; } } return true; } void DumpLines() const { for (const auto & entry : s_lines) { fprintf(stderr, "Tag(%s) Prio(%d): %s\n", entry.tag.c_str(), static_cast<int>(entry.lvl), entry.text.c_str()); } } private: static inline std::vector<LogLine> s_lines; static void LogDebug(const char * tag, const char * text) { s_lines.emplace_back(LogLine{Level::DEBUG, tag, text}); } static void LogInfo(const char * tag, const char * text) { s_lines.emplace_back(LogLine{Level::INFO, tag, text}); } static void LogWarning(const char * tag, const char * text) { s_lines.emplace_back(LogLine{Level::WARNING, tag, text}); } static void LogError(const char * tag, const char * text) { s_lines.emplace_back(LogLine{Level::ERROR, tag, text}); } static void LogFatal(const char * tag, const char * text) { s_lines.emplace_back(LogLine{Level::FATAL, tag, text}); } }; #endif // TESTS_FAKELOGGER_HPP
23.142857
91
0.580247
1cc2c32fe849253ec5bcaa89abc100f454914d6b
6,048
cpp
C++
code/source/thread_capture.cpp
DEAKSoftware/KFX
8a759d21a651d9f8acbfef2e3d19b1e8580a74b5
[ "MIT" ]
null
null
null
code/source/thread_capture.cpp
DEAKSoftware/KFX
8a759d21a651d9f8acbfef2e3d19b1e8580a74b5
[ "MIT" ]
null
null
null
code/source/thread_capture.cpp
DEAKSoftware/KFX
8a759d21a651d9f8acbfef2e3d19b1e8580a74b5
[ "MIT" ]
null
null
null
/*=========================================================================== Video Capture Thread Dominik Deak ===========================================================================*/ #ifndef ___THREAD_CAPTURE_CPP___ #define ___THREAD_CAPTURE_CPP___ /*--------------------------------------------------------------------------- Header files ---------------------------------------------------------------------------*/ #include "common.h" #include "debug.h" #include "mutex.h" #include "thread_capture.h" /*--------------------------------------------------------------------------- Static data. ---------------------------------------------------------------------------*/ const char* CaptureThread::ExtTGA = "tga"; const char* CaptureThread::ExtPNG = "png"; /*--------------------------------------------------------------------------- Opens a new target directory for streaming. The subdirectory names are generated automatically, based on the current date and timestamp, and with the Prefix added. ---------------------------------------------------------------------------*/ CaptureThread::CaptureThread(QObject* Parent, const QString &Path, const QString &Prefix, CapFormat Format, bool Compress) : QThread(Parent) { Clear(); if (Parent == nullptr) {throw dexception("Invalid parameters.");} setTerminationEnabled(true); //Hook signal functions to the parent class' slot functions QObject::connect(this, SIGNAL(SignalError(QString)), Parent, SLOT(CaptureError(QString))); CaptureThread::Format = Format; CaptureThread::Compress = Compress; Dir = Path; switch (CaptureThread::Format) { case CaptureThread::FormatTGA : Ext = CaptureThread::ExtTGA; break; case CaptureThread::FormatPNG : Ext = CaptureThread::ExtPNG; break; default : throw dexception("The specified file format is unknown."); } QString SubDir; bool Exists = false; uint I = 0; do { QDate Date = QDate::currentDate(); QTime Time = QTime::currentTime(); SubDir = Prefix; SubDir += Date.toString(" yyyy-MM-dd "); SubDir += Time.toString("HH-mm-ss-zzz"); if (I > 0) {SubDir += QString(" %1").arg(I);} I++; Exists = Dir.exists(SubDir); } while (Exists && I < MaxSubDirAttempts); if (Exists) {throw dexception("Failed to create a unique subdirectory.");} if (!Dir.mkdir(SubDir)) {throw dexception("Failed to create a new subdirectory.");} if (!Dir.cd(SubDir)) {throw dexception("Failed to change into subdirectory.");} start(); } /*--------------------------------------------------------------------------- Destructor. ---------------------------------------------------------------------------*/ CaptureThread::~CaptureThread(void) { Destroy(); } /*--------------------------------------------------------------------------- Clears the structure. ---------------------------------------------------------------------------*/ void CaptureThread::Clear(void) { Count = 0; Format = CaptureThread::FormatTGA; Ext = CaptureThread::ExtTGA; Compress = false; Exit = false; } /*--------------------------------------------------------------------------- Destroys the structure. ---------------------------------------------------------------------------*/ void CaptureThread::Destroy(void) { Clear(); } /*--------------------------------------------------------------------------- Thread entry point. ---------------------------------------------------------------------------*/ void CaptureThread::run(void) { debug("Started capture thread.\n"); try { while (!Exit) { //Wait for new frame QMutexLocker MutexLocker(&UpdateMutex); UpdateWait.wait(&UpdateMutex); //Lock frame NAMESPACE_PROJECT::MutexControl Mutex(Frame.GetMutexHandle()); if (!Mutex.LockRequest()) {debug("Mutex already locked, dropping frame.\n"); continue;} if (Frame.Size() < 1) {debug("No data in frame, dropping frame.\n"); continue;} //Construct file name FileName = QString("%1.").arg((long)Count, FileNameDigits, FileNameBase, QLatin1Char('0')) + Ext; FileName = Dir.absoluteFilePath(FileName); Path = FileName.toAscii(); //Save frame switch (Format) { case CaptureThread::FormatTGA : TGA.Save(Frame, Path.constData(), false, Compress); break; case CaptureThread::FormatPNG : PNG.Save(Frame, Path.constData(), Compress ? NAMESPACE_PROJECT::File::PNG::CompSpeed : NAMESPACE_PROJECT::File::PNG::CompNone); break; default : throw dexception("The specified file format is unknown."); } Count++; } } catch (std::exception &e) { SignalError(e.what()); Exit = true; } catch (...) { SignalError("Trapped an unhandled exception in the capture thread."); Exit = true; } debug("Stopping capture thread.\n"); } /*--------------------------------------------------------------------------- Signals to exit thread. ---------------------------------------------------------------------------*/ void CaptureThread::stop(void) { Exit = true; UpdateWait.wakeAll(); } /*--------------------------------------------------------------------------- Signals thread to saves a frame to file. ---------------------------------------------------------------------------*/ void CaptureThread::update(void) { if (Exit) {return;} UpdateWait.wakeAll(); } //==== End of file =========================================================== #endif
31.175258
144
0.430556
1cc82007e7d7bf67fbd363d61d85c060a6120404
5,276
cpp
C++
src/directions/VDWDirection.cpp
XiyuChenFAU/kgs_vibration_entropy
117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9
[ "MIT" ]
1
2020-05-23T18:26:14.000Z
2020-05-23T18:26:14.000Z
src/directions/VDWDirection.cpp
XiyuChenFAU/kgs_vibration_entropy
117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9
[ "MIT" ]
8
2017-01-26T19:54:38.000Z
2021-02-06T16:06:30.000Z
src/directions/VDWDirection.cpp
XiyuChenFAU/kgs_vibration_entropy
117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9
[ "MIT" ]
null
null
null
/* Excited States software: KGS Contributors: See CONTRIBUTORS.txt Contact: kgs-contact@simtk.org Copyright (C) 2009-2017 Stanford University 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: This entire text, including 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, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "VDWDirection.h" #include <vector> #include <gsl/gsl_cblas.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include "core/Molecule.h" #include "core/Grid.h" #include "core/Chain.h" void VDWDirection::computeGradient(Configuration* conf, Configuration* target, gsl_vector* ret) { gsl_vector_set_all(ret, 0.0); Molecule * protein = conf->updatedMolecule(); gsl_matrix* atomJacobian1 = gsl_matrix_calloc(3,protein->totalDofNum()); gsl_matrix* atomJacobian2 = gsl_matrix_calloc(3,protein->totalDofNum()); gsl_vector* p12 = gsl_vector_calloc(3); gsl_vector* p_temp = gsl_vector_calloc(protein->totalDofNum()); for (auto const& atom1: protein->getAtoms()) { std::vector<Atom*> neighbors = protein->getGrid()->getNeighboringAtomsVDW(atom1, //atom true, //neighborWithLargerId true, //noCovBondNeighbor true, //noSecondCovBondNeighbor true, //noHbondNeighbor VDW_R_MAX); //radius computeAtomJacobian(atom1,atomJacobian1); for(auto const& atom2: neighbors){ double r_12 = atom1->distanceTo(atom2); //Dimitars version //double atomContribution = (-12)*VDW_SIGMA*(pow(VDW_R0,6)*pow(r_12,-8)-pow(VDW_R0,12)*pow(r_12,-14)); double vdw_r12 = atom1->getRadius() + atom2->getRadius() ; // from CHARMM: arithmetic mean double eps_r12 = sqrt(atom1->getEpsilon() * atom2->getEpsilon()); // from CHARMM: geometric mean double ratio = vdw_r12/r_12; //double atomContribution = 4 * eps_r12 * (pow(ratio,12)-2*pow(ratio,6)); double atomContribution = 12 * 4 * eps_r12 * (pow(ratio,6)-pow(ratio,12))/r_12; computeAtomJacobian(atom2,atomJacobian2); gsl_matrix_sub(atomJacobian1,atomJacobian2); // atomJacobian1 = atomJacobian1 - atomJacobian2 Math3D::Vector3 p12_v3 = atom1->m_position - atom2->m_position;//TODO: Subtract directly into gsl_vector Coordinate::copyToGslVector(p12_v3, p12); gsl_blas_dgemv(CblasTrans,1,atomJacobian1,p12,0,p_temp); //std::cout<<"VDWDirection::computeGradient - pair-gradient norm: "<<gsl_blas_dnrm2(p_temp)<<std::endl; gsl_vector_scale(p_temp, atomContribution/gsl_blas_dnrm2(p_temp)); //std::cout<<"VDWDirection::computeGradient - after scaling: "<<gsl_blas_dnrm2(p_temp)<<std::endl; gsl_vector_add(ret,p_temp); } } gsl_vector_scale(ret,0.001); //std::cout<<"VDWDirection::computeGradient - total gradient norm: "<<gsl_blas_dnrm2(ret)<<std::endl; //TODO: Improve to minimize reallocations gsl_matrix_free(atomJacobian1); gsl_matrix_free(atomJacobian2); gsl_vector_free(p12); gsl_vector_free(p_temp); } void VDWDirection::computeAtomJacobian (Atom* atom, gsl_matrix* jacobian) { Molecule * protein = atom->getResidue()->getChain()->getMolecule(); //KinVertex *vertex = protein->getRigidbodyGraphVertex(atom); KinVertex *vertex = atom->getRigidbody()->getVertex(); while (vertex->m_parent!=nullptr) { KinEdge* edge = vertex->m_parent->findEdge(vertex); int dof_id = edge->getDOF()->getIndex(); // Bond * bond_ptr = edge->getBond(); // Coordinate bp1 = bond_ptr->Atom1->m_position; // Coordinate bp2 = bond_ptr->m_atom2->m_position; // Math3D::Vector3 jacobian_entry = ComputeJacobianEntry(bp1,bp2,atom->m_position); Math3D::Vector3 jacobian_entry = edge->getDOF()->getDerivative(atom->m_position); gsl_matrix_set(jacobian,0,dof_id,jacobian_entry.x); gsl_matrix_set(jacobian,1,dof_id,jacobian_entry.y); gsl_matrix_set(jacobian,2,dof_id,jacobian_entry.z); vertex = vertex->m_parent; } //Todo: This should be optimizable using the sorted vertices and the Abé implementation of the MSD gradient }
45.094017
115
0.682714
1cc8b81bd2ea2c25f32328f85b60a2ae1b81d3d8
364
cpp
C++
src/column.cpp
aschaffer/libgdf
dd9bc77a61098215b37f63cc8a09c3dc69cf1cb3
[ "Apache-2.0" ]
5
2018-10-17T20:28:42.000Z
2022-02-15T17:33:01.000Z
src/column.cpp
aschaffer/libgdf
dd9bc77a61098215b37f63cc8a09c3dc69cf1cb3
[ "Apache-2.0" ]
19
2018-07-18T07:15:44.000Z
2021-02-22T17:00:18.000Z
src/column.cpp
aschaffer/libgdf
dd9bc77a61098215b37f63cc8a09c3dc69cf1cb3
[ "Apache-2.0" ]
2
2020-05-01T09:54:34.000Z
2021-04-17T10:57:07.000Z
#include <gdf/gdf.h> gdf_size_type gdf_column_sizeof() { return sizeof(gdf_column); } gdf_error gdf_column_view(gdf_column *column, void *data, gdf_valid_type *valid, gdf_size_type size, gdf_dtype dtype) { column->data = data; column->valid = valid; column->size = size; column->dtype = dtype; return GDF_SUCCESS; }
21.411765
80
0.662088
1cd27e671a0ca1a0581041df32c1c948f55e5809
4,119
cpp
C++
src/tanktextures.cpp
Eae02/tank-game
0c526b177ccc15dd49e3228489163f13335040db
[ "Zlib" ]
null
null
null
src/tanktextures.cpp
Eae02/tank-game
0c526b177ccc15dd49e3228489163f13335040db
[ "Zlib" ]
null
null
null
src/tanktextures.cpp
Eae02/tank-game
0c526b177ccc15dd49e3228489163f13335040db
[ "Zlib" ]
null
null
null
#include "tanktextures.h" #include "exceptions/invalidstateexception.h" #include "utils/utils.h" #include "utils/ioutils.h" #include "graphics/textureloadoperation.h" namespace TankGame { static std::unique_ptr<TankTextures> instance; class TankTexturesLoadOperation : public IASyncOperation { public: TankTexturesLoadOperation() : m_baseDiffuseLoadOps{ TextureLoadOperation(GetResDirectory() / "tank" / "base0.png", nullptr), TextureLoadOperation(GetResDirectory() / "tank" / "base1.png", nullptr), TextureLoadOperation(GetResDirectory() / "tank" / "base2.png", nullptr), TextureLoadOperation(GetResDirectory() / "tank" / "base3.png", nullptr), TextureLoadOperation(GetResDirectory() / "tank" / "base4.png", nullptr), TextureLoadOperation(GetResDirectory() / "tank" / "base5.png", nullptr), TextureLoadOperation(GetResDirectory() / "tank" / "base6.png", nullptr), TextureLoadOperation(GetResDirectory() / "tank" / "base7.png", nullptr), TextureLoadOperation(GetResDirectory() / "tank" / "base8.png", nullptr) }, m_baseNormalsLoadOp(GetResDirectory() / "tank" / "base-normals.png", nullptr) { } virtual void DoWork() override { for (TextureLoadOperation& loadOperation : m_baseDiffuseLoadOps) loadOperation.DoWork(); m_baseNormalsLoadOp.DoWork(); } virtual void ProcessResult() override { instance = std::make_unique<TankTextures>(m_baseDiffuseLoadOps[0].CreateTexture(), m_baseDiffuseLoadOps[1].CreateTexture(), m_baseDiffuseLoadOps[2].CreateTexture(), m_baseDiffuseLoadOps[3].CreateTexture(), m_baseDiffuseLoadOps[4].CreateTexture(), m_baseDiffuseLoadOps[5].CreateTexture(), m_baseDiffuseLoadOps[6].CreateTexture(), m_baseDiffuseLoadOps[7].CreateTexture(), m_baseDiffuseLoadOps[8].CreateTexture(), m_baseNormalsLoadOp.CreateTexture()); } private: TextureLoadOperation m_baseDiffuseLoadOps[9]; TextureLoadOperation m_baseNormalsLoadOp; }; TankTextures::TankTextures(Texture2D&& baseDiffuse0, Texture2D&& baseDiffuse1, Texture2D&& baseDiffuse2, Texture2D&& baseDiffuse3, Texture2D&& baseDiffuse4, Texture2D&& baseDiffuse5, Texture2D&& baseDiffuse6, Texture2D&& baseDiffuse7, Texture2D&& baseDiffuse8, Texture2D&& baseNormals) : m_baseDiffuse{ std::move(baseDiffuse0), std::move(baseDiffuse1), std::move(baseDiffuse2), std::move(baseDiffuse3), std::move(baseDiffuse4), std::move(baseDiffuse5), std::move(baseDiffuse6), std::move(baseDiffuse7), std::move(baseDiffuse8) }, m_baseNormals(std::move(baseNormals)), m_baseMaterials{ SpriteMaterial(m_baseDiffuse[0], m_baseNormals, 1, 30), SpriteMaterial(m_baseDiffuse[1], m_baseNormals, 1, 30), SpriteMaterial(m_baseDiffuse[2], m_baseNormals, 1, 30), SpriteMaterial(m_baseDiffuse[3], m_baseNormals, 1, 30), SpriteMaterial(m_baseDiffuse[4], m_baseNormals, 1, 30), SpriteMaterial(m_baseDiffuse[5], m_baseNormals, 1, 30), SpriteMaterial(m_baseDiffuse[6], m_baseNormals, 1, 30), SpriteMaterial(m_baseDiffuse[7], m_baseNormals, 1, 30), SpriteMaterial(m_baseDiffuse[8], m_baseNormals, 1, 30) } { for (Texture2D& texture : m_baseDiffuse) texture.SetWrapMode(GL_CLAMP_TO_EDGE); m_baseNormals.SetWrapMode(GL_CLAMP_TO_EDGE); } std::unique_ptr<IASyncOperation> TankTextures::CreateInstance() { if (instance != nullptr) throw InvalidStateException("Tank textures already loaded."); CallOnClose([] { instance = nullptr; }); return std::make_unique<TankTexturesLoadOperation>(); } const TankTextures& TankTextures::GetInstance() { return *instance; } }
49.035714
105
0.646759
1cd2b5bee1b0b729cf337ab461287ad15a9185f9
46,483
cpp
C++
external/vsomeip/implementation/endpoints/src/tcp_server_endpoint_impl.cpp
lixiaolia/ndk-someip-lib
f4088e87f07e3a6bcec402514bb7ebb77ec946ce
[ "Apache-2.0" ]
3
2021-06-17T14:01:04.000Z
2022-03-18T09:22:44.000Z
external/vsomeip/implementation/endpoints/src/tcp_server_endpoint_impl.cpp
lixiaolia/ndk-someip-lib
f4088e87f07e3a6bcec402514bb7ebb77ec946ce
[ "Apache-2.0" ]
1
2022-03-15T06:21:33.000Z
2022-03-28T06:31:12.000Z
external/vsomeip/implementation/endpoints/src/tcp_server_endpoint_impl.cpp
lixiaolia/ndk-someip-lib
f4088e87f07e3a6bcec402514bb7ebb77ec946ce
[ "Apache-2.0" ]
4
2021-06-17T14:12:18.000Z
2021-12-13T11:53:10.000Z
// Copyright (C) 2014-2017 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <iomanip> #include <boost/asio/write.hpp> #include <vsomeip/constants.hpp> #include <vsomeip/internal/logger.hpp> #include "../include/endpoint_definition.hpp" #include "../include/endpoint_host.hpp" #include "../../routing/include/routing_host.hpp" #include "../include/tcp_server_endpoint_impl.hpp" #include "../../utility/include/utility.hpp" #include "../../utility/include/byteorder.hpp" namespace ip = boost::asio::ip; namespace vsomeip_v3 { tcp_server_endpoint_impl::tcp_server_endpoint_impl( const std::shared_ptr<endpoint_host>& _endpoint_host, const std::shared_ptr<routing_host>& _routing_host, const endpoint_type& _local, boost::asio::io_service &_io, const std::shared_ptr<configuration>& _configuration) : tcp_server_endpoint_base_impl(_endpoint_host, _routing_host, _local, _io, _configuration->get_max_message_size_reliable(_local.address().to_string(), _local.port()), _configuration->get_endpoint_queue_limit(_local.address().to_string(), _local.port()), _configuration), acceptor_(_io), buffer_shrink_threshold_(configuration_->get_buffer_shrink_threshold()), local_port_(_local.port()), // send timeout after 2/3 of configured ttl, warning after 1/3 send_timeout_(configuration_->get_sd_ttl() * 666) { is_supporting_magic_cookies_ = true; boost::system::error_code ec; acceptor_.open(_local.protocol(), ec); boost::asio::detail::throw_error(ec, "acceptor open"); acceptor_.set_option(boost::asio::socket_base::reuse_address(true), ec); boost::asio::detail::throw_error(ec, "acceptor set_option"); #ifndef _WIN32 // If specified, bind to device std::string its_device(configuration_->get_device()); if (its_device != "") { if (setsockopt(acceptor_.native_handle(), SOL_SOCKET, SO_BINDTODEVICE, its_device.c_str(), (int)its_device.size()) == -1) { VSOMEIP_WARNING << "TCP Server: Could not bind to device \"" << its_device << "\""; } } #endif acceptor_.bind(_local, ec); boost::asio::detail::throw_error(ec, "acceptor bind"); acceptor_.listen(boost::asio::socket_base::max_connections, ec); boost::asio::detail::throw_error(ec, "acceptor listen"); } tcp_server_endpoint_impl::~tcp_server_endpoint_impl() { } bool tcp_server_endpoint_impl::is_local() const { return false; } void tcp_server_endpoint_impl::start() { std::lock_guard<std::mutex> its_lock(acceptor_mutex_); if (acceptor_.is_open()) { connection::ptr new_connection = connection::create( std::dynamic_pointer_cast<tcp_server_endpoint_impl>( shared_from_this()), max_message_size_, buffer_shrink_threshold_, has_enabled_magic_cookies_, service_, send_timeout_); { std::unique_lock<std::mutex> its_socket_lock(new_connection->get_socket_lock()); acceptor_.async_accept(new_connection->get_socket(), std::bind(&tcp_server_endpoint_impl::accept_cbk, std::dynamic_pointer_cast<tcp_server_endpoint_impl>( shared_from_this()), new_connection, std::placeholders::_1)); } } } void tcp_server_endpoint_impl::stop() { server_endpoint_impl::stop(); { std::lock_guard<std::mutex> its_lock(acceptor_mutex_); if(acceptor_.is_open()) { boost::system::error_code its_error; acceptor_.close(its_error); } } { std::lock_guard<std::mutex> its_lock(connections_mutex_); for (const auto &c : connections_) { c.second->stop(); } connections_.clear(); } } bool tcp_server_endpoint_impl::send_to( const std::shared_ptr<endpoint_definition> _target, const byte_t *_data, uint32_t _size) { std::lock_guard<std::mutex> its_lock(mutex_); endpoint_type its_target(_target->get_address(), _target->get_port()); return send_intern(its_target, _data, _size); } bool tcp_server_endpoint_impl::send_error( const std::shared_ptr<endpoint_definition> _target, const byte_t *_data, uint32_t _size) { bool ret(false); std::lock_guard<std::mutex> its_lock(mutex_); const endpoint_type its_target(_target->get_address(), _target->get_port()); const queue_iterator_type target_queue_iterator(find_or_create_queue_unlocked(its_target)); auto& its_qpair = target_queue_iterator->second; const bool queue_size_zero_on_entry(its_qpair.second.empty()); if (check_message_size(nullptr, _size, its_target) == endpoint_impl::cms_ret_e::MSG_OK && check_queue_limit(_data, _size, its_qpair.first)) { its_qpair.second.emplace_back( std::make_shared<message_buffer_t>(_data, _data + _size)); its_qpair.first += _size; if (queue_size_zero_on_entry) { // no writing in progress send_queued(target_queue_iterator); } ret = true; } return ret; } void tcp_server_endpoint_impl::send_queued(const queue_iterator_type _queue_iterator) { connection::ptr its_connection; { std::lock_guard<std::mutex> its_lock(connections_mutex_); auto connection_iterator = connections_.find(_queue_iterator->first); if (connection_iterator != connections_.end()) { its_connection = connection_iterator->second; } else { VSOMEIP_INFO << "Didn't find connection: " << _queue_iterator->first.address().to_string() << ":" << std::dec << static_cast<std::uint16_t>(_queue_iterator->first.port()) << " dropping outstanding messages (" << std::dec << _queue_iterator->second.second.size() << ")."; queues_.erase(_queue_iterator->first); } } if (its_connection) { its_connection->send_queued(_queue_iterator); } } void tcp_server_endpoint_impl::get_configured_times_from_endpoint( service_t _service, method_t _method, std::chrono::nanoseconds *_debouncing, std::chrono::nanoseconds *_maximum_retention) const { configuration_->get_configured_timing_responses(_service, tcp_server_endpoint_base_impl::local_.address().to_string(), tcp_server_endpoint_base_impl::local_.port(), _method, _debouncing, _maximum_retention); } bool tcp_server_endpoint_impl::is_established(const std::shared_ptr<endpoint_definition>& _endpoint) { bool is_connected = false; endpoint_type endpoint(_endpoint->get_address(), _endpoint->get_port()); { std::lock_guard<std::mutex> its_lock(connections_mutex_); auto connection_iterator = connections_.find(endpoint); if (connection_iterator != connections_.end()) { is_connected = true; } else { VSOMEIP_INFO << "Didn't find TCP connection: Subscription " << "rejected for: " << endpoint.address().to_string() << ":" << std::dec << static_cast<std::uint16_t>(endpoint.port()); } } return is_connected; } bool tcp_server_endpoint_impl::get_default_target(service_t, tcp_server_endpoint_impl::endpoint_type &) const { return false; } void tcp_server_endpoint_impl::remove_connection( tcp_server_endpoint_impl::connection *_connection) { std::lock_guard<std::mutex> its_lock(connections_mutex_); for (auto it = connections_.begin(); it != connections_.end();) { if (it->second.get() == _connection) { it = connections_.erase(it); break; } else { ++it; } } } void tcp_server_endpoint_impl::accept_cbk(const connection::ptr& _connection, boost::system::error_code const &_error) { if (!_error) { boost::system::error_code its_error; endpoint_type remote; { std::unique_lock<std::mutex> its_socket_lock(_connection->get_socket_lock()); socket_type &new_connection_socket = _connection->get_socket(); remote = new_connection_socket.remote_endpoint(its_error); _connection->set_remote_info(remote); // Nagle algorithm off new_connection_socket.set_option(ip::tcp::no_delay(true), its_error); new_connection_socket.set_option(boost::asio::socket_base::keep_alive(true), its_error); if (its_error) { VSOMEIP_WARNING << "tcp_server_endpoint::connect: couldn't enable " << "keep_alive: " << its_error.message(); } } if (!its_error) { { std::lock_guard<std::mutex> its_lock(connections_mutex_); connections_[remote] = _connection; } _connection->start(); } } if (_error != boost::asio::error::bad_descriptor && _error != boost::asio::error::operation_aborted && _error != boost::asio::error::no_descriptors) { start(); } else if (_error == boost::asio::error::no_descriptors) { VSOMEIP_ERROR<< "tcp_server_endpoint_impl::accept_cbk: " << _error.message() << " (" << std::dec << _error.value() << ") Will try to accept again in 1000ms"; std::shared_ptr<boost::asio::steady_timer> its_timer = std::make_shared<boost::asio::steady_timer>(service_, std::chrono::milliseconds(1000)); auto its_ep = std::dynamic_pointer_cast<tcp_server_endpoint_impl>( shared_from_this()); its_timer->async_wait([its_timer, its_ep] (const boost::system::error_code& _error) { if (!_error) { its_ep->start(); } }); } } std::uint16_t tcp_server_endpoint_impl::get_local_port() const { return local_port_; } bool tcp_server_endpoint_impl::is_reliable() const { return true; } /////////////////////////////////////////////////////////////////////////////// // class tcp_service_impl::connection /////////////////////////////////////////////////////////////////////////////// tcp_server_endpoint_impl::connection::connection( const std::weak_ptr<tcp_server_endpoint_impl>& _server, std::uint32_t _max_message_size, std::uint32_t _recv_buffer_size_initial, std::uint32_t _buffer_shrink_threshold, bool _magic_cookies_enabled, boost::asio::io_service &_io_service, std::chrono::milliseconds _send_timeout) : socket_(_io_service), server_(_server), max_message_size_(_max_message_size), recv_buffer_size_initial_(_recv_buffer_size_initial), recv_buffer_(_recv_buffer_size_initial, 0), recv_buffer_size_(0), missing_capacity_(0), shrink_count_(0), buffer_shrink_threshold_(_buffer_shrink_threshold), remote_port_(0), magic_cookies_enabled_(_magic_cookies_enabled), last_cookie_sent_(std::chrono::steady_clock::now() - std::chrono::seconds(11)), send_timeout_(_send_timeout), send_timeout_warning_(_send_timeout / 2) { } tcp_server_endpoint_impl::connection::ptr tcp_server_endpoint_impl::connection::create( const std::weak_ptr<tcp_server_endpoint_impl>& _server, std::uint32_t _max_message_size, std::uint32_t _buffer_shrink_threshold, bool _magic_cookies_enabled, boost::asio::io_service & _io_service, std::chrono::milliseconds _send_timeout) { const std::uint32_t its_initial_receveive_buffer_size = VSOMEIP_SOMEIP_HEADER_SIZE + 8 + MAGIC_COOKIE_SIZE + 8; return ptr(new connection(_server, _max_message_size, its_initial_receveive_buffer_size, _buffer_shrink_threshold, _magic_cookies_enabled, _io_service, _send_timeout)); } tcp_server_endpoint_impl::socket_type & tcp_server_endpoint_impl::connection::get_socket() { return socket_; } std::unique_lock<std::mutex> tcp_server_endpoint_impl::connection::get_socket_lock() { return std::unique_lock<std::mutex>(socket_mutex_); } void tcp_server_endpoint_impl::connection::start() { receive(); } void tcp_server_endpoint_impl::connection::receive() { std::lock_guard<std::mutex> its_lock(socket_mutex_); if(socket_.is_open()) { const std::size_t its_capacity(recv_buffer_.capacity()); size_t buffer_size = its_capacity - recv_buffer_size_; try { if (missing_capacity_) { if (missing_capacity_ > MESSAGE_SIZE_UNLIMITED) { VSOMEIP_ERROR << "Missing receive buffer capacity exceeds allowed maximum!"; return; } const std::size_t its_required_capacity(recv_buffer_size_ + missing_capacity_); if (its_capacity < its_required_capacity) { recv_buffer_.reserve(its_required_capacity); recv_buffer_.resize(its_required_capacity, 0x0); if (recv_buffer_.size() > 1048576) { VSOMEIP_INFO << "tse: recv_buffer size is: " << recv_buffer_.size() << " local: " << get_address_port_local() << " remote: " << get_address_port_remote(); } } buffer_size = missing_capacity_; missing_capacity_ = 0; } else if (buffer_shrink_threshold_ && shrink_count_ > buffer_shrink_threshold_ && recv_buffer_size_ == 0) { recv_buffer_.resize(recv_buffer_size_initial_, 0x0); recv_buffer_.shrink_to_fit(); buffer_size = recv_buffer_size_initial_; shrink_count_ = 0; } } catch (const std::exception &e) { handle_recv_buffer_exception(e); // don't start receiving again return; } socket_.async_receive(boost::asio::buffer(&recv_buffer_[recv_buffer_size_], buffer_size), std::bind(&tcp_server_endpoint_impl::connection::receive_cbk, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } } void tcp_server_endpoint_impl::connection::stop() { std::lock_guard<std::mutex> its_lock(socket_mutex_); if (socket_.is_open()) { boost::system::error_code its_error; socket_.shutdown(socket_.shutdown_both, its_error); socket_.close(its_error); } } void tcp_server_endpoint_impl::connection::send_queued( const queue_iterator_type _queue_iterator) { std::shared_ptr<tcp_server_endpoint_impl> its_server(server_.lock()); if (!its_server) { VSOMEIP_TRACE << "tcp_server_endpoint_impl::connection::send_queued " " couldn't lock server_"; return; } message_buffer_ptr_t its_buffer = _queue_iterator->second.second.front(); const service_t its_service = VSOMEIP_BYTES_TO_WORD( (*its_buffer)[VSOMEIP_SERVICE_POS_MIN], (*its_buffer)[VSOMEIP_SERVICE_POS_MAX]); const method_t its_method = VSOMEIP_BYTES_TO_WORD( (*its_buffer)[VSOMEIP_METHOD_POS_MIN], (*its_buffer)[VSOMEIP_METHOD_POS_MAX]); const client_t its_client = VSOMEIP_BYTES_TO_WORD( (*its_buffer)[VSOMEIP_CLIENT_POS_MIN], (*its_buffer)[VSOMEIP_CLIENT_POS_MAX]); const session_t its_session = VSOMEIP_BYTES_TO_WORD( (*its_buffer)[VSOMEIP_SESSION_POS_MIN], (*its_buffer)[VSOMEIP_SESSION_POS_MAX]); if (magic_cookies_enabled_) { const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); if (std::chrono::duration_cast<std::chrono::milliseconds>( now - last_cookie_sent_) > std::chrono::milliseconds(10000)) { if (send_magic_cookie(its_buffer)) { last_cookie_sent_ = now; _queue_iterator->second.first += sizeof(SERVICE_COOKIE); } } } { std::lock_guard<std::mutex> its_lock(socket_mutex_); { std::lock_guard<std::mutex> its_sent_lock(its_server->sent_mutex_); its_server->is_sending_ = true; } boost::asio::async_write(socket_, boost::asio::buffer(*its_buffer), std::bind(&tcp_server_endpoint_impl::connection::write_completion_condition, shared_from_this(), std::placeholders::_1, std::placeholders::_2, its_buffer->size(), its_service, its_method, its_client, its_session, std::chrono::steady_clock::now()), std::bind(&tcp_server_endpoint_base_impl::send_cbk, its_server, _queue_iterator, std::placeholders::_1, std::placeholders::_2)); } } void tcp_server_endpoint_impl::connection::send_queued_sync( const queue_iterator_type _queue_iterator) { message_buffer_ptr_t its_buffer = _queue_iterator->second.second.front(); if (magic_cookies_enabled_) { const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); if (std::chrono::duration_cast<std::chrono::milliseconds>( now - last_cookie_sent_) > std::chrono::milliseconds(10000)) { if (send_magic_cookie(its_buffer)) { last_cookie_sent_ = now; _queue_iterator->second.first += sizeof(SERVICE_COOKIE); } } } try { std::lock_guard<std::mutex> its_lock(socket_mutex_); boost::asio::write(socket_, boost::asio::buffer(*its_buffer)); } catch (const boost::system::system_error &e) { if (e.code() != boost::asio::error::broken_pipe) { VSOMEIP_ERROR << "tcp_server_endpoint_impl::connection::" << __func__ << " " << e.what(); } } } bool tcp_server_endpoint_impl::connection::send_magic_cookie( message_buffer_ptr_t &_buffer) { if (max_message_size_ == MESSAGE_SIZE_UNLIMITED || max_message_size_ - _buffer->size() >= VSOMEIP_SOMEIP_HEADER_SIZE + VSOMEIP_SOMEIP_MAGIC_COOKIE_SIZE) { _buffer->insert(_buffer->begin(), SERVICE_COOKIE, SERVICE_COOKIE + sizeof(SERVICE_COOKIE)); return true; } return false; } bool tcp_server_endpoint_impl::connection::is_magic_cookie(size_t _offset) const { return (0 == std::memcmp(CLIENT_COOKIE, &recv_buffer_[_offset], sizeof(CLIENT_COOKIE))); } void tcp_server_endpoint_impl::connection::receive_cbk( boost::system::error_code const &_error, std::size_t _bytes) { if (_error == boost::asio::error::operation_aborted) { // endpoint was stopped return; } std::shared_ptr<tcp_server_endpoint_impl> its_server(server_.lock()); if (!its_server) { VSOMEIP_ERROR << "tcp_server_endpoint_impl::connection::receive_cbk " " couldn't lock server_"; return; } #if 0 std::stringstream msg; for (std::size_t i = 0; i < _bytes + recv_buffer_size_; ++i) msg << std::hex << std::setw(2) << std::setfill('0') << (int) recv_buffer_[i] << " "; VSOMEIP_INFO << msg.str(); #endif std::shared_ptr<routing_host> its_host = its_server->routing_host_.lock(); if (its_host) { if (!_error && 0 < _bytes) { if (recv_buffer_size_ + _bytes < recv_buffer_size_) { VSOMEIP_ERROR << "receive buffer overflow in tcp client endpoint ~> abort!"; return; } recv_buffer_size_ += _bytes; size_t its_iteration_gap = 0; bool has_full_message; do { uint64_t read_message_size = utility::get_message_size(&recv_buffer_[its_iteration_gap], recv_buffer_size_); if (read_message_size > MESSAGE_SIZE_UNLIMITED) { VSOMEIP_ERROR << "Message size exceeds allowed maximum!"; return; } uint32_t current_message_size = static_cast<uint32_t>(read_message_size); has_full_message = (current_message_size > VSOMEIP_RETURN_CODE_POS && current_message_size <= recv_buffer_size_); if (has_full_message) { bool needs_forwarding(true); if (is_magic_cookie(its_iteration_gap)) { magic_cookies_enabled_ = true; } else { if (magic_cookies_enabled_) { uint32_t its_offset = its_server->find_magic_cookie(&recv_buffer_[its_iteration_gap], recv_buffer_size_); if (its_offset < current_message_size) { { std::lock_guard<std::mutex> its_lock(socket_mutex_); VSOMEIP_ERROR << "Detected Magic Cookie within message data. Resyncing." << " local: " << get_address_port_local() << " remote: " << get_address_port_remote(); } if (!is_magic_cookie(its_iteration_gap)) { auto its_endpoint_host = its_server->endpoint_host_.lock(); if (its_endpoint_host) { its_endpoint_host->on_error(&recv_buffer_[its_iteration_gap], static_cast<length_t>(recv_buffer_size_),its_server.get(), remote_address_, remote_port_); } } current_message_size = its_offset; needs_forwarding = false; } } } if (needs_forwarding) { if (utility::is_request( recv_buffer_[its_iteration_gap + VSOMEIP_MESSAGE_TYPE_POS])) { const client_t its_client = VSOMEIP_BYTES_TO_WORD( recv_buffer_[its_iteration_gap + VSOMEIP_CLIENT_POS_MIN], recv_buffer_[its_iteration_gap + VSOMEIP_CLIENT_POS_MAX]); if (its_client != MAGIC_COOKIE_CLIENT) { const session_t its_session = VSOMEIP_BYTES_TO_WORD( recv_buffer_[its_iteration_gap + VSOMEIP_SESSION_POS_MIN], recv_buffer_[its_iteration_gap + VSOMEIP_SESSION_POS_MAX]); its_server->clients_mutex_.lock(); its_server->clients_[its_client][its_session] = remote_; its_server->clients_mutex_.unlock(); } } if (!magic_cookies_enabled_) { its_host->on_message(&recv_buffer_[its_iteration_gap], current_message_size, its_server.get(), boost::asio::ip::address(), VSOMEIP_ROUTING_CLIENT, std::make_pair(ANY_UID, ANY_GID), remote_address_, remote_port_); } else { // Only call on_message without a magic cookie in front of the buffer! if (!is_magic_cookie(its_iteration_gap)) { its_host->on_message(&recv_buffer_[its_iteration_gap], current_message_size, its_server.get(), boost::asio::ip::address(), VSOMEIP_ROUTING_CLIENT, std::make_pair(ANY_UID, ANY_GID), remote_address_, remote_port_); } } } calculate_shrink_count(); missing_capacity_ = 0; recv_buffer_size_ -= current_message_size; its_iteration_gap += current_message_size; } else if (magic_cookies_enabled_ && recv_buffer_size_ > 0) { uint32_t its_offset = its_server->find_magic_cookie(&recv_buffer_[its_iteration_gap], recv_buffer_size_); if (its_offset < recv_buffer_size_) { { std::lock_guard<std::mutex> its_lock(socket_mutex_); VSOMEIP_ERROR << "Detected Magic Cookie within message data. Resyncing." << " local: " << get_address_port_local() << " remote: " << get_address_port_remote(); } if (!is_magic_cookie(its_iteration_gap)) { auto its_endpoint_host = its_server->endpoint_host_.lock(); if (its_endpoint_host) { its_endpoint_host->on_error(&recv_buffer_[its_iteration_gap], static_cast<length_t>(recv_buffer_size_), its_server.get(), remote_address_, remote_port_); } } recv_buffer_size_ -= its_offset; its_iteration_gap += its_offset; has_full_message = true; // trigger next loop if (!is_magic_cookie(its_iteration_gap)) { auto its_endpoint_host = its_server->endpoint_host_.lock(); if (its_endpoint_host) { its_endpoint_host->on_error(&recv_buffer_[its_iteration_gap], static_cast<length_t>(recv_buffer_size_), its_server.get(), remote_address_, remote_port_); } } } } if (!has_full_message) { if (recv_buffer_size_ > VSOMEIP_RETURN_CODE_POS && (recv_buffer_[its_iteration_gap + VSOMEIP_PROTOCOL_VERSION_POS] != VSOMEIP_PROTOCOL_VERSION || !utility::is_valid_message_type(static_cast<message_type_e>(recv_buffer_[its_iteration_gap + VSOMEIP_MESSAGE_TYPE_POS])) || !utility::is_valid_return_code(static_cast<return_code_e>(recv_buffer_[its_iteration_gap + VSOMEIP_RETURN_CODE_POS])) )) { if (recv_buffer_[its_iteration_gap + VSOMEIP_PROTOCOL_VERSION_POS] != VSOMEIP_PROTOCOL_VERSION) { { std::lock_guard<std::mutex> its_lock(socket_mutex_); VSOMEIP_ERROR << "tse: Wrong protocol version: 0x" << std::hex << std::setw(2) << std::setfill('0') << std::uint32_t(recv_buffer_[its_iteration_gap + VSOMEIP_PROTOCOL_VERSION_POS]) << " local: " << get_address_port_local() << " remote: " << get_address_port_remote() << ". Closing connection due to missing/broken data TCP stream."; } // ensure to send back a error message w/ wrong protocol version its_host->on_message(&recv_buffer_[its_iteration_gap], VSOMEIP_SOMEIP_HEADER_SIZE + 8, its_server.get(), boost::asio::ip::address(), VSOMEIP_ROUTING_CLIENT, std::make_pair(ANY_UID, ANY_GID), remote_address_, remote_port_); } else if (!utility::is_valid_message_type(static_cast<message_type_e>( recv_buffer_[its_iteration_gap + VSOMEIP_MESSAGE_TYPE_POS]))) { std::lock_guard<std::mutex> its_lock(socket_mutex_); VSOMEIP_ERROR << "tse: Invalid message type: 0x" << std::hex << std::setw(2) << std::setfill('0') << std::uint32_t(recv_buffer_[its_iteration_gap + VSOMEIP_MESSAGE_TYPE_POS]) << " local: " << get_address_port_local() << " remote: " << get_address_port_remote() << ". Closing connection due to missing/broken data TCP stream."; } else if (!utility::is_valid_return_code(static_cast<return_code_e>( recv_buffer_[its_iteration_gap + VSOMEIP_RETURN_CODE_POS]))) { std::lock_guard<std::mutex> its_lock(socket_mutex_); VSOMEIP_ERROR << "tse: Invalid return code: 0x" << std::hex << std::setw(2) << std::setfill('0') << std::uint32_t(recv_buffer_[its_iteration_gap + VSOMEIP_RETURN_CODE_POS]) << " local: " << get_address_port_local() << " remote: " << get_address_port_remote() << ". Closing connection due to missing/broken data TCP stream."; } wait_until_sent(boost::asio::error::operation_aborted); return; } else if (max_message_size_ != MESSAGE_SIZE_UNLIMITED && current_message_size > max_message_size_) { recv_buffer_size_ = 0; recv_buffer_.resize(recv_buffer_size_initial_, 0x0); recv_buffer_.shrink_to_fit(); if (magic_cookies_enabled_) { std::lock_guard<std::mutex> its_lock(socket_mutex_); VSOMEIP_ERROR << "Received a TCP message which exceeds " << "maximum message size (" << std::dec << current_message_size << " > " << std::dec << max_message_size_ << "). Magic Cookies are enabled: " << "Resetting receiver. local: " << get_address_port_local() << " remote: " << get_address_port_remote(); } else { { std::lock_guard<std::mutex> its_lock(socket_mutex_); VSOMEIP_ERROR << "Received a TCP message which exceeds " << "maximum message size (" << std::dec << current_message_size << " > " << std::dec << max_message_size_ << ") Magic cookies are disabled: " << "Connection will be closed! local: " << get_address_port_local() << " remote: " << get_address_port_remote(); } wait_until_sent(boost::asio::error::operation_aborted); return; } } else if (current_message_size > recv_buffer_size_) { missing_capacity_ = current_message_size - static_cast<std::uint32_t>(recv_buffer_size_); } else if (VSOMEIP_SOMEIP_HEADER_SIZE > recv_buffer_size_) { missing_capacity_ = VSOMEIP_SOMEIP_HEADER_SIZE - static_cast<std::uint32_t>(recv_buffer_size_); } else if (magic_cookies_enabled_ && recv_buffer_size_ > 0) { // no need to check for magic cookie here again: has_full_message // would have been set to true if there was one present in the data recv_buffer_size_ = 0; recv_buffer_.resize(recv_buffer_size_initial_, 0x0); recv_buffer_.shrink_to_fit(); missing_capacity_ = 0; std::lock_guard<std::mutex> its_lock(socket_mutex_); VSOMEIP_ERROR << "Didn't find magic cookie in broken" << " data, trying to resync." << " local: " << get_address_port_local() << " remote: " << get_address_port_remote(); } else { { std::lock_guard<std::mutex> its_lock(socket_mutex_); VSOMEIP_ERROR << "tse::c<" << this << ">rcb: recv_buffer_size is: " << std::dec << recv_buffer_size_ << " but couldn't read " "out message_size. recv_buffer_capacity: " << recv_buffer_.capacity() << " its_iteration_gap: " << its_iteration_gap << "local: " << get_address_port_local() << " remote: " << get_address_port_remote() << ". Closing connection due to missing/broken data TCP stream."; } wait_until_sent(boost::asio::error::operation_aborted); return; } } } while (has_full_message && recv_buffer_size_); if (its_iteration_gap) { // Copy incomplete message to front for next receive_cbk iteration for (size_t i = 0; i < recv_buffer_size_; ++i) { recv_buffer_[i] = recv_buffer_[i + its_iteration_gap]; } // Still more capacity needed after shifting everything to front? if (missing_capacity_ && missing_capacity_ <= recv_buffer_.capacity() - recv_buffer_size_) { missing_capacity_ = 0; } } receive(); } } if (_error == boost::asio::error::eof || _error == boost::asio::error::connection_reset || _error == boost::asio::error::timed_out) { if(_error == boost::asio::error::timed_out) { std::lock_guard<std::mutex> its_lock(socket_mutex_); VSOMEIP_WARNING << "tcp_server_endpoint receive_cbk: " << _error.message() << " local: " << get_address_port_local() << " remote: " << get_address_port_remote(); } wait_until_sent(boost::asio::error::operation_aborted); } } void tcp_server_endpoint_impl::connection::calculate_shrink_count() { if (buffer_shrink_threshold_) { if (recv_buffer_.capacity() != recv_buffer_size_initial_) { if (recv_buffer_size_ < (recv_buffer_.capacity() >> 1)) { shrink_count_++; } else { shrink_count_ = 0; } } } } void tcp_server_endpoint_impl::connection::set_remote_info( const endpoint_type &_remote) { remote_ = _remote; remote_address_ = _remote.address(); remote_port_ = _remote.port(); } const std::string tcp_server_endpoint_impl::connection::get_address_port_remote() const { std::string its_address_port; its_address_port.reserve(21); boost::system::error_code ec; its_address_port += remote_address_.to_string(ec); its_address_port += ":"; its_address_port += std::to_string(remote_port_); return its_address_port; } const std::string tcp_server_endpoint_impl::connection::get_address_port_local() const { std::string its_address_port; its_address_port.reserve(21); boost::system::error_code ec; if (socket_.is_open()) { endpoint_type its_local_endpoint = socket_.local_endpoint(ec); if (!ec) { its_address_port += its_local_endpoint.address().to_string(ec); its_address_port += ":"; its_address_port += std::to_string(its_local_endpoint.port()); } } return its_address_port; } void tcp_server_endpoint_impl::connection::handle_recv_buffer_exception( const std::exception &_e) { std::stringstream its_message; its_message <<"tcp_server_endpoint_impl::connection catched exception" << _e.what() << " local: " << get_address_port_local() << " remote: " << get_address_port_remote() << " shutting down connection. Start of buffer: "; for (std::size_t i = 0; i < recv_buffer_size_ && i < 16; i++) { its_message << std::setw(2) << std::setfill('0') << std::hex << (int) (recv_buffer_[i]) << " "; } its_message << " Last 16 Bytes captured: "; for (int i = 15; recv_buffer_size_ > 15 && i >= 0; i--) { its_message << std::setw(2) << std::setfill('0') << std::hex << (int) (recv_buffer_[static_cast<size_t>(i)]) << " "; } VSOMEIP_ERROR << its_message.str(); recv_buffer_.clear(); if (socket_.is_open()) { boost::system::error_code its_error; socket_.shutdown(socket_.shutdown_both, its_error); socket_.close(its_error); } std::shared_ptr<tcp_server_endpoint_impl> its_server = server_.lock(); if (its_server) { its_server->remove_connection(this); } } std::size_t tcp_server_endpoint_impl::connection::get_recv_buffer_capacity() const { return recv_buffer_.capacity(); } std::size_t tcp_server_endpoint_impl::connection::write_completion_condition( const boost::system::error_code& _error, std::size_t _bytes_transferred, std::size_t _bytes_to_send, service_t _service, method_t _method, client_t _client, session_t _session, const std::chrono::steady_clock::time_point _start) { if (_error) { VSOMEIP_ERROR << "tse::write_completion_condition: " << _error.message() << "(" << std::dec << _error.value() << ") bytes transferred: " << std::dec << _bytes_transferred << " bytes to sent: " << std::dec << _bytes_to_send << " " << "remote:" << get_address_port_remote() << " (" << std::hex << std::setw(4) << std::setfill('0') << _client <<"): [" << std::hex << std::setw(4) << std::setfill('0') << _service << "." << std::hex << std::setw(4) << std::setfill('0') << _method << "." << std::hex << std::setw(4) << std::setfill('0') << _session << "]"; stop_and_remove_connection(); return 0; } const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); const std::chrono::milliseconds passed = std::chrono::duration_cast<std::chrono::milliseconds>(now - _start); if (passed > send_timeout_warning_) { if (passed > send_timeout_) { VSOMEIP_ERROR << "tse::write_completion_condition: " << _error.message() << "(" << std::dec << _error.value() << ") took longer than " << std::dec << send_timeout_.count() << "ms bytes transferred: " << std::dec << _bytes_transferred << " bytes to sent: " << std::dec << _bytes_to_send << " remote:" << get_address_port_remote() << " (" << std::hex << std::setw(4) << std::setfill('0') << _client <<"): [" << std::hex << std::setw(4) << std::setfill('0') << _service << "." << std::hex << std::setw(4) << std::setfill('0') << _method << "." << std::hex << std::setw(4) << std::setfill('0') << _session << "]"; } else { VSOMEIP_WARNING << "tse::write_completion_condition: " << _error.message() << "(" << std::dec << _error.value() << ") took longer than " << std::dec << send_timeout_warning_.count() << "ms bytes transferred: " << std::dec << _bytes_transferred << " bytes to sent: " << std::dec << _bytes_to_send << " remote:" << get_address_port_remote() << " (" << std::hex << std::setw(4) << std::setfill('0') << _client <<"): [" << std::hex << std::setw(4) << std::setfill('0') << _service << "." << std::hex << std::setw(4) << std::setfill('0') << _method << "." << std::hex << std::setw(4) << std::setfill('0') << _session << "]"; } } return _bytes_to_send - _bytes_transferred; } void tcp_server_endpoint_impl::connection::stop_and_remove_connection() { std::shared_ptr<tcp_server_endpoint_impl> its_server(server_.lock()); if (!its_server) { VSOMEIP_ERROR << "tse::connection::stop_and_remove_connection " " couldn't lock server_"; return; } { std::lock_guard<std::mutex> its_lock(its_server->connections_mutex_); stop(); } its_server->remove_connection(this); } // Dummies void tcp_server_endpoint_impl::receive() { // intentionally left empty } void tcp_server_endpoint_impl::print_status() { std::lock_guard<std::mutex> its_lock(mutex_); connections_t its_connections; { std::lock_guard<std::mutex> its_lock(connections_mutex_); its_connections = connections_; } VSOMEIP_INFO << "status tse: " << std::dec << local_port_ << " connections: " << std::dec << its_connections.size() << " queues: " << std::dec << queues_.size(); for (const auto &c : its_connections) { std::size_t its_data_size(0); std::size_t its_queue_size(0); std::size_t its_recv_size(0); { std::unique_lock<std::mutex> c_s_lock(c.second->get_socket_lock()); its_recv_size = c.second->get_recv_buffer_capacity(); } auto found_queue = queues_.find(c.first); if (found_queue != queues_.end()) { its_queue_size = found_queue->second.second.size(); its_data_size = found_queue->second.first; } VSOMEIP_INFO << "status tse: client: " << c.second->get_address_port_remote() << " queue: " << std::dec << its_queue_size << " data: " << std::dec << its_data_size << " recv_buffer: " << std::dec << its_recv_size; } } std::string tcp_server_endpoint_impl::get_remote_information( const queue_iterator_type _queue_iterator) const { boost::system::error_code ec; return _queue_iterator->first.address().to_string(ec) + ":" + std::to_string(_queue_iterator->first.port()); } std::string tcp_server_endpoint_impl::get_remote_information( const endpoint_type& _remote) const { boost::system::error_code ec; return _remote.address().to_string(ec) + ":" + std::to_string(_remote.port()); } bool tcp_server_endpoint_impl::tp_segmentation_enabled(service_t _service, method_t _method) const { (void)_service; (void)_method; return false; } void tcp_server_endpoint_impl::connection::wait_until_sent(const boost::system::error_code &_error) { std::shared_ptr<tcp_server_endpoint_impl> its_server(server_.lock()); std::unique_lock<std::mutex> its_sent_lock(its_server->sent_mutex_); if (!its_server->is_sending_ || !_error) { its_sent_lock.unlock(); if (!_error) VSOMEIP_WARNING << __func__ << ": Maximum wait time for send operation exceeded for tse."; { std::lock_guard<std::mutex> its_lock(its_server->connections_mutex_); stop(); } its_server->remove_connection(this); } else { std::chrono::milliseconds its_timeout(VSOMEIP_MAX_TCP_SENT_WAIT_TIME); boost::system::error_code ec; its_server->sent_timer_.expires_from_now(its_timeout, ec); its_server->sent_timer_.async_wait(std::bind(&tcp_server_endpoint_impl::connection::wait_until_sent, std::dynamic_pointer_cast<tcp_server_endpoint_impl::connection>(shared_from_this()), std::placeholders::_1)); } } } // namespace vsomeip_v3
47.383282
148
0.553557
1cd624056df2e7aaa352ab483ad1d97874aba4d5
2,228
cpp
C++
src/code-examples/chapter-04/printing-people/main.cpp
nhatvu148/helpers
1a6875017cf39790dfe40ecec9dcee4410b1d89e
[ "MIT" ]
null
null
null
src/code-examples/chapter-04/printing-people/main.cpp
nhatvu148/helpers
1a6875017cf39790dfe40ecec9dcee4410b1d89e
[ "MIT" ]
null
null
null
src/code-examples/chapter-04/printing-people/main.cpp
nhatvu148/helpers
1a6875017cf39790dfe40ecec9dcee4410b1d89e
[ "MIT" ]
null
null
null
#include <string> #include <iostream> #include <vector> #include <algorithm> #include <functional> #include <fstream> #include "../../common/person.h" void print_person(const person_t &person, std::ostream &out, person_t::output_format_t format) { if (format == person_t::name_only) { out << person.name() << '\n'; } else if (format == person_t::full_name) { out << person.name() << ' ' << person.surname() << '\n'; } } int main(int argc, char *argv[]) { using namespace std::placeholders; std::vector<person_t> people { { "David" , person_t::male }, { "Jane" , person_t::female }, { "Martha" , person_t::female }, { "Peter" , person_t::male }, { "Rose" , person_t::female }, { "Tom" , person_t::male } }; std::ofstream file("test"); // Passing a non-member function as the function object to std::bind std::for_each(people.cbegin(), people.cend(), std::bind(print_person, _1, std::ref(std::cout), person_t::name_only )); std::for_each(people.cbegin(), people.cend(), std::bind(print_person, _1, std::ref(file), person_t::full_name )); // Passing a member function pointer to std::bind std::for_each(people.cbegin(), people.cend(), std::bind(&person_t::print, _1, std::ref(std::cout), person_t::name_only )); // Passing a lambda function instead of using std::bind std::for_each(people.cbegin(), people.cend(), [] (const person_t &person) { print_person(person, std::cout, person_t::name_only); }); std::for_each(people.cbegin(), people.cend(), [&file] (const person_t &person) { print_person(person, file, person_t::full_name); }); return 0; }
27.85
72
0.474865
1cdb59d29336c26315412dcf45704dbc2251c68b
4,803
cc
C++
deps/smmr/example/client_server/client_server.cc
xflagstudio/network-bfd-sample
89a21dd7ff195527fd8c3ce811ed0520acaac6b5
[ "MIT" ]
6
2017-03-24T08:37:39.000Z
2020-07-24T08:08:30.000Z
deps/smmr/example/client_server/client_server.cc
xflagstudio/network-bfd-sample
89a21dd7ff195527fd8c3ce811ed0520acaac6b5
[ "MIT" ]
null
null
null
deps/smmr/example/client_server/client_server.cc
xflagstudio/network-bfd-sample
89a21dd7ff195527fd8c3ce811ed0520acaac6b5
[ "MIT" ]
2
2017-07-17T03:25:34.000Z
2019-06-09T18:14:15.000Z
#include "smmr_pagedbuffer.h" #include "smmr_categories.h" #include "smmr_memory.h" #include "smmr_database.h" #include "smmr_tree.h" #include <sys/types.h> #include <sys/wait.h> #define UNUSED(x) (void)(x) const char *SERVER_MSGKEY = "from_server_to_client"; char SERVER_HELLOW[] = "hellow client."; const char *CLIENT_MSGKEY = "from_client_to_server"; char CLIENT_HELLOW[] = "hi server."; #define CLIENT_TO (10) // ----------------------- // クライアント // ----------------------- static void do_client(void){ // ipcshm_categories_ptr CATEGORIES_C = (ipcshm_categories_ptr)-1; ipcshm_datafiles_ptr DATAFILES_C = (ipcshm_datafiles_ptr)-1; datafiles_on_process_t DATAFILES_INDEX_C; categories_on_process_t CATEGORIES_INDEX_C; tree_instance_ptr ROOT_C; printf("client\n"); // if (childinit_categories_area(&CATEGORIES_C,&CATEGORIES_INDEX_C) != RET_OK){ exit(1); } if (childinit_db_area(&DATAFILES_C,&DATAFILES_INDEX_C) != RET_OK){ exit(3); } // インデックス ルートオブジェクト構築 ROOT_C = create_tree_unsafe(CATEGORIES_C,&CATEGORIES_INDEX_C); if (!ROOT_C){ exit(2); } // サーバメッセージを読み取る char *resp = NULL; uint32_t resplen = 0; // if (search(DATAFILES_C,&DATAFILES_INDEX_C,ROOT_C,SERVER_MSGKEY,strlen(SERVER_MSGKEY),&resp,&resplen) == RET_OK){ if (resp && resplen){ printf("from server .. %s == %s\n", SERVER_HELLOW, resp); }else{ fprintf(stderr, "failed.search.:resp(%s)\n", SERVER_MSGKEY); } }else{ fprintf(stderr, "failed.search.(%s)\n", SERVER_MSGKEY); } // ack to server if (store(DATAFILES_C,&DATAFILES_INDEX_C,ROOT_C,CLIENT_MSGKEY,strlen(CLIENT_MSGKEY),CLIENT_HELLOW,strlen(CLIENT_HELLOW),0)!= RET_OK){ fprintf(stderr, "failed.store.(%s)\n", CLIENT_MSGKEY); } // 子プロセスでリソース解放 if (childuninit_db_area(&DATAFILES_C,&DATAFILES_INDEX_C) != RET_OK){ exit(4); } if (ROOT_C != NULL){ free(ROOT_C); } ROOT_C = NULL; if (childuninit_categories_area(&CATEGORIES_C,&CATEGORIES_INDEX_C) != RET_OK){ exit(5); } printf("client-completed.\n"); } // ----------------------- // サーバ // ----------------------- static void do_server(pid_t pid){ printf("server\n"); // ipcshm_categories_ptr CATEGORIES = (ipcshm_categories_ptr)-1; ipcshm_datafiles_ptr DATAFILES = (ipcshm_datafiles_ptr)-1; datafiles_on_process_t DATAFILES_INDEX; categories_on_process_t CATEGORIES_INDEX; tree_instance_ptr ROOT; int cstat = 0; int timeout = 0; char index_dir[128] = {0},data_dir[128] = {0}; snprintf(index_dir,sizeof(index_dir)-1,"/tmp/%u/", (unsigned)getpid()); mkdir(index_dir,0755); snprintf(data_dir,sizeof(data_dir)-1,"/tmp/%u/db/", (unsigned)getpid()); mkdir(data_dir,0755); // システム初期化 // サーバプロセスでインデクス初期化 if (create_categories_area(index_dir,&CATEGORIES,&CATEGORIES_INDEX) != RET_OK){ exit(1); } if (init_categories_from_file(CATEGORIES,&CATEGORIES_INDEX,0) != RET_OK){ exit(1); } if (rebuild_pages_area(&CATEGORIES_INDEX) != RET_OK){ exit(1); } // サーバプロセスでデータファイル初期化 if (create_db_area_parent(data_dir,&DATAFILES) != RET_OK){ exit(1); } if (init_datafiles_from_file(DATAFILES,&DATAFILES_INDEX) != RET_OK){ exit(1); } // ツリールート if ((ROOT = create_tree_unsafe(CATEGORIES,&CATEGORIES_INDEX)) ==NULL){ exit(1); } // サーバでデータを書き込み if (store(DATAFILES,&DATAFILES_INDEX,ROOT,SERVER_MSGKEY,strlen(SERVER_MSGKEY),SERVER_HELLOW,strlen(SERVER_HELLOW),0)!= RET_OK){ exit(1); } // クライアントのデータ書き込みを待機 for(timeout=0;timeout < CLIENT_TO;timeout++){ char *resp = NULL; uint32_t resplen = 0; sleep(1); if (search(DATAFILES,&DATAFILES_INDEX,ROOT,CLIENT_MSGKEY,strlen(CLIENT_MSGKEY),&resp,&resplen) == RET_OK){ if (resp && resplen){ printf("%s -> %s\n",CLIENT_MSGKEY, resp); free(resp); } break; } fprintf(stderr, "nothing client. responce...(%d)\n", timeout); } if (timeout >= CLIENT_TO){ fprintf(stderr, "timeout client. responce...\n"); } // parent pid_t pidr = waitpid(pid, &cstat, 0); printf("waitpid(for client complete) /%d -> %d : %d\n",pid ,pidr, cstat); // システム終了処理 if (remove_db_area_parent(&DATAFILES,&DATAFILES_INDEX) != RET_OK){ exit(1); } if (remove_categories_area(&CATEGORIES,&CATEGORIES_INDEX) != RET_OK){ exit(1); } remove_safe(index_dir); remove_safe(data_dir); } int main(int argc, char** argv) { pid_t pid = fork(); // if (pid < 0){ exit(1); }else if (pid == 0){ // wait for prepared shared area from parent. sleep(3); do_client(); exit(0); }else{ do_server(pid); } return(0); }
34.804348
142
0.634812
1cdd107e2bbce48e8df7103aa1c0817e30708734
985
cpp
C++
09_QueueWithTwoStacks/main09.cpp
HaoliangLi/CodingInterviewChinese2
c3ae0d7bec404d92dc3f5f395ccefb5455d08eb3
[ "BSD-3-Clause" ]
null
null
null
09_QueueWithTwoStacks/main09.cpp
HaoliangLi/CodingInterviewChinese2
c3ae0d7bec404d92dc3f5f395ccefb5455d08eb3
[ "BSD-3-Clause" ]
null
null
null
09_QueueWithTwoStacks/main09.cpp
HaoliangLi/CodingInterviewChinese2
c3ae0d7bec404d92dc3f5f395ccefb5455d08eb3
[ "BSD-3-Clause" ]
null
null
null
/*** * @Date: 2021-11-27 17:36:41 * @LastEditors: zjulhl * @LastEditTime: 2021-11-28 13:25:47 * @Description: * @FilePath: /CodingInterviewChinese2/09_QueueWithTwoStacks/main09.cpp */ #include <stack> using namespace std; class CQueue { stack<int> stack1, stack2; public: CQueue() { while (!stack1.empty()) { stack1.pop(); } while (!stack2.empty()) { stack2.pop(); } } void appendTail(int value) { stack1.push(value); } int deleteHead() { // 如果第二个栈为空 if (stack2.empty()) { while (!stack1.empty()) { stack2.push(stack1.top()); stack1.pop(); } } if (stack2.empty()) { return -1; } else { int deleteItem = stack2.top(); stack2.pop(); return deleteItem; } } };
17.589286
71
0.447716
1cde2492418251c053d007af77a2e1f334cd06e9
228
hpp
C++
include/FindTheDifference.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
43
2015-10-10T12:59:52.000Z
2018-07-11T18:07:00.000Z
include/FindTheDifference.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
null
null
null
include/FindTheDifference.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
11
2015-10-10T14:41:11.000Z
2018-07-28T06:03:16.000Z
#ifndef FIND_THE_DIFFERENCE_HPP_ #define FIND_THE_DIFFERENCE_HPP_ #include <string> using namespace std; class FindTheDifference { public: char findTheDifference(string s, string t); }; #endif // FIND_THE_DIFFERENCE_HPP_
17.538462
47
0.798246
1ce098a977b00d0e57343ab54ff9a2978c182aec
1,218
cpp
C++
Solutions/Longest Valid Parentheses/main.cpp
Crayzero/LeetCodeProgramming
b10ebe22c0de1501722f0f5c934c0c1902a26789
[ "MIT" ]
1
2015-04-13T10:58:30.000Z
2015-04-13T10:58:30.000Z
Solutions/Longest Valid Parentheses/main.cpp
Crayzero/LeetCodeProgramming
b10ebe22c0de1501722f0f5c934c0c1902a26789
[ "MIT" ]
null
null
null
Solutions/Longest Valid Parentheses/main.cpp
Crayzero/LeetCodeProgramming
b10ebe22c0de1501722f0f5c934c0c1902a26789
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: int longestValidParentheses(string s) { int s_size = s.size(); if (s_size <= 1) { return 0; } int *dp = new int [s_size]; for(int i = 0; i < s_size; i++) { dp[i] = 0; } int res = 0; for(int i = 1; i < s_size; i++) { if (s[i] == ')' && s[i-1] == '(') { dp[i] = (i>=2 ? dp[i-2] : 0) + 2; } else if (dp[i-1] != 0 && s[i] == ')') { if (i-dp[i-1] > 0 && s[i-dp[i-1]-1] == '(') { dp[i] = dp[i-1] + 2; if (i-dp[i] > 0 && dp[i-dp[i]] != 0) { dp[i] = dp[i] + dp[i-dp[i]]; } } } else { dp[i] = 0; } res = max(res, dp[i]); for(int i = 0; i < s_size; i++) { cout<<dp[i]<<" "; } cout<<endl; } return res; } }; int main() { string s1 = "()(())"; string s2 = "(()())"; Solution s; cout<<s.longestValidParentheses(s1); return 0; }
23.882353
61
0.325123
1ce1eaa1c65f735565091b2e87477fb75e979f02
2,271
hpp
C++
include/Core/Castor3D/Render/ShadowMap/ShadowMapPassPoint.hpp
Mu-L/Castor3D
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
[ "MIT" ]
245
2015-10-29T14:31:45.000Z
2022-03-31T13:04:45.000Z
include/Core/Castor3D/Render/ShadowMap/ShadowMapPassPoint.hpp
Mu-L/Castor3D
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
[ "MIT" ]
64
2016-03-11T19:45:05.000Z
2022-03-31T23:58:33.000Z
include/Core/Castor3D/Render/ShadowMap/ShadowMapPassPoint.hpp
Mu-L/Castor3D
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
[ "MIT" ]
11
2018-05-24T09:07:43.000Z
2022-03-21T21:05:20.000Z
/* See LICENSE file in root folder */ #ifndef ___C3D_SHADOW_MAP_PASS_POINT_H___ #define ___C3D_SHADOW_MAP_PASS_POINT_H___ #include "ShadowMapModule.hpp" #include "Castor3D/Render/ShadowMap/ShadowMapPass.hpp" #include "Castor3D/Render/Viewport.hpp" #include <ashespp/Buffer/UniformBuffer.hpp> namespace castor3d { class ShadowMapPassPoint : public ShadowMapPass { public: /** *\~english *\brief Constructor. *\param[in] engine The engine. *\param[in] index The pass index. *\param[in] matrixUbo The scene matrices UBO. *\param[in] culler The culler for this pass. *\param[in] shadowMap The parent shadow map. *\~french *\brief Constructeur. *\param[in] engine Le moteur. *\param[in] index L'indice de la passe. *\param[in] matrixUbo L'UBO de matrices de la scène. *\param[in] culler Le culler pour cette passe. *\param[in] shadowMap La shadow map parente. */ C3D_API ShadowMapPassPoint( crg::FramePass const & pass , crg::GraphContext & context , crg::RunnableGraph & graph , RenderDevice const & device , uint32_t index , MatrixUbo & matrixUbo , SceneCuller & culler , ShadowMap const & shadowMap ); /** *\~english *\brief Destructor. *\~french *\brief Destructeur. */ C3D_API ~ShadowMapPassPoint()override; /** *\copydoc castor3d::ShadowMapPass::update */ bool update( CpuUpdater & updater )override; /** *\copydoc castor3d::ShadowMapPass::update */ void update( GpuUpdater & updater )override; protected: void doUpdateNodes( QueueCulledRenderNodes & nodes ); private: void doUpdateUbos( CpuUpdater & updater )override; ashes::PipelineDepthStencilStateCreateInfo doCreateDepthStencilState( PipelineFlags const & flags )const override; ashes::PipelineColorBlendStateCreateInfo doCreateBlendState( PipelineFlags const & flags )const override; void doUpdateFlags( PipelineFlags & flags )const override; ShaderPtr doGetVertexShaderSource( PipelineFlags const & flags )const override; ShaderPtr doGetPixelShaderSource( PipelineFlags const & flags )const override; public: C3D_API static uint32_t const TextureSize; private: OnSceneNodeChangedConnection m_onNodeChanged; castor::Matrix4x4f m_projection; }; } #endif
28.037037
116
0.730956
1ce309004a88acddaa5b3abce61c11ee69147d9b
309
cpp
C++
2_formulas/is_leap.cpp
alphaolomi/cpp-examples
eda9c371ddf4264f2830425c036fd1570b9efda1
[ "Apache-2.0" ]
null
null
null
2_formulas/is_leap.cpp
alphaolomi/cpp-examples
eda9c371ddf4264f2830425c036fd1570b9efda1
[ "Apache-2.0" ]
null
null
null
2_formulas/is_leap.cpp
alphaolomi/cpp-examples
eda9c371ddf4264f2830425c036fd1570b9efda1
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int main() { int year; cout << "Enter a year: " << endl; cin >> year; if ((year % 4) == 0) { cout << " Leap Year "; } else { cout << " Not a Leap Year" << endl; } return 0; } /* Enter a year: 2016 Leap Year */
12.875
43
0.466019
1ce568a02137152b50ce38760832e528aa88db29
3,318
cpp
C++
examples/rara.cpp
rodriguescr/libfastlib
b89172ae727cd36f84d0d02359ce635eb11b8472
[ "BSD-3-Clause-LBNL" ]
null
null
null
examples/rara.cpp
rodriguescr/libfastlib
b89172ae727cd36f84d0d02359ce635eb11b8472
[ "BSD-3-Clause-LBNL" ]
null
null
null
examples/rara.cpp
rodriguescr/libfastlib
b89172ae727cd36f84d0d02359ce635eb11b8472
[ "BSD-3-Clause-LBNL" ]
null
null
null
// $Id$ // Author: John Wu <John.Wu at ACM.org> Lawrence Berkeley National Laboratory // Copyright (c) 2008-2017 the Regents of the University of California /** @file rara.cpp This is meant to be the simplest test program for the querying functions of ibis::query and ibis::part. It accepts the following fixed list of arguments to simplify the program: data-dir query-conditions [column-to-print [column-to-print ...]] The data-dir must exist and contain valid data files and query conditions much be specified as well. If no column-to-print, this program effective is answering the following SQL query SELECT count(*) FROM data-dir WHERE query-conditions If any column-to-print is specified, all of them are concatenated together and the SQL query answered is of the form SELECT column-to-print, column-to-print, ... FROM data-dir WHERE query-conditions About the name: Bostrychia rara, Spot-breasted Ibis, the smallest ibis <http://www.sandiegozoo.org/animalbytes/t-ibis.html>. As an example program for using FastBit IBIS, this might be also the smallest. @ingroup FastBitExamples */ #include "ibis.h" // FastBit IBIS primary include file // printout the usage string static void usage(const char* name) { std::cout << "usage:\n" << name << " data-dir query-conditions" << " [column-to-print [column-to-print ...]]\n" << std::endl; } // usage int main(int argc, char** argv) { if (argc < 3) { usage(*argv); return -1; } // construct a data partition from the given data directory. ibis::part apart(argv[1], static_cast<const char*>(0)); // create a query object with the current user name. ibis::query aquery(ibis::util::userName(), &apart); // assign the query conditions as the where clause. int ierr = aquery.setWhereClause(argv[2]); if (ierr < 0) { std::clog << *argv << " setWhereClause(" << argv[2] << ") failed with error code " << ierr << std::endl; return -2; } // collect all column-to-print together std::string sel; for (int j = 3; j < argc; ++ j) { if (j > 3) sel += ", "; sel += argv[j]; } if (sel.empty()) { // select count(*)... ierr = aquery.evaluate(); // evaluate the query std::cout << "SELECT count(*) FROM " << argv[1] << " WHERE " << argv[2] << "\n--> "; if (ierr >= 0) { std::cout << aquery.getNumHits(); } else { std::cout << "error " << ierr; } } else { // select column-to-print... ierr = aquery.setSelectClause(sel.c_str()); if (ierr < 0) { std::clog << *argv << " setSelectClause(" << sel << ") failed with error code " << ierr << std::endl; return -3; } ierr = aquery.evaluate(); // evaluate the query std::cout << "SELECT " << sel << " FROM " << argv[1] << " WHERE " << argv[2] << "\n--> "; if (ierr >= 0) { // print out the select values aquery.printSelected(std::cout); } else { std::cout << "error " << ierr; } } std::cout << std::endl; return ierr; } // main
35.677419
85
0.570223
1ce6121b396bcd37b7818d11901a5a873c67387c
193
hpp
C++
src/linux/linux_platform.hpp
NickCao/ebpf-verifier
ccbfd158ca2b4c24b91c235ce21a1fbd192d458e
[ "Apache-2.0", "MIT" ]
181
2019-03-12T22:39:25.000Z
2022-03-28T13:34:35.000Z
src/linux/linux_platform.hpp
NickCao/ebpf-verifier
ccbfd158ca2b4c24b91c235ce21a1fbd192d458e
[ "Apache-2.0", "MIT" ]
153
2019-02-21T18:44:11.000Z
2022-03-31T23:22:11.000Z
src/linux/linux_platform.hpp
NickCao/ebpf-verifier
ccbfd158ca2b4c24b91c235ce21a1fbd192d458e
[ "Apache-2.0", "MIT" ]
30
2019-04-19T18:33:55.000Z
2022-01-04T19:49:31.000Z
// Copyright (c) Prevail Verifier contributors. // SPDX-License-Identifier: MIT #pragma once EbpfHelperPrototype get_helper_prototype_linux(int32_t n); bool is_helper_usable_linux(int32_t n);
27.571429
58
0.818653
1ce74f81493c64aa21f249d0f83e812d93f2f98d
306
cpp
C++
tutorials/learncpp.com#1.0#1/variables_part_ii/enumerated_types/source2.cpp
officialrafsan/CppDroid
5fb2cc7750fea53b1ea6ff47b5094da6e95e9224
[ "MIT" ]
null
null
null
tutorials/learncpp.com#1.0#1/variables_part_ii/enumerated_types/source2.cpp
officialrafsan/CppDroid
5fb2cc7750fea53b1ea6ff47b5094da6e95e9224
[ "MIT" ]
null
null
null
tutorials/learncpp.com#1.0#1/variables_part_ii/enumerated_types/source2.cpp
officialrafsan/CppDroid
5fb2cc7750fea53b1ea6ff47b5094da6e95e9224
[ "MIT" ]
null
null
null
enum Color { COLOR_BLACK, // assigned 0 COLOR_RED, // assigned 1 COLOR_BLUE, // assigned 2 COLOR_GREEN, // assigned 3 COLOR_WHITE, // assigned 4 COLOR_CYAN, // assigned 5 COLOR_YELLOW, // assigned 6 COLOR_MAGENTA // assigned 7 }; Color eColor = COLOR_WHITE; cout << eColor;
21.857143
31
0.653595
1ce9df55b36a4a6a72489cde35526546cb787727
1,236
hpp
C++
src/shuffler.hpp
nikolaimerkel/edgepart
58b3d57eebd850dfdd7016e90352bddcf840e1f5
[ "MIT" ]
21
2018-04-19T07:27:18.000Z
2022-02-23T19:33:04.000Z
src/shuffler.hpp
nikolaimerkel/edgepart
58b3d57eebd850dfdd7016e90352bddcf840e1f5
[ "MIT" ]
1
2020-12-30T01:40:51.000Z
2021-02-20T03:36:17.000Z
src/shuffler.hpp
nikolaimerkel/edgepart
58b3d57eebd850dfdd7016e90352bddcf840e1f5
[ "MIT" ]
9
2019-06-19T13:40:57.000Z
2021-12-09T19:30:50.000Z
#pragma once #include <string> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "util.hpp" #include "conversions.hpp" class Shuffler : public Converter { private: struct work_t { Shuffler *shuffler; int nchunks; std::vector<edge_t> chunk_buf; void operator()() { std::random_shuffle(chunk_buf.begin(), chunk_buf.end()); int file = open(shuffler->chunk_filename(nchunks).c_str(), O_WRONLY | O_CREAT, S_IROTH | S_IWOTH | S_IWUSR | S_IRUSR); size_t chunk_size = chunk_buf.size() * sizeof(edge_t); writea(file, (char *)&chunk_buf[0], chunk_size); close(file); chunk_buf.clear(); } }; size_t chunk_bufsize; int nchunks, old_nchunks; std::vector<edge_t> chunk_buf, old_chunk_buf; std::string chunk_filename(int chunk); void chunk_clean(); void cwrite(edge_t e, bool flush = false); public: Shuffler(std::string basefilename) : Converter(basefilename) {} bool done() { return is_exists(shuffled_binedgelist_name(basefilename)); } void init(); void finalize(); void add_edge(vid_t source, vid_t target); };
26.297872
80
0.618123
1cec0fe776c42b019c1dff63883f60e3d7408525
31,587
cc
C++
MT_systems/matxin-lex/squoia_xfer_lex.cc
ariosquoia/squoia
3f3c3c253bdb2d891889e0427790e6c972870f08
[ "Apache-2.0" ]
9
2016-04-27T16:48:58.000Z
2021-01-17T21:55:55.000Z
MT_systems/matxin-lex/squoia_xfer_lex.cc
ariosquoia/squoia
3f3c3c253bdb2d891889e0427790e6c972870f08
[ "Apache-2.0" ]
null
null
null
MT_systems/matxin-lex/squoia_xfer_lex.cc
ariosquoia/squoia
3f3c3c253bdb2d891889e0427790e6c972870f08
[ "Apache-2.0" ]
6
2016-03-29T22:26:50.000Z
2021-01-17T21:56:21.000Z
/* * Copyright (C) 2005 IXA Research Group / IXA Ikerkuntza Taldea. * * 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 */ /* * This file has been adapted for SQUOIA. */ #include <lttoolbox/fst_processor.h> #include <lttoolbox/ltstr.h> #include <lttoolbox/xml_parse_util.h> #include <string> #include <iostream> #include <sstream> #include <fstream> #include <locale> #include <getopt.h> #include <libgen.h> #include <wctype.h> using namespace std; // Method prototypes // from string_utils: tolower wstring tolower(wstring const &s); // from data_manager: init_lexInfo, get_lexInfo, lexical_selection void init_lexInfo(wstring name, string fitxName); wstring get_lexInfo(wstring name, wstring type_es); vector<wstring> lexical_selection(wstring parent_attributes, wstring common_attributes, vector<wstring> child_attributes); // from matxin_string_utils void Tokenize(const wstring& str, vector<wstring>& tokens, const wstring& delimiter = L" "); void Tokenize2(const wstring& str, wstring& tokens, const wstring& delimiter = L" "); /* * Splits multi-attribute text from a elment into * attributes from separate elements. * * For example, having this input string: * str = L"lem='beste\bat' pos='[DET][DZG]\[DET][DZH]' pos='4'" * it will return a vector with these elements: * v = {L"lem='beste' pos='[DET][DZG]' pos='4'" , * L"lem='bat' pos='[DET][DZH]' pos='4'"} */ vector<wstring> split_multiattrib(wstring str); wstring v2s(vector<wstring> vector, wstring delimiter = L" "); // from XML_reader string xmlc2s(xmlChar const * entrada); wstring write_xml(wstring input); wstring getTagName(xmlTextReaderPtr reader); int nextTag(xmlTextReaderPtr reader); wstring attrib(xmlTextReaderPtr reader, string const &nombre); wstring allAttrib(xmlTextReaderPtr reader); wstring allAttrib_except(xmlTextReaderPtr reader, wstring attrib_no); wstring text_attrib(wstring attributes, wstring const &nombre); wstring text_allAttrib_except(wstring attributes, const wstring &nombre); // original matxin_xfer_lex wstring upper_type(wstring form, wstring mi, wstring ord); wstring get_dict_attributes(const wstring full); wstring getsyn(vector<wstring> translations); void order_ordainak(vector<wstring> &ordainak); vector<wstring> disambiguate(wstring &full); vector<wstring> get_translation(wstring lem, wstring mi, bool &unknown); wstring multiNodes (wstring &full, wstring attributes); std::pair<wstring,wstring> procNODE(xmlTextReaderPtr reader, bool head, wstring parent_attribs, wstring& attributes); wstring procCHUNK(xmlTextReaderPtr reader, wstring parent_attribs); wstring procSENTENCE (xmlTextReaderPtr reader); void endProgram(char *name); FSTProcessor fstp; // Transducer with bilingual dictionary // from string_utils wstring tolower(wstring const &s) { wstring l=s; for(unsigned i=0; i<s.length(); i++) { l[i] = (wchar_t) towlower(s[i]); } return l; } // from data_manager struct lexInfo { wstring name; map<wstring,wstring> info; }; static vector<lexInfo> lexical_information; void init_lexInfo(wstring name, string fitxName) { wifstream fitx; lexInfo lex; lex.name = name; fitx.open(fitxName.c_str()); wstring lerro; while (getline(fitx, lerro)) { // Remove comments if (lerro.find(L'#') != wstring::npos) lerro = lerro.substr(0, lerro.find(L'#')); // Remove whitespace and so... for (int i = 0; i < int(lerro.size()); i++) { if (lerro[i] == L' ' and (lerro[i+1] == L' ' or lerro[i+1] == L'\t')) lerro[i] = L'\t'; if ((lerro[i] == L' ' or lerro[i] == L'\t') and (i == 0 or lerro[i-1] == L'\t')) { lerro.erase(i,1); i--; } } if (lerro[lerro.size()-1] == L' ' or lerro[lerro.size()-1] == L'\t') lerro.erase(lerro.size()-1,1); size_t pos = lerro.find(L"\t"); if (pos == wstring::npos) continue; wstring key = lerro.substr(0,pos); wstring value = lerro.substr(pos+1); lex.info[key] = value; } fitx.close(); lexical_information.push_back(lex); } wstring get_lexInfo(wstring name, wstring key) { for (size_t i = 0; i < lexical_information.size(); i++) { if (lexical_information[i].name == name) { return lexical_information[i].info[key]; } } return L""; } vector<wstring> lexical_selection(wstring parent_attributes, wstring common_attribs, vector<wstring> child_attributes) { wstring src_lemma; wstring trgt_lemma; wstring attributes; vector<wstring> default_case; src_lemma = text_attrib(common_attribs, L"slem"); // Save the first value just in case there's no default set in the rules if (child_attributes.size() > 0) default_case.push_back(child_attributes[0]); for (size_t i = 0; i < child_attributes.size(); i++) { attributes = common_attribs + L" " + child_attributes[i]; trgt_lemma = text_attrib(attributes, L"lem"); } return default_case; } // from matxin_string_utils void Tokenize(const wstring& str, vector<wstring>& tokens, const wstring& delimiters) { // Skip delimiters at beginning size_t lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter" size_t pos = str.find_first_of(delimiters, lastPos); while (pos != wstring::npos || lastPos != wstring::npos) { // Found a token, add it to the vector tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } } void Tokenize2(const wstring& str, wstring& tokens, const wstring& delimiters) { // Skip delimiters at beginning size_t lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter" size_t pos = str.find_first_of(delimiters, lastPos); while (pos != wstring::npos || lastPos != wstring::npos) { // Found a token, add it to the resulting string tokens += str.substr(lastPos, pos - lastPos); // Skip delimiters lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } } vector<wstring> split_multiattrib(wstring str) { vector<wstring> tokens; vector<wstring> result; wstring resultStr; Tokenize(str, tokens); for (size_t i = 0; i < tokens.size(); i++) { vector<wstring> attribs; vector<wstring> valueparts; wstring values; Tokenize(tokens[i], attribs, L"="); Tokenize2(attribs[1], values, L"'"); Tokenize(values, valueparts, L"\\"); for (size_t j = 0; j < valueparts.size(); j++) { resultStr = attribs[0] + L"='" + valueparts[j] + L"' "; if (result.size() > j) result[j].append(resultStr); else { result.resize(valueparts.size()); result[j] = resultStr; } } } return result; } wstring v2s(vector<wstring> vector, wstring delimiter) { wstring result = L""; for (size_t i = 0; i < vector.size(); i++) result += delimiter + vector[i]; return result; } // from XML_reader // Converts xmlChar strings used by libxml2 to ordinary strings string xmlc2s(xmlChar const *entrada) { if (entrada == NULL) return ""; return reinterpret_cast<char const *>(entrada); } wstring getTagName(xmlTextReaderPtr reader) { xmlChar const *xname = xmlTextReaderConstName(reader); wstring tagName = XMLParseUtil::stows(xmlc2s(xname)); return tagName; } int nextTag(xmlTextReaderPtr reader) { int ret = xmlTextReaderRead(reader); wstring tagName = getTagName(reader); int tagType = xmlTextReaderNodeType(reader); while (ret == 1 and (tagType == XML_READER_TYPE_DOCUMENT_TYPE or tagName == L"#text")) { ret = xmlTextReaderRead(reader); tagName = getTagName(reader); tagType = xmlTextReaderNodeType(reader); } return ret; } wstring attrib(xmlTextReaderPtr reader, string const &nombre) { if (nombre[0] == '\'' && nombre[nombre.size() - 1] == '\'') return XMLParseUtil::stows(nombre.substr(1, nombre.size() - 2)); xmlChar *nomatrib = xmlCharStrdup(nombre.c_str()); xmlChar *atrib = xmlTextReaderGetAttribute(reader,nomatrib); wstring result = XMLParseUtil::stows(xmlc2s(atrib)); xmlFree(atrib); xmlFree(nomatrib); return result; } wstring allAttrib(xmlTextReaderPtr reader) { wstring output = L""; for (int hasAttrib = xmlTextReaderMoveToFirstAttribute(reader); hasAttrib > 0; hasAttrib = xmlTextReaderMoveToNextAttribute(reader)) { xmlChar const *xname = xmlTextReaderConstName(reader); xmlChar const *xvalue = xmlTextReaderConstValue(reader); output += L" " + XMLParseUtil::stows(xmlc2s(xname)) + L"='" + XMLParseUtil::stows(xmlc2s(xvalue)) + L"'"; } xmlTextReaderMoveToElement(reader); return output; } wstring allAttrib_except(xmlTextReaderPtr reader, wstring attrib_no) { wstring output = L""; for (int hasAttrib=xmlTextReaderMoveToFirstAttribute(reader); hasAttrib > 0; hasAttrib = xmlTextReaderMoveToNextAttribute(reader)) { xmlChar const *xname = xmlTextReaderConstName(reader); xmlChar const *xvalue = xmlTextReaderConstValue(reader); if (XMLParseUtil::stows(xmlc2s(xname)) != attrib_no) output += L" " + XMLParseUtil::stows(xmlc2s(xname)) + L"='" + XMLParseUtil::stows(xmlc2s(xvalue)) + L"'"; } xmlTextReaderMoveToElement(reader); return output; } wstring text_allAttrib_except(wstring attributes, const wstring &nombre) { vector<wstring> tokens; Tokenize(attributes, tokens); for (size_t i = 0; i < tokens.size(); i++) { vector<wstring> attribs; Tokenize(tokens[i], attribs, L"="); if (attribs[0] == nombre) { tokens.erase(tokens.begin() + i); break; } } return v2s(tokens); } wstring write_xml(wstring s) { size_t pos = 0; while ((pos = s.find(L"&", pos)) != wstring::npos) { s.replace(pos, 1, L"&amp;"); pos += 4; } while ((pos = s.find(L'"')) != wstring::npos) { s.replace(pos, 1, L"&quot;"); } pos = 0; while ((pos = s.find(L'\'', pos)) != wstring::npos) { if (s[pos - 1] != L'=' && s[pos + 1] != L' ' && pos != (s.size() - 1)) s.replace(pos, 1, L"&apos;"); else pos++; } while ((pos = s.find(L"<")) != wstring::npos) { s.replace(pos, 1, L"&lt;"); } while ((pos = s.find(L">")) != wstring::npos) { s.replace(pos, 1, L"&gt;"); } return s; } wstring text_attrib(wstring attributes, const wstring& nombre) { vector<wstring> tokens; wstring value = L""; Tokenize(attributes, tokens); for (size_t i = 0; i < tokens.size(); i++) { vector<wstring> attribs; Tokenize(tokens[i], attribs, L"="); if (attribs[0] == nombre) { Tokenize2(attribs[1], value, L"'"); break; } } return value; } // original matxin_xfer_lex wstring upper_type(wstring form, wstring mi, wstring ord) { wstring case_type = L"none"; size_t form_begin, form_end; int upper_case, lower_case; form_begin = 0; if (form.find(L"_", form_begin + 1) == wstring::npos) form_end = form.size(); else form_end = form.find(L"_", form_begin + 1); upper_case = lower_case = 0; while (form_begin != form.size()) { if (tolower(form[form_begin]) != form[form_begin] and (ord != L"1" or mi.substr(0, 2) == L"NP")) { if (form_begin == 0) case_type = L"first"; else case_type = L"title"; } for (size_t i = form_begin; i < form_end; i++) { if (form[i] != tolower(form[i])) upper_case++; else lower_case++; } if (form.size() > form_end) form_begin = form_end + 1; else form_begin = form.size(); if (form.find(L"_", form_begin + 1) == wstring::npos) form_end = form.size(); else form_end = form.find(L"_", form_begin + 1); } if (upper_case > lower_case) case_type = L"all"; return case_type; } /* * Gets attributes from the bilingual dictionary * input: "lemma<key1>value1<key2>value2...<keyn>valueN" * output: "lem='lemma' key1='value1' ... keyN='valueN'" */ wstring get_dict_attributes(const wstring full) { vector<wstring> tokens; wstring result = L""; bool empty_lemma = false; Tokenize(full, tokens, L"<"); // Special case, empty lemma if (full.substr(0, 1) == L"<") { result += L"lem=''"; empty_lemma = true; } for (size_t i = 0; i < tokens.size(); i ++) { if (i == 0 && !empty_lemma) { result += L"lem='" + write_xml(tokens[i]) + L"'"; } else { vector<wstring> attribs; Tokenize(tokens[i], attribs, L">"); result += L" " + attribs[0] + L"='" + write_xml(attribs[1]) + L"'"; } } return result; } wstring getsyn2lems(vector<wstring> translations, wstring slem) { wstring output; for (size_t i = 0; i < translations.size(); i++) output += L"<SYN " + translations[i] + L" slem='" + slem + L"' />\n"; return output; } wstring getsyn(vector<wstring> translations) { wstring output; for (size_t i = 0; i < translations.size(); i++) output += L"<SYN " + translations[i] + L"/>\n"; return output; } void order_ordainak(vector<wstring> &ordainak) { vector<wstring> ordered_ordain; int sense; bool zero_sense = false; vector<wstring>::iterator it; for (it = ordainak.begin(); it != ordainak.end(); it++) { sense = 0; size_t pos, pos2; if ((pos = (*it).find(L" sense='")) != wstring::npos) { if ((pos2 = (*it).find(L"'", pos+8)) != wstring::npos) sense = wcstol((*it).substr(pos+8, pos2-pos-8).c_str(), NULL, 10); } if (sense == 0) { zero_sense = true; ordered_ordain.insert(ordered_ordain.begin(), *it); } else { if (!zero_sense) sense--; if (ordered_ordain.size() < sense+1) ordered_ordain.resize(sense+1); ordered_ordain[sense] = *it; } } ordainak = ordered_ordain; } // Hiztegi elebidunaren euskarazko ordainetik lehenengoa lortzen du. // IN: Euskarazko ordainak ( ordain1[/ordain2]* ) // note: segfaults if full has no mi // OUT: lehenengoa ( oradin1 ) vector<wstring> disambiguate(wstring &full) { wstring output = full; vector<wstring> ordainak; // Això no és precisament disambiguació, és més aviat dit // 'selecció de la primera opció' for (size_t i = 0; i < output.size(); i++) { if (output[i] == L'/') { ordainak.push_back(get_dict_attributes(output.substr(0, i))); output = output.substr(i + 1); i = 0; } if (output[i] == L'\\') output.erase(i, 1); } ordainak.push_back(get_dict_attributes(output)); order_ordainak(ordainak); return ordainak; } vector<wstring> get_translation(wstring lem, wstring mi, bool &unknown) { vector<wstring> translation; wstring trad = L""; wstring input = L""; input = L"^" + lem + L"<parol>" + mi + L"$"; trad = fstp.biltrans(input); trad = trad.substr(1, trad.size() - 2); unknown = false; if (trad[0] == L'@' || trad.find(L">") < trad.find(L"<")) { unknown = true; return translation; } translation = disambiguate(trad); return translation; } // Hiztegi elebidunaren euskarazko ordaina NODO bat baino gehiagoz osaturik badago. // Adb. oso<ADB><ADOARR><+><MG><+>\eskas<ADB><ADJ><+><MG><+>. // Azken NODOa ezik besteak tratatzen ditu // IN: Euskarazko ordain bat, NODO bat baino gehiago izan ditzake. // OUT: Lehen NODOei dagokien XML zuhaitza. //wstring multiNodes (xmlTextReaderPtr reader, wstring &full, wstring attributes) wstring multiNodes (wstring &full, wstring attributes) { wstring output = L""; vector<wstring> tmp; tmp = split_multiattrib(full); for (size_t i = 1; i < tmp.size(); i++) { output += L"<NODE " + attributes; output += L" " + tmp[i] + L" />\n"; } return output; } // NODE etiketa irakurri eta prozesatzen du, NODE hori AS motakoa ez den CHUNK baten barruan dagoela: // - ord -> ref : ord atributuan dagoen balioa, ref atributuan idazten du (helmugak jatorrizkoaren erreferentzia izateko postedizioan) // - (S) preposizioen eta (F) puntuazio ikurren kasuan ez da transferentzia egiten. // - Beste kasuetan: // - Transferentzia lexikoa egiten da, lem, pos, mi, cas eta sub attributuak sortuz. // - Hitz horren semantika begiratzen da // - NODEaren azpian dauden NODEak irakurri eta prozesatzen ditu. std::pair<wstring,wstring> procNODE(xmlTextReaderPtr reader, bool head, wstring parent_attribs, wstring& attributes) { wstring nodes, pos; wstring subnodes; wstring synonyms; wstring synonyms2; wstring child_attributes; wstring tagName = getTagName(reader); vector<wstring> trad; // squoia: ambiguos lemmas-> need 2nd trad vector<wstring> trad2; wstring lem1, lem2; vector<wstring> select; int tagType = xmlTextReaderNodeType(reader); bool head_child = false; bool unknown = false; bool ambilem = false; // ord -> ref : ord atributuan dagoen balioa, ref atributuan idazten du // alloc atributua mantentzen da if (tagName == L"NODE" and tagType != XML_READER_TYPE_END_ELEMENT) { nodes = L"<NODE "; attributes = L"ref='" + write_xml(attrib(reader, "ord")) + L"'" + L" alloc='" + write_xml(attrib(reader, "alloc")) + L"'" + L" slem='" + write_xml(attrib(reader, "lem")) + L"'" + L" smi='" + write_xml(attrib(reader, "mi")) + L"'" + L" sform='" + write_xml(attrib(reader, "form")) + L"'" + L" UpCase='" + write_xml(upper_type(attrib(reader, "form"), attrib(reader, "mi"), attrib(reader, "ord"))) + L"'"; if (attrib(reader, "unknown") != L"") { attributes += L" unknown='" + write_xml(attrib(reader, "unknown")) + L"'"; } // TODO: LANGUAGE INDEPENDENCE // else if (attrib(reader,"mi") != L"" && // attrib(reader, "mi").substr(0,1) == L"W" or // attrib(reader, "mi").substr(0,1) == L"Z") // { // // Daten (W) eta zenbakien (Z) kasuan ez da transferentzia egiten. // // lem eta mi mantentzen dira // attributes += L" lem='" + write_xml(attrib(reader, "lem")) + L"'" + // L" pos='[" + write_xml(attrib(reader, "mi")) + L"]'"; // } else { // Beste kasuetan: // Transferentzia lexikoa egiten da, lem, pos, mi, cas eta sub attributuak sortuz. // trad = get_translation(attrib(reader, "lem"), attrib(reader, "mi"), unknown); // changed squoia: if number 'Z' or 'DN' -> use word form for lookup, not lemma if(attrib(reader, "mi").substr(0,1) == L"Z" or attrib(reader, "mi").substr(0,2) == L"DN"){ trad = get_translation(attrib(reader, "form"), attrib(reader, "mi"), unknown); } else{ // squoia: split ambiguous lemmas from tagging (e.g. asiento: asentir/asentar) and lookup both // TODO: insert some attribute to know which slem belongs to which lem! int split =attrib(reader, "lem").find(L"#"); if(split != wstring::npos){ ambilem = true; // wcerr << attrib(reader, "lem") << L"1 split at: " << split << L"\n"; lem1 = attrib(reader, "lem").substr(0,split); lem2 = attrib(reader, "lem").substr(split+2,wstring::npos); //wcerr << L"lemma 1" << lem1 << L" lemma 2: " << lem2 << L"\n"; bool unknown1 = false; trad = get_translation(lem1, attrib(reader, "mi"), unknown1); bool unknown2 = false; trad2 = get_translation(lem2, attrib(reader, "mi"), unknown2); unknown = unknown1 and unknown2; //wcerr << L"trad size lem1 " <<trad.size() << L" trad size lem2:" << trad2[0] << L"\n"; } else{ trad = get_translation(attrib(reader, "lem"),attrib(reader, "mi"), unknown); } } if (unknown) { attributes += L" unknown='transfer'"; } else // either trad or trad2 has at least one translation { if (trad.size() > 1 ) { select = lexical_selection(parent_attribs, attributes, trad); } else if (trad.size() > 0) { select = trad; } else if (trad2.size() > 1) { select = lexical_selection(parent_attribs, attributes, trad2); } else { select = trad2; } if (trad.size() > 1 and not ambilem) { synonyms = getsyn(trad); } // if there was a second lemma translated: add slem to synonyms to avoid confusion else if (trad.size() > 1 or (trad.size() > 0 and trad2.size() > 0)) { synonyms = getsyn2lems(trad, lem1); } if (trad2.size() > 1 or (trad2.size() > 0 and trad.size() > 0)) { synonyms2 = getsyn2lems(trad2,lem2); } if (ambilem) { if (trad.size() > 0) { // add tradlem='lem1' to node, so that we know which lemma belongs to the first translation attributes += L" tradlem='" + lem1 + L"' "; } else { attributes += L" tradlem='" + lem2 + L"' "; } } if (select[0].find(L"\\") != wstring::npos) { subnodes = multiNodes(select[0], attributes); } attributes += L" " + select[0]; head_child = head && (text_attrib(select[0], L"lem") == L""); } } if (xmlTextReaderIsEmptyElement(reader) == 1 and subnodes == L"" && synonyms == L"" && synonyms2 == L"") { // NODE hutsa bada (<NODE .../>), NODE hutsa sortzen da eta // momentuko NODEarekin bukatzen dugu. // empty nodes (?) nodes += attributes + L"/>\n"; return std::make_pair(nodes,pos); } else if (xmlTextReaderIsEmptyElement(reader) == 1) { // NODE hutsa bada (<NODE .../>), NODE hutsa sortzen da eta // momentuko NODEarekin bukatzen dugu. nodes += attributes + L">\n" + synonyms +synonyms2 + subnodes + L"</NODE>\n"; return std::make_pair(nodes,pos); } else { // bestela NODE hasiera etiketaren bukaera idatzi eta // etiketa barrukoa tratatzera pasatzen gara. nodes += attributes + L">\n" + synonyms + synonyms2 + subnodes; } } else { wcerr << L"ERROR: invalid tag: <" << tagName << allAttrib(reader) << L"> when <NODE> was expected..." << endl; exit(-1); } int ret = nextTag(reader); tagName = getTagName(reader); tagType = xmlTextReaderNodeType(reader); wstring attribs = attributes; if (text_attrib(attributes, L"lem") == L"") attribs = parent_attribs; // NODEaren azpian dauden NODE guztietarako while (ret == 1 and tagName == L"NODE" and tagType == XML_READER_TYPE_ELEMENT) { // NODEa irakurri eta prozesatzen du. //nodes += procNODE(reader, head_child, attributes, cfg); std::pair<wstring,wstring> pr = procNODE(reader, head_child, attribs, child_attributes); wstring NODOA = pr.first; nodes += NODOA; ret = nextTag(reader); tagName = getTagName(reader); tagType = xmlTextReaderNodeType(reader); } if (text_attrib(attributes, L"lem") == L"") attributes = child_attributes; // NODE bukaera etiketa tratatzen da. if (tagName == L"NODE" and tagType == XML_READER_TYPE_END_ELEMENT) { nodes += L"</NODE>\n"; } else { wcerr << L"ERROR: invalid document: found <" << tagName << allAttrib(reader) << L"> when </NODE> was expected..." << endl; exit(-1); } return std::make_pair(nodes,pos); } // CHUNK etiketa irakurri eta prozesatzen du: // - ord -> ref : ord atributuan dagoen balioa, ref atributuan idazten du (helmugak jatorrizkoaren erreferentzia izateko postedizioan) // - type : CHUNKaren type atributua itzultzen da wstring procCHUNK(xmlTextReaderPtr reader, wstring parent_attribs) { wstring tagName = getTagName(reader); int tagType = xmlTextReaderNodeType(reader); wstring tree, chunk_type, head_attribs; wstring old_type, si, ref, other_attribs, nodes; if (tagName == L"CHUNK" and tagType == XML_READER_TYPE_ELEMENT) { // ord -> ref : ord atributuan dagoen balioa, ref atributuan idazten du // type : CHUNKaren type atributua itzultzen da // si atributua mantentzen da old_type = attrib(reader, "type"); chunk_type = get_lexInfo(L"chunkType", old_type); // might change below si = attrib(reader, "si"); ref = attrib(reader, "ord"); other_attribs = text_allAttrib_except(allAttrib_except(reader, L"ord"), L"type"); // Store CHUNK attribs before call to nextTag(reader). These are // written to the tree after the call to procNODE in case // chunk_type has to be based on the pos attrib of the first NODE } else { wcerr << L"ERROR: invalid tag: <" << tagName << allAttrib(reader) << L"> when <CHUNK> was expected..." << endl; exit(-1); } int ret = nextTag(reader); tagName = getTagName(reader); tagType = xmlTextReaderNodeType(reader); std::pair<wstring,wstring> pr = procNODE(reader, true, parent_attribs, head_attribs); nodes = pr.first; if (old_type == L"") { wstring pos = pr.second; chunk_type = get_lexInfo(L"chunkType", si + pos); if (chunk_type == L"") { // if syntactic function wasn't in chunktype_file, or no chunktype_file given: chunk_type = si + pos; } } else { chunk_type = get_lexInfo(L"chunkType", old_type); if (chunk_type == L"") { chunk_type = old_type; } } tree = L"<CHUNK ref='" + write_xml(ref) + L"' type='" + write_xml(chunk_type) + L"'" + write_xml(other_attribs) + L">\n" + nodes; ret = nextTag(reader); tagName = getTagName(reader); tagType = xmlTextReaderNodeType(reader); while (ret == 1 and tagName == L"CHUNK" and tagType == XML_READER_TYPE_ELEMENT) { tree += procCHUNK(reader, head_attribs); ret = nextTag(reader); tagName = getTagName(reader); tagType = xmlTextReaderNodeType(reader); } if (tagName == L"CHUNK" and tagType == XML_READER_TYPE_END_ELEMENT) { tree += L"</CHUNK>\n"; } else { wcerr << L"ERROR: invalid document: found <" << tagName << allAttrib(reader) << L"> when </CHUNK> was expected..." << endl; exit(-1); } return tree; } // SENTENCE etiketa irakurri eta prozesatzen du: // - ord -> ref : ord atributuan dagoen balioa, ref atributuan idazten du (helmugak jatorrizkoaren erreferentzia izateko postedizioan) // - SENTENCE barruan dauden CHUNKak irakurri eta prozesatzen ditu. wstring procSENTENCE (xmlTextReaderPtr reader) { wstring tree; wstring tagName = getTagName(reader); int tagType = xmlTextReaderNodeType(reader); if (tagName == L"SENTENCE" and tagType != XML_READER_TYPE_END_ELEMENT) { // ord -> ref : ord atributuan dagoen balioa, ref atributuan gordetzen du tree = L"<SENTENCE ref='" + write_xml(attrib(reader, "ord")) + L"'" + write_xml(allAttrib_except(reader, L"ord")) + L">\n"; } else { wcerr << L"ERROR: invalid document: found <" << tagName << allAttrib(reader) << L"> when <SENTENCE> was expected..." << endl; exit(-1); } int ret = nextTag(reader); tagName = getTagName(reader); tagType = xmlTextReaderNodeType(reader); // SENTENCE barruan dauden CHUNK guztietarako while (ret == 1 and tagName == L"CHUNK") { // CHUNKa irakurri eta prozesatzen du. tree += procCHUNK(reader, L""); ret = nextTag(reader); tagName = getTagName(reader); tagType = xmlTextReaderNodeType(reader); } if (ret == 1 and tagName == L"SENTENCE" and tagType == XML_READER_TYPE_END_ELEMENT) { tree += L"</SENTENCE>\n"; } else { wcerr << L"ERROR: invalid document: found <" << tagName << allAttrib(reader) << L"> when </SENTENCE> was expected..." << endl; exit(-1); } return tree; } void endProgram(char *name) { cout << basename(name) << ": run lexical transfer on a Matxin input stream" << endl; cout << "USAGE: " << basename(name) << " [-c chunktype_file] fst_file" << endl; cout << "Options:" << endl; #if HAVE_GETOPT_LONG cout << " -c, --chunktype-file: give a file listing chunk types" << endl; #else cout << " -c: give a file listing chunk types" << endl; #endif exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { // This sets the C++ locale and affects to C and C++ locales. // wcout.imbue doesn't have any effect but the in/out streams use the proper encoding. #ifndef NeXTBSD #ifdef __APPLE__ setlocale(LC_ALL, ""); // locale("") doesn't work on mac, except with C/POSIX #else locale::global(locale("")); #endif #else setlocale(LC_ALL, ""); #endif if(argc < 2) { endProgram(argv[0]); } #if HAVE_GETOPT_LONG static struct option long_options[]= { {"chunk-file", 0, 0, 'c'}, }; #endif while(true) { #if HAVE_GETOPT_LONG int option_index; int c = getopt_long(argc, argv, "c:", long_options, &option_index); #else int c = getopt(argc, argv, "c:"); #endif if(c == -1) { break; } switch(c) { case 'c': //check if the file exists and is readable init_lexInfo(L"chunkType", optarg); break; default: endProgram(argv[0]); break; } } FILE *transducer = 0; transducer = fopen(argv[optind], "r"); fstp.load(transducer); fclose(transducer); fstp.initBiltrans(); // libXml liburutegiko reader hasieratzen da, sarrera estandarreko fitxategia irakurtzeko. xmlTextReaderPtr reader; reader = xmlReaderForFd(0, "", NULL, 0); int ret = nextTag(reader); wstring tagName = getTagName(reader); int tagType = xmlTextReaderNodeType(reader); if(tagName == L"corpus" and tagType != XML_READER_TYPE_END_ELEMENT) { wcout << L"<?xml version='1.0' encoding='UTF-8'?>" << endl; wcout << L"<corpus " << write_xml(allAttrib(reader)) << ">" << endl; } else { wcerr << L"ERROR: invalid document: found <" << tagName << allAttrib(reader) << L"> when <corpus> was expected..." << endl; exit(-1); } ret = nextTag(reader); tagName = getTagName(reader); tagType = xmlTextReaderNodeType(reader); int i = 0; // corpus barruan dauden SENTENCE guztietarako while (ret == 1 and tagName == L"SENTENCE") { //SENTENCE irakurri eta prozesatzen du. wstring tree = procSENTENCE(reader); wcout << tree << endl; wcout.flush(); ret = nextTag(reader); tagName = getTagName(reader); tagType = xmlTextReaderNodeType(reader); } xmlFreeTextReader(reader); xmlCleanupParser(); if(ret == 1 and tagName == L"corpus" and tagType == XML_READER_TYPE_END_ELEMENT) { wcout << L"</corpus>\n"; } else { wcerr << L"ERROR: invalid document: found <" << tagName << allAttrib(reader) << L"> when </corpus> was expected..." << endl; exit(-1); } }
28.00266
134
0.629246
1ced0d82f1e0edc30c2e913f425fbac2084d7fd7
1,858
cpp
C++
Source/Game/MainMenuScene.cpp
nathanlink169/3D-Shaders-Test
2493fb71664d75100fbb4a80ac70f657a189593d
[ "MIT" ]
null
null
null
Source/Game/MainMenuScene.cpp
nathanlink169/3D-Shaders-Test
2493fb71664d75100fbb4a80ac70f657a189593d
[ "MIT" ]
null
null
null
Source/Game/MainMenuScene.cpp
nathanlink169/3D-Shaders-Test
2493fb71664d75100fbb4a80ac70f657a189593d
[ "MIT" ]
null
null
null
#include "CommonHeader.h" MainMenuScene::MainMenuScene() { } MainMenuScene::~MainMenuScene() { } void MainMenuScene::OnSurfaceChanged(unsigned int aWidth, unsigned int aHeight) { Scene::OnSurfaceChanged(aWidth, aHeight); } void MainMenuScene::LoadContent() { Scene::LoadContent(); CreateCameraObject(); Label* label = new Label(this, "Loading Label", "Loading", vec3(0.0f, 0.0f, 0.0f), vec3(0.0f, 0.0f, 0.0f), vec3(0.035f, 0.035f, 0.035f), nullptr, g_pGame->GetShader("2D Colour"), g_pGame->GetTexture("Black")); label->Colour = Colours::Crimson; label->SetFont("arial"); label->Text = "Press Space To Start"; label->Orientation = Center; AddGameObject(label, "Label"); //AudioManager::PlayBGM("Main Theme"); std::ifstream myfile("Data/SaveData/Score.npwscore"); if (myfile.is_open()) { std::string line; ScoreEntry entries; getline(myfile, line); entries.Name = line; getline(myfile, line); entries.Score = (uint)(std::stoi(line)); Label* score = new Label(this, "High Score Label", "Label", vec3(0.0f, -0.1f, 0.0f), vec3(0.0f, 0.0f, 0.0f), vec3(0.015f, 0.015f, 0.015f), nullptr, g_pGame->GetShader("2D Colour"), g_pGame->GetTexture("Black")); score->Colour = Colours::Crimson; score->SetFont("arial"); score->Text = "Highscore: " + entries.Name + " - " + std::to_string(entries.Score); score->Orientation = Center; AddGameObject(score, "HighScoreLabel"); } } void MainMenuScene::Update(double aDelta) { Scene::Update(aDelta); if (Input::KeyJustPressed(VK_SPACE)) g_pGame->StartGame(); } void MainMenuScene::Draw() { m_Matrix.CreatePerspectiveVFoV(CAMERA_PERSPECTIVE_ANGLE, CAMERA_ASPECT_RATIO, CAMERA_NEAR_Z, CAMERA_FAR_Z); m_MainCamera->CreateLookAtLeftHandAndReturn(Vector3(0, 1, 0), GetGameObject("Label")->GetPosition()); Scene::Draw(); }
28.151515
213
0.684069
1cefe798b4d803b740eb9cc858578e7cd56a1af5
3,076
cpp
C++
C++/Stack/stack_linked-list.cpp
Vishwas-10/Data-structures
34598895b56c9bf26e03c02e81a9b3222a61cd9a
[ "MIT" ]
null
null
null
C++/Stack/stack_linked-list.cpp
Vishwas-10/Data-structures
34598895b56c9bf26e03c02e81a9b3222a61cd9a
[ "MIT" ]
null
null
null
C++/Stack/stack_linked-list.cpp
Vishwas-10/Data-structures
34598895b56c9bf26e03c02e81a9b3222a61cd9a
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; /* Steps: - Create linked list node which stores value(data), next(pointer), min(current min element) - while pushing elements : - if stack is empty store current val in min - if current element is less than min than store (2*x – minEle) in min - while poping elements : - if current element is min restore as (2*minEle – y) - Time complexity of push is O(1) - Time complexity of pop is O(1) - Time complexity of getmin is O(1) */ // Structure of Linked list Node:- struct Node{ int val; // value struct Node* next; // pointer to next node int min; }; // Creating stack class with push, pop, getmin functions class stack{ struct Node* top; int min; public: stack(){ top=NULL; } void push(int value) // Push function { /* - if(top == NULL) push the node and min -> value - if(value > min) push the node and no need to change min - if(value < min) push the node and store 2 * current min - value -> node.min and update min -> value */ Node* ptr; if(top==NULL) { ptr=new Node; ptr->val=value; ptr->next=NULL; ptr->min=value; min = value; top=ptr; } else if(value > min) { ptr=new Node; ptr->val=value; ptr->next=top; ptr->min=value; top=ptr; } else { ptr=new Node; ptr->val=value; ptr->next=top; ptr->min=2*value - min; top=ptr; min = value; } } void pop() // Pop function { // if poped element is minimum restore the 2nd min value : min -> 2*min - node.min Node* temp; if(top == NULL) { cout<<endl<<-1; return; } temp= top; if (temp->min < min) { min = 2*min - top->min; } top=top->next; cout<<temp->val<<" "; delete temp; } void print(){ Node* temp1=top; cout<<"Stack : "; while (temp1!=NULL){ cout<<temp1->val<<" "; temp1=temp1->next; } cout<<endl; } void getmin() // Getmin function { cout<<"Minimum element : "<<min<<endl; } }; int main() { //freopen("input.txt","r", stdin); //freopen("output.txt","w", stdout); // Calling stack class stack s; int n,a; // n is the number of elements pushed cin>>n; for(int i=0;i<n;i++) { cin>>a; s.push(a); // Push elements } s.print(); // Print the current stack cin>>n; // n is the number of elements popped cout<<"Popped elements : "; for(int i=0;i<n;i++) { s.pop(); // Pop elements } cout<<endl; s.print(); // Print the current stack s.getmin(); // get minimum element in the present stack return 0; }
24.412698
114
0.491222
1cf05e916039a1c77ac99a82b67ece7c35271c0c
756
cpp
C++
cpp/bjyd/06/TestGeometricObject2.cpp
skyofsmith/servePractice
d143497ec7c13dcbb55354c9050fd48e5b1c7b51
[ "MIT" ]
null
null
null
cpp/bjyd/06/TestGeometricObject2.cpp
skyofsmith/servePractice
d143497ec7c13dcbb55354c9050fd48e5b1c7b51
[ "MIT" ]
18
2020-07-16T21:36:57.000Z
2022-03-25T18:59:38.000Z
cpp/bjyd/06/TestGeometricObject2.cpp
skyofsmith/servePractice
d143497ec7c13dcbb55354c9050fd48e5b1c7b51
[ "MIT" ]
null
null
null
#include <iostream> //#include "AbstractGeometricObject.h" #include "DerivedCircle2.h" #include "Rectangle2.h" using namespace std; bool equalArea(GeometricObject &object1, GeometricObject &object2) { return object1.getArea() == object2.getArea(); } void displayGeometricObject(GeometricObject &object) { cout << "The area is " << object.getArea() << endl; cout << "The perimeter is " << object.getPerimeter() << endl; } int main() { Circle circle(5); Rectangle rectangle(5, 3); cout << "Circle info: " << endl; displayGeometricObject(circle); cout << "\nRectangle info: " << endl; displayGeometricObject(rectangle); cout << "\nThe two objects have the same area? " << (equalArea(circle, rectangle) ? "Yes" : "No") << endl; return 0; }
22.909091
66
0.691799
1cf6d96673df89a58ee0fc7bb8581a94ce538a35
321
cxx
C++
cxx/extends.cxx
coalpha/coalpha.github.io
8a620314a5c0bcbe2225d29f733379d181534430
[ "Apache-2.0" ]
null
null
null
cxx/extends.cxx
coalpha/coalpha.github.io
8a620314a5c0bcbe2225d29f733379d181534430
[ "Apache-2.0" ]
1
2020-04-12T07:48:18.000Z
2020-04-12T07:49:29.000Z
cxx/extends.cxx
coalpha/coalpha.github.io
8a620314a5c0bcbe2225d29f733379d181534430
[ "Apache-2.0" ]
1
2020-09-30T05:27:07.000Z
2020-09-30T05:27:07.000Z
#include <type_traits> using namespace std; template <typename Base, typename Derived> using extends = enable_if_t<is_base_of_v<Base, Derived>>; struct cat{}; struct dog{}; template <typename T, typename = extends<cat, T>> void only_cats(T) noexcept; int main() noexcept { only_cats(cat{}); only_dogs(dog{}); }
18.882353
57
0.719626
7f2fbcd1d85fa5f4336de189dfc07777ac507a16
12,108
cpp
C++
src/Sparrow/Sparrow/Implementations/Dftb/Utils/SKPair.cpp
qcscine/sparrow
387e56ed8da78e10d96861758c509f7c375dcf07
[ "BSD-3-Clause" ]
45
2019-06-12T20:04:00.000Z
2022-02-28T21:43:54.000Z
src/Sparrow/Sparrow/Implementations/Dftb/Utils/SKPair.cpp
qcscine/sparrow
387e56ed8da78e10d96861758c509f7c375dcf07
[ "BSD-3-Clause" ]
12
2019-06-12T23:53:57.000Z
2022-03-28T18:35:57.000Z
src/Sparrow/Sparrow/Implementations/Dftb/Utils/SKPair.cpp
qcscine/sparrow
387e56ed8da78e10d96861758c509f7c375dcf07
[ "BSD-3-Clause" ]
11
2019-06-22T22:52:51.000Z
2022-03-11T16:59:59.000Z
/** * @file * @copyright This code is licensed under the 3-clause BSD license.\n * Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n * See LICENSE.txt for details. */ #include "SKPair.h" #include "SKAtom.h" #include <Utils/IO/Regex.h> #include <Utils/Scf/MethodExceptions.h> #include <Utils/Technical/ScopedLocale.h> #include <cmath> #include <fstream> #include <regex> namespace Scine { namespace Sparrow { using std::exp; using namespace Utils::AutomaticDifferentiation; namespace dftb { // Declare space for values in binary at runtime constexpr decltype(SKPair::integralIndexes) SKPair::integralIndexes; SKPair::SKPair(SKAtom* atomicParameters1, SKAtom* atomicParameters2, SkfData data) : atomType1(atomicParameters1), atomType2(atomicParameters2), gridDist(data.gridDistance), nGridPoints(data.integralTable.front().size()), rMax(gridDist * nGridPoints + distFudge), integralTable(std::move(data.integralTable)), repulsion_(std::move(data.repulsion)), extrC3(28), extrC4(28), extrC5(28) { if (integralTable.back().empty()) { throw std::runtime_error("Back columns of integral table are empty instead of default-initialized!"); } if (data.atomicParameters) { const auto& p = data.atomicParameters.value(); atomicParameters1->setEnergies(p.Es, p.Ep, p.Ed); atomicParameters1->setHubbardParameter(p.Us, p.Up, p.Ud); atomicParameters1->setOccupations(p.fs, p.fp, p.fd); } // Set the number of integrals for the atom pair const int nAOsA = atomicParameters1->getnAOs(); const int nAOsB = atomicParameters2->getnAOs(); if (nAOsA + nAOsB == 2) { // Only s orbitals nIntegrals = 2; } else if (nAOsA + nAOsB == 5) { // one atom only has s, the other one s and p nIntegrals = 4; } else if (nAOsA + nAOsB == 8) { // Both atoms have s and p nIntegrals = 10; } else if (nAOsA + nAOsB == 10) { // one has s, one has d nIntegrals = 14; } else if (nAOsA + nAOsB == 13) { // one has p, one has d nIntegrals = 22; } else if (nAOsA + nAOsB == 18) { // both have d nIntegrals = 28; } } void SKPair::precalculateGammaTerms() { // Precondition: not same atom type. In this case the gamma terms are not needed if (atomType1 == atomType2) return; double ta = atomType1->getHubbardParameter() * 3.2; double tb = atomType2->getHubbardParameter() * 3.2; double ta2 = ta * ta; double tb2 = tb * tb; gamma.g1a = (tb2 * tb2 * ta) / (2.0 * (ta2 - tb2) * (ta2 - tb2)); gamma.g1b = (ta2 * ta2 * tb) / (2.0 * (tb2 - ta2) * (tb2 - ta2)); gamma.g2a = tb2 * tb2 * (tb2 - 3 * ta2) / ((ta2 - tb2) * (ta2 - tb2) * (ta2 - tb2)); gamma.g2b = ta2 * ta2 * (ta2 - 3 * tb2) / ((tb2 - ta2) * (tb2 - ta2) * (tb2 - ta2)); gammaDerivative.dgab1a = (tb2 * tb2 * tb2 + 3.0 * ta2 * tb2 * tb2) / (2.0 * (ta2 - tb2) * (ta2 - tb2) * (ta2 - tb2)); gammaDerivative.dgab2a = (12.0 * ta2 * ta * tb2 * tb2) / ((ta2 - tb2) * (ta2 - tb2) * (ta2 - tb2) * (ta2 - tb2)); gammaDerivative.dgab1b = (2.0 * ta2 * ta * tb2 * tb) / ((ta2 - tb2) * (ta2 - tb2) * (ta2 - tb2)); gammaDerivative.dgab2b = (12.0 * ta2 * ta2 * tb2 * tb) / ((ta2 - tb2) * (ta2 - tb2) * (ta2 - tb2) * (ta2 - tb2)); gammaDerivative.dgba1a = (ta2 * ta2 * ta2 + 3.0 * tb2 * ta2 * ta2) / (2.0 * (tb2 - ta2) * (tb2 - ta2) * (tb2 - ta2)); gammaDerivative.dgba2a = (12.0 * tb2 * tb * ta2 * ta2) / ((tb2 - ta2) * (tb2 - ta2) * (tb2 - ta2) * (tb2 - ta2)); gammaDerivative.dgba1b = (2.0 * tb2 * tb * ta2 * ta) / ((tb2 - ta2) * (tb2 - ta2) * (tb2 - ta2)); gammaDerivative.dgba2b = (12.0 * tb2 * tb2 * ta2 * ta) / ((tb2 - ta2) * (tb2 - ta2) * (tb2 - ta2) * (tb2 - ta2)); gammaDerivative.dgadr = (tb2 * tb2 * tb2 - 3.0 * ta2 * tb2 * tb2) / ((ta2 - tb2) * (ta2 - tb2) * (ta2 - tb2)); gammaDerivative.dgbdr = (ta2 * ta2 * ta2 - 3.0 * tb2 * ta2 * ta2) / ((tb2 - ta2) * (tb2 - ta2) * (tb2 - ta2)); } const SKPair::GammaTerms& SKPair::getGammaTerms() const { return gamma; } const SKPair::GammaDerivativeTerms& SKPair::getGammaDerTerms() const { return gammaDerivative; } void SKPair::complete(SKPair* p) { assert(p != nullptr); constexpr double factor = -1.0; for (int i = 0; i < nGridPoints; i++) { integralTable[20][i] = factor * p->integralTable[3][i]; integralTable[21][i] = factor * p->integralTable[4][i]; integralTable[22][i] = p->integralTable[7][i]; integralTable[23][i] = factor * p->integralTable[8][i]; integralTable[24][i] = factor * p->integralTable[13][i]; integralTable[25][i] = factor * p->integralTable[14][i]; integralTable[26][i] = p->integralTable[17][i]; integralTable[27][i] = factor * p->integralTable[18][i]; } // Precompute the coefficients for the extrapolation precompute5Extrapolation(); } void SKPair::precompute5Extrapolation() { int indStart = nGridPoints - nInter; InterpolationValues<Utils::DerivativeOrder::One> t1; InterpolationValues<Utils::DerivativeOrder::One> t2; // Calculate interpolated values right after and right before the last given // point in parameter table; these values are used to compute the numerical // derivatives at the last point interpolate(t1, static_cast<double>(nGridPoints - 1) - deltaR, indStart); // Get values right before last given point interpolate(t2, static_cast<double>(nGridPoints - 1) + deltaR, indStart); // Get values right after last given point double yd0, yd1, yd2; // zero, first and second order derivatives double dx1, dx2; // Temporary variables needed for the extrapolation for (int L = 0; L < nIntegrals; L++) { assert(integralIndexes[L] < static_cast<int>(integralTable.size())); yd0 = integralTable[integralIndexes[L]][nGridPoints - 1]; yd1 = t1.derivIntegral[L].derivative(); yd2 = (t2.derivIntegral[L].derivative() - t1.derivIntegral[L].derivative()) / (deltaR); // 5th order extrapolation (impose derivatives at last gridpoint, and zero value and derivatives at rMax) dx1 = -yd1 * (distFudge / gridDist); dx2 = yd2 * (distFudge / gridDist) * (distFudge / gridDist); extrC3[L] = 10 * yd0 - 4 * dx1 + 0.5 * dx2; extrC4[L] = -15 * yd0 + 7 * dx1 - dx2; extrC5[L] = 6 * yd0 - 3 * dx1 + 0.5 * dx2; } } template<Utils::DerivativeOrder O> Value1DType<O> SKPair::getRepulsion(double const& r) const { auto R = variableWithUnitDerivative<O>(r); if (r > repulsion_.cutoff) return constant1D<O>(0); if (r < repulsion_.splines[0].start) return exp(-repulsion_.a1 * R + repulsion_.a2) + repulsion_.a3; auto i = static_cast<int>((r - repulsion_.splines[0].start) / (repulsion_.cutoff - repulsion_.splines[0].start) * repulsion_.nSplineInts); // If not the right bin, find the right one: if (repulsion_.splines[i].start > r) { while (repulsion_.splines[--i].start > r) { } } else if (repulsion_.splines[i].end < r) { while (repulsion_.splines[++i].end < r) { } } const auto& spline = repulsion_.splines[i]; auto dr = R - spline.start; auto conditional = (i == repulsion_.nSplineInts - 1 ? dr * (repulsion_.c4 + dr * repulsion_.c5) : constant1D<O>(0.0)); // clang-format off return ( spline.c0 + dr * ( spline.c1 + dr * ( spline.c2 + dr * ( spline.c3 + conditional ) ) ) ); // clang-format on } template<Utils::DerivativeOrder O> int SKPair::getHS(double dist, InterpolationValues<O>& val) const { // If 'dist' too short or too large, return 0 if (dist < gridDist || dist > rMax) { for (int L = 0; L < nIntegrals; L++) val.derivIntegral[L] = constant1D<O>(0.0); return 0; } // If 'dist' is in the extrapolation zone, take simple formula if (dist > nGridPoints * gridDist) { double dr = dist - rMax; auto xr = variableWithUnitDerivative<O>(-dr / distFudge); // 5th order extrapolation (impose derivatives at last gridpoint, and zero value and derivatives at rMax) for (int L = 0; L < nIntegrals; L++) val.derivIntegral[L] = ((extrC5[L] * xr + extrC4[L]) * xr + extrC3[L]) * xr * xr * xr; return 1; } // Else: do interpolation getHSIntegral(val, dist); return 1; } template<Utils::DerivativeOrder O> int SKPair::getHSIntegral(InterpolationValues<O>& val, double dist) const { double position = dist / gridDist - 1.0; int ind; // Current index during interpolation ind = static_cast<int>(position); int indStart; // first index for interpolation indStart = (ind >= nGridPoints - nInterRight) ? nGridPoints - nInter : ((ind < nInterLeft) ? 0 : ind - nInterLeft + 1); // -1 because loop afterward goes from i = 0 to nInter - 1 -> // first item accessed is indStart + 0, last element // accessed is indStart + nInter - 1 assert(indStart + nInter - 1 < nGridPoints); interpolate(val, position, indStart); return 1; } template<Utils::DerivativeOrder O> void SKPair::interpolate(InterpolationValues<O>& val, double x, int start) const { /* * Taken from Numerical recipes * Adapted to treat simultaneously the different orbitals */ double dift, dif = x - start; int ns = 0; // index of closest table entry for (int L = 0; L < nIntegrals; L++) { for (int i = 0; i < nInter; i++) { val.ya[L][i] = integralTable[integralIndexes[L]][start + i]; val.C[L][i] = constant1D<O>(integralTable[integralIndexes[L]][start + i]); val.D[L][i] = constant1D<O>(integralTable[integralIndexes[L]][start + i]); } } for (int i = 0; i < nInter; i++) { val.xa[i] = static_cast<double>(start + i); if ((dift = std::abs(x - val.xa[i])) < dif) { dif = dift; ns = i; } } for (int L = 0; L < nIntegrals; L++) { val.derivIntegral[L] = constant1D<O>(val.ya[L][ns]); } ns--; Value1DType<O> w, den; double ho, hp; for (int m = 1; m < nInter; m++) { for (int i = 0; i <= nInter - 1 - m; i++) { ho = val.xa[i] - x; hp = val.xa[i + m] - x; for (int L = 0; L < nIntegrals; L++) { w = val.C[L][i + 1] - val.D[L][i]; den = w / (ho - hp); val.D[L][i] = getFromFull<O>(hp, -1.0 / gridDist, 0) * den; val.C[L][i] = getFromFull<O>(ho, -1.0 / gridDist, 0) * den; } } for (int L = 0; L < nIntegrals; L++) { val.derivIntegral[L] += (2 * (ns + 1) < (nInter - m)) ? val.C[L][ns + 1] : val.D[L][ns]; } if (!(2 * (ns + 1) < (nInter - m))) ns--; } } template int SKPair::getHS<Utils::DerivativeOrder::Zero>(double, InterpolationValues<Utils::DerivativeOrder::Zero>&) const; template int SKPair::getHS<Utils::DerivativeOrder::One>(double, InterpolationValues<Utils::DerivativeOrder::One>&) const; template int SKPair::getHS<Utils::DerivativeOrder::Two>(double, InterpolationValues<Utils::DerivativeOrder::Two>&) const; template int SKPair::getHSIntegral<Utils::DerivativeOrder::Zero>(InterpolationValues<Utils::DerivativeOrder::Zero>&, double) const; template int SKPair::getHSIntegral<Utils::DerivativeOrder::One>(InterpolationValues<Utils::DerivativeOrder::One>&, double) const; template int SKPair::getHSIntegral<Utils::DerivativeOrder::Two>(InterpolationValues<Utils::DerivativeOrder::Two>&, double) const; template void SKPair::interpolate<Utils::DerivativeOrder::Zero>(InterpolationValues<Utils::DerivativeOrder::Zero>&, double, int) const; template void SKPair::interpolate<Utils::DerivativeOrder::One>(InterpolationValues<Utils::DerivativeOrder::One>&, double, int) const; template void SKPair::interpolate<Utils::DerivativeOrder::Two>(InterpolationValues<Utils::DerivativeOrder::Two>&, double, int) const; template double SKPair::getRepulsion<Utils::DerivativeOrder::Zero>(double const& r) const; template First1D SKPair::getRepulsion<Utils::DerivativeOrder::One>(double const& r) const; template Second1D SKPair::getRepulsion<Utils::DerivativeOrder::Two>(double const& r) const; } // namespace dftb } // namespace Sparrow } // namespace Scine
39.439739
131
0.631318
7f33db92718d0e225f767b59142b526a75fdc42c
605
cpp
C++
tests/unit/appc/util/test_option.cpp
cdaylward/libappc
4f7316b584d92a110198a3f1573c170e5492194c
[ "Apache-2.0" ]
63
2015-01-20T18:35:27.000Z
2021-11-16T10:53:40.000Z
tests/unit/appc/util/test_option.cpp
Manu343726/libappc
8d181ef4ee80c8f1bcbf6ca04cf66e04e5e5bc8a
[ "Apache-2.0" ]
5
2015-01-20T17:28:54.000Z
2015-02-09T17:36:54.000Z
tests/unit/appc/util/test_option.cpp
cdaylward/libappc
4f7316b584d92a110198a3f1573c170e5492194c
[ "Apache-2.0" ]
12
2015-01-26T04:37:08.000Z
2020-11-14T02:19:13.000Z
#include "gtest/gtest.h" #include "appc/util/option.h" TEST(Option, none_is_false) { auto none = None<int>(); ASSERT_FALSE(none); } TEST(Option, some_is_true) { auto some = Some(std::string{""}); ASSERT_TRUE(some); } TEST(Option, some_is_shared_ptr) { auto some = Some(std::string("")); std::shared_ptr<std::string> ptr = some; ASSERT_EQ(2, ptr.use_count()); } TEST(Option, some_dereferences) { auto some = Some(std::string("one")); ASSERT_EQ(typeid(std::string), typeid(*some)); ASSERT_EQ(typeid(std::string), typeid(from_some(some))); ASSERT_EQ(std::string{"one"}, *some); }
21.607143
58
0.669421
7f34132ef268ccb61428758f166ec384c7d0ad3d
14,400
cc
C++
chrome/browser/ui/views/page_info/permission_selector_row.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/views/page_info/permission_selector_row.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/views/page_info/permission_selector_row.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 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. #include "chrome/browser/ui/views/page_info/permission_selector_row.h" #include "base/i18n/rtl.h" #include "base/macros.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/ui/page_info/page_info_ui.h" #include "chrome/browser/ui/page_info/permission_menu_model.h" #include "chrome/browser/ui/views/harmony/chrome_typography.h" #include "chrome/browser/ui/views/page_info/non_accessible_image_view.h" #include "chrome/browser/ui/views/page_info/page_info_bubble_view.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/material_design/material_design_controller.h" #include "ui/base/models/combobox_model.h" #include "ui/gfx/image/image.h" #include "ui/views/controls/button/menu_button.h" #include "ui/views/controls/combobox/combobox.h" #include "ui/views/controls/combobox/combobox_listener.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/label.h" #include "ui/views/controls/menu/menu_runner.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" namespace internal { // The |PermissionMenuButton| provides a menu for selecting a setting a // permissions type. class PermissionMenuButton : public views::MenuButton, public views::MenuButtonListener { public: // Creates a new |PermissionMenuButton| with the passed |text|. The ownership // of the |model| remains with the caller and is not transfered to the // |PermissionMenuButton|. If the |show_menu_marker| flag is true, then a // small icon is be displayed next to the button |text|, indicating that the // button opens a drop down menu. PermissionMenuButton(const base::string16& text, PermissionMenuModel* model, bool show_menu_marker); ~PermissionMenuButton() override; // Overridden from views::View. void GetAccessibleNodeData(ui::AXNodeData* node_data) override; void OnNativeThemeChanged(const ui::NativeTheme* theme) override; private: // Overridden from views::MenuButtonListener. void OnMenuButtonClicked(views::MenuButton* source, const gfx::Point& point, const ui::Event* event) override; PermissionMenuModel* menu_model_; // Owned by |PermissionSelectorRow|. std::unique_ptr<views::MenuRunner> menu_runner_; bool is_rtl_display_; DISALLOW_COPY_AND_ASSIGN(PermissionMenuButton); }; /////////////////////////////////////////////////////////////////////////////// // PermissionMenuButton /////////////////////////////////////////////////////////////////////////////// PermissionMenuButton::PermissionMenuButton(const base::string16& text, PermissionMenuModel* model, bool show_menu_marker) : MenuButton(text, this, show_menu_marker), menu_model_(model) { // Since PermissionMenuButtons are added to a GridLayout, they are not always // sized to their preferred size. Disclosure arrows are always right-aligned, // so if the text is not right-aligned, awkward space appears between the text // and the arrow. SetHorizontalAlignment(gfx::ALIGN_RIGHT); // Update the themed border before the NativeTheme is applied. Usually this // happens in a call to LabelButton::OnNativeThemeChanged(). However, if // PermissionMenuButton called that from its override, the NativeTheme would // be available, and the button would get native GTK styling on Linux. UpdateThemedBorder(); SetFocusForPlatform(); set_request_focus_on_press(true); is_rtl_display_ = base::i18n::RIGHT_TO_LEFT == base::i18n::GetStringDirection(text); } PermissionMenuButton::~PermissionMenuButton() {} void PermissionMenuButton::GetAccessibleNodeData(ui::AXNodeData* node_data) { MenuButton::GetAccessibleNodeData(node_data); node_data->SetValue(GetText()); } void PermissionMenuButton::OnNativeThemeChanged(const ui::NativeTheme* theme) { SetTextColor( views::Button::STATE_NORMAL, theme->GetSystemColor(ui::NativeTheme::kColorId_LabelEnabledColor)); SetTextColor( views::Button::STATE_HOVERED, theme->GetSystemColor(ui::NativeTheme::kColorId_LabelEnabledColor)); SetTextColor( views::Button::STATE_DISABLED, theme->GetSystemColor(ui::NativeTheme::kColorId_LabelDisabledColor)); } void PermissionMenuButton::OnMenuButtonClicked(views::MenuButton* source, const gfx::Point& point, const ui::Event* event) { menu_runner_.reset( new views::MenuRunner(menu_model_, views::MenuRunner::HAS_MNEMONICS)); gfx::Point p(point); p.Offset(is_rtl_display_ ? source->width() : -source->width(), 0); menu_runner_->RunMenuAt(source->GetWidget()->GetTopLevelWidget(), this, gfx::Rect(p, gfx::Size()), views::MENU_ANCHOR_TOPLEFT, ui::MENU_SOURCE_NONE); } // This class adapts a |PermissionMenuModel| into a |ui::ComboboxModel| so that // |PermissionCombobox| can use it. class ComboboxModelAdapter : public ui::ComboboxModel { public: explicit ComboboxModelAdapter(PermissionMenuModel* model) : model_(model) {} ~ComboboxModelAdapter() override {} void OnPerformAction(int index); // Returns the checked index of the underlying PermissionMenuModel, of which // there must be exactly one. This is used to choose which index is selected // in the PermissionCombobox. int GetCheckedIndex(); // ui::ComboboxModel: int GetItemCount() const override; base::string16 GetItemAt(int index) override; private: PermissionMenuModel* model_; }; void ComboboxModelAdapter::OnPerformAction(int index) { model_->ExecuteCommand(index, 0); } int ComboboxModelAdapter::GetCheckedIndex() { int checked_index = -1; for (int i = 0; i < model_->GetItemCount(); ++i) { if (model_->IsCommandIdChecked(i)) { // This function keeps track of |checked_index| instead of returning early // here so that it can DCHECK that there's exactly one selected item, // which is not normally guaranteed by MenuModel, but *is* true of // PermissionMenuModel. DCHECK_EQ(checked_index, -1); checked_index = i; } } return checked_index; } int ComboboxModelAdapter::GetItemCount() const { DCHECK(model_); return model_->GetItemCount(); } base::string16 ComboboxModelAdapter::GetItemAt(int index) { return model_->GetLabelAt(index); } // The |PermissionCombobox| provides a combobox for selecting a permission type. // This is only used on platforms where the permission dialog uses a combobox // instead of a MenuButton (currently, Mac). class PermissionCombobox : public views::Combobox, public views::ComboboxListener { public: PermissionCombobox(ComboboxModelAdapter* model, bool enabled, bool use_default); ~PermissionCombobox() override; void UpdateSelectedIndex(bool use_default); private: // views::Combobox: void OnPaintBorder(gfx::Canvas* canvas) override; // views::ComboboxListener: void OnPerformAction(Combobox* combobox) override; ComboboxModelAdapter* model_; }; PermissionCombobox::PermissionCombobox(ComboboxModelAdapter* model, bool enabled, bool use_default) : views::Combobox(model), model_(model) { set_listener(this); SetEnabled(enabled); UpdateSelectedIndex(use_default); if (ui::MaterialDesignController::IsSecondaryUiMaterial()) { set_size_to_largest_label(false); ModelChanged(); } } PermissionCombobox::~PermissionCombobox() {} void PermissionCombobox::UpdateSelectedIndex(bool use_default) { int index = model_->GetCheckedIndex(); if (use_default && index == -1) { index = 0; } SetSelectedIndex(index); } void PermissionCombobox::OnPaintBorder(gfx::Canvas* canvas) { // No border except a focus indicator for MD mode. if (ui::MaterialDesignController::IsSecondaryUiMaterial() && !HasFocus()) { return; } Combobox::OnPaintBorder(canvas); } void PermissionCombobox::OnPerformAction(Combobox* combobox) { model_->OnPerformAction(combobox->selected_index()); } } // namespace internal /////////////////////////////////////////////////////////////////////////////// // PermissionSelectorRow /////////////////////////////////////////////////////////////////////////////// PermissionSelectorRow::PermissionSelectorRow( Profile* profile, const GURL& url, const PageInfoUI::PermissionInfo& permission, views::GridLayout* layout) : profile_(profile), icon_(NULL), menu_button_(NULL), combobox_(NULL) { // Create the permission icon. icon_ = new NonAccessibleImageView(); const gfx::Image& image = PageInfoUI::GetPermissionIcon(permission); icon_->SetImage(image.ToImageSkia()); layout->AddView(icon_, 1, 1, views::GridLayout::CENTER, views::GridLayout::CENTER); // Create the label that displays the permission type. label_ = new views::Label(PageInfoUI::PermissionTypeToUIString(permission.type), CONTEXT_BODY_TEXT_LARGE); layout->AddView(label_, 1, 1, views::GridLayout::LEADING, views::GridLayout::CENTER); // Create the menu model. menu_model_.reset(new PermissionMenuModel( profile, url, permission, base::Bind(&PermissionSelectorRow::PermissionChanged, base::Unretained(this)))); // Create the permission menu button. #if defined(OS_MACOSX) bool use_real_combobox = true; #else bool use_real_combobox = ui::MaterialDesignController::IsSecondaryUiMaterial(); #endif if (use_real_combobox) { InitializeComboboxView(layout, permission); } else { InitializeMenuButtonView(layout, permission); } // Show the permission decision reason, if it was not the user. base::string16 reason = PageInfoUI::PermissionDecisionReasonToUIString(profile, permission, url); if (!reason.empty()) { layout->StartRow(1, 1); layout->SkipColumns(1); views::Label* permission_decision_reason = new views::Label(reason); permission_decision_reason->SetEnabledColor( PageInfoUI::GetPermissionDecisionTextColor()); // Long labels should span the remaining width of the row. views::ColumnSet* column_set = layout->GetColumnSet(1); DCHECK(column_set); layout->AddView(permission_decision_reason, column_set->num_columns() - 2, 1, views::GridLayout::LEADING, views::GridLayout::CENTER); } } void PermissionSelectorRow::AddObserver( PermissionSelectorRowObserver* observer) { observer_list_.AddObserver(observer); } PermissionSelectorRow::~PermissionSelectorRow() { // Gross. On paper the Combobox and the ComboboxModelAdapter are both owned by // this class, but actually, the Combobox is owned by View and will be // destroyed in ~View(), which runs *after* ~PermissionSelectorRow() is done, // which means the Combobox gets destroyed after its ComboboxModel, which // causes an explosion when the Combobox attempts to stop observing the // ComboboxModel. This hack ensures the Combobox is deleted before its // ComboboxModel. // // Technically, the MenuButton has the same problem, but MenuButton doesn't // use its model in its destructor. if (combobox_) { combobox_->parent()->RemoveChildView(combobox_); } } void PermissionSelectorRow::InitializeMenuButtonView( views::GridLayout* layout, const PageInfoUI::PermissionInfo& permission) { bool button_enabled = permission.source == content_settings::SETTING_SOURCE_USER; menu_button_ = new internal::PermissionMenuButton( PageInfoUI::PermissionActionToUIString( profile_, permission.type, permission.setting, permission.default_setting, permission.source), menu_model_.get(), button_enabled); menu_button_->SetEnabled(button_enabled); menu_button_->SetAccessibleName( PageInfoUI::PermissionTypeToUIString(permission.type)); layout->AddView(menu_button_); } void PermissionSelectorRow::InitializeComboboxView( views::GridLayout* layout, const PageInfoUI::PermissionInfo& permission) { bool button_enabled = permission.source == content_settings::SETTING_SOURCE_USER; combobox_model_adapter_.reset( new internal::ComboboxModelAdapter(menu_model_.get())); combobox_ = new internal::PermissionCombobox(combobox_model_adapter_.get(), button_enabled, true); combobox_->SetEnabled(button_enabled); combobox_->SetAccessibleName( PageInfoUI::PermissionTypeToUIString(permission.type)); layout->AddView(combobox_); } void PermissionSelectorRow::PermissionChanged( const PageInfoUI::PermissionInfo& permission) { // Change the permission icon to reflect the selected setting. const gfx::Image& image = PageInfoUI::GetPermissionIcon(permission); icon_->SetImage(image.ToImageSkia()); // Update the menu button text to reflect the new setting. if (menu_button_) { menu_button_->SetText(PageInfoUI::PermissionActionToUIString( profile_, permission.type, permission.setting, permission.default_setting, content_settings::SETTING_SOURCE_USER)); menu_button_->SizeToPreferredSize(); // Re-layout will be done at the |PageInfoBubbleView| level, since // that view may need to resize itself to accomodate the new sizes of its // contents. menu_button_->InvalidateLayout(); } else if (combobox_) { bool use_default = permission.setting == CONTENT_SETTING_DEFAULT; combobox_->UpdateSelectedIndex(use_default); } for (PermissionSelectorRowObserver& observer : observer_list_) { observer.OnPermissionChanged(permission); } } views::View* PermissionSelectorRow::button() { // These casts are required because the two arms of a ?: cannot have different // types T1 and T2, even if the resulting value of the ?: is about to be a T // and T1 and T2 are both subtypes of T. return menu_button_ ? static_cast<views::View*>(menu_button_) : static_cast<views::View*>(combobox_); }
38.4
80
0.702083
7f344ec08e017dcdf3c41926a1d07bd06a239b8b
757
hpp
C++
bia/memory/gc/root.hpp
bialang/bia
b54fff096b4fe91ddb0b1d509ea828daa11cee7e
[ "BSD-3-Clause" ]
2
2017-09-09T17:03:18.000Z
2018-03-02T20:02:02.000Z
bia/memory/gc/root.hpp
terrakuh/Bia
412b7e8aeb259f4925c3b588f6025760a43cd0b7
[ "BSD-3-Clause" ]
7
2018-10-11T18:14:19.000Z
2018-12-26T15:31:04.000Z
bia/memory/gc/root.hpp
terrakuh/Bia
412b7e8aeb259f4925c3b588f6025760a43cd0b7
[ "BSD-3-Clause" ]
null
null
null
#ifndef BIA_MEMORY_GC_ROOT_HPP_ #define BIA_MEMORY_GC_ROOT_HPP_ #include <bia/util/gsl.hpp> #include <cstddef> #include <memory> #include <mutex> namespace bia { namespace memory { namespace gc { class GC; /// Defines the root for the search tree for the marking phase during garbage collection. This class is not /// thread-safe. class Root { public: Root(const Root& copy) = delete; ~Root() noexcept; void* at(std::size_t index); void put(std::size_t index, void* ptr); Root& operator=(const Root& copy) = delete; private: friend GC; typedef util::Span<void**> Data; GC* _parent = nullptr; Data _data; std::mutex _mutex; Root(GC* parent, std::size_t size) noexcept; }; } // namespace gc } // namespace memory } // namespace bia #endif
18.02381
107
0.712021
7f379093ec9f642f9797b97b5696ef29a2f9e7dc
469
hpp
C++
archive/stan/src/stan/model/standalone_functions_header.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
archive/stan/src/stan/model/standalone_functions_header.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
archive/stan/src/stan/model/standalone_functions_header.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MODEL_STANDALONE_FUNCTIONS_HEADER_HPP #define STAN_MODEL_STANDALONE_FUNCTIONS_HEADER_HPP #include <stan/math.hpp> #include <boost/random/additive_combine.hpp> #include <stan/io/program_reader.hpp> #include <stan/lang/rethrow_located.hpp> #include <stan/model/indexing.hpp> #include <cmath> #include <cstddef> #include <fstream> #include <iostream> #include <sstream> #include <stdexcept> #include <utility> #include <vector> #endif
22.333333
51
0.763326
7f3ebfb97f2fa4678666afd5f2133eaaafbea074
1,762
cc
C++
thirdparty/jplayer/thirdparty/libde265/libde265/encoder/algo/tb-rateestim.cc
Houkime/echo
d115ca55faf3a140bea04feffeb2efdedb0e7f82
[ "MIT" ]
675
2019-02-07T01:23:19.000Z
2022-03-28T05:45:10.000Z
thirdparty/jplayer/thirdparty/libde265/libde265/encoder/algo/tb-rateestim.cc
Houkime/echo
d115ca55faf3a140bea04feffeb2efdedb0e7f82
[ "MIT" ]
843
2019-01-25T01:06:46.000Z
2022-03-16T11:15:53.000Z
thirdparty/jplayer/thirdparty/libde265/libde265/encoder/algo/tb-rateestim.cc
Houkime/echo
d115ca55faf3a140bea04feffeb2efdedb0e7f82
[ "MIT" ]
83
2019-02-20T06:18:46.000Z
2022-03-20T09:36:09.000Z
/* * H.265 video codec. * Copyright (c) 2013-2014 struktur AG, Dirk Farin <farin@struktur.de> * * Authors: struktur AG, Dirk Farin <farin@struktur.de> * * This file is part of libde265. * * libde265 is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * libde265 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with libde265. If not, see <http://www.gnu.org/licenses/>. */ #include "libde265/encoder/algo/tb-rateestim.h" #include "libde265/encoder/encoder-syntax.h" #include <assert.h> #include <iostream> float Algo_TB_RateEstimation_Exact::encode_transform_unit(encoder_context* ectx, context_model_table& ctxModel, const enc_tb* tb, const enc_cb* cb, int x0,int y0, int xBase,int yBase, int log2TrafoSize, int trafoDepth, int blkIdx) { CABAC_encoder_estim estim; estim.set_context_models(&ctxModel); leaf(cb, NULL); ::encode_transform_unit(ectx, &estim, tb,cb, x0,y0, xBase,yBase, log2TrafoSize, trafoDepth, blkIdx); return estim.getRDBits(); }
37.489362
93
0.613507
7f41e852364ec3899156a3df2674f78ef0c58bfa
738
cpp
C++
algorithms/cpp/1_TwoSum_Easy/main.cpp
vsawce/leetcode_practice
f0195d0749e3143e25708668bf9f35e152d895cf
[ "MIT" ]
null
null
null
algorithms/cpp/1_TwoSum_Easy/main.cpp
vsawce/leetcode_practice
f0195d0749e3143e25708668bf9f35e152d895cf
[ "MIT" ]
null
null
null
algorithms/cpp/1_TwoSum_Easy/main.cpp
vsawce/leetcode_practice
f0195d0749e3143e25708668bf9f35e152d895cf
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; vector<int> twoSum(vector<int>& nums, int target) { for (int i = 0; i < nums.size(); i++) { for (int j = 0; j < i; j++) { if (nums[i] + nums[j] == target) { return vector<int> {j, i}; } } } return nums; } int main() { vector<int> v1 {2,7,11,15}; int t1 = 9; vector<int> v2 {3,2,4}; int t2 = 6; vector<int> v3 {3,3}; int t3 = 6; cout << "[" << twoSum(v1,t1)[0] << ", " << twoSum(v1, t1)[1] << "]\n"; cout << "[" << twoSum(v2,t2)[0] << ", " << twoSum(v2, t2)[1] << "]\n"; cout << "[" << twoSum(v3,t3)[0] << ", " << twoSum(v3, t3)[1] << "]\n"; return 0; }
18.45
74
0.424119
7f470ee74bb40907b5c8a97d042ed1ee216e9aef
74,059
cc
C++
lullaby/systems/render/next/render_system_next.cc
jjzhang166/lullaby
d9b11ea811cb5869b46165b9b9537b6063c6cbae
[ "Apache-2.0" ]
null
null
null
lullaby/systems/render/next/render_system_next.cc
jjzhang166/lullaby
d9b11ea811cb5869b46165b9b9537b6063c6cbae
[ "Apache-2.0" ]
null
null
null
lullaby/systems/render/next/render_system_next.cc
jjzhang166/lullaby
d9b11ea811cb5869b46165b9b9537b6063c6cbae
[ "Apache-2.0" ]
null
null
null
/* Copyright 2017 Google 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 "lullaby/systems/render/next/render_system_next.h" #include <inttypes.h> #include <stdio.h> #include "fplbase/glplatform.h" #include "fplbase/internal/type_conversions_gl.h" #include "fplbase/render_utils.h" #include "lullaby/events/render_events.h" #include "lullaby/modules/config/config.h" #include "lullaby/modules/dispatcher/dispatcher.h" #include "lullaby/modules/ecs/entity_factory.h" #include "lullaby/modules/file/file.h" #include "lullaby/modules/flatbuffers/mathfu_fb_conversions.h" #include "lullaby/modules/render/mesh_util.h" #include "lullaby/modules/render/triangle_mesh.h" #include "lullaby/modules/script/function_binder.h" #include "lullaby/systems/dispatcher/dispatcher_system.h" #include "lullaby/systems/dispatcher/event.h" #include "lullaby/systems/render/detail/profiler.h" #include "lullaby/systems/render/next/render_state.h" #include "lullaby/systems/render/render_stats.h" #include "lullaby/systems/render/simple_font.h" #include "lullaby/util/logging.h" #include "lullaby/util/make_unique.h" #include "lullaby/util/math.h" #include "lullaby/util/trace.h" #include "lullaby/generated/render_def_generated.h" namespace lull { namespace { constexpr int kInitialRenderPoolSize = 512; const HashValue kRenderDefHash = Hash("RenderDef"); const RenderSystemNext::RenderComponentID kDefaultRenderId = 0; constexpr int kNumVec4sInAffineTransform = 3; constexpr const char* kColorUniform = "color"; constexpr const char* kTextureBoundsUniform = "uv_bounds"; constexpr const char* kClampBoundsUniform = "clamp_bounds"; constexpr const char* kBoneTransformsUniform = "bone_transforms"; // We break the naming convention here for compatibility with early VR apps. constexpr const char* kIsRightEyeUniform = "uIsRightEye"; template <typename T> void RemoveFromVector(std::vector<T>* vector, const T& value) { if (!vector) { return; } for (auto it = vector->cbegin(); it != vector->cend(); ++it) { if (*it == value) { vector->erase(it); return; } } } bool IsSupportedUniformDimension(int dimension) { return (dimension == 1 || dimension == 2 || dimension == 3 || dimension == 4 || dimension == 16); } void SetDebugUniform(Shader* shader, const char* name, const float values[4]) { const fplbase::UniformHandle location = shader->FindUniform(name); if (fplbase::ValidUniformHandle(location)) { shader->SetUniform(location, values, 4); } } void DrawDynamicMesh(const MeshData* mesh) { const fplbase::Mesh::Primitive prim = Mesh::GetFplPrimitiveType(mesh->GetPrimitiveType()); const VertexFormat& vertex_format = mesh->GetVertexFormat(); const uint32_t vertex_size = static_cast<uint32_t>(vertex_format.GetVertexSize()); fplbase::Attribute fpl_attribs[Mesh::kMaxFplAttributeArraySize]; Mesh::GetFplAttributes(vertex_format, fpl_attribs); if (mesh->GetNumIndices() > 0) { fplbase::RenderArray(prim, static_cast<int>(mesh->GetNumIndices()), fpl_attribs, vertex_size, mesh->GetVertexBytes(), mesh->GetIndexData()); } else { fplbase::RenderArray(prim, mesh->GetNumVertices(), fpl_attribs, vertex_size, mesh->GetVertexBytes()); } } fplbase::RenderTargetTextureFormat RenderTargetTextureFormatToFpl( TextureFormat format) { switch (format) { case TextureFormat_A8: return fplbase::kRenderTargetTextureFormatA8; break; case TextureFormat_R8: return fplbase::kRenderTargetTextureFormatR8; break; case TextureFormat_RGB8: return fplbase::kRenderTargetTextureFormatRGB8; break; case TextureFormat_RGBA8: return fplbase::kRenderTargetTextureFormatRGBA8; break; default: LOG(DFATAL) << "Unknown render target texture format."; return fplbase::kRenderTargetTextureFormatCount; } } fplbase::DepthStencilFormat DepthStencilFormatToFpl(DepthStencilFormat format) { switch (format) { case DepthStencilFormat_None: return fplbase::kDepthStencilFormatNone; break; case DepthStencilFormat_Depth16: return fplbase::kDepthStencilFormatDepth16; break; case DepthStencilFormat_Depth24: return fplbase::kDepthStencilFormatDepth24; break; case DepthStencilFormat_Depth32F: return fplbase::kDepthStencilFormatDepth32F; break; case DepthStencilFormat_Depth24Stencil8: return fplbase::kDepthStencilFormatDepth24Stencil8; break; case DepthStencilFormat_Depth32FStencil8: return fplbase::kDepthStencilFormatDepth32FStencil8; break; case DepthStencilFormat_Stencil8: return fplbase::kDepthStencilFormatStencil8; break; default: LOG(DFATAL) << "Unknown depth stencil format."; return fplbase::kDepthStencilFormatCount; } } void UpdateUniformBinding(Uniform::Description* desc, const ShaderPtr& shader) { if (!desc) { return; } if (shader) { const Shader::UniformHnd handle = shader->FindUniform(desc->name.c_str()); if (fplbase::ValidUniformHandle(handle)) { desc->binding = fplbase::GlUniformHandle(handle); return; } } desc->binding = -1; } } // namespace RenderSystemNext::RenderSystemNext(Registry* registry) : System(registry), components_(kInitialRenderPoolSize), sort_order_manager_(registry_) { renderer_.Initialize(mathfu::kZeros2i, "lull::RenderSystem"); factory_ = registry->Create<RenderFactory>(registry, &renderer_); registry_->Get<Dispatcher>()->Connect( this, [this](const ParentChangedEvent& event) { OnParentChanged(event); }); FunctionBinder* binder = registry->Get<FunctionBinder>(); if (binder) { binder->RegisterMethod("lull.Render.Show", &lull::RenderSystem::Show); binder->RegisterMethod("lull.Render.Hide", &lull::RenderSystem::Hide); binder->RegisterFunction("lull.Render.GetTextureId", [this](Entity entity) { TexturePtr texture = GetTexture(entity, 0); return texture ? static_cast<int>(texture->GetResourceId().handle) : 0; }); } } RenderSystemNext::~RenderSystemNext() { FunctionBinder* binder = registry_->Get<FunctionBinder>(); if (binder) { binder->UnregisterFunction("lull.Render.Show"); binder->UnregisterFunction("lull.Render.Hide"); binder->UnregisterFunction("lull.Render.GetTextureId"); } registry_->Get<Dispatcher>()->DisconnectAll(this); } void RenderSystemNext::Initialize() { InitDefaultRenderPasses(); } void RenderSystemNext::SetStereoMultiviewEnabled(bool enabled) { multiview_enabled_ = enabled; } void RenderSystemNext::PreloadFont(const char* name) { LOG(FATAL) << "Deprecated."; } FontPtr RenderSystemNext::LoadFonts(const std::vector<std::string>& names) { LOG(FATAL) << "Deprecated."; return nullptr; } const TexturePtr& RenderSystemNext::GetWhiteTexture() const { return factory_->GetWhiteTexture(); } const TexturePtr& RenderSystemNext::GetInvalidTexture() const { return factory_->GetInvalidTexture(); } TexturePtr RenderSystemNext::LoadTexture(const std::string& filename, bool create_mips) { return factory_->LoadTexture(filename, create_mips); } TexturePtr RenderSystemNext::GetTexture(HashValue texture_hash) const { return factory_->GetCachedTexture(texture_hash); } void RenderSystemNext::LoadTextureAtlas(const std::string& filename) { const bool create_mips = false; factory_->LoadTextureAtlas(filename, create_mips); } MeshPtr RenderSystemNext::LoadMesh(const std::string& filename) { return factory_->LoadMesh(filename); } ShaderPtr RenderSystemNext::LoadShader(const std::string& filename) { return factory_->LoadShader(filename); } void RenderSystemNext::Create(Entity e, HashValue component_id, HashValue pass) { const EntityIdPair entity_id_pair(e, component_id); RenderComponent* component = components_.Emplace(entity_id_pair); if (!component) { LOG(DFATAL) << "RenderComponent for Entity " << e << " with id " << component_id << " already exists."; return; } entity_ids_[e].push_back(entity_id_pair); component->pass = pass; SetSortOrderOffset(e, 0); } void RenderSystemNext::Create(Entity e, HashValue pass) { Create(e, kDefaultRenderId, pass); } void RenderSystemNext::Create(Entity e, HashValue type, const Def* def) { if (type != kRenderDefHash) { LOG(DFATAL) << "Invalid type passed to Create. Expecting RenderDef!"; return; } const RenderDef& data = *ConvertDef<RenderDef>(def); if (data.font()) { LOG(FATAL) << "Deprecated."; } const EntityIdPair entity_id_pair(e, data.id()); RenderComponent* component = components_.Emplace(entity_id_pair); if (!component) { LOG(DFATAL) << "RenderComponent for Entity " << e << " with id " << data.id() << " already exists."; return; } entity_ids_[e].push_back(entity_id_pair); if (data.pass() == RenderPass_Pano) { component->pass = ConstHash("Pano"); } else if (data.pass() == RenderPass_Opaque) { component->pass = ConstHash("Opaque"); } else if (data.pass() == RenderPass_Main) { component->pass = ConstHash("Main"); } else if (data.pass() == RenderPass_OverDraw) { component->pass = ConstHash("OverDraw"); } else if (data.pass() == RenderPass_Debug) { component->pass = ConstHash("Debug"); } else if (data.pass() == RenderPass_Invisible) { component->pass = ConstHash("Invisible"); } else if (data.pass() == RenderPass_OverDrawGlow) { component->pass = ConstHash("OverDrawGlow"); } component->hidden = data.hidden(); if (data.shader()) { SetShader(e, data.id(), LoadShader(data.shader()->str())); } if (data.textures()) { for (unsigned int i = 0; i < data.textures()->size(); ++i) { TexturePtr texture = factory_->LoadTexture(data.textures()->Get(i)->c_str(), data.create_mips()); SetTexture(e, data.id(), i, texture); } } else if (data.texture() && data.texture()->size() > 0) { TexturePtr texture = factory_->LoadTexture(data.texture()->c_str(), data.create_mips()); SetTexture(e, data.id(), 0, texture); } else if (data.external_texture()) { #ifdef GL_TEXTURE_EXTERNAL_OES GLuint texture_id; GL_CALL(glGenTextures(1, &texture_id)); GL_CALL(glBindTexture(GL_TEXTURE_EXTERNAL_OES, texture_id)); GL_CALL(glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); GL_CALL(glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); GL_CALL(glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); GL_CALL(glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); SetTextureId(e, data.id(), 0, GL_TEXTURE_EXTERNAL_OES, texture_id); #else LOG(WARNING) << "External textures are not available."; #endif // GL_TEXTURE_EXTERNAL_OES } if (data.mesh()) { SetMesh(e, data.id(), factory_->LoadMesh(data.mesh()->c_str())); } if (data.color()) { mathfu::vec4 color; MathfuVec4FromFbColor(data.color(), &color); SetUniform(e, data.id(), kColorUniform, &color[0], 4, 1); component->default_color = color; } else if (data.color_hex()) { mathfu::vec4 color; MathfuVec4FromFbColorHex(data.color_hex()->c_str(), &color); SetUniform(e, data.id(), kColorUniform, &color[0], 4, 1); component->default_color = color; } if (data.uniforms()) { for (const UniformDef* uniform : *data.uniforms()) { if (!uniform->name() || !uniform->float_value()) { LOG(DFATAL) << "Missing required uniform name or value"; continue; } if (uniform->dimension() <= 0) { LOG(DFATAL) << "Uniform dimension must be positive: " << uniform->dimension(); continue; } if (uniform->count() <= 0) { LOG(DFATAL) << "Uniform count must be positive: " << uniform->count(); continue; } if (uniform->float_value()->size() != static_cast<size_t>(uniform->dimension() * uniform->count())) { LOG(DFATAL) << "Uniform must have dimension x count values: " << uniform->float_value()->size(); continue; } SetUniform(e, data.id(), uniform->name()->c_str(), uniform->float_value()->data(), uniform->dimension(), uniform->count()); } } SetSortOrderOffset(e, data.id(), data.sort_order_offset()); } void RenderSystemNext::PostCreateInit(Entity e, HashValue type, const Def* def) { if (type == kRenderDefHash) { auto& data = *ConvertDef<RenderDef>(def); if (data.text()) { LOG(FATAL) << "Deprecated."; } else if (data.quad()) { const QuadDef& quad_def = *data.quad(); Quad quad; quad.size = mathfu::vec2(quad_def.size_x(), quad_def.size_y()); quad.verts = mathfu::vec2i(quad_def.verts_x(), quad_def.verts_y()); quad.has_uv = quad_def.has_uv(); quad.corner_radius = quad_def.corner_radius(); quad.corner_verts = quad_def.corner_verts(); if (data.shape_id()) { quad.id = Hash(data.shape_id()->c_str()); } SetQuad(e, data.id(), quad); } } } void RenderSystemNext::Destroy(Entity e) { SetStencilMode(e, StencilMode::kDisabled, 0); auto iter = entity_ids_.find(e); if (iter != entity_ids_.end()) { for (const EntityIdPair& entity_id_pair : iter->second) { components_.Destroy(entity_id_pair); } entity_ids_.erase(iter); } deformations_.erase(e); sort_order_manager_.Destroy(e); } void RenderSystemNext::Destroy(Entity e, HashValue component_id) { const EntityIdPair entity_id_pair(e, component_id); SetStencilMode(e, component_id, StencilMode::kDisabled, 0); auto iter = entity_ids_.find(e); if (iter != entity_ids_.end()) { RemoveFromVector(&iter->second, entity_id_pair); } deformations_.erase(e); sort_order_manager_.Destroy(entity_id_pair); } void RenderSystemNext::SetQuadImpl(Entity e, HashValue component_id, const Quad& quad) { if (quad.has_uv) { SetMesh(e, component_id, CreateQuad<VertexPT>(e, component_id, quad)); } else { SetMesh(e, component_id, CreateQuad<VertexP>(e, component_id, quad)); } } void RenderSystemNext::CreateDeferredMeshes() { while (!deferred_meshes_.empty()) { DeferredMesh& defer = deferred_meshes_.front(); switch (defer.type) { case DeferredMesh::kQuad: SetQuadImpl(defer.entity_id_pair.entity, defer.entity_id_pair.id, defer.quad); break; case DeferredMesh::kMesh: DeformMesh(defer.entity_id_pair.entity, defer.entity_id_pair.id, &defer.mesh); SetMesh(defer.entity_id_pair.entity, defer.entity_id_pair.id, defer.mesh); break; } deferred_meshes_.pop(); } } void RenderSystemNext::ProcessTasks() { LULLABY_CPU_TRACE_CALL(); CreateDeferredMeshes(); factory_->UpdateAssetLoad(); } void RenderSystemNext::WaitForAssetsToLoad() { CreateDeferredMeshes(); factory_->WaitForAssetsToLoad(); } const mathfu::vec4& RenderSystemNext::GetDefaultColor(Entity entity) const { const RenderComponent* component = components_.Get(entity); if (component) { return component->default_color; } return mathfu::kOnes4f; } void RenderSystemNext::SetDefaultColor(Entity entity, const mathfu::vec4& color) { RenderComponent* component = components_.Get(entity); if (component) { component->default_color = color; } } bool RenderSystemNext::GetColor(Entity entity, mathfu::vec4* color) const { return GetUniform(entity, kColorUniform, 4, &(*color)[0]); } void RenderSystemNext::SetColor(Entity entity, const mathfu::vec4& color) { SetUniform(entity, kColorUniform, &color[0], 4, 1); } void RenderSystemNext::SetUniform(Entity e, const char* name, const float* data, int dimension, int count) { SetUniform(e, kDefaultRenderId, name, data, dimension, count); } void RenderSystemNext::SetUniform(Entity e, HashValue component_id, const char* name, const float* data, int dimension, int count) { if (!IsSupportedUniformDimension(dimension)) { LOG(DFATAL) << "Unsupported uniform dimension " << dimension; return; } const EntityIdPair entity_id_pair(e, component_id); auto* render_component = components_.Get(entity_id_pair); if (!render_component || !render_component->material.GetShader()) { return; } const size_t num_bytes = dimension * count * sizeof(float); Uniform* uniform = render_component->material.GetUniformByName(name); if (!uniform || uniform->GetDescription().num_bytes != num_bytes) { Uniform::Description desc( name, (dimension > 4) ? Uniform::Type::kMatrix : Uniform::Type::kFloats, num_bytes, count); if (!uniform) { render_component->material.AddUniform(desc); } else { render_component->material.UpdateUniform(desc); } } render_component->material.SetUniformByName(name, data, dimension * count); uniform = render_component->material.GetUniformByName(name); if (uniform && uniform->GetDescription().binding == -1) { UpdateUniformBinding(&uniform->GetDescription(), render_component->material.GetShader()); } } bool RenderSystemNext::GetUniform(Entity e, const char* name, size_t length, float* data_out) const { return GetUniform(e, kDefaultRenderId, name, length, data_out); } bool RenderSystemNext::GetUniform(Entity e, HashValue component_id, const char* name, size_t length, float* data_out) const { const EntityIdPair entity_id_pair(e, component_id); auto* render_component = components_.Get(entity_id_pair); if (!render_component) { return false; } const Uniform* uniform = render_component->material.GetUniformByName(name); if (!uniform) { return false; } const Uniform::Description& desc = uniform->GetDescription(); // Length is the number of floats expected. Convert it into size in bytes. const size_t expected_bytes = length * sizeof(float); if (expected_bytes < desc.num_bytes) { return false; } memcpy(data_out, uniform->GetData<float>(), sizeof(float) * length); return true; } void RenderSystemNext::CopyUniforms(Entity entity, Entity source) { RenderComponent* component = components_.Get(entity); if (!component) { return; } component->material.ClearUniforms(); const RenderComponent* source_component = components_.Get(source); if (source_component) { const UniformVector& uniforms = source_component->material.GetUniforms(); for (auto& uniform : uniforms) { component->material.AddUniform(uniform); } if (component->material.GetShader() != source_component->material.GetShader()) { // Fix the locations using |entity|'s shader. UpdateUniformLocations(component); } } } void RenderSystemNext::UpdateUniformLocations(RenderComponent* component) { if (!component->material.GetShader()) { return; } auto& uniforms = component->material.GetUniforms(); for (Uniform& uniform : uniforms) { UpdateUniformBinding(&uniform.GetDescription(), component->material.GetShader()); } } int RenderSystemNext::GetNumBones(Entity entity) const { const RenderComponent* component = components_.Get(entity); if (!component || !component->mesh) { return 0; } return component->mesh->GetNumBones(); } const uint8_t* RenderSystemNext::GetBoneParents(Entity e, int* num) const { auto* render_component = components_.Get(e); if (!render_component || !render_component->mesh) { if (num) { *num = 0; } return nullptr; } return render_component->mesh->GetBoneParents(num); } const std::string* RenderSystemNext::GetBoneNames(Entity e, int* num) const { auto* render_component = components_.Get(e); if (!render_component || !render_component->mesh) { if (num) { *num = 0; } return nullptr; } return render_component->mesh->GetBoneNames(num); } const mathfu::AffineTransform* RenderSystemNext::GetDefaultBoneTransformInverses(Entity e, int* num) const { auto* render_component = components_.Get(e); if (!render_component || !render_component->mesh) { if (num) { *num = 0; } return nullptr; } return render_component->mesh->GetDefaultBoneTransformInverses(num); } void RenderSystemNext::SetBoneTransforms( Entity entity, const mathfu::AffineTransform* transforms, int num_transforms) { RenderComponent* component = components_.Get(entity); if (!component || !component->mesh) { return; } const int num_shader_bones = component->mesh->GetNumShaderBones(); shader_transforms_.resize(num_shader_bones); if (num_transforms != component->mesh->GetNumBones()) { LOG(DFATAL) << "Mesh must have " << num_transforms << " bones."; return; } component->mesh->GatherShaderTransforms(transforms, shader_transforms_.data()); // GLES2 only supports square matrices, so send the affine transforms as an // array of 3 * num_transforms vec4s. const float* data = &(shader_transforms_[0][0]); const int dimension = 4; const int count = kNumVec4sInAffineTransform * num_shader_bones; SetUniform(entity, kBoneTransformsUniform, data, dimension, count); } void RenderSystemNext::OnTextureLoaded(const RenderComponent& component, int unit, const TexturePtr& texture) { const Entity entity = component.GetEntity(); const mathfu::vec4 clamp_bounds = texture->CalculateClampBounds(); SetUniform(entity, kClampBoundsUniform, &clamp_bounds[0], 4, 1); if (factory_->IsTextureValid(texture)) { // TODO(b/38130323) Add CheckTextureSizeWarning that does not depend on HMD. auto* dispatcher_system = registry_->Get<DispatcherSystem>(); if (dispatcher_system) { dispatcher_system->Send(entity, TextureReadyEvent(entity, unit)); if (IsReadyToRenderImpl(component)) { dispatcher_system->Send(entity, ReadyToRenderEvent(entity)); } } } } void RenderSystemNext::SetTexture(Entity e, int unit, const TexturePtr& texture) { SetTexture(e, kDefaultRenderId, unit, texture); } void RenderSystemNext::SetTexture(Entity e, HashValue component_id, int unit, const TexturePtr& texture) { const EntityIdPair entity_id_pair(e, component_id); auto* render_component = components_.Get(entity_id_pair); if (!render_component) { return; } render_component->material.SetTexture(unit, texture); max_texture_unit_ = std::max(max_texture_unit_, unit); // Add subtexture coordinates so the vertex shaders will pick them up. These // are known when the texture is created; no need to wait for load. SetUniform(e, component_id, kTextureBoundsUniform, &texture->UvBounds()[0], 4, 1); if (texture->IsLoaded()) { OnTextureLoaded(*render_component, unit, texture); } else { texture->AddOnLoadCallback([this, unit, entity_id_pair, texture]() { RenderComponent* render_component = components_.Get(entity_id_pair); if (render_component && render_component->material.GetTexture(unit) == texture) { OnTextureLoaded(*render_component, unit, texture); } }); } } TexturePtr RenderSystemNext::CreateProcessedTexture( const TexturePtr& source_texture, bool create_mips, RenderSystem::TextureProcessor processor) { return factory_->CreateProcessedTexture(source_texture, create_mips, processor); } TexturePtr RenderSystemNext::CreateProcessedTexture( const TexturePtr& source_texture, bool create_mips, const RenderSystem::TextureProcessor& processor, const mathfu::vec2i& output_dimensions) { return factory_->CreateProcessedTexture(source_texture, create_mips, processor, output_dimensions); } void RenderSystemNext::SetTextureId(Entity e, int unit, uint32_t texture_target, uint32_t texture_id) { SetTextureId(e, kDefaultRenderId, unit, texture_target, texture_id); } void RenderSystemNext::SetTextureId(Entity e, HashValue component_id, int unit, uint32_t texture_target, uint32_t texture_id) { const EntityIdPair entity_id_pair(e, component_id); auto* render_component = components_.Get(entity_id_pair); if (!render_component) { return; } auto texture = factory_->CreateTexture(texture_target, texture_id); SetTexture(e, component_id, unit, texture); } TexturePtr RenderSystemNext::GetTexture(Entity entity, int unit) const { const auto* render_component = components_.Get(entity); if (!render_component) { return TexturePtr(); } return render_component->material.GetTexture(unit); } void RenderSystemNext::SetPano(Entity entity, const std::string& filename, float heading_offset_deg) { LOG(FATAL) << "Deprecated."; } void RenderSystemNext::SetText(Entity e, const std::string& text) { LOG(FATAL) << "Deprecated."; } void RenderSystemNext::SetFont(Entity entity, const FontPtr& font) { LOG(FATAL) << "Deprecated."; } void RenderSystemNext::SetTextSize(Entity entity, int size) { LOG(FATAL) << "Deprecated."; } const std::vector<LinkTag>* RenderSystemNext::GetLinkTags(Entity e) const { LOG(FATAL) << "Deprecated."; return nullptr; } const std::vector<mathfu::vec3>* RenderSystemNext::GetCaretPositions( Entity e) const { LOG(FATAL) << "Deprecated."; return nullptr; } bool RenderSystemNext::GetQuad(Entity e, Quad* quad) const { const auto* render_component = components_.Get(e); if (!render_component) { return false; } *quad = render_component->quad; return true; } void RenderSystemNext::SetQuad(Entity e, const Quad& quad) { SetQuad(e, kDefaultRenderId, quad); } void RenderSystemNext::SetQuad(Entity e, HashValue component_id, const Quad& quad) { const EntityIdPair entity_id_pair(e, component_id); auto* render_component = components_.Get(entity_id_pair); if (!render_component) { LOG(WARNING) << "Missing entity for SetQuad: " << entity_id_pair.entity << ", with id: " << entity_id_pair.id; return; } render_component->quad = quad; auto iter = deformations_.find(entity_id_pair); if (iter != deformations_.end()) { DeferredMesh defer; defer.entity_id_pair = entity_id_pair; defer.type = DeferredMesh::kQuad; defer.quad = quad; deferred_meshes_.push(std::move(defer)); } else { SetQuadImpl(e, component_id, quad); } } void RenderSystemNext::SetMesh(Entity e, const TriangleMesh<VertexPT>& mesh) { SetMesh(e, kDefaultRenderId, mesh); } void RenderSystemNext::SetMesh(Entity e, HashValue component_id, const TriangleMesh<VertexPT>& mesh) { SetMesh(e, component_id, factory_->CreateMesh(mesh)); } void RenderSystemNext::SetAndDeformMesh(Entity entity, const TriangleMesh<VertexPT>& mesh) { SetAndDeformMesh(entity, kDefaultRenderId, mesh); } void RenderSystemNext::SetAndDeformMesh(Entity entity, HashValue component_id, const TriangleMesh<VertexPT>& mesh) { const EntityIdPair entity_id_pair(entity, component_id); auto iter = deformations_.find(entity_id_pair); if (iter != deformations_.end()) { DeferredMesh defer; defer.entity_id_pair = entity_id_pair; defer.type = DeferredMesh::kMesh; defer.mesh.GetVertices() = mesh.GetVertices(); defer.mesh.GetIndices() = mesh.GetIndices(); deferred_meshes_.emplace(std::move(defer)); } else { SetMesh(entity, component_id, mesh); } } void RenderSystemNext::SetMesh(Entity e, const MeshData& mesh) { SetMesh(e, factory_->CreateMesh(mesh)); } void RenderSystemNext::SetMesh(Entity e, const std::string& file) { SetMesh(e, factory_->LoadMesh(file)); } RenderSystemNext::SortOrderOffset RenderSystemNext::GetSortOrderOffset( Entity entity) const { return sort_order_manager_.GetOffset(entity); } void RenderSystemNext::SetSortOrderOffset(Entity e, SortOrderOffset sort_order_offset) { SetSortOrderOffset(e, kDefaultRenderId, sort_order_offset); } void RenderSystemNext::SetSortOrderOffset(Entity e, HashValue component_id, SortOrderOffset sort_order_offset) { const EntityIdPair entity_id_pair(e, component_id); sort_order_manager_.SetOffset(entity_id_pair, sort_order_offset); sort_order_manager_.UpdateSortOrder(entity_id_pair, [this](EntityIdPair entity_id_pair) { return components_.Get(entity_id_pair); }); } bool RenderSystemNext::IsTextureSet(Entity e, int unit) const { auto* render_component = components_.Get(e); if (!render_component) { return false; } return render_component->material.GetTexture(unit) != nullptr; } bool RenderSystemNext::IsTextureLoaded(Entity e, int unit) const { const auto* render_component = components_.Get(e); if (!render_component) { return false; } if (!render_component->material.GetTexture(unit)) { return false; } return render_component->material.GetTexture(unit)->IsLoaded(); } bool RenderSystemNext::IsTextureLoaded(const TexturePtr& texture) const { return texture->IsLoaded(); } bool RenderSystemNext::IsReadyToRender(Entity entity) const { const auto* render_component = components_.Get(entity); if (!render_component) { // No component, no textures, no fonts, no problem. return true; } return IsReadyToRenderImpl(*render_component); } bool RenderSystemNext::IsReadyToRenderImpl( const RenderComponent& component) const { const auto& textures = component.material.GetTextures(); for (const auto& pair : textures) { const TexturePtr& texture = pair.second; if (!texture->IsLoaded() || !factory_->IsTextureValid(texture)) { return false; } } return true; } bool RenderSystemNext::IsHidden(Entity e) const { const auto* render_component = components_.Get(e); const bool render_component_hidden = render_component && render_component->hidden; // If there are no models associated with this entity, then it is hidden. // Otherwise, it is hidden if the RenderComponent is hidden. return (render_component_hidden || !render_component); } ShaderPtr RenderSystemNext::GetShader(Entity entity, HashValue component_id) const { const EntityIdPair entity_id_pair(entity, component_id); const RenderComponent* component = components_.Get(entity_id_pair); return component ? component->material.GetShader() : ShaderPtr(); } ShaderPtr RenderSystemNext::GetShader(Entity entity) const { const RenderComponent* component = components_.Get(entity); return component ? component->material.GetShader() : ShaderPtr(); } void RenderSystemNext::SetShader(Entity e, const ShaderPtr& shader) { SetShader(e, kDefaultRenderId, shader); } void RenderSystemNext::SetShader(Entity e, HashValue component_id, const ShaderPtr& shader) { const EntityIdPair entity_id_pair(e, component_id); auto* render_component = components_.Get(entity_id_pair); if (!render_component) { return; } render_component->material.SetShader(shader); // Update the uniforms' locations in the new shader. UpdateUniformLocations(render_component); } void RenderSystemNext::SetMesh(Entity e, MeshPtr mesh) { SetMesh(e, kDefaultRenderId, mesh); } void RenderSystemNext::SetMesh(Entity e, HashValue component_id, const MeshPtr& mesh) { const EntityIdPair entity_id_pair(e, component_id); auto* render_component = components_.Get(entity_id_pair); if (!render_component) { LOG(WARNING) << "Missing RenderComponent, " << "skipping mesh update for entity: " << e << ", with id: " << component_id; return; } render_component->mesh = std::move(mesh); if (render_component->mesh) { auto& transform_system = *registry_->Get<TransformSystem>(); transform_system.SetAabb(e, render_component->mesh->GetAabb()); const int num_shader_bones = render_component->mesh->GetNumShaderBones(); if (num_shader_bones > 0) { const mathfu::AffineTransform identity = mathfu::mat4::ToAffineTransform(mathfu::mat4::Identity()); shader_transforms_.clear(); shader_transforms_.resize(num_shader_bones, identity); const float* data = &(shader_transforms_[0][0]); const int dimension = 4; const int count = kNumVec4sInAffineTransform * num_shader_bones; SetUniform(e, component_id, kBoneTransformsUniform, data, dimension, count); } } } MeshPtr RenderSystemNext::GetMesh(Entity e, HashValue component_id) { const EntityIdPair entity_id_pair(e, component_id); auto* render_component = components_.Get(entity_id_pair); if (!render_component) { LOG(WARNING) << "Missing RenderComponent for entity: " << e << ", with id: " << component_id; return nullptr; } return render_component->mesh; } template <typename Vertex> void RenderSystemNext::DeformMesh(Entity entity, HashValue component_id, TriangleMesh<Vertex>* mesh) { const EntityIdPair entity_id_pair(entity, component_id); auto iter = deformations_.find(entity_id_pair); const Deformation deform = iter != deformations_.end() ? iter->second : nullptr; if (deform) { // TODO(b/28313614) Use TriangleMesh::ApplyDeformation. if (sizeof(Vertex) % sizeof(float) == 0) { const int stride = static_cast<int>(sizeof(Vertex) / sizeof(float)); std::vector<Vertex>& vertices = mesh->GetVertices(); deform(reinterpret_cast<float*>(vertices.data()), vertices.size() * stride, stride); } else { LOG(ERROR) << "Tried to deform an unsupported vertex format."; } } } template <typename Vertex> MeshPtr RenderSystemNext::CreateQuad(Entity e, HashValue component_id, const Quad& quad) { if (quad.size.x == 0 || quad.size.y == 0) { return nullptr; } TriangleMesh<Vertex> mesh; mesh.SetQuad(quad.size.x, quad.size.y, quad.verts.x, quad.verts.y, quad.corner_radius, quad.corner_verts, quad.corner_mask); DeformMesh<Vertex>(e, component_id, &mesh); if (quad.id != 0) { return factory_->CreateMesh(quad.id, mesh); } else { return factory_->CreateMesh(mesh); } } void RenderSystemNext::SetStencilMode(Entity e, StencilMode mode, int value) { SetStencilMode(e, kDefaultRenderId, mode, value); } void RenderSystemNext::SetStencilMode(Entity e, HashValue component_id, StencilMode mode, int value) { const EntityIdPair entity_id_pair(e, component_id); auto* render_component = components_.Get(entity_id_pair); if (!render_component || render_component->stencil_mode == mode) { return; } render_component->stencil_mode = mode; render_component->stencil_value = value; } void RenderSystemNext::SetDeformationFunction(Entity e, const Deformation& deform) { if (deform) { deformations_.emplace(e, deform); } else { deformations_.erase(e); } } void RenderSystemNext::Hide(Entity e) { auto* render_component = components_.Get(e); if (render_component && !render_component->hidden) { render_component->hidden = true; SendEvent(registry_, e, HiddenEvent(e)); } } void RenderSystemNext::Show(Entity e) { auto* render_component = components_.Get(e); if (render_component && render_component->hidden) { render_component->hidden = false; SendEvent(registry_, e, UnhiddenEvent(e)); } } HashValue RenderSystemNext::GetRenderPass(Entity entity) const { const RenderComponent* component = components_.Get(entity); return component ? component->pass : 0; } void RenderSystemNext::SetRenderPass(Entity e, HashValue pass) { RenderComponent* render_component = components_.Get(e); if (render_component) { render_component->pass = pass; } } RenderSystem::SortMode RenderSystemNext::GetSortMode(HashValue pass) const { const auto it = pass_definitions_.find(pass); return (it != pass_definitions_.cend()) ? it->second.sort_mode : SortMode::kNone; } void RenderSystemNext::SetSortMode(HashValue pass, SortMode mode) { pass_definitions_[pass].sort_mode = mode; } RenderSystem::CullMode RenderSystemNext::GetCullMode(HashValue pass) { const auto it = pass_definitions_.find(pass); return (it != pass_definitions_.cend()) ? it->second.cull_mode : CullMode::kNone; } void RenderSystemNext::SetCullMode(HashValue pass, CullMode mode) { pass_definitions_[pass].cull_mode = mode; } void RenderSystemNext::SetRenderState(HashValue pass, const fplbase::RenderState& state) { pass_definitions_[pass].render_state = state; } const fplbase::RenderState* RenderSystemNext::GetRenderState( HashValue pass) const { const auto& it = pass_definitions_.find(pass); if (it == pass_definitions_.end()) { return nullptr; } return &it->second.render_state; } void RenderSystemNext::SetDepthTest(const bool enabled) { if (enabled) { #if !ION_PRODUCTION // GL_DEPTH_BITS was deprecated in desktop GL 3.3, so make sure this get // succeeds before checking depth_bits. GLint depth_bits = 0; glGetIntegerv(GL_DEPTH_BITS, &depth_bits); if (glGetError() == 0 && depth_bits == 0) { // This has been known to cause problems on iOS 10. LOG_ONCE(WARNING) << "Enabling depth test without a depth buffer; this " "has known issues on some platforms."; } #endif // !ION_PRODUCTION renderer_.SetDepthFunction(fplbase::kDepthFunctionLess); return; } renderer_.SetDepthFunction(fplbase::kDepthFunctionDisabled); } void RenderSystemNext::SetDepthWrite(const bool enabled) { renderer_.SetDepthWrite(enabled); } void RenderSystemNext::SetViewport(const View& view) { LULLABY_CPU_TRACE_CALL(); renderer_.SetViewport(fplbase::Viewport(view.viewport, view.dimensions)); } void RenderSystemNext::SetClipFromModelMatrix(const mathfu::mat4& mvp) { renderer_.set_model_view_projection(mvp); } void RenderSystemNext::BindStencilMode(StencilMode mode, int ref) { // Stencil mask setting all the bits to be 1. static const fplbase::StencilMask kStencilMaskAllBits = ~0; switch (mode) { case StencilMode::kDisabled: renderer_.SetStencilMode(fplbase::kStencilDisabled, ref, kStencilMaskAllBits); break; case StencilMode::kTest: renderer_.SetStencilMode(fplbase::kStencilCompareEqual, ref, kStencilMaskAllBits); break; case StencilMode::kWrite: renderer_.SetStencilMode(fplbase::kStencilWrite, ref, kStencilMaskAllBits); break; } } void RenderSystemNext::BindVertexArray(uint32_t ref) { // VAOs are part of the GLES3 & GL3 specs. if (renderer_.feature_level() == fplbase::kFeatureLevel30) { #if GL_ES_VERSION_3_0 || defined(GL_VERSION_3_0) GL_CALL(glBindVertexArray(ref)); #endif return; } // VAOs were available prior to GLES3 using an extension. #if GL_OES_vertex_array_object #ifndef GL_GLEXT_PROTOTYPES static PFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES = []() { return (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress( "glBindVertexArrayOES"); }; if (glBindVertexArrayOES) { GL_CALL(glBindVertexArrayOES(ref)); } #else // GL_GLEXT_PROTOTYPES GL_CALL(glBindVertexArrayOES(ref)); #endif // !GL_GLEXT_PROTOTYPES #endif // GL_OES_vertex_array_object } void RenderSystemNext::ClearSamplers() { if (renderer_.feature_level() != fplbase::kFeatureLevel30) { return; } // Samplers are part of GLES3 & GL3.3 specs. #if GL_ES_VERSION_3_0 || defined(GL_VERSION_3_3) for (int i = 0; i <= max_texture_unit_; ++i) { // Confusingly, glBindSampler takes an index, not the raw texture unit // (GL_TEXTURE0 + index). GL_CALL(glBindSampler(i, 0)); } #endif // GL_ES_VERSION_3_0 || GL_VERSION_3_3 } void RenderSystemNext::ResetState() { const fplbase::RenderState& render_state = renderer_.GetRenderState(); // Clear render state. SetBlendMode(fplbase::kBlendModeOff); renderer_.SetCulling(fplbase::kCullingModeBack); SetDepthTest(true); GL_CALL(glEnable(GL_DEPTH_TEST)); renderer_.ScissorOff(); GL_CALL(glDisable(GL_STENCIL_TEST)); GL_CALL(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE)); GL_CALL( glDepthMask(render_state.depth_state.write_enabled ? GL_TRUE : GL_FALSE)); GL_CALL(glStencilMask(~0)); GL_CALL(glFrontFace(GL_CCW)); GL_CALL(glPolygonOffset(0, 0)); // Clear sampler objects, since FPL doesn't use them. ClearSamplers(); // Clear VAO since it overrides VBOs. BindVertexArray(0); // Clear attributes, though we can leave position. GL_CALL(glDisableVertexAttribArray(fplbase::Mesh::kAttributeNormal)); GL_CALL(glDisableVertexAttribArray(fplbase::Mesh::kAttributeTangent)); GL_CALL(glDisableVertexAttribArray(fplbase::Mesh::kAttributeTexCoord)); GL_CALL(glDisableVertexAttribArray(fplbase::Mesh::kAttributeTexCoordAlt)); GL_CALL(glDisableVertexAttribArray(fplbase::Mesh::kAttributeColor)); GL_CALL(glDisableVertexAttribArray(fplbase::Mesh::kAttributeBoneIndices)); GL_CALL(glDisableVertexAttribArray(fplbase::Mesh::kAttributeBoneWeights)); shader_.reset(); } void RenderSystemNext::SetBlendMode(fplbase::BlendMode blend_mode) { renderer_.SetBlendMode(blend_mode); blend_mode_ = blend_mode; } mathfu::vec4 RenderSystemNext::GetClearColor() const { return clear_color_; } void RenderSystemNext::SetClearColor(float r, float g, float b, float a) { clear_color_ = mathfu::vec4(r, g, b, a); } void RenderSystemNext::SubmitRenderData() { RenderData* data = render_data_buffer_.LockWriteBuffer(); if (!data) { return; } data->clear(); const auto* transform_system = registry_->Get<TransformSystem>(); components_.ForEach([&](RenderComponent& render_component) { if (render_component.hidden) { return; } if (render_component.pass == 0) { return; } const Entity entity = render_component.GetEntity(); if (entity == kNullEntity) { return; } const mathfu::mat4* world_from_entity_matrix = transform_system->GetWorldFromEntityMatrix(entity); if (world_from_entity_matrix == nullptr || !transform_system->IsEnabled(entity)) { return; } RenderObject render_obj; render_obj.mesh = render_component.mesh; render_obj.material = render_component.material; render_obj.sort_order = render_component.sort_order; render_obj.stencil_mode = render_component.stencil_mode; render_obj.stencil_value = render_component.stencil_value; render_obj.world_from_entity_matrix = *world_from_entity_matrix; RenderPassAndObjects& entry = (*data)[render_component.pass]; entry.render_objects.emplace_back(std::move(render_obj)); }); for (auto& iter : *data) { const RenderPassDefinition& pass = pass_definitions_[iter.first]; iter.second.pass_definition = pass; // Sort only objects with "static" sort order, such as explicit sort order // or absolute z-position. if (IsSortModeViewIndependent(pass.sort_mode)) { SortObjects(&iter.second.render_objects, pass.sort_mode); } } render_data_buffer_.UnlockWriteBuffer(); } void RenderSystemNext::BeginRendering() { LULLABY_CPU_TRACE_CALL(); GL_CALL(glClearColor(clear_color_.x, clear_color_.y, clear_color_.z, clear_color_.w)); GL_CALL(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)); // Retrieve the (current) default frame buffer. glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &default_frame_buffer_); active_render_data_ = render_data_buffer_.LockReadBuffer(); } void RenderSystemNext::EndRendering() { GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, 0)); GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)); render_data_buffer_.UnlockReadBuffer(); active_render_data_ = nullptr; default_frame_buffer_ = 0; } void RenderSystemNext::SetViewUniforms(const View& view) { renderer_.set_camera_pos(view.world_from_eye_matrix.TranslationVector3D()); rendering_right_eye_ = view.eye == 1; } void RenderSystemNext::RenderAt(const RenderObject* component, const mathfu::mat4& world_from_entity_matrix, const View& view) { LULLABY_CPU_TRACE_CALL(); const ShaderPtr& shader = component->material.GetShader(); if (!shader || !component->mesh) { return; } const mathfu::mat4 clip_from_entity_matrix = view.clip_from_world_matrix * world_from_entity_matrix; renderer_.set_model_view_projection(clip_from_entity_matrix); renderer_.set_model(world_from_entity_matrix); BindShader(shader); SetShaderUniforms(component->material.GetUniforms()); const Shader::UniformHnd mat_normal_uniform_handle = shader->FindUniform("mat_normal"); if (fplbase::ValidUniformHandle(mat_normal_uniform_handle)) { const int uniform_gl = fplbase::GlUniformHandle(mat_normal_uniform_handle); // Compute the normal matrix. This is the transposed matrix of the inversed // world position. This is done to avoid non-uniform scaling of the normal. // A good explanation of this can be found here: // http://www.lighthouse3d.com/tutorials/glsl-12-tutorial/the-normal-matrix/ const mathfu::mat3 normal_matrix = ComputeNormalMatrix(world_from_entity_matrix); mathfu::vec3_packed packed[3]; normal_matrix.Pack(packed); GL_CALL(glUniformMatrix3fv(uniform_gl, 1, false, packed[0].data)); } const Shader::UniformHnd camera_dir_handle = shader->FindUniform("camera_dir"); if (fplbase::ValidUniformHandle(camera_dir_handle)) { const int uniform_gl = fplbase::GlUniformHandle(camera_dir_handle); mathfu::vec3_packed camera_dir; CalculateCameraDirection(view.world_from_eye_matrix).Pack(&camera_dir); GL_CALL(glUniform3fv(uniform_gl, 1, camera_dir.data)); } const auto& textures = component->material.GetTextures(); for (const auto& texture : textures) { texture.second->Bind(texture.first); } // Bit of magic to determine if the scalar is negative and if so flip the cull // face. This possibly be revised (b/38235916). CorrectFrontFaceFromMatrix(world_from_entity_matrix); BindStencilMode(component->stencil_mode, component->stencil_value); DrawMeshFromComponent(component); } void RenderSystemNext::RenderAtMultiview( const RenderObject* component, const mathfu::mat4& world_from_entity_matrix, const View* views) { LULLABY_CPU_TRACE_CALL(); const ShaderPtr& shader = component->material.GetShader(); if (!shader || !component->mesh) { return; } const mathfu::mat4 clip_from_entity_matrix[] = { views[0].clip_from_world_matrix * world_from_entity_matrix, views[1].clip_from_world_matrix * world_from_entity_matrix, }; renderer_.set_model(world_from_entity_matrix); BindShader(shader); SetShaderUniforms(component->material.GetUniforms()); const Shader::UniformHnd mvp_uniform_handle = shader->FindUniform("model_view_projection"); if (fplbase::ValidUniformHandle(mvp_uniform_handle)) { const int uniform_gl = fplbase::GlUniformHandle(mvp_uniform_handle); GL_CALL(glUniformMatrix4fv(uniform_gl, 2, false, &(clip_from_entity_matrix[0][0]))); } const Shader::UniformHnd mat_normal_uniform_handle = shader->FindUniform("mat_normal"); if (fplbase::ValidUniformHandle(mat_normal_uniform_handle)) { const int uniform_gl = fplbase::GlUniformHandle(mat_normal_uniform_handle); const mathfu::mat3 normal_matrix = ComputeNormalMatrix(world_from_entity_matrix); mathfu::VectorPacked<float, 3> packed[3]; normal_matrix.Pack(packed); GL_CALL(glUniformMatrix3fv(uniform_gl, 1, false, packed[0].data)); } const Shader::UniformHnd camera_dir_handle = shader->FindUniform("camera_dir"); if (fplbase::ValidUniformHandle(camera_dir_handle)) { const int uniform_gl = fplbase::GlUniformHandle(camera_dir_handle); mathfu::vec3_packed camera_dir[2]; for (size_t i = 0; i < 2; ++i) { CalculateCameraDirection(views[i].world_from_eye_matrix) .Pack(&camera_dir[i]); } GL_CALL(glUniform3fv(uniform_gl, 2, camera_dir[0].data)); } const auto& textures = component->material.GetTextures(); for (const auto& texture : textures) { texture.second->Bind(texture.first); } // Bit of magic to determine if the scalar is negative and if so flip the cull // face. This possibly be revised (b/38235916). CorrectFrontFaceFromMatrix(world_from_entity_matrix); BindStencilMode(component->stencil_mode, component->stencil_value); DrawMeshFromComponent(component); } void RenderSystemNext::SetShaderUniforms(const UniformVector& uniforms) { for (const auto& uniform : uniforms) { BindUniform(uniform); } } void RenderSystemNext::DrawMeshFromComponent(const RenderObject* component) { if (component->mesh) { component->mesh->Render(&renderer_); detail::Profiler* profiler = registry_->Get<detail::Profiler>(); if (profiler) { profiler->RecordDraw(component->material.GetShader(), component->mesh->GetNumVertices(), component->mesh->GetNumTriangles()); } } } void RenderSystemNext::RenderPanos(const View* views, size_t num_views) { LOG(FATAL) << "Deprecated."; } void RenderSystemNext::Render(const View* views, size_t num_views) { renderer_.BeginRendering(); ResetState(); known_state_ = true; // assume a max of 2 views, one for each eye. RenderView pano_views[2]; CHECK_LE(num_views, 2); GenerateEyeCenteredViews({views, num_views}, pano_views); Render(pano_views, num_views, ConstHash("Pano")); Render(views, num_views, ConstHash("Opaque")); Render(views, num_views, ConstHash("Main")); Render(views, num_views, ConstHash("OverDraw")); Render(views, num_views, ConstHash("OverDrawGlow")); known_state_ = false; renderer_.EndRendering(); } void RenderSystemNext::Render(const View* views, size_t num_views, HashValue pass) { LULLABY_CPU_TRACE_CALL(); if (!active_render_data_) { LOG(DFATAL) << "Render between BeginRendering() and EndRendering()!"; return; } auto iter = active_render_data_->find(pass); if (iter == active_render_data_->end()) { // No data associated with this pass. return; } if (iter->second.render_objects.empty()) { // No objects to render with this pass. return; } if (!known_state_) { renderer_.BeginRendering(); if (pass != 0) { ResetState(); } } bool reset_state = true; auto* config = registry_->Get<Config>(); if (config) { static const HashValue kRenderResetStateHash = Hash("lull.Render.ResetState"); reset_state = config->Get(kRenderResetStateHash, reset_state); } const RenderPassDefinition& pass_definition = iter->second.pass_definition; // Set the render target, if needed. if (pass_definition.render_target) { pass_definition.render_target->SetAsRenderTarget(); } // Prepare the pass. renderer_.SetRenderState(pass_definition.render_state); cached_render_state_ = pass_definition.render_state; // Draw the elements. if (pass == ConstHash("Debug")) { RenderDebugStats(views, num_views); } else { RenderObjectList& objects = iter->second.render_objects; if (!IsSortModeViewIndependent(pass_definition.sort_mode)) { SortObjectsUsingView(&objects, pass_definition.sort_mode, views, num_views); } RenderObjects(objects, views, num_views); } // Set the render target back to default, if needed. if (pass_definition.render_target) { GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, default_frame_buffer_)); } if (reset_state) { static const fplbase::RenderState kDefaultRenderState; renderer_.SetRenderState(kDefaultRenderState); } if (!known_state_) { renderer_.EndRendering(); } } void RenderSystemNext::RenderObjects(const std::vector<RenderObject>& objects, const View* views, size_t num_views) { if (objects.empty()) { return; } if (multiview_enabled_) { SetViewport(views[0]); SetViewUniforms(views[0]); for (const RenderObject& obj : objects) { RenderAtMultiview(&obj, obj.world_from_entity_matrix, views); } } else { for (size_t i = 0; i < num_views; ++i) { const View& view = views[i]; SetViewport(view); SetViewUniforms(view); for (const RenderObject& obj : objects) { RenderAt(&obj, obj.world_from_entity_matrix, views[i]); } } } // Reset states that are set at the entity level in RenderAt. BindStencilMode(StencilMode::kDisabled, 0); GL_CALL(glFrontFace(GL_CCW)); } void RenderSystemNext::BindShader(const ShaderPtr& shader) { // Don't early exit if shader == shader_, since fplbase::Shader::Set also sets // the common fpl uniforms. shader_ = shader; shader->Bind(); // Bind uniform describing whether or not we're rendering in the right eye. // This uniform is an int due to legacy reasons, but there's no pipeline in // FPL for setting int uniforms, so we have to make a direct gl call instead. fplbase::UniformHandle uniform_is_right_eye = shader->FindUniform(kIsRightEyeUniform); if (fplbase::ValidUniformHandle(uniform_is_right_eye)) { GL_CALL(glUniform1i(fplbase::GlUniformHandle(uniform_is_right_eye), static_cast<int>(rendering_right_eye_))); } } void RenderSystemNext::BindTexture(int unit, const TexturePtr& texture) { texture->Bind(unit); } void RenderSystemNext::BindUniform(const char* name, const float* data, int dimension) { if (!IsSupportedUniformDimension(dimension)) { LOG(DFATAL) << "Unsupported uniform dimension " << dimension; return; } if (!shader_) { LOG(DFATAL) << "Cannot bind uniform on unbound shader!"; return; } const fplbase::UniformHandle location = shader_->FindUniform(name); if (fplbase::ValidUniformHandle(location)) { shader_->SetUniform(location, data, dimension); } } void RenderSystemNext::DrawPrimitives(PrimitiveType type, const VertexFormat& format, const void* vertex_data, size_t num_vertices) { const fplbase::Mesh::Primitive fpl_type = Mesh::GetFplPrimitiveType(type); fplbase::Attribute attributes[Mesh::kMaxFplAttributeArraySize]; Mesh::GetFplAttributes(format, attributes); fplbase::RenderArray(fpl_type, static_cast<int>(num_vertices), attributes, static_cast<int>(format.GetVertexSize()), vertex_data); } void RenderSystemNext::DrawIndexedPrimitives( PrimitiveType type, const VertexFormat& format, const void* vertex_data, size_t num_vertices, const uint16_t* indices, size_t num_indices) { const fplbase::Mesh::Primitive fpl_type = Mesh::GetFplPrimitiveType(type); fplbase::Attribute attributes[Mesh::kMaxFplAttributeArraySize]; Mesh::GetFplAttributes(format, attributes); fplbase::RenderArray(fpl_type, static_cast<int>(num_indices), attributes, static_cast<int>(format.GetVertexSize()), vertex_data, indices); } void RenderSystemNext::UpdateDynamicMesh( Entity entity, PrimitiveType primitive_type, const VertexFormat& vertex_format, const size_t max_vertices, const size_t max_indices, const std::function<void(MeshData*)>& update_mesh) { RenderComponent* component = components_.Get(entity); if (!component) { return; } if (max_vertices > 0) { DataContainer vertex_data = DataContainer::CreateHeapDataContainer( max_vertices * vertex_format.GetVertexSize()); DataContainer index_data = DataContainer::CreateHeapDataContainer( max_indices * sizeof(MeshData::Index)); MeshData data(primitive_type, vertex_format, std::move(vertex_data), std::move(index_data)); update_mesh(&data); component->mesh = factory_->CreateMesh(data); } else { component->mesh.reset(); } } void RenderSystemNext::RenderDebugStats(const View* views, size_t num_views) { RenderStats* render_stats = registry_->Get<RenderStats>(); if (!render_stats || num_views == 0) { return; } const bool stats_enabled = render_stats->IsLayerEnabled(RenderStats::Layer::kRenderStats); const bool fps_counter = render_stats->IsLayerEnabled(RenderStats::Layer::kFpsCounter); if (!stats_enabled && !fps_counter) { return; } SimpleFont* font = render_stats->GetFont(); if (!font || !font->GetShader()) { return; } // Calculate the position and size of the text from the projection matrix. const bool is_perspective = views[0].clip_from_eye_matrix[15] == 0.0f; const bool is_stereo = (num_views == 2 && is_perspective && views[1].clip_from_eye_matrix[15] == 0.0f); mathfu::vec3 start_pos; float font_size; // TODO(b/29914331) Separate, tested matrix decomposition util functions. if (is_perspective) { const float kTopOfTextScreenScale = .45f; const float kFontScreenScale = .075f; const float z = -1.0f; const float tan_half_fov = 1.0f / views[0].clip_from_eye_matrix[5]; font_size = .5f * kFontScreenScale * -z * tan_half_fov; start_pos = mathfu::vec3(-.5f, kTopOfTextScreenScale * -z * tan_half_fov, z); } else { const float kNearPlaneOffset = .0001f; const float bottom = (-1.0f - views[0].clip_from_eye_matrix[13]) / views[0].clip_from_eye_matrix[5]; const float top = bottom + 2.0f / views[0].clip_from_eye_matrix[5]; const float near_z = (1.0f + views[0].clip_from_eye_matrix[14]) / views[0].clip_from_eye_matrix[10]; const int padding = 20; font_size = 16; start_pos = mathfu::vec3(padding, top - padding, -(near_z - kNearPlaneOffset)); } // Setup shared render state. font->GetTexture()->Bind(0); font->SetSize(font_size); const float uv_bounds[4] = {0, 0, 1, 1}; SetDebugUniform(font->GetShader().get(), kTextureBoundsUniform, uv_bounds); const float color[4] = {1, 1, 1, 1}; SetDebugUniform(font->GetShader().get(), kColorUniform, color); SetDepthTest(false); SetDepthWrite(false); char buf[512] = ""; // Draw in each view. for (size_t i = 0; i < num_views; ++i) { SetViewport(views[i]); SetViewUniforms(views[i]); renderer_.set_model_view_projection(views[i].clip_from_eye_matrix); BindShader( font->GetShader()); // Shader needs to be bound after setting MVP. mathfu::vec3 pos = start_pos; if (is_stereo && i > 0) { // Reposition text so that it's consistently placed in both eye views. pos = views[i].world_from_eye_matrix.Inverse() * (views[0].world_from_eye_matrix * start_pos); } SimpleFontRenderer text(font); text.SetCursor(pos); // Draw basic render stats. const detail::Profiler* profiler = registry_->Get<detail::Profiler>(); if (profiler && stats_enabled) { snprintf(buf, sizeof(buf), "FPS %0.2f\n" "CPU ms %0.2f\n" "GPU ms %0.2f\n" "# draws %d\n" "# shader swaps %d\n" "# verts %d\n" "# tris %d", profiler->GetFilteredFps(), profiler->GetCpuFrameMs(), profiler->GetGpuFrameMs(), profiler->GetNumDraws(), profiler->GetNumShaderSwaps(), profiler->GetNumVerts(), profiler->GetNumTris()); text.Print(buf); } else if (profiler) { DCHECK(fps_counter); snprintf(buf, sizeof(buf), "FPS %0.2f\n", profiler->GetFilteredFps()); text.Print(buf); } if (!text.GetMesh().IsEmpty()) { const TriangleMesh<VertexPT>& mesh = text.GetMesh(); auto vertices = mesh.GetVertices(); auto indices = mesh.GetIndices(); DrawIndexedPrimitives(MeshData::PrimitiveType::kTriangles, VertexPT::kFormat, vertices.data(), vertices.size(), indices.data(), indices.size()); } } // Cleanup render state. SetDepthTest(true); SetDepthWrite(true); } void RenderSystemNext::OnParentChanged(const ParentChangedEvent& event) { sort_order_manager_.UpdateSortOrder( event.target, [this](EntityIdPair entity) { return components_.Get(entity); }); } const fplbase::RenderState& RenderSystemNext::GetRenderState() const { return renderer_.GetRenderState(); } void RenderSystemNext::UpdateCachedRenderState( const fplbase::RenderState& render_state) { renderer_.UpdateCachedRenderState(render_state); } bool RenderSystemNext::IsSortModeViewIndependent(SortMode mode) { switch (mode) { case SortMode::kAverageSpaceOriginBackToFront: case SortMode::kAverageSpaceOriginFrontToBack: return false; default: return true; } } void RenderSystemNext::SortObjects(RenderObjectList* objects, SortMode mode) { switch (mode) { case SortMode::kNone: // Do nothing. break; case SortMode::kSortOrderDecreasing: std::sort(objects->begin(), objects->end(), [](const RenderObject& a, const RenderObject& b) { return a.sort_order > b.sort_order; }); break; case SortMode::kSortOrderIncreasing: std::sort(objects->begin(), objects->end(), [](const RenderObject& a, const RenderObject& b) { return a.sort_order < b.sort_order; }); break; case SortMode::kWorldSpaceZBackToFront: std::sort(objects->begin(), objects->end(), [](const RenderObject& a, const RenderObject& b) { return a.world_from_entity_matrix.TranslationVector3D().z < b.world_from_entity_matrix.TranslationVector3D().z; }); break; case SortMode::kWorldSpaceZFrontToBack: std::sort(objects->begin(), objects->end(), [](const RenderObject& a, const RenderObject& b) { return a.world_from_entity_matrix.TranslationVector3D().z > b.world_from_entity_matrix.TranslationVector3D().z; }); break; default: LOG(DFATAL) << "SortObjects called with unsupported sort mode!"; break; } } void RenderSystemNext::SortObjectsUsingView(RenderObjectList* objects, SortMode mode, const View* views, size_t num_views) { // Get the average camera position. if (num_views <= 0) { LOG(DFATAL) << "Must have at least 1 view."; return; } mathfu::vec3 avg_pos = mathfu::kZeros3f; mathfu::vec3 avg_z(0, 0, 0); for (size_t i = 0; i < num_views; ++i) { avg_pos += views[i].world_from_eye_matrix.TranslationVector3D(); avg_z += GetMatrixColumn3D(views[i].world_from_eye_matrix, 2); } avg_pos /= static_cast<float>(num_views); avg_z.Normalize(); // Give relative values to the elements. for (RenderObject& obj : *objects) { const mathfu::vec3 world_pos = obj.world_from_entity_matrix.TranslationVector3D(); obj.z_sort_order = mathfu::vec3::DotProduct(world_pos - avg_pos, avg_z); } switch (mode) { case SortMode::kAverageSpaceOriginBackToFront: std::sort(objects->begin(), objects->end(), [&](const RenderObject& a, const RenderObject& b) { return a.z_sort_order < b.z_sort_order; }); break; case SortMode::kAverageSpaceOriginFrontToBack: std::sort(objects->begin(), objects->end(), [&](const RenderObject& a, const RenderObject& b) { return a.z_sort_order > b.z_sort_order; }); break; default: LOG(DFATAL) << "SortObjectsUsingView called with unsupported sort mode!"; break; } } void RenderSystemNext::InitDefaultRenderPasses() { fplbase::RenderState render_state; // RenderPass_Pano. Premultiplied alpha blend state, everything else default. render_state.blend_state.enabled = true; render_state.blend_state.src_alpha = fplbase::BlendState::kOne; render_state.blend_state.src_color = fplbase::BlendState::kOne; render_state.blend_state.dst_alpha = fplbase::BlendState::kOneMinusSrcAlpha; render_state.blend_state.dst_color = fplbase::BlendState::kOneMinusSrcAlpha; SetRenderState(ConstHash("Pano"), render_state); // RenderPass_Opaque. Depth test and write on. BlendMode disabled, face cull // mode back. render_state.blend_state.enabled = false; render_state.depth_state.test_enabled = true; render_state.depth_state.write_enabled = true; render_state.depth_state.function = fplbase::kRenderLessEqual; render_state.cull_state.enabled = true; render_state.cull_state.face = fplbase::CullState::kBack; SetRenderState(ConstHash("Opaque"), render_state); // RenderPass_Main. Depth test on, write off. Premultiplied alpha blend state, // face cull mode back. render_state.blend_state.enabled = true; render_state.blend_state.src_alpha = fplbase::BlendState::kOne; render_state.blend_state.src_color = fplbase::BlendState::kOne; render_state.blend_state.dst_alpha = fplbase::BlendState::kOneMinusSrcAlpha; render_state.blend_state.dst_color = fplbase::BlendState::kOneMinusSrcAlpha; render_state.depth_state.test_enabled = true; render_state.depth_state.function = fplbase::kRenderLessEqual; render_state.depth_state.write_enabled = false; render_state.cull_state.enabled = true; render_state.cull_state.face = fplbase::CullState::kBack; SetRenderState(ConstHash("Main"), render_state); // RenderPass_OverDraw. Depth test and write false, premultiplied alpha, back // face culling. render_state.depth_state.test_enabled = false; render_state.depth_state.write_enabled = false; render_state.blend_state.enabled = true; render_state.blend_state.src_alpha = fplbase::BlendState::kOne; render_state.blend_state.src_color = fplbase::BlendState::kOne; render_state.blend_state.dst_alpha = fplbase::BlendState::kOneMinusSrcAlpha; render_state.blend_state.dst_color = fplbase::BlendState::kOneMinusSrcAlpha; render_state.cull_state.enabled = true; render_state.cull_state.face = fplbase::CullState::kBack; SetRenderState(ConstHash("OverDraw"), render_state); // RenderPass_OverDrawGlow. Depth test and write off, additive blend mode, no // face culling. render_state.depth_state.test_enabled = false; render_state.depth_state.write_enabled = false; render_state.blend_state.enabled = true; render_state.blend_state.src_alpha = fplbase::BlendState::kOne; render_state.blend_state.src_color = fplbase::BlendState::kOne; render_state.blend_state.dst_alpha = fplbase::BlendState::kOne; render_state.blend_state.dst_color = fplbase::BlendState::kOne; render_state.cull_state.enabled = false; SetRenderState(ConstHash("OverDrawGlow"), render_state); SetSortMode(ConstHash("Opaque"), SortMode::kAverageSpaceOriginFrontToBack); SetSortMode(ConstHash("Main"), SortMode::kSortOrderIncreasing); } void RenderSystemNext::SetRenderPass(const RenderPassDefT& data) { const HashValue pass = Hash(data.name.c_str()); RenderPassDefinition& def = pass_definitions_[pass]; switch (data.sort_mode) { case SortMode_None: break; case SortMode_SortOrderDecreasing: def.sort_mode = SortMode::kSortOrderDecreasing; break; case SortMode_SortOrderIncreasing: def.sort_mode = SortMode::kSortOrderIncreasing; break; case SortMode_WorldSpaceZBackToFront: def.sort_mode = SortMode::kWorldSpaceZBackToFront; break; case SortMode_WorldSpaceZFrontToBack: def.sort_mode = SortMode::kWorldSpaceZFrontToBack; break; case SortMode_AverageSpaceOriginBackToFront: def.sort_mode = SortMode::kAverageSpaceOriginBackToFront; break; case SortMode_AverageSpaceOriginFrontToBack: def.sort_mode = SortMode::kAverageSpaceOriginFrontToBack; break; case SortMode_Optimized: break; } Apply(&def.render_state, data.render_state); } void RenderSystemNext::CreateRenderTarget( HashValue render_target_name, const mathfu::vec2i& dimensions, TextureFormat texture_format, DepthStencilFormat depth_stencil_format) { DCHECK_EQ(render_targets_.count(render_target_name), 0); // Create the render target. auto render_target = MakeUnique<fplbase::RenderTarget>(); render_target->Initialize(dimensions, RenderTargetTextureFormatToFpl(texture_format), DepthStencilFormatToFpl(depth_stencil_format)); // Create a bindable texture. TexturePtr texture = factory_->CreateTexture( GL_TEXTURE_2D, fplbase::GlTextureHandle(render_target->GetTextureId())); factory_->CacheTexture(render_target_name, texture); // Store the render target. render_targets_[render_target_name] = std::move(render_target); } void RenderSystemNext::SetRenderTarget(HashValue pass, HashValue render_target_name) { auto iter = render_targets_.find(render_target_name); if (iter == render_targets_.end()) { LOG(FATAL) << "SetRenderTarget called with non-existent render target: " << render_target_name; return; } pass_definitions_[pass].render_target = iter->second.get(); } void RenderSystemNext::CorrectFrontFaceFromMatrix(const mathfu::mat4& matrix) { if (CalculateDeterminant3x3(matrix) >= 0.0f) { // If the scalar is positive, match the default settings. renderer_.SetFrontFace(cached_render_state_.cull_state.front); } else { // Otherwise, reverse the order. renderer_.SetFrontFace(static_cast<fplbase::CullState::FrontFace>( fplbase::CullState::kFrontFaceCount - cached_render_state_.cull_state.front - 1)); } } void RenderSystemNext::BindUniform(const Uniform& uniform) { const Uniform::Description& desc = uniform.GetDescription(); int binding = 0; if (desc.binding >= 0) { binding = desc.binding; } else { const Shader::UniformHnd handle = shader_->FindUniform(desc.name.c_str()); if (fplbase::ValidUniformHandle(handle)) { binding = fplbase::GlUniformHandle(handle); } else { return; } } const size_t bytes_per_component = desc.num_bytes / desc.count; switch (desc.type) { case Uniform::Type::kFloats: { switch (bytes_per_component) { case 4: GL_CALL(glUniform1fv(binding, desc.count, uniform.GetData<float>())); break; case 8: GL_CALL(glUniform2fv(binding, desc.count, uniform.GetData<float>())); break; case 12: GL_CALL(glUniform3fv(binding, desc.count, uniform.GetData<float>())); break; case 16: GL_CALL(glUniform4fv(binding, desc.count, uniform.GetData<float>())); break; default: LOG(DFATAL) << "Uniform named \"" << desc.name << "\" is set to unsupported type floats with size " << desc.num_bytes; } } break; case Uniform::Type::kMatrix: { switch (bytes_per_component) { case 64: GL_CALL(glUniformMatrix4fv(binding, desc.count, false, uniform.GetData<float>())); break; case 36: GL_CALL(glUniformMatrix3fv(binding, desc.count, false, uniform.GetData<float>())); break; case 16: GL_CALL(glUniformMatrix2fv(binding, desc.count, false, uniform.GetData<float>())); break; default: LOG(DFATAL) << "Uniform named \"" << desc.name << "\" is set to unsupported type matrix with size " << desc.num_bytes; } } break; default: // Error or missing implementation. LOG(DFATAL) << "Trying to bind uniform of unknown type."; } } } // namespace lull
34.542444
80
0.686439
7f5039992eb67ceedc2414dfed8e29ad0caf0b2e
109
cpp
C++
sources/shared_ptr.cpp
Denis-Gorbachev/lab-03-shared-ptr
555967045a5893a0f79507e60e5ccf386335fbe6
[ "MIT" ]
null
null
null
sources/shared_ptr.cpp
Denis-Gorbachev/lab-03-shared-ptr
555967045a5893a0f79507e60e5ccf386335fbe6
[ "MIT" ]
null
null
null
sources/shared_ptr.cpp
Denis-Gorbachev/lab-03-shared-ptr
555967045a5893a0f79507e60e5ccf386335fbe6
[ "MIT" ]
null
null
null
// Copyright 2021 Denis <denis.gorbachev2002@yandex.ru> //#include <stdexcept> //#include <shared_ptr.hpp>
18.166667
55
0.733945
7f56ba7b9b0425620218970964694ac78674c346
3,703
cpp
C++
lib/common/Shader.cpp
ynsn/rendor
b4d9da7ccedd472c7fc6d0155000c5b6a031dd1a
[ "MIT" ]
null
null
null
lib/common/Shader.cpp
ynsn/rendor
b4d9da7ccedd472c7fc6d0155000c5b6a031dd1a
[ "MIT" ]
null
null
null
lib/common/Shader.cpp
ynsn/rendor
b4d9da7ccedd472c7fc6d0155000c5b6a031dd1a
[ "MIT" ]
null
null
null
/** * MIT License * * Copyright (c) 2019 Yoram * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <glad/glad.h> #include <vector> #include <string> #include <iostream> #include <sstream> #include <fstream> #include "cg/common/Shader.h" namespace cg { Shader::Shader(const ShaderType &type) : shaderType(type) { this->shaderHandle = glCreateShader(static_cast<GLenum>(this->shaderType)); if (this->shaderHandle == 0) { fprintf(stderr, "Error: could not create shader, id = 0...\n"); } } Shader::~Shader() { glDeleteShader(this->shaderHandle); } void Shader::setShaderSource(const std::string &shaderSource) const { const char *source = shaderSource.c_str(); glShaderSource(this->shaderHandle, 1, &source, nullptr); } bool Shader::compileShader() { glCompileShader(this->shaderHandle); int status = 0; glGetShaderiv(this->shaderHandle, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) { int length = 0; glGetShaderiv(this->shaderHandle, GL_INFO_LOG_LENGTH, &length); std::vector<char> log(length); glGetShaderInfoLog(this->shaderHandle, length, &length, &log[0]); std::string logString(log.begin(), log.end()); fprintf(stderr, "Shader compilation log (id = %u, type = %u): %s", this->shaderHandle, this->shaderType, logString.c_str()); this->compiled = false; } else { this->compiled = true; } return this->compiled; } const ShaderType &Shader::getShaderType() const { return this->shaderType; } const std::string Shader::getShaderSource() const { std::vector<char> sourceBuf(getShaderSourceLength()); glGetShaderSource(this->shaderHandle, sourceBuf.size(), NULL, &sourceBuf[0]); std::string source(sourceBuf.begin(), sourceBuf.end()); return source; } const int Shader::getShaderSourceLength() const { int length; glGetShaderiv(this->shaderHandle, GL_SHADER_SOURCE_LENGTH, &length); return length; } const bool Shader::isDeleted() const { int deleted = false; glGetShaderiv(this->shaderHandle, GL_DELETE_STATUS, &deleted); return static_cast<const bool>(deleted); } bool Shader::isCompiled() const { return this->compiled; } const unsigned int Shader::getHandle() const { return this->shaderHandle; } Shader *Shader::LoadFromSourceFile(const ShaderType &type1, const std::string &path) { std::ifstream file; file.open(path); if (!file.is_open()) { fprintf(stderr, "Error: could not read file '%s'\n", path.c_str()); return nullptr; } std::stringstream source; source << file.rdbuf(); auto *shader = new Shader(type1); shader->setShaderSource(source.str()); return shader; } }
29.15748
86
0.709155
7f59467bbebf778457679b5aae0d9fca38b6115d
578
cpp
C++
util/mod_count_in_range.cpp
sekiya9311/CplusplusAlgorithmLibrary
f29dbdfbf3594da055185e39765880ff5d1e64ae
[ "Apache-2.0" ]
null
null
null
util/mod_count_in_range.cpp
sekiya9311/CplusplusAlgorithmLibrary
f29dbdfbf3594da055185e39765880ff5d1e64ae
[ "Apache-2.0" ]
8
2019-04-13T15:11:11.000Z
2020-03-19T17:14:18.000Z
util/mod_count_in_range.cpp
sekiya9311/CplusplusAlgorithmLibrary
f29dbdfbf3594da055185e39765880ff5d1e64ae
[ "Apache-2.0" ]
null
null
null
// 範囲内のmodごとの数 // [l, r] 閉区間 std::vector<long long> mod_count_in_range(long long left, long long right, int mod) { const long long range = (right - left + 1); std::vector<long long> mod_count(mod, range / mod); if (range % mod > 0) { const int add_of_rest_left = left % mod; int add_of_rest_right; if (left % mod <= right % mod) { add_of_rest_right = right % mod; } else { add_of_rest_right = right % mod + mod; } for (int i = add_of_rest_left; i <= add_of_rest_right; i++) { mod_count[i % mod]++; } } return mod_count; }
28.9
85
0.610727
7f5d6320aa10eee491059fc407abd1e679737819
366
cpp
C++
basic/root.cpp
ray2060/learn-cpp
bcf322d32574e1741a048219acff5697c99b2614
[ "MIT" ]
null
null
null
basic/root.cpp
ray2060/learn-cpp
bcf322d32574e1741a048219acff5697c99b2614
[ "MIT" ]
null
null
null
basic/root.cpp
ray2060/learn-cpp
bcf322d32574e1741a048219acff5697c99b2614
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <sstream> using namespace std; string root(string s) { if (s.size() == 1) return s; int m; for (int i = 0; i < s.size(); i ++) m += s[i] - 48; stringstream st; st << m; string t; st >> t; return root(t); } int main() { string s; cin >> s; cout << root(s); return 0; }
15.25
55
0.510929
7f5fd23d9e82092bb4d7066d6d588405d98299aa
23,640
cpp
C++
DesignPages/DesignFormPanel.cpp
LibertyWarriorMusic/DBWorks
4bda411608cecb86f2cfc7f9319b160ed558a853
[ "MIT" ]
1
2020-03-10T03:26:50.000Z
2020-03-10T03:26:50.000Z
DesignPages/DesignFormPanel.cpp
LibertyWarriorMusic/DBWorks
4bda411608cecb86f2cfc7f9319b160ed558a853
[ "MIT" ]
1
2020-03-20T05:16:14.000Z
2020-03-20T05:17:25.000Z
DesignPages/DesignFormPanel.cpp
LibertyWarriorMusic/DBWorks
4bda411608cecb86f2cfc7f9319b160ed558a853
[ "MIT" ]
null
null
null
// // DrawPan.cpp // P2 // // Created by Nicholas Zounis on 27/2/20. // #include <wx/artprov.h> #include <wx/xrc/xmlres.h> #include <wx/button.h> #include <wx/string.h> #include <wx/bitmap.h> #include <wx/image.h> #include <wx/icon.h> #include <wx/gdicmn.h> #include <wx/font.h> #include <wx/colour.h> #include <wx/settings.h> #include <wx/combobox.h> #include <wx/textctrl.h> #include <wx/gbsizer.h> #include <wx/minifram.h> #include <wx/sizer.h> #include "wx/wx.h" #include "wx/sizer.h" #include "ObControl.h" #include "../Shared/global.h" #include "../Shared/Utility.h" #include "../MyEvent.h" #include "../Dialog/DlgTableSelect.h" #include "../Dialog/LinkedTableDlg.h" #include "../Dialog/MultiTextDlg.h" #include "../Dialog/SelectionFieldQueryDlg.h" #include "../Dialog/SetFlagsDlg.h" #include "../Dialog/ListBoxDlg.h" #include "../Dialog/SingleTextDlg.h" #include "../Dialog/ManageActionsDlg.h" #include "../Generic/GenericQueryGrid.h" #include "mysql.h" #include "mysql++.h" #include "DesignFormPanel.h" #include <cmath> #include <wx/arrimpl.cpp> WX_DEFINE_OBJARRAY(ArrayDrawControls); using namespace mysqlpp; enum { ID_MENU_ADD_CONTROL = wxID_HIGHEST + 600, ID_MENU_EDIT_LINKED_FIELD, ID_MENU_DELETE_CONTROL, ID_BUTTON_ADD_VALUE, ID_BUTTON_REMOVE_LAST, ID_CHK_AS, ID_CHK_EQUAL, ID_CHK_LIKE, ID_MENU_EDIT_STATIC, ID_MENU_RUN_QUERY, ID_MENU_EDIT_SET_FLAGS, ID_MENU_SELECTION_OPTIONS, ID_MENU_EDIT_LINKED_TABLE, ID_MENU_EDIT_DESCRIPTION, ID_MENU_MANAGE_ACTIONS }; BEGIN_EVENT_TABLE(DesignFormPanel, wxPanel) // some useful events EVT_MOTION(DesignFormPanel::mouseMoved) EVT_LEFT_DOWN(DesignFormPanel::mouseDown) EVT_LEFT_DCLICK(DesignFormPanel::mouseDoubleClick) EVT_LEFT_UP(DesignFormPanel::mouseReleased) EVT_RIGHT_DOWN(DesignFormPanel::rightClick) EVT_LEAVE_WINDOW(DesignFormPanel::mouseLeftWindow) EVT_KEY_DOWN(DesignFormPanel::keyPressed) EVT_KEY_UP(DesignFormPanel::keyReleased) EVT_MOUSEWHEEL(DesignFormPanel::mouseWheelMoved) EVT_MENU(ID_MENU_EDIT_LINKED_FIELD, DesignFormPanel::OnMenuEditLinkedFields) EVT_MENU(ID_MENU_DELETE_CONTROL, DesignFormPanel::OnMenuDeleteControl) EVT_MENU(ID_MENU_EDIT_STATIC, DesignFormPanel::OnMenuEditStatic) EVT_MENU(ID_MENU_EDIT_DESCRIPTION, DesignFormPanel::OnMenuEditDescription) EVT_MENU(ID_MENU_RUN_QUERY, DesignFormPanel::OnRunQuery) EVT_MENU(ID_MENU_EDIT_SET_FLAGS, DesignFormPanel::OnSetFlags) EVT_MENU(ID_MENU_SELECTION_OPTIONS, DesignFormPanel::OnSetSelectionOptions) EVT_MENU(ID_MENU_EDIT_LINKED_TABLE, DesignFormPanel::OnSetLinkedTable) EVT_MENU(ID_MENU_MANAGE_ACTIONS, DesignFormPanel::OnManageActions) EVT_PAINT(DesignFormPanel::paintEvent) END_EVENT_TABLE() void DesignFormPanel::rightClick(wxMouseEvent& event) { m_pObCurrentFormControl= nullptr; m_MousePos = event.GetPosition(); //Remember the mouse position to draw ObControl* pCtl = GetObjectHitByMouse(m_MousePos); //Diagram menus //Create a context menu to do stuff here. auto *menu = new wxMenu; if(pCtl!= nullptr) { m_pObCurrentFormControl = pCtl; if(m_pObCurrentFormControl->GetTypeName()=="CTL_STATIC" ) { menu->Append(ID_MENU_EDIT_STATIC, wxT("Set Label"), wxT("Set the Label.")); } else if(m_pObCurrentFormControl->GetTypeName()=="CTL_SPACER" ){ } else if(m_pObCurrentFormControl->GetTypeName()=="CTL_SELECTION" || m_pObCurrentFormControl->GetTypeName()=="CTL_SELECTION_ADDITIVE"){ menu->Append(ID_MENU_EDIT_STATIC, wxT("Set Label"), wxT("Set the Label.")); menu->Append(ID_MENU_EDIT_LINKED_FIELD, wxT("Set Linked Field"), wxT("Edit table definitions.")); menu->Append(ID_MENU_SELECTION_OPTIONS, wxT("Manage Options"), wxT("Manage options.")); } else if(m_pObCurrentFormControl->GetTypeName()=="CTL_SELECTION_LINKED_NAME" || m_pObCurrentFormControl->GetTypeName()=="CTL_SELECTION_LOOKUP_NAME"){ menu->Append(ID_MENU_EDIT_STATIC, wxT("Set Label"), wxT("Set the Label.")); menu->Append(ID_MENU_EDIT_LINKED_FIELD, wxT("Set Linked Field"), wxT("Edit table definitions.")); menu->Append(ID_MENU_EDIT_LINKED_TABLE, wxT("Set Linked Table"), wxT("Set Linked Table.")); } else if(m_pObCurrentFormControl->GetTypeName()=="CTL_BUTTON") { menu->Append(ID_MENU_EDIT_STATIC, wxT("Set Button Label"), wxT("Set the Button Label.")); menu->Append(ID_MENU_EDIT_DESCRIPTION, wxT("Set Button Description"), wxT("Set Button Description.")); menu->Append(ID_MENU_MANAGE_ACTIONS, wxT("Manage Actions"), wxT("Manage Actions")); } else if(m_pObCurrentFormControl->GetTypeName()=="CTL_GRID_DISPLAY") { } else if(m_pObCurrentFormControl->GetTypeName()!="CTL_RECORD_SELECTOR") { menu->Append(ID_MENU_EDIT_STATIC, wxT("Set Label"), wxT("Set the Label.")); menu->Append(ID_MENU_EDIT_LINKED_FIELD, wxT("Set Linked Field"), wxT("Edit table definitions.")); //Don't do this. //menu->Append(ID_MENU_EDIT_SET_FLAGS, wxT("Set Flags"), wxT("Set flags for this controlFS.")); } menu->Append(ID_MENU_DELETE_CONTROL, wxT("Delete Control"), wxT("Delete Control.")); } else{ menu->Append(ID_MENU_RUN_QUERY, wxT("Test query"), wxT("Test query.")); // menu->AppendSeparator(); } PopupMenu( menu, m_MousePos); //Tell the parent to add a table to the drawing at the mouse point. MyEvent my_event( this ); my_event.m_bStatusMessage=true; my_event.m_pMousePoint=m_MousePos; GetParent()->ProcessWindowEvent( my_event ); } DesignFormPanel::~DesignFormPanel() { DeleteDrawObject(); } DesignFormPanel::DesignFormPanel(wxFrame* parent) : wxPanel(parent) { m_pObjectToDrawTEMP = nullptr; m_pObCurrentFormControl = nullptr; m_MouseMoveOffset.x=0; m_MouseMoveOffset.y=0; m_sizeWinObjectsExtend.x=0; m_sizeWinObjectsExtend.y=0; } void DesignFormPanel::SetFormID(wxString sFormId) { m_sFormId=sFormId; } wxString DesignFormPanel::GetFormID() { return m_sFormId; } //=================== //MENU EVENT FUNCTIONS void DesignFormPanel::OnMenuEditStatic(wxCommandEvent& event) { wxString sData = PromptEditSingleTextDialog("Label","Set Label","Label"); m_pObCurrentFormControl->SetLabel(sData); RedrawControlObjects(); } void DesignFormPanel::OnMenuEditDescription(wxCommandEvent& event) { wxString sData = PromptEditSingleTextDialog("Short_Description","Edit short description","Short Description."); m_pObCurrentFormControl->SetDescription(sData); RedrawControlObjects(); } wxString DesignFormPanel::PromptEditSingleTextDialog(wxString sKey, wxString sDialogTitle, wxString sLabel) { if(m_pObCurrentFormControl!= nullptr){ wxString sControlId = m_pObCurrentFormControl->GetControlID(); SingleTextDlg * pDlg = new SingleTextDlg(nullptr, sDialogTitle, sLabel); Utility::LoadTableData(Settings.sDatabase,"usr_controls",sControlId,sKey,sLabel); pDlg->SetDataValue("ID_TEXT",sLabel); if(pDlg->ShowModal()==wxOK) { sLabel = pDlg->GetDataValue("ID_TEXT"); Utility::SaveTableData(Settings.sDatabase,"usr_controls",sControlId,sKey,sLabel); //We need to create a new entry in the Form queries. } pDlg->Destroy(); } return sLabel; } void DesignFormPanel::OnManageActions(wxCommandEvent& event) { if(m_pObCurrentFormControl!= nullptr){ wxString sControlId = m_pObCurrentFormControl->GetControlID(); ManageActionsDlg * pDlg = new ManageActionsDlg(nullptr, sControlId, "Avaliable actions", "Select Action"); if(pDlg->ShowModal()==wxOK) { pDlg->Save(); //So we can redraw on the screen. m_pObCurrentFormControl->SetAction(pDlg->GetAction()); RedrawControlObjects(); //We need to create a new entry in the Form queries. } pDlg->Destroy(); } } void DesignFormPanel::OnMenuEditLinkedFields(wxCommandEvent& event) { if(m_pObCurrentFormControl!= nullptr){ wxString sControlId = m_pObCurrentFormControl->GetControlID(); SelectionFieldQueryDlg * pDlg = new SelectionFieldQueryDlg(nullptr, "Avaliable Fields", "Select Field"); pDlg->SetControlID(sControlId); pDlg->SetQuery(m_sBuildQuery); pDlg->Load(); if(pDlg->ShowModal()==wxOK) { pDlg->Save(); //So we can redraw on the screen. m_pObCurrentFormControl->SetField(pDlg->GetField()); RedrawControlObjects(); //We need to create a new entry in the Form queries. } pDlg->Destroy(); } } void DesignFormPanel::OnSetFlags(wxCommandEvent& event) { SetFlagsDlg * pDlg = new SetFlagsDlg(nullptr, "Avaliable Fields", "Select Field"); wxString sControlId = m_pObCurrentFormControl->GetControlID(); wxString flags=""; wxString sKey="FLAGS"; Utility::LoadTableData(Settings.sDatabase,"usr_controls",sControlId,sKey,flags); pDlg->SetDataValue("ID_FLAGS",flags); if(pDlg->ShowModal()==wxOK) { wxString flags = pDlg->GetDataValue("ID_FLAGS"); Utility::SaveTableData(Settings.sDatabase,"usr_controls",sControlId,"FLAGS",flags); } pDlg->Destroy(); } void DesignFormPanel::OnSetSelectionOptions(wxCommandEvent& event) { ListBoxDlg * pDlg = new ListBoxDlg(nullptr, "Selection Options List", "Selection Options"); wxString sControlId = m_pObCurrentFormControl->GetControlID(); pDlg->SetControlID(sControlId); pDlg->LoadItems(); if(pDlg->ShowModal()==wxOK) pDlg->SaveItems(); pDlg->Destroy(); } void DesignFormPanel::OnSetLinkedTable(wxCommandEvent& event) { LinkedTableDlg * pDlg = new LinkedTableDlg(nullptr, "Selection Options List", "Selection Options"); wxString sControlId = m_pObCurrentFormControl->GetControlID(); pDlg->SetControlID(sControlId); pDlg->Load(); if(pDlg->ShowModal()==wxOK) pDlg->Save(); pDlg->Destroy(); } void DesignFormPanel::OnMenuDeleteControl(wxCommandEvent& event) { if(m_pObCurrentFormControl!= nullptr){ wxString sControlTypeName = m_pObCurrentFormControl->GetTypeName(); wxString sControlId = m_pObCurrentFormControl->GetControlID(); //The field doesn't exist, do you want to add it. auto *dlg = new wxMessageDialog(nullptr, "Are you sure you want to delete this control? \n\n", wxT("Delete Control"), wxYES_NO | wxICON_EXCLAMATION); if ( dlg->ShowModal() == wxID_YES ){ wxString dropQuery= "DELETE FROM usr_controls WHERE usr_controlsId= "+m_pObCurrentFormControl->GetControlID(); Utility::ExecuteQuery(dropQuery); RemoveControlFromList(m_pObCurrentFormControl->GetControlID()); RedrawControlObjects(); dlg->Destroy(); } } } void DesignFormPanel::OnRunQuery(wxCommandEvent& event) { MyEvent my_event( this ); my_event.m_bOpenRunQuery=true; GetParent()->ProcessWindowEvent( my_event ); } void DesignFormPanel::OnMenuOpenControl(wxCommandEvent& event) { if(m_pObCurrentFormControl!= nullptr){ MyEvent my_event( this ); my_event.m_bOpen=true; my_event.m_sTableName=m_pObCurrentFormControl->GetTypeName(); my_event.m_sTableId=m_pObCurrentFormControl->GetControlID(); GetParent()->ProcessWindowEvent( my_event ); } } // Testing draw the position when the mouse is down. void DesignFormPanel::mouseDown(wxMouseEvent& event) { m_MousePos = event.GetPosition(); //Remember the mouse position to draw wxString fieldName=""; wxRect fieldRect; ObControl* pCtl = GetObjectHitByMouse(m_MousePos,fieldName,fieldRect); if(pCtl!= nullptr) { if(!fieldName.IsEmpty()){ } else m_MouseMoveOffset=Utility::CalcPtInRectOffset(m_MousePos,pCtl->GetControlRect()); //NOTE we never want to delete m_pObjectToDrawTEMP because this is the object on the screen, but we want to make the pointer null when we are finished with it. m_pObjectToDrawTEMP = pCtl; m_pObjectToDrawTEMP->TurnSnapOff(); } MyEvent my_event( this ); my_event.m_bStatusMessage=true; my_event.m_sData="mouseDown"; GetParent()->ProcessWindowEvent( my_event ); } void DesignFormPanel::mouseMoved(wxMouseEvent& event) { m_MousePos = event.GetPosition(); //Remember the mouse position to draw if (m_pObjectToDrawTEMP != nullptr){ wxPoint pos; pos.x = m_MousePos.x - m_MouseMoveOffset.x; pos.y = m_MousePos.y - m_MouseMoveOffset.y; //Drag the object m_pObjectToDrawTEMP->SetControlPosition(pos); //This is going to be too show. We need to only move the object. wxClientDC dc(this); m_pObjectToDrawTEMP->DrawControlObject(dc); } } void DesignFormPanel::mouseReleased(wxMouseEvent& event) { m_MousePos = event.GetPosition(); //Remember the mouse position to draw if(m_pObjectToDrawTEMP!=nullptr){ //Restore the snap condition to what is was before we moved the object m_pObjectToDrawTEMP->RestorePreviousSnapCondition(); wxPoint pos; pos.x = m_MousePos.x - m_MouseMoveOffset.x; pos.y = m_MousePos.y - m_MouseMoveOffset.y; m_pObjectToDrawTEMP->SetControlPosition(pos); //This also checks the limits and doesn't draw the object in the query builder section. wxClientDC dc(this); m_pObjectToDrawTEMP->DrawControlObject(dc); m_pObjectToDrawTEMP->SaveDB(m_pObjectToDrawTEMP->GetControlID()); //We can save it directly //Reset these m_pObjectToDrawTEMP = nullptr; m_MouseMoveOffset.x=0; m_MouseMoveOffset.y=0; } MyEvent my_event( this ); my_event.m_bStatusMessage=true; my_event.m_sData="mouseReleased"; GetParent()->ProcessWindowEvent( my_event ); } void DesignFormPanel::DeleteDrawObject() { /* You don't need to do this I believe, I haven't yet checked if the program leaks memory, but if you do this the program crashes. // I think the object array deletes the objects when it is destroyed. int count = m_ObTableList.GetCount(); if(m_ObTableList.GetCount()>0){ for (int index=0; index<m_ObTableList.GetCount();index++) delete &m_ObTableList[index]; } */ } wxSize DesignFormPanel::GetSizeDiagramExtend() { wxSize size = m_sizeWinObjectsExtend; size.x = m_sizeWinObjectsExtend.x + 300; size.y = m_sizeWinObjectsExtend.y + 300; return size; } void DesignFormPanel::mouseDoubleClick(wxMouseEvent& event) { m_MousePos = event.GetPosition(); //Remember the mouse position to draw ObControl* pCtl = GetObjectHitByMouse(m_MousePos); if(pCtl!= nullptr) { MyEvent my_event( this ); my_event.m_bOpen=true; my_event.m_sTableName=pCtl->GetTypeName(); my_event.m_sTableId=pCtl->GetControlID(); GetParent()->ProcessWindowEvent( my_event ); } } void DesignFormPanel::mouseWheelMoved(wxMouseEvent& event) { MyEvent my_event( this ); my_event.m_bStatusMessage=true; my_event.m_sData="mouseWheelMoved"; GetParent()->ProcessWindowEvent( my_event ); } void DesignFormPanel::mouseLeftWindow(wxMouseEvent& event) { /* m_MousePos = event.GetPosition(); //Remember the mouse position to draw MyEvent my_event( this ); my_event.m_bStatusMessage=true; my_event.m_sData="mouseLeftWindow"; GetParent()->ProcessWindowEvent( my_event );*/ } void DesignFormPanel::keyPressed(wxKeyEvent& event) { /* m_MousePos = event.GetPosition(); //Remember the mouse position to draw MyEvent my_event( this ); my_event.m_bStatusMessage=true; my_event.m_sData="keyPressed"; GetParent()->ProcessWindowEvent( my_event );*/ } void DesignFormPanel::keyReleased(wxKeyEvent& event) { /* m_MousePos = event.GetPosition(); //Remember the mouse position to draw MyEvent my_event( this ); my_event.m_bStatusMessage=true; my_event.m_sData="keyReleased"; GetParent()->ProcessWindowEvent( my_event );*/ } /* * Called by the system of by wxWidgets when the panel needs * to be redrawn. You can also trigger this call by * calling Refresh()/Update(). */ void DesignFormPanel::paintEvent(wxPaintEvent & evt) { wxPaintDC dc(this); render(dc); } void DesignFormPanel::RedrawControlObjects() { wxClientDC dc(this); dc.Clear(); render(dc); //dc.Clear(); //NOT SURE why I put this after render, was it a mistake? I should of commented this. //Now we might want to put the default background colour on } //This is where you place stuff you need to do on refresh. void DesignFormPanel::Refresh() { RedrawControlObjects(); } /* * Here we do the actual rendering. I put it in a separate * method so that it can work no matter what type of DC * (e.g. wxPaintDC or wxClientDC) is used. */ void DesignFormPanel::render(wxDC& dc) { //Draw all the object to the screen. for (int index=0; index<m_ControlList.GetCount();index++) { ObControl* pCtl = &m_ControlList[index]; if(pCtl!= nullptr) pCtl->DrawControlObject(dc); } } ObControl * DesignFormPanel::GetObjectHitByMouse(wxPoint mousePt) { //Draw all the object to the screen. for (int index=0; index<m_ControlList.GetCount();index++) { ObControl* pCtl = &m_ControlList[index]; if(pCtl!= nullptr){ if(pCtl->HitTest(mousePt)){ return pCtl; } } } return nullptr; } //The the mouse point hit a field, will return the field name ObControl * DesignFormPanel::GetObjectHitByMouse(wxPoint mousePt, wxString& sHitFieldName, wxRect& sfieldRect) { ObControl * pCtl = GetObjectHitByMouse(mousePt); //if(pCtl != nullptr) //sHitFieldName = pCtl->HitTestField(mousePt,sfieldRect); return pCtl; } //Adds a drawing object to the diagram panel. void DesignFormPanel::AddControlObject(const wxString& sTypeID) { ObControl *pCtl = NewCtlObject(); if(pCtl != nullptr) { //The Control doesn't exist, so add it. pCtl->SetTypeID(sTypeID); pCtl->SetControlPosition(m_MousePos); pCtl->SetFormID(GetFormID()); wxArrayString sArray; Utility::GetFieldFromTableWhereFieldEquals(Settings.sDatabase, sArray, "usr_control_types", "typeName", "usr_control_typesId", sTypeID); if(sArray.GetCount()==1){ pCtl->SetTypeName(sArray[0]); } m_ControlList.Add(pCtl); pCtl->SaveDB(""); } RedrawControlObjects(); // Redraw all the objects. } void DesignFormPanel::RemoveControlFromList(wxString sControlId) { int count = m_ControlList.GetCount(); if(m_ControlList.GetCount()>0) { for (int index = 0; index < count; index++) { if(m_ControlList[index].GetControlID()==sControlId){ //Remove this from the list, redraw and exit m_ControlList.RemoveAt(index); break; } } } } //Loads all the controls from the database and creates the drawing void DesignFormPanel::LoadControlObjects() { // If we have existing object, clear the list. if(m_ControlList.GetCount()>0) m_ControlList.Clear(); wxString QueryString = "SELECT usr_control_types.usr_control_typesId, usr_control_types.typeName, usr_controls.usr_controlsId, usr_controls.table_data "; QueryString += " FROM usr_control_types, usr_controls "; QueryString += " WHERE usr_control_types.usr_control_typesId = usr_controls.usr_control_typesId"; QueryString += " AND usr_controls.usr_formsId = "+GetFormID(); ArrayFieldRecord saControl; Utility::LoadArrayFieldRecordFromQuery(saControl, QueryString); int count = saControl.GetCount(); if(saControl.GetCount()>0){ for(int index=0;index<count;index++){ wxString sData=""; wxString sControlId = saControl[index].GetData("usr_controlsId"); wxString sTypeName = saControl[index].GetData("typeName"); wxString sTypeID = saControl[index].GetData("usr_control_typesId"); wxString sEntireTableData = saControl[index].GetData("table_data"); Utility::LoadTableData(Settings.sDatabase,"usr_controls",sControlId,"ObControlShow",sData,sEntireTableData); if(sData=="yes"){ //Load the data and create the table object. //wxString sTableID = Utility::GetTableIdFromSYS_TABLESByTableName(Settings.sDatabase,saControlId[index]); //The table doesn't exist, so add it. ObControl * pCtl = NewCtlObject(); pCtl->SetControlID(sControlId); pCtl->SetFormID(GetFormID()); pCtl->SetTypeName(sTypeName); pCtl->SetTypeID(sTypeID); wxString sLabel=""; wxString sField=""; wxString xPos = ""; wxString yPos = ""; Utility::LoadTableData(Settings.sDatabase,"usr_controls",sControlId,wxT("ObControlPositionX"),xPos); Utility::LoadTableData(Settings.sDatabase,"usr_controls",sControlId,wxT("ObControlPositionY"),yPos); Utility::LoadTableData(Settings.sDatabase,"usr_controls",sControlId,wxT("Label"),sLabel); pCtl->SetLabel(sLabel); Utility::LoadTableData(Settings.sDatabase,"usr_controls",sControlId,wxT("Short_Description"),sLabel); pCtl->SetDescription(sLabel); Utility::LoadTableData(Settings.sDatabase,"usr_controls",sControlId,wxT("Action"),sLabel); pCtl->SetAction(sLabel); Utility::LoadTableData(Settings.sDatabase,"usr_controls",sControlId,wxT("Field"),sField); pCtl->SetField(sField); int lxPos = Utility::StringToInt(xPos); int lyPos = Utility::StringToInt(yPos); if(lxPos> m_sizeWinObjectsExtend.x){ m_sizeWinObjectsExtend.x = lxPos; } if(lyPos> m_sizeWinObjectsExtend.y){ m_sizeWinObjectsExtend.y = lyPos; } wxPoint pt(Utility::StringToInt(xPos),Utility::StringToInt(yPos)); pCtl->SetControlPosition(pt); m_ControlList.Add(pCtl); } } RedrawControlObjects(); // Draw them to the screen. } } void DesignFormPanel::SetQuery(wxString sQuery) { m_sBuildQuery=sQuery; } wxString DesignFormPanel::GetQuery() { return m_sBuildQuery; } ObControl* DesignFormPanel::NewCtlObject() { ObControl* pCtl= new ObControl; return pCtl; } /* //Check to make sure we already don't have an existing table. ObControl* DesignFormPanel::DoesControlExist(wxString sControlId) { for (int index=0; index<m_ControlList.GetCount();index++) { ObControl *pCtl = &m_ControlList[index]; if(pCtl->GetID()== sControlId) return pCtl; } return nullptr; } */ //We can send a message to the parent that this window is destroyed. bool DesignFormPanel::Destroy() { MyEvent my_event( this ); my_event.m_bDestroyed=true; GetParent()->ProcessWindowEvent( my_event ); //bool bResult = wxPanel::Destroy(); return true; }
32.383562
167
0.677876
7f60bb0f944ba4d08ab554d599ac5ea4d433bb12
19,513
cc
C++
Archive/Stroika_FINAL_for_STERL_1992/Library/Graphix/Sources/Shape.cc
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
28
2015-09-22T21:43:32.000Z
2022-02-28T01:35:01.000Z
Archive/Stroika_FINAL_for_STERL_1992/Library/Graphix/Sources/Shape.cc
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
98
2015-01-22T03:21:27.000Z
2022-03-02T01:47:00.000Z
Archive/Stroika_FINAL_for_STERL_1992/Library/Graphix/Sources/Shape.cc
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
4
2019-02-21T16:45:25.000Z
2022-02-18T13:40:04.000Z
/* Copyright(c) Sophist Solutions Inc. 1990-1992. All rights reserved */ /* * $Header: /fuji/lewis/RCS/Shape.cc,v 1.7 1992/09/11 18:41:55 sterling Exp $ * * TODO: * * - Desperately need the ability to scale shapes - probably shouyld add general * transform capabilty - at least scale, etc.. * * Changes: * $Log: Shape.cc,v $ * Revision 1.7 1992/09/11 18:41:55 sterling * new Shape stuff, got rid of String Peek references * * Revision 1.6 1992/09/05 16:14:25 lewis * Renamed Nil->Nil. * * Revision 1.5 1992/09/01 15:36:53 sterling * Lots of Foundation changes. * * Revision 1.4 1992/07/08 02:11:42 lewis * Renamed PointInside->Contains (). * * Revision 1.3 1992/07/04 14:50:03 lewis * Added BlockAllocation/operator new/delete overrides to the shape reps for * better performance. Also, lots of cleanups including removing ifdefed out * code. * * Revision 1.2 1992/07/04 02:37:40 lewis * See header for big picture - but mainly here we renamed all shape classes X, * to XRepresention, and commented out methods that were setters - just recreate * the object - with out new paradigm its a little harder to do sets - may support * them again, if sterl thinks its worth it... * * Revision 1.1 1992/06/19 22:34:01 lewis * Initial revision * * Revision 1.12 1992/05/23 00:10:07 lewis * #include BlockAllocated instead of Memory.hh * * Revision 1.11 92/04/15 14:31:18 14:31:18 lewis (Lewis Pringle) * Adjust asserts to be call AsDegrees () when comparing with hardwired degress values. * * Revision 1.9 1992/02/21 18:06:44 lewis * Got rid of qGPlus_ClassOpNewDelBroke workaround. * * * * */ #include "OSRenamePre.hh" #if qMacGDI #include <Memory.h> #include <OSUtils.h> #include <QuickDraw.h> #endif /*qMacGDI*/ #include "OSRenamePost.hh" #include "BlockAllocated.hh" #include "Debug.hh" #include "PixelMap.hh" #include "Tablet.hh" #include "Shape.hh" #if !qRealTemplatesAvailable Implement (Iterator, Point); Implement (Collection, Point); Implement (AbSequence, Point); Implement (Array, Point); Implement (Sequence_Array, Point); Implement (Sequence, Point); #endif /*!qRealTemplatesAvailable*/ #if qMacGDI struct WorkTablet : Tablet { WorkTablet (osGrafPort* osg): Tablet (osg) { AssertNotNil (osg); } }; static struct ModuleInit { ModuleInit () { osGrafPort* port = new (osGrafPort); ::OpenPort (port); fTablet = new WorkTablet (port); } Tablet* fTablet; } kModuleGlobals; #endif /*qMacGDI*/ #if !qRealTemplatesAvailable Implement (Shared, ShapeRepresentation); #endif /* ******************************************************************************** ***************************** ShapeRepresentation ****************************** ******************************************************************************** */ Boolean ShapeRepresentation::Contains (const Point& p, const Rect& shapeBounds) const { if (shapeBounds.Contains (p)) { return (ToRegion (shapeBounds).Contains (p)); } else { return (False); } } Region ShapeRepresentation::ToRegion (const Rect& shapeBounds) const { #if qMacGDI static osRegion** tmp = ::NewRgn (); static const Pen kRegionPen = Pen (kBlackTile, eCopyTMode, Point (1, 1)); AssertNotNil (kModuleGlobals.fTablet->GetOSGrafPtr ()); osGrafPort* oldPort = qd.thePort; Tablet::xDoSetPort (kModuleGlobals.fTablet->GetOSGrafPtr ()); ::OpenRgn (); OutLine (*kModuleGlobals.fTablet, shapeBounds, kRegionPen); ::CloseRgn (tmp); Tablet::xDoSetPort (oldPort); return (Region (tmp)); #elif qXGDI // for now, hack and just return bounding rectable - we must fix this soon!!! return (shapeBounds); #endif /*qMacGDI || qXGDI*/ } Point ShapeRepresentation::GetLogicalSize () const { return (kZeroPoint); } /* ******************************************************************************** *************************** RectangleRepresentation **************************** ******************************************************************************** */ RectangleRepresentation::RectangleRepresentation () { } Boolean RectangleRepresentation::Contains (const Point& p, const Rect& shapeBounds) const { return (shapeBounds.Contains (p)); } void RectangleRepresentation::Paint (Tablet& on, const Rect& shapeBounds, const Brush& brush) const { on.PaintRect (shapeBounds, brush); } void RectangleRepresentation::OutLine (Tablet& on, const Rect& shapeBounds, const Pen& pen) const { on.OutLineRect (shapeBounds, pen); } Region RectangleRepresentation::ToRegion (const Rect& shapeBounds) const { return (Region (shapeBounds)); } #if !qRealTemplatesAvailable BlockAllocatedDeclare (RectangleRepresentation); BlockAllocatedImplement (RectangleRepresentation); #endif /*!qRealTemplatesAvailable*/ void* RectangleRepresentation::operator new (size_t n) { #if qRealTemplatesAvailable return (BlockAllocated<RectangleRepresentation>::operator new (n)); #else /*qRealTemplatesAvailable*/ return (BlockAllocated(RectangleRepresentation)::operator new (n)); #endif /*qRealTemplatesAvailable*/ } void RectangleRepresentation::operator delete (void* p) { #if qRealTemplatesAvailable BlockAllocated<RectangleRepresentation>::operator delete (p); #else /*qRealTemplatesAvailable*/ BlockAllocated(RectangleRepresentation)::operator delete (p); #endif /*qRealTemplatesAvailable*/ } /* ******************************************************************************** ****************************** RoundedRectangle ******************************** ******************************************************************************** */ Point RoundedRectangle::kDefaultRounding = Point (10, 10); /* ******************************************************************************** *********************** RoundedRectangleRepresentation ************************* ******************************************************************************** */ RoundedRectangleRepresentation::RoundedRectangleRepresentation (const Point& rounding): fRounding (rounding) { Require (rounding.GetH () == (short)rounding.GetH ()); Require (rounding.GetV () == (short)rounding.GetV ()); } void RoundedRectangleRepresentation::Paint (Tablet& on, const Rect& shapeBounds, const Brush& brush) const { on.PaintRoundedRect (shapeBounds, fRounding, brush); } void RoundedRectangleRepresentation::OutLine (Tablet& on, const Rect& shapeBounds, const Pen& pen) const { on.OutLineRoundedRect (shapeBounds, fRounding, pen); } Point RoundedRectangleRepresentation::GetRounding () const { return (fRounding); } #if !qRealTemplatesAvailable BlockAllocatedDeclare (RoundedRectangleRepresentation); BlockAllocatedImplement (RoundedRectangleRepresentation); #endif /*!qRealTemplatesAvailable*/ void* RoundedRectangleRepresentation::operator new (size_t n) { #if qRealTemplatesAvailable return (BlockAllocated<RoundedRectangleRepresentation>::operator new (n)); #else /*qRealTemplatesAvailable*/ return (BlockAllocated(RoundedRectangleRepresentation)::operator new (n)); #endif /*qRealTemplatesAvailable*/ } void RoundedRectangleRepresentation::operator delete (void* p) { #if qRealTemplatesAvailable BlockAllocated<RoundedRectangleRepresentation>::operator delete (p); #else /*qRealTemplatesAvailable*/ BlockAllocated(RoundedRectangleRepresentation)::operator delete (p); #endif /*qRealTemplatesAvailable*/ } /* ******************************************************************************** ******************************** OvalRepresentation **************************** ******************************************************************************** */ OvalRepresentation::OvalRepresentation () { } void OvalRepresentation::Paint (Tablet& on, const Rect& shapeBounds, const Brush& brush) const { on.PaintOval (shapeBounds, brush); } void OvalRepresentation::OutLine (Tablet& on, const Rect& shapeBounds, const Pen& pen) const { on.OutLineOval (shapeBounds, pen); } #if !qRealTemplatesAvailable BlockAllocatedDeclare (OvalRepresentation); BlockAllocatedImplement (OvalRepresentation); #endif /*!qRealTemplatesAvailable*/ void* OvalRepresentation::operator new (size_t n) { #if qRealTemplatesAvailable return (BlockAllocated<OvalRepresentation>::operator new (n)); #else /*qRealTemplatesAvailable*/ return (BlockAllocated(OvalRepresentation)::operator new (n)); #endif /*qRealTemplatesAvailable*/ } void OvalRepresentation::operator delete (void* p) { #if qRealTemplatesAvailable BlockAllocated<OvalRepresentation>::operator delete (p); #else /*qRealTemplatesAvailable*/ BlockAllocated(OvalRepresentation)::operator delete (p); #endif /*qRealTemplatesAvailable*/ } /* ******************************************************************************** ******************************* ArcRepresentation ***************************** ******************************************************************************** */ ArcRepresentation::ArcRepresentation (Angle startAngle, Angle arcAngle): fStartAngle (startAngle), fArcAngle (arcAngle) { Require (startAngle.AsDegrees () >= 0); Require (arcAngle.AsDegrees () <= 360); } void ArcRepresentation::Paint (Tablet& on, const Rect& shapeBounds, const Brush& brush) const { on.PaintArc (fStartAngle, fArcAngle, shapeBounds, brush); } void ArcRepresentation::OutLine (Tablet& on, const Rect& shapeBounds, const Pen& pen) const { on.OutLineArc (fStartAngle, fArcAngle, shapeBounds, pen); } Angle ArcRepresentation::GetStart () const { return (fStartAngle); } Angle ArcRepresentation::GetAngle () const { return (fArcAngle); } #if !qRealTemplatesAvailable BlockAllocatedDeclare (ArcRepresentation); BlockAllocatedImplement (ArcRepresentation); #endif /*!qRealTemplatesAvailable*/ void* ArcRepresentation::operator new (size_t n) { #if qRealTemplatesAvailable return (BlockAllocated<ArcRepresentation>::operator new (n)); #else /*qRealTemplatesAvailable*/ return (BlockAllocated(ArcRepresentation)::operator new (n)); #endif /*qRealTemplatesAvailable*/ } void ArcRepresentation::operator delete (void* p) { #if qRealTemplatesAvailable BlockAllocated<ArcRepresentation>::operator delete (p); #else /*qRealTemplatesAvailable*/ BlockAllocated(ArcRepresentation)::operator delete (p); #endif /*qRealTemplatesAvailable*/ } /* ******************************************************************************** ************************** RegionShapeRepresentation *************************** ******************************************************************************** */ RegionShapeRepresentation::RegionShapeRepresentation (const Region& rgn): fRegion (rgn) { } void RegionShapeRepresentation::Paint (Tablet& on, const Rect& shapeBounds, const Brush& brush) const { on.PaintRegion (fRegion, shapeBounds, brush); } void RegionShapeRepresentation::OutLine (Tablet& on, const Rect& shapeBounds, const Pen& pen) const { on.OutLineRegion (fRegion, shapeBounds, pen); } Region RegionShapeRepresentation::ToRegion (const Rect& shapeBounds) const { if ((shapeBounds.Empty ()) or (fRegion == kEmptyRegion)) { return (kEmptyRegion); } if (shapeBounds == fRegion.GetBounds ()) { return (fRegion); } else { Region tempRgn = fRegion; #if qMacGDI osRect osr; osRect osBounds; os_cvt (fRegion.GetBounds (), osBounds); os_cvt (shapeBounds, osr); ::MapRgn (tempRgn.GetOSRegion (), &osBounds, &osr); #elif qXGDI return (shapeBounds); // see Shape::ToRegion ()!!! THIS IS BROKEN!!! #endif /*qMacGDI*/ return (tempRgn); } } Point RegionShapeRepresentation::GetLogicalSize () const { return (fRegion.GetBounds ().GetSize ()); } #if !qRealTemplatesAvailable BlockAllocatedDeclare (RegionShapeRepresentation); BlockAllocatedImplement (RegionShapeRepresentation); #endif /*!qRealTemplatesAvailable*/ void* RegionShapeRepresentation::operator new (size_t n) { #if qRealTemplatesAvailable return (BlockAllocated<RegionShapeRepresentation>::operator new (n)); #else /*qRealTemplatesAvailable*/ return (BlockAllocated(RegionShapeRepresentation)::operator new (n)); #endif /*qRealTemplatesAvailable*/ } void RegionShapeRepresentation::operator delete (void* p) { #if qRealTemplatesAvailable BlockAllocated<RegionShapeRepresentation>::operator delete (p); #else /*qRealTemplatesAvailable*/ BlockAllocated(RegionShapeRepresentation)::operator delete (p); #endif /*qRealTemplatesAvailable*/ } /* ******************************************************************************** ******************************** PolygonRepresentation ************************* ******************************************************************************** */ PolygonRepresentation::PolygonRepresentation (const AbSequence(Point)& points): ShapeRepresentation (), #if qMacGDI fOSPolygon (Nil), #endif /*qMacGDI*/ fPoints (points) { RebuildOSPolygon (); #if qXGDI AssertNotImplemented (); #endif /*qXGDI*/ } PolygonRepresentation::~PolygonRepresentation () { #if qMacGDI if (fOSPolygon != Nil) { ::KillPoly (fOSPolygon); } #endif /*qMacGDI*/ } void PolygonRepresentation::Paint (Tablet& on, const Rect& shapeBounds, const Brush& brush) const { #if qMacGDI on.PaintPolygon (fOSPolygon, shapeBounds, brush); #endif /*qMacGDI*/ } void PolygonRepresentation::OutLine (Tablet& on, const Rect& shapeBounds, const Pen& pen) const { #if qMacGDI on.OutLinePolygon (fOSPolygon, shapeBounds, pen); #endif /*qMacGDI*/ } Point PolygonRepresentation::GetLogicalSize () const { #if qMacGDI return (os_cvt ((*fOSPolygon)->polyBBox).GetSize ()); #endif /*qMacGDI*/ } const AbSequence(Point)& PolygonRepresentation::GetPoints () const { return (fPoints); } void PolygonRepresentation::RebuildOSPolygon () const { #if qMacGDI if (fOSPolygon != Nil) { ::KillPoly (fOSPolygon); } Tablet::xDoSetPort (kModuleGlobals.fTablet->GetOSGrafPtr ()); *((osPolygon***)&fOSPolygon) = ::OpenPoly (); // avoid const violation error if (fPoints.GetLength () >= 2) { Iterator(Point)* i = fPoints; Point p = i->Current (); ::MoveTo ((short)p.GetH (), (short)p.GetV ()); for (i->Next (); not (i->Done ()); i->Next ()) { p = i->Current (); Assert ((short)p.GetH () == p.GetH ()); Assert ((short)p.GetV () == p.GetV ()); ::LineTo ((short)p.GetH (), (short)p.GetV ()); } delete i; } ::ClosePoly (); #endif /*qMacGDI*/ } #if !qRealTemplatesAvailable BlockAllocatedDeclare (PolygonRepresentation); BlockAllocatedImplement (PolygonRepresentation); #endif /*!qRealTemplatesAvailable*/ void* PolygonRepresentation::operator new (size_t n) { #if qRealTemplatesAvailable return (BlockAllocated<PolygonRepresentation>::operator new (n)); #else /*qRealTemplatesAvailable*/ return (BlockAllocated(PolygonRepresentation)::operator new (n)); #endif /*qRealTemplatesAvailable*/ } void PolygonRepresentation::operator delete (void* p) { #if qRealTemplatesAvailable BlockAllocated<PolygonRepresentation>::operator delete (p); #else /*qRealTemplatesAvailable*/ BlockAllocated(PolygonRepresentation)::operator delete (p); #endif /*qRealTemplatesAvailable*/ } /* ******************************************************************************** ******************************** LineRepresentation **************************** ******************************************************************************** */ LineRepresentation::LineRepresentation (const Point& from, const Point& to): fFrom (from), fTo (to) { } void LineRepresentation::Paint (Tablet& on, const Rect& shapeBounds, const Brush& brush) const { /* lines have no interior, only an outline */ } void LineRepresentation::OutLine (Tablet& on, const Rect& shapeBounds, const Pen& pen) const { // probably should somehow use shapeBounds, probably by scaling points (EG QD's ::MapRect, :MapRgn) // SORRY STERL, But this attemt is wrong! It does not // use the shapeSize, which it needs to. Use QD mapPt() I think!!!, or do equiv. on.DrawLine (GetFrom () + shapeBounds.GetOrigin (), GetTo () + shapeBounds.GetOrigin (), pen); } Point LineRepresentation::GetLogicalSize () const { return (BoundingRect (fFrom, fTo).GetSize ()); } Point LineRepresentation::GetFrom () const { return (fFrom); } Point LineRepresentation::GetTo () const { return (fTo); } Region LineRepresentation::ToRegion (const Rect& shapeBounds) const { /* * Unfortunately, (and I must think this out further) the definition of regions is * that they are on a pixel basis and represent how many pixels are enclosed. Also, * somewhat strangly, if a Region contains no pixels, we rename it kEmptyRegion. Since * lines are infinitely thin, they contain no pixels, and thus their region is empty. * We may want to consider changing lines to have a thickness, or to intrduce a new * class that adds this concept. */ return (kEmptyRegion); } Real LineRepresentation::GetSlope () const { AssertNotReached (); return (0); } Real LineRepresentation::GetXIntercept () const { AssertNotReached (); return (0); } Real LineRepresentation::GetYIntercept () const { AssertNotReached (); return (0); } Point LineRepresentation::GetPointOnLine (Real percentFrom) const { AssertNotReached (); return (kZeroPoint); } Line LineRepresentation::GetPerpendicular (const Point& throughPoint) const { AssertNotReached (); return ((LineRepresentation*)this); // just a hack - hack around const and later // build real line... } Line LineRepresentation::GetBisector () const { return (GetPerpendicular (GetPointOnLine (0.5))); } Real LineRepresentation::GetLength () const { return (Distance (fFrom, fTo)); } #if !qRealTemplatesAvailable BlockAllocatedDeclare (LineRepresentation); BlockAllocatedImplement (LineRepresentation); #endif /*!qRealTemplatesAvailable*/ void* LineRepresentation::operator new (size_t n) { #if qRealTemplatesAvailable return (BlockAllocated<LineRepresentation>::operator new (n)); #else /*qRealTemplatesAvailable*/ return (BlockAllocated(LineRepresentation)::operator new (n)); #endif /*qRealTemplatesAvailable*/ } void LineRepresentation::operator delete (void* p) { #if qRealTemplatesAvailable BlockAllocated<LineRepresentation>::operator delete (p); #else /*qRealTemplatesAvailable*/ BlockAllocated(LineRepresentation)::operator delete (p); #endif /*qRealTemplatesAvailable*/ } /* ******************************************************************************** *************************** OrientedRectShapeRepresentation ******************** ******************************************************************************** */ // INCOMPLETE!!!! MAYBE BAD IDEA??? OrientedRectShapeRepresentation::OrientedRectShapeRepresentation (const Rect& rect, Angle angle): ShapeRepresentation (), fRect (kZeroRect), fAngle (0), fRegion (kEmptyRegion) { } OrientedRectShapeRepresentation::OrientedRectShapeRepresentation (const Point& aCorner, const Point& bCorner, Coordinate height): ShapeRepresentation (), fRect (kZeroRect), fAngle (0), fRegion (kEmptyRegion) { } void OrientedRectShapeRepresentation::OutLine (Tablet& on, const Rect& shapeBounds, const Pen& pen) const { } void OrientedRectShapeRepresentation::Paint (Tablet& on, const Rect& shapeBounds, const Brush& brush) const { } Region OrientedRectShapeRepresentation::ToRegion (const Rect& shapeBounds) const { } Point OrientedRectShapeRepresentation::GetLogicalSize () const { } // For gnuemacs: // Local Variables: *** // mode:C++ *** // tab-width:4 *** // End: ***
25.810847
129
0.656178
7f64675a48af53579e50b10fcf74a2893e7bf43b
730
cc
C++
ash/quick_pair/common/account_key_failure.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
ash/quick_pair/common/account_key_failure.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
ash/quick_pair/common/account_key_failure.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2021 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. #include "ash/quick_pair/common/account_key_failure.h" namespace ash { namespace quick_pair { std::ostream& operator<<(std::ostream& stream, AccountKeyFailure failure) { switch (failure) { case AccountKeyFailure::kAccountKeyCharacteristicDiscovery: stream << "[Failed to find the Account Key GATT characteristic]"; break; case AccountKeyFailure::kAccountKeyCharacteristicWrite: stream << "[Failed to write to the Account Key GATT characteristic]"; break; } return stream; } } // namespace quick_pair } // namespace ash
28.076923
75
0.730137
7f648ca329c34393391088b306750f82f8dc4b08
5,949
cpp
C++
mbed-glove-firmware/sensor_tests.cpp
apadin1/Team-GLOVE
d5f5134da79d050164dffdfdf87f12504f6b1370
[ "Apache-2.0" ]
null
null
null
mbed-glove-firmware/sensor_tests.cpp
apadin1/Team-GLOVE
d5f5134da79d050164dffdfdf87f12504f6b1370
[ "Apache-2.0" ]
null
null
null
mbed-glove-firmware/sensor_tests.cpp
apadin1/Team-GLOVE
d5f5134da79d050164dffdfdf87f12504f6b1370
[ "Apache-2.0" ]
1
2019-01-09T05:16:42.000Z
2019-01-09T05:16:42.000Z
/* * Copyright (c) 2016 by Nick Bertoldi, Ben Heckathorn, Ryan O'Keefe, * Adrian Padin, Timothy Schumacher * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "mbed.h" #include "rtos.h" #include "drivers/flex_sensor.h" #include "drivers/imu.h" #include "drivers/touch_sensor.h" #include "drivers/analog_button.h" #include "drivers/dot_star_leds.h" #define INCLUDE_TOUCH 1 const PinName GLOVE_I2C_SDA = p30; //I2C_SDA0; // p30 const PinName GLOVE_I2C_SCL = p7; //I2C_SCL0; // p7 static I2C i2c(GLOVE_I2C_SDA, GLOVE_I2C_SCL); static Serial pc(USBTX, USBRX); static DigitalOut led(LED1); static DigitalOut l2(LED2); static DigitalOut l3(LED3); static DigitalOut l4(LED4); void touch_to_lights() { key_states_t keys; DigitalOut led1(P0_15); DigitalOut led2(P0_14); DigitalOut led3(P0_13); DigitalOut led4(P0_12); I2C i2c(I2C_SDA0, I2C_SCL0); TouchSensor touch_sensor(i2c, TOUCH_INTERRUPT); for (;;) { touch_sensor.spawnUpdateThread(); Thread::wait(15); touch_sensor.writeKeys(&keys); if (keys.a == 1) led1 = 0; else led1 = 1; if (keys.b == 1) led2 = 0; else led2 = 1; if (keys.c == 1) led3 = 0; else led3 = 1; if (keys.d == 1) led4 = 0; else led4 = 1; touch_sensor.terminateUpdateThreadIfBlocking(); Thread::wait(5); } } void imu_to_lights() { bno_imu_t data; DigitalOut led1(P0_15); DigitalOut led2(P0_14); DigitalOut led3(P0_13); DigitalOut led4(P0_12); led3 = 1; led1 = 1; led4 = 1; led2 = 1; I2C i2c(I2C_SDA0, I2C_SCL0); IMU_BNO055 imu(i2c); /*DEBUG if (imu.hwDebugCheckVal()) { led4 = 1; wait_ms(500); } for (;;) { led2 = !led2; wait_ms(20); }*/ for (;;) { led4 = !led4; imu.updateAndWrite(&data); if (data.orient_pitch > 30) { led3 = 0; } else led3 = 1; if (data.orient_roll > 40) { led2 = 0; } else led2 = 1; //if (data.orient_yaw > 15) { // led3 = 0; //} //else led3 = 1; wait_ms(20); } } void blink() { l2 = 1; led = 0; for (;;) { led = !led; l2 = !l2; Thread::wait(520); } } void boot_delay(uint8_t t) { // this loop is to prevent the strange fatal state // happening with serial debug led = 1; for (uint8_t i = 0; i < t; ++i) { led = 0; l2 = 0; l3 = 0; l4 = 0; wait(0.25); led = 1; l2 = 1; l3 = 1; l4 = 1; wait(0.75); } } void calibration_mode() { /* * The idea here is to go into a special mode for a fixed time, * and measure the maximum and minimum values on all the sensors */ // setup objects const uint16_t ms_period = 20; for (uint32_t i = 0; i < 8000 / (ms_period - 8); ++i) { // gather data // update max/mins // print results Thread::wait(ms_period - 8); } } void sensors_to_lights() { led = 1; l2 = 1; l3 = 1; l4 = 1; DotStarLEDs ds_leds(2); uint8_t red, green, blue; IMU_BNO055 imu(i2c); bno_imu_t imu_vals; FlexSensors flex_sensors; flex_sensor_t flex_vals[4]; //TouchSensor touch_sensor(i2c, p16); key_states_t keys; float flex_val; uint16_t flex_min = 250; uint16_t flex_max = 750; /* * Flex zero sets led 0 red/blue * * Any touch sets both lights to bright white * * Light one is the combined IMU status */ for (;;) { led = !led; //touch_sensor.spawnUpdateThread(); imu.updateAndWrite(&imu_vals); flex_sensors.updateAndWrite(flex_vals); //touch_sensor.writeKeys(&keys); imu.print(pc); //printf("f: %d, clib: 0x%x, p: %f\r\n", flex_vals[0], imu.hwDebugCheckVal(), imu_vals.orient_pitch); if (flex_vals[0] < flex_min) { flex_min = flex_vals[0]; } if (flex_vals[0] > flex_max) { flex_max = flex_vals[0]; } if (keys.pack()) { ds_leds.set_RGB(0,0,255,0); } else { // set flex light flex_val = map_unsigned_analog_to_percent(flex_min, flex_max, flex_vals[0]); red = 255*flex_val; green = 0; blue = 255*(1-flex_val); ds_leds.set_RGB(0, red, green, blue); // set imu light blue = 255*map_float_analog_to_percent(-45.0, 45.0, imu_vals.orient_pitch); red = 255*map_float_analog_to_percent(-45.0, 45.0, imu_vals.orient_roll); green = 255*map_float_analog_to_percent(0.0, 360.0, imu_vals.orient_yaw); ds_leds.set_RGB(1, red, green, blue, 3); } //touch_sensor.terminateUpdateThreadIfBlocking(); Thread::wait(1000); } }
25.207627
109
0.593713
7f65000118ec2d9709cec5f5792f3d4512aeba66
1,607
hpp
C++
src/component/symbol_table.hpp
aabaa/mizcore
5542f080278d79a993df741bd3bf3daa24ac28f9
[ "MIT" ]
1
2020-11-17T12:47:29.000Z
2020-11-17T12:47:29.000Z
src/component/symbol_table.hpp
aabaa/mizcore
5542f080278d79a993df741bd3bf3daa24ac28f9
[ "MIT" ]
null
null
null
src/component/symbol_table.hpp
aabaa/mizcore
5542f080278d79a993df741bd3bf3daa24ac28f9
[ "MIT" ]
2
2020-02-28T09:19:45.000Z
2020-02-28T09:26:17.000Z
#pragma once #include <map> #include <memory> #include <string> #include <string_view> #include <vector> #include "symbol_type.hpp" #include "tsl/htrie_map.h" namespace mizcore { class Symbol; class SymbolTable { public: // ctor, dtor SymbolTable(); virtual ~SymbolTable() = default; SymbolTable(const SymbolTable&) = delete; SymbolTable(SymbolTable&&) = delete; SymbolTable& operator=(const SymbolTable&) = delete; SymbolTable& operator=(SymbolTable&&) = delete; // attributes Symbol* AddSymbol(std::string_view filename, std::string_view text, SYMBOL_TYPE type, uint8_t priority = 64); void AddSynonym(Symbol* s0, Symbol* s1); void AddValidFileName(std::string_view filename) { valid_filenames_.emplace_back(filename); } std::vector<Symbol*> CollectFileSymbols(std::string_view filename) const; const std::vector<std::pair<Symbol*, Symbol*>>& CollectSynonyms() const; // operations void Initialize(); void BuildQueryMap(); Symbol* QueryLongestMatchSymbol(std::string_view text) const; private: // implementation void BuildQueryMapOne(std::string_view filename); static bool IsWordBoundary(std::string_view text, size_t pos); static bool IsWordBoundaryCharacter(char x); std::map<std::string, std::vector<std::unique_ptr<Symbol>>> file2symbols_; std::vector<std::pair<Symbol*, Symbol*>> synonyms_; std::vector<std::string> valid_filenames_; tsl::htrie_map<char, Symbol*> query_map_; }; } // namespace mizcore
27.237288
78
0.676416
7f6e05b69da4a03db5b0fa024ad65f9d7d59f3ae
1,312
cpp
C++
src/Compiler/CodeGen/For.cpp
BenjaminNavarro/Feral
579411c36a1cc66f96fcda1b82e3259e22022ac2
[ "BSD-3-Clause" ]
null
null
null
src/Compiler/CodeGen/For.cpp
BenjaminNavarro/Feral
579411c36a1cc66f96fcda1b82e3259e22022ac2
[ "BSD-3-Clause" ]
null
null
null
src/Compiler/CodeGen/For.cpp
BenjaminNavarro/Feral
579411c36a1cc66f96fcda1b82e3259e22022ac2
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2020, Electrux All rights reserved. Using the BSD 3-Clause license for the project, main LICENSE file resides in project's root directory. Please read that file and understand the license terms before using or altering the project. */ #include "Internal.hpp" bool stmt_for_t::gen_code( bcode_t & bc, const bool f1, const bool f2 ) const { bc.add( idx(), OP_PUSH_LOOP ); if( m_init ) m_init->gen_code( bc ); size_t iter_jmp_loc = bc.size(); if( m_cond ) m_cond->gen_code( bc ); size_t cond_fail_jmp_from = bc.size(); if( m_cond ) { // placeholder location bc.addsz( m_cond->idx(), OP_JMPFPOP, 0 ); } size_t body_begin = bc.size(); m_body->gen_code( bc ); size_t body_end = bc.size(); size_t continue_jmp_loc = bc.size(); if( m_incr ) m_incr->gen_code( bc ); bc.addsz( idx(), OP_JMP, iter_jmp_loc ); if( m_cond ) { bc.updatesz( cond_fail_jmp_from, bc.size() ); } // pos where break goes size_t break_jmp_loc = bc.size(); bc.add( idx(), OP_POP_LOOP ); // update all continue and break calls for( size_t i = body_begin; i < body_end; ++i ) { if( bc.at( i ) == OP_CONTINUE && bc.get()[ i ].data.sz == 0 ) bc.updatesz( i, continue_jmp_loc ); if( bc.at( i ) == OP_BREAK && bc.get()[ i ].data.sz == 0 ) bc.updatesz( i, break_jmp_loc ); } return true; }
25.230769
99
0.664634
7f725472e5d2bd0568eeea50d9f6e7e71d806e3a
4,611
cc
C++
file_exchange_client.cc
yitzikc/grpc-file-exchange
668798c5d2e770f643f696fb65e89b5e5c0e10dd
[ "MIT" ]
13
2020-07-10T18:54:40.000Z
2021-12-07T22:36:25.000Z
file_exchange_client.cc
yitzikc/grpc-file-exchange
668798c5d2e770f643f696fb65e89b5e5c0e10dd
[ "MIT" ]
null
null
null
file_exchange_client.cc
yitzikc/grpc-file-exchange
668798c5d2e770f643f696fb65e89b5e5c0e10dd
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> #include <string> #include <vector> #include <string> #include <cstdlib> #include <cstdint> #include <utility> #include <cassert> #include <sysexits.h> #include <grpc/grpc.h> #include <grpc++/channel.h> #include <grpc++/client_context.h> #include <grpc++/create_channel.h> #include <grpc++/security/credentials.h> #include "utils.h" #include "sequential_file_writer.h" #include "file_reader_into_stream.h" using grpc::Channel; using grpc::ClientContext; using grpc::ClientReader; using grpc::ClientReaderWriter; using grpc::ClientWriter; using grpc::Status; using fileexchange::FileId; using fileexchange::FileContent; using fileexchange::FileExchange; class FileExchangeClient { public: FileExchangeClient(std::shared_ptr<Channel> channel) : m_stub(FileExchange::NewStub(channel)) { } bool PutFile(std::int32_t id, const std::string& filename) { FileId returnedId; ClientContext context; std::unique_ptr<ClientWriter<FileContent>> writer(m_stub->PutFile(&context, &returnedId)); try { FileReaderIntoStream< ClientWriter<FileContent> > reader(filename, id, *writer); // TODO: Make the chunk size configurable const size_t chunk_size = 1UL << 20; // Hardcoded to 1MB, which seems to be recommended from experience. reader.Read(chunk_size); } catch (const std::exception& ex) { std::cerr << "Failed to send the file " << filename << ": " << ex.what() << std::endl; // FIXME: Indicate to the server that something went wrong and that the trasfer should be aborted. } writer->WritesDone(); Status status = writer->Finish(); if (!status.ok()) { std::cerr << "File Exchange rpc failed: " << status.error_message() << std::endl; return false; } else { std::cout << "Finished sending file with id " << returnedId.id() << std::endl; } return true; } bool GetFileContent(std::int32_t id) { FileId requestedId; FileContent contentPart; ClientContext context; SequentialFileWriter writer; std::string filename; requestedId.set_id(id); std::unique_ptr<ClientReader<FileContent> > reader(m_stub->GetFileContent(&context, requestedId)); try { while (reader->Read(&contentPart)) { assert(contentPart.id() == id); filename = contentPart.name(); writer.OpenIfNecessary(contentPart.name()); auto* const data = contentPart.mutable_content(); writer.Write(*data); }; const auto status = reader->Finish(); if (! status.ok()) { std::cerr << "Failed to get the file "; if (! filename.empty()) { std::cerr << filename << ' '; } std::cerr << "with id " << id << ": " << status.error_message() << std::endl; return false; } std::cout << "Finished receiving the file " << filename << " id: " << id << std::endl; } catch (const std::system_error& ex) { std::cerr << "Failed to receive " << filename << ": " << ex.what(); return false; } return true; } private: std::unique_ptr<fileexchange::FileExchange::Stub> m_stub; }; void usage [[ noreturn ]] (const char* prog_name) { std::cerr << "USAGE: " << prog_name << " [put|get] num_id [filename]" << std::endl; std::exit(EX_USAGE); } int main(int argc, char** argv) { if (argc < 3) { usage(argv[0]); } const std::string verb = argv[1]; std::int32_t id = -1; try { id = std::atoi(argv[2]); } catch (std::invalid_argument) { std::cerr << "Invalid Id " << argv[2] << std::endl; usage(argv[0]); } bool succeeded = false; FileExchangeClient client(grpc::CreateChannel("localhost:50051", grpc::InsecureChannelCredentials())); if ("put" == verb) { if (4 != argc) { usage(argv[0]); } const std::string filename = argv[3]; succeeded = client.PutFile(id, filename); } else if ("get" == verb) { if (3 != argc) { usage(argv[0]); } succeeded = client.GetFileContent(id); } else { std::cerr << "Unknown verb " << verb << std::endl; usage(argv[0]); } return succeeded ? EX_OK : EX_IOERR; }
29.369427
119
0.567773
7f7265728b572c76da1e29ebe58b29a88f345161
2,169
cpp
C++
src/core/features/defuse.cpp
mov-rax-rax/gamesneeze
09b2d9d6ef5b6ad7c9c820f98f1a6339bf1405a1
[ "MIT" ]
1
2022-01-13T07:05:26.000Z
2022-01-13T07:05:26.000Z
src/core/features/defuse.cpp
mov-rax-rax/gamesneeze
09b2d9d6ef5b6ad7c9c820f98f1a6339bf1405a1
[ "MIT" ]
null
null
null
src/core/features/defuse.cpp
mov-rax-rax/gamesneeze
09b2d9d6ef5b6ad7c9c820f98f1a6339bf1405a1
[ "MIT" ]
1
2021-12-31T13:02:42.000Z
2021-12-31T13:02:42.000Z
#include "../../includes.hpp" #include "features.hpp" void Features::Defuse::createMoveStart(Command *cmd) { auto autoDefuse = CONFIGBOOL("Misc>Misc>Misc>Auto Defuse"); auto silentDefuse = CONFIGBOOL("Misc>Misc>Misc>Silent Defuse"); auto antiAiming = CONFIGINT("Rage>AntiAim>Type") != 0; if (!(autoDefuse || silentDefuse || antiAiming)) { return; } if (Features::Defuse::performDefuse) { cmd->buttons |= IN_USE; } if ((cmd->buttons & IN_USE) != 0 && Features::Defuse::canDefuse && (silentDefuse || antiAiming)) { cmd->viewAngle = Features::Defuse::angles; } } void Features::Defuse::createMoveEnd(Command *cmd) { Features::Defuse::canDefuse = false; Features::Defuse::performDefuse = false; } void Features::Defuse::onBombRender(PlantedC4 *bomb) { auto autoDefuse = CONFIGBOOL("Misc>Misc>Misc>Auto Defuse"); auto silentDefuse = CONFIGBOOL("Misc>Misc>Misc>Silent Defuse"); auto antiAiming = CONFIGINT("Rage>AntiAim>Type") != 0; if (!(autoDefuse || silentDefuse || antiAiming)) { Features::Defuse::canDefuse = false; Features::Defuse::performDefuse = false; return; } auto playerOrigin = Globals::localPlayer->origin(); auto bombOrigin = bomb->origin(); if (getDistanceNoSqrt(playerOrigin, bombOrigin) < 5625) { Features::Defuse::canDefuse = true; } else { Features::Defuse::canDefuse = false; } if (silentDefuse || antiAiming) { auto eyePos = Globals::localPlayer->eyePos(); auto angles = calcAngle(eyePos, bombOrigin); clampAngle(angles); Features::Defuse::angles = angles; } if (CONFIGBOOL("Misc>Misc>Misc>Latest Defuse")) { auto timeRemaining = bomb->time() - (Interfaces::globals->currentTime + ((float)playerResource->GetPing(Globals::localPlayer->index()) / 1000.f)); if (timeRemaining < (Globals::localPlayer->defuser() ? 5.1f: 10.1f)) { Features::Defuse::performDefuse = true; return; } } else { Features::Defuse::performDefuse = true; } Features::Defuse::performDefuse = false; }
30.549296
154
0.632089
7f771b35efe4c9619b2da87401e3ab7679742766
3,159
hpp
C++
packages/monte_carlo/core/src/MonteCarlo_AdjointPhotonProbeState.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/monte_carlo/core/src/MonteCarlo_AdjointPhotonProbeState.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/monte_carlo/core/src/MonteCarlo_AdjointPhotonProbeState.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_AdjointPhotonProbeState.hpp //! \author Alex Robinson //! \brief Adjoint photon probe state class declaration //! //---------------------------------------------------------------------------// #ifndef MONTE_CARLO_ADJOINT_PHOTON_PROBE_STATE_HPP #define MONTE_CARLO_ADJOINT_PHOTON_PROBE_STATE_HPP // Boost Includes #include <boost/serialization/shared_ptr.hpp> // FRENSIE Includes #include "MonteCarlo_AdjointPhotonState.hpp" #include "Utility_TypeNameTraits.hpp" namespace MonteCarlo{ /*! The adjoint photon probe state class * \details The probe state get killed when its energy changes (after being * activated). */ class AdjointPhotonProbeState : public AdjointPhotonState { public: // The adjoint photon probe tag struct AdjointPhotonProbeTag{}; // Typedef for the adjoint photon probe tag struct AdjointPhotonProbeTag ParticleTag; //! Default constructor AdjointPhotonProbeState(); //! Constructor AdjointPhotonProbeState( const ParticleState::historyNumberType history_number ); //! Copy constructor (with possible creation of new generation) AdjointPhotonProbeState( const ParticleState& existing_base_state, const bool increment_generation_number = false, const bool reset_collision_number = false ); //! Copy constructor (with possible creation of new generation) AdjointPhotonProbeState( const AdjointPhotonProbeState& existing_base_state, const bool increment_generation_number = false, const bool reset_collision_number = false ); //! Destructor ~AdjointPhotonProbeState() { /* ... */ } //! Set the energy of the particle (MeV) void setEnergy( const energyType energy ); //! Check if this is a probe bool isProbe() const; //! Activate the probe void activate(); //! Returns if the probe is active bool isActive() const; //! Clone the particle state (do not use to generate new particles!) AdjointPhotonProbeState* clone() const; //! Print the adjoint photon state void toStream( std::ostream& os ) const; private: // Save the state to an archive template<typename Archive> void serialize( Archive& ar, const unsigned version ) { ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(AdjointPhotonState); ar & BOOST_SERIALIZATION_NVP( d_active ); } // Declare the boost serialization access object as a friend friend class boost::serialization::access; // Flag that indicates if the probe is active bool d_active; }; } // end MonteCarlo namespace BOOST_CLASS_VERSION( MonteCarlo::AdjointPhotonProbeState, 0 ); BOOST_CLASS_EXPORT_KEY2( MonteCarlo::AdjointPhotonProbeState, "AdjointPhotonProbeState" ); EXTERN_EXPLICIT_CLASS_SERIALIZE_INST( MonteCarlo, AdjointPhotonProbeState ); TYPE_NAME_TRAITS_QUICK_DECL2( AdjointPhotonProbeState, MonteCarlo ); #endif // end MONTE_CARLO_ADJOINT_PHOTON_PROBE_STATE_HPP //---------------------------------------------------------------------------// // end MonteCarlo_AdjointPhotonProbeState.hpp //---------------------------------------------------------------------------//
30.375
90
0.686926
7f7a350edbf1b381dbd5d2994a11701cbd83b77b
3,015
cpp
C++
Ejercicios/Ejercicio44-Punto-de-Venta-parte-V/productos.cpp
DanielaVH/cpp
c54c853681cdd46d85172546b14019ed48909999
[ "MIT" ]
null
null
null
Ejercicios/Ejercicio44-Punto-de-Venta-parte-V/productos.cpp
DanielaVH/cpp
c54c853681cdd46d85172546b14019ed48909999
[ "MIT" ]
null
null
null
Ejercicios/Ejercicio44-Punto-de-Venta-parte-V/productos.cpp
DanielaVH/cpp
c54c853681cdd46d85172546b14019ed48909999
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; extern void agregarProducto(string descripcion, int cantidad, double precio); void productos(int opcion) { system("cls"); int opcionProducto = 0; switch (opcion) { case 1: { cout << "BEBIDAS CALIENTES" << endl; cout << "******************" << endl; cout << "1- Capuccino" << endl; cout << "2- Expresso" << endl; cout << "3- Cafe Latte" << endl; cout << endl; cout << "Ingrese una opcion: "; cin >> opcionProducto; switch (opcionProducto) { case 1: agregarProducto("1 Capuccino - L 40.00", 1, 40); break; case 2: agregarProducto("1 Expresso - L 30.00", 1, 30); break; case 3: agregarProducto("1 Cafe Latte - L 40.00", 1, 40); break; default: { cout << "opcion no valida"; return; break; } } cout << endl; cout << "Producto agregado" << endl << endl; system("pause"); break; } case 2: { cout << "BEBIDAS FRIAS" << endl; cout << "************" << endl; cout << "1- Granita de cafe" << endl; cout << "2- Mochaccino" << endl; cout << "3- Frapuchatta" << endl; cout << endl; cout << "Ingrese una opcion: "; cin >> opcionProducto; switch (opcionProducto) { case 1: agregarProducto("1 Granita de cafe - L 30.00", 1, 30); break; case 2: agregarProducto("1 Expresso - L 60.00", 1, 60); break; case 3: agregarProducto("1 Frapuchatta - L 70.00", 1, 70); break; default: { cout << "opcion no valida"; return; break; } } cout << endl; cout << "Producto agregado" << endl << endl; system("pause"); break; } case 3: { cout << "REPOSTERIA" << endl; cout << "*********" << endl; cout << "1- Porcion-Pastel de Zanahoria" << endl; cout << "2- Galleta alfajor" << endl; cout << "3- Porcion-Pastel de Limon" << endl; cout << endl; cout << "Ingrese una opcion: "; cin >> opcionProducto; switch (opcionProducto) { case 1: agregarProducto("1 Porcion-Pastel de Zanahoria - L 40.00", 1, 40); break; case 2: agregarProducto("1 Galleta alfajor - L 30.00", 1, 30); break; case 3: agregarProducto("1 Porcion-Pastel de limon - L 60.00", 1, 60); break; default: { cout << "opcion no valida"; return; break; } } cout << endl; cout << "Producto agregado" << endl << endl; system("pause"); break; } default: break; } }
22.333333
78
0.448093
7f7eb0c1e0f936d0f4e7a2690c69c17e9e1d80e0
5,504
cpp
C++
tests/bint_div.cpp
mrdcvlsc/bintlib
9290f779eb50101bd35b00148eea94c5c30dcc61
[ "MIT" ]
2
2020-10-30T06:39:01.000Z
2020-10-31T02:18:00.000Z
tests/bint_div.cpp
mrdcvlsc/bintlib
9290f779eb50101bd35b00148eea94c5c30dcc61
[ "MIT" ]
2
2020-10-30T06:49:01.000Z
2020-10-31T11:12:42.000Z
tests/bint_div.cpp
mrdcvlsc/bintlib
9290f779eb50101bd35b00148eea94c5c30dcc61
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #ifndef _MAKE_LIB #include "../core.hpp" #else #include <bint.hpp> #endif #include "mini-test.hpp" int main() { START_TEST; // test variables apa::bint ONE = 1, ZERO = 0; apa::bint NUM1( "0x19cf0546f6a3fc1e93d8dbda5ea2889551cb7248d21125fbf60f3c622a4ab01456703c3" "39c96f18bed4ce4fa268983f97dcb83ae847f8ecf19f81870578c41ede22ccf76553d1c38" "deb692820ac53f361c2a2e0b0dc6e6b77810b15d656775b37fc2afb2200632008419c0555" "ccffd2f9377262ef48b6a096629b8af1048f07dc1a8152eebd3d209041dfccb9df9e5ef94" "f4b55bae8fb825d7dcfb68e89e0ab027f27bbd2d0b226a82e0fbcc85eeb8b1df2c6fd6ee3" "8e4b43e78649af542686ba5a385d34ed7c51c6b77c5ab1ff868deca9b0158edc44de55c44",16 ); apa::bint NUM2( "0xa4027a170efee729e543877bc6d8cb88c00810d0b3f18c77f9755907f470a1a94f4ab26" "825e763265c216490f5a93c0426485cc2bfc99ed1fd883aa983759e4662f26cdd96cf3289",16 ); apa::bint NUM3 = 2; apa::bint NUM1_DIV_NUM2( "0x2848ca2401c26ea27bfc2689ff8ce447b6092adcab3c610c5d646521e7a4358f0aa93a39" "d8ec904a02856cf99e4456452e00a219a64b823b59edadaa23841fa573d848bc586e2840ca" "c74808ed76bff1a3168be007b1f2270efbbb42156794955629291df55af4ae1f3933e5dc77" "9f5c0b38f66e4a48da1d91a4461c682f0bdd4d688f6b70b338b7895a4ce0fb3236c7be0e",16 ); apa::bint NUM1_DIV_NUM3( "0xce782a37b51fe0f49ec6ded2f51444aa8e5b924690892fdfb079e311525580a2b381e19ce" "4b78c5f6a6727d1344c1fcbee5c1d7423fc7678cfc0c382bc620f6f11667bb2a9e8e1c6f5b4" "94105629f9b0e15170586e3735bbc0858aeb2b3bad9bfe157d910031900420ce02aae67fe97" "c9bb93177a45b504b314dc578824783ee0d40a9775e9e904820efe65cefcf2f7ca7a5aadd74" "7dc12ebee7db4744f055813f93dde9685913541707de642f75c58ef9637eb771c725a1f3c32" "4d7aa13435d2d1c2e9a76be28e35bbe2d58ffc346f654d80ac76e226f2ae22",16 ); apa::bint NUM2_DIV_NUM3( "0x52013d0b877f7394f2a1c3bde36c65c46004086859f8c63bfcbaac83fa3850d4a7a559341" "2f3b1932e10b2487ad49e0213242e615fe4cf68fec41d54c1bacf233179366ecb679944",16 ); apa::bint NUM1_MOD_NUM2( "0x79b744150065c5ae9c0a197c73841d9a27735226bdd3e6177c1956e524095dad2dd6f9799" "fb95a944dc7b49a9bc204b1b81eb48bd25ecf6d7eef5f8afdcfc44cce56623d188feac6",16 ); apa::bint NUM1_MOD_NUM3 = 0; apa::bint NUM2_MOD_NUM3 = 1; apa::bint ANSQ1 = NUM1/NUM2, ANSQ1_NEG = -NUM1 / NUM2, ANSQ2 = NUM1/NUM3, ANSQ3 = NUM2/NUM3, ANSR1 = NUM1%NUM2, ANSR2 = NUM1%NUM3, ANSR3 = NUM2%NUM3; ASSERT_EQUALITY((-NUM1)/NUM1,(-ONE), "1 -NUM1/NUM1 "); ASSERT_EQUALITY(NUM2/NUM2,ONE, "2 NUM2/NUM2 "); ASSERT_EQUALITY(NUM3/NUM3,ONE, "3 NUM3/NUM3 "); ASSERT_EQUALITY((NUM1/NUM1),ONE, "4 NUM1/NUM1 "); ASSERT_EQUALITY((NUM2/NUM2),ONE, "5 NUM2/NUM2 "); ASSERT_EQUALITY((NUM3/NUM3),ONE, "6 NUM3/NUM3 "); ASSERT_EQUALITY(ANSQ1,NUM1_DIV_NUM2, "7 NUM1/NUM2 "); ASSERT_EQUALITY(ANSQ1_NEG,-NUM1_DIV_NUM2, "7.5 -NUM1/NUM2"); ASSERT_EQUALITY(ANSQ2,NUM1_DIV_NUM3, "8 NUM1/NUM3 "); ASSERT_EQUALITY(ANSQ3,NUM2_DIV_NUM3, "9 NUM2/NUM3 "); ASSERT_EQUALITY((NUM1/(-NUM2)),(-NUM1_DIV_NUM2),"10 -NUM1/NUM2 "); ASSERT_EQUALITY((NUM1/NUM3),NUM1_DIV_NUM3, "11 NUM1/NUM3 "); ASSERT_EQUALITY(((-NUM2)/NUM3),(-NUM2_DIV_NUM3),"12 -NUM2/NUM3 "); ASSERT_EQUALITY((NUM3/NUM1),ZERO, "13 NUM3/NUM1 "); ASSERT_EQUALITY((NUM3/NUM2),ZERO, "14 NUM3/NUM2 "); ASSERT_EQUALITY((NUM2/NUM1),ZERO, "15 NUM2/NUM1 "); apa::bint NEGNUM1_MOD_NUM1 = (-NUM1)%NUM1; ASSERT_EQUALITY(NEGNUM1_MOD_NUM1,ZERO, "16 -NUM1%NUM1 "); ASSERT_EQUALITY(NUM2%NUM2,ZERO, "17 NUM2%NUM2 "); ASSERT_EQUALITY(NUM3%NUM3,ZERO, "18 NUM3%NUM13 "); ASSERT_EQUALITY((NUM1%NUM1),ZERO, "19 NUM1%NUM1 "); ASSERT_EQUALITY((NUM2%NUM2),ZERO, "20 NUM2%NUM2 "); ASSERT_EQUALITY((NUM3%NUM3),ZERO, "21 NUM3%NUM3 "); ASSERT_EQUALITY(ANSR1,NUM1_MOD_NUM2, "22 NUM1%NUM2 "); ASSERT_EQUALITY(ANSR2,NUM1_MOD_NUM3, "23 NUM1%NUM3 "); ASSERT_EQUALITY(ANSR3,NUM2_MOD_NUM3, "24 NUM2%NUM3 "); apa::bint NEG_NUM1_MOD_NUM2 = -NUM1 % NUM2; apa::bint NUM1_MOD_NEG_NUM2 = NUM1 % -NUM2; ASSERT_EQUALITY(NEG_NUM1_MOD_NUM2,-NUM1_MOD_NUM2,"25 -NUM1%NUM2 "); ASSERT_EQUALITY(NUM1_MOD_NEG_NUM2,NUM1_MOD_NUM2,"26 NUM1%-NUM2 "); ASSERT_EQUALITY((NUM1%(-NUM3)),(apa::__BINT_ZERO),"27 NUM1%-NUM3 "); ASSERT_EQUALITY((NUM2%NUM3),NUM2_MOD_NUM3, "28 NUM2%NUM3 "); ASSERT_EQUALITY((NUM3%NUM1),NUM3, "29 NUM3%NUM1 "); ASSERT_EQUALITY((NUM3%NUM2),NUM3, "30 NUM3%NUM2 "); ASSERT_EQUALITY((NUM2%NUM1),NUM2, "31 NUM2%NUM1 "); #if defined(_BASE2_16) RESULT("BINT BASE 2^16 DIVISION"); #elif defined(_BASE2_32) RESULT("BINT BASE 2^32 DIVISION"); #elif defined(_BASE2_64) RESULT("BINT BASE 2^64 DIVISION"); #endif }
45.866667
90
0.646802
7f7fd0a272828d9329a064393a4fb8097fcfcaf6
2,850
cpp
C++
ardupilot/libraries/AP_BattMonitor/AP_BattMonitor_SMBus_PX4.cpp
quadrotor-IITKgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
1
2021-07-17T11:37:16.000Z
2021-07-17T11:37:16.000Z
ardupilot/libraries/AP_BattMonitor/AP_BattMonitor_SMBus_PX4.cpp
arl-kgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
null
null
null
ardupilot/libraries/AP_BattMonitor/AP_BattMonitor_SMBus_PX4.cpp
arl-kgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
null
null
null
/* Battery SMBus PX4 driver */ /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <AP_HAL/AP_HAL.h> #if CONFIG_HAL_BOARD == HAL_BOARD_PX4 #include "AP_BattMonitor_SMBus_PX4.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <drivers/drv_batt_smbus.h> #include <uORB/topics/battery_status.h> extern const AP_HAL::HAL& hal; // Constructor AP_BattMonitor_SMBus_PX4::AP_BattMonitor_SMBus_PX4(AP_BattMonitor &mon, uint8_t instance, AP_BattMonitor::BattMonitor_State &mon_state) : AP_BattMonitor_SMBus(mon, instance, mon_state), _batt_fd(-1), _capacity_updated(false) { // orb subscription for battery status _batt_sub = orb_subscribe(ORB_ID(battery_status)); } void AP_BattMonitor_SMBus_PX4::init() { // open the device _batt_fd = open(BATT_SMBUS0_DEVICE_PATH, O_RDWR); if (_batt_fd == -1) { hal.console->printf("Unable to open " BATT_SMBUS0_DEVICE_PATH); _state.healthy = false; } } // read - read latest voltage and current void AP_BattMonitor_SMBus_PX4::read() { bool updated = false; struct battery_status_s batt_status; // check if new info has arrived from the orb orb_check(_batt_sub, &updated); // retrieve latest info if (updated) { if (OK == orb_copy(ORB_ID(battery_status), _batt_sub, &batt_status)) { _state.voltage = batt_status.voltage_v; _state.current_amps = batt_status.current_a; _state.last_time_micros = hal.scheduler->micros(); _state.current_total_mah = batt_status.discharged_mah; _state.healthy = true; // read capacity if ((_batt_fd >= 0) && !_capacity_updated) { uint16_t tmp; if (ioctl(_batt_fd, BATT_SMBUS_GET_CAPACITY, (unsigned long)&tmp) == OK) { _capacity_updated = true; set_capacity(tmp); } } } } else if (_state.healthy) { // timeout after 5 seconds if ((hal.scheduler->micros() - _state.last_time_micros) > AP_BATTMONITOR_SMBUS_TIMEOUT_MICROS) { _state.healthy = false; } } } #endif // CONFIG_HAL_BOARD == HAL_BOARD_PX4
31.318681
137
0.669825
7f8142b6435655dade52964f1658b48d4b45c721
276
hpp
C++
tools/editor/utils.hpp
ijacquez/SMT-DS-SH
6fe6c15b76fb74ecb5bbb735139aa5791d79fcb8
[ "MIT" ]
6
2015-10-03T20:51:04.000Z
2019-10-21T04:19:06.000Z
tools/editor/utils.hpp
ijacquez/SMT-DS-SH
6fe6c15b76fb74ecb5bbb735139aa5791d79fcb8
[ "MIT" ]
null
null
null
tools/editor/utils.hpp
ijacquez/SMT-DS-SH
6fe6c15b76fb74ecb5bbb735139aa5791d79fcb8
[ "MIT" ]
null
null
null
#ifndef UTILS_HPP #define UTILS_HPP #include "jansson.h" #define BIG2LE_16(x) (((x) & 0x00FF) << 8) | (((x) >> 8) & 0x00FF) #define BIG2LE_32(x) (BIG2LE_16((x) & 0x0000FFFF) << 16) | \ BIG2LE_16(((x) >> 16) & 0x0000FFFF) #endif /* !UTILS_HPP */
25.090909
80
0.547101
7f83d6e4766ea81b9e559b467aa37682d6ef14dc
10,242
cc
C++
tls/src/params.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
40
2015-03-10T07:55:39.000Z
2021-06-11T10:13:56.000Z
tls/src/params.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
297
2015-04-30T10:02:04.000Z
2022-03-09T13:31:54.000Z
tls/src/params.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
29
2015-08-03T10:04:15.000Z
2021-11-25T12:21:00.000Z
/* ** Copyright 2009-2013,2021 Centreon ** ** 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. ** ** For more information : contact@centreon.com */ #include "com/centreon/broker/tls/params.hh" #include <gnutls/gnutls.h> #include <cstdlib> #include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/tls/internal.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::tls; using namespace com::centreon::exceptions; /** * Params constructor. * * @param[in] type Either CLIENT or SERVER, depending on connection * initialization. This cannot be modified after * construction. */ params::params(params::connection_type type) : _compress(false), _init(false), _type(type) {} /** * Destructor. */ params::~params() { _clean(); } /** * Apply parameters to a GNU TLS session object. * * @param[out] session Object on which parameters will be applied. */ void params::apply(gnutls_session_t session) { // Set the encryption method (normal ciphers with anonymous // Diffie-Hellman and optionnally compression). int ret; ret = gnutls_priority_set_direct( session, (_compress ? "NORMAL:-VERS-DTLS1.0:-VERS-DTLS1.2:-VERS-SSL3.0:-VERS-TLS1." "0:-VERS-TLS1.1:+ANON-DH:%COMPAT" : "NORMAL:-VERS-DTLS1.0:-VERS-DTLS1.2:-VERS-SSL3.0:-VERS-TLS1." "0:-VERS-TLS1.1:+ANON-DH:+COMP-" "DEFLATE:%COMPAT"), nullptr); if (ret != GNUTLS_E_SUCCESS) { log_v2::tls()->error("TLS: encryption parameter application failed: {}", gnutls_strerror(ret)); throw msg_fmt("TLS: encryption parameter application failed: {}", gnutls_strerror(ret)); } // Set anonymous credentials... if (_cert.empty() || _key.empty()) { if (CLIENT == _type) { log_v2::tls()->info("TLS: using anonymous client credentials"); ret = gnutls_credentials_set(session, GNUTLS_CRD_ANON, _cred.client); } else { log_v2::tls()->info("TLS: using anonymous server credentials"); ret = gnutls_credentials_set(session, GNUTLS_CRD_ANON, _cred.server); } } // ... or certificate credentials. else { log_v2::tls()->info("TLS: using certificates as credentials"); ret = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, _cred.cert); if (SERVER == _type) gnutls_certificate_server_set_request(session, GNUTLS_CERT_REQUEST); } if (ret != GNUTLS_E_SUCCESS) { log_v2::tls()->error("TLS: could not set credentials: {}", gnutls_strerror(ret)); throw msg_fmt("TLS: could not set credentials: {}", gnutls_strerror(ret)); } } /** * Load TLS parameters. */ void params::load() { // Certificate-based. if (!_cert.empty() && !_key.empty()) { // Initialize credentials. int ret; ret = gnutls_certificate_allocate_credentials(&_cred.cert); if (ret != GNUTLS_E_SUCCESS) { log_v2::tls()->error("TLS: credentials allocation failed: {}", gnutls_strerror(ret)); throw msg_fmt("TLS: credentials allocation failed: {}", gnutls_strerror(ret)); } gnutls_certificate_set_dh_params(_cred.cert, dh_params); _init = true; // Load certificate files. ret = gnutls_certificate_set_x509_key_file( _cred.cert, _cert.c_str(), _key.c_str(), GNUTLS_X509_FMT_PEM); if (ret != GNUTLS_E_SUCCESS) { log_v2::tls()->error("TLS: could not load certificate ({}, {}): {}", _cert, _key, gnutls_strerror(ret)); throw msg_fmt("TLS: could not load certificate: {}", gnutls_strerror(ret)); } if (!_ca.empty()) { // Load certificate. ret = gnutls_certificate_set_x509_trust_file(_cred.cert, _ca.c_str(), GNUTLS_X509_FMT_PEM); if (ret <= 0) { log_v2::tls()->error( "TLS: could not load trusted Certificate Authority's certificate " "'{}': {}", _ca, gnutls_strerror(ret)); throw msg_fmt( "TLS: could not load trusted Certificate Authority's certificate: " "{}", gnutls_strerror(ret)); } } } // Anonymous. else _init_anonymous(); } /** * @brief Reset parameters to their default values. * * Parameters are changed back to the default anonymous mode without * compression. */ void params::reset() { _clean(); } /** * @brief Set certificates to use for connection encryption. * * Two encryption mode are provided : anonymous and certificate-based. * If you want to use certificates for encryption, call this function * with the name of the PEM-encoded public certificate (cert) and the * private key (key). * * @param[in] cert The path to the PEM-encoded public certificate. * @param[in] key The path to the PEM-encoded private key. */ void params::set_cert(std::string const& cert, std::string const& key) { _cert = cert; _key = key; } /** * @brief Set the compression mode (on/off). * * Determines whether or not the encrypted stream should also be * compressed using the Deflate algorithm. This kind of compression * usually works well on text or other compressible data. The * compression algorithm, may be useful in high bandwidth TLS tunnels, * and in cases where network usage has to be minimized. As a drawback, * compression increases latency. * * @param[in] compress true if the stream should be compressed, false * otherwise. */ void params::set_compression(bool compress) { _compress = compress; } /** * @brief Set the hostname. * * If this parameter is set, certificate verify peers use this hostname rather * than the common name of the certificate. * * @param[in] tls_hostname the name of common name on the certificate. */ void params::set_tls_hostname(std::string const& tls_hostname) { _tls_hostname = tls_hostname; } /** * @brief Set the trusted CA certificate. * * If this parameter is set, certificate checking will be performed on * the connection against this CA certificate. * * @param[in] ca_cert The path to the PEM-encoded public certificate of * the trusted Certificate Authority. */ void params::set_trusted_ca(std::string const& ca_cert) { _ca = ca_cert; } /** * @brief Check if the peer's certificate is valid. * * Check if the certificate invalid or revoked or untrusted or * insecure. In those case, the connection should not be trusted. If no * certificate is used for this connection or no trusted CA has been * set, the method will return false. * * @param[in] session Session on which checks will be performed. */ void params::validate_cert(gnutls_session_t session) { if (!_ca.empty()) { int ret; uint32_t status; if (!_tls_hostname.empty()) { log_v2::tls()->info( "TLS: common name '{}' used for certificate verification", _tls_hostname); ret = gnutls_certificate_verify_peers3(session, _tls_hostname.c_str(), &status); } else { log_v2::tls()->info( "TLS: Server hostname used for certificate verification"); ret = gnutls_certificate_verify_peers2(session, &status); } if (ret != GNUTLS_E_SUCCESS) { log_v2::tls()->error( "TLS: certificate verification failed , assuming invalid " "certificate: {}", gnutls_strerror(ret)); throw msg_fmt( "TLS: certificate verification failed, assuming invalid certificate: " "{}", gnutls_strerror(ret)); } else if (status & GNUTLS_CERT_INVALID) { log_v2::tls()->error("TLS: peer certificate is invalid"); throw msg_fmt("TLS: peer certificate is invalid"); } else if (status & GNUTLS_CERT_REVOKED) { log_v2::tls()->error("TLS: peer certificate was revoked"); throw msg_fmt("TLS: peer certificate was revoked"); } else if (status & GNUTLS_CERT_SIGNER_NOT_FOUND) { log_v2::tls()->error( "TLS: peer certificate was not issued by a trusted authority"); throw msg_fmt( "TLS: peer certificate was not issued by a trusted authority"); } else if (status & GNUTLS_CERT_INSECURE_ALGORITHM) { log_v2::tls()->error( "TLS: peer certificate is using an insecure algorithm that cannot be " "trusted"); throw msg_fmt( "TLS: peer certificate is using an insecure algorithm that cannot be " "trusted"); } } } /** * @brief Clean the params instance. * * All allocated ressources will be released. */ void params::_clean() { if (_init) { if (_cert.empty() || _key.empty()) { if (CLIENT == _type) gnutls_anon_free_client_credentials(_cred.client); else gnutls_anon_free_server_credentials(_cred.server); } else gnutls_certificate_free_credentials(_cred.cert); _init = false; } } /** * Initialize anonymous credentials. */ void params::_init_anonymous() { int ret; if (CLIENT == _type) ret = gnutls_anon_allocate_client_credentials(&_cred.client); else ret = gnutls_anon_allocate_server_credentials(&_cred.server); if (ret != GNUTLS_E_SUCCESS) { log_v2::tls()->error("TLS: anonymous credentials initialization failed: {}", gnutls_strerror(ret)); throw msg_fmt("TLS: anonymous credentials initialization failed: {}", gnutls_strerror(ret)); } if (_type != CLIENT) gnutls_anon_set_server_dh_params(_cred.server, dh_params); _init = true; }
33.03871
80
0.647335
7f872e524a56490cc8fea1da694a27bdc9480b4a
296
cpp
C++
main.cpp
RoliSoft/Obfuscation-Tunnel
cbd31a1c80a7bd5b51057e1a976628727fc8987e
[ "BSD-2-Clause" ]
11
2020-09-15T11:59:41.000Z
2022-02-11T16:49:08.000Z
main.cpp
RoliSoft/Obfuscation-Tunnel
cbd31a1c80a7bd5b51057e1a976628727fc8987e
[ "BSD-2-Clause" ]
2
2021-11-13T12:38:01.000Z
2021-12-06T01:38:07.000Z
main.cpp
RoliSoft/Obfuscation-Tunnel
cbd31a1c80a7bd5b51057e1a976628727fc8987e
[ "BSD-2-Clause" ]
2
2021-08-12T07:43:16.000Z
2021-08-23T00:12:20.000Z
#include "factory.cpp" int main(int argc, char* argv[]) { signal(SIGINT, sig_handler); struct session session; int ret = parse_arguments(argc, argv, &session); if (ret == EXIT_SUCCESS || ret == EXIT_FAILURE) { return ret; } return run_session(&session); }
17.411765
52
0.618243
7f8da4f6e297a835989c59cdb729061244ed91ea
401
cpp
C++
vjezbe3/zadatak2/main.cpp
Miillky/objektno_orijentirano_programiranje
b41fe690c25a73acd09aff5606524b9e43f0b38a
[ "MIT" ]
null
null
null
vjezbe3/zadatak2/main.cpp
Miillky/objektno_orijentirano_programiranje
b41fe690c25a73acd09aff5606524b9e43f0b38a
[ "MIT" ]
null
null
null
vjezbe3/zadatak2/main.cpp
Miillky/objektno_orijentirano_programiranje
b41fe690c25a73acd09aff5606524b9e43f0b38a
[ "MIT" ]
null
null
null
// Prošlu strukturu i funkcije implementirajte u zasebnoj datoteci zaglavlja i implementacije(kompleksniBroj.hpp i KompleksniBroj.cpp) // U glavnoj datoteci includajte vašu datoteku i prikažite korištenje strukture i pripadnih funkcija. #include <iostream> #include "KompleksniBroj.hpp" int main(){ prikaziKompleksniBroj(23.3, 67.2); std::cout << zbrojiKompleksneBrojeve(23.3, 67.2).zbroj; }
40.1
134
0.783042
7f91fcd150dfc74048f2f3e4c806d85457f6bb95
50
hpp
C++
include/JsonLoader.hpp
0x0015/CP2DG
ae919b15dc06631171116b927ff46d7d98da4dd9
[ "MIT" ]
2
2021-10-06T03:11:06.000Z
2022-01-06T18:53:43.000Z
include/JsonLoader.hpp
0x0015/CP2DG
ae919b15dc06631171116b927ff46d7d98da4dd9
[ "MIT" ]
null
null
null
include/JsonLoader.hpp
0x0015/CP2DG
ae919b15dc06631171116b927ff46d7d98da4dd9
[ "MIT" ]
null
null
null
#pragma once #include "JsonLoader/JsonLoader.hpp"
16.666667
36
0.8
7f94b0353c36e3bed4d29bfca747840bde03bc43
9,396
cpp
C++
test/test_core_estimator.cpp
accosmin/libnan
a47c28f22df2c0943697dccb007de946090c7705
[ "MIT" ]
null
null
null
test/test_core_estimator.cpp
accosmin/libnan
a47c28f22df2c0943697dccb007de946090c7705
[ "MIT" ]
null
null
null
test/test_core_estimator.cpp
accosmin/libnan
a47c28f22df2c0943697dccb007de946090c7705
[ "MIT" ]
null
null
null
#include <fstream> #include <utest/utest.h> #include "fixture/enum.h" #include <nano/core/stream.h> #include <nano/core/estimator.h> using namespace nano; static auto to_string(const estimator_t& estimator) { std::ostringstream stream; UTEST_REQUIRE_NOTHROW(estimator.write(stream)); UTEST_REQUIRE(stream); return stream.str(); } static auto check_stream(const estimator_t& estimator) { { std::ofstream stream; UTEST_CHECK_THROW(estimator.write(stream), std::runtime_error); } string_t str; { std::ostringstream stream; UTEST_CHECK_NOTHROW(estimator.write(stream)); str = stream.str(); } { estimator_t xestimator; std::istringstream stream(str); UTEST_CHECK_NOTHROW(xestimator.read(stream)); } { estimator_t xestimator; std::ifstream stream; UTEST_CHECK_THROW(xestimator.read(stream), std::runtime_error); } { std::ostringstream ostream; UTEST_CHECK_NOTHROW(::nano::write(ostream, estimator)); estimator_t xestimator; std::istringstream istream(ostream.str()); UTEST_CHECK_NOTHROW(::nano::read(istream, xestimator)); return xestimator; } } UTEST_BEGIN_MODULE(test_core_estimator) UTEST_CASE(string) { for (const auto& string : {std::string{}, std::string("stream strings")}) { std::ostringstream ostream; UTEST_REQUIRE_NOTHROW(::nano::write(ostream, string)); UTEST_REQUIRE(ostream); const auto ostring = ostream.str(); UTEST_CHECK_EQUAL(ostring.size(), string.size() + 4); std::string istring; std::istringstream istream(ostring); UTEST_REQUIRE(istream); UTEST_REQUIRE_NOTHROW(::nano::read(istream, istring)); UTEST_REQUIRE(istream); UTEST_CHECK_EQUAL(string, istring); std::string ifstring; std::ifstream ifstream; UTEST_REQUIRE(ifstream); UTEST_REQUIRE_NOTHROW(::nano::read(ifstream, ifstring)); UTEST_REQUIRE(!ifstream); } } UTEST_CASE(vector) { const auto vector = std::vector<int32_t>{2, 3}; std::ostringstream ostream; UTEST_REQUIRE_NOTHROW(::nano::write(ostream, vector)); UTEST_REQUIRE(ostream); const auto ostring = ostream.str(); UTEST_CHECK_EQUAL(ostring.size(), 4U * vector.size() + 8U); std::vector<int32_t> ivector; std::istringstream istream(ostring); UTEST_REQUIRE(istream); UTEST_REQUIRE_NOTHROW(::nano::read(istream, ivector)); UTEST_REQUIRE(istream); UTEST_CHECK_EQUAL(vector, ivector); { std::ifstream ifstream; UTEST_REQUIRE(ifstream); UTEST_REQUIRE_NOTHROW(::nano::read(ifstream, ivector)); UTEST_REQUIRE(!ifstream); } { std::ofstream ofstream; UTEST_REQUIRE(ofstream); UTEST_REQUIRE_NOTHROW(::nano::write(ofstream, ivector)); UTEST_REQUIRE(!ofstream); } } UTEST_CASE(estimator_default) { const auto estimator = estimator_t{}; UTEST_CHECK_EQUAL(estimator.major_version(), ::nano::major_version); UTEST_CHECK_EQUAL(estimator.minor_version(), ::nano::minor_version); UTEST_CHECK_EQUAL(estimator.patch_version(), ::nano::patch_version); } UTEST_CASE(estimator_read_const) { auto estimator = estimator_t{}; auto str = to_string(estimator); UTEST_REQUIRE_EQUAL(str.size(), size_t(3 * 4 + 8)); std::istringstream stream(str); UTEST_REQUIRE_NOTHROW(estimator.read(stream)); UTEST_REQUIRE(stream); UTEST_REQUIRE_EQUAL(static_cast<size_t>(stream.tellg()), str.size()); UTEST_CHECK_EQUAL(estimator.major_version(), ::nano::major_version); UTEST_CHECK_EQUAL(estimator.minor_version(), ::nano::minor_version); UTEST_CHECK_EQUAL(estimator.patch_version(), ::nano::patch_version); } UTEST_CASE(estimator_read_major) { auto estimator = estimator_t{}; auto str = to_string(estimator); UTEST_REQUIRE_EQUAL(str.size(), size_t(3 * 4 + 8)); reinterpret_cast<int32_t*>(const_cast<char*>(str.data()))[0] = ::nano::major_version - 1; // NOLINT std::istringstream stream(str); UTEST_REQUIRE_NOTHROW(estimator.read(stream)); UTEST_REQUIRE(stream); UTEST_REQUIRE_EQUAL(static_cast<size_t>(stream.tellg()), str.size()); UTEST_CHECK_EQUAL(estimator.major_version(), ::nano::major_version - 1); UTEST_CHECK_EQUAL(estimator.minor_version(), ::nano::minor_version - 0); UTEST_CHECK_EQUAL(estimator.patch_version(), ::nano::patch_version - 0); } UTEST_CASE(estimator_read_minor) { auto estimator = estimator_t{}; auto str = to_string(estimator); UTEST_REQUIRE_EQUAL(str.size(), size_t(3 * 4 + 8)); reinterpret_cast<int32_t*>(const_cast<char*>(str.data()))[1] = ::nano::minor_version - 2; // NOLINT std::istringstream stream(str); UTEST_REQUIRE_NOTHROW(estimator.read(stream)); UTEST_REQUIRE(stream); UTEST_REQUIRE_EQUAL(static_cast<size_t>(stream.tellg()), str.size()); UTEST_CHECK_EQUAL(estimator.major_version(), ::nano::major_version - 0); UTEST_CHECK_EQUAL(estimator.minor_version(), ::nano::minor_version - 2); UTEST_CHECK_EQUAL(estimator.patch_version(), ::nano::patch_version - 0); } UTEST_CASE(estimator_read_patch) { auto estimator = estimator_t{}; auto str = to_string(estimator); UTEST_REQUIRE_EQUAL(str.size(), size_t(3 * 4 + 8)); reinterpret_cast<int32_t*>(const_cast<char*>(str.data()))[2] = ::nano::patch_version - 3; // NOLINT std::istringstream stream(str); UTEST_REQUIRE_NOTHROW(estimator.read(stream)); UTEST_REQUIRE(stream); UTEST_REQUIRE_EQUAL(static_cast<size_t>(stream.tellg()), str.size()); UTEST_CHECK_EQUAL(estimator.major_version(), ::nano::major_version - 0); UTEST_CHECK_EQUAL(estimator.minor_version(), ::nano::minor_version - 0); UTEST_CHECK_EQUAL(estimator.patch_version(), ::nano::patch_version - 3); } UTEST_CASE(estimator_write_fail) { const auto estimator = estimator_t{}; std::ofstream stream; UTEST_CHECK_THROW(estimator.write(stream), std::runtime_error); } UTEST_CASE(estimator_read_fail_major) { auto estimator = estimator_t{}; auto str = to_string(estimator); reinterpret_cast<int32_t*>(const_cast<char*>(str.data()))[0] = ::nano::major_version + 1; // NOLINT std::istringstream stream(str); UTEST_REQUIRE_THROW(estimator.read(stream), std::runtime_error); } UTEST_CASE(estimator_read_fail_minor) { auto estimator = estimator_t{}; auto str = to_string(estimator); reinterpret_cast<int32_t*>(const_cast<char*>(str.data()))[1] = ::nano::minor_version + 1; // NOLINT std::istringstream stream(str); UTEST_REQUIRE_THROW(estimator.read(stream), std::runtime_error); } UTEST_CASE(estimator_read_fail_patch) { auto estimator = estimator_t{}; auto str = to_string(estimator); reinterpret_cast<int32_t*>(const_cast<char*>(str.data()))[2] = ::nano::patch_version + 1; // NOLINT std::istringstream stream(str); UTEST_REQUIRE_THROW(estimator.read(stream), std::runtime_error); } UTEST_CASE(no_parameters) { const auto check_params = [] (const estimator_t& estimator) { UTEST_CHECK(estimator.parameters().empty()); }; auto estimator = estimator_t{}; check_params(estimator); const auto* const pname = "nonexistent_param_name"; const auto sname = string_t{"unknown_param_name"}; UTEST_CHECK_THROW(estimator.parameter(pname), std::runtime_error); UTEST_CHECK_THROW(estimator.parameter(sname), std::runtime_error); UTEST_CHECK_THROW(const_cast<const estimator_t&>(estimator).parameter(pname), std::runtime_error); // NOLINT UTEST_CHECK_THROW(const_cast<const estimator_t&>(estimator).parameter(sname), std::runtime_error); // NOLINT UTEST_CHECK(estimator.parameter_if(pname) == nullptr); UTEST_CHECK(estimator.parameter_if(sname) == nullptr); UTEST_CHECK(const_cast<const estimator_t&>(estimator).parameter_if(pname) == nullptr); // NOLINT UTEST_CHECK(const_cast<const estimator_t&>(estimator).parameter_if(sname) == nullptr); // NOLINT check_params(check_stream(estimator)); } UTEST_CASE(parameters) { const auto eparam = parameter_t::make_enum("eparam", enum_type::type3); const auto iparam = parameter_t::make_integer("iparam", 1, LE, 5, LE, 9); const auto fparam = parameter_t::make_scalar_pair("fparam", 1.0, LT, 2.0, LE, 2.0, LT, 5.0); const auto check_params = [&] (const estimator_t& estimator) { UTEST_CHECK_EQUAL(estimator.parameters().size(), 3U); UTEST_CHECK_EQUAL(estimator.parameter("eparam"), eparam); UTEST_CHECK_EQUAL(estimator.parameter("iparam"), iparam); UTEST_CHECK_EQUAL(estimator.parameter("fparam"), fparam); }; auto estimator = estimator_t{}; UTEST_CHECK_NOTHROW(estimator.register_parameter(eparam)); UTEST_CHECK_NOTHROW(estimator.register_parameter(iparam)); UTEST_CHECK_NOTHROW(estimator.register_parameter(fparam)); check_params(estimator); check_params(check_stream(estimator)); UTEST_CHECK_THROW(estimator.register_parameter(eparam), std::runtime_error); UTEST_CHECK_THROW(estimator.register_parameter(iparam), std::runtime_error); UTEST_CHECK_THROW(estimator.register_parameter(fparam), std::runtime_error); check_params(estimator); check_params(check_stream(estimator)); } UTEST_END_MODULE()
32.4
112
0.70083
7f94c3b7cd19f83bf8b6492a094d92257be28f5e
718
cpp
C++
stable.cpp
okosan/AStar
867da5417a97cafd620db9016c8b0efb399b139c
[ "MIT" ]
4
2016-11-11T10:50:07.000Z
2021-04-01T10:06:51.000Z
stable.cpp
okosan/AStar
867da5417a97cafd620db9016c8b0efb399b139c
[ "MIT" ]
1
2020-02-11T15:47:43.000Z
2020-02-11T15:47:43.000Z
stable.cpp
okosan/AStar
867da5417a97cafd620db9016c8b0efb399b139c
[ "MIT" ]
1
2017-10-23T07:24:55.000Z
2017-10-23T07:24:55.000Z
#include "stable.h" void xfBeep(int freq, int duration) { std::printf ("beeping!!!"); } bool xfBetween(double val, double val1, double val2) { if (val1<val2) { if ((val >= val1) && (val <= val2)) return true; return false; } else { if ((val >= val2) && (val <= val1)) return true; return false; } } bool xfBetweenExcl(double val, double val1, double val2) { if (val1<val2) { if ((val > val1) && (val < val2)) return true; return false; } else { if ((val > val2) && (val < val1)) return true; return false; } }
17.95
57
0.448468
7f967881b38f927953ac0ffa7aca6fae3a2413f8
663
cpp
C++
Programming-Contest/Number Theory/BSGS.cpp
ar-pavel/Code-Library
2d1b952231c1059bbf98d85d2c23fd8fb21b455c
[ "MIT" ]
null
null
null
Programming-Contest/Number Theory/BSGS.cpp
ar-pavel/Code-Library
2d1b952231c1059bbf98d85d2c23fd8fb21b455c
[ "MIT" ]
null
null
null
Programming-Contest/Number Theory/BSGS.cpp
ar-pavel/Code-Library
2d1b952231c1059bbf98d85d2c23fd8fb21b455c
[ "MIT" ]
null
null
null
/* Shnak's Baby-Step-giant-Step Algorithm a^x = b (mod m) return the power x where a , b , m given */ #define mod 100000007 ll solve (ll a, ll b, ll m) { ll n = (ll) sqrt (m + .0) + 1 , an = 1 , curr ; rep(i,n) an = (an * a) % m; map<ll,ll> vals; curr = an ; For(i,n){ if ( !vals.count(curr) ) vals[ curr ] = i; curr = (curr * an) % m; } ll ans = mod ; curr = b ; rep(i,n+1){ if ( vals.count(curr) ) { ans = min( ans , vals[ curr ] * n - i ); // finding the minimum solution //if (ans < m) return ans; // return any solution } curr = (curr * a) % m; } return ans ; //return -1; // if no solution cant be found }
21.387097
76
0.523379
7f99b358e33664d4255b10c28de67d0b5d3f8ca5
6,590
cc
C++
chrome/browser/chromeos/status/clock_menu_button.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-02-20T14:25:04.000Z
2019-12-13T13:58:28.000Z
chrome/browser/chromeos/status/clock_menu_button.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-07-25T09:37:22.000Z
2017-08-04T07:18:56.000Z
chrome/browser/chromeos/status/clock_menu_button.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2020-01-12T00:55:53.000Z
2020-11-04T06:36:41.000Z
// Copyright (c) 2011 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. #include "chrome/browser/chromeos/status/clock_menu_button.h" #include "base/i18n/time_formatting.h" #include "base/string_util.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/status/status_area_host.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" #include "content/common/notification_details.h" #include "content/common/notification_source.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/canvas.h" #include "ui/gfx/font.h" #include "unicode/datefmt.h" namespace chromeos { // Amount of slop to add into the timer to make sure we're into the next minute // when the timer goes off. const int kTimerSlopSeconds = 1; ClockMenuButton::ClockMenuButton(StatusAreaHost* host) : StatusAreaButton(host, this) { // Add as SystemAccess observer. We update the clock if timezone changes. SystemAccess::GetInstance()->AddObserver(this); CrosLibrary::Get()->GetPowerLibrary()->AddObserver(this); // Start monitoring the kUse24HourClock preference. if (host->GetProfile()) { // This can be NULL in the login screen. registrar_.Init(host->GetProfile()->GetPrefs()); registrar_.Add(prefs::kUse24HourClock, this); } UpdateTextAndSetNextTimer(); } ClockMenuButton::~ClockMenuButton() { CrosLibrary::Get()->GetPowerLibrary()->RemoveObserver(this); SystemAccess::GetInstance()->RemoveObserver(this); } void ClockMenuButton::UpdateTextAndSetNextTimer() { UpdateText(); // Try to set the timer to go off at the next change of the minute. We don't // want to have the timer go off more than necessary since that will cause // the CPU to wake up and consume power. base::Time now = base::Time::Now(); base::Time::Exploded exploded; now.LocalExplode(&exploded); // Often this will be called at minute boundaries, and we'll actually want // 60 seconds from now. int seconds_left = 60 - exploded.second; if (seconds_left == 0) seconds_left = 60; // Make sure that the timer fires on the next minute. Without this, if it is // called just a teeny bit early, then it will skip the next minute. seconds_left += kTimerSlopSeconds; timer_.Start(base::TimeDelta::FromSeconds(seconds_left), this, &ClockMenuButton::UpdateTextAndSetNextTimer); } void ClockMenuButton::UpdateText() { base::Time time(base::Time::Now()); // If the profie is present, check the use 24-hour clock preference. const bool use_24hour_clock = host_->GetProfile() && host_->GetProfile()->GetPrefs()->GetBoolean(prefs::kUse24HourClock); if (use_24hour_clock) { SetText(UTF16ToWide(base::TimeFormatTimeOfDayWithHourClockType( time, base::k24HourClock))); } else { // Remove the am/pm field if it's present. scoped_ptr<icu::DateFormat> formatter( icu::DateFormat::createTimeInstance(icu::DateFormat::kShort)); icu::UnicodeString time_string; icu::FieldPosition ampm_field(icu::DateFormat::kAmPmField); formatter->format( static_cast<UDate>(time.ToDoubleT() * 1000), time_string, ampm_field); int ampm_length = ampm_field.getEndIndex() - ampm_field.getBeginIndex(); if (ampm_length) { int begin = ampm_field.getBeginIndex(); // Doesn't include any spacing before the field. if (begin) begin--; time_string.removeBetween(begin, ampm_field.getEndIndex()); } string16 time_string16 = string16(time_string.getBuffer(), static_cast<size_t>(time_string.length())); SetText(UTF16ToWide(time_string16)); } SetTooltipText(UTF16ToWide(base::TimeFormatShortDate(time))); SchedulePaint(); } //////////////////////////////////////////////////////////////////////////////// // ClockMenuButton, NotificationObserver implementation: void ClockMenuButton::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type == NotificationType::PREF_CHANGED) { std::string* pref_name = Details<std::string>(details).ptr(); if (*pref_name == prefs::kUse24HourClock) { UpdateText(); } } } //////////////////////////////////////////////////////////////////////////////// // ClockMenuButton, ui::MenuModel implementation: int ClockMenuButton::GetItemCount() const { // If options dialog is unavailable, don't count a separator and configure // menu item. return host_->ShouldOpenButtonOptions(this) ? 3 : 1; } ui::MenuModel::ItemType ClockMenuButton::GetTypeAt(int index) const { // There's a separator between the current date and the menu item to open // the options menu. return index == 1 ? ui::MenuModel::TYPE_SEPARATOR: ui::MenuModel::TYPE_COMMAND; } string16 ClockMenuButton::GetLabelAt(int index) const { if (index == 0) return base::TimeFormatFriendlyDate(base::Time::Now()); return l10n_util::GetStringUTF16(IDS_STATUSBAR_CLOCK_OPEN_OPTIONS_DIALOG); } bool ClockMenuButton::IsEnabledAt(int index) const { // The 1st item is the current date, which is disabled. return index != 0; } void ClockMenuButton::ActivatedAt(int index) { host_->OpenButtonOptions(this); } /////////////////////////////////////////////////////////////////////////////// // ClockMenuButton, PowerLibrary::Observer implementation: void ClockMenuButton::SystemResumed() { UpdateText(); } /////////////////////////////////////////////////////////////////////////////// // ClockMenuButton, SystemAccess::Observer implementation: void ClockMenuButton::TimezoneChanged(const icu::TimeZone& timezone) { UpdateText(); } //////////////////////////////////////////////////////////////////////////////// // ClockMenuButton, views::ViewMenuDelegate implementation: void ClockMenuButton::RunMenu(views::View* source, const gfx::Point& pt) { if (!clock_menu_.get()) clock_menu_.reset(new views::Menu2(this)); else clock_menu_->Rebuild(); clock_menu_->UpdateStates(); clock_menu_->RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT); } //////////////////////////////////////////////////////////////////////////////// // ClockMenuButton, views::View implementation: void ClockMenuButton::OnLocaleChanged() { UpdateText(); } } // namespace chromeos
35.240642
80
0.667527
7f9b48ea988e27f03c7214538543556df8cbbc24
4,133
cpp
C++
deps/MFEM/ComputeFemMassMatrix1/ComputeFemMassMatrixMfem.cpp
kailaix/AdFem.jl
77eabfeedb297570a42d1f26575c59f0712796d9
[ "MIT" ]
47
2020-10-18T01:33:11.000Z
2022-03-16T00:13:24.000Z
deps/MFEM/ComputeFemMassMatrix1/ComputeFemMassMatrixMfem.cpp
kailaix/AdFem.jl
77eabfeedb297570a42d1f26575c59f0712796d9
[ "MIT" ]
10
2020-10-19T03:51:31.000Z
2022-03-22T23:38:46.000Z
deps/MFEM/ComputeFemMassMatrix1/ComputeFemMassMatrixMfem.cpp
kailaix/AdFem.jl
77eabfeedb297570a42d1f26575c59f0712796d9
[ "MIT" ]
11
2020-11-05T11:34:16.000Z
2022-03-03T19:30:09.000Z
#include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/platform/default/logging.h" #include "tensorflow/core/framework/shape_inference.h" #include<cmath> // Signatures for GPU kernels here using namespace tensorflow; #include "ComputeFemMassMatrixMfem.h" REGISTER_OP("ComputeFemMassMatrixMfem") .Input("rho : double") .Output("indices : int64") .Output("vv : double") .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) { shape_inference::ShapeHandle rho_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &rho_shape)); c->set_output(0, c->Matrix(-1,2)); c->set_output(1, c->Vector(-1)); return Status::OK(); }); REGISTER_OP("ComputeFemMassMatrixMfemGrad") .Input("grad_vv : double") .Input("indices : int64") .Input("vv : double") .Input("rho : double") .Output("grad_rho : double"); /*-------------------------------------------------------------------------------------*/ class ComputeFemMassMatrixMfemOp : public OpKernel { private: public: explicit ComputeFemMassMatrixMfemOp(OpKernelConstruction* context) : OpKernel(context) { } void Compute(OpKernelContext* context) override { DCHECK_EQ(1, context->num_inputs()); const Tensor& rho = context->input(0); const TensorShape& rho_shape = rho.shape(); DCHECK_EQ(rho_shape.dims(), 1); // extra check // create output shape int N = mmesh.ngauss * mmesh.elem_ndof * mmesh.elem_ndof; TensorShape indices_shape({N,2}); TensorShape vv_shape({N}); // create output tensor Tensor* indices = NULL; OP_REQUIRES_OK(context, context->allocate_output(0, indices_shape, &indices)); Tensor* vv = NULL; OP_REQUIRES_OK(context, context->allocate_output(1, vv_shape, &vv)); // get the corresponding Eigen tensors for data access auto rho_tensor = rho.flat<double>().data(); auto indices_tensor = indices->flat<int64>().data(); auto vv_tensor = vv->flat<double>().data(); // implement your forward function here // TODO: MFEM::ComputeFemMassMatrix1_forward(indices_tensor, vv_tensor, rho_tensor); } }; REGISTER_KERNEL_BUILDER(Name("ComputeFemMassMatrixMfem").Device(DEVICE_CPU), ComputeFemMassMatrixMfemOp); class ComputeFemMassMatrixMfemGradOp : public OpKernel { private: public: explicit ComputeFemMassMatrixMfemGradOp(OpKernelConstruction* context) : OpKernel(context) { } void Compute(OpKernelContext* context) override { const Tensor& grad_vv = context->input(0); const Tensor& indices = context->input(1); const Tensor& vv = context->input(2); const Tensor& rho = context->input(3); const TensorShape& grad_vv_shape = grad_vv.shape(); const TensorShape& indices_shape = indices.shape(); const TensorShape& vv_shape = vv.shape(); const TensorShape& rho_shape = rho.shape(); DCHECK_EQ(grad_vv_shape.dims(), 1); DCHECK_EQ(indices_shape.dims(), 2); DCHECK_EQ(vv_shape.dims(), 1); DCHECK_EQ(rho_shape.dims(), 1); // extra check // int m = Example.dim_size(0); // create output shape TensorShape grad_rho_shape(rho_shape); // create output tensor Tensor* grad_rho = NULL; OP_REQUIRES_OK(context, context->allocate_output(0, grad_rho_shape, &grad_rho)); // get the corresponding Eigen tensors for data access auto rho_tensor = rho.flat<double>().data(); auto grad_vv_tensor = grad_vv.flat<double>().data(); auto indices_tensor = indices.flat<int64>().data(); auto vv_tensor = vv.flat<double>().data(); auto grad_rho_tensor = grad_rho->flat<double>().data(); // implement your backward function here // TODO: grad_rho->flat<double>().setZero(); MFEM::ComputeFemMassMatrix1_backward(grad_rho_tensor, grad_vv_tensor, vv_tensor, rho_tensor); } }; REGISTER_KERNEL_BUILDER(Name("ComputeFemMassMatrixMfemGrad").Device(DEVICE_CPU), ComputeFemMassMatrixMfemGradOp);
28.503448
113
0.66586
7f9ca1a35e2ae5f8187a902da1f17182140c90ad
364
cpp
C++
src/codepulsar/pulsar/Parser.cpp
FireTheLost/JPulse
1c462ef4c605bd844a4a5fb9a28a4e91233286be
[ "MIT" ]
null
null
null
src/codepulsar/pulsar/Parser.cpp
FireTheLost/JPulse
1c462ef4c605bd844a4a5fb9a28a4e91233286be
[ "MIT" ]
null
null
null
src/codepulsar/pulsar/Parser.cpp
FireTheLost/JPulse
1c462ef4c605bd844a4a5fb9a28a4e91233286be
[ "MIT" ]
null
null
null
#include "Parser.h" Pulsar::Parser::Parser(std::string sourceCode) { this->sourceCode = sourceCode; } void Pulsar::Parser::parse() { Pulsar::Lexer lexer = Lexer(this->sourceCode); this->tokens = lexer.tokenize(); this->errors = lexer.getErrors(); if (this->errors->hasError()) return; Pulsar::TokenDisassembler::display(this->tokens); }
24.266667
53
0.67033