hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
d8125a64d6924506b9204f640e33bf63d6afaa7c
7,145
cc
C++
src/pixloc/main.cc
kstenschke/pixloc
041ba39a0a89149eba08e59689b77355ed6c652f
[ "BSD-3-Clause" ]
2
2019-03-04T20:41:03.000Z
2019-12-23T20:21:34.000Z
src/pixloc/main.cc
kstenschke/pixloc
041ba39a0a89149eba08e59689b77355ed6c652f
[ "BSD-3-Clause" ]
null
null
null
src/pixloc/main.cc
kstenschke/pixloc
041ba39a0a89149eba08e59689b77355ed6c652f
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2019, Kay Stenschke 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 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 <X11/Xlib.h> #include <cstdio> #include <cstring> #include <iostream> #include "config.h" #include "external/clara.hpp" #include "pixloc/helper/strings.h" #include "cli_options.h" #include "pixloc/models/pixel_scanner.h" using namespace clara; /** * @param argc Amount of arguments received * @param argv Array of arguments received, argv[0] is name and path of executable */ int main(int argc, char **argv) { std::string mode; std::string from; std::string range; std::string color; std::string amount; std::string bitmask; std::string tolerance; std::string step; bool show_help = false; // Use clara CLI options parser auto clara_parser = Opt(mode, "mode")["-m"]["--mode"]("see usage examples for available modes").required() | Opt(from, "from")["-f"]["--from"]("starting coordinate").required() | Opt(range, "range")["-r"]["--range"]("amount of pixels to be scanned").required() | Opt(color, "color")["-c"]["--color"]("rgb color value to find").optional() | Opt(amount, "amount")["-a"]["--amount"]("amount of consecutive pixels of given color to find").optional() | Opt(bitmask, "bitmask")["-b"]["--bitmask"]("pixel mask to find (* = given color, _ = other colors)").optional() | Opt(tolerance, "tolerance")["-t"]["--tolerance"]("optional: color tolerance").optional() | Opt(step, "step")["-s"]["--step"]("optional: interval step size of horizontal/vertical find mode").optional() | Help(show_help); auto clara_result = clara_parser.parse(Args(argc, reinterpret_cast<const char *const *>(argv))); if (!clara_result) { std::cerr << "Error in command line: " << clara_result.errorMessage() << std::endl; return 1; } if (show_help) { std::cout << "pixloc version " << Pixloc_VERSION_MAJOR << "." << Pixloc_VERSION_MINOR << "\n" "Copyright (c) 2019 Kay Stenschke\n\n"; clara_parser.writeToStream(std::cout); std::cout << pixloc::clioptions::kUsageExamples; return 0; } // Resolve options Display *display; unsigned short mode_id, amount_px = 1, color_tolerance = 0, step_size = 1; int from_x = -1, from_y = -1, range_x = -1, range_y = -1, red = -1, green = -1, blue = -1; bool is_bitmask_mode, is_trace_mode; try { display = XOpenDisplay(nullptr); if (!display) throw "Failed to open default display.\n"; mode_id = pixloc::clioptions::GetModeIdFromName(mode); is_trace_mode = pixloc::clioptions::IsTraceMode(mode_id); bool use_mouse_for_from = strcmp(from.c_str(), "mouse")==0; if (use_mouse_for_from || mode_id==pixloc::clioptions::kModeIdTraceMouse) { // Get current mouse position XEvent event{}; XQueryPointer(display, RootWindow(display, DefaultScreen(display)), &event.xbutton.root, &event.xbutton.window, &event.xbutton.x_root, &event.xbutton.y_root, &from_x, &from_y, &event.xbutton.state); if (is_trace_mode) { printf("x=%d; y=%d;\n", from_x, from_y); if (mode_id==pixloc::clioptions::kModeIdTraceMouse) return 0; } } if (!use_mouse_for_from && !helper::strings::ResolveNumericTupel(from, from_x, from_y)) throw "Valid from coordinate is required."; pixloc::clioptions::ResolveScanningRange(mode_id, range, range_x, range_y); pixloc::clioptions::ValidateScanningRectangle(from_x, from_y, range_x, range_y, display); if (pixloc::clioptions::ModeRequiresAmountPx(mode_id) && (amount_px = static_cast<unsigned short>(helper::strings::ToInt(amount, 0)))==0) throw "Valid amount of pixels to find is required."; is_bitmask_mode = pixloc::clioptions::IsBitmaskMode(mode_id); if (pixloc::clioptions::ModeRequiresBitmask(mode_id)) pixloc::clioptions::ValidateBitmask(bitmask, range_x, range_y); if (pixloc::clioptions::ModeRequiresColor(mode_id)) pixloc::clioptions::ResolveRgbColor(color, red, green, blue); if (!tolerance.empty()) { if (!helper::strings::IsNumeric(tolerance)) throw "Invalid color tolerance value given."; color_tolerance = static_cast<unsigned short>(helper::strings::ToInt(tolerance, 0)); } if (!step.empty()) { if (!helper::strings::IsNumeric(step)) throw "Invalid step size given."; step_size = static_cast<unsigned short>(helper::strings::ToInt(step, 1)); if (step_size < 1) step_size = 1; if (step_size > ((range_x > 1) ? range_x : range_y)) throw "Step size exceeds range."; } } catch (char const *exception) { std::cerr << "Error: " << exception << "\nFor help run: pixloc -h\n\n"; return -1; } // Scan pixels auto *scanner = new pixloc::PixelScanner( display, static_cast<unsigned short>(from_x), static_cast<unsigned short>(from_y), static_cast<unsigned short>(range_x), static_cast<unsigned short>(range_y), static_cast<unsigned short>(red * 256), static_cast<unsigned short>(green * 256), static_cast<unsigned short>(blue * 256), static_cast<unsigned short>(color_tolerance * 256)); if (mode_id == pixloc::clioptions::kModeIdTraceMainColor) { scanner->TraceMainColor(); } else if (is_bitmask_mode) { if (is_trace_mode) scanner->TraceBitmask(); else std::cout << scanner->FindBitmask(bitmask); } else { int location = scanner->ScanUniaxial(amount_px, step_size, is_trace_mode); if (!is_trace_mode) std::cout << (range_y < 2 ? "x:" : "y:" ) << location << ";"; } delete scanner; return 0; }
41.540698
121
0.675997
kstenschke
d81564e8fbc1548223fa8e2fabc020737e35a4d1
10,973
cpp
C++
src/CConcatFind.cpp
colinw7/CConcat
59a653c7730a5fbebe6fd8df8ec47c94d4467c6c
[ "MIT" ]
null
null
null
src/CConcatFind.cpp
colinw7/CConcat
59a653c7730a5fbebe6fd8df8ec47c94d4467c6c
[ "MIT" ]
null
null
null
src/CConcatFind.cpp
colinw7/CConcat
59a653c7730a5fbebe6fd8df8ec47c94d4467c6c
[ "MIT" ]
null
null
null
#include <CConcatFind.h> #include <CCommentParser.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> class CommentParser : public CCommentParser { public: CommentParser(CConcatFind *find) : find_(find) { } void put_comment(char c) override { if (find_->isComment()) find_->addLineChar(c); } void put_normal(char c) override { if (find_->isNoComment()) find_->addLineChar(c); } int getChar() const override { return find_->getChar(); } private: CConcatFind *find_ { nullptr }; }; //--- int main(int argc, char **argv) { auto showUsage = []() { std::cerr << "Usage:"; std::cerr << " CConcatFind [-l|L] [-n] [-i] [-e] [-f] [-R] [-g] [-w] <file> <pattern>\n"; std::cerr << "\n"; std::cerr << " -l|L : list files containing pattern\n"; std::cerr << " -n : show line number\n"; std::cerr << " -i : no case matching\n"; std::cerr << " -e <exts> : only match files with specified extensions\n"; std::cerr << " -f : match only filename\n"; std::cerr << " -fp <pattern> : file pattern\n"; std::cerr << " -d : match only directory\n"; std::cerr << " -R <root> : root directory of file\n"; std::cerr << " -g : glob match\n"; std::cerr << " -x : regexp match\n"; std::cerr << " -w : word match\n"; std::cerr << " -comment : match comments only\n"; std::cerr << " -nocomment : match no comments only\n"; std::cerr << " -h|--help : help for usage\n"; }; std::string filename; std::string filePattern; std::string pattern; bool glob = false; bool regexp = false; bool nocase = false; bool matchWord = false; std::string root; CConcatFind::Strings extensions; bool list = false; bool showFile = true; bool number = false; bool matchFile = false; bool matchDir = false; bool comment = false; bool nocomment = false; bool parse_args = true; for (int i = 1; i < argc; i++) { if (parse_args && argv[i][0] == '-') { std::string arg = &argv[i][1]; if (arg == "comment") { comment = true; } else if (arg == "nocomment" || arg == "no_comment") { nocomment = true; } else if (arg == "nofile" || arg == "no_file") { showFile = false; } else if (arg == "L" || arg == "l") list = true; else if (arg == "n") number = true; else if (arg == "i") nocase = true; else if (arg == "e") { ++i; if (i < argc) { std::string exts = argv[i]; std::string ext; for (int j = 0; j < exts.size(); ++j) { if (exts[j] == '|') { if (ext != "") extensions.push_back(ext); ext = ""; } else ext += exts[j]; } if (ext != "") extensions.push_back(ext); } } else if (arg == "f") { matchFile = true; } else if (arg == "fp") { ++i; if (i < argc) { filePattern = argv[i]; } } else if (arg == "d") { matchDir = true; } else if (arg == "R") { ++i; if (i < argc) root = std::string(argv[i]) + "/"; } else if (arg == "g") { glob = true; } else if (arg == "x") { regexp = true; } else if (arg == "w") { matchWord = true; } else if (arg == "h" || arg == "-help") { showUsage(); exit(0); } else if (arg == "-") { parse_args = false; } else { std::cerr << "Invalid option " << argv[i] << std::endl; exit(1); } } else { if (filename == "") filename = argv[i]; else if (pattern == "") pattern = argv[i]; else { showUsage(); exit(1); } } } if (filename == "") { showUsage(); exit(1); } CConcatFind find; find.setFilename(filename); find.setFilePattern(filePattern); find.setPattern (pattern); find.setRegExp (regexp); find.setGlob (glob); find.setNoCase (nocase); find.setMatchWord(matchWord); find.setList (list); find.setShowFile (showFile); find.setNumber (number); find.setExtensions (extensions); find.setMatchFile (matchFile); find.setMatchDir (matchDir); find.setRoot (root); find.setComment (comment); find.setNoComment (nocomment); if (! find.exec()) exit(1); return 0; } CConcatFind:: CConcatFind() { } CConcatFind:: ~CConcatFind() { delete commentParser_; } void CConcatFind:: setFilePattern(const std::string &s) { filePattern_.str = s; if (filePattern_.str != "") { filePattern_.glob = CGlob("*" + filePattern_.str + "*"); filePattern_.regexp = CRegExp(".*" + filePattern_.str + ".*"); } else { filePattern_.glob = CGlob(); filePattern_.regexp = CRegExp(); } filePattern_.lstr = filePattern_.str; } void CConcatFind:: setPattern(const std::string &s) { pattern_.str = s; pattern_.glob = CGlob("*" + pattern_.str + "*"); pattern_.regexp = CRegExp(".*" + pattern_.str + ".*"); if (isNoCase()) pattern_.lstr = toLower(pattern_.str); else pattern_.lstr = pattern_.str; } bool CConcatFind:: exec() { if (isComment() || isNoComment()) commentParser_ = new CommentParser(this); //--- // open file fp_ = fopen(filename().c_str(), "rb"); if (! fp_) { std::cerr << "Can't Open Input File " << filename() << std::endl; return false; } //--- // read concat id line char buffer[256]; int no = fread(buffer, 1, 10, fp_); if (no != 10 || strncmp(buffer, "CONCAT_ID=", 10) != 0) { std::cerr << "Invalid Concat File " << filename() << std::endl; exit(1); } if (! readId(fp_)) exit(1); //--- // read id uint len = id_.size(); no = fread(buffer, 1, len, fp_); if (no != len || strncmp(buffer, id_.c_str(), len) != 0) { std::cerr << "Invalid Concat File " << filename() << std::endl; exit(1); } //--- // read file chars while (true) { // get file name setCurrentFile(""); int c = getChar(); while (c != '\n' && c != EOF) { currentFile_ += char(c); c = getChar(); } if (c != '\n') { std::cerr << "Invalid Concat File " << filename() << std::endl; exit(1); } //--- // check extensions bool skip = false; if (! extensions().empty()) { std::string::size_type p = currentFile().rfind('.'); std::string ext; if (p != std::string::npos) ext = currentFile().substr(p + 1); skip = true; for (int j = 0; j < extensions().size(); ++j) { if (extensions()[j] == ext) { skip = false; break; } } } //--- // check file name match if (filePattern_.str != "") { if (! checkFilePattern(currentFile())) skip = true; } //--- // check file match bool found = false; if (isMatchFile()) { if (checkPattern(currentFile())) { if (! isMatchDir()) std::cout << root() << currentFile() << std::endl; else std::cout << root() << getDirName() << std::endl; found = true; } skip = true; } //--- // process lines currentLine_ = 1; line_ = ""; bytesWritten_ = 0; while ((c = getChar()) != EOF) { if (checkMatch(c)) break; if (c == '\n') { if (! skip && ! found) { bool found1 = checkLine(line_); if (isList() && found1) { if (! isMatchDir()) std::cout << root() << currentFile() << std::endl; else std::cout << root() << getDirName() << std::endl; found = true; } } if (isComment() || isNoComment()) commentParser_->processCChar(c); line_ = ""; ++currentLine_; } else { if (isComment() || isNoComment()) commentParser_->processCChar(c); else addLineChar(c); } } checkMatch(EOF); if (c == EOF) break; } fclose(fp_); return true; } std::string CConcatFind:: getDirName() const { auto filename = currentFile(); auto p = filename.rfind('/'); if (p != std::string::npos) return filename.substr(0, p); return filename; } void CConcatFind:: addLineChar(char c) { if (c == '\n') c = ' '; line_ += c; } int CConcatFind:: getChar() const { return fgetc(fp_); } bool CConcatFind:: checkLine(const std::string &line) const { if (! checkPattern(line)) return false; if (! isList()) { if (isShowFile()) std::cout << root() << currentFile() << ":"; if (isNumber()) std::cout << currentLine() << ": " << line << std::endl; else std::cout << line << std::endl; } return true; } bool CConcatFind:: checkPattern(const std::string &str) const { return checkPatternData(str, pattern_); } bool CConcatFind:: checkFilePattern(const std::string &str) const { return checkPatternData(str, filePattern_); } bool CConcatFind:: checkPatternData(const std::string &str, const PatternData &data) { if (data.isGlob) return data.glob.compare(str); if (data.isRegExp) return data.regexp.find(str); if (! data.noCase) { auto p = str.find(data.str); if (p == std::string::npos) return false; if (data.matchWord) { if (! isWord(str, p, data.str.size())) return false; } } else { std::string lstr = toLower(str); auto p = lstr.find(data.lstr); if (p == std::string::npos) return false; if (data.matchWord) { if (! isWord(lstr, p, data.lstr.size())) return false; } } return true; } bool CConcatFind:: checkMatch(int c) { if (c != id_[checkPos_]) { bytesWritten_ += checkPos_; if (c != EOF) ++bytesWritten_; checkPos_ = 0; checkBuffer_ = ""; return false; } checkBuffer_ += char(c); ++checkPos_; uint len = id_.size(); if (checkPos_ >= len) { checkPos_ = 0; return true; } return false; } std::string CConcatFind:: toLower(const std::string &str) { std::string lstr = str; for (size_t i = 0; i < str.size(); ++i) lstr[i] = tolower(lstr[i]); return lstr; } bool CConcatFind:: isWord(const std::string &str, int p, int len) { // word characters [A-Z],[a-z],[0-9]_ int pl = p - 1; if (pl > 0 && isalnum(str[pl]) || str[pl] == '_') return false; int pr = p + len; if (str[pr] != '\0' && isalnum(str[pr]) || str[pr] == '_') return false; return true; }
18.984429
94
0.504238
colinw7
d8197aab074d8788bddf671d07a4e2f95f146e8b
462
cpp
C++
leetcode/422. Valid Word Square/s1.cpp
zhuohuwu0603/leetcode_cpp_lzl124631x
6a579328810ef4651de00fde0505934d3028d9c7
[ "Fair" ]
787
2017-05-12T05:19:57.000Z
2022-03-30T12:19:52.000Z
leetcode/422. Valid Word Square/s1.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
8
2020-03-16T05:55:38.000Z
2022-03-09T17:19:17.000Z
leetcode/422. Valid Word Square/s1.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
247
2017-04-30T15:07:50.000Z
2022-03-30T09:58:57.000Z
// OJ: https://leetcode.com/problems/valid-word-square/ // Author: github.com/lzl124631x // Time: O(MN) // Space: O(1) class Solution { public: bool validWordSquare(vector<string>& words) { for (int i = 0, M = words.size(); i < M; ++i) { for (int j = 0, N = words[i].size(); j < N; ++j) { if (j >= M || i >= words[j].size() || words[i][j] != words[j][i]) return false; } } return true; } };
30.8
95
0.493506
zhuohuwu0603
d81a6be099ed31ab5eece1cd31421cee7f039029
13,287
cpp
C++
platforms/cuda/src/CudaTestKernels.cpp
WangXinyan940/openmm-nlexample
0f336b965fca580787565a325f1760b00413c1f6
[ "MIT" ]
null
null
null
platforms/cuda/src/CudaTestKernels.cpp
WangXinyan940/openmm-nlexample
0f336b965fca580787565a325f1760b00413c1f6
[ "MIT" ]
null
null
null
platforms/cuda/src/CudaTestKernels.cpp
WangXinyan940/openmm-nlexample
0f336b965fca580787565a325f1760b00413c1f6
[ "MIT" ]
null
null
null
#include "CudaTestKernels.h" #include "CudaTestKernelSources.h" #include "openmm/internal/ContextImpl.h" #include "openmm/cuda/CudaBondedUtilities.h" #include "openmm/cuda/CudaNonbondedUtilities.h" #include "openmm/cuda/CudaForceInfo.h" #include "openmm/cuda/CudaParameterSet.h" #include "CudaKernelSources.h" #include <map> #include <set> #include <iostream> #include <utility> using namespace TestPlugin; using namespace OpenMM; using namespace std; class CudaCalcTestForceInfo : public CudaForceInfo { public: CudaCalcTestForceInfo(const TestForce& force) : force(force) { } bool areParticlesIdentical(int particle1, int particle2) { double p1, p2; p1 = force.getParticleParameter(particle1); p2 = force.getParticleParameter(particle2); return (p1 == p2); } int getNumParticleGroups() { int natom = force.getNumParticles(); return natom; } void getParticlesInGroup(int index, vector<int>& particles) { particles.resize(1); particles[0] = index; } bool areGroupsIdentical(int group1, int group2) { double p1 = force.getParticleParameter(group1); double p2 = force.getParticleParameter(group2); return (p1 == p2); } private: const TestForce& force; }; CudaCalcTestForceKernel::~CudaCalcTestForceKernel() { } void CudaCalcTestForceKernel::initialize(const System& system, const TestForce& force) { cu.setAsCurrent(); int numParticles = system.getNumParticles(); int elementSize = cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float); ifPBC = force.usesPeriodicBoundaryConditions(); cutoff = force.getCutoffDistance(); // vector<vector<int>> exclusions; exclusions.resize(numParticles); for(int ii=0;ii<numParticles;ii++){ exclusions[ii].push_back(ii); } for(int ii=0;ii<force.getNumExclusions();ii++){ int p1, p2; force.getExclusionParticles(ii, p1, p2); exclusions[p1].push_back(p2); exclusions[p2].push_back(p1); } // Inititalize CUDA objects. // if noPBC if (cu.getUseDoublePrecision()){ vector<double> parameters; for(int ii=0;ii<numParticles;ii++){ double prm = force.getParticleParameter(ii); parameters.push_back(prm); } params.initialize(cu, numParticles, elementSize, "params"); params.upload(parameters); } else { vector<float> parameters; for(int ii=0;ii<numParticles;ii++){ float prm = force.getParticleParameter(ii); parameters.push_back(prm); } params.initialize(cu, numParticles, elementSize, "params"); params.upload(parameters); } numexclusions = force.getNumExclusions(); if (numexclusions > 0){ vector<int> exidx0, exidx1; exidx0.resize(force.getNumExclusions()); exidx1.resize(force.getNumExclusions()); for(int ii=0;ii<force.getNumExclusions();ii++){ int p1, p2; force.getExclusionParticles(ii, p1, p2); exidx0[ii] = p1; exidx1[ii] = p2; } expairidx0.initialize(cu, exidx0.size(), sizeof(int), "exindex0"); expairidx1.initialize(cu, exidx1.size(), sizeof(int), "exindex1"); expairidx0.upload(exidx0); expairidx1.upload(exidx1); } if (!ifPBC){ map<string, string> defines; CUmodule module = cu.createModule(CudaKernelSources::vectorOps + CudaTestKernelSources::noPBCForce, defines); calcTestForceNoPBCKernel = cu.getKernel(module, "calcTestForceNoPBC"); calcExcludeForceNoPBCKernel = cu.getKernel(module, "calcExcludeForceNoPBC"); vector<int> idx0; vector<int> idx1; idx0.resize(numParticles*(numParticles-1)/2); idx1.resize(numParticles*(numParticles-1)/2); int count = 0; for(int ii=0;ii<numParticles;ii++){ for(int jj=ii+1;jj<numParticles;jj++){ idx0[count] = ii; idx1[count] = jj; count += 1; } } pairidx0.initialize(cu, numParticles*(numParticles-1)/2, sizeof(int), "index0"); pairidx1.initialize(cu, numParticles*(numParticles-1)/2, sizeof(int), "index1"); pairidx0.upload(idx0); pairidx1.upload(idx1); } else { cu.getNonbondedUtilities().addInteraction(true, true, true, cutoff, exclusions, "", force.getForceGroup()); set<pair<int, int>> tilesWithExclusions; for (int atom1 = 0; atom1 < (int) exclusions.size(); ++atom1) { int x = atom1/CudaContext::TileSize; for (int atom2 : exclusions[atom1]) { int y = atom2/CudaContext::TileSize; tilesWithExclusions.insert(make_pair(max(x, y), min(x, y))); } } vector<int> indexAtomVec; indexAtomVec.resize(numParticles); indexAtom.initialize(cu, numParticles, sizeof(int), "indexAtom"); indexAtom.upload(indexAtomVec); map<string, string> pbcDefines; pbcDefines["NUM_ATOMS"] = cu.intToString(numParticles); pbcDefines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms()); pbcDefines["NUM_BLOCKS"] = cu.intToString(cu.getNumAtomBlocks()); pbcDefines["THREAD_BLOCK_SIZE"] = cu.intToString(cu.getNonbondedUtilities().getForceThreadBlockSize()); pbcDefines["TILE_SIZE"] = cu.intToString(CudaContext::TileSize); int numExclusionTiles = tilesWithExclusions.size(); pbcDefines["NUM_TILES_WITH_EXCLUSIONS"] = cu.intToString(numExclusionTiles); int numContexts = cu.getPlatformData().contexts.size(); int startExclusionIndex = cu.getContextIndex()*numExclusionTiles/numContexts; int endExclusionIndex = (cu.getContextIndex()+1)*numExclusionTiles/numContexts; pbcDefines["FIRST_EXCLUSION_TILE"] = cu.intToString(startExclusionIndex); pbcDefines["LAST_EXCLUSION_TILE"] = cu.intToString(endExclusionIndex); pbcDefines["USE_PERIODIC"] = "1"; pbcDefines["USE_CUTOFF"] = "1"; pbcDefines["USE_EXCLUSIONS"] = ""; pbcDefines["USE_SYMMETRIC"] = "1"; pbcDefines["INCLUDE_FORCES"] = "1"; pbcDefines["INCLUDE_ENERGY"] = "1"; pbcDefines["CUTOFF"] = cu.doubleToString(cutoff); // macro for short-range // CUmodule PBCModule = cu.createModule(CudaKernelSources::vectorOps + CudaTestKernelSources::PBCForce, pbcDefines); // calcTestForcePBCKernel = cu.getKernel(PBCModule, "calcTestForcePBC"); CUmodule PBCModule = cu.createModule(CudaKernelSources::vectorOps + CudaTestKernelSources::PBCForce, pbcDefines); calcTestForcePBCKernel = cu.getKernel(PBCModule, "computeNonbonded"); calcExclusionPBCKernel = cu.getKernel(PBCModule, "computeExclusion"); indexAtomKernel = cu.getKernel(PBCModule, "genIndexAtom"); } cu.addForce(new CudaCalcTestForceInfo(force)); hasInitializedKernel = true; } double CudaCalcTestForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { int numParticles = cu.getNumAtoms(); double energy = 0.0; if (ifPBC){ int paddedNumAtoms = cu.getPaddedNumAtoms(); CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); int startTileIndex = nb.getStartTileIndex(); int numTileIndices = nb.getNumTiles(); unsigned int maxTiles = nb.getInteractingTiles().getSize(); int maxSinglePairs = nb.getSinglePairs().getSize(); void* args[] = { &cu.getForce().getDevicePointer(), // unsigned long long* __restrict__ forceBuffers, &cu.getEnergyBuffer().getDevicePointer(), // mixed* __restrict__ energyBuffer, &cu.getPosq().getDevicePointer(), // const real4* __restrict__ posq, &params.getDevicePointer(), // const real* __restrict__ params, &cu.getAtomIndexArray().getDevicePointer(), // const int* __restrict__ atomIndex, &nb.getExclusions().getDevicePointer(), // const tileflags* __restrict__ exclusions, &nb.getExclusionTiles().getDevicePointer(), // const int2* __restrict__ exclusionTiles, &startTileIndex, // unsigned int startTileIndex, &numTileIndices, // unsigned long long numTileIndices, &nb.getInteractingTiles().getDevicePointer(), // const int* __restrict__ tiles, &nb.getInteractionCount().getDevicePointer(), // const unsigned int* __restrict__ interactionCoun cu.getPeriodicBoxSizePointer(), // real4 periodicBoxSize cu.getInvPeriodicBoxSizePointer(), // real4 invPeriodicBoxS cu.getPeriodicBoxVecXPointer(), // real4 periodicBoxVecX cu.getPeriodicBoxVecYPointer(), // real4 periodicBoxVecY cu.getPeriodicBoxVecZPointer(), // real4 periodicBoxVecZ &maxTiles, // unsigned int maxTiles, &nb.getBlockCenters().getDevicePointer(), // const real4* __restrict__ blockCenter, &nb.getBlockBoundingBoxes().getDevicePointer(), // const real4* __restrict__ blockSize, &nb.getInteractingAtoms().getDevicePointer(), // const unsigned int* __restrict__ interactingAtom &maxSinglePairs, // unsigned int maxSinglePairs, &nb.getSinglePairs().getDevicePointer() // const int2* __restrict__ singlePairs }; cu.executeKernel(calcTestForcePBCKernel, args, nb.getNumForceThreadBlocks()*nb.getForceThreadBlockSize(), nb.getForceThreadBlockSize()); if (numexclusions > 0){ void* argSwitch[] = { &cu.getAtomIndexArray().getDevicePointer(), &indexAtom.getDevicePointer(), &numParticles }; cu.executeKernel(indexAtomKernel, argSwitch, numParticles); void* argsEx[] = { &cu.getForce().getDevicePointer(), // forceBuffers, &cu.getEnergyBuffer().getDevicePointer(), // energyBuffer, &cu.getPosq().getDevicePointer(), // posq, &params.getDevicePointer(), // params, &cu.getAtomIndexArray().getDevicePointer(), // atomIndex, &indexAtom.getDevicePointer(), // indexAtom, &expairidx0.getDevicePointer(), // exclusionidx1, &expairidx1.getDevicePointer(), // exclusionidx2, &numexclusions, // numExclusions, cu.getPeriodicBoxSizePointer(), // periodicBoxSize, cu.getInvPeriodicBoxSizePointer(), // invPeriodicBoxSize, cu.getPeriodicBoxVecXPointer(), // periodicBoxVecX, cu.getPeriodicBoxVecYPointer(), // periodicBoxVecY, cu.getPeriodicBoxVecZPointer() // periodicBoxVecZ }; cu.executeKernel(calcExclusionPBCKernel, argsEx, numexclusions); } } else { int paddedNumAtoms = cu.getPaddedNumAtoms(); void* args[] = { &cu.getEnergyBuffer().getDevicePointer(), &cu.getPosq().getDevicePointer(), &cu.getForce().getDevicePointer(), &params.getDevicePointer(), &cu.getAtomIndexArray().getDevicePointer(), &pairidx0.getDevicePointer(), &pairidx1.getDevicePointer(), &numParticles, &paddedNumAtoms }; cu.executeKernel(calcTestForceNoPBCKernel, args, numParticles*(numParticles-1)/2); if (numexclusions > 0){ void* args2[] = { &cu.getEnergyBuffer().getDevicePointer(), &cu.getPosq().getDevicePointer(), &cu.getForce().getDevicePointer(), &params.getDevicePointer(), &cu.getAtomIndexArray().getDevicePointer(), &expairidx0.getDevicePointer(), &expairidx1.getDevicePointer(), &numexclusions, &numParticles, &paddedNumAtoms }; cu.executeKernel(calcExcludeForceNoPBCKernel, args2, numexclusions); } } return energy; }
47.623656
144
0.582675
WangXinyan940
d820abb05e5cccc0c412ca7c15fae0b5889c45a6
3,529
hpp
C++
cplusplus/RCF/include/RCF/thread/posix_event.hpp
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
22
2015-05-18T07:04:36.000Z
2021-08-02T03:01:43.000Z
cplusplus/RCF/include/RCF/thread/posix_event.hpp
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
1
2017-08-31T22:13:57.000Z
2017-09-05T15:00:25.000Z
cplusplus/RCF/include/RCF/thread/posix_event.hpp
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
6
2015-06-06T07:16:12.000Z
2021-07-06T13:45:56.000Z
//****************************************************************************** // RCF - Remote Call Framework // // Copyright (c) 2005 - 2013, Delta V Software. All rights reserved. // http://www.deltavsoft.com // // RCF is distributed under dual licenses - closed source or GPL. // Consult your particular license for conditions of use. // // If you have not purchased a commercial license, you are using RCF // under GPL terms. // // Version: 2.0 // Contact: support <at> deltavsoft.com // //****************************************************************************** // // detail/posix_event.hpp // ~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef RCF_DETAIL_POSIX_EVENT_HPP #define RCF_DETAIL_POSIX_EVENT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #if defined(BOOST_HAS_PTHREADS) #include <boost/assert.hpp> #include <pthread.h> #include <errno.h> #include <RCF/thread/push_options.hpp> #include <sys/time.h> namespace RCF { namespace detail { class posix_event : private noncopyable { public: // Constructor. RCF_EXPORT posix_event(); // Destructor. ~posix_event() { ::pthread_cond_destroy(&cond_); } // Signal one waiting thread. template <typename Lock> void signal_one(Lock& lock) { BOOST_ASSERT(lock.locked()); (void)lock; ::pthread_cond_signal(&cond_); // Ignore EINVAL. } // Signal all waiting threads. template <typename Lock> void signal_all(Lock& lock) { BOOST_ASSERT(lock.locked()); (void)lock; ::pthread_cond_broadcast(&cond_); // Ignore EINVAL. } // Reset the event. template <typename Lock> void clear(Lock& lock) { BOOST_ASSERT(lock.locked()); (void)lock; } // Wait for the event to become signalled. template <typename Lock> void wait(Lock& lock) { // POSIX automatically unlocks and locks the mutex. BOOST_ASSERT(lock.locked()); ::pthread_cond_wait(&cond_, &lock.mutex().mutex_); // Ignore EINVAL. } template <typename Lock> bool timed_wait(Lock& lock, boost::uint32_t waitMs) { BOOST_ASSERT(lock.locked()); struct timeval tp = {0}; gettimeofday(&tp, NULL); // Convert from timeval to timespec. struct timespec ts = {0}; ts.tv_sec = tp.tv_sec; ts.tv_nsec = tp.tv_usec * 1000; // Add waitMs to current time. ts.tv_sec += (waitMs / 1000); boost::uint32_t remainderMs = waitMs % 1000; ts.tv_nsec += (remainderMs * 1000 * 1000); // Check for overflow in tv_nsec. if (ts.tv_nsec >= 1000*1000*1000) { BOOST_ASSERT(ts.tv_nsec < 2*1000*1000*1000); ts.tv_sec += 1; ts.tv_nsec -= 1000*1000*1000; } // POSIX automatically unlocks and locks the mutex. int ret = ::pthread_cond_timedwait(&cond_, &lock.mutex().mutex_, &ts); // Ignore EINVAL. if (ret == ETIMEDOUT) { return false; } return true; } // Signal the event. template <typename Lock> void notify_all(Lock& lock) { signal_all(lock); } protected: ::pthread_cond_t cond_; }; } // namespace detail } // namespace RCF #include <RCF/thread/pop_options.hpp> #endif // defined(BOOST_HAS_PTHREADS) #endif // RCF_DETAIL_POSIX_EVENT_HPP
22.767742
94
0.618305
ASMlover
d8211212f095c10cb7d9de126a936bfce4d71079
971
cpp
C++
SecondaryTreeIndexTest.cpp
spakai/index_search
75a39d536781cb3e2f91ffea496b003ca5c51ebf
[ "Apache-2.0" ]
null
null
null
SecondaryTreeIndexTest.cpp
spakai/index_search
75a39d536781cb3e2f91ffea496b003ca5c51ebf
[ "Apache-2.0" ]
null
null
null
SecondaryTreeIndexTest.cpp
spakai/index_search
75a39d536781cb3e2f91ffea496b003ca5c51ebf
[ "Apache-2.0" ]
null
null
null
#include "gmock/gmock.h" #include "SecondaryTreeIndex.h" #include "FileTable.h" using namespace testing; class SecondaryTreeIndexTest : public Test { public: FileTable ft; SecondaryTreeIndex index; void SetUp() override { ft.init("../csv/abnumber.csv"); index.buildIndex(ft, 0); } }; TEST_F(SecondaryTreeIndexTest,GetSizeofIndex) { ASSERT_THAT(index.size(), Eq(5)); } TEST_F(SecondaryTreeIndexTest,ExactMatchWhenExactMatchLookupIsCalled) { ASSERT_THAT(index.exactMatch("00605"), ElementsAre(0,1)); } TEST_F(SecondaryTreeIndexTest,BestMatchLookup) { ASSERT_THAT(index.bestMatch("006051"), ElementsAre(0,1)); } TEST_F(SecondaryTreeIndexTest,ExactMatchWhenBestMatchLookupIsCalled) { ASSERT_THAT(index.bestMatch("00605"), ElementsAre(0,1)); } TEST_F(SecondaryTreeIndexTest,AllMatchesLookup) { ASSERT_THAT(index.allMatches("006051"), ElementsAre(0,1,3)); }
26.243243
71
0.69413
spakai
d82341412f1d05f2ee915c5899a853d5c0a3814b
25,543
cpp
C++
Clerk/UI/Schedulers/SchedulerDialog.cpp
sergeylenkov/Clerk
b220864e89559207c5eeea113668891236fcbfb9
[ "MIT" ]
14
2016-11-01T15:48:02.000Z
2020-07-15T13:00:27.000Z
Clerk/UI/Schedulers/SchedulerDialog.cpp
sergeylenkov/Clerk
b220864e89559207c5eeea113668891236fcbfb9
[ "MIT" ]
29
2017-11-16T04:15:33.000Z
2021-12-22T07:15:42.000Z
Clerk/UI/Schedulers/SchedulerDialog.cpp
sergeylenkov/Clerk
b220864e89559207c5eeea113668891236fcbfb9
[ "MIT" ]
2
2018-08-15T15:25:11.000Z
2019-01-28T12:49:50.000Z
#include "SchedulerDialog.h" SchedulerDialog::SchedulerDialog(wxFrame *parent, const wxChar *title, int x, int y, int width, int height) : wxFrame(parent, -1, title, wxPoint(x, y), wxSize(width, height), wxDEFAULT_FRAME_STYLE & ~(wxRESIZE_BORDER | wxMAXIMIZE_BOX)) { SetBackgroundColour(wxColor(*wxWHITE)); this->SetSizeHints(wxDefaultSize, wxDefaultSize); this->SetIcon(wxICON(APP_ICON)); wxString allowedChars[13] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", ",", " " }; wxArrayString chars(13, allowedChars); wxTextValidator amountValidator(wxFILTER_INCLUDE_CHAR_LIST); amountValidator.SetIncludes(chars); int daysValue; int dayValue; int monthValue; int weekValue; wxIntegerValidator<int> daysValidator(&daysValue, wxNUM_VAL_DEFAULT); daysValidator.SetRange(1, 365); wxIntegerValidator<int> dayValidator(&dayValue, wxNUM_VAL_DEFAULT); dayValidator.SetRange(1, 31); wxIntegerValidator<int> weekValidator(&weekValue, wxNUM_VAL_DEFAULT); weekValidator.SetRange(1, 52); wxIntegerValidator<int> monthValidator(&monthValue, wxNUM_VAL_DEFAULT); monthValidator.SetRange(1, 12); wxBoxSizer *mainSizer = new wxBoxSizer(wxVERTICAL); mainPanel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); wxBoxSizer *panelSizer = new wxBoxSizer(wxVERTICAL); wxBoxSizer *horizontalSizer = new wxBoxSizer(wxHORIZONTAL); nameLabel = new wxStaticText(mainPanel, wxID_ANY, wxT("Name:"), wxDefaultPosition, wxSize(40, -1), 0); horizontalSizer->Add(nameLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); nameField = new wxTextCtrl(mainPanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0); horizontalSizer->Add(nameField, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5); panelSizer->Add(horizontalSizer, 0, wxALL | wxEXPAND, 5); wxBoxSizer *staticBoxSizer = new wxStaticBoxSizer(new wxStaticBox(mainPanel, wxID_ANY, wxT("Recurrence pattern")), wxHORIZONTAL); wxPanel *buttonsPanel = new wxPanel(mainPanel, wxID_ANY, wxDefaultPosition, wxSize(80, -1), wxTAB_TRAVERSAL); wxBoxSizer *buttonsSizer = new wxBoxSizer(wxVERTICAL); dailyButton = new wxRadioButton(buttonsPanel, wxID_ANY, wxT("Daily"), wxDefaultPosition, wxDefaultSize, 0); buttonsSizer->Add(dailyButton, 0, wxALL, 5); weeklyButton = new wxRadioButton(buttonsPanel, wxID_ANY, wxT("Weekly"), wxDefaultPosition, wxDefaultSize, 0); buttonsSizer->Add(weeklyButton, 0, wxALL, 5); monthlyButton = new wxRadioButton(buttonsPanel, wxID_ANY, wxT("Monthly"), wxDefaultPosition, wxDefaultSize, 0); buttonsSizer->Add(monthlyButton, 0, wxALL, 5); yearlyButton = new wxRadioButton(buttonsPanel, wxID_ANY, wxT("Yearly"), wxDefaultPosition, wxDefaultSize, 0); buttonsSizer->Add(yearlyButton, 0, wxALL, 5); buttonsPanel->SetSizer(buttonsSizer); buttonsPanel->Layout(); staticBoxSizer->Add(buttonsPanel, 0, wxALL, 5); wxStaticLine *staticLine = new wxStaticLine(mainPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_VERTICAL); staticBoxSizer->Add(staticLine, 0, wxEXPAND | wxALL, 5); patternPanel = new wxPanel(mainPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize); staticBoxSizer->Add(patternPanel, 1, wxEXPAND | wxALL, 5); patternSizer = new wxBoxSizer(wxVERTICAL); patternPanel->SetSizer(patternSizer); patternPanel->Layout(); patternSizer->Fit(patternPanel); panelSizer->Add(staticBoxSizer, 1, wxEXPAND | wxALL, 10); staticBoxSizer = new wxStaticBoxSizer(new wxStaticBox(this, wxID_ANY, wxT("Transaction")), wxVERTICAL); horizontalSizer = new wxBoxSizer(wxHORIZONTAL); fromLabel = new wxStaticText(mainPanel, wxID_ANY, wxT("From:"), wxDefaultPosition, wxSize(40, -1), 0); horizontalSizer->Add(fromLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); fromList = new wxBitmapComboBox(mainPanel, wxID_ANY, wxT(""), wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_READONLY); horizontalSizer->Add(fromList, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5); fromAmountField = new wxTextCtrl(mainPanel, wxID_ANY, wxT("1000"), wxDefaultPosition, wxSize(80, -1), wxTE_RIGHT, amountValidator); horizontalSizer->Add(fromAmountField, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); fromAmountLabel = new wxStaticText(mainPanel, wxID_ANY, wxT("RUB"), wxDefaultPosition, wxDefaultSize, 0); horizontalSizer->Add(fromAmountLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); staticBoxSizer->Add(horizontalSizer, 0, wxALL | wxEXPAND, 5); horizontalSizer = new wxBoxSizer(wxHORIZONTAL); toLabel = new wxStaticText(mainPanel, wxID_ANY, wxT("To:"), wxDefaultPosition, wxSize(40, -1), 0); toLabel->Wrap(-1); horizontalSizer->Add(toLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); toList = new wxBitmapComboBox(mainPanel, wxID_ANY, wxT(""), wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_READONLY); horizontalSizer->Add(toList, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5); toAmountField = new wxTextCtrl(mainPanel, wxID_ANY, wxT("1000"), wxDefaultPosition, wxSize(80, -1), wxTE_RIGHT, amountValidator); horizontalSizer->Add(toAmountField, 0, wxALL, 5); toAmountLabel = new wxStaticText(mainPanel, wxID_ANY, wxT("RUB"), wxDefaultPosition, wxDefaultSize, 0); horizontalSizer->Add(toAmountLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); staticBoxSizer->Add(horizontalSizer, 0, wxALL | wxEXPAND, 5); horizontalSizer = new wxBoxSizer(wxHORIZONTAL); tagsLabel = new wxStaticText(mainPanel, wxID_ANY, wxT("Tags:"), wxDefaultPosition, wxSize(40, -1), 0); horizontalSizer->Add(tagsLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); tagsField = new wxTextCtrl(mainPanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0); horizontalSizer->Add(tagsField, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5); staticBoxSizer->Add(horizontalSizer, 0, wxALL | wxEXPAND, 5); panelSizer->Add(staticBoxSizer, 1, wxEXPAND | wxALL, 10); horizontalSizer = new wxBoxSizer(wxHORIZONTAL); okButton = new wxButton(mainPanel, wxID_ANY, wxT("OK"), wxDefaultPosition, wxDefaultSize, 0); horizontalSizer->Add(okButton, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); cancelButton = new wxButton(mainPanel, wxID_ANY, wxT("Cancel"), wxDefaultPosition, wxDefaultSize, 0); horizontalSizer->Add(cancelButton, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); panelSizer->Add(horizontalSizer, 0, wxALIGN_RIGHT | wxALL, 5); // dailyPatternPanel = new wxPanel(patternPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); horizontalSizer = new wxBoxSizer(wxHORIZONTAL); wxStaticText *dailyPatternLabel = new wxStaticText(dailyPatternPanel, wxID_ANY, wxT("Every"), wxDefaultPosition, wxDefaultSize, 0); horizontalSizer->Add(dailyPatternLabel, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5); dailyDayField = new wxTextCtrl(dailyPatternPanel, wxID_ANY, wxT("1"), wxDefaultPosition, wxSize(40, -1), wxTE_RIGHT, daysValidator); horizontalSizer->Add(dailyDayField, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5); wxStaticText *daysLabel = new wxStaticText(dailyPatternPanel, wxID_ANY, wxT("days"), wxDefaultPosition, wxDefaultSize, 0); horizontalSizer->Add(daysLabel, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5); dailyPatternPanel->SetSizer(horizontalSizer); dailyPatternPanel->Layout(); horizontalSizer->Fit(dailyPatternPanel); patternSizer->Add(dailyPatternPanel, 0, wxALIGN_TOP | wxALL, 0); // weeklyPatternPanel = new wxPanel(patternPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); wxBoxSizer *verticalSizer = new wxBoxSizer(wxVERTICAL); horizontalSizer = new wxBoxSizer(wxHORIZONTAL); wxStaticText *m_staticText1011 = new wxStaticText(weeklyPatternPanel, wxID_ANY, wxT("Every"), wxDefaultPosition, wxDefaultSize, 0); horizontalSizer->Add(m_staticText1011, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5); weeklyWeekField = new wxTextCtrl(weeklyPatternPanel, wxID_ANY, wxT("1"), wxDefaultPosition, wxSize(40, -1), wxTE_RIGHT, weekValidator); horizontalSizer->Add(weeklyWeekField, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5); wxStaticText *m_staticText911 = new wxStaticText(weeklyPatternPanel, wxID_ANY, wxT("weeks on:"), wxDefaultPosition, wxDefaultSize, 0); horizontalSizer->Add(m_staticText911, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5); verticalSizer->Add(horizontalSizer, 0, wxALIGN_TOP | wxBOTTOM, 5); wxWrapSizer *wrapSizer = new wxWrapSizer(wxHORIZONTAL, wxWRAPSIZER_DEFAULT_FLAGS); mondayCheckBox = new wxRadioButton(weeklyPatternPanel, wxID_ANY, wxT("Monday"), wxDefaultPosition, wxDefaultSize, 0); wrapSizer->Add(mondayCheckBox, 0, wxALL, 5); tuesdayCheckBox = new wxRadioButton(weeklyPatternPanel, wxID_ANY, wxT("Tuesday"), wxDefaultPosition, wxDefaultSize, 0); wrapSizer->Add(tuesdayCheckBox, 0, wxALL, 5); wednesdayCheckBox = new wxRadioButton(weeklyPatternPanel, wxID_ANY, wxT("Wednesday"), wxDefaultPosition, wxDefaultSize, 0); wrapSizer->Add(wednesdayCheckBox, 0, wxALL, 5); thursdayCheckBox = new wxRadioButton(weeklyPatternPanel, wxID_ANY, wxT("Thursday"), wxDefaultPosition, wxDefaultSize, 0); wrapSizer->Add(thursdayCheckBox, 0, wxALL, 5); fridayCheckBox = new wxRadioButton(weeklyPatternPanel, wxID_ANY, wxT("Friday"), wxDefaultPosition, wxDefaultSize, 0); wrapSizer->Add(fridayCheckBox, 0, wxALL, 5); saturdayCheckBox = new wxRadioButton(weeklyPatternPanel, wxID_ANY, wxT("Saturday"), wxDefaultPosition, wxDefaultSize, 0); wrapSizer->Add(saturdayCheckBox, 0, wxALL, 5); sundayCheckBox = new wxRadioButton(weeklyPatternPanel, wxID_ANY, wxT("Sunday"), wxDefaultPosition, wxDefaultSize, 0); wrapSizer->Add(sundayCheckBox, 0, wxALL, 5); verticalSizer->Add(wrapSizer, 1, wxEXPAND, 5); weeklyPatternPanel->SetSizer(verticalSizer); weeklyPatternPanel->Layout(); wrapSizer->Fit(weeklyPatternPanel); patternSizer->Add(weeklyPatternPanel, 1, wxEXPAND | wxALL, 0); // monthlyPatternPanel = new wxPanel(patternPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); horizontalSizer = new wxBoxSizer(wxHORIZONTAL); wxStaticText *m_staticText912 = new wxStaticText(monthlyPatternPanel, wxID_ANY, wxT("Day"), wxDefaultPosition, wxDefaultSize, 0); horizontalSizer->Add(m_staticText912, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5); monthlyDayField = new wxTextCtrl(monthlyPatternPanel, wxID_ANY, wxT("1"), wxDefaultPosition, wxSize(40, -1), wxTE_RIGHT, dayValidator); horizontalSizer->Add(monthlyDayField, 0, wxLEFT | wxRIGHT, 5); wxStaticText *m_staticText1012 = new wxStaticText(monthlyPatternPanel, wxID_ANY, wxT("every"), wxDefaultPosition, wxDefaultSize, 0); horizontalSizer->Add(m_staticText1012, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5); monthlyMonthField = new wxTextCtrl(monthlyPatternPanel, wxID_ANY, wxT("1"), wxDefaultPosition, wxSize(40, -1), wxTE_RIGHT, monthValidator); horizontalSizer->Add(monthlyMonthField, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5); wxStaticText *m_staticText10121 = new wxStaticText(monthlyPatternPanel, wxID_ANY, wxT("month(s)"), wxDefaultPosition, wxDefaultSize, 0); horizontalSizer->Add(m_staticText10121, 0, wxALIGN_CENTER_VERTICAL | wxLEFT, 5); monthlyPatternPanel->SetSizer(horizontalSizer); monthlyPatternPanel->Layout(); horizontalSizer->Fit(monthlyPatternPanel); patternSizer->Add(monthlyPatternPanel, 0, wxALIGN_TOP | wxALL, 0); // yearlyPatternPanel = new wxPanel(patternPanel, wxID_ANY, wxDefaultPosition, wxSize(-1, -1), wxTAB_TRAVERSAL); horizontalSizer = new wxBoxSizer(wxHORIZONTAL); wxStaticText *m_staticText913 = new wxStaticText(yearlyPatternPanel, wxID_ANY, wxT("Every"), wxDefaultPosition, wxDefaultSize, 0); horizontalSizer->Add(m_staticText913, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5); yearlyDayField = new wxTextCtrl(yearlyPatternPanel, wxID_ANY, wxT("1"), wxDefaultPosition, wxSize(40, -1), wxTE_RIGHT, dayValidator); horizontalSizer->Add(yearlyDayField, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5); wxString months[] = { wxT("January"), wxT("February"), wxT("March"), wxT("April"), wxT("May"), wxT("June"), wxT("Jule"), wxT("August"), wxT("September"), wxT("October"), wxT("November"), wxT("December") }; yearlyMonthChoice = new wxComboBox(yearlyPatternPanel, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, 12, months, wxCB_READONLY); yearlyMonthChoice->SetSelection(0); horizontalSizer->Add(yearlyMonthChoice, 0, wxLEFT | wxRIGHT, 5); yearlyPatternPanel->SetSizer(horizontalSizer); yearlyPatternPanel->Layout(); horizontalSizer->Fit(yearlyPatternPanel); patternSizer->Add(yearlyPatternPanel, 0, wxALIGN_TOP | wxALL, 0); mainPanel->SetSizer(panelSizer); mainPanel->Layout(); panelSizer->Fit(mainPanel); mainSizer->Add(mainPanel, 1, wxEXPAND | wxALL, 0); this->SetSizer(mainSizer); this->Layout(); this->Centre(wxBOTH); tagsPopup = new TagsPopup(this); tagsPopup->OnSelectTag = std::bind(&SchedulerDialog::OnSelectTag, this); okButton->Bind(wxEVT_BUTTON, &SchedulerDialog::OnOK, this); cancelButton->Bind(wxEVT_BUTTON, &SchedulerDialog::OnCancel, this); fromList->Bind(wxEVT_COMBOBOX, &SchedulerDialog::OnFromAccountSelect, this); toList->Bind(wxEVT_COMBOBOX, &SchedulerDialog::OnToAccountSelect, this); fromAmountField->Bind(wxEVT_KILL_FOCUS, &SchedulerDialog::OnFromAmountKillFocus, this); toAmountField->Bind(wxEVT_KILL_FOCUS, &SchedulerDialog::OnToAmountKillFocus, this); tagsField->Bind(wxEVT_KEY_UP, &SchedulerDialog::OnTextChanged, this); tagsField->Bind(wxEVT_KILL_FOCUS, &SchedulerDialog::OnTagsKillFocus, this); dailyButton->Bind(wxEVT_RADIOBUTTON, &SchedulerDialog::OnPatternSelect, this); weeklyButton->Bind(wxEVT_RADIOBUTTON, &SchedulerDialog::OnPatternSelect, this); monthlyButton->Bind(wxEVT_RADIOBUTTON, &SchedulerDialog::OnPatternSelect, this); yearlyButton->Bind(wxEVT_RADIOBUTTON, &SchedulerDialog::OnPatternSelect, this); Bind(wxEVT_CHAR_HOOK, &SchedulerDialog::OnKeyDown, this); fromValue = 0; toValue = 0; /*for (auto account : DataHelper::GetInstance().GetAccountsByType(AccountType::Receipt)) { accounts.push_back(account); } for (auto account : DataHelper::GetInstance().GetAccountsByType(AccountType::Deposit)) { accounts.push_back(account); } for (auto account : DataHelper::GetInstance().GetAccountsByType(AccountType::Virtual)) { accounts.push_back(account); } for (auto account : DataHelper::GetInstance().GetAccountsByType(AccountType::Expens)) { accounts.push_back(account); } for (auto account : DataHelper::GetInstance().GetAccountsByType(AccountType::Debt)) { accounts.push_back(account); }*/ UpdateFromList(); SelectFromAccount(0); UpdateToList(fromAccount); SelectToAccount(0); SelectPatternType(SchedulerType::Daily); SelectWeekday(1); nameField->SetFocus(); } SchedulerDialog::~SchedulerDialog() { delete tagsPopup; } void SchedulerDialog::SetScheduler(std::shared_ptr<SchedulerModel> scheduler) { this->scheduler = scheduler; /*nameField->SetValue(*scheduler->name); fromAmountField->SetValue(wxString::Format("%.2f", scheduler->fromAmount)); toAmountField->SetValue(wxString::Format("%.2f", scheduler->toAmount)); tagsField->SetValue(*scheduler->tags); if (scheduler->fromAccount) { for (unsigned int i = 0; i < fromAccounts.size(); i++) { if (scheduler->fromAccount->id == fromAccounts[i]->id) { SelectFromAccount(i); UpdateToList(fromAccounts[i]); break; } } } else { SelectFromAccount(0); } if (scheduler->toAccount) { for (unsigned int i = 0; i < toAccounts.size(); i++) { if (scheduler->toAccount->id == toAccounts[i]->id) { SelectToAccount(i); break; } } } else { SelectToAccount(0); } fromAmountField->SetFocus(); fromAmountField->SelectAll(); SelectPatternType(scheduler->type); if (scheduler->type == Scheduler::Type::Daily) { dailyDayField->SetValue(wxString::Format("%d", scheduler->day)); } if (scheduler->type == Scheduler::Type::Weekly) { weeklyWeekField->SetValue(wxString::Format("%d", scheduler->week)); SelectWeekday(scheduler->day); } if (scheduler->type == Scheduler::Type::Monthly) { monthlyDayField->SetValue(wxString::Format("%d", scheduler->day)); monthlyMonthField->SetValue(wxString::Format("%d", scheduler->month)); } if (scheduler->type == Scheduler::Type::Yearly) { yearlyDayField->SetValue(wxString::Format("%d", scheduler->day)); yearlyMonthChoice->SetSelection(scheduler->month); } nameField->SetFocus();*/ } void SchedulerDialog::UpdateFromList() { /*for (auto account : accounts) { if (account->type == Account::Type::Receipt || account->type == Account::Type::Deposit || account->type == Account::Type::Virtual) { int iconId = 0; if (account->iconId < DataHelper::GetInstance().accountsImageList->GetImageCount()) { iconId = account->iconId; } //fromList->Append(*account->name, DataHelper::GetInstance().accountsImageList->GetBitmap(iconId)); fromAccounts.push_back(account); } }*/ } void SchedulerDialog::UpdateToList(std::shared_ptr<AccountModel> account) { toList->Clear(); toAccounts.clear(); /*for (auto toAccount : accounts) { if (account->id == toAccount->id) { continue; } if (account->type == Account::Type::Receipt) { if (toAccount->type == Account::Type::Deposit) { int iconId = 0; if (toAccount->iconId < DataHelper::GetInstance().accountsImageList->GetImageCount()) { iconId = toAccount->iconId; } //toList->Append(*toAccount->name, DataHelper::GetInstance().accountsImageList->GetBitmap(iconId)); toAccounts.push_back(toAccount); } } else if (account->type == Account::Type::Deposit || account->type == Account::Type::Virtual) { if (toAccount->type == Account::Type::Deposit || toAccount->type == Account::Type::Expens || toAccount->type == Account::Type::Debt || toAccount->type == Account::Type::Virtual) { int iconId = 0; if (toAccount->iconId < DataHelper::GetInstance().accountsImageList->GetImageCount()) { iconId = toAccount->iconId; } toList->Append(toAccount->name, DataHelper::GetInstance().accountsImageList->GetBitmap(iconId)); toAccounts.push_back(toAccount); } } }*/ } void SchedulerDialog::SelectFromAccount(int index) { auto account = fromAccounts[index]; fromList->Select(index); //fromAmountLabel->SetLabel(account->currency->shortName); fromAccount = account; } void SchedulerDialog::SelectToAccount(int id) { auto account = toAccounts[id]; toList->Select(id); //toAmountLabel->SetLabel(*account->currency->shortName); toAccount = account; } void SchedulerDialog::SelectToAccount(std::shared_ptr<AccountModel> account) { for (unsigned int i = 0; i < toAccounts.size(); i++) { if (toAccounts[i]->id == account->id) { SelectToAccount(i); return; } } SelectToAccount(0); } void SchedulerDialog::OnFromAccountSelect(wxCommandEvent &event) { SelectFromAccount(fromList->GetSelection()); UpdateToList(fromAccount); SelectToAccount(toAccount); } void SchedulerDialog::OnToAccountSelect(wxCommandEvent &event) { SelectToAccount(toList->GetSelection()); } void SchedulerDialog::OnOK(wxCommandEvent &event) { /*scheduler->name = make_shared<wxString>(nameField->GetValue()); scheduler->fromAccount = fromAccounts[fromList->GetSelection()]; scheduler->toAccount = toAccounts[toList->GetSelection()]; scheduler->tags = make_shared<wxString>(tagsField->GetValue()); scheduler->type = type; double amountValue; wxString value = fromAmountField->GetValue(); value.Replace(" ", ""); value.Replace(",", "."); value.ToDouble(&amountValue); scheduler->fromAmount = amountValue; value = toAmountField->GetValue(); value.Replace(" ", ""); value.Replace(",", "."); value.ToDouble(&amountValue); scheduler->toAmount = amountValue; unsigned long intValue; if (type == Scheduler::Type::Daily) { dailyDayField->GetValue().ToULong(&intValue); scheduler->day = intValue; } if (type == Scheduler::Type::Weekly) { weeklyWeekField->GetValue().ToULong(&intValue); scheduler->week = intValue; scheduler->day = 1; if (mondayCheckBox->GetValue()) { scheduler->day = 1; } if (tuesdayCheckBox->GetValue()) { scheduler->day = 2; } if (wednesdayCheckBox->GetValue()) { scheduler->day = 3; } if (thursdayCheckBox->GetValue()) { scheduler->day = 4; } if (fridayCheckBox->GetValue()) { scheduler->day = 5; } if (saturdayCheckBox->GetValue()) { scheduler->day = 6; } if (sundayCheckBox->GetValue()) { scheduler->day = 7; } } if (type == Scheduler::Type::Monthly) { monthlyDayField->GetValue().ToULong(&intValue); scheduler->day = intValue; monthlyMonthField->GetValue().ToULong(&intValue); scheduler->month = intValue; } if (type == Scheduler::Type::Yearly) { yearlyDayField->GetValue().ToULong(&intValue); scheduler->day = intValue; scheduler->month = yearlyMonthChoice->GetSelection(); } //TODO moved method to interactor //scheduler->Save(); Close(); if (OnClose) { OnClose(); }*/ } void SchedulerDialog::OnCancel(wxCommandEvent &event) { Close(); } void SchedulerDialog::OnFromAmountKillFocus(wxFocusEvent &event) { event.Skip(); /*wxString stringAmount = this->ClearAmountValue(fromAmountField->GetValue()); fromAmountField->SetValue(stringAmount); int fromCurrencyId = fromAccounts[fromList->GetSelection()]->currency->id; int toCurrencyId = toAccounts[toList->GetSelection()]->currency->id; double val; toAmountField->GetValue().ToDouble(&val); if (val == 0 && fromCurrencyId == toCurrencyId) { toAmountField->SetValue(fromAmountField->GetValue()); }*/ } void SchedulerDialog::OnToAmountKillFocus(wxFocusEvent &event) { event.Skip(); wxString stringAmount = this->ClearAmountValue(toAmountField->GetValue()); toAmountField->SetValue(stringAmount); } void SchedulerDialog::OnTextChanged(wxKeyEvent &event) { if (event.GetKeyCode() == WXK_ESCAPE) { tagsPopup->Hide(); } else if (event.GetKeyCode() == WXK_UP) { tagsPopup->SelectPrev(); event.StopPropagation(); } else if (event.GetKeyCode() == WXK_DOWN) { tagsPopup->SelectNext(); } else if (event.GetKeyCode() == WXK_RETURN) { AddTag(); tagsPopup->Hide(); } else { wxStringTokenizer tokenizer(tagsField->GetValue(), ","); std::vector<wxString> tokens; while (tokenizer.HasMoreTokens()) { wxString token = tokenizer.GetNextToken().Trim(true).Trim(false); tokens.push_back(token); } if (!tokens.empty()) { //TODO auto tags = std::vector<std::shared_ptr<wxString>>(); //DataHelper::GetInstance().GetTagsBySearch(tokens.back()); if (!tokens.empty()) { //tagsPopup->Update(tags); wxPoint pos = tagsField->GetScreenPosition(); wxSize size = tagsField->GetSize(); tagsPopup->Position(wxPoint(pos.x - 200, pos.y - 200 + size.GetHeight()), wxSize(200, 200)); tagsPopup->Show(); } else { tagsPopup->Hide(); } } } event.Skip(); } void SchedulerDialog::OnTagsKillFocus(wxFocusEvent &event) { tagsPopup->Hide(); event.Skip(); } void SchedulerDialog::OnSelectTag() { AddTag(); tagsPopup->Hide(); } void SchedulerDialog::AddTag() { /*wxString tag = tagsPopup->GetSelectedTag(); wxString result = ""; wxStringTokenizer tokenizer(tagsField->GetValue(), ","); vector<wxString> tokens; while (tokenizer.HasMoreTokens()) { wxString token = tokenizer.GetNextToken().Trim(true).Trim(false); tokens.push_back(token); } for (unsigned int i = 0; i < tokens.size() - 1; i++) { result.Append(tokens[i]); result.Append(", "); } result.Append(tag); tagsField->SetValue(result); tagsField->SetInsertionPointEnd();*/ } wxString SchedulerDialog::ClearAmountValue(wxString &value) { value.Trim(true); value.Trim(false); value.Replace(",", ".", true); value.Replace(" ", "", true); return value; } void SchedulerDialog::OnPatternSelect(wxCommandEvent &event) { if (dailyButton->GetValue()) { SelectPatternType(SchedulerType::Daily); } if (weeklyButton->GetValue()) { SelectPatternType(SchedulerType::Weekly); } if (monthlyButton->GetValue()) { SelectPatternType(SchedulerType::Monthly); } if (yearlyButton->GetValue()) { SelectPatternType(SchedulerType::Yearly); } } void SchedulerDialog::SelectPatternType(SchedulerType type) { this->type = type; dailyPatternPanel->Hide(); weeklyPatternPanel->Hide(); monthlyPatternPanel->Hide(); yearlyPatternPanel->Hide(); if (type == SchedulerType::Daily) { dailyButton->SetValue(true); dailyPatternPanel->Show(); } if (type == SchedulerType::Weekly) { weeklyButton->SetValue(true); weeklyPatternPanel->Show(); } if (type == SchedulerType::Monthly) { monthlyButton->SetValue(true); monthlyPatternPanel->Show(); } if (type == SchedulerType::Yearly) { yearlyButton->SetValue(true); yearlyPatternPanel->Show(); } patternPanel->Layout(); } void SchedulerDialog::SelectWeekday(int day) { mondayCheckBox->SetValue(false); tuesdayCheckBox->SetValue(false); wednesdayCheckBox->SetValue(false); thursdayCheckBox->SetValue(false); fridayCheckBox->SetValue(false); saturdayCheckBox->SetValue(false); sundayCheckBox->SetValue(false); switch (day) { case 1: mondayCheckBox->SetValue(true); break; case 2: tuesdayCheckBox->SetValue(true); break; case 3: wednesdayCheckBox->SetValue(true); break; case 4: thursdayCheckBox->SetValue(true); break; case 5: fridayCheckBox->SetValue(true); break; case 6: saturdayCheckBox->SetValue(true); break; case 7: sundayCheckBox->SetValue(true); break; default: mondayCheckBox->SetValue(true); break; } } void SchedulerDialog::OnKeyDown(wxKeyEvent &event) { if ((int)event.GetKeyCode() == 27) { event.StopPropagation(); Close(); } else { event.Skip(); } }
31.849127
237
0.737501
sergeylenkov
d827bf26b4e2928646bc027ee89cd41ebd71d443
26,379
cpp
C++
qamsource/podmgr/podserver/commonDownloadManager/cdownloadcvtvalidationmgr.cpp
rdkcmf/rdk-mediaframework
55c7753eedaeb15719c5825f212372857459a87e
[ "Apache-2.0" ]
null
null
null
qamsource/podmgr/podserver/commonDownloadManager/cdownloadcvtvalidationmgr.cpp
rdkcmf/rdk-mediaframework
55c7753eedaeb15719c5825f212372857459a87e
[ "Apache-2.0" ]
null
null
null
qamsource/podmgr/podserver/commonDownloadManager/cdownloadcvtvalidationmgr.cpp
rdkcmf/rdk-mediaframework
55c7753eedaeb15719c5825f212372857459a87e
[ "Apache-2.0" ]
null
null
null
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2011 RDK Management * * 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 "cdownloadcvtvalidationmgr.h" #include "pkcs7utils.h" #include "cvtdownloadtypes.h" #include <CommonDownloadNVDataAccess.h> #include <strings.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include "vlpluginapp_halcdlapi.h" #include "coreUtilityApi.h" #if USE_SYSRES_MLT #include "rpl_malloc.h" #endif CDownloadCVTValidationMgr::CDownloadCVTValidationMgr() { } CDownloadCVTValidationMgr::~CDownloadCVTValidationMgr() { } static void PrintBuff(unsigned char *pData, int Size) { int ii; RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","\nVIVIDCvc[size:%d]={ \n",Size); for(ii = 0; ii < Size; ii++) { RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","0x%02X, ",pData[ii]); if( ((ii+1) % 16) == 0) { RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","\n"); } } RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","\n};\n"); } static int vlGetNumOfCvcs(unsigned char *pData, int len, int *pCvcNum) { unsigned char *pTemp,*pCvc,CvtType; unsigned long Length,CvcLen; int ii=0; *pCvcNum = 0; Length = len; pTemp = pData; while(1) { if(len < 5) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","vlGetNumOfCvcs: len:%d < 5 Error !! \n",len); return -1; } CvtType = pData[0]; CvcLen = (unsigned long)( ((unsigned long)pData[3] << 8) | pData[4] ); CvcLen += 4; if(len < CvcLen) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","vlGetNumOfCvcs: Error in CVCs Length:%d len:%d CvcLen:%d\n",Length,len,CvcLen); return -1; } ii++; RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","vlGetNumOfCvcs:CvtType[%d]:0x%02X CvcLen[%d]:%d\n",ii,CvtType,ii,CvcLen); len = len - (int)CvcLen - 1; if(len <= 0) break; pData = pData + CvcLen + 1; } *pCvcNum = ii; return 0; } int CDownloadCVTValidationMgr::processCVTTrigger(TableCVT *cvt) { unsigned char *mfrName=NULL; unsigned char *coName = NULL; cvcinfo_t cvcInfos[4],cvcInfosCheck[4]; cvc_data_t cvc_data; cvcAccessStart_t currentCvcAccessStart; int mfrIndex = -1; int coIndex = -1; int i; unsigned char *key; unsigned long keySize; unsigned char *cvcRoot,*cvcCA,*ManCvc; unsigned long cvcRootLen,cvcCALen,ManCvcLen; unsigned char *cvcRootKey,*cvcCAKey; int cvcRootKeyLen,cvcCAKeyLen; unsigned char *current; int currentLen; int num_cvcs = 0; int cvcMask = 0; int numberOfCvcs = 0; cvcinfo_t cvcRootInfo; cvcinfo_t cvcCAInfo; mfrName = CommonDownloadGetManufacturerName(); if((mfrName == NULL) ) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr:Error NULL pointer retunred from mfrName == %X || coName == %X \n",mfrName,coName); return -1; } if(mfrName) { RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","mfrName:%s \n",mfrName); } coName = CommonDownloadGetCosignerName(); if(coName == NULL) { return -1; } if(coName) { RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","coName:%s \n",coName); } bzero(cvcInfos, sizeof(cvcinfo_t)*4); // get CVC/s from CVT. switch(cvt->getCVT_Type()) { case CVT_T1V1: { int currentType,iRet; cvt_t1v1_download_data_t *cvtData = (cvt_t1v1_download_data_t*)cvt->getCVT_Data(); cvc_data = cvtData->cvc_data; current = cvc_data.data; RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL"," >>>>>>>>> CDownloadCVTValidationMgr: CVT 1 cvc_data.len:%d \n",cvc_data.len); vlMpeosDumpBuffer(RDK_LOG_INFO, "LOG.RDK.CDL", cvc_data.data,cvc_data.len); iRet = vlGetNumOfCvcs(cvc_data.data, int(cvc_data.len),&numberOfCvcs); if(iRet != 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr: CVT1 Error returned from vlGetNumOfCvcs \n"); free(cvtData); return -1; } if((cvc_data.len == 0) || (numberOfCvcs == 0) ) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: NO Cvcs found !! ERROR !!\n", __FUNCTION__); free(cvtData); return -1; } RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL"," CDownloadCVTValidationMgr: Number of CVCs:%d \n",numberOfCvcs); while(num_cvcs < numberOfCvcs) { currentType = current[0]; currentLen = (current[3] << 8) | current[4]; ////////////////////////////////// RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","Cvc From CVT1 Len:%d\n",currentLen + 4); //PrintBuff((current + 1), (currentLen + 4)); ///////////////////////////////////// #ifdef PKCS_UTILS if(getCVCInfoFromNonSignedData(current + 1, currentLen + 4, &cvcInfos[num_cvcs]) < 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownoadCVTValidationMgr::%s: Failed to find a CVT1 CVC\n", __FUNCTION__); free(cvtData); return -1; } #endif switch(currentType) { case 0: // Mfr CVC { if(strcmp((const char*)mfrName, (const char*)cvcInfos[num_cvcs].subjectOrgName) != 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: CVT1 CVC name [%s] does not match Mfr Name [%s]\n", __FUNCTION__, cvcInfos[num_cvcs].subjectOrgName, mfrName); free(cvtData); return -1; } mfrIndex = num_cvcs; cvcMask != MFR_CVC; break; } case 1: // CoSigner CVC { if(strcmp((const char*)coName, (const char*)cvcInfos[num_cvcs].subjectOrgName) != 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s:CVT1 CVC name [%s] does not match Mfr Name [%s]\n", __FUNCTION__, cvcInfos[num_cvcs].subjectOrgName, coName); free(cvtData); return -1; } coIndex = num_cvcs; cvcMask != CO_CVC; break; } default: { // deside what VVL wants to do in the case. RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: Unknown CVT1 CVC type of %d\n", __FUNCTION__, currentType); free(cvtData); return -1; } }//switch current = current + currentLen + 4 + 1; num_cvcs++; }//while free(cvtData); break; } case CVT_T2Vx: { if( cvt->getCVT_Version() == 1) { int currentType; cvt_t2v1_download_data_t *cvtData = (cvt_t2v1_download_data_t*)cvt->getCVT_Data(); cvc_data = cvtData->cvc_data; current = cvc_data.data; numberOfCvcs = cvtData->num_cvcs; if(cvc_data.len == 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: NO Cvcs found !! ERROR !!\n", __FUNCTION__); free(cvtData); return -1; } RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL"," CDownloadCVTValidationMgr: Number of CVCs:%d \n",numberOfCvcs); while(num_cvcs < cvtData->num_cvcs) { currentType = current[0]; currentLen = (current[3] << 8) | current[4]; ////////////////////////////////// RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","Cvc From CVT Len:%d\n",currentLen + 4); //PrintBuff((current + 1), (currentLen + 4)); ///////////////////////////////////// #ifdef PKCS_UTILS if(getCVCInfoFromNonSignedData(current + 1, currentLen + 4, &cvcInfos[num_cvcs]) < 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownoadCVTValidationMgr::%s: Failed to find a CVC\n", __FUNCTION__); free(cvtData); return -1; } #endif switch(currentType) { case 0: // Mfr CVC { if(strcmp((const char*)mfrName, (const char*)cvcInfos[num_cvcs].subjectOrgName) != 0) { RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: CVC name [%s] does not match Mfr Name [%s]\n", __FUNCTION__, cvcInfos[num_cvcs].subjectOrgName, mfrName); free(cvtData); return -1; } mfrIndex = num_cvcs; cvcMask != MFR_CVC; break; } case 1: // CoSigner CVC { if(strcmp((const char*)coName, (const char*)cvcInfos[num_cvcs].subjectOrgName) != 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: CVC name [%s] does not match Mfr Name [%s]\n", __FUNCTION__, cvcInfos[num_cvcs].subjectOrgName, coName); free(cvtData); return -1; } coIndex = num_cvcs; cvcMask != CO_CVC; break; } default: { // deside what VVL wants to do in the case. RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: Unknown CVC type of %d\n", __FUNCTION__, currentType); free(cvtData); return -1; } }//switch current = current + currentLen + 4 + 1; num_cvcs++; }//while free(cvtData); } else if( cvt->getCVT_Version() == 2) { int currentType; cvt_t2v2_download_data_t *cvtData = (cvt_t2v2_download_data_t*)cvt->getCVT_Data(); cvc_data = cvtData->cvc_data; current = cvc_data.data; numberOfCvcs = cvtData->num_cvcs; if(cvc_data.len == 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: NO Cvcs found !! ERROR !!\n", __FUNCTION__); if(cvtData->cvc_data.data != NULL) { free(cvtData->cvc_data.data); cvtData->cvc_data.data = NULL; } free(cvtData); return -1; } RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL"," CDownloadCVTValidationMgr: Number of CVCs:%d \n",numberOfCvcs); while(num_cvcs < cvtData->num_cvcs) { currentType = current[0]; currentLen = (current[3] << 8) | current[4]; ////////////////////////////////// RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","Cvc From CVT Len:%d\n",currentLen + 4); //PrintBuff((current + 1), (currentLen + 4)); ///////////////////////////////////// #ifdef PKCS_UTILS if(getCVCInfoFromNonSignedData(current + 1, currentLen + 4, &cvcInfos[num_cvcs]) < 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownoadCVTValidationMgr::%s: Failed to find a CVC\n", __FUNCTION__); free(cvtData); return -1; } #endif switch(currentType) { case 0: // Mfr CVC { if(strcmp((const char*)mfrName, (const char*)cvcInfos[num_cvcs].subjectOrgName) != 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: CVC name [%s] does not match Mfr Name [%s]\n", __FUNCTION__, cvcInfos[num_cvcs].subjectOrgName, mfrName); free(cvtData); return -1; } mfrIndex = num_cvcs; cvcMask != MFR_CVC; break; } case 1: // CoSigner CVC { if(strcmp((const char*)coName, (const char*)cvcInfos[num_cvcs].subjectOrgName) != 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: CVC name [%s] does not match Mfr Name [%s]\n", __FUNCTION__, cvcInfos[num_cvcs].subjectOrgName, coName); free(cvtData); return -1; } coIndex = num_cvcs; cvcMask != CO_CVC; break; } default: { // deside what VVL wants to do in the case. RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: Unknown CVC type of %d\n", __FUNCTION__, currentType); free(cvtData); return -1; } }//switch current = current + currentLen + 4 + 1; num_cvcs++; }//while free(cvtData); } break; }//case CVT_T2Vx: default: { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: Unknown CVT type of %d\n", __FUNCTION__, cvt->getCVT_Type()); return -1; } }//switch(cvt->getCVT_Type()) // verify Mfr CVC in codeFile SignedData // check OrgName is identical to Mfr name in Host memory // check CVC validity start time is >= cvcAccessTime held in host // check extendedKeyUsage in CVC includes OID ip-kp-codeSigning if(mfrIndex == -1 && coIndex == -1) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: Failed to find a CVC for Mfr %s!\n", __FUNCTION__, mfrName); return -1; } if(mfrIndex != -1 ) { if(cvcInfos[mfrIndex].codeSigningExists != 1) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: Mfr CVC fails extendedKeyUsage test!\n", __FUNCTION__); return -1; } } #if 1 RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","CDownloadCVTValidationMgr: Going to Verify CLCvcCA\n"); if(CommonDownloadGetCLCvcRootCA(&cvcRoot, &cvcRootLen)) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: Failed to get CL Root CVC from NVM!\n", __FUNCTION__); return -1; } RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","CL CVC ROOT cvcRootLen:%d\n",cvcRootLen); #ifdef PKCS_UTILS //PrintBuff(cvcRoot, cvcRootLen); if(getPublicKeyFromCVC(cvcRoot, cvcRootLen, &cvcRootKey, &cvcRootKeyLen)) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: Failed to get PubKey from CL Root CVC in NVM!\n", __FUNCTION__); free( cvcRoot ); return -1; } #endif #endif RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","Reading CL CVC CA \n"); if(CommonDownloadGetCLCvcCA(&cvcCA, &cvcCALen)) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: Failed to get CL Root CVC from NVM!\n", __FUNCTION__); return -1; } RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","CL CVC CA Len:%d\n",cvcCALen); //PrintBuff(cvcCA, cvcCALen); #ifdef PKCS_UTILS if(validateCertSignature(cvcCA, cvcCALen, cvcRootKey, cvcRootKeyLen)) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: CVC data failed to validate to CL CVC Root PublicKey!\n", __FUNCTION__); free( cvcRoot ); free( cvcCA ); return -1; } RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL"," ##################################################\n"); RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL"," >>>> SUCESS verifying CLCVCCA signature <<<<<<<< \n"); RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL"," ##################################################\n"); if(getCVCInfoFromNonSignedData(cvcRoot, cvcRootLen, &cvcRootInfo) < 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: Failed to get CVC Root Information!\n", __FUNCTION__); free( cvcRoot ); free( cvcCA ); return -1; } #endif #ifdef PKCS_UTILS if(getCVCInfoFromNonSignedData(cvcCA, cvcCALen, &cvcCAInfo) < 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: Failed to get CVC CA Information!\n", __FUNCTION__); free( cvcRoot ); free( cvcCA ); return -1; } if(strcmp((const char*)cvcRootInfo.subjectOrgName, (const char*)cvcCAInfo.issuerOrgName) != 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownladCVTValidationMgr::%s: CVC CA failed to chain to the CVC Root via OrgNames!\n", __FUNCTION__); free( cvcRoot ); free( cvcCA ); return -1; } if(strcmp((const char*)cvcRootInfo.subjectCommonName, (const char*)cvcCAInfo.issuerCommonName) != 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownladCVTValidationMgr::%s: CVC CA failed to chain to the CVC Root via CommonNames!\n", __FUNCTION__); free( cvcRoot ); free( cvcCA ); return -1; } #endif RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","#########################################################################\n"); RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","CDownladCVTValidationMgr:CVC ROOT and CVC CA Link Verification is SUCCESS \n"); RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","##########################################################################\n"); // Validate CVC signature via the CL CVC CA Public Key held in device // If fail, send invalid cert event #if 0 if(CommonDownloadGetCvcCAPublicKey(&key, &keySize) < 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: Failed to get CVC CA PubKey from NVM!\n", __FUNCTION__); return -1; } #endif #ifdef PKCS_UTILS if(getPublicKeyFromCVC(cvcCA, cvcCALen, &cvcCAKey, &cvcCAKeyLen)) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: Failed to get PubKey from CL Root CVC in NVM!\n", __FUNCTION__); free( cvcRoot ); free( cvcCA ); return -1; } #endif current = cvc_data.data; num_cvcs = 0; bzero(cvcInfosCheck, sizeof(cvcinfo_t)*4); while(num_cvcs < numberOfCvcs) { currentLen = (current[3] << 8) | current[4]; #ifdef PKCS_UTILS if(getCVCInfoFromNonSignedData(current + 1, currentLen + 4, &cvcInfosCheck[num_cvcs]) < 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: Failed to find a CVC\n", __FUNCTION__); free( cvcRoot ); free( cvcCA ); return -1; } if( validateCertSignature(current + 1, currentLen + 4, cvcCAKey, cvcCAKeyLen) ) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: Failed to validate CertSignature with stored key!\n", __FUNCTION__); free( cvcRoot ); free( cvcCA ); return -1; } #endif VL_CDL_CV_CERTIFICATE eCmCvc; int iRet; eCmCvc.eCvcType = VL_CDL_CVC_TYPE_MANUFACTURER; eCmCvc.cvCertificate.nBytes = currentLen + 4; eCmCvc.cvCertificate.pData = current + 1; vlMpeosDumpBuffer(RDK_LOG_INFO, "LOG.RDK.CDL", eCmCvc.cvCertificate.pData,eCmCvc.cvCertificate.nBytes); iRet = CHALCdl_notify_cdl_mgr_event(VL_CDL_MANAGER_EVENT_SET_CV_CERTIFICATE, (unsigned long )&eCmCvc); if(VL_CDL_RESULT_SUCCESS != iRet ) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","####################### VL_CDL_MANAGER_EVENT_SET_CV_CERTIFICATE Failed with Error:0x%X \n",iRet); } RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","#######################################################################\n"); RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL"," CDownladCVTValidationMgr:Received CVC Signature Verification is SUCCESS \n"); RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","########################################################################\n"); #if 1 if(strcmp((const char*)cvcCAInfo.subjectOrgName, (const char*)(cvcInfosCheck[num_cvcs].issuerOrgName)) != 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownladCVTValidationMgr::%s: CVC CA failed to chain to the CVC Root via OrgNames!\n", __FUNCTION__); free( cvcRoot ); free( cvcCA ); return -1; } if(strcmp((const char*)cvcCAInfo.subjectCommonName, (const char*)(cvcInfosCheck[num_cvcs].issuerCommonName)) != 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownladCVTValidationMgr::%s: CVC CA failed to chain to the CVC Root via CommonNames!\n", __FUNCTION__); free( cvcRoot ); free( cvcCA ); return -1; } #endif RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","######################################################\n"); RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","CDownladCVTValidationMgr:CVC Link Verification is SUCCESS \n"); RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","######################################################\n"); current = current + currentLen + 4 + 1; num_cvcs++; }//while(num_cvcs < cvtData->num_cvcs) RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","############################################################\n"); RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","CDownladCVTValidationMgr:Complete CVC Verification is SUCCESS \n"); RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","############################################################\n"); if(CommonDownloadGetCvcAccessStartTime(&currentCvcAccessStart, COM_DOWNL_MAN_CVC) != 0) { RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s Failed to get the current CVCAccessStart time!\n", __FUNCTION__); free( cvcRoot ); free( cvcCA ); return -1; } RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","CDownloadCVTValidationMgr: Checking the time \n"); if(mfrIndex != -1 ) { cvcAccessStart_t cvcTime; #ifdef PKCS_UTILS if(checkTime( currentCvcAccessStart.Time,cvcInfos[mfrIndex].notBefore) < 0) { //returns 0 if Time 1 = Time 2 // returns 1 if Time1 < Time2 // retunrs -1 if Time1 > Time2 RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: Mfr CVC fails cvcAccessStart time test!\n", __FUNCTION__); //return -1; } #endif memcpy(cvcTime.Time,cvcInfos[mfrIndex].notBefore,12); // Update time varying controls RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","CDownloadCVTValidationMgr: Calling CommonDownloadSetCvcAccessStartTime COM_DOWNL_MAN_CVC \n"); CommonDownloadSetCvcAccessStartTime((cvcAccessStart_t *)(&cvcTime), COM_DOWNL_MAN_CVC); } if(coIndex != -1) { cvcAccessStart_t cvcTime; #ifdef PKCS_UTILS if(checkTime(currentCvcAccessStart.Time,cvcInfos[coIndex].notBefore ) < 0) { //returns 0 if Time 1 = Time 2 // returns 1 if Time1 < Time2 // retunrs -1 if Time1 > Time2 RDK_LOG(RDK_LOG_ERROR, "LOG.RDK.CDL","CDownloadCVTValidationMgr::%s: Co CVC fails cvcAccessStart time test!\n", __FUNCTION__); free( cvcRoot ); free( cvcCA ); return -1; } #endif memcpy(cvcTime.Time,cvcInfos[coIndex].notBefore,12); RDK_LOG(RDK_LOG_INFO, "LOG.RDK.CDL","CDownloadCVTValidationMgr: Calling CommonDownloadSetCvcAccessStartTime COM_DOWNL_COSIG_CVC \n"); CommonDownloadSetCvcAccessStartTime((cvcAccessStart_t *)(&cvcTime), COM_DOWNL_COSIG_CVC); } #ifdef PKCS_UTILS setCVCUsage(cvcMask); #endif free( cvcRoot ); free( cvcCA ); return 0; }
41.152886
163
0.519732
rdkcmf
d829b711b85637c4e414287e74e1dbe2cd3acc9d
4,609
cpp
C++
cpp-htp/standard/ch07solutions/Ex07_25/Part_B/Ex07_25.cpp
yanshengjia/cplusplus-practice-range
6767a0ac50de8b532255511cd450dc84c66d1517
[ "Apache-2.0" ]
75
2020-03-23T11:00:31.000Z
2022-02-20T05:22:53.000Z
cpp-htp/standard/ch07solutions/Ex07_25/Part_B/Ex07_25.cpp
yanshengjia/cplusplus-practice-range
6767a0ac50de8b532255511cd450dc84c66d1517
[ "Apache-2.0" ]
null
null
null
cpp-htp/standard/ch07solutions/Ex07_25/Part_B/Ex07_25.cpp
yanshengjia/cplusplus-practice-range
6767a0ac50de8b532255511cd450dc84c66d1517
[ "Apache-2.0" ]
39
2020-04-03T23:47:24.000Z
2022-01-19T05:06:39.000Z
// Exercise 7.25 Part B Solution: Ex07_25.cpp #include <iostream> #include <iomanip> #include <cstdlib> #include <ctime> using namespace std; const int SIZE = 8; const int TOURS = 1000; const int MAXMOVES = 65; bool validMove( int, int, int, const int [][ SIZE ] ); int main() { int currentRow; int currentColumn; int moveType; int moveNumber; int testRow; int testColumn; int moveTotal[ MAXMOVES ] = {}; int goodMove; int board[ SIZE ][ SIZE ]; int horizontal[ SIZE ] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int vertical[ SIZE ] = { -1, -2, -2, -1, 1, 2, 2, 1 }; bool done; srand( time( 0 ) ); // set all squares equal to 0 for ( int i = 0; i < TOURS; ++i ) { for ( int row = 0; row < SIZE; row++ ) { for ( int col = 0; col < SIZE; col++ ) board[ row ][ col ] = 0; } // end for moveNumber = 1; currentRow = rand() % SIZE; currentColumn = rand() % SIZE; board[ currentRow ][ currentColumn ] = moveNumber++; done = false; // continue while knight still has valid moves while ( !done ) { moveType = rand() % SIZE; testRow = currentRow + vertical[ moveType ]; testColumn = currentColumn + horizontal[ moveType ]; goodMove = validMove( testRow, testColumn, moveType, board ); // if desired move is valid, move knight to square if ( goodMove ) { currentRow = testRow; currentColumn = testColumn; board[ currentRow ][ currentColumn ] = moveNumber++; } // end if else { // if move is invalid, test other possible moves for ( int count = 0; count < SIZE - 1 && !goodMove; count++ ) { moveType = ++moveType % SIZE; testRow = currentRow + vertical[ moveType ]; testColumn = currentColumn + horizontal[ moveType ]; goodMove = validMove( testRow, testColumn, moveType, board ); // if move is valid, move knight to square if ( goodMove ) { currentRow = testRow; currentColumn = testColumn; board[ currentRow ][ currentColumn ] = moveNumber++; } // end if } // end for // if no valid moves, while loop exits if ( !goodMove ) done = true; } // end else // if full tour is made, while loop exits if ( moveNumber - 1 == 64 ) done = true; } // end while moveTotal[ moveNumber ]++; } // end outer for // display how many tours of each move number were made for ( int j = 1; j < MAXMOVES; j++ ) { if ( moveTotal[ j ] ) cout << "There were " << moveTotal[ j ] << " tours of " << j << " moves." << endl; } // end for } // end main // function to determine if a move is legal bool validMove( int testRow, int testColumn, int moveType, const int board[][ SIZE ] ) { // test if square is on board and if knight has previously visited it if ( testRow >= 0 && testRow < SIZE && testColumn >= 0 && testColumn < SIZE ) return board[ testRow ][ testColumn ] != 0 ? false : true; else return false; } // end function validMove /************************************************************************** * (C) Copyright 1992-2010 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * **************************************************************************/
35.453846
77
0.505099
yanshengjia
d82b5475b787e5cea074b426e64a88be7348816a
1,725
cc
C++
gnc/gnc_autocode/src/ekf.cc
PeterWofford/astrobee
d4c05f6a938f0d56f071ee79ce86d90c24f1b2cb
[ "Apache-2.0" ]
629
2017-08-31T23:09:00.000Z
2022-03-30T11:55:40.000Z
gnc/gnc_autocode/src/ekf.cc
PeterWofford/astrobee
d4c05f6a938f0d56f071ee79ce86d90c24f1b2cb
[ "Apache-2.0" ]
269
2018-05-05T12:31:16.000Z
2022-03-30T22:04:11.000Z
gnc/gnc_autocode/src/ekf.cc
PeterWofford/astrobee
d4c05f6a938f0d56f071ee79ce86d90c24f1b2cb
[ "Apache-2.0" ]
248
2017-08-31T23:20:56.000Z
2022-03-30T22:29:16.000Z
/* Copyright (c) 2017, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * * All rights reserved. * * The Astrobee platform is 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 <gnc_autocode/ekf.h> #include <config_reader/config_reader.h> #include <assert.h> #include <est_tunable_funcs.h> namespace gnc_autocode { GncEkfAutocode::GncEkfAutocode(void) { int s = 15 + 6 + 6 * ASE_OF_NUM_AUG; P_ = static_cast<float*>(malloc(sizeof(float) * s * s)); assert(P_); est_ = est_estimator(&vis_, &reg_, &of_, &hand_, &imu_, &cmc_, quat_, &kfl_, P_); assert(est_); assert(rtmGetErrorStatus(est_) == NULL); Initialize(); } GncEkfAutocode::~GncEkfAutocode() { est_estimator_terminate(est_); free(P_); } void GncEkfAutocode::Step() { est_estimator_step(est_, &vis_, &reg_, &of_, &hand_, &imu_, &cmc_, quat_, &kfl_, P_); } void GncEkfAutocode::Initialize() { // initialize model est_estimator_initialize(est_, &vis_, &reg_, &of_, &hand_, &imu_, &cmc_, quat_, &kfl_, P_); } void GncEkfAutocode::ReadParams(config_reader::ConfigReader* config) { est_ReadParams(config, est_); } } // end namespace gnc_autocode
30.263158
93
0.718261
PeterWofford
d831c62da5ee18486b6488686d337f48022282c6
4,913
cpp
C++
disasm/cdis/CapstoneChunk.cpp
stjordanis/ViDi
91a001e024ee03a1a4fb07a8c11e6d66a04306f1
[ "BSD-2-Clause" ]
77
2016-10-29T23:00:23.000Z
2021-12-26T13:15:22.000Z
disasm/cdis/CapstoneChunk.cpp
stjordanis/ViDi
91a001e024ee03a1a4fb07a8c11e6d66a04306f1
[ "BSD-2-Clause" ]
2
2018-03-27T14:47:11.000Z
2019-11-29T02:06:08.000Z
disasm/cdis/CapstoneChunk.cpp
stjordanis/ViDi
91a001e024ee03a1a4fb07a8c11e6d66a04306f1
[ "BSD-2-Clause" ]
23
2016-10-30T23:28:38.000Z
2021-12-23T08:34:56.000Z
#include "CapstoneChunk.h" using namespace minidis; #define MAX_ARG_NUM 4 bool CapstoneChunk::fetchTargetAddr(const size_t argNum, TargetValue &targetVal, cs_detail *m_detail) const { if (!m_detail) return false; size_t cnt = static_cast<size_t>(m_detail->x86.op_count); if (argNum >= cnt) return false; targetVal.m_targetOpNum = argNum; const size_t opSize = m_detail->x86.operands[argNum].size; const x86_op_type type = m_detail->x86.operands[argNum].type; const x86_reg reg = static_cast<x86_reg>(m_detail->x86.operands[argNum].mem.base); const bool isEIPrelative = (reg == X86_REG_IP || reg == X86_REG_EIP || reg == X86_REG_RIP); if (type == X86_OP_MEM) { int64_t lval = m_detail->x86.operands[argNum].mem.disp; if (reg <= X86_REG_INVALID) { //simple case, no reg value to add if (!isValidAddr(lval, Executable::VA)) return false; return setTargetVal(targetVal, argNum, Executable::VA, lval); } if (isEIPrelative) { const offset_t currIP = this->m_startOffset + this->getOffset() + this->getChunkSize(); const offset_t target = currIP + lval; if (!isValidAddr(target, Executable::RVA)) return false; return setTargetVal(targetVal, argNum, Executable::RVA, target); } } if (type == X86_OP_IMM) { const bool isImm = true; int64_t lval = this->signExtend(m_detail->x86.operands[argNum].imm, opSize); //do not check registers in case of (short) branchings if (this->isBranching() && !isLongOp()) { const offset_t target = m_startOffset + lval; return setTargetVal(targetVal, argNum, Executable::RVA, target, isImm); } if (reg <= X86_REG_INVALID) { //simple case, no reg value to add if (!isValidAddr(lval, Executable::VA)) return false; return setTargetVal(targetVal, argNum, Executable::VA, lval, isImm); } //other registers, not supported case //printf("%s %s\n", this->m_insn.mnemonic, this->m_insn.op_str); return false; } return false; } TargetValue CapstoneChunk::fetchTargetAddr(cs_detail *detail) { TargetValue targetVal; targetVal.setValues(0, Executable::NOT_ADDR, INVALID_ADDR, INVALID_ADDR); const size_t cnt = getMaxArg(); if (cnt == 0) return targetVal; for (size_t i = 0; i < cnt; i++) { bool isOk = fetchTargetAddr(i, targetVal, detail); if (!isOk || targetVal.getAddrType() == Executable::NOT_ADDR) continue; // OK: return targetVal; } targetVal.setValues(0, Executable::NOT_ADDR, INVALID_ADDR, INVALID_ADDR); return targetVal; } //--- mnem_type CapstoneChunk::fetchMnemType(const x86_insn cMnem) { if (cMnem >= X86_INS_JAE && cMnem <= X86_INS_JS) { if (cMnem == X86_INS_JMP || cMnem == X86_INS_LJMP) return MT_JUMP; return MT_COND_JUMP; } if (cMnem >= X86_INS_MOV && cMnem <= X86_INS_MOVZX) { return MT_MOV; } switch (cMnem) { case X86_INS_LOOP: case X86_INS_LOOPE: case X86_INS_LOOPNE: return MT_LOOP; case X86_INS_CALL : case X86_INS_LCALL: return MT_CALL; case X86_INS_RET: case X86_INS_RETF: case X86_INS_RETFQ: return MT_RET; case X86_INS_NOP : return MT_NOP; case X86_INS_INVALID : return MT_INVALID; case X86_INS_POP: case X86_INS_POPAW: case X86_INS_POPAL: case X86_INS_POPCNT: case X86_INS_POPF: case X86_INS_POPFD: case X86_INS_POPFQ: { return MT_POP; } case X86_INS_PUSH: case X86_INS_PUSHAW: case X86_INS_PUSHAL: case X86_INS_PUSHF: case X86_INS_PUSHFD: case X86_INS_PUSHFQ: { return MT_PUSH; } case X86_INS_INT3 : return MT_INT3; case X86_INS_INT: return MT_INTX; } return MT_OTHER; } /* QString CapstoneChunk::valToString() const { if (!m_detail) return ""; size_t cnt = static_cast<size_t>(m_detail->x86.op_count); if (cnt == 0) return ""; QString opCount = " : "+ QString::number(cnt); if (cnt > 0) { bool isOk; int64_t lval = this->getSignedLVal(0, isOk); if (!isOk) return opCount +" fail"; QString opVal = " : "+ QString::number(lval, 16); return " ("+ opVal +")"; } return opCount; }*/ QString CapstoneChunk::translateBranchingMnemonic() const { if (this->m_insn.mnemonic == NULL || !this->isBranching()) { return ""; } QString desc = QString(this->m_insn.mnemonic).toUpper(); const x86_insn cMnem = static_cast<x86_insn>(this->m_insn.id); if (cMnem == X86_INS_JMP) { desc += " SHORT"; } return desc; }
28.563953
107
0.611235
stjordanis
d835aa288ed1ec0e1c7e231d37c119144dfa4e37
1,482
cpp
C++
libyangmeeting2/src/src/YangMeetingFactory.cpp
yangxinghai/yangrtc
92cc28ade5af6cbe22c151cd1220ab12816694e7
[ "MIT" ]
23
2021-09-13T06:24:34.000Z
2022-03-24T10:05:12.000Z
libyangmeeting2/src/src/YangMeetingFactory.cpp
yangxinghai/yangrtc
92cc28ade5af6cbe22c151cd1220ab12816694e7
[ "MIT" ]
null
null
null
libyangmeeting2/src/src/YangMeetingFactory.cpp
yangxinghai/yangrtc
92cc28ade5af6cbe22c151cd1220ab12816694e7
[ "MIT" ]
9
2021-09-13T06:27:44.000Z
2022-03-02T00:23:17.000Z
/* * YangUtilFactory.cpp * * Created on: 2020年10月17日 * Author: yang */ #include "YangMeetingHandleImpl.h" #include <yangmeeting/yangmeetingtype.h> #include <yangmeeting/YangMeetingFactory.h> #include "yangutil/sys/YangIni.h" #include "YangMeetingMessageHandle.h" YangMeetingFactory::YangMeetingFactory() { } YangSysMessageHandle* YangMeetingFactory::createSysMessageHandle(YangMeetingContext *pcontext,YangReceiveMessageI* prec){ return new YangMeetingMessageHandle(pcontext,prec); } YangMeetingHandle* YangMeetingFactory::createMeetingHandle(YangMeetingContext *pcontext){ return new YangMeetingHandleImpl(pcontext); } YangMeetingHandle* YangMeetingFactory::getMeetingHandle(YangSysMessageHandle *phandle){ return ((YangMeetingMessageHandle*)phandle)->m_videoMeeting; } /** void YangMeetingFactory::createIni(const char* p_filename,YangMeetingContext *pcontext){ YangMeetingConfigIni yi; yi.init(p_filename); //pcontext->m_log=new YangLog(); yi.initAudio(&pcontext->audio); yi.initVideo(&pcontext->video); yi.initSys(&pcontext->sys); yi.initHd(&pcontext->hd); yi.initEnc(&pcontext->enc); yi.initRtc(&pcontext->rtc); //yi.initCamera(&pcontext->camera); //pcontext->hasVr=yi.readIntValue("sys","hasVr",0); memset(pcontext->bgFilename, 0, sizeof(pcontext->bgFilename)); yi.readStringValue("sys", "bgFilename", pcontext->bgFilename, "/home/yang/bmp/jpg/03.jpeg"); //pcontext->isMulterCamera=0; //pcontext->context=new YangMeetingContext1(); } **/
29.64
121
0.772605
yangxinghai
d838ab09c72fdd45c44f768858bf4401a4632c58
1,513
cpp
C++
vivi/vivi64/CommandLine.cpp
vivisuke/openViVi
d3e57727393bfc48625945f09ca743e81bf14817
[ "MIT" ]
54
2020-02-15T23:17:25.000Z
2021-11-14T17:13:22.000Z
vivi/vivi64/CommandLine.cpp
vivisuke/openViVi
d3e57727393bfc48625945f09ca743e81bf14817
[ "MIT" ]
11
2020-06-01T08:04:40.000Z
2020-11-22T02:18:41.000Z
vivi/vivi64/CommandLine.cpp
vivisuke/openViVi
d3e57727393bfc48625945f09ca743e81bf14817
[ "MIT" ]
1
2020-06-01T07:51:47.000Z
2020-06-01T07:51:47.000Z
#include <QKeyEvent> #include "CommandLine.h" CommandLine::CommandLine(QWidget *parent) : QLineEdit(parent) { } CommandLine::~CommandLine() { } void CommandLine::focusOutEvent( QFocusEvent * event ) { QLineEdit::focusOutEvent(event); emit focusOut(); } void CommandLine::keyPressEvent(QKeyEvent *event) { const bool ctrl = (event->modifiers() & Qt::ControlModifier) != 0; const bool shift = (event->modifiers() & Qt::ShiftModifier) != 0; const bool alt = (event->modifiers() & Qt::AltModifier) != 0; if( event->key() == Qt::Key_Backspace && !hasSelectedText() && cursorPosition() == 1 ) { emit escPressed(); return; } if( event->key() == Qt::Key_Home ) { setCursorPosition(1); return; } if( event->key() == Qt::Key_Up ) { emit upPressed(); return; } if( event->key() == Qt::Key_Down ) { emit downPressed(); return; } if( event->key() == Qt::Key_Left && cursorPosition() == 1 ) { return; } if( event->key() == Qt::Key_A && ctrl ) { setSelection(1, text().size()); return; } QLineEdit::keyPressEvent(event); // 基底クラスの処理 if( event->key() == Qt::Key_Escape ) { emit escPressed(); } if( event->key() == Qt::Key_Space ) { emit spacePressed(); } if( event->key() == Qt::Key_Slash || event->key() == Qt::Key_Backslash ) { emit slashPressed(); // ディレクトリ区切り文字が入力された } if( event->key() == Qt::Key_Colon) { emit colonPressed(); } if( event->key() == Qt::Key_Tab) { emit tabPressed(); } } bool CommandLine::focusNextPrevChild(bool next) { return false; }
22.25
75
0.630535
vivisuke
d83ac1d2a5b8f88c4c3ec8caac492348a20fd75a
1,826
cpp
C++
CarpOS/Keyboard.cpp
cartman300/CarpOS
c8ab9332f5cd7953601aa5b528cd3f0467770c8c
[ "Unlicense" ]
2
2015-12-24T10:12:55.000Z
2017-05-03T12:13:54.000Z
CarpOS/Keyboard.cpp
cartman300/CarpOS
c8ab9332f5cd7953601aa5b528cd3f0467770c8c
[ "Unlicense" ]
null
null
null
CarpOS/Keyboard.cpp
cartman300/CarpOS
c8ab9332f5cd7953601aa5b528cd3f0467770c8c
[ "Unlicense" ]
1
2022-01-21T02:06:42.000Z
2022-01-21T02:06:42.000Z
#include "Keyboard.h" #include "Kernel.h" #include <intrin.h> #include <string.h> byte kbdus[128] = { 0, 27, '1', '2', '3', '4', '5', '6', '7', '8', /* 9 */ '9', '0', '-', '=', '\b', /* Backspace */ '\t', /* Tab */ 'q', 'w', 'e', 'r', /* 19 */ 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\n', /* Enter key */ 0, /* 29 - Control */ 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', /* 39 */ '\'', '`', 0, /* Left shift */ '\\', 'z', 'x', 'c', 'v', 'b', 'n', /* 49 */ 'm', ',', '.', '/', 0, /* Right shift */ '*', 0, /* Alt */ ' ', /* Space bar */ 0, /* Caps lock */ 0, /* 59 - F1 key ... > */ 0, 0, 0, 0, 0, 0, 0, 0, 0, /* < ... F10 */ 0, /* 69 - Num lock*/ 0, /* Scroll Lock */ 0, /* Home key */ 0, /* Up Arrow */ 0, /* Page Up */ '-', 0, /* Left Arrow */ 0, 0, /* Right Arrow */ '+', 0, /* 79 - End key*/ 0, /* Down Arrow */ 0, /* Page Down */ 0, /* Insert Key */ 0, /* Delete Key */ 0, 0, 0, 0, /* F11 Key */ 0, /* F12 Key */ 0, /* All other keys are undefined */ }; bool Keyboard::CapsLock = false; bool Keyboard::IgnoreInput = false; void Keyboard::OnKey(byte Scancode) { if (IgnoreInput) return; if (Scancode & 0x80) { //print("RELEASED\n"); } else { if (Scancode == 0x3A) { // Caps lock CapsLock = !CapsLock; SetLED((CapsLock ? 1 : 0) << 2); return; } //char Key = (CapsLock ? -32 : 0) + kbdus[Scancode]; } } void Keyboard::SetLED(byte LED) { while (IsBusy()); OutData(0xED); InData(); OutData(LED); InData(); } bool Keyboard::IsBusy() { return (InCommand() & 2) != 0; } void Keyboard::OutCommand(byte Cmd) { __outbyte(0x64, Cmd); } void Keyboard::OutData(byte Data) { __outbyte(0x60, Data); } byte Keyboard::InCommand() { return __inbyte(0x64); } byte Keyboard::InData() { return __inbyte(0x60); }
20.065934
63
0.470975
cartman300
d83c67feb35240718090f52771b772529d970e9c
1,150
cpp
C++
solutions/LeetCode/C++/877.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
854
2018-11-09T08:06:16.000Z
2022-03-31T06:05:53.000Z
solutions/LeetCode/C++/877.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
29
2019-06-02T05:02:25.000Z
2021-11-15T04:09:37.000Z
solutions/LeetCode/C++/877.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
347
2018-12-23T01:57:37.000Z
2022-03-12T14:51:21.000Z
__________________________________________________________________________________________________ sample 4 ms submission class Solution { public: bool stoneGame(vector<int>& piles) { int dp_a = max(piles[0],piles[piles.size()-1]); int dp_l = min(piles[0],piles[piles.size()-1]); int sum_a = dp_a; int sum_l = dp_l; for(int i = 1; i<piles.size()/2;i++) { if(i%2 == 1) // it's alex's turn { dp_a = max(piles[i],piles[piles.size()-1-i]); sum_a += dp_a; } else { dp_l = min(piles[i],piles[piles.size()-1-i]); sum_l += dp_l; } } if(sum_a > sum_l) return true; else return false; } }; __________________________________________________________________________________________________ sample 8456 kb submission class Solution { public: bool stoneGame(vector<int>& piles) { return true ; } }; __________________________________________________________________________________________________
30.263158
98
0.588696
timxor
d83e3f875685afba035e04f1be00ffa7404c6728
6,821
cpp
C++
game/client/hud_redraw.cpp
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
252
2020-12-16T15:34:43.000Z
2022-03-31T23:21:37.000Z
game/client/hud_redraw.cpp
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
23
2020-12-20T18:02:54.000Z
2022-03-28T16:58:32.000Z
game/client/hud_redraw.cpp
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
42
2020-12-19T04:32:33.000Z
2022-03-30T06:00:28.000Z
//===== Copyright � 1996-2005, Valve Corporation, All rights reserved. ======// // // Purpose: // // $NoKeywords: $ // //===========================================================================// // // hud_redraw.cpp // #include "cbase.h" #include "hudelement.h" #include "iclientmode.h" #include "itextmessage.h" #include "vgui_basepanel.h" #include "hud_crosshair.h" #if defined( INCLUDE_SCALEFORM ) #include "HUD/sfhudflashinterface.h" #endif #include <vgui/ISurface.h> // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" using namespace vgui; //For progress bar orientations const int CHud::HUDPB_HORIZONTAL = 0; const int CHud::HUDPB_VERTICAL = 1; const int CHud::HUDPB_HORIZONTAL_INV = 2; // Called when a ConVar changes value static void FovChanged_Callback( IConVar *pConVar, const char *pOldString, float flOldValue ) { ConVarRef var( pConVar ); if ( engine->IsInGame() ) { engine->ServerCmd( VarArgs( "fov %f\n", var.GetFloat() ) ); } } static ConVar fov_watcher( "_fov", "0", 0, "Automates fov command to server.", FovChanged_Callback ); void CHud::DoElementThink( CHudElement* pElement, vgui::Panel* pPanel ) { bool visible = true; //if we are globally disabling the HUD (and the pElement obeys global hiding), override the ShouldDraw check if ( m_iDisabledCount > 0 && !pElement->GetIgnoreGlobalHudDisable() ) { visible = false; } else { visible = pElement->ShouldDraw(); } pElement->SetActive( visible ); pElement->Think(); if ( pPanel && pPanel->IsVisible() != visible ) { pPanel->SetVisible( visible ); } bool bProcessInput = visible; #if defined( INCLUDE_SCALEFORM ) if ( bProcessInput ) { if ( SFHudFlashInterface *pHudFlashInterface = dynamic_cast< SFHudFlashInterface * >( pElement ) ) { if ( !pHudFlashInterface->FlashAPIIsValid() && !pHudFlashInterface->ShouldProcessInputBeforeFlashApiReady() ) bProcessInput = false; } } #endif if ( bProcessInput ) { pElement->ProcessInput(); } } //----------------------------------------------------------------------------- // Purpose: Think //----------------------------------------------------------------------------- void CHud::Think( void ) { // Determine the visibility of all hud elements CUtlVector< CHudElement * > & list = GetHudList(); CUtlVector< vgui::Panel * > & hudPanelList = GetHudPanelList(); int c = list.Count(); Assert( c == hudPanelList.Count() ); m_bEngineIsInGame = engine->IsInGame() && ( engine->IsLevelMainMenuBackground() == false ); for ( int i = 0; i < c; ++i ) { CHudElement* pElement = list[i]; if ( !pElement->m_bWantLateUpdate ) { DoElementThink( pElement, hudPanelList[ i ] ); } } // Let the active weapon at the keybits C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); if ( pPlayer ) { C_BaseCombatWeapon *pWeapon = pPlayer->GetActiveWeapon(); if ( pWeapon ) { pWeapon->HandleInput(); } } if ( ( m_flScreenShotTime > 0 ) && ( m_flScreenShotTime < gpGlobals->curtime ) ) { if ( !IsGameConsole() ) { engine->ClientCmd( "screenshot" ); } m_flScreenShotTime = -1; } } void CHud::OnTimeJump(void) { CUtlVector< CHudElement * > & list = GetHudList(); int c = list.Count(); for ( int i = 0; i < c; ++i ) { CHudElement* pElement = list[i]; if ( !pElement->m_bWantLateUpdate ) { pElement->OnTimeJump(); } } } void CHud::LateThink( void ) { SNPROF("LateThink"); CUtlVector< CHudElement * > & list = GetHudList(); CUtlVector< vgui::Panel * > & hudPanelList = GetHudPanelList(); int c = list.Count(); Assert( c == hudPanelList.Count() ); m_bEngineIsInGame = engine->IsInGame() && ( engine->IsLevelMainMenuBackground() == false ); for ( int i = 0; i < c; ++i ) { CHudElement* pElement = list[i]; if ( pElement->m_bWantLateUpdate ) { DoElementThink( pElement, hudPanelList[ i ] ); } } } //----------------------------------------------------------------------------- // Purpose: The percentage passed in is expected and clamped to 0.0f to 1.0f // Input : x - // y - // width - // height - // percentage - // clr - // type - //----------------------------------------------------------------------------- void CHud::DrawProgressBar( int x, int y, int width, int height, float percentage, Color& clr, unsigned char type ) { //Clamp our percentage percentage = MIN( 1.0f, percentage ); percentage = MAX( 0.0f, percentage ); Color lowColor = clr; lowColor[ 0 ] /= 2; lowColor[ 1 ] /= 2; lowColor[ 2 ] /= 2; //Draw a vertical progress bar if ( type == HUDPB_VERTICAL ) { int barOfs = height * percentage; surface()->DrawSetColor( lowColor ); surface()->DrawFilledRect( x, y, x + width, y + barOfs ); surface()->DrawSetColor( clr ); surface()->DrawFilledRect( x, y + barOfs, x + width, y + height ); } else if ( type == HUDPB_HORIZONTAL ) { int barOfs = width * percentage; surface()->DrawSetColor( lowColor ); surface()->DrawFilledRect( x, y, x + barOfs, y + height ); surface()->DrawSetColor( clr ); surface()->DrawFilledRect( x + barOfs, y, x + width, y + height ); } else if ( type == HUDPB_HORIZONTAL_INV ) { int barOfs = width * percentage; surface()->DrawSetColor( clr ); surface()->DrawFilledRect( x, y, x + barOfs, y + height ); surface()->DrawSetColor( lowColor ); surface()->DrawFilledRect( x + barOfs, y, x + width, y + height ); } } //----------------------------------------------------------------------------- // Purpose: The percentage passed in is expected and clamped to 0.0f to 1.0f // Input : x - // y - // *icon - // percentage - // clr - // type - //----------------------------------------------------------------------------- void CHud::DrawIconProgressBar( int x, int y, CHudTexture *icon, CHudTexture *icon2, float percentage, Color& clr, int type ) { if ( icon == NULL ) return; //Clamp our percentage percentage = MIN( 1.0f, percentage ); percentage = MAX( 0.0f, percentage ); int height = icon->Height(); int width = icon->Width(); //Draw a vertical progress bar if ( type == HUDPB_VERTICAL ) { int barOfs = height * percentage; icon2->DrawSelfCropped( x, y, // Pos 0, 0, width, barOfs, // Cropped subrect clr ); icon->DrawSelfCropped( x, y + barOfs, 0, barOfs, width, height - barOfs, // Cropped subrect clr ); } else if ( type == HUDPB_HORIZONTAL ) { int barOfs = width * percentage; icon2->DrawSelfCropped( x, y, // Pos 0, 0, barOfs, height, // Cropped subrect clr ); icon->DrawSelfCropped( x + barOfs, y, barOfs, 0, width - barOfs, height, // Cropped subrect clr ); } }
25.077206
125
0.581586
DannyParker0001
d84900f81fd56ef599a889883f58c237053d8f18
1,731
cpp
C++
BulletPhysicsWrapper/physics/bullet/cPlaneComponent.cpp
BobEh/Game-Engine
2086336c8e0d4b49166b8f9c8b8c1db99728e206
[ "MIT" ]
1
2020-03-14T18:51:09.000Z
2020-03-14T18:51:09.000Z
BulletPhysicsWrapper/physics/bullet/cPlaneComponent.cpp
BobEh/Game-Engine
2086336c8e0d4b49166b8f9c8b8c1db99728e206
[ "MIT" ]
null
null
null
BulletPhysicsWrapper/physics/bullet/cPlaneComponent.cpp
BobEh/Game-Engine
2086336c8e0d4b49166b8f9c8b8c1db99728e206
[ "MIT" ]
null
null
null
#include "cPlaneComponent.h" #include "nConvert.h" nPhysics::cPlaneComponent::cPlaneComponent(nPhysics::sPlaneDef thePlaneDef) { btCollisionShape* shape = new btStaticPlaneShape(nConvert::ToBullet(thePlaneDef.Normal), thePlaneDef.Constant); btTransform transform; transform.setIdentity(); //using motionstate is optional, it provides interpolation capabilities, and only synchronizes 'active' objects btDefaultMotionState* myMotionState = new btDefaultMotionState(transform); btRigidBody::btRigidBodyConstructionInfo rbInfo(0.f, myMotionState, shape, btVector3(0, 0, 0)); rbInfo.m_restitution = 0.8f; mBody = new btRigidBody(rbInfo); mBody->setUserPointer(this); } nPhysics::cPlaneComponent::~cPlaneComponent() { mBody->setUserPointer(0); delete mBody->getCollisionShape(); delete mBody->getMotionState(); delete mBody; } void nPhysics::cPlaneComponent::GetTransform(glm::mat4& transformOut) { btTransform transform; mBody->getMotionState()->getWorldTransform(transform); nConvert::ToSimple(transform, transformOut); } void nPhysics::cPlaneComponent::GetPosition(glm::vec3& positionOut) { positionOut = position; } void nPhysics::cPlaneComponent::SetPosition(glm::vec3 positionIn) { position = positionIn; } void nPhysics::cPlaneComponent::GetVelocity(glm::vec3& velocityOut) { velocityOut = velocity; } int nPhysics::cPlaneComponent::GetMassType() { return _physicsType; } void nPhysics::cPlaneComponent::SetMassType(int physicsType) { _physicsType = physicsType; } std::string nPhysics::cPlaneComponent::GetPlaneType() { return planeType; } void nPhysics::cPlaneComponent::ApplyForce(const glm::vec3& force) { //mBody->activate(true); //mBody->applyCentralForce(nConvert::ToBullet(force)); }
24.728571
112
0.780474
BobEh
d8496c4aae9eb9232814c8266b91bfe72bcc1201
12,523
cpp
C++
CppImport/src/manager/TranslateManager.cpp
patrick-luethi/Envision
b93e6f9bbb2a534b5534a5e48ed40a2c43baba8a
[ "BSD-3-Clause" ]
null
null
null
CppImport/src/manager/TranslateManager.cpp
patrick-luethi/Envision
b93e6f9bbb2a534b5534a5e48ed40a2c43baba8a
[ "BSD-3-Clause" ]
null
null
null
CppImport/src/manager/TranslateManager.cpp
patrick-luethi/Envision
b93e6f9bbb2a534b5534a5e48ed40a2c43baba8a
[ "BSD-3-Clause" ]
null
null
null
/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the ** following disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ #include "TranslateManager.h" namespace CppImport { TranslateManager::TranslateManager(OOModel::Project* root) : rootProject_{root} {} TranslateManager::~TranslateManager() { SAFE_DELETE(nh_); } void TranslateManager::setSourceManager(const clang::SourceManager* mngr) { nh_->setSourceManager(mngr); } void TranslateManager::setUtils(CppImportUtilities* utils) { Q_ASSERT(utils); utils_ = utils; } OOModel::Module *TranslateManager::insertNamespace(clang::NamespaceDecl* namespaceDecl) { const QString hash = nh_->hashNameSpace(namespaceDecl); if(nameSpaceMap_.contains(hash)) return nameSpaceMap_.value(hash); OOModel::Module* ooModule = new OOModel::Module(QString::fromStdString(namespaceDecl->getNameAsString())); nameSpaceMap_.insert(hash, ooModule); if(namespaceDecl->getDeclContext()->isTranslationUnit()) rootProject_->modules()->append(ooModule); else if(auto p = llvm::dyn_cast<clang::NamespaceDecl>(namespaceDecl->getDeclContext())) { const QString pHash = nh_->hashNameSpace(p); if(!nameSpaceMap_.contains(pHash)) return nullptr; nameSpaceMap_.value(pHash)->modules()->append(ooModule); } else return nullptr; return ooModule; } bool TranslateManager::insertClass(clang::CXXRecordDecl* rDecl, OOModel::Class* ooClass) { const QString hash = nh_->hashRecord(rDecl); // if rdecl is not managed yet add it: if(!classMap_.contains(hash)) { classMap_.insert(hash,ooClass); return true; } return false; } bool TranslateManager::insertClassTemplate(clang::ClassTemplateDecl* classTemplate, OOModel::Class* ooClass) { const QString hash = nh_->hashClassTemplate(classTemplate); if(!classMap_.contains(hash)) { classMap_.insert(hash, ooClass); return true; } return false; } bool TranslateManager::insertClassTemplateSpec (clang::ClassTemplateSpecializationDecl* classTemplate, OOModel::Class* ooClass) { const QString hash = nh_->hashClassTemplateSpec(classTemplate); if(!classMap_.contains(hash)) { classMap_.insert(hash, ooClass); return true; } return false; } OOModel::Method* TranslateManager::insertMethodDecl(clang::CXXMethodDecl* mDecl, OOModel::Method::MethodKind kind) { OOModel::Method* method = nullptr; // only consider methods where the parent has already been visited if(classMap_.contains(nh_->hashRecord(mDecl->getParent()))) { const QString hash = nh_->hashMethod(mDecl); if(!methodMap_.contains(hash)) method = addNewMethod(mDecl, kind); else { method = methodMap_.value(hash); // If the method in the map is just a declaration and the method we currently have is a definition // there might be some argument names in the definition which are not yet considered. // Therefore we look at them now. if(method->items()->size() || !mDecl->isThisDeclarationADefinition()) return method; for(int i = 0; i< method->arguments()->size(); i++) { OOModel::FormalArgument* ooArg = method->arguments()->at(i); // note that this never should/can be out of range otherwise the hash would be different ooArg->setName(QString::fromStdString(mDecl->getParamDecl(i)->getNameAsString())); } return method; } } return method; } OOModel::Method* TranslateManager::insertFunctionDecl(clang::FunctionDecl* functionDecl) { OOModel::Method* ooFunction = nullptr; const QString hash = nh_->hashFunction(functionDecl); if(!functionMap_.contains(hash)) ooFunction = addNewFunction(functionDecl); else { ooFunction = functionMap_.value(hash); if(ooFunction->items()->size()) return ooFunction; // the method which is in the map is just a declaration // therefore it might miss some arguments name which we collect here for(int i = 0; i< ooFunction->arguments()->size(); i++) { OOModel::FormalArgument* ooArg = ooFunction->arguments()->at(i); // note that this never should/can be out of range otherwise the hash would be different ooArg->setName(QString::fromStdString(functionDecl->getParamDecl(i)->getNameAsString())); } return ooFunction; } return ooFunction; } OOModel::Field* TranslateManager::insertField(clang::FieldDecl* fieldDecl) { const QString hash = nh_->hashRecord(fieldDecl->getParent()); if(classMap_.contains(hash)) { OOModel::Field* ooField = new OOModel::Field(); ooField->setName(QString::fromStdString(fieldDecl->getNameAsString())); classMap_.value(hash)->fields()->append(ooField); return ooField; } return nullptr; } OOModel::Field* TranslateManager::insertStaticField(clang::VarDecl* varDecl, bool& wasDeclared) { const QString hash = nh_->hashStaticField(varDecl); if(staticFieldMap_.contains(hash)) { wasDeclared = true; return staticFieldMap_.value(hash); } wasDeclared = false; const QString parentHash = nh_->hashParentOfStaticField(varDecl->getDeclContext()); if(classMap_.contains(parentHash)) { OOModel::Field* ooField = new OOModel::Field(QString::fromStdString(varDecl->getNameAsString())); classMap_.value(parentHash)->fields()->append(ooField); staticFieldMap_.insert(hash, ooField); return ooField; } return nullptr; } OOModel::ExplicitTemplateInstantiation* TranslateManager::insertExplicitTemplateInstantiation (const clang::ClassTemplateSpecializationDecl* explicitTemplateInst) { OOModel::ExplicitTemplateInstantiation* ooExplicitTemplateInst = nullptr; const QString hash = nh_->hashClassTemplateSpec(explicitTemplateInst); if(!explicitTemplateInstMap_.contains(hash)) { ooExplicitTemplateInst = new OOModel::ExplicitTemplateInstantiation(); explicitTemplateInstMap_.insert(hash, ooExplicitTemplateInst); } return ooExplicitTemplateInst; } OOModel::NameImport* TranslateManager::insertUsingDecl(clang::UsingDecl* usingDecl) { OOModel::NameImport* ooName = nullptr; const QString hash = nh_->hashUsingDecl(usingDecl); if(!usingDeclMap_.contains(hash)) { ooName = new OOModel::NameImport(); usingDeclMap_.insert(hash, ooName); } return ooName; } OOModel::NameImport* TranslateManager::insertUsingDirective(clang::UsingDirectiveDecl* usingDirective) { OOModel::NameImport* ooName = nullptr; const QString hash = nh_->hashUsingDirective(usingDirective); if(!usingDirectiveMap_.contains(hash)) { ooName = new OOModel::NameImport(); usingDirectiveMap_.insert(hash, ooName); } return ooName; } OOModel::NameImport* TranslateManager::insertUnresolvedUsing(clang::UnresolvedUsingValueDecl* unresolvedUsing) { OOModel::NameImport* ooName = nullptr; const QString hash = nh_->hashUnresolvedUsingDecl(unresolvedUsing); if(!usingDeclMap_.contains(hash)) { ooName = new OOModel::NameImport(); usingDeclMap_.insert(hash, ooName); } return ooName; } OOModel::TypeAlias*TranslateManager::insertNamespaceAlias(clang::NamespaceAliasDecl* namespaceAlias) { OOModel::TypeAlias* ooAlias = nullptr; const QString hash = nh_->hashNameSpaceAlias(namespaceAlias); if(!namespacAliasMap_.contains(hash)) { ooAlias = new OOModel::TypeAlias(); namespacAliasMap_.insert(hash, ooAlias); } return ooAlias; } OOModel::TypeAlias*TranslateManager::insertTypeAlias(clang::TypedefNameDecl* typeAlias) { OOModel::TypeAlias* ooAlias = nullptr; const QString hash = nh_->hashTypeAlias(typeAlias); if(!typeAliasMap_.contains(hash)) { ooAlias = new OOModel::TypeAlias(); typeAliasMap_.insert(hash, ooAlias); } return ooAlias; } OOModel::TypeAlias* TranslateManager::insertTypeAliasTemplate(clang::TypeAliasTemplateDecl* typeAliasTemplate) { OOModel::TypeAlias* ooAlias = nullptr; const QString hash = nh_->hashTypeAliasTemplate(typeAliasTemplate); if(!typeAliasMap_.contains(hash)) { ooAlias = new OOModel::TypeAlias(); typeAliasMap_.insert(hash, ooAlias); } return ooAlias; } OOModel::Method* TranslateManager::addNewMethod(clang::CXXMethodDecl* mDecl, OOModel::Method::MethodKind kind) { const QString hash = nh_->hashMethod(mDecl); // remove type argument from name because clang has that in the name of constructors of template classes. // template<class T> class List{ List();}; results in List<T> as name. QString name = QString::fromStdString(mDecl->getNameAsString()); if(name.endsWith(">")) name = name.left(name.indexOf("<")); OOModel::Method* method = new OOModel::Method(name, kind); if(!llvm::isa<clang::CXXConstructorDecl>(mDecl) && !llvm::isa<clang::CXXDestructorDecl>(mDecl)) { // process result type OOModel::Expression* restype = utils_->translateQualifiedType(mDecl->getResultType(), mDecl->getLocStart()); if(restype) { OOModel::FormalResult* methodResult = new OOModel::FormalResult(); methodResult->setTypeExpression(restype); method->results()->append(methodResult); } } // process arguments clang::FunctionDecl::param_const_iterator it = mDecl->param_begin(); for(;it != mDecl->param_end();++it) { OOModel::FormalArgument* arg = new OOModel::FormalArgument(); arg->setName(QString::fromStdString((*it)->getNameAsString())); OOModel::Expression* type = utils_->translateQualifiedType((*it)->getType(), (*it)->getLocStart()); if(type) arg->setTypeExpression(type); method->arguments()->append(arg); } // find the correct class to add the method if(classMap_.contains(nh_->hashRecord(mDecl->getParent()))) { OOModel::Class* parent = classMap_.value(nh_->hashRecord(mDecl->getParent())); parent->methods()->append(method); } else std::cout << "ERROR TRANSLATEMNGR: METHOD DECL NO PARENT FOUND" << std::endl; methodMap_.insert(hash, method); return method; } OOModel::Method* TranslateManager::addNewFunction(clang::FunctionDecl* functionDecl) { // add a new method OOModel::Method* ooFunction= new OOModel::Method(); ooFunction->setName(QString::fromStdString(functionDecl->getNameAsString())); // process result type OOModel::Expression* restype = utils_->translateQualifiedType(functionDecl->getResultType(), functionDecl->getLocStart()); if(restype) { OOModel::FormalResult* methodResult = new OOModel::FormalResult(); methodResult->setTypeExpression(restype); ooFunction->results()->append(methodResult); } // process arguments clang::FunctionDecl::param_const_iterator it = functionDecl->param_begin(); for(;it != functionDecl->param_end();++it) { OOModel::FormalArgument* arg = new OOModel::FormalArgument(); arg->setName(QString::fromStdString((*it)->getNameAsString())); OOModel::Expression* type = utils_->translateQualifiedType((*it)->getType(), (*it)->getLocStart()); if(type) arg->setTypeExpression(type); ooFunction->arguments()->append(arg); } functionMap_.insert(nh_->hashFunction(functionDecl),ooFunction); return ooFunction; } bool TranslateManager::containsClass(clang::CXXRecordDecl* recordDecl) { return classMap_.contains(nh_->hashRecord(recordDecl)); } }
34.980447
120
0.735926
patrick-luethi
d84c933ea05982a70bcca57a741c72c137a55269
3,430
cpp
C++
L2/common/src/sw/xNativeFPGA.cpp
Xilinx/HPC
c5d11c41f98a6ce8fc4a3fc9e7f5a133a09a9af3
[ "Apache-2.0" ]
4
2021-08-16T18:25:48.000Z
2022-03-22T08:49:43.000Z
L2/common/src/sw/xNativeFPGA.cpp
Xilinx/HPC
c5d11c41f98a6ce8fc4a3fc9e7f5a133a09a9af3
[ "Apache-2.0" ]
null
null
null
L2/common/src/sw/xNativeFPGA.cpp
Xilinx/HPC
c5d11c41f98a6ce8fc4a3fc9e7f5a133a09a9af3
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019-2021 Xilinx, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "sw/xNativeFPGA.hpp" #include "sw/xNativeFPGAExpection.hpp" namespace xilinx_apps { namespace hpc_common { void FPGA::setId(const int p_id) { m_id = p_id; m_device = xrt::device(p_id); } void FPGA::load_xclbin(const std::string& xclbin_fnm) { m_uuid = m_device.load_xclbin(xclbin_fnm); } const xrt::device& FPGA::getDevice() const { return m_device; } const xrt::uuid& FPGA::getUUID() const { return m_uuid; } void IP::fpga(FPGA* p_fpga) { m_fpga = p_fpga; } void IP::getIP(const std::string& p_ipName) { m_ip = xrt::ip(m_fpga->getDevice(), m_fpga->getUUID(), p_ipName); } uint32_t IP::readReg(const size_t p_regOffset) const { return (m_ip.read_register(p_regOffset)); } void IP::writeReg(const size_t p_regOffset, const uint32_t p_regVal) { m_ip.write_register(p_regOffset, p_regVal); } void KERNEL::fpga(FPGA* p_fpga) { m_fpga = p_fpga; } void KERNEL::createKernel(const std::string& name) { m_kernel = xrt::kernel(m_fpga->getDevice(), m_fpga->getUUID().get(), name); m_run = xrt::run(m_kernel); } void* KERNEL::createBO(const int p_argIdx, const size_t p_bytes) { xrt::bo l_bo = xrt::bo(m_fpga->getDevice(), p_bytes, m_kernel.group_id(p_argIdx)); m_bos.insert({p_argIdx, l_bo}); void* l_mem = l_bo.map<void*>(); return l_mem; } //p_hostPtr must be 4K aligned void KERNEL::createBOfromHostPtr(const int p_argIdx, const size_t p_bytes, void* p_hostPtr) { xrt::bo l_bo = xrt::bo(m_fpga->getDevice(), p_hostPtr, p_bytes, m_kernel.group_id(p_argIdx)); m_bos.insert({p_argIdx, l_bo}); } void KERNEL::sendBO(const int p_argIdx) { xrt::bo l_bo = m_bos.find(p_argIdx)->second; l_bo.sync(XCL_BO_SYNC_BO_TO_DEVICE); } void KERNEL::setMemArg(const int p_argIdx) { if (m_bos.find(p_argIdx) != m_bos.end()) { xrt::bo l_bo = m_bos.find(p_argIdx)->second; m_run.set_arg(p_argIdx, l_bo); } else { throw xilinx_apps::hpc_common::xNativeFPGAInvalidValue("could not find the BO"); } } template <typename t_Type> void KERNEL::setScalarArg(const int p_argIdx, t_Type p_argVal) { m_run.set_arg(p_argIdx, p_argVal); } void KERNEL::run() { m_run.start(); } void KERNEL::getBO(const int p_argIdx) { auto state = m_run.wait(); //std::cout << "state " << state << std::endl; // ERT_CMD_STATE_COMPLETED = 4 if (m_bos.find(p_argIdx) != m_bos.end()) { xrt::bo l_bo = m_bos.find(p_argIdx)->second; l_bo.sync(XCL_BO_SYNC_BO_FROM_DEVICE); } else { throw xilinx_apps::hpc_common::xNativeFPGAInvalidValue("could not find the BO"); } } void KERNEL::wait() { auto state = m_run.wait(); //std::cout << "state " << state << std::endl; } void KERNEL::clearBOMap() { m_bos.clear(); } template void KERNEL::setScalarArg<unsigned int>(const int, unsigned int); } }
29.067797
97
0.68688
Xilinx
d84debae06b721217690a3aaa6ae822731c7984f
345
inl
C++
Refureku/Library/Include/Public/Refureku/TypeInfo/Archetypes/Template/NonTypeTemplateArgument.inl
jsoysouvanh/Refureku
7548cb3b196793119737a51c1cedc136aa60d3ee
[ "MIT" ]
143
2020-04-07T21:38:21.000Z
2022-03-30T01:06:33.000Z
Refureku/Library/Include/Public/Refureku/TypeInfo/Archetypes/Template/NonTypeTemplateArgument.inl
jsoysouvanh/Refureku
7548cb3b196793119737a51c1cedc136aa60d3ee
[ "MIT" ]
7
2021-03-30T07:26:21.000Z
2022-03-28T16:31:02.000Z
Refureku/Library/Include/Public/Refureku/TypeInfo/Archetypes/Template/NonTypeTemplateArgument.inl
jsoysouvanh/Refureku
7548cb3b196793119737a51c1cedc136aa60d3ee
[ "MIT" ]
11
2020-06-06T09:45:12.000Z
2022-01-25T17:17:55.000Z
/** * Copyright (c) 2021 Julien SOYSOUVANH - All Rights Reserved * * This file is part of the Refureku library project which is released under the MIT License. * See the README.md file for full license details. */ template <typename T> T NonTypeTemplateArgument::getValue() const noexcept { return *reinterpret_cast<T const*>(getValuePtr()); }
28.75
92
0.756522
jsoysouvanh
d84ebb81df863d7fc70ad11d01650f1cfb93cd31
72
cpp
C++
build/staticLib/main.cpp
NoCodeProgram/ModernCPP
ac7b05a4d720678e68878d70c0a7a69f56885d00
[ "MIT" ]
5
2020-08-17T12:14:44.000Z
2022-01-21T06:57:56.000Z
build/staticLib/main.cpp
NoCodeProgram/ModernCPP
ac7b05a4d720678e68878d70c0a7a69f56885d00
[ "MIT" ]
null
null
null
build/staticLib/main.cpp
NoCodeProgram/ModernCPP
ac7b05a4d720678e68878d70c0a7a69f56885d00
[ "MIT" ]
2
2022-01-18T03:20:51.000Z
2022-02-11T14:50:19.000Z
#include "cat.h" int main() { Cat kitty; kitty.speak(); return 0; }
8
16
0.597222
NoCodeProgram
d84f0e706e3b56b718041ddfda630ecadfad0384
301
cpp
C++
c++/84-7897-268-4/cap.2/Entrada/cadena3.cpp
leopansa/libros
1fd44aaa230eedb493f52497e82bed1ab1cc6252
[ "MIT" ]
null
null
null
c++/84-7897-268-4/cap.2/Entrada/cadena3.cpp
leopansa/libros
1fd44aaa230eedb493f52497e82bed1ab1cc6252
[ "MIT" ]
null
null
null
c++/84-7897-268-4/cap.2/Entrada/cadena3.cpp
leopansa/libros
1fd44aaa230eedb493f52497e82bed1ab1cc6252
[ "MIT" ]
null
null
null
//PROG204.CPP - Operacion de cadenas // Imprimir unicamente cuando detecta numeros #include <iostream> int main() { int n; //solo acepta numeros std::cout << "Introducir numeros: " << std::endl; while(std::cin >> n) { std::cout << n << std::endl; } return 0; }
17.705882
53
0.578073
leopansa
d84fc22bfcbda44f90a5b747e2fdb8a045aa833b
4,388
cpp
C++
src/Cello/test_Schedule.cpp
aoife-flood/enzo-e
ab8ebc4716fff22bed9f692daf0472ae6ffffe73
[ "BSD-3-Clause" ]
26
2019-02-12T19:39:13.000Z
2022-03-31T01:52:29.000Z
src/Cello/test_Schedule.cpp
aoife-flood/enzo-e
ab8ebc4716fff22bed9f692daf0472ae6ffffe73
[ "BSD-3-Clause" ]
128
2019-02-13T20:22:30.000Z
2022-03-29T20:21:00.000Z
src/Cello/test_Schedule.cpp
aoife-flood/enzo-e
ab8ebc4716fff22bed9f692daf0472ae6ffffe73
[ "BSD-3-Clause" ]
29
2019-02-12T19:37:51.000Z
2022-03-14T14:02:45.000Z
// See LICENSE_CELLO file for license and copyright information /// @file test_Schedule.cpp /// @author James Bordner (jobordner@ucsd.edu) /// @date 2010-04-02 /// @brief Test program for the Schedule class #include "main.hpp" #include "test.hpp" #include "io.hpp" PARALLEL_MAIN_BEGIN { PARALLEL_INIT; unit_init(0,1); unit_class("ScheduleInterval"); { ScheduleInterval * schedule = new ScheduleInterval; unit_assert (schedule != NULL); //-------------------------------------------------- schedule->set_active(true); unit_assert(schedule->is_active()); schedule->set_active(false); unit_assert(! schedule->is_active()); schedule->set_active(true); unit_assert(schedule->is_active()); unit_func("write_this_cycle"); schedule->set_time_interval(10.0,2.0,20.0); unit_assert(schedule->write_this_cycle (0, 8.0) == false); unit_assert(schedule->write_this_cycle (0, 10.0) == true); unit_assert(schedule->write_this_cycle (0, 12.0) == false); schedule->next(); unit_assert(schedule->write_this_cycle (0, 10.0) == false); unit_assert(schedule->write_this_cycle (0, 12.0) == true); unit_assert(schedule->write_this_cycle (0, 14.0) == false); schedule->next(); unit_assert(schedule->write_this_cycle (0, 12.0) == false); unit_assert(schedule->write_this_cycle (0, 14.0) == true); unit_assert(schedule->write_this_cycle (0, 16.0) == false); schedule->next(); unit_assert(schedule->write_this_cycle (0, 14.0) == false); unit_assert(schedule->write_this_cycle (0, 16.0) == true); unit_assert(schedule->write_this_cycle (0, 18.0) == false); schedule->next(); unit_assert(schedule->write_this_cycle (0, 16.0) == false); unit_assert(schedule->write_this_cycle (0, 18.0) == true); unit_assert(schedule->write_this_cycle (0, 20.0) == false); schedule->next(); unit_assert(schedule->write_this_cycle (0, 18.0) == false); unit_assert(schedule->write_this_cycle (0, 20.0) == true); unit_assert(schedule->write_this_cycle (0, 22.0) == false); schedule->next(); unit_assert(schedule->write_this_cycle (0, 22.0) == false); unit_func("update_timestep"); unit_assert(schedule->update_timestep(11.0, 0.1) == 0.1); unit_assert(schedule->update_timestep(12.0, 0.1) == 0.1); unit_assert (unit_incomplete); // schedule->set_time_interval(13.3, 2.0, 19); unit_func("set_time_list"); unit_assert (unit_incomplete); // std::vector<double> list_double; // list.push_back(7/3); // list.push_back(-18.9); // list.push_back(7); // schedule->set_time_list (list_double); unit_func("this_cycle "); unit_assert (unit_incomplete); unit_func("t = schedule->update_timestep"); unit_assert (unit_incomplete); unit_func("set_skip_cycle "); unit_assert (unit_incomplete); unit_func("set_skip_time "); unit_assert (unit_incomplete); delete schedule; } { ScheduleInterval * schedule = new ScheduleInterval; unit_assert (schedule != NULL); //-------------------------------------------------- schedule->set_active(true); unit_assert(schedule->is_active()); schedule->set_active(false); unit_assert(! schedule->is_active()); schedule->set_active(true); unit_assert(schedule->is_active()); unit_func("write_this_cycle"); schedule->set_seconds_interval(1.0,3.0,5.0); unit_assert(schedule->write_this_cycle (0, 0.0) == false); unit_assert(schedule->write_this_cycle (0, 0.0) == false); unit_assert(schedule->write_this_cycle (0, 0.0) == false); int err; err = system("sleep 2"); unit_assert(schedule->write_this_cycle (0, 0.0) == true); unit_assert(schedule->write_this_cycle (0, 0.0) == true); schedule->next(); unit_assert(schedule->write_this_cycle (0, 0.0) == false); unit_assert(schedule->write_this_cycle (0, 0.0) == false); err = system("sleep 2"); unit_assert(schedule->write_this_cycle (0, 0.0) == true); unit_assert(schedule->write_this_cycle (0, 0.0) == true); schedule->next(); unit_assert(schedule->write_this_cycle (0, 0.0) == false); unit_assert(schedule->write_this_cycle (0, 0.0) == false); } //-------------------------------------------------- unit_finalize(); exit_(); } PARALLEL_MAIN_END
27.772152
63
0.640155
aoife-flood
d851e7ebb2246acf9264a52af3b5a7d47b05970c
2,105
cpp
C++
src/signal.cpp
orbitrc/blusher-qt
23a868875fbe600a14ea6d49226226fea8931ab6
[ "MIT" ]
null
null
null
src/signal.cpp
orbitrc/blusher-qt
23a868875fbe600a14ea6d49226226fea8931ab6
[ "MIT" ]
null
null
null
src/signal.cpp
orbitrc/blusher-qt
23a868875fbe600a14ea6d49226226fea8931ab6
[ "MIT" ]
null
null
null
#include <blusher/signal.h> #include <stdint.h> #include "signal-impl.h" #ifdef emit #undef emit #endif #define BLUSHER_SIGNAL_CONSTRUCTOR { this->_impl = new SignalImpl(); } #define BLUSHER_CONNECTION_CONSTRUCTOR { this->_impl = impl; } #define BLUSHER_CONNECTION_CONSTRUCTOR_ARG(type) template<> \ Signal<type>::Connection::Connection(ConnectionImpl *impl) \ { this->_impl = impl; } #define BLUSHER_CONNECTION_DISCONNECT_VOID template<> \ bool Signal<>::Connection::disconnect() \ { return this->_impl->disconnect(); } #define BLUSHER_CONNECTION_DISCONNECT_ARG(type) template<> \ bool Signal<type>::Connection::disconnect() \ { return this->_impl->disconnect(); } namespace bl { //=============== // void //=============== template<> Signal<>::Signal() BLUSHER_SIGNAL_CONSTRUCTOR template<> Signal<>::Connection::Connection(ConnectionImpl *impl) BLUSHER_CONNECTION_CONSTRUCTOR BLUSHER_CONNECTION_DISCONNECT_VOID template<> void Signal<>::emit() { this->_impl->emitSignal(); } template<> Signal<>::Connection Signal<>::connect(std::function<void()> slot) { return Connection(this->_impl->connect(slot)); } //=============== // int //=============== template<> Signal<int>::Signal() BLUSHER_SIGNAL_CONSTRUCTOR BLUSHER_CONNECTION_CONSTRUCTOR_ARG(int) BLUSHER_CONNECTION_DISCONNECT_ARG(int) template<> void Signal<int>::emit(int arg) { this->_impl->emitSignal(arg); } template<> Signal<int>::Connection Signal<int>::connect(std::function<void(int)> slot) { return Connection(this->_impl->connect(slot)); } //================== // Surface::State //================== template<> Signal<Surface::State>::Signal() BLUSHER_SIGNAL_CONSTRUCTOR BLUSHER_CONNECTION_CONSTRUCTOR_ARG(Surface::State) BLUSHER_CONNECTION_DISCONNECT_ARG(Surface::State) template<> void Signal<Surface::State>::emit(Surface::State arg) { this->_impl->emitSignal(arg); } template<> Signal<Surface::State>::Connection Signal<Surface::State>::connect( std::function<void(Surface::State)> slot) { return Connection(this->_impl->connect(slot)); } } // namespace bl
20.841584
75
0.695962
orbitrc
d852f59d03cc9769dfe656042d4898b851006831
1,598
hpp
C++
src/tts/include/ttsService.hpp
3rang/TTS
5a84b49ea08af599ad553ae27efb36b2682f3f76
[ "MIT" ]
null
null
null
src/tts/include/ttsService.hpp
3rang/TTS
5a84b49ea08af599ad553ae27efb36b2682f3f76
[ "MIT" ]
null
null
null
src/tts/include/ttsService.hpp
3rang/TTS
5a84b49ea08af599ad553ae27efb36b2682f3f76
[ "MIT" ]
null
null
null
// SPDX-FileCopyrightText: 2021 MBition GmbH // // SPDX-License-Identifier: Closed software #ifndef INC_TTSSERVICE_HPP_ #define INC_TTSSERVICE_HPP_ #include <iostream> #include <vector> #include <cstdint> #include <cstring> #include <string> #include <chrono> #include <fstream> #include <tensorflow/lite/interpreter.h> #include <tensorflow/lite/kernels/register.h> #include <tensorflow/lite/model.h> #include <tensorflow/lite/optional_debug_tools.h> typedef struct { float *mel_Data; std::vector<int32_t> mel_Shape; int32_t mel_bytes; } MelGenData; #define TFLITE_MINIMAL_CHECK(x) \ if (!(x)) { \ fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__); \ exit(1); \ } class ttsBase { public: std::unique_ptr<tflite::FlatBufferModel> model; std::unique_ptr<tflite::Interpreter> interpreter; tflite::ops::builtin::BuiltinOpResolver resolver; }; class ttsBaseMel:public ttsBase { private: const char* melgenPath; public: ttsBaseMel(const char* melgenfile): melgenPath(melgenfile) { std::cout << "TTSModel melgenPath" << std::endl; }; MelGenData interpreterBuildMel(std::vector<int32_t> &localbuf); }; class ttsBasevocodoer:public ttsBase { private: const char* vocoderPath; public: ttsBasevocodoer(const char* vocoderfile): vocoderPath(vocoderfile) { std::cout << "TTSModel vocoderfile" << std::endl; }; std::vector<float> interpreterBuildvocoder(MelGenData &localbufV); }; #endif /* INC_TTSSERVICE_HPP_ */
18.581395
68
0.673342
3rang
d85738cfcfa355fa4fddd2fd103c87dcc3d0baac
1,226
cpp
C++
Search/binarysearch.cpp
JobayerAhmmed/DSA_C
2af3d702820dd3e1b9db49558e4398ea978e71ca
[ "MIT" ]
null
null
null
Search/binarysearch.cpp
JobayerAhmmed/DSA_C
2af3d702820dd3e1b9db49558e4398ea978e71ca
[ "MIT" ]
null
null
null
Search/binarysearch.cpp
JobayerAhmmed/DSA_C
2af3d702820dd3e1b9db49558e4398ea978e71ca
[ "MIT" ]
null
null
null
#include<stdio.h> int parti(int* data, int left, int right) { int pivot = data[left + (right - left)/2]; int i = left - 1; int j = right + 1; while (true) { do { i++; } while(data[i] < pivot); do { j--; } while(data[j] > pivot); if (i >= j) return j; int temp = data[i]; data[i] = data[j]; data[j] = temp; } } void quicksort(int* data, int left, int right) { if (left < right) { int p = parti(data, left, right); quicksort(data, left, p); quicksort(data, p + 1, right); } } int binarysearch(int* data, int left, int right, int item) { while (left <= right) { int p = left + (right - left) / 2; if(data[p] < item) left = p + 1; else if(data[p] > item) right = p - 1; else return p; } return -1; } int main() { int data[] = {20, 30, 40, 50, 80, 90, 100}; int n = sizeof(data) / sizeof(data[0]); quicksort(data, 0, n-1); int searchItem = 50; int index = binarysearch(data, 0, n-1, searchItem); printf("Index of %d = %d\n", searchItem, index); return 0; }
18.575758
58
0.468189
JobayerAhmmed
d85c0e9c96e659eeb77708e1772fb5a31eaf9dcf
2,663
hh
C++
cblite/LiteCorePolyfill.hh
couchbaselabs/couchbase-mobile-tools
b0d2c40cf5b6043b508434cc0ef310f29df2d2c1
[ "Apache-2.0" ]
27
2019-02-12T15:48:50.000Z
2022-03-31T10:03:42.000Z
cblite/LiteCorePolyfill.hh
couchbaselabs/couchbase-mobile-tools
b0d2c40cf5b6043b508434cc0ef310f29df2d2c1
[ "Apache-2.0" ]
20
2019-02-20T19:57:05.000Z
2022-03-21T20:04:35.000Z
cblite/LiteCorePolyfill.hh
couchbaselabs/couchbase-mobile-tools
b0d2c40cf5b6043b508434cc0ef310f29df2d2c1
[ "Apache-2.0" ]
18
2019-04-08T10:11:25.000Z
2022-03-29T04:55:25.000Z
// // LiteCorePolyfill.hh // // Copyright © 2021 Couchbase. All rights reserved. // // This header is a compatibility shim for pre-3.0 versions of LiteCore. // It adds definitions of some newer types and functions that the cblite tool uses. #pragma once #include "c4.h" #include "fleece/Fleece.h" #include "fleece/slice.hh" // Unofficial LiteCore C++ API helpers; in dev their header has been renamed #if __has_include("tests/c4CppUtils.hh") # include "tests/c4CppUtils.hh" // dev branch #else # include "c4.hh" // master branch (as of May 2021); TODO: remove after merge # include "c4Transaction.hh" #endif #ifndef LITECORE_VERSION // LITECORE_VERSION was added to the dev and master branches May 19 2021. // If building with older source code, use some heuristics to figure out what it is: #ifdef C4_ASSUME_NONNULL_BEGIN // (this macro was added post-2.8.) #define LITECORE_VERSION 30000 #if __has_include("c4Collection.h") #define LITECORE_API_VERSION 350 // dev branch (May 2021) #else #define LITECORE_API_VERSION 300 // master branch (May 2021) #endif #else #define LITECORE_VERSION 20800 // else assume CBL 2.8 #define LITECORE_API_VERSION 200 #endif #endif // Test if collections are available #if __has_include("c4Collection.h") # define HAS_COLLECTIONS #endif #if LITECORE_API_VERSION < 300 // Define stuff we use that's not in LiteCore 2.8: enum C4DocContentLevel { kDocGetCurrentRev, kDocGetAll, }; static inline C4StringResult c4db_getName(C4Database *db) { fleece::alloc_slice apath = c4db_getPath(db); fleece::slice path = apath; if (path.hasSuffix("/") || path.hasSuffix("\\")) path.setSize(path.size - 1); if (path.hasSuffix(".cblite2")) path.setSize(path.size - 8); for (auto c = (const char *)path.end(); c >= path.buf; --c) if (c[-1] == '/' || c[-1] == '\\') { path.setStart(c); break; } return C4StringResult(fleece::alloc_slice(path)); } static inline C4Document* c4db_getDoc(C4Database *db, C4String docID, bool mustExist, C4DocContentLevel, C4Error *error) { return c4doc_get(db, docID, mustExist, error); } static inline C4Slice c4doc_getRevisionBody(C4Document *doc) { return doc->selectedRev.body; } static inline FLDict c4doc_getProperties(C4Document *doc) { if (doc->selectedRev.body.buf) return FLValue_AsDict( FLValue_FromData(doc->selectedRev.body, kFLTrusted) ); else return nullptr; } #endif
29.588889
99
0.6549
couchbaselabs
d85dfef9fd06f50ff2d53810a7109b851c3697d0
17,905
cpp
C++
opengl-text/src/freetype.cpp
Deception666/opengl-font-renderer
32007d89389c426657d0025ec1a09f75176a1281
[ "MIT" ]
null
null
null
opengl-text/src/freetype.cpp
Deception666/opengl-font-renderer
32007d89389c426657d0025ec1a09f75176a1281
[ "MIT" ]
null
null
null
opengl-text/src/freetype.cpp
Deception666/opengl-font-renderer
32007d89389c426657d0025ec1a09f75176a1281
[ "MIT" ]
null
null
null
#include "freetype.h" #include "error_reporting_private.h" #include <algorithm> #if __linux__ #include <cstdlib> #include <filesystem> #endif #include <stdexcept> #include <utility> #if _WIN32 #include <windows.h> #elif __linux__ #include <dlfcn.h> #endif namespace opengl { template < typename T > inline T GetFuncAddress( const char * const function, void * const module, T ) noexcept { #if _WIN32 return reinterpret_cast< T >( GetProcAddress( reinterpret_cast< const HMODULE >(module), function)); #elif __linux__ return reinterpret_cast< T >( dlsym( module, function)); #else #error "Define for this platform!" #endif } template < size_t OFFSET, typename T > T GetBitmapData( const FT_Face::pointer ft_face ) noexcept { #if _WIN32 #if _M_IX86 const size_t glyph_offset { 84 }; const size_t bitmap_offset { 76 }; #elif _M_X64 const size_t glyph_offset { 120 }; const size_t bitmap_offset { 104 }; #else #define "Define for this platform type!" #endif // _M_IX86 #elif __linux__ #if __i386__ const size_t glyph_offset { 84 }; const size_t bitmap_offset { 76 }; #elif __x86_64__ const size_t glyph_offset { 152 }; const size_t bitmap_offset { 152 }; #else #define "Define for this platform type!" #endif // __i386__ #else #error "Define for this platform type!" #endif // _WIN32 const uint8_t * const glyph = reinterpret_cast< const uint8_t * >( *reinterpret_cast< const size_t * >( reinterpret_cast< const uint8_t * >( ft_face) + glyph_offset)); return *reinterpret_cast< const T * >( glyph + bitmap_offset + OFFSET); } template < size_t OFFSET, typename T > T GetGlyphData( const FT_Face::pointer ft_face ) noexcept { #if _WIN32 #if _M_IX86 const size_t glyph_offset { 84 }; #elif _M_X64 const size_t glyph_offset { 120 }; #else #error "Define for this platform type!" #endif // _M_IX86 #elif __linux__ #if __i386__ const size_t glyph_offset { 84 }; #elif __x86_64__ const size_t glyph_offset { 152 }; #else #error "Define for this platform type!" #endif // __i386__ #else #error "Define for this platform type!" #endif // _WIN32 const uint8_t * const glyph = reinterpret_cast< const uint8_t * >( *reinterpret_cast< const size_t * >( reinterpret_cast< const uint8_t * >( ft_face) + glyph_offset)); return *reinterpret_cast< const T * >( glyph + OFFSET); } template < size_t OFFSET, typename T > T GetFaceData( const FT_Face::pointer ft_face ) noexcept { const uint8_t * const face = reinterpret_cast< const uint8_t * >( ft_face); return *reinterpret_cast< const T * >( face + OFFSET); } std::shared_ptr< FreeType > FreeType::Create( ) noexcept { std::shared_ptr< FreeType > instance; #if _WIN32 || __linux__ const char * const module_name = #if _WIN32 #ifdef NDEBUG "freetype.dll"; #else "freetyped.dll"; #endif const auto module = LoadLibrary( module_name); #elif __linux__ #ifdef NDEBUG "libfreetype.so.6"; #else "libfreetype.so.6"; #endif const auto module = dlopen( module_name, RTLD_NOW); #endif try { if (!module) { throw std::runtime_error { "Unable to open freetype library " + std::string { module_name } }; } else { instance.reset( new FreeType { FT_Module { module, [ ] ( void * const module ) { #if _WIN32 FreeLibrary( static_cast< HMODULE >( module)); #elif __linux__ dlclose( module); #endif } }}); } } catch (const std::exception & e) { ReportError( e.what()); } #else #error "Define for this platform!" #endif // _WIN32 return instance; } #if __linux__ std::string ConstructFontPath( const std::string & font_filename ) noexcept { std::string font_abs_path; const auto home_dir = std::getenv( "HOME"); const std::string root_dirs[] { home_dir ? std::string { home_dir } + "/.fonts" : std::string { }, "/usr/local/share/fonts", "/usr/share/fonts" }; for (const auto root_dir : root_dirs) { try { for (const auto & dir_entry : std::filesystem::recursive_directory_iterator( root_dir)) { if (dir_entry.is_regular_file() && dir_entry.path().filename() == font_filename) { font_abs_path = dir_entry.path(); break; } } } catch (const std::exception & e) { ReportError( e.what()); } } return font_abs_path; } #endif // __linux__ bool FreeType::SetFont( const std::string & font_filename ) noexcept { bool set { false }; #if _WIN32 const std::string font_abs_path = "c:/windows/fonts/" + font_filename; #elif __linux__ const std::string font_abs_path = ConstructFontPath( font_filename); #else #error "Define for this platform!" #endif // _WIN32 FT_Face::pointer face_ptr { nullptr }; const auto face_created = new_face_( instance_.get(), font_abs_path.c_str(), 0, &face_ptr); if (face_created == 0) { FT_Face face { face_ptr, face_.get_deleter() }; if (SetSize(face.get(), size_)) { face_.reset( face.release()); glyphs_.clear(); font_filename_ = font_filename; set = true; } } return set; } const std::string & FreeType::GetFont( ) const noexcept { return font_filename_; } bool FreeType::SetSize( const uint32_t size ) noexcept { bool set { false }; if (face_) { set = SetSize( face_.get(), size); if (set) { size_ = size; glyphs_.clear(); } } return set; } uint32_t FreeType::GetSize( ) const noexcept { return size_; } const FreeType::Glyph * FreeType::GetGlyph( const uint32_t character ) noexcept { const Glyph * glyph_ptr { nullptr }; if (face_) { decltype(glyphs_)::const_iterator glyph_it = glyphs_.find( character); if (glyph_it != glyphs_.cend()) { glyph_ptr = &glyph_it->second; } else { const int32_t FT_LOAD_RENDER { 1 << 2 }; const bool loaded = load_char_( face_.get(), character, FT_LOAD_RENDER) == 0; if (loaded) { const auto bitmap_width = GetBitmapWidth(face_.get()); const auto bitmap_height = GetBitmapHeight(face_.get()); Glyph glyph { bitmap_width, bitmap_height, GetGlyphTop(face_.get()), GetGlyphLeft(face_.get()), GetGlyphAdvance(face_.get()), std::vector< uint8_t > ( bitmap_width * bitmap_height ) }; if (const auto data = GetBitmapData(face_.get())) { std::copy( data, data + glyph.bitmap.size(), glyph.bitmap.data()); } const auto inserted = glyphs_.emplace( character, std::move(glyph)); if (inserted.second) { glyph_ptr = &inserted.first->second; } } } } return glyph_ptr; } double FreeType::GetGlobalGlyphHeight( ) const noexcept { double global_glyph_height { 0.0 }; if (face_) { const auto units_per_em = GetFaceUnitsPerEM(face_.get()); if (units_per_em) { const auto ascender = GetFaceAscender(face_.get()); const auto descender = GetFaceDescender(face_.get()); global_glyph_height = static_cast< double >(ascender - descender) * GetSize() / units_per_em; } } return global_glyph_height; } FreeType::FreeType( FT_Module module ) : init_ { GetFuncAddress("FT_Init_FreeType", module.get(), init_) }, uninit_ { GetFuncAddress("FT_Done_FreeType", module.get(), uninit_) }, version_ { GetFuncAddress("FT_Library_Version", module.get(), version_) }, new_face_ { GetFuncAddress("FT_New_Face", module.get(), new_face_) }, delete_face_ { GetFuncAddress("FT_Done_Face", module.get(), delete_face_) }, set_pixel_sizes_ { GetFuncAddress("FT_Set_Pixel_Sizes", module.get(), set_pixel_sizes_) }, load_char_ { GetFuncAddress("FT_Load_Char", module.get(), load_char_) }, size_ { 48 }, glyphs_ { 128 }, module_ { std::move(module) }, instance_ { nullptr, uninit_ }, face_ { nullptr, delete_face_ } { if (!init_ || !uninit_ || !version_ || !new_face_ || !delete_face_ || !set_pixel_sizes_ || !load_char_) { throw std::runtime_error { "Required FreeType functions not found!" }; } FT_Instance::pointer instance { nullptr }; if (init_(&instance) != 0) { throw std::runtime_error { "Unable to initialize a FT instnace!" }; } instance_.reset( instance); int32_t version_mmp[3] { }; version_( instance, version_mmp + 0, version_mmp + 1, version_mmp + 2); const uint32_t version { static_cast< uint32_t >(version_mmp[0] << 16) | static_cast< uint32_t >(version_mmp[1] << 8) | static_cast< uint32_t >(version_mmp[2]) }; // assume that versions greater than the one // specified below are compatible with this impl if (version < 0x00020A00) { throw std::runtime_error { "FreeType version must be 2.10.4 or greater!" }; } else if (version >= 0x00030000) { throw std::runtime_error { "FreeType version validated with 2.x.x of the library! " "A major version upgrade may no longer be compatible!" }; } } bool FreeType::SetSize( const FT_Face::pointer face, const uint32_t size ) noexcept { bool set { false }; if (face) { set = set_pixel_sizes_( face, 0, size) == 0; } return set; } uint32_t FreeType::GetBitmapWidth( const FT_Face::pointer face ) const noexcept { #if _WIN32 #if _M_IX86 const size_t BITMAP_WIDTH_OFFSET { 4 }; #elif _M_X64 const size_t BITMAP_WIDTH_OFFSET { 4 }; #else #error "Define for this platform type!" #endif // _M_IX86 #elif __linux__ #if __i386__ const size_t BITMAP_WIDTH_OFFSET { 4 }; #elif __x86_64__ const size_t BITMAP_WIDTH_OFFSET { 4 }; #else #error "Define for this platform type!" #endif // __i386__ #else #error "Define for this platform type!" #endif // _WIN32 return face ? opengl::GetBitmapData< BITMAP_WIDTH_OFFSET, uint32_t >( face) : 0ul; } uint32_t FreeType::GetBitmapHeight( const FT_Face::pointer face ) const noexcept { #if _WIN32 #if _M_IX86 const size_t BITMAP_HEIGHT_OFFSET { 0 }; #elif _M_X64 const size_t BITMAP_HEIGHT_OFFSET { 0 }; #else #error "Define for this platform type!" #endif // _M_IX86 #elif __linux__ #if __i386__ const size_t BITMAP_HEIGHT_OFFSET { 0 }; #elif __x86_64__ const size_t BITMAP_HEIGHT_OFFSET { 0 }; #else #error "Define for this platform type!" #endif // __i386__ #else #error "Define for this platform type!" #endif // _WIN32 return face ? opengl::GetBitmapData< BITMAP_HEIGHT_OFFSET, uint32_t >( face) : 0ul; } const uint8_t * FreeType::GetBitmapData( const FT_Face::pointer face ) const noexcept { #if _WIN32 #if _M_IX86 const size_t BITMAP_DATA_OFFSET { 12 }; #elif _M_X64 const size_t BITMAP_DATA_OFFSET { 16 }; #else #error "Define for this platform type!" #endif // _M_IX86 #elif __linux__ #if __i386__ const size_t BITMAP_DATA_OFFSET { 12 }; #elif __x86_64__ const size_t BITMAP_DATA_OFFSET { 16 }; #else #error "Define for this platform type!" #endif // __i386__ #else #error "Define for this platform type!" #endif // _WIN32 return face ? opengl::GetBitmapData< BITMAP_DATA_OFFSET, const uint8_t * >( face) : nullptr; } int32_t FreeType::GetGlyphTop( const FT_Face::pointer face ) const noexcept { #if _WIN32 #if _M_IX86 const size_t GLYPH_TOP_OFFSET { 104 }; #elif _M_X64 const size_t GLYPH_TOP_OFFSET { 148 }; #else #error "Define for this platform type!" #endif // _M_IX86 #elif __linux__ #if __i386__ const size_t GLYPH_TOP_OFFSET { 104 }; #elif __x86_64__ const size_t GLYPH_TOP_OFFSET { 196 }; #else #error "Define for this platform type!" #endif // __i386__ #else #error "Define for this platform type!" #endif // _WIN32 return face ? opengl::GetGlyphData< GLYPH_TOP_OFFSET, int32_t >( face) : 0; } int32_t FreeType::GetGlyphLeft( const FT_Face::pointer face ) const noexcept { #if _WIN32 #if _M_IX86 const size_t GLYPH_LEFT_OFFSET { 100 }; #elif _M_X64 const size_t GLYPH_LEFT_OFFSET { 144 }; #else #error "Define for this platform type!" #endif // _M_IX86 #elif __linux__ #if __i386__ const size_t GLYPH_LEFT_OFFSET { 100 }; #elif __x86_64__ const size_t GLYPH_LEFT_OFFSET { 192 }; #else #error "Define for this platform type!" #endif // __i386__ #else #error "Define for this platform type!" #endif // _WIN32 return face ? opengl::GetGlyphData< GLYPH_LEFT_OFFSET, int32_t >( face) : 0; } double FreeType::GetGlyphAdvance( const FT_Face::pointer face ) const noexcept { #if _WIN32 #if _M_IX86 const size_t GLYPH_ADVANCE_OFFSET { 64 }; #elif _M_X64 const size_t GLYPH_ADVANCE_OFFSET { 88 }; #else #error "Define for this platform type!" #endif // _M_IX86 #elif __linux__ #if __i386__ const size_t GLYPH_ADVANCE_OFFSET { 64 }; #elif __x86_64__ const size_t GLYPH_ADVANCE_OFFSET { 128 }; #else #error "Define for this platform type!" #endif // __i386__ #else #error "Define for this platform type!" #endif // _WIN32 return face ? opengl::GetGlyphData< GLYPH_ADVANCE_OFFSET, int32_t >( face) / 64.0 : 0.0; } uint16_t FreeType::GetFaceUnitsPerEM( const FT_Face::pointer face ) const noexcept { #if _WIN32 #if _M_IX86 const size_t FACE_UNITS_PER_EM_OFFSET { 68 }; #elif _M_X64 const size_t FACE_UNITS_PER_EM_OFFSET { 104 }; #else #error "Define for this platform type!" #endif // _M_IX86 #elif __linux__ #if __i386__ const size_t FACE_UNITS_PER_EM_OFFSET { 68 }; #elif __x86_64__ const size_t FACE_UNITS_PER_EM_OFFSET { 136 }; #else #error "Define for this platform type!" #endif // __i386__ #else #error "Define for this platform type!" #endif // _WIN32 return face ? opengl::GetFaceData< FACE_UNITS_PER_EM_OFFSET, uint16_t >( face) : 0; } int16_t FreeType::GetFaceAscender( const FT_Face::pointer face ) const noexcept { #if _WIN32 #if _M_IX86 const size_t FACE_ASCENDER_OFFSET { 70 }; #elif _M_X64 const size_t FACE_ASCENDER_OFFSET { 106 }; #else #error "Define for this platform type!" #endif // _M_IX86 #elif __linux__ #if __i386__ const size_t FACE_ASCENDER_OFFSET { 70 }; #elif __x86_64__ const size_t FACE_ASCENDER_OFFSET { 138 }; #else #error "Define for this platform type!" #endif // __i386__ #else #error "Define for this platform type!" #endif // _WIN32 return face ? opengl::GetFaceData< FACE_ASCENDER_OFFSET, int16_t >( face) : 0; } int16_t FreeType::GetFaceDescender( const FT_Face::pointer face ) const noexcept { #if _WIN32 #if _M_IX86 const size_t FACE_DESCENDER_OFFSET { 72 }; #elif _M_X64 const size_t FACE_DESCENDER_OFFSET { 108 }; #else #error "Define for this platform type!" #endif // _M_IX86 #elif __linux__ #if __i386__ const size_t FACE_DESCENDER_OFFSET { 72 }; #elif __x86_64__ const size_t FACE_DESCENDER_OFFSET { 140 }; #else #error "Define for this platform type!" #endif // __i386__ #else #error "Define for this platform type!" #endif // _WIN32 return face ? opengl::GetFaceData< FACE_DESCENDER_OFFSET, int16_t >( face) : 0; } } // namespace opengl
20.771462
91
0.569171
Deception666
d85fa61a522661759c42f15f766de322e8b4edd9
6,495
cpp
C++
drm/libmediadrm/DrmUtils.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
null
null
null
drm/libmediadrm/DrmUtils.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
null
null
null
drm/libmediadrm/DrmUtils.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
2
2021-07-08T07:42:11.000Z
2021-07-09T21:56:10.000Z
/* * Copyright (C) 2019 The Android Open Source Project * * 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. */ //#define LOG_NDEBUG 0 #define LOG_TAG "DrmUtils" #include <android/hardware/drm/1.0/ICryptoFactory.h> #include <android/hardware/drm/1.0/ICryptoPlugin.h> #include <android/hardware/drm/1.0/IDrmFactory.h> #include <android/hardware/drm/1.0/IDrmPlugin.h> #include <android/hardware/drm/1.1/ICryptoFactory.h> #include <android/hardware/drm/1.1/IDrmFactory.h> #include <android/hardware/drm/1.2/ICryptoFactory.h> #include <android/hardware/drm/1.2/IDrmFactory.h> #include <android/hardware/drm/1.3/ICryptoFactory.h> #include <android/hardware/drm/1.3/IDrmFactory.h> #include <android/hidl/manager/1.2/IServiceManager.h> #include <hidl/HidlSupport.h> #include <utils/Errors.h> #include <utils/Log.h> #include <utils/String16.h> #include <cutils/properties.h> #include <mediadrm/CryptoHal.h> #include <mediadrm/DrmHal.h> #include <mediadrm/DrmUtils.h> #include <mediadrm/ICrypto.h> #include <mediadrm/IDrm.h> using HServiceManager = ::android::hidl::manager::V1_2::IServiceManager; using ::android::hardware::hidl_array; using ::android::hardware::hidl_string; using ::android::hardware::hidl_vec; using namespace ::android::hardware::drm; namespace android { namespace DrmUtils { namespace { template<typename Hal> Hal *MakeObject(status_t *pstatus) { status_t err = OK; status_t &status = pstatus ? *pstatus : err; auto obj = new Hal(); status = obj->initCheck(); if (status != OK && status != NO_INIT) { return NULL; } return obj; } template <typename Hal, typename V> void MakeHidlFactories(const uint8_t uuid[16], V &factories) { sp<HServiceManager> serviceManager = HServiceManager::getService(); if (serviceManager == nullptr) { ALOGE("Failed to get service manager"); exit(-1); } serviceManager->listManifestByInterface(Hal::descriptor, [&](const hidl_vec<hidl_string> &registered) { for (const auto &instance : registered) { auto factory = Hal::getService(instance); if (factory != nullptr) { ALOGI("found %s %s", Hal::descriptor, instance.c_str()); if (!uuid || factory->isCryptoSchemeSupported(uuid)) { factories.push_back(factory); } } } }); } hidl_vec<uint8_t> toHidlVec(const void *ptr, size_t size) { hidl_vec<uint8_t> vec(size); if (ptr != nullptr) { memcpy(vec.data(), ptr, size); } return vec; } hidl_array<uint8_t, 16> toHidlArray16(const uint8_t *ptr) { if (ptr == nullptr) { return hidl_array<uint8_t, 16>(); } return hidl_array<uint8_t, 16>(ptr); } sp<::V1_0::IDrmPlugin> MakeDrmPlugin(const sp<::V1_0::IDrmFactory> &factory, const uint8_t uuid[16], const char *appPackageName) { sp<::V1_0::IDrmPlugin> plugin; factory->createPlugin(toHidlArray16(uuid), hidl_string(appPackageName), [&](::V1_0::Status status, const sp<::V1_0::IDrmPlugin> &hPlugin) { if (status != ::V1_0::Status::OK) { return; } plugin = hPlugin; }); return plugin; } sp<::V1_0::ICryptoPlugin> MakeCryptoPlugin(const sp<::V1_0::ICryptoFactory> &factory, const uint8_t uuid[16], const void *initData, size_t initDataSize) { sp<::V1_0::ICryptoPlugin> plugin; factory->createPlugin(toHidlArray16(uuid), toHidlVec(initData, initDataSize), [&](::V1_0::Status status, const sp<::V1_0::ICryptoPlugin> &hPlugin) { if (status != ::V1_0::Status::OK) { return; } plugin = hPlugin; }); return plugin; } } // namespace bool UseDrmService() { return property_get_bool("mediadrm.use_mediadrmserver", true); } sp<IDrm> MakeDrm(status_t *pstatus) { return MakeObject<DrmHal>(pstatus); } sp<ICrypto> MakeCrypto(status_t *pstatus) { return MakeObject<CryptoHal>(pstatus); } std::vector<sp<::V1_0::IDrmFactory>> MakeDrmFactories(const uint8_t uuid[16]) { std::vector<sp<::V1_0::IDrmFactory>> drmFactories; MakeHidlFactories<::V1_0::IDrmFactory>(uuid, drmFactories); MakeHidlFactories<::V1_1::IDrmFactory>(uuid, drmFactories); MakeHidlFactories<::V1_2::IDrmFactory>(uuid, drmFactories); MakeHidlFactories<::V1_3::IDrmFactory>(uuid, drmFactories); return drmFactories; } std::vector<sp<::V1_0::IDrmPlugin>> MakeDrmPlugins(const uint8_t uuid[16], const char *appPackageName) { std::vector<sp<::V1_0::IDrmPlugin>> plugins; for (const auto &factory : MakeDrmFactories(uuid)) { plugins.push_back(MakeDrmPlugin(factory, uuid, appPackageName)); } return plugins; } std::vector<sp<::V1_0::ICryptoFactory>> MakeCryptoFactories(const uint8_t uuid[16]) { std::vector<sp<::V1_0::ICryptoFactory>> cryptoFactories; MakeHidlFactories<::V1_0::ICryptoFactory>(uuid, cryptoFactories); MakeHidlFactories<::V1_1::ICryptoFactory>(uuid, cryptoFactories); MakeHidlFactories<::V1_2::ICryptoFactory>(uuid, cryptoFactories); MakeHidlFactories<::V1_3::ICryptoFactory>(uuid, cryptoFactories); return cryptoFactories; } std::vector<sp<ICryptoPlugin>> MakeCryptoPlugins(const uint8_t uuid[16], const void *initData, size_t initDataSize) { std::vector<sp<ICryptoPlugin>> plugins; for (const auto &factory : MakeCryptoFactories(uuid)) { plugins.push_back(MakeCryptoPlugin(factory, uuid, initData, initDataSize)); } return plugins; } } // namespace DrmUtils } // namespace android
35.686813
107
0.639723
Dreadwyrm
d860b1c22aafb78a60109848507a96710ecd29b6
1,891
cpp
C++
cpp-macro-parser/test_data/define.cpp
zoloypzuo/regex_engine
22365d7229d1a346ea7a730ebcad1c889c323e1d
[ "MIT" ]
null
null
null
cpp-macro-parser/test_data/define.cpp
zoloypzuo/regex_engine
22365d7229d1a346ea7a730ebcad1c889c323e1d
[ "MIT" ]
null
null
null
cpp-macro-parser/test_data/define.cpp
zoloypzuo/regex_engine
22365d7229d1a346ea7a730ebcad1c889c323e1d
[ "MIT" ]
null
null
null
#define data1 0x20 /*cmment start*/#define /*this is comment*/ data2 2.5f #define data3 L"this is a data" #define data4 true #define data5 'a' #define data6 { {2.0, "abc"}, {1.5, "def"}, {5.6f, "7.2"}} // 浮点与字符串组成的结构体初始化聚合, 再进一步聚合组成了数组 #define data5 {5.0, 7.5, 3.8} #define data6 'c' #define data1 1.0f /* this is float may be changed */ #define data2 2 #define data3 false #define data4 "this is a data" #define data5 'B' #define data6 {1, 6, 3} #define data7 0xa #define data5 'D' #define data6 {1, 6} #define comment "// /* */<!-- --" #define long_unsigned_intn 776255 #define _X 64 #define testE1 -0.00015 #define c_hex 12 #define backslash 92 #define HEX_C 1267 #define HEX_B 261561 #define HEX_A -42152 #define _XY {-23,41} #define unsigned_intn 123 #define c_quote 34 #define special "'1~!@#$^&*()_+-={':[,]}|;.</>?" #define _1X 32.0 #define c_newline 10 #define tab_ 9 #define _Y -84 #define float_only 100.2 #define TT 123123 #define c_back 8 #define controls "\v\'\"\f \"\n\r\t\b\a\\" #define quotes "&#34; (0x0022) 0x21 034 &#x22;" #define _1Y -48.97 #define slash "/ &^ \\" #define NSRT "XXX \\tYYY\\nZZZZ \\n" #define c_formfeed 12 #define controls_v "\\v\\\'\\\"\f \\\"\n\r\\r\t\b\a\\" #define c_oct 10 #define decimal_only 0.0075 #define CHARDATA {97,{98},23} #define quote 34 #define STRDATA {"god","(hi),{how are [you]?}",",",{"inner_{1}",{"inner_{2}","inner_{2}_(1)"}}} #define long_intn 4293955295 #define MC_TEST #define COMPDATA {{{1,3},{2,3,5},{31}},{{12,14},{1,30,0}},23} #define c_vtab 11 #define _wide_str L"This is a string literal." #define NS1 "with tab " #define c_bell 7 #define COMSTRUCT {{1,2.0,"str"},{49,0.075,"\\\\\\\\\\\\\\\\\\//////////////////"},{1952687,1.2,"\v\'\"\f \"\n\r\t\b\a\\"}} #define splitstr "24'23't323df" #define c_squote 39 #define long_double 100.0 #define testE 0.0025 #define trap "#define AA 123" #define c_htab 9 #define c_bslash 92
28.223881
123
0.648334
zoloypzuo
d86271b0f08f0d5601052f4675e6e7657ab7cf56
576
tpp
C++
rb_tree/includes/btree_level_count.tpp
paulahemsi/ft_containers
c7d6c878c25bf4faeb60f86f977639c8a7006776
[ "MIT" ]
1
2022-03-02T15:14:16.000Z
2022-03-02T15:14:16.000Z
rb_tree/includes/btree_level_count.tpp
paulahemsi/ft_containers
c7d6c878c25bf4faeb60f86f977639c8a7006776
[ "MIT" ]
73
2021-12-11T18:54:53.000Z
2022-03-28T01:32:52.000Z
rb_tree/includes/btree_level_count.tpp
paulahemsi/ft_containers
c7d6c878c25bf4faeb60f86f977639c8a7006776
[ "MIT" ]
null
null
null
#ifndef BTREE_LEVEL_COUNT_TPP #define BTREE_LEVEL_COUNT_TPP #include "btree.tpp" template <class T> size_t max_depth(size_t left_depth, size_t right_depth, ft::btree<T> *root) { root++; root--; if (left_depth > right_depth) return (left_depth); return (right_depth); } template <class T> size_t btree_level_count(ft::btree<T> *root) { if (!root || (!root->left && !root->right)) return (0); size_t left_level = btree_level_count(root->left); size_t right_level = btree_level_count(root->right); return (1 + max_depth(left_level, right_level, root)); } #endif
20.571429
75
0.722222
paulahemsi
d86274ba27915117d292cc9a571897383778152b
1,295
cpp
C++
Fw/Log/test/ut/LogTest.cpp
AlperenCetin0/fprime
7e20febd34019c730da1358567e7a512592de4d8
[ "Apache-2.0" ]
9,182
2017-07-06T15:51:35.000Z
2022-03-30T11:20:33.000Z
Fw/Log/test/ut/LogTest.cpp
AlperenCetin0/fprime
7e20febd34019c730da1358567e7a512592de4d8
[ "Apache-2.0" ]
719
2017-07-14T17:56:01.000Z
2022-03-31T02:41:35.000Z
Fw/Log/test/ut/LogTest.cpp
AlperenCetin0/fprime
7e20febd34019c730da1358567e7a512592de4d8
[ "Apache-2.0" ]
1,216
2017-07-12T15:41:08.000Z
2022-03-31T21:44:37.000Z
#include <gtest/gtest.h> #include <Fw/Log/LogPacket.hpp> #include <Fw/Com/ComBuffer.hpp> #include <Fw/Log/LogString.hpp> TEST(FwLogTest,LogPacketSerialize) { // Serialize data Fw::LogPacket pktIn; Fw::LogBuffer buffIn; ASSERT_EQ(Fw::FW_SERIALIZE_OK,buffIn.serialize(static_cast<U32>(12))); Fw::Time timeIn(TB_WORKSTATION_TIME,10,11); pktIn.setId(10); pktIn.setTimeTag(timeIn); pktIn.setLogBuffer(buffIn); Fw::ComBuffer comBuff; ASSERT_EQ(Fw::FW_SERIALIZE_OK,comBuff.serialize(pktIn)); // Deserialize data Fw::LogPacket pktOut; Fw::LogBuffer buffOut; Fw::Time timeOut(TB_WORKSTATION_TIME,10,11); ASSERT_EQ(Fw::FW_SERIALIZE_OK,comBuff.deserialize(pktOut)); ASSERT_EQ(pktOut.getId(),10u); ASSERT_EQ(pktOut.getTimeTag(),timeOut); U32 valOut = 0; buffOut = pktOut.getLogBuffer(); buffOut.resetDeser(); ASSERT_EQ(Fw::FW_SERIALIZE_OK,buffOut.deserialize(valOut)); ASSERT_EQ(valOut,12u); // serialize string Fw::LogStringArg str1; Fw::LogStringArg str2; str1 = "Foo"; buffOut.resetSer(); str1.serialize(buffOut); str2.deserialize(buffOut); ASSERT_EQ(str1,str2); } int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
25.392157
74
0.689575
AlperenCetin0
d866d581aab7118ca1f78c0f9c33c451a948e370
780
cpp
C++
CtCI/chapter20/20.5.cpp
wqw547243068/DS_Algorithm
6d4a9baeb3650a8f93308c7405c9483bac59e98b
[ "RSA-MD" ]
2
2021-12-29T14:42:51.000Z
2021-12-29T14:46:45.000Z
CtCI/chapter20/20.5.cpp
wqw547243068/DS_Algorithm
6d4a9baeb3650a8f93308c7405c9483bac59e98b
[ "RSA-MD" ]
null
null
null
CtCI/chapter20/20.5.cpp
wqw547243068/DS_Algorithm
6d4a9baeb3650a8f93308c7405c9483bac59e98b
[ "RSA-MD" ]
null
null
null
#include <iostream> using namespace std; const int kMaxInt = ~(1<<31); int ShortestDist(string text[], int n, string word1, string word2){ int min = kMaxInt / 2; int pos1 = -min; int pos2 = -min; for(int pos=0; pos<n; ++pos){ if(text[pos] == word1){ pos1 = pos; int dist = pos1 - pos2; if(dist < min) min = dist; } else if(text[pos] == word2){ pos2 = pos; int dist = pos2 - pos1; if(dist < min) min = dist; } } return min; } int main(){ string text[] = { "What","is","your","name","My","name","is","Hawstein" }; int len = 8; cout<<ShortestDist(text, len, "is", "name")<<endl; return 0; }
21.666667
67
0.465385
wqw547243068
d867313f72aa79a829de0e99bb03d1657692db2e
3,923
hpp
C++
include/h3api/H3Creatures/H3CreatureInformation.hpp
Patrulek/H3API
91f10de37c6b86f3160706c1fdf4792f927e9952
[ "MIT" ]
14
2020-09-07T21:49:26.000Z
2021-11-29T18:09:41.000Z
include/h3api/H3Creatures/H3CreatureInformation.hpp
Day-of-Reckoning/H3API
a82d3069ec7d5127b13528608d5350d2b80d57be
[ "MIT" ]
2
2021-02-12T15:52:31.000Z
2021-02-12T16:21:24.000Z
include/h3api/H3Creatures/H3CreatureInformation.hpp
Day-of-Reckoning/H3API
a82d3069ec7d5127b13528608d5350d2b80d57be
[ "MIT" ]
8
2021-02-12T15:52:41.000Z
2022-01-31T15:28:10.000Z
////////////////////////////////////////////////////////////////////// // // // Created by RoseKavalier: // // rosekavalierhc@gmail.com // // Created or last updated on: 2021-02-02 // // ***You may use or distribute these files freely // // so long as this notice remains present.*** // // // ////////////////////////////////////////////////////////////////////// #pragma once #include "h3api/H3Base.hpp" #include "h3api/H3GameData/H3Resources.hpp" #include "h3api/H3Constants/H3CstCreatures.hpp" namespace h3 { _H3API_DECLARE_(CreatureInformation); #pragma pack(push, 4) // * hardcoded creature information in heroes3.exe struct H3CreatureInformation { _H3API_SIZE_(0x74); _H3API_GET_INFO_(0x6747B0, H3CreatureInformation); /** @brief [0] */ // -1 means neutral INT32 town; /** @brief [4] */ // 0 ~ 6 INT32 level; /** @brief [8] */ LPCSTR soundName; /** @brief [C] */ LPCSTR defName; /** @brief [10] */ union { struct { unsigned doubleWide : 1; // 1 unsigned flyer : 1; // 2 unsigned shooter : 1; // 4 unsigned extendedAttack : 1; // 8 ~ aka dragon breath unsigned alive : 1; // 10 unsigned destroyWalls : 1; // 20 unsigned siegeWeapon : 1; // 40 unsigned king1 : 1; // 80 ~ all creatures of 7th level and neutral dragons that do not belong to the KING2 or KING3 unsigned king2 : 1; // 100 unsigned king3 : 1; // 200 unsigned mindImmunity : 1; // 400 unsigned shootsRay : 1; // 800 WoG incorrectly refers to this as 'no obstacle penalty' instead it's a flag used to draw a straight line when shooting - see 0x43F23D unsigned noMeleePenalty : 1; // 1000 unsigned unk2000 : 1; // 2000 unsigned fireImmunity : 1; // 4000 unsigned doubleAttack : 1; // 8000 unsigned noRetaliation : 1; // 10000 unsigned noMorale : 1; // 20000 unsigned undead : 1; // 40000 unsigned attackAllAround : 1; // 80000 unsigned fireballAttack : 1; // 100000 unsigned cannotMove : 1; // 200000 ~21 unsigned summon : 1; // 400000 unsigned clone : 1; // 800000 unsigned morale : 1; // 1000000 unsigned waiting : 1; // 2000000 ~25 unsigned done : 1; // 4000000 unsigned defending : 1; // 8000000 unsigned sacrificed : 1; // 10000000 unsigned noColoring : 1; // 20000000 unsigned gray : 1; // 40000000 unsigned dragon : 1; // 80000000 }; UINT32 flags; }; /** @brief [14] */ LPCSTR nameSingular; /** @brief [18] */ LPCSTR namePlural; /** @brief [1C] */ LPCSTR description; /** @brief [20] */ H3Resources cost; /** @brief [3C] */ INT32 fightValue; /** @brief [40] */ INT32 aiValue; /** @brief [44] */ INT32 grow; /** @brief [48] */ INT32 hGrow; /** @brief [4C] */ INT32 hitPoints; /** @brief [50] */ INT32 speed; /** @brief [54] */ INT32 attack; /** @brief [58] */ INT32 defence; /** @brief [5C] */ INT32 damageLow; /** @brief [60] */ INT32 damageHigh; /** @brief [64] */ INT32 numberShots; /** @brief [68] */ INT32 spellCharges; /** @brief [6C] */ INT32 advMapLow; /** @brief [70] */ INT32 advMapHigh; _H3API_ LPCSTR GetCreatureName(INT32 count) const; _H3API_ H3Resources UpgradeCost(H3CreatureInformation* upg, INT32 count) const; }; _H3API_ASSERT_SIZE_(H3CreatureInformation); #pragma pack(pop) /* align-4 */ } /* namespace h3 */
31.637097
176
0.513638
Patrulek
d86a61337af4391883603fdbccf97280c7f70321
309
cpp
C++
Graphics/Graphics/main.cpp
functard/Graphics-Framework
90ed2e1d4631c6dce5c1aad5003e5a462966be87
[ "MIT" ]
1
2022-02-22T13:42:43.000Z
2022-02-22T13:42:43.000Z
Graphics/Graphics/main.cpp
functard/Graphics-Framework
90ed2e1d4631c6dce5c1aad5003e5a462966be87
[ "MIT" ]
null
null
null
Graphics/Graphics/main.cpp
functard/Graphics-Framework
90ed2e1d4631c6dce5c1aad5003e5a462966be87
[ "MIT" ]
null
null
null
#include "PCH.h" #include "Engine.h" int CALLBACK wWinMain(HINSTANCE _hInstance, HINSTANCE _hPrevInstance, PWSTR _cmdLineArgs, int _cmdShow) { int value = CEngine::Get()->Init(_hInstance); if (FAILED(value)) { return value; } value = CEngine::Get()->Run(); CEngine::Get()->Finish(); return value; }
20.6
103
0.695793
functard
d86fc8514ab5d78bc145138a1f6a44ddf98b29e0
4,283
cc
C++
analysis/aero/rotor_3d_lookup.cc
leozz37/makani
c94d5c2b600b98002f932e80a313a06b9285cc1b
[ "Apache-2.0" ]
1,178
2020-09-10T17:15:42.000Z
2022-03-31T14:59:35.000Z
analysis/aero/rotor_3d_lookup.cc
leozz37/makani
c94d5c2b600b98002f932e80a313a06b9285cc1b
[ "Apache-2.0" ]
1
2020-05-22T05:22:35.000Z
2020-05-22T05:22:35.000Z
analysis/aero/rotor_3d_lookup.cc
leozz37/makani
c94d5c2b600b98002f932e80a313a06b9285cc1b
[ "Apache-2.0" ]
107
2020-09-10T17:29:30.000Z
2022-03-18T09:00:14.000Z
// Copyright 2020 Makani Technologies LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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 <gflags/gflags.h> #include <glog/logging.h> #include <cmath> #include <cstdio> #include <cstdlib> #include <string> #include <iostream> #include "common/c_math/force_moment.h" #include "common/c_math/linalg.h" #include "common/c_math/vec3.h" #include "common/macros.h" #include "common/runfiles_dir.h" #include "control/system_params.h" #include "control/system_types.h" #include "lib/json_load/load_params.h" #include "sim/physics/aero.h" #include "sim/physics/aero_frame.h" #include "sim/sim_params.h" #include "sim/physics/rotor_database_3d.h" #include "sim/sim_types.h" DEFINE_double(v_axial, 0.0, "Axial velocity of rotor, m/s."); DEFINE_double(v_edgewise, 10.0, "Edgewise velocity of rotor, m/s."); DEFINE_double(omega, 150.0, "Angular velocity of rotor, rad/s."); DEFINE_int32(dir, 1, "Spin direction about thrust axis."); DEFINE_double(air_density, 1.10, "Air density, kg/m^3."); namespace { void PrintRotorCoefficients(double z_force, double side_force, double roll_moment, double pitch_moment, double thrust, double torque) { printf( "\n V_axial : %7.1f m/s" "\n V_edgewise : %7.1f m/s" "\n Omega : %7.1f rad/s \n" "\n Thrust FX: %7.1f N" "\n Torque MX: %7.1f Nm" "\n Z Force FZ: %7.1f N" "\n Side Force FY: %7.1f N" "\n Roll Mom MZ: %7.1f Nm" "\n Pitch Mom MY: %7.1f Nm \n\n", FLAGS_v_axial, FLAGS_v_edgewise, FLAGS_omega, thrust, torque, z_force, side_force, roll_moment, pitch_moment); } } // namespace int main(int argc, char *argv[]) { google::InitGoogleLogging(argv[0]); google::ParseCommandLineFlags(&argc, &argv, true); // Specify runfiles dir for database access. SetRunfilesDirFromBinaryPath(argv[0]); // Load runtime parameters. json_load::LoadSystemParams(GetSystemParamsUnsafe()); json_load::LoadSimParams(GetSimParamsUnsafe()); // Pull rotor database name from rotor_sim params. const RotorSimParams &rotor_sim_params = GetSimParams()->rotor_sim; RotorDatabase3d rotor3d(RunfilesDir() + "/database/" + rotor_sim_params.database_3d_names[0].name); // Perform lookup in rotor_database_3d.cc. double z_force = rotor3d.CalcForceZPrime(FLAGS_omega, FLAGS_v_axial, FLAGS_v_edgewise, FLAGS_air_density); double side_force = rotor3d.CalcForceYPrime(FLAGS_omega, FLAGS_v_axial, FLAGS_v_edgewise, FLAGS_air_density, FLAGS_dir); double roll_moment = rotor3d.CalcMomZPrime(FLAGS_omega, FLAGS_v_axial, FLAGS_v_edgewise, FLAGS_air_density, FLAGS_dir); double pitch_moment = rotor3d.CalcMomYPrime(FLAGS_omega, FLAGS_v_axial, FLAGS_v_edgewise, FLAGS_air_density); double thrust = rotor3d.CalcThrust(FLAGS_omega, FLAGS_v_axial, FLAGS_v_edgewise, FLAGS_air_density); double torque = rotor3d.CalcTorque(FLAGS_omega, FLAGS_v_axial, FLAGS_v_edgewise, FLAGS_air_density, FLAGS_dir); // Print to screen. PrintRotorCoefficients(z_force, side_force, roll_moment, pitch_moment, thrust, torque); return EXIT_SUCCESS; }
38.936364
75
0.616157
leozz37
d871ee7890bd384c9b0316a1edc8206e9dd0a4e1
1,922
hpp
C++
test/tgfx-test/internal/ansi-color.hpp
sarahkittyy/tgfx
0839d0f30076708b4b848dcf614ee0a8614aa699
[ "MIT" ]
1
2019-08-18T19:56:26.000Z
2019-08-18T19:56:26.000Z
test/tgfx-test/internal/ansi-color.hpp
sarahkittyy/tgfx
0839d0f30076708b4b848dcf614ee0a8614aa699
[ "MIT" ]
null
null
null
test/tgfx-test/internal/ansi-color.hpp
sarahkittyy/tgfx
0839d0f30076708b4b848dcf614ee0a8614aa699
[ "MIT" ]
null
null
null
#pragma once #include "gtest/gtest.h" #include "tgfx/color.hpp" #include "tgfx/internal/ansi-color.hpp" #ifdef COLOR_MODE_16 TEST(ansi_color, MODE_16) { using namespace tgfx::internal; using tgfx::color; EXPECT_EQ(get_color_escape_code(color()), "\u001b[30m"); EXPECT_EQ(get_color_escape_code(color(128, 128, 128)), "\u001b[1;30m"); EXPECT_EQ(get_color_escape_code(color(), false), "\u001b[40m"); EXPECT_EQ(get_color_escape_code(color(128, 128, 128), false), "\u001b[1;40m"); EXPECT_EQ(get_color_escape_code(color(255, 255, 255)), "\u001b[1;37m"); EXPECT_EQ(get_color_escape_code(color(192, 192, 192)), "\u001b[37m"); EXPECT_EQ(get_color_escape_code(color(255, 255, 255), false), "\u001b[1;47m"); EXPECT_EQ(get_color_escape_code(color(192, 192, 192), false), "\u001b[47m"); } #elif COLOR_MODE_256 TEST(ansi_color, MODE_256) { using namespace tgfx::internal; using tgfx::color; EXPECT_EQ(get_color_escape_code(color(0x880000ff)), "\u001b[38;5;88 m"); EXPECT_EQ(get_color_escape_code(color(0x87af5eff)), "\u001b[38;5;107 m"); EXPECT_EQ(get_color_escape_code(color(0xaf0000ff)), "\u001b[38;5;124 m"); EXPECT_EQ(get_color_escape_code(color(0x880000ff), false), "\u001b[48;5;88 m"); EXPECT_EQ(get_color_escape_code(color(127, 127, 255), false), "\u001b[48;5;105 m"); } #elif COLOR_MODE_TRUE TEST(ansi_color, MODE_TRUE) { using namespace tgfx::internal; using tgfx::color; EXPECT_EQ(get_color_escape_code(color(127, 127, 255)), "\u001b[38;2;127;127;255 m"); EXPECT_EQ(get_color_escape_code(color(127, 127, 255), false), "\u001b[48;2;127;127;255 m"); EXPECT_EQ(get_color_escape_code(color(82, 190, 40)), "\u001b[38;2;82;190;40 m"); EXPECT_EQ(get_color_escape_code(color(82, 190, 40), false), "\u001b[48;2;82;190;40 m"); EXPECT_EQ(get_color_escape_code(color(20, 255, 0)), "\u001b[38;2;20;255;0 m"); EXPECT_EQ(get_color_escape_code(color(20, 255, 0), false), "\u001b[48;2;20;255;0 m"); } #endif
36.264151
92
0.731009
sarahkittyy
d873e38847419568c1beae6747142feb49120324
1,432
hpp
C++
include/dca/phys/dca_step/cluster_solver/ss_ct_hyb/ss_ct_hyb_typedefs.hpp
PMDee/DCA
a8196ec3c88d07944e0499ff00358ea3c830b329
[ "BSD-3-Clause" ]
27
2018-08-02T04:28:23.000Z
2021-07-08T02:14:20.000Z
include/dca/phys/dca_step/cluster_solver/ss_ct_hyb/ss_ct_hyb_typedefs.hpp
PMDee/DCA
a8196ec3c88d07944e0499ff00358ea3c830b329
[ "BSD-3-Clause" ]
200
2018-08-02T18:19:03.000Z
2022-03-16T21:28:41.000Z
include/dca/phys/dca_step/cluster_solver/ss_ct_hyb/ss_ct_hyb_typedefs.hpp
PMDee/DCA
a8196ec3c88d07944e0499ff00358ea3c830b329
[ "BSD-3-Clause" ]
22
2018-08-15T15:50:00.000Z
2021-09-30T13:41:46.000Z
// Copyright (C) 2010 Philipp Werner // // Integrated into DCA++ by Peter Staar (taa@zurich.ibm.com) and Bart Ydens. // // This class defines common types for the Single-Site Hybridization Monte Carlo Integrator. #ifndef DCA_PHYS_DCA_STEP_CLUSTER_SOLVER_SS_CT_HYB_SS_CT_HYB_TYPEDEFS_HPP #define DCA_PHYS_DCA_STEP_CLUSTER_SOLVER_SS_CT_HYB_SS_CT_HYB_TYPEDEFS_HPP #include "dca/linalg/matrix.hpp" #include "dca/phys/dca_step/cluster_solver/ss_ct_hyb/structures/ss_ct_hyb_configuration.hpp" namespace dca { namespace phys { namespace solver { namespace cthyb { // dca::phys::solver::cthyb:: template <class parameters_type, class MOMS_type> class SsCtHybTypedefs { public: // Types that define the profiling. typedef typename parameters_type::concurrency_type concurrency_type; typedef typename parameters_type::profiler_type profiler_type; // Types that define the scalar type and matrix type. typedef double scalartype; // typedef resizeable_square_matrix<scalartype> vertex_vertex_matrix_type; typedef dca::linalg::Matrix<scalartype, dca::linalg::CPU> vertex_vertex_matrix_type; // Types that define the vertex and configuration type. typedef SS_CT_HYB_configuration configuration_type; typedef typename configuration_type::orbital_configuration_type orbital_configuration_type; }; } // cthyb } // solver } // phys } // dca #endif // DCA_PHYS_DCA_STEP_CLUSTER_SOLVER_SS_CT_HYB_SS_CT_HYB_TYPEDEFS_HPP
34.095238
93
0.807263
PMDee
d87a2ac121c97d7ca6e8bf9bca530107ccb1b789
1,845
hpp
C++
oanda_v20/include/oanda/v20/json/exception/OutOfRange.hpp
CodeRancher/offcenter_oanda
c7817299b2c7199508307b2379179923e3f60fdc
[ "Apache-2.0" ]
null
null
null
oanda_v20/include/oanda/v20/json/exception/OutOfRange.hpp
CodeRancher/offcenter_oanda
c7817299b2c7199508307b2379179923e3f60fdc
[ "Apache-2.0" ]
null
null
null
oanda_v20/include/oanda/v20/json/exception/OutOfRange.hpp
CodeRancher/offcenter_oanda
c7817299b2c7199508307b2379179923e3f60fdc
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2020 Scott Brauer * * 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 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. */ /* * @file OutOfRange.hpp * @author Scott Brauer * @date 12-11-2020 */ #ifndef OANDA_V20_JSON_EXCEPTION_OUTOFRANGE_HPP_ #define OANDA_V20_JSON_EXCEPTION_OUTOFRANGE_HPP_ #include <string> #include <stdexcept> #include <sstream> #include <nlohmann/json.hpp> namespace oanda { namespace v20 { namespace json { namespace exception { class OutOfRange : public std::out_of_range { public: explicit OutOfRange(const std::string& what_arg): std::out_of_range(what_arg) {} explicit OutOfRange(const char* what_arg): std::out_of_range(what_arg) {} explicit OutOfRange(nlohmann::json::exception& e, const std::string& file = "", int line = 0, const std::string& function = ""): std::out_of_range(OutOfRange::join({ e.what(), ":id(", std::to_string(e.id), ") ", "File(", file, ") ", "Line(", std::to_string(line), ") ", "Function(", function, ") " })) {} virtual ~OutOfRange() = default; static std::string join(std::initializer_list<std::string> elements) { std::ostringstream ss; for (auto element : elements) ss << element; return ss.str(); } }; } /* namespace exception */ } /* namespace json */ } /* namespace rest */ } /* namespace oanda */ #endif /* OANDA_V20_JSON_EXCEPTION_OUTOFRANGE_HPP_ */
24.6
75
0.695935
CodeRancher
d87b83b50d9c023e4201347db2a271f190fd69c7
1,461
cpp
C++
MyGUIWrapper/Src/EventComboChangePositionTranslator.cpp
AnomalousMedical/Engine
a19e21f597bd277e4ca17e0e5f3f89577f2307bb
[ "MIT" ]
null
null
null
MyGUIWrapper/Src/EventComboChangePositionTranslator.cpp
AnomalousMedical/Engine
a19e21f597bd277e4ca17e0e5f3f89577f2307bb
[ "MIT" ]
null
null
null
MyGUIWrapper/Src/EventComboChangePositionTranslator.cpp
AnomalousMedical/Engine
a19e21f597bd277e4ca17e0e5f3f89577f2307bb
[ "MIT" ]
null
null
null
#include "StdAfx.h" #include "../Include/MyGUIEventTranslator.h" class EventComboChangePositionTranslator : public MyGUIEventTranslator { public: typedef void (*NativeEventDelegate)(MyGUI::ComboBox* sender, size_t index HANDLE_ARG); private: MyGUI::ComboBox* widget; NativeEventDelegate nativeEvent; HANDLE_INSTANCE #ifdef FULL_AOT_COMPILE void fireEvent(MyGUI::ComboBox* sender, size_t index) { nativeEvent(sender, index PASS_HANDLE_ARG); } #endif public: EventComboChangePositionTranslator(MyGUI::ComboBox* widget, EventComboChangePositionTranslator::NativeEventDelegate nativeEventCallback HANDLE_ARG) :widget(widget), nativeEvent(nativeEventCallback) ASSIGN_HANDLE_INITIALIZER { } virtual ~EventComboChangePositionTranslator() { } virtual void bindEvent() { #ifdef FULL_AOT_COMPILE widget->eventComboChangePosition = MyGUI::newDelegate(this, &EventComboChangePositionTranslator::fireEvent); #else widget->eventComboChangePosition = MyGUI::newDelegate(nativeEvent); #endif } virtual void unbindEvent() { widget->eventComboChangePosition = NULL; } }; extern "C" _AnomalousExport EventComboChangePositionTranslator* EventComboChangePositionTranslator_Create(MyGUI::ComboBox* widget, EventComboChangePositionTranslator::NativeEventDelegate nativeEventCallback HANDLE_ARG) { return new EventComboChangePositionTranslator(widget, nativeEventCallback PASS_HANDLE_ARG); }
28.096154
219
0.78987
AnomalousMedical
f21da49631e28baaa66180e8e1e5f8dc690311d7
829
cpp
C++
demo/weather_station/ttn/arduino/library's/Enabling_democode/examples/SensorLib/LoRaPacket.cpp
YangSkyL/lora_weather_station
d1fc9e63bab7b4336770157dbdf1b32cca819645
[ "Apache-2.0" ]
1
2019-06-26T08:18:40.000Z
2019-06-26T08:18:40.000Z
demo/weather_station/ttn/arduino/library's/Enabling_democode/examples/SensorLib/LoRaPacket.cpp
YangSkyL/lora_weather_station
d1fc9e63bab7b4336770157dbdf1b32cca819645
[ "Apache-2.0" ]
null
null
null
demo/weather_station/ttn/arduino/library's/Enabling_democode/examples/SensorLib/LoRaPacket.cpp
YangSkyL/lora_weather_station
d1fc9e63bab7b4336770157dbdf1b32cca819645
[ "Apache-2.0" ]
1
2019-10-05T11:21:30.000Z
2019-10-05T11:21:30.000Z
/* LoRaPacket.cpp - SmartLiving.io Arduino library */ #include "LoRaPacket.h" //create the object LoRaPacket::LoRaPacket() { } unsigned char LoRaPacket::write(unsigned char* result) { result[0] = 0x7E; result[3] = getFrameType(); result[4] = contId; return 5; } //assigns the asset/container id to the packet void LoRaPacket::SetId(unsigned char id) { contId = id; } unsigned char LoRaPacket::getFrameType() { return 0x40; //the default packet type } unsigned char LoRaPacket::calculateCheckSum(unsigned char* toSend, short len) { int sum = 0; for (int i = 0; i < len; i++) sum += toSend[i]; while (sum > 0xFF) { toSend = (unsigned char*) &sum; int newsum = 0; len = sizeof(int); for (int i = 0; i < len; i++) newsum += toSend[i]; sum = newsum; } return 0xFF - (unsigned char) sum; }
19.27907
79
0.651387
YangSkyL
f21e3dd071eeb5eb98135062ae5f08611024fa99
5,605
cxx
C++
smtk/bridge/remote/smtk-model-server.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
smtk/bridge/remote/smtk-model-server.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
4
2016-11-10T15:49:51.000Z
2017-02-06T23:24:16.000Z
smtk/bridge/remote/smtk-model-server.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #ifndef SHIBOKEN_SKIP #include "smtk/Options.h" #include "smtk/SharedPtr.h" #include "smtk/model/StringData.h" #include "smtk/common/Paths.h" #ifndef _MSC_VER # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdelete-non-virtual-dtor" #endif #include "remus/server/Server.h" #include "remus/server/WorkerFactory.h" #ifndef _MSC_VER # pragma GCC diagnostic pop #endif #include "clpp/parser.hpp" #include <iostream> using namespace smtk::model; int usage( int errCode = 0, const std::string& msg = std::string()) { // I. Basic usage info. std::cout << "Usage:\n" << " smtk-model-server [options]\n" << "where options may include\n" << " -no-default-search Excludes default RemusWorker (.rw) search directories.\n" << " -search=<dir> Specifies a path to search for RemusWorker (.rw) files\n" << " -client=<host:port> Specifies the host and port to listen for client connections\n" << " -worker=<host:port> Specifies the host and port to listen for worker connections\n" << "\n" ; // II. Print user-specified message and return exit code. if (!msg.empty()) std::cout << msg << "\n"; return errCode; } // A struct to hold options passed to the model server. struct ProgOpts { ProgOpts() : m_printhelp(false), m_clientSet(false), m_workerSet(false), m_clientHost("127.0.0.1"), m_clientPort(remus::SERVER_CLIENT_PORT), m_workerHost("127.0.0.1"), m_workerPort(remus::SERVER_WORKER_PORT) { smtk::common::Paths paths; this->m_search = paths.workerSearchPaths(); } void setProgPath(const std::string& selfPath) { this->m_progPath = selfPath; } void setPrintHelp() { this->m_printhelp = true; } void setClient(const std::string& hostport) { this->convertHostPort(hostport, this->m_clientHost, this->m_clientPort); this->m_clientSet = true; } void setWorker(const std::string& hostport) { this->convertHostPort(hostport, this->m_workerHost, this->m_workerPort); this->m_workerSet = true; } void clearSearch() { this->m_search.clear(); } void addSearch(const std::string& path) { this->m_search.push_back(path); } std::string progPath() const { return this->m_progPath; } bool printHelp() const { return this->m_printhelp; } std::string clientHost() const { return this->m_clientHost; } int clientPort() const { return this->m_clientPort; } std::string workerHost() const { return this->m_workerHost; } int workerPort() const { return this->m_workerPort; } const StringList& search() const { return this->m_search; } bool clientSet() const { return this->m_clientSet; } bool workerSet() const { return this->m_workerSet; } void convertHostPort(const std::string& hostport, std::string& host, int& port) { std::string::size_type pos = hostport.rfind(':'); if (pos > 0) host = hostport.substr(0, pos); if (pos + 1 != std::string::npos) { std::stringstream pstr(hostport.substr(pos + 1)); pstr >> port; } } bool m_printhelp; bool m_clientSet; bool m_workerSet; std::string m_clientHost; int m_clientPort; std::string m_workerHost; int m_workerPort; StringList m_search; std::string m_progPath; }; int main (int argc, char* argv[]) { ProgOpts opts; opts.setProgPath(argv[0]); clpp::command_line_parameters_parser args; try { args.add_parameter("-no-default-search", &opts, &ProgOpts::clearSearch); args.add_parameter("-search", &opts, &ProgOpts::addSearch); args.add_parameter("-client", &opts, &ProgOpts::setClient); args.add_parameter("-worker", &opts, &ProgOpts::setWorker); args.parse(argc, argv); } catch (std::exception& e) { return usage(1, e.what()); } if (opts.printHelp()) { return usage(0); } remus::server::ServerPorts ports; if (opts.clientSet() || opts.workerSet()) { ports = remus::server::ServerPorts( opts.clientHost(), opts.clientPort(), opts.workerHost(), opts.workerPort()); } boost::shared_ptr<remus::server::WorkerFactory> factory = boost::shared_ptr<remus::server::WorkerFactory>( new remus::server::WorkerFactory); StringList::const_iterator pathIt; for (pathIt = opts.search().begin(); pathIt != opts.search().end(); ++pathIt) { std::cout << "Looking for workers in " << *pathIt << "\n"; factory->addWorkerSearchDirectory(*pathIt); } factory->setMaxWorkerCount(10); remus::common::MeshIOTypeSet mtypes = factory->supportedIOTypes(); remus::common::MeshIOTypeSet::const_iterator it; for (it = mtypes.begin(); it != mtypes.end(); ++it) std::cout << " Worker " << it->inputType() << "->" << it->outputType() << "\n"; std::cout << "Listening for clients on " << ports.client().host() << ":" << ports.client().port() << "\n" << "Listening for workers on " << ports.worker().host() << ":" << ports.worker().port() << "\n" << "...\n"; remus::server::Server server(ports, factory); bool valid = server.startBrokeringWithoutSignalHandling(); server.waitForBrokeringToFinish(); return valid ? 0 : 1; } #endif // SHIBOKEN_SKIP
32.398844
99
0.645852
yumin
f221521881832649aec7153ab6d320a15c241b49
599
cpp
C++
src/cpp/uml/literalSpecification.cpp
nemears/uml-cpp
d72c8b5506f391f2b6a5696972ff8da7ec10bd21
[ "MIT" ]
null
null
null
src/cpp/uml/literalSpecification.cpp
nemears/uml-cpp
d72c8b5506f391f2b6a5696972ff8da7ec10bd21
[ "MIT" ]
1
2022-02-25T18:14:21.000Z
2022-03-10T08:59:55.000Z
src/cpp/uml/literalSpecification.cpp
nemears/uml-cpp
d72c8b5506f391f2b6a5696972ff8da7ec10bd21
[ "MIT" ]
null
null
null
#include "uml/literalSpecification.h" #include "uml/package.h" #include "uml/stereotype.h" #include "uml/behavior.h" #include "uml/dataType.h" #include "uml/association.h" #include "uml/association.h" #include "uml/interface.h" #include "uml/deployment.h" using namespace UML; LiteralSpecification::LiteralSpecification() : Element(ElementType::LITERAL_SPECIFICATION) { } bool LiteralSpecification::isSubClassOf(ElementType eType) const { bool ret = ValueSpecification::isSubClassOf(eType); if (!ret) { ret = eType == ElementType::LITERAL_SPECIFICATION; } return ret; }
23.96
92
0.737896
nemears
f2226373e98348a11d1b6efc7573ac53fe048d6c
2,114
cpp
C++
modules/task_2/kren_p_grid_torus_topology/main.cpp
RachinIA/pp_2020_autumn_engineer
23f7df688a77cad9496b9d95bbe2645e0528f106
[ "BSD-3-Clause" ]
1
2020-10-30T13:49:58.000Z
2020-10-30T13:49:58.000Z
modules/task_2/kren_p_grid_torus_topology/main.cpp
RachinIA/pp_2020_autumn_engineer
23f7df688a77cad9496b9d95bbe2645e0528f106
[ "BSD-3-Clause" ]
1
2020-11-01T18:53:35.000Z
2020-11-01T18:53:35.000Z
modules/task_2/kren_p_grid_torus_topology/main.cpp
RachinIA/pp_2020_autumn_engineer
23f7df688a77cad9496b9d95bbe2645e0528f106
[ "BSD-3-Clause" ]
1
2021-03-14T18:08:22.000Z
2021-03-14T18:08:22.000Z
// Copyright 2020 Kren Polina #include <gtest-mpi-listener.hpp> #include <gtest/gtest.h> #include <mpi.h> #include "./grid_torus_topology.h" TEST(Grid_Torus_Topology, can_create_grid_torus) { MPI_Comm comm_torus = getCommTorus(MPI_COMM_WORLD); int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { ASSERT_TRUE(testGridTorus(comm_torus)); } } TEST(Grid_Torus_Topology, not_cart_comm_has_no_torus_topology) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { ASSERT_FALSE(testGridTorus(MPI_COMM_WORLD)); } } TEST(Grid_Torus_Topology, none_period_comm_has_no_torus_topology) { MPI_Comm main_comm; int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int size; MPI_Comm_size(MPI_COMM_WORLD, &size); int dims[] = { 0, 0 }; int period[] = { 1, 0 }; MPI_Dims_create(size, 2, dims); MPI_Cart_create(MPI_COMM_WORLD, 2, dims, period, 1, &main_comm); if (rank == 0) { ASSERT_FALSE(testGridTorus(main_comm)); } } TEST(Grid_Torus_Topology, cant_create_with_wrong_size) { int rank; int size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm main_comm = getCommTorus(MPI_COMM_WORLD, size + 1); if (rank == 0) { ASSERT_EQ(main_comm, MPI_COMM_NULL); } } TEST(Grid_Torus_Topology, shift_works_correctly) { MPI_Comm comm_torus = getCommTorus(MPI_COMM_WORLD); int rank; MPI_Comm_rank(comm_torus, &rank); bool flag = testRelation(comm_torus); if (rank == 0) { ASSERT_TRUE(flag); } } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); MPI_Init(&argc, &argv); ::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment); ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); listeners.Release(listeners.default_result_printer()); listeners.Release(listeners.default_xml_generator()); listeners.Append(new GTestMPIListener::MPIMinimalistPrinter); return RUN_ALL_TESTS(); }
24.581395
78
0.688269
RachinIA
f2227b20dba0d7ab0fdef547be23b785d97d7b5e
1,340
hpp
C++
module07/ex01/iter.hpp
selysse/CPP-Piscine
72884c60ac5007d34874b006e37dad7a04e846bb
[ "MIT" ]
1
2021-09-17T13:25:47.000Z
2021-09-17T13:25:47.000Z
module07/ex01/iter.hpp
selysse/CPP-Piscine
72884c60ac5007d34874b006e37dad7a04e846bb
[ "MIT" ]
null
null
null
module07/ex01/iter.hpp
selysse/CPP-Piscine
72884c60ac5007d34874b006e37dad7a04e846bb
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* iter.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gselyse <gselyse@student.21-school.ru> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/12 13:56:13 by gselyse #+# #+# */ /* Updated: 2021/03/17 01:30:15 by gselyse ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef ITER_HPP # define ITER_HPP # include <iostream> # include <string> template<typename T> void decrement(T const &input) { T num; num = input; num--; std::cout << num << " "; } template<typename T> void increment(T const &input) { T num; num = input; num++; std::cout << num << " "; } template <typename T> void iter(const T *array, size_t size, void (*f)(const T &p)) { for (size_t i = 0; i < size; i++) f(array[i]); } #endif
31.162791
80
0.281343
selysse
f222dc457ea7882ced38c451d6948f7e32726072
3,879
cpp
C++
sail/csrc/core/kernels/native/Copy.cpp
sail-ml/sail
e261ef22661aa267bcf32d1552be95d8b7255220
[ "BSD-3-Clause" ]
1
2021-04-28T16:29:02.000Z
2021-04-28T16:29:02.000Z
sail/csrc/core/kernels/native/Copy.cpp
sail-ml/sail
e261ef22661aa267bcf32d1552be95d8b7255220
[ "BSD-3-Clause" ]
56
2021-04-28T16:39:05.000Z
2021-07-29T01:13:25.000Z
sail/csrc/core/kernels/native/Copy.cpp
sail-ml/sail
e261ef22661aa267bcf32d1552be95d8b7255220
[ "BSD-3-Clause" ]
null
null
null
// allow-no-header #include "kernels/Copy.h" #include "Tensor.h" #include "factories.h" #include "kernels/dispatch.h" #include "kernels/native/loops.h" #include "loops.h" #include "ops/broadcast.h" #include "slice.h" #include "tensor_shape.h" namespace sail { namespace internal { namespace { void copy_kernel(const Tensor &t1, Tensor &out) { dispatch_all_numeric_types(t1.get_dtype(), [&](auto pt) { using T = typename decltype(pt)::type; struct Impl { inline void call_base(T &x1, T &out) { out = x1; } }; native::UnaryElementwise<T>(Impl{}, t1, out); }); } void cast_kernel(const Tensor &t1, Tensor &out_tensor) { dispatch_all_types(t1.get_dtype(), [&](auto pt) { dispatch_all_types(out_tensor.get_dtype(), [&](auto xt) { using T_in = typename decltype(pt)::type; using T_out = typename decltype(xt)::type; int numel = t1.get_shape().numel(); int i; struct Impl { inline void call_base(T_in &x1, T_out &out) { out = static_cast<T_out>(x1); } }; T_in *p1; T_out *p2; p1 = static_cast<T_in *>(t1.get_data()); p2 = static_cast<T_out *>(out_tensor.get_data()); Impl op = Impl{}; if (t1.is_view()) { TensorShape s = t1.get_shape(); MultiTensorIterator iter = MultiTensorIterator(s); int inner_loop_size = iter.inner_loop_size(); int outer_steps = iter.out_loop_size(); int z = 0; for (int i = 0; i < outer_steps; i++) { for (int j = 0; j < inner_loop_size; j += 1) { op.call_base(p1[iter.d_ptrs[0]], p2[z]); iter.advance_d_ptr(1); z += 1; } iter.backup_d_ptr(); iter.next(); } } else { for (i = 0; i < numel; i += 1) { op.call_base(p1[i], p2[i]); } } }); }); } Tensor _pad_simple(const Tensor &base, Tensor &pad_width) { std::vector<long> new_shape; long loop_size = pad_width.get_shape().shape[0]; for (long i = 0; i < loop_size; i += 1) { Tensor x = pad_width[i]; new_shape.push_back(base.get_shape()[i] + x[0].get<long>() + x[1].get<long>()); } Tensor padded = zeros(TensorShape(new_shape), base.get_dtype()); std::vector<std::vector<long>> original_area; for (long i = 0; i < loop_size; i += 1) { Tensor x = pad_width[i]; long left = x[0].get<long>(); long size = base.get_shape()[i]; std::vector<long> slice = {left, left + size}; original_area.push_back(slice); } Slice s = Slice(original_area); padded.slice(s).assign(base); return padded; } Tensor pad_kernel(const Tensor &t1, std::vector<std::vector<long>> pads) { std::vector<long> flat; for (std::vector<long> inner : pads) { for (long i : inner) { flat.push_back(i); } } void *pads_ptr = (void *)flat.data(); long pad_size = static_cast<long>(pads.size()); long pad_0_size = static_cast<long>(pads[0].size()); Tensor pad_tensor_ = from_data(pads_ptr, Dtype::sInt64, TensorShape({pad_size, pad_0_size})); Tensor pad_tensor = ops::broadcast_to(pad_tensor_, TensorShape({t1.get_ndim(), 2})); Tensor o = _pad_simple(t1, pad_tensor); return o; } } // namespace REGISTER_ARCH_DISPATCH(copy_stub, DEFAULT, &copy_kernel); REGISTER_ONLY_NATIVE_DISPATCH(cast_stub, &cast_kernel); REGISTER_ONLY_NATIVE_DISPATCH(pad_stub, &pad_kernel); } // namespace internal } // namespace sail
29.610687
80
0.544986
sail-ml
f224794ac91fd4286b36c860fd316f0f4eadf478
756
cpp
C++
Year3Game/PitchRegion.cpp
EvanCGriffin/soccergame
8056b39a4c7adfab3aa47333237474fc8250e7ac
[ "MIT" ]
1
2021-09-29T14:27:07.000Z
2021-09-29T14:27:07.000Z
Year3Game/PitchRegion.cpp
EvanCGriffin/soccergame
8056b39a4c7adfab3aa47333237474fc8250e7ac
[ "MIT" ]
null
null
null
Year3Game/PitchRegion.cpp
EvanCGriffin/soccergame
8056b39a4c7adfab3aa47333237474fc8250e7ac
[ "MIT" ]
null
null
null
#include "PitchRegion.h" #include <Year3Engine\Utils.h> PitchRegion::PitchRegion(double x, double y, double width, double height, int id) :id(id) { rect = SDL_Rect(); rect.x = x; rect.y = y; rect.w = width; rect.h = height; center = b2Vec2(x + (width * 0.5), y + (height * 0.5)); color = b2Color(0, 0, 0); } PitchRegion::~PitchRegion(void) { } void PitchRegion::Draw(DebugDraw* debugDraw) { b2AABB aabb; aabb.lowerBound = b2Vec2(rect.x, rect.y + rect.h); aabb.upperBound = b2Vec2(rect.x + rect.w, rect.y); debugDraw->DrawCircle(center, 10, color); debugDraw->DrawAABB(&aabb, color); } inline b2Vec2 PitchRegion::GetRandomPosition() { return b2Vec2(RandInRange(rect.x, (rect.x + rect.w)), RandInRange(rect.y, (rect.y + rect.h))); }
19.384615
81
0.667989
EvanCGriffin
f226daa5fa73416c271ea4aad4fe53a00c444e78
12,892
cpp
C++
game_state.cpp
tobiascr/four-in-a-row-cpp
64d4cbe9d40b98dde66ba73ecff0a01b5baad1dc
[ "MIT" ]
1
2020-07-24T01:50:58.000Z
2020-07-24T01:50:58.000Z
game_state.cpp
tobiascr/four-in-a-row-cpp
64d4cbe9d40b98dde66ba73ecff0a01b5baad1dc
[ "MIT" ]
null
null
null
game_state.cpp
tobiascr/four-in-a-row-cpp
64d4cbe9d40b98dde66ba73ecff0a01b5baad1dc
[ "MIT" ]
null
null
null
#include <bitset> #include "game_state.h" namespace Engine { GameState::GameState() { reset(); } void GameState::reset() { bitboard[0] = 0; bitboard[1] = 0; number_of_moves = 0; player_in_turn = 0; } char GameState::get_value(int column, int row) const { if ((bitboard[0] >> (column * 7 + row)) & one == 1) { return '1'; } if ((bitboard[1] >> (column * 7 + row)) & one == 1) { return '2'; } return '0'; } bool GameState::column_not_full(int column) const { return get_number_of_disks_in_column(column) < 6; } int GameState::get_number_of_disks_in_column(int column) const { const std::array<uint64_t, 7> columns = { 0b0000000000000000000000000000000000000000000111111, 0b0000000000000000000000000000000000001111110000000, 0b0000000000000000000000000000011111100000000000000, 0b0000000000000000000000111111000000000000000000000, 0b0000000000000001111110000000000000000000000000000, 0b0000000011111100000000000000000000000000000000000, 0b0111111000000000000000000000000000000000000000000}; const std::bitset<64> bits = (bitboard[0] | bitboard[1]) & columns[column]; return bits.count(); } void GameState::make_move(int column) { const uint64_t nm = next_move(column); history[number_of_moves] = bitboard[player_in_turn]; bitboard[player_in_turn] |= nm; number_of_moves++; player_in_turn = 1 - player_in_turn; } void GameState::undo_move(int column) { number_of_moves--; player_in_turn = 1 - player_in_turn; bitboard[player_in_turn] = history[number_of_moves]; } void GameState::make_move_fast(uint64_t move_bitboard) { bitboard[player_in_turn] |= move_bitboard; number_of_moves++; player_in_turn = 1 - player_in_turn; } void GameState::undo_move_fast(uint64_t move_bitboard) { number_of_moves--; player_in_turn = 1 - player_in_turn; bitboard[player_in_turn] ^= move_bitboard; } uint64_t GameState::next_move(int column) const { const uint64_t next_moves = get_next_moves(); const std::array<uint64_t, 7> columns = { 0b0000000000000000000000000000000000000000000111111, 0b0000000000000000000000000000000000001111110000000, 0b0000000000000000000000000000011111100000000000000, 0b0000000000000000000000111111000000000000000000000, 0b0000000000000001111110000000000000000000000000000, 0b0000000011111100000000000000000000000000000000000, 0b0111111000000000000000000000000000000000000000000}; return next_moves & columns[column]; } bool GameState::four_in_a_row() const { return four_in_a_row(bitboard[1 - player_in_turn]); } bool GameState::four_in_a_row(uint64_t bitboard) const { /* Looking for four in a rows is done in two steps. The first step produces a bitboard with a three in a row if there is a four in a row. The second step checks if there exist points that are two steps distant from each other.*/ uint64_t a; const int shifts[4] = {6, 8, 7, 1}; for (int n=0; n<=3; n++) { a = (bitboard << shifts[n]) & bitboard; if (a & (a << (shifts[n] * 2))) {return true;} } return false; } bool GameState::four_in_a_row_no_vertical(uint64_t bitboard) const { /* Looking for four in a rows is done in two steps. The first step produces a bitboard with a three in a row if there is a four in a row. The second step checks if there exist points that are two steps distant from each other.*/ uint64_t a; const int shifts[3] = {6, 8, 7}; for (int n=0; n<=2; n++) { a = (bitboard << shifts[n]) & bitboard; if (a & (a << (shifts[n] * 2))) {return true;} } return false; } bool GameState::four_in_a_row(int player, int column, int row) const { return four_in_a_row(bitboard[player] | (one << (column * 7 + row))); } bool GameState::can_win_this_move() const { const uint64_t b = bitboard[player_in_turn]; const uint64_t next_moves = get_next_moves(); // Masks for various columns. const uint64_t mask_0246 = 0b0111111000000001111110000000011111100000000111111; const uint64_t mask_04 = 0b0000000000000001111110000000000000000000000111111; const uint64_t mask_26 = 0b0111111000000000000000000000011111100000000000000; const uint64_t mask_135 = 0b0000000011111100000000111111000000001111110000000; const uint64_t mask_15 = 0b0000000011111100000000000000000000001111110000000; const uint64_t mask_3 = 0b0000000000000000000000111111000000000000000000000; // First a test of 4 moves together that might give a false positive. if (four_in_a_row(b | (mask_0246 & next_moves))) { // To rule out false positives, more tests are done. // Test column 0 and 4. if (four_in_a_row(b | (mask_04 & next_moves))) {return true;} // Test column 2 and 6. if (four_in_a_row(b | (mask_26 & next_moves))) {return true;} } // First a test of 3 moves together that might give a false positive. if (four_in_a_row(b | (mask_135 & next_moves))) { // To rule out false positives, more tests are done. // Test column 1 and 5. if (four_in_a_row(b | (mask_15 & next_moves))) {return true;} // Test column 3. if (four_in_a_row(b | (mask_3 & next_moves))) {return true;} } return false; } bool GameState::opponent_four_in_a_row_above(int column) const { if (get_number_of_disks_in_column(column) >= 5) {return false;} return four_in_a_row_no_vertical(bitboard[1 - player_in_turn] | (next_move(column) << 1)); } bool GameState::own_threat_above(int column) const { if (get_number_of_disks_in_column(column) >= 5) {return false;} return four_in_a_row_no_vertical(bitboard[player_in_turn] | (next_move(column) << 1)); } bool GameState::is_blocking_move(int column) const { return four_in_a_row(bitboard[1 - player_in_turn] | next_move(column)); } uint64_t GameState::get_opponent_winning_positions_bitboard() const { return get_winning_positions_bitboard(bitboard[1 - player_in_turn]); } uint64_t GameState::get_winning_positions_bitboard(uint64_t bitboard) const /* Can also include already occupied positions and positions outside the board.*/ { // Vertical direction uint64_t winning_positions = (bitboard & (bitboard << 1) & (bitboard << 2)) << 1; // Horizontal direction winning_positions |= (bitboard & (bitboard << 7) & (bitboard << 14)) << 7; // ooox winning_positions |= (bitboard & (bitboard << 7) & (bitboard << 14)) >> 21; // xooo winning_positions |= ((bitboard & (bitboard << 21)) & (bitboard << 14)) >> 7; // ooxo winning_positions |= ((bitboard & (bitboard << 21)) & (bitboard << 7)) >> 14; // oxoo // Diagonal direction 1 winning_positions |= (bitboard & (bitboard << 6) & (bitboard << 12)) << 6; // ooox winning_positions |= (bitboard & (bitboard << 6) & (bitboard << 12)) >> 18; // xooo winning_positions |= ((bitboard & (bitboard << 18)) & (bitboard << 12)) >> 6; // ooxo winning_positions |= ((bitboard & (bitboard << 18)) & (bitboard << 6)) >> 12; // oxoo // Diagonal direction 2 winning_positions |= (bitboard & (bitboard << 8) & (bitboard << 16)) << 8; // ooox winning_positions |= (bitboard & (bitboard << 8) & (bitboard << 16)) >> 24; // xooo winning_positions |= ((bitboard & (bitboard << 24)) & (bitboard << 16)) >> 8; // ooxo winning_positions |= ((bitboard & (bitboard << 24)) & (bitboard << 8)) >> 16; // oxoo return winning_positions; } uint64_t GameState::get_winning_positions_bitboard_non_vertical(uint64_t bitboard) const /* Can also include already occupied positions and positions outside the board.*/ { uint64_t winning_positions = 0; // Horizontal direction winning_positions |= (bitboard & (bitboard << 7) & (bitboard << 14)) << 7; // ooox winning_positions |= (bitboard & (bitboard << 7) & (bitboard << 14)) >> 21; // xooo winning_positions |= ((bitboard & (bitboard << 21)) & (bitboard << 14)) >> 7; // ooxo winning_positions |= ((bitboard & (bitboard << 21)) & (bitboard << 7)) >> 14; // oxoo // Diagonal direction 1 winning_positions |= (bitboard & (bitboard << 6) & (bitboard << 12)) << 6; // ooox winning_positions |= (bitboard & (bitboard << 6) & (bitboard << 12)) >> 18; // xooo winning_positions |= ((bitboard & (bitboard << 18)) & (bitboard << 12)) >> 6; // ooxo winning_positions |= ((bitboard & (bitboard << 18)) & (bitboard << 6)) >> 12; // oxoo // Diagonal direction 2 winning_positions |= (bitboard & (bitboard << 8) & (bitboard << 16)) << 8; // ooox winning_positions |= (bitboard & (bitboard << 8) & (bitboard << 16)) >> 24; // xooo winning_positions |= ((bitboard & (bitboard << 24)) & (bitboard << 16)) >> 8; // ooxo winning_positions |= ((bitboard & (bitboard << 24)) & (bitboard << 8)) >> 16; // oxoo return winning_positions; } uint64_t GameState::get_next_moves() const { return (bitboard[0] | bitboard[1]) + bottom_row; } uint64_t GameState::get_non_losing_moves() const { const uint64_t next_moves = get_next_moves(); const uint64_t opponent_winning_positions = get_winning_positions_bitboard(bitboard[1 - player_in_turn]) & board_mask; const uint64_t blocking_moves = opponent_winning_positions & next_moves; if(blocking_moves) { if(blocking_moves & (blocking_moves - 1)) // Test if more than 1 bit is set to 1. { return 0; } else { if((opponent_winning_positions >> 1) & blocking_moves) { return 0; } else { return blocking_moves; } } } return next_moves & board_mask & (~(opponent_winning_positions >> 1)); } int GameState::open_four_in_a_row_count(int player) const { std::bitset<64> winning_positions = get_winning_positions_bitboard_non_vertical (bitboard[player]) & board_mask & (~(bitboard[0] | bitboard[1])); return winning_positions.count(); } bool GameState::board_full() const { return number_of_moves == 42; } int GameState::get_number_of_moves() const { return number_of_moves; } int GameState::get_player_in_turn() const { return player_in_turn; } uint64_t GameState::get_unique_key() const { // return bitboard[0] | next_moves; return bitboard[0] + 2 * bitboard[1]; // This works because the next moves bitboard can be expressed as bitboard[0] + bitboard[1] + bottom_row. // Skipping bottom_row every time does not change the uniqueness. } uint64_t GameState::get_unique_mirror_key() const { uint64_t key = get_unique_key(); uint64_t mirrored_key = 0; const int bitboard_height = 7; mirrored_key |= (key & 0b0000000000000000000000000000000000000000001111111) << (bitboard_height * 6); mirrored_key |= (key & 0b0000000000000000000000000000000000011111110000000) << (bitboard_height * 4); mirrored_key |= (key & 0b0000000000000000000000000000111111100000000000000) << (bitboard_height * 2); mirrored_key |= (key & 0b0000000000000000000001111111000000000000000000000); mirrored_key |= (key & 0b0000000000000011111110000000000000000000000000000) >> (bitboard_height * 2); mirrored_key |= (key & 0b0000000111111100000000000000000000000000000000000) >> (bitboard_height * 4); mirrored_key |= (key & 0b1111111000000000000000000000000000000000000000000) >> (bitboard_height * 6); return mirrored_key; } int GameState::possible_four_in_a_row_count(bool include_vertical) { int number_of_possible_four_in_a_rows = 0; int start_index = 0; if(not include_vertical) { start_index = 21; }; for(int i = start_index; i< 69; i++) { if((four_in_a_row_bitboards[i] & bitboard[player_in_turn]) == 0) { if(four_in_a_row_bitboards[i] & bitboard[1 - player_in_turn]) { number_of_possible_four_in_a_rows++; } }; } return number_of_possible_four_in_a_rows; } int GameState::open_four_in_a_row_count_2_missing(bool include_vertical) { int n = 0; int start_index = 0; if(not include_vertical) { start_index = 21; }; for(int i = start_index; i< 69; i++) { if((four_in_a_row_bitboards[i] & bitboard[player_in_turn]) == 0) { std::bitset<64> possible_open_four_in_a_row = four_in_a_row_bitboards[i] & bitboard[1 - player_in_turn]; if(possible_open_four_in_a_row.count() == 2) { n++; } }; } return n; } }
32.887755
109
0.657074
tobiascr
f2281ed3b38a89f2fceaa74170a27e25a348fee5
3,213
cpp
C++
src/geno/engine/GenoEngine.cpp
Gnarwhal/LudumDare44
a09e60a57cd7da22d401651ae4b9fbe3f7389ab0
[ "MIT" ]
1
2019-01-27T15:09:08.000Z
2019-01-27T15:09:08.000Z
src/geno/engine/GenoEngine.cpp
GnarlyNarwhal/Genome
35701f56b7c581e162e4bd5dab42f5df52e77ba5
[ "MIT" ]
null
null
null
src/geno/engine/GenoEngine.cpp
GnarlyNarwhal/Genome
35701f56b7c581e162e4bd5dab42f5df52e77ba5
[ "MIT" ]
null
null
null
/******************************************************************************* * * Copyright (c) 2018 Gnarly Narwhal * * ----------------------------------------------------------------------------- * * 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 <iostream> #include "../gl/GenoGL.h" #include "GenoInput.h" #include "GenoMonitor.h" #include "../audio/GenoAudioDevice.h" #include "GenoEngine.h" namespace { void errorCallback(int32 code, const char * message); } GenoLoopCallback GenoEngine::callback = 0; GenoLoop * GenoEngine::loop = 0; GenoEngine::GenoEventPollFunc GenoEngine::getEvents = 0; void GenoEngine::defaultLoop() { GenoInput::update(); GenoEngine::pollEvents(); callback(); } bool GenoEngine::init() { glfwSetErrorCallback(errorCallback); if (!glfwInit()) { std::cerr << "GL Framework failed to initialize!" << std::endl; return false; } getEvents = glfwPollEvents; GenoMonitors::init(); GenoAudioDevices::init(); return true; } bool GenoEngine::initGlew() { if (glewInit() != GLEW_NO_ERROR) { std::cerr << "GL Extension Wrangler failed to initialize!" << std::endl; return false; } return true; } void GenoEngine::setLoop(GenoLoopCreateInfo info, bool overrideDefault) { delete loop; if (!overrideDefault) { callback = info.callback; info.callback = defaultLoop; } loop = new GenoLoop(info); } void GenoEngine::startLoop() { loop->start(); } void GenoEngine::stopLoop() { loop->stop(); } void GenoEngine::destroy() { stopLoop(); delete loop; GenoAudioDevices::cleanup(); GenoMonitors::cleanup(); glfwTerminate(); } void GenoEngine::setSwapInterval(uint8 swapInterval) { glfwSwapInterval(swapInterval); } void GenoEngine::pollEvents() { getEvents(); } void GenoEngine::setPollFunc(bool pollFunc) { getEvents = pollFunc ? glfwPollEvents : glfwWaitEvents; } GenoLoop * GenoEngine::getLoop() { return loop; } GenoEngine::GenoEngine() {} GenoEngine::~GenoEngine() {} namespace { void errorCallback(int32 code, const char * message) { std::cerr << "GLFW error " << code << ": " << message << std::endl; } }
25.299213
81
0.668223
Gnarwhal
f229c54432c3bf2ab8a1dd4e7adfa72a77cb1bd0
120
hxx
C++
src/Providers/UNIXProviders/ElementAsUser/UNIX_ElementAsUser_AIX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/ElementAsUser/UNIX_ElementAsUser_AIX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/ElementAsUser/UNIX_ElementAsUser_AIX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
#ifdef PEGASUS_OS_AIX #ifndef __UNIX_ELEMENTASUSER_PRIVATE_H #define __UNIX_ELEMENTASUSER_PRIVATE_H #endif #endif
10
38
0.841667
brunolauze
f22c51e01de12190eb227150f08205f7520db7b2
319
cpp
C++
utils/utils.cpp
bitesandbytes/supreme-octo-adventure
795d69ab9eaf1ef8f7e938dca8799b4560368538
[ "MIT" ]
null
null
null
utils/utils.cpp
bitesandbytes/supreme-octo-adventure
795d69ab9eaf1ef8f7e938dca8799b4560368538
[ "MIT" ]
null
null
null
utils/utils.cpp
bitesandbytes/supreme-octo-adventure
795d69ab9eaf1ef8f7e938dca8799b4560368538
[ "MIT" ]
null
null
null
#include <stdlib.h> #include "utils.h" double Utils::doubleRand() { double r, x; r = ((double) rand() / ((double) (RAND_MAX) + (double) (1))); return r; } int Utils::randInRange(int max) { double r, x; r = ((double) rand() / ((double) (RAND_MAX) + (double) (1))); x = (r * (max + 1)); return (int) x; }
19.9375
63
0.551724
bitesandbytes
f22e7e2e6c5533baf6f8f2c9e1481b7571bd7cef
587
hxx
C++
src/Tools/Algo/Predicate_ite.hxx
WilliamMajor/aff3ct
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
[ "MIT" ]
1
2022-02-17T08:47:47.000Z
2022-02-17T08:47:47.000Z
src/Tools/Algo/Predicate_ite.hxx
WilliamMajor/aff3ct
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
[ "MIT" ]
null
null
null
src/Tools/Algo/Predicate_ite.hxx
WilliamMajor/aff3ct
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
[ "MIT" ]
1
2021-11-24T01:54:41.000Z
2021-11-24T01:54:41.000Z
#include <sstream> #include "Tools/Exception/exception.hpp" #include "Tools/Algo/Predicate_ite.hpp" namespace aff3ct { namespace tools { Predicate_ite::Predicate_ite(const int n_ite) : n_ite(n_ite), cur_ite(0) { if (n_ite <= 0) { std::stringstream message; message << "'n_ite' has to be equal or greater than 0 ('n_ite' = " << n_ite << ")."; throw invalid_argument(__FILE__, __LINE__, __func__, message.str()); } } bool Predicate_ite::operator()() { const bool predicate = cur_ite >= n_ite; cur_ite++; return predicate; } void Predicate_ite::reset() { cur_ite = 0; } } }
17.787879
86
0.689949
WilliamMajor
f233a4d50426273586dd94dd8cd0ec33e1c131af
309
cpp
C++
URI/1175/1175.cpp
IrineuAlmeidaJr/C
e04e818be1e8b302cc5d542f4b0ba9c6e07d9b15
[ "MIT" ]
null
null
null
URI/1175/1175.cpp
IrineuAlmeidaJr/C
e04e818be1e8b302cc5d542f4b0ba9c6e07d9b15
[ "MIT" ]
null
null
null
URI/1175/1175.cpp
IrineuAlmeidaJr/C
e04e818be1e8b302cc5d542f4b0ba9c6e07d9b15
[ "MIT" ]
null
null
null
#include<stdio.h> #define TF 20 int main() { int vet[TF], i, aux1, aux2; for (i=0; i<TF; i++) scanf("%d", &vet[i]); i=0; while (i<TF/2) { aux1=vet[TF-1-i]; aux2=vet[i]; vet[i]=aux1; vet[TF-1-i]=aux2; i++; } for (i=0; i<TF; i++) printf("N[%d] = %d\n", i, vet[i]); return 0; }
11.035714
36
0.475728
IrineuAlmeidaJr
f238ee98b99c834ac94915d167f36ecddee11a3a
3,982
cpp
C++
sources/main.cpp
BiarnGamer/pommeDePin
21f525e728614c31d08d8b90821d37b74e481203
[ "Apache-2.0" ]
null
null
null
sources/main.cpp
BiarnGamer/pommeDePin
21f525e728614c31d08d8b90821d37b74e481203
[ "Apache-2.0" ]
null
null
null
sources/main.cpp
BiarnGamer/pommeDePin
21f525e728614c31d08d8b90821d37b74e481203
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <string> #include <cstdlib> #include <ctime> #include "../entetes/animal.h" //Déja inclut dans menu.h //#include "../entetes/enclos.h" #include "../entetes/set.h" #include "../entetes/parc.h" #include "../entetes/menu.h" #include "../entetes/affichage.h" // Pas besoin de utilisateur.h car il est inclut dans menu.h //#include "../entetes/utilisateur.h" using namespace std; void chargerJeuTest(Parc & Parc1) { /* *************************** */ /* CRÉATION D'ANIMAUX */ /* *************************** */ Tigre Helico(105, 654, "Diego", 1); Tigre Paul(241, 3321, "Pau'Pol", 2); Tigre Paul2(541, 12, "Chicos", 2); Basque Xabi(125, 63, 1, 9999, "Xabi", 3); Basque Ninicolas(12, 125, 14, 4419, "Nicolas Belloir", 4); Basque Antoine(36, 4512, 124, 874, "Antoine Lefier", 4); Marmotte Miam(95, 6544, "Shakira", 5); Marmotte Tekitoi(245, 20, "Rihanna", 6); Marmotte pipicaca(42, 874, "Roberta", 6); Elephant Pikachu(1021, 365, 102, "Valentin", 74); Elephant PHP(412, 35, 212, "C++", 744); Elephant Elephanto(874, 384, 784, "Chabal", 744); Aigle Piafabec(95, 6544, "Poussin", 51); Aigle Roucarnage(652, 474, "Pousse pousse", 11); Aigle Nirondelle(412, 24, "Envole Moi", 11); Lapin Valou(64, "Rouge", "Mimie Matti", 26); Lapin Tuture(205, "Blanche", "GTi", 205); Lapin Lapine(412, "Invisible", "Nom temporaire en attendant d'avoir des parents inspirés", 205); Tortue Toto(35, 1201, "Arc-end-ciel", "Speedy Gonzalez", 7); Tortue Toutou(135, 11, "La même que toi", "Faut pas pousser mes mail dans les ordis !", 17); Tortue TordreTue(42, 8751, "Transparent", "Wall-E", 17); Crocodile GrosseDent(3045, 124, "Mange de l'herbe", 8); Crocodile MoiJaiFaim(212345, 542, "Trotro Rigolo !", 84); Crocodile Grr(4577, 697, "RRRrrrr", 84); Girafe PetiteB(120, 5412, "Gigi", 9); Girafe QuiVeutDesTalons(21, 6854, "Tour Eiffel", 19); Girafe Torticoli(784, 124, "TeCognePas!", 19); Loutre loulou(12,14,"Moi j'ai des amis !", 110); Loutre PasDeSequelles(1,4,"Gnééé !", 150); Loutre Gneeee(174,474,"Gogo Gadgeto !", 150); /* *************************** */ /* CRÉATION D'ENCLOS */ /* *************************** */ Parc1.creerEnclos("Attrapez-les tous !",1,23); Parc1.creerEnclos("Zone 51",3,2); Parc1.creerEnclos("Fac Informatique",2,53); Parc1.creerEnclos("La planète des singes",3,5); Parc1.creerEnclos("Qwerty",1,21); Parc1.creerEnclos("Cours Structure de Donnée",3,4); Parc1.creerEnclos("La pension",2,85); Parc1.creerEnclos("Pikachu Island",2,3); Parc1.creerEnclos("Enclos R2D2",1,42); Parc1.creerEnclos("Coin des développeurs",1,64); /* *************************** */ /* AJOUT D'ANIMAUX */ /* *************************** */ /* Répartition des animaux : aléatoire, en respectant ces quotas : 3 et 5 : vides 1:4 2:3 4:5 6:2 7:1 8:6 9:4 10:5 */ Parc1.creerAnimal(&Helico,1); Parc1.creerAnimal(&Paul,1); Parc1.creerAnimal(&Paul2,4); Parc1.creerAnimal(&Xabi,6); Parc1.creerAnimal(&Ninicolas,2); Parc1.creerAnimal(&Antoine,4); Parc1.creerAnimal(&Miam,7); Parc1.creerAnimal(&Tekitoi,9); Parc1.creerAnimal(&pipicaca,6); Parc1.creerAnimal(&Piafabec,10); Parc1.creerAnimal(&Roucarnage,8); Parc1.creerAnimal(&Nirondelle,10); Parc1.creerAnimal(&Valou,4); Parc1.creerAnimal(&Tuture,1); Parc1.creerAnimal(&Lapine,8); Parc1.creerAnimal(&Toto,8); Parc1.creerAnimal(&Toutou,10); Parc1.creerAnimal(&TordreTue,9); Parc1.creerAnimal(&GrosseDent,8); Parc1.creerAnimal(&MoiJaiFaim,1); Parc1.creerAnimal(&Grr,10); Parc1.creerAnimal(&PetiteB,10); Parc1.creerAnimal(&Torticoli,9); Parc1.creerAnimal(&QuiVeutDesTalons,8); Parc1.creerAnimal(&loulou,2); Parc1.creerAnimal(&PasDeSequelles,2); Parc1.creerAnimal(&Gneeee,9); Parc1.creerAnimal(&Pikachu,4); Parc1.creerAnimal(&PHP,4); Parc1.creerAnimal(&Elephanto,8); } int main() { /** POUR DE L'ALÉATOIRE **/ srand(time(NULL)); Parc Parc1; chargerJeuTest(Parc1); menuPrincipal(Parc1); return 0; }
27.088435
97
0.650929
BiarnGamer
f23fb8c17720dc91686d112e795c7996125dbcbc
32,620
cpp
C++
Development/External/wxWindows_2.4.0/src/common/event.cpp
addstone/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
37
2020-05-22T18:18:47.000Z
2022-03-19T06:51:54.000Z
Development/External/wxWindows_2.4.0/src/common/event.cpp
AdanosGotoman/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
null
null
null
Development/External/wxWindows_2.4.0/src/common/event.cpp
AdanosGotoman/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
27
2020-05-17T01:03:30.000Z
2022-03-06T19:10:14.000Z
///////////////////////////////////////////////////////////////////////////// // Name: event.cpp // Purpose: Event classes // Author: Julian Smart // Modified by: // Created: 01/02/97 // RCS-ID: $Id: event.cpp,v 1.110.2.1 2002/10/30 19:55:38 RR Exp $ // Copyright: (c) Julian Smart and Markus Holzem // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- #ifdef __GNUG__ #pragma implementation "event.h" #endif // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/defs.h" #include "wx/app.h" #include "wx/list.h" #if wxUSE_GUI #include "wx/control.h" #include "wx/utils.h" #include "wx/dc.h" #endif // wxUSE_GUI #endif #include "wx/event.h" #if wxUSE_GUI #include "wx/validate.h" #endif // wxUSE_GUI // ---------------------------------------------------------------------------- // wxWin macros // ---------------------------------------------------------------------------- IMPLEMENT_DYNAMIC_CLASS(wxEvtHandler, wxObject) IMPLEMENT_ABSTRACT_CLASS(wxEvent, wxObject) #if wxUSE_GUI IMPLEMENT_DYNAMIC_CLASS(wxIdleEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxCommandEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxNotifyEvent, wxCommandEvent) IMPLEMENT_DYNAMIC_CLASS(wxScrollEvent, wxCommandEvent) IMPLEMENT_DYNAMIC_CLASS(wxScrollWinEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxMouseEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxKeyEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxSizeEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxPaintEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxNcPaintEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxEraseEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxMoveEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxFocusEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxChildFocusEvent, wxCommandEvent) IMPLEMENT_DYNAMIC_CLASS(wxCloseEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxShowEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxMaximizeEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxIconizeEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxMenuEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxJoystickEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxDropFilesEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxActivateEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxInitDialogEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxSetCursorEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxSysColourChangedEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxDisplayChangedEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxUpdateUIEvent, wxCommandEvent) IMPLEMENT_DYNAMIC_CLASS(wxNavigationKeyEvent, wxCommandEvent) IMPLEMENT_DYNAMIC_CLASS(wxPaletteChangedEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxQueryNewPaletteEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxWindowCreateEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxWindowDestroyEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxHelpEvent, wxCommandEvent) IMPLEMENT_DYNAMIC_CLASS(wxContextMenuEvent, wxCommandEvent) IMPLEMENT_DYNAMIC_CLASS(wxMouseCaptureChangedEvent, wxEvent) #endif // wxUSE_GUI const wxEventTable *wxEvtHandler::GetEventTable() const { return &wxEvtHandler::sm_eventTable; } const wxEventTable wxEvtHandler::sm_eventTable = { (const wxEventTable *)NULL, &wxEvtHandler::sm_eventTableEntries[0] }; const wxEventTableEntry wxEvtHandler::sm_eventTableEntries[] = { DECLARE_EVENT_TABLE_ENTRY(wxEVT_NULL, 0, 0, (wxObjectEventFunction)NULL, NULL) }; // ---------------------------------------------------------------------------- // global variables // ---------------------------------------------------------------------------- // To put pending event handlers wxList *wxPendingEvents = (wxList *)NULL; #if wxUSE_THREADS // protects wxPendingEvents list wxCriticalSection *wxPendingEventsLocker = (wxCriticalSection *)NULL; #endif #if !WXWIN_COMPATIBILITY_EVENT_TYPES // common event types are defined here, other event types are defined by the // components which use them DEFINE_EVENT_TYPE(wxEVT_NULL) DEFINE_EVENT_TYPE(wxEVT_COMMAND_BUTTON_CLICKED) DEFINE_EVENT_TYPE(wxEVT_COMMAND_CHECKBOX_CLICKED) DEFINE_EVENT_TYPE(wxEVT_COMMAND_CHOICE_SELECTED) DEFINE_EVENT_TYPE(wxEVT_COMMAND_LISTBOX_SELECTED) DEFINE_EVENT_TYPE(wxEVT_COMMAND_LISTBOX_DOUBLECLICKED) DEFINE_EVENT_TYPE(wxEVT_COMMAND_CHECKLISTBOX_TOGGLED) DEFINE_EVENT_TYPE(wxEVT_COMMAND_MENU_SELECTED) DEFINE_EVENT_TYPE(wxEVT_COMMAND_SLIDER_UPDATED) DEFINE_EVENT_TYPE(wxEVT_COMMAND_RADIOBOX_SELECTED) DEFINE_EVENT_TYPE(wxEVT_COMMAND_RADIOBUTTON_SELECTED) DEFINE_EVENT_TYPE(wxEVT_COMMAND_SCROLLBAR_UPDATED) DEFINE_EVENT_TYPE(wxEVT_COMMAND_VLBOX_SELECTED) DEFINE_EVENT_TYPE(wxEVT_COMMAND_COMBOBOX_SELECTED) DEFINE_EVENT_TYPE(wxEVT_COMMAND_TOOL_RCLICKED) DEFINE_EVENT_TYPE(wxEVT_COMMAND_TOOL_ENTER) DEFINE_EVENT_TYPE(wxEVT_COMMAND_SPINCTRL_UPDATED) // Sockets and timers send events, too DEFINE_EVENT_TYPE(wxEVT_SOCKET) DEFINE_EVENT_TYPE(wxEVT_TIMER) // Mouse event types DEFINE_EVENT_TYPE(wxEVT_LEFT_DOWN) DEFINE_EVENT_TYPE(wxEVT_LEFT_UP) DEFINE_EVENT_TYPE(wxEVT_MIDDLE_DOWN) DEFINE_EVENT_TYPE(wxEVT_MIDDLE_UP) DEFINE_EVENT_TYPE(wxEVT_RIGHT_DOWN) DEFINE_EVENT_TYPE(wxEVT_RIGHT_UP) DEFINE_EVENT_TYPE(wxEVT_MOTION) DEFINE_EVENT_TYPE(wxEVT_ENTER_WINDOW) DEFINE_EVENT_TYPE(wxEVT_LEAVE_WINDOW) DEFINE_EVENT_TYPE(wxEVT_LEFT_DCLICK) DEFINE_EVENT_TYPE(wxEVT_MIDDLE_DCLICK) DEFINE_EVENT_TYPE(wxEVT_RIGHT_DCLICK) DEFINE_EVENT_TYPE(wxEVT_SET_FOCUS) DEFINE_EVENT_TYPE(wxEVT_KILL_FOCUS) DEFINE_EVENT_TYPE(wxEVT_CHILD_FOCUS) DEFINE_EVENT_TYPE(wxEVT_MOUSEWHEEL) // Non-client mouse events DEFINE_EVENT_TYPE(wxEVT_NC_LEFT_DOWN) DEFINE_EVENT_TYPE(wxEVT_NC_LEFT_UP) DEFINE_EVENT_TYPE(wxEVT_NC_MIDDLE_DOWN) DEFINE_EVENT_TYPE(wxEVT_NC_MIDDLE_UP) DEFINE_EVENT_TYPE(wxEVT_NC_RIGHT_DOWN) DEFINE_EVENT_TYPE(wxEVT_NC_RIGHT_UP) DEFINE_EVENT_TYPE(wxEVT_NC_MOTION) DEFINE_EVENT_TYPE(wxEVT_NC_ENTER_WINDOW) DEFINE_EVENT_TYPE(wxEVT_NC_LEAVE_WINDOW) DEFINE_EVENT_TYPE(wxEVT_NC_LEFT_DCLICK) DEFINE_EVENT_TYPE(wxEVT_NC_MIDDLE_DCLICK) DEFINE_EVENT_TYPE(wxEVT_NC_RIGHT_DCLICK) // Character input event type DEFINE_EVENT_TYPE(wxEVT_CHAR) DEFINE_EVENT_TYPE(wxEVT_CHAR_HOOK) DEFINE_EVENT_TYPE(wxEVT_NAVIGATION_KEY) DEFINE_EVENT_TYPE(wxEVT_KEY_DOWN) DEFINE_EVENT_TYPE(wxEVT_KEY_UP) // Set cursor event DEFINE_EVENT_TYPE(wxEVT_SET_CURSOR) // wxScrollbar and wxSlider event identifiers DEFINE_EVENT_TYPE(wxEVT_SCROLL_TOP) DEFINE_EVENT_TYPE(wxEVT_SCROLL_BOTTOM) DEFINE_EVENT_TYPE(wxEVT_SCROLL_LINEUP) DEFINE_EVENT_TYPE(wxEVT_SCROLL_LINEDOWN) DEFINE_EVENT_TYPE(wxEVT_SCROLL_PAGEUP) DEFINE_EVENT_TYPE(wxEVT_SCROLL_PAGEDOWN) DEFINE_EVENT_TYPE(wxEVT_SCROLL_THUMBTRACK) DEFINE_EVENT_TYPE(wxEVT_SCROLL_THUMBRELEASE) DEFINE_EVENT_TYPE(wxEVT_SCROLL_ENDSCROLL) // Scroll events from wxWindow DEFINE_EVENT_TYPE(wxEVT_SCROLLWIN_TOP) DEFINE_EVENT_TYPE(wxEVT_SCROLLWIN_BOTTOM) DEFINE_EVENT_TYPE(wxEVT_SCROLLWIN_LINEUP) DEFINE_EVENT_TYPE(wxEVT_SCROLLWIN_LINEDOWN) DEFINE_EVENT_TYPE(wxEVT_SCROLLWIN_PAGEUP) DEFINE_EVENT_TYPE(wxEVT_SCROLLWIN_PAGEDOWN) DEFINE_EVENT_TYPE(wxEVT_SCROLLWIN_THUMBTRACK) DEFINE_EVENT_TYPE(wxEVT_SCROLLWIN_THUMBRELEASE) // System events DEFINE_EVENT_TYPE(wxEVT_SIZE) DEFINE_EVENT_TYPE(wxEVT_MOVE) DEFINE_EVENT_TYPE(wxEVT_CLOSE_WINDOW) DEFINE_EVENT_TYPE(wxEVT_END_SESSION) DEFINE_EVENT_TYPE(wxEVT_QUERY_END_SESSION) DEFINE_EVENT_TYPE(wxEVT_ACTIVATE_APP) DEFINE_EVENT_TYPE(wxEVT_POWER) DEFINE_EVENT_TYPE(wxEVT_ACTIVATE) DEFINE_EVENT_TYPE(wxEVT_CREATE) DEFINE_EVENT_TYPE(wxEVT_DESTROY) DEFINE_EVENT_TYPE(wxEVT_SHOW) DEFINE_EVENT_TYPE(wxEVT_ICONIZE) DEFINE_EVENT_TYPE(wxEVT_MAXIMIZE) DEFINE_EVENT_TYPE(wxEVT_MOUSE_CAPTURE_CHANGED) DEFINE_EVENT_TYPE(wxEVT_PAINT) DEFINE_EVENT_TYPE(wxEVT_ERASE_BACKGROUND) DEFINE_EVENT_TYPE(wxEVT_NC_PAINT) DEFINE_EVENT_TYPE(wxEVT_PAINT_ICON) DEFINE_EVENT_TYPE(wxEVT_MENU_OPEN) DEFINE_EVENT_TYPE(wxEVT_MENU_CLOSE) DEFINE_EVENT_TYPE(wxEVT_MENU_HIGHLIGHT) DEFINE_EVENT_TYPE(wxEVT_CONTEXT_MENU) DEFINE_EVENT_TYPE(wxEVT_SYS_COLOUR_CHANGED) DEFINE_EVENT_TYPE(wxEVT_DISPLAY_CHANGED) DEFINE_EVENT_TYPE(wxEVT_SETTING_CHANGED) DEFINE_EVENT_TYPE(wxEVT_QUERY_NEW_PALETTE) DEFINE_EVENT_TYPE(wxEVT_PALETTE_CHANGED) DEFINE_EVENT_TYPE(wxEVT_JOY_BUTTON_DOWN) DEFINE_EVENT_TYPE(wxEVT_JOY_BUTTON_UP) DEFINE_EVENT_TYPE(wxEVT_JOY_MOVE) DEFINE_EVENT_TYPE(wxEVT_JOY_ZMOVE) DEFINE_EVENT_TYPE(wxEVT_DROP_FILES) DEFINE_EVENT_TYPE(wxEVT_DRAW_ITEM) DEFINE_EVENT_TYPE(wxEVT_MEASURE_ITEM) DEFINE_EVENT_TYPE(wxEVT_COMPARE_ITEM) DEFINE_EVENT_TYPE(wxEVT_INIT_DIALOG) DEFINE_EVENT_TYPE(wxEVT_IDLE) DEFINE_EVENT_TYPE(wxEVT_UPDATE_UI) // Generic command events // Note: a click is a higher-level event than button down/up DEFINE_EVENT_TYPE(wxEVT_COMMAND_LEFT_CLICK) DEFINE_EVENT_TYPE(wxEVT_COMMAND_LEFT_DCLICK) DEFINE_EVENT_TYPE(wxEVT_COMMAND_RIGHT_CLICK) DEFINE_EVENT_TYPE(wxEVT_COMMAND_RIGHT_DCLICK) DEFINE_EVENT_TYPE(wxEVT_COMMAND_SET_FOCUS) DEFINE_EVENT_TYPE(wxEVT_COMMAND_KILL_FOCUS) DEFINE_EVENT_TYPE(wxEVT_COMMAND_ENTER) // Help events DEFINE_EVENT_TYPE(wxEVT_HELP) DEFINE_EVENT_TYPE(wxEVT_DETAILED_HELP) #endif // !WXWIN_COMPATIBILITY_EVENT_TYPES // ============================================================================ // implementation // ============================================================================ // ---------------------------------------------------------------------------- // event initialization // ---------------------------------------------------------------------------- int wxNewEventType() { // MT-FIXME static int s_lastUsedEventType = wxEVT_FIRST; #if WXWIN_COMPATIBILITY_2 // check that we don't overlap with the user-defined types: if it does // happen, the best solution is probably to update the existing code to // use wxNewEventType() instead of wxEVT_USER_FIRST // // due to the uncertainty wxASSERT_MSG( s_lastUsedEventType < wxEVT_USER_FIRST - 1, _T("possible event type conflict") ); #endif // WXWIN_COMPATIBILITY_2 return s_lastUsedEventType++; } // ---------------------------------------------------------------------------- // wxEvent // ---------------------------------------------------------------------------- /* * General wxWindows events, covering * all interesting things that might happen (button clicking, resizing, * setting text in widgets, etc.). * * For each completely new event type, derive a new event class. * */ wxEvent::wxEvent(int theId, wxEventType commandType ) { m_eventType = commandType; m_eventObject = (wxObject *) NULL; m_timeStamp = 0; m_id = theId; m_skipped = FALSE; m_callbackUserData = (wxObject *) NULL; m_isCommandEvent = FALSE; } wxEvent::wxEvent(const wxEvent &src) : wxObject() , m_eventObject(src.m_eventObject) , m_eventType(src.m_eventType) , m_timeStamp(src.m_timeStamp) , m_id(src.m_id) , m_callbackUserData(src.m_callbackUserData) , m_skipped(src.m_skipped) , m_isCommandEvent(src.m_isCommandEvent) { } #if wxUSE_GUI /* * Command events * */ wxCommandEvent::wxCommandEvent(wxEventType commandType, int theId) : wxEvent(theId, commandType) { m_clientData = (char *) NULL; m_clientObject = (wxClientData *) NULL; m_extraLong = 0; m_commandInt = 0; m_commandString = wxEmptyString; m_isCommandEvent = TRUE; } /* * Scroll events */ wxScrollEvent::wxScrollEvent(wxEventType commandType, int id, int pos, int orient) : wxCommandEvent(commandType, id) { m_extraLong = orient; m_commandInt = pos; } /* * ScrollWin events */ wxScrollWinEvent::wxScrollWinEvent(wxEventType commandType, int pos, int orient) { m_eventType = commandType; m_extraLong = orient; m_commandInt = pos; } /* * Mouse events * */ wxMouseEvent::wxMouseEvent(wxEventType commandType) { m_eventType = commandType; m_metaDown = FALSE; m_altDown = FALSE; m_controlDown = FALSE; m_shiftDown = FALSE; m_leftDown = FALSE; m_rightDown = FALSE; m_middleDown = FALSE; m_x = 0; m_y = 0; m_wheelRotation = 0; m_wheelDelta = 0; m_linesPerAction = 0; } void wxMouseEvent::Assign(const wxMouseEvent& event) { m_eventType = event.m_eventType; m_x = event.m_x; m_y = event.m_y; m_leftDown = event.m_leftDown; m_middleDown = event.m_middleDown; m_rightDown = event.m_rightDown; m_controlDown = event.m_controlDown; m_shiftDown = event.m_shiftDown; m_altDown = event.m_altDown; m_metaDown = event.m_metaDown; m_wheelRotation = event.m_wheelRotation; m_wheelDelta = event.m_wheelDelta; m_linesPerAction = event.m_linesPerAction; } // True if was a button dclick event (1 = left, 2 = middle, 3 = right) // or any button dclick event (but = -1) bool wxMouseEvent::ButtonDClick(int but) const { switch (but) { case -1: return (LeftDClick() || MiddleDClick() || RightDClick()); case 1: return LeftDClick(); case 2: return MiddleDClick(); case 3: return RightDClick(); default: wxFAIL_MSG(wxT("invalid parameter in wxMouseEvent::ButtonDClick")); } return FALSE; } // True if was a button down event (1 = left, 2 = middle, 3 = right) // or any button down event (but = -1) bool wxMouseEvent::ButtonDown(int but) const { switch (but) { case -1: return (LeftDown() || MiddleDown() || RightDown()); case 1: return LeftDown(); case 2: return MiddleDown(); case 3: return RightDown(); default: wxFAIL_MSG(wxT("invalid parameter in wxMouseEvent::ButtonDown")); } return FALSE; } // True if was a button up event (1 = left, 2 = middle, 3 = right) // or any button up event (but = -1) bool wxMouseEvent::ButtonUp(int but) const { switch (but) { case -1: return (LeftUp() || MiddleUp() || RightUp()); case 1: return LeftUp(); case 2: return MiddleUp(); case 3: return RightUp(); default: wxFAIL_MSG(wxT("invalid parameter in wxMouseEvent::ButtonUp")); } return FALSE; } // True if the given button is currently changing state bool wxMouseEvent::Button(int but) const { switch (but) { case -1: return (ButtonUp(-1) || ButtonDown(-1) || ButtonDClick(-1)); case 1: return (LeftDown() || LeftUp() || LeftDClick()); case 2: return (MiddleDown() || MiddleUp() || MiddleDClick()); case 3: return (RightDown() || RightUp() || RightDClick()); default: wxFAIL_MSG(wxT("invalid parameter in wxMouseEvent::Button")); } return FALSE; } bool wxMouseEvent::ButtonIsDown(int but) const { switch (but) { case -1: return (LeftIsDown() || MiddleIsDown() || RightIsDown()); case 1: return LeftIsDown(); case 2: return MiddleIsDown(); case 3: return RightIsDown(); default: wxFAIL_MSG(wxT("invalid parameter in wxMouseEvent::ButtonIsDown")); } return FALSE; } int wxMouseEvent::GetButton() const { for ( int i = 1; i <= 3; i++ ) { if ( Button(i) ) { return i; } } return -1; } // Find the logical position of the event given the DC wxPoint wxMouseEvent::GetLogicalPosition(const wxDC& dc) const { wxPoint pt(dc.DeviceToLogicalX(m_x), dc.DeviceToLogicalY(m_y)); return pt; } /* * Keyboard event * */ wxKeyEvent::wxKeyEvent(wxEventType type) { m_eventType = type; m_shiftDown = FALSE; m_controlDown = FALSE; m_metaDown = FALSE; m_altDown = FALSE; m_keyCode = 0; m_scanCode = 0; #if wxUSE_UNICODE m_uniChar = 0; #endif } wxKeyEvent::wxKeyEvent(const wxKeyEvent& evt) : wxEvent(evt) { m_x = evt.m_x; m_y = evt.m_y; m_keyCode = evt.m_keyCode; m_controlDown = evt.m_controlDown; m_shiftDown = evt.m_shiftDown; m_altDown = evt.m_altDown; m_metaDown = evt.m_metaDown; m_scanCode = evt.m_scanCode; m_rawCode = evt.m_rawCode; m_rawFlags = evt.m_rawFlags; #if wxUSE_UNICODE m_uniChar = evt.m_uniChar; #endif } wxWindowCreateEvent::wxWindowCreateEvent(wxWindow *win) { SetEventType(wxEVT_CREATE); SetEventObject(win); } wxWindowDestroyEvent::wxWindowDestroyEvent(wxWindow *win) { SetEventType(wxEVT_DESTROY); SetEventObject(win); } wxChildFocusEvent::wxChildFocusEvent(wxWindow *win) : wxCommandEvent(wxEVT_CHILD_FOCUS) { SetEventObject(win); } #endif // wxUSE_GUI // ---------------------------------------------------------------------------- // wxEvtHandler // ---------------------------------------------------------------------------- /* * Event handler */ wxEvtHandler::wxEvtHandler() { m_nextHandler = (wxEvtHandler *) NULL; m_previousHandler = (wxEvtHandler *) NULL; m_enabled = TRUE; m_dynamicEvents = (wxList *) NULL; m_isWindow = FALSE; m_pendingEvents = (wxList *) NULL; // no client data (yet) m_clientData = NULL; m_clientDataType = wxClientData_None; } wxEvtHandler::~wxEvtHandler() { // Takes itself out of the list of handlers if (m_previousHandler) m_previousHandler->m_nextHandler = m_nextHandler; if (m_nextHandler) m_nextHandler->m_previousHandler = m_previousHandler; if (m_dynamicEvents) { wxNode *node = m_dynamicEvents->First(); while (node) { #if WXWIN_COMPATIBILITY_EVENT_TYPES wxEventTableEntry *entry = (wxEventTableEntry*)node->Data(); #else // !WXWIN_COMPATIBILITY_EVENT_TYPES wxDynamicEventTableEntry *entry = (wxDynamicEventTableEntry*)node->Data(); #endif // WXWIN_COMPATIBILITY_EVENT_TYPES/!WXWIN_COMPATIBILITY_EVENT_TYPES if (entry->m_callbackUserData) delete entry->m_callbackUserData; delete entry; node = node->Next(); } delete m_dynamicEvents; }; delete m_pendingEvents; // we only delete object data, not untyped if ( m_clientDataType == wxClientData_Object ) delete m_clientObject; } #if wxUSE_THREADS bool wxEvtHandler::ProcessThreadEvent(wxEvent& event) { // check that we are really in a child thread wxASSERT_MSG( !wxThread::IsMain(), wxT("use ProcessEvent() in main thread") ); AddPendingEvent(event); return TRUE; } #endif // wxUSE_THREADS void wxEvtHandler::AddPendingEvent(wxEvent& event) { // 1) Add event to list of pending events of this event handler wxEvent *eventCopy = event.Clone(); // we must be able to copy the events here so the event class must // implement Clone() properly instead of just providing a NULL stab for it wxCHECK_RET( eventCopy, _T("events of this type aren't supposed to be posted") ); wxENTER_CRIT_SECT( m_eventsLocker); if ( !m_pendingEvents ) m_pendingEvents = new wxList; m_pendingEvents->Append(eventCopy); wxLEAVE_CRIT_SECT( m_eventsLocker); // 2) Add this event handler to list of event handlers that // have pending events. wxENTER_CRIT_SECT(*wxPendingEventsLocker); if ( !wxPendingEvents ) wxPendingEvents = new wxList; wxPendingEvents->Append(this); wxLEAVE_CRIT_SECT(*wxPendingEventsLocker); // 3) Inform the system that new pending events are somwehere, // and that these should be processed in idle time. wxWakeUpIdle(); } void wxEvtHandler::ProcessPendingEvents() { wxENTER_CRIT_SECT( m_eventsLocker); wxNode *node = m_pendingEvents->First(); while ( node ) { wxEvent *event = (wxEvent *)node->Data(); delete node; // In ProcessEvent, new events might get added and // we can safely leave the crtical section here. wxLEAVE_CRIT_SECT( m_eventsLocker); ProcessEvent(*event); delete event; wxENTER_CRIT_SECT( m_eventsLocker); node = m_pendingEvents->First(); } wxLEAVE_CRIT_SECT( m_eventsLocker); } /* * Event table stuff */ bool wxEvtHandler::ProcessEvent(wxEvent& event) { #if wxUSE_GUI // We have to use the actual window or processing events from // wxWindowNative destructor won't work (we don't see the wxWindow class) #ifdef __WXDEBUG__ // check that our flag corresponds to reality wxClassInfo* info = NULL; #ifdef __WXUNIVERSAL__ # if defined(__WXMSW__) info = CLASSINFO(wxWindowMSW); # elif defined(__WXGTK__) info = CLASSINFO(wxWindowGTK); # elif defined(__WXX11__) info = CLASSINFO(wxWindowX11); # elif defined(__WXMGL__) info = CLASSINFO(wxWindowMGL); # elif defined(__WXPM__) info = CLASSINFO(wxWindowOS2); # elif defined(__WXMAC__) info = CLASSINFO(wxWindowMac); # elif defined(__WXMOTIF__) info = CLASSINFO(wxWindowMotif); # endif #else info = CLASSINFO(wxWindow); #endif if ( m_isWindow != IsKindOf(info) ) { wxString msg = GetClassInfo()->GetClassName(); msg += _T(" should [not] be a window but it is [not]"); wxFAIL_MSG( msg ); } #endif // __WXDEBUG__ #endif // wxUSE_GUI // allow the application to hook into event processing if ( wxTheApp ) { int rc = wxTheApp->FilterEvent(event); if ( rc != -1 ) { wxASSERT_MSG( rc == 1 || rc == 0, _T("unexpected wxApp::FilterEvent return value") ); return rc != 0; } //else: proceed normally } // An event handler can be enabled or disabled if ( GetEvtHandlerEnabled() ) { #if 0 /* What is this? When using GUI threads, a non main threads can send an event and process it itself. This breaks GTK's GUI threads, so please explain. */ // Check whether we are in a child thread. if ( !wxThread::IsMain() ) return ProcessThreadEvent(event); #endif // Handle per-instance dynamic event tables first if ( m_dynamicEvents && SearchDynamicEventTable(event) ) return TRUE; // Then static per-class event tables const wxEventTable *table = GetEventTable(); #if wxUSE_GUI && wxUSE_VALIDATORS // Try the associated validator first, if this is a window. // Problem: if the event handler of the window has been replaced, // this wxEvtHandler may no longer be a window. // Therefore validators won't be processed if the handler // has been replaced with SetEventHandler. // THIS CAN BE CURED if PushEventHandler is used instead of // SetEventHandler, and then processing will be passed down the // chain of event handlers. if (m_isWindow) { wxWindow *win = (wxWindow *)this; // Can only use the validator of the window which // is receiving the event if ( win == event.GetEventObject() ) { wxValidator *validator = win->GetValidator(); if ( validator && validator->ProcessEvent(event) ) { return TRUE; } } } #endif // Search upwards through the inheritance hierarchy while (table) { if ( SearchEventTable((wxEventTable&)*table, event) ) return TRUE; table = table->baseTable; } } // Try going down the event handler chain if ( GetNextHandler() ) { if ( GetNextHandler()->ProcessEvent(event) ) return TRUE; } #if wxUSE_GUI // Carry on up the parent-child hierarchy, but only if event is a command // event: it wouldn't make sense for a parent to receive a child's size // event, for example if ( m_isWindow && event.IsCommandEvent() ) { wxWindow *win = (wxWindow *)this; // honour the requests to stop propagation at this window: this is // used by the dialogs, for example, to prevent processing the events // from the dialog controls in the parent frame which rarely, if ever, // makes sense if ( !(win->GetExtraStyle() & wxWS_EX_BLOCK_EVENTS) ) { wxWindow *parent = win->GetParent(); if ( parent && !parent->IsBeingDeleted() ) return parent->GetEventHandler()->ProcessEvent(event); } } #endif // wxUSE_GUI // Last try - application object. if ( wxTheApp && (this != wxTheApp) ) { // Special case: don't pass wxEVT_IDLE to wxApp, since it'll always // swallow it. wxEVT_IDLE is sent explicitly to wxApp so it will be // processed appropriately via SearchEventTable. if ( event.GetEventType() != wxEVT_IDLE ) { if ( wxTheApp->ProcessEvent(event) ) return TRUE; } } return FALSE; } bool wxEvtHandler::SearchEventTable(wxEventTable& table, wxEvent& event) { wxEventType eventType = event.GetEventType(); int eventId = event.GetId(); // BC++ doesn't like testing for m_fn without != 0 for ( int i = 0; table.entries[i].m_fn != 0; i++ ) { // the line using reference exposes a bug in gcc: although it _seems_ // to work, it leads to weird crashes later on during program // execution #ifdef __GNUG__ wxEventTableEntry entry = table.entries[i]; #else const wxEventTableEntry& entry = table.entries[i]; #endif // match only if the event type is the same and the id is either -1 in // the event table (meaning "any") or the event id matches the id // specified in the event table either exactly or by falling into // range between first and last if ( eventType == entry.m_eventType ) { int tableId1 = entry.m_id, tableId2 = entry.m_lastId; if ( (tableId1 == -1) || (tableId2 == -1 && eventId == tableId1) || (tableId2 != -1 && (eventId >= tableId1 && eventId <= tableId2)) ) { event.Skip(FALSE); event.m_callbackUserData = entry.m_callbackUserData; (this->*((wxEventFunction) (entry.m_fn)))(event); return !event.GetSkipped(); } } } return FALSE; } void wxEvtHandler::Connect( int id, int lastId, int eventType, wxObjectEventFunction func, wxObject *userData ) { #if WXWIN_COMPATIBILITY_EVENT_TYPES wxEventTableEntry *entry = new wxEventTableEntry; entry->m_eventType = eventType; entry->m_id = id; entry->m_lastId = lastId; entry->m_fn = func; entry->m_callbackUserData = userData; #else // !WXWIN_COMPATIBILITY_EVENT_TYPES wxDynamicEventTableEntry *entry = new wxDynamicEventTableEntry(eventType, id, lastId, func, userData); #endif // WXWIN_COMPATIBILITY_EVENT_TYPES/!WXWIN_COMPATIBILITY_EVENT_TYPES if (!m_dynamicEvents) m_dynamicEvents = new wxList; m_dynamicEvents->Append( (wxObject*) entry ); } bool wxEvtHandler::Disconnect( int id, int lastId, wxEventType eventType, wxObjectEventFunction func, wxObject *userData ) { if (!m_dynamicEvents) return FALSE; wxNode *node = m_dynamicEvents->First(); while (node) { #if WXWIN_COMPATIBILITY_EVENT_TYPES wxEventTableEntry *entry = (wxEventTableEntry*)node->Data(); #else // !WXWIN_COMPATIBILITY_EVENT_TYPES wxDynamicEventTableEntry *entry = (wxDynamicEventTableEntry*)node->Data(); #endif // WXWIN_COMPATIBILITY_EVENT_TYPES/!WXWIN_COMPATIBILITY_EVENT_TYPES if ((entry->m_id == id) && ((entry->m_lastId == lastId) || (lastId == -1)) && ((entry->m_eventType == eventType) || (eventType == wxEVT_NULL)) && ((entry->m_fn == func) || (func == (wxObjectEventFunction)NULL)) && ((entry->m_callbackUserData == userData) || (userData == (wxObject*)NULL))) { if (entry->m_callbackUserData) delete entry->m_callbackUserData; m_dynamicEvents->DeleteNode( node ); delete entry; return TRUE; } node = node->Next(); } return FALSE; } bool wxEvtHandler::SearchDynamicEventTable( wxEvent& event ) { wxCHECK_MSG( m_dynamicEvents, FALSE, wxT("caller should check that we have dynamic events") ); int commandId = event.GetId(); wxNode *node = m_dynamicEvents->First(); while (node) { #if WXWIN_COMPATIBILITY_EVENT_TYPES wxEventTableEntry *entry = (wxEventTableEntry*)node->Data(); #else // !WXWIN_COMPATIBILITY_EVENT_TYPES wxDynamicEventTableEntry *entry = (wxDynamicEventTableEntry*)node->Data(); #endif // WXWIN_COMPATIBILITY_EVENT_TYPES/!WXWIN_COMPATIBILITY_EVENT_TYPES if (entry->m_fn) { // Match, if event spec says any id will do (id == -1) if ( (event.GetEventType() == entry->m_eventType) && (entry->m_id == -1 || (entry->m_lastId == -1 && commandId == entry->m_id) || (entry->m_lastId != -1 && (commandId >= entry->m_id && commandId <= entry->m_lastId))) ) { event.Skip(FALSE); event.m_callbackUserData = entry->m_callbackUserData; (this->*((wxEventFunction) (entry->m_fn)))(event); if (event.GetSkipped()) return FALSE; else return TRUE; } } node = node->Next(); } return FALSE; }; void wxEvtHandler::DoSetClientObject( wxClientData *data ) { wxASSERT_MSG( m_clientDataType != wxClientData_Void, wxT("can't have both object and void client data") ); if ( m_clientObject ) delete m_clientObject; m_clientObject = data; m_clientDataType = wxClientData_Object; } wxClientData *wxEvtHandler::DoGetClientObject() const { // it's not an error to call GetClientObject() on a window which doesn't // have client data at all - NULL will be returned wxASSERT_MSG( m_clientDataType != wxClientData_Void, wxT("this window doesn't have object client data") ); return m_clientObject; } void wxEvtHandler::DoSetClientData( void *data ) { wxASSERT_MSG( m_clientDataType != wxClientData_Object, wxT("can't have both object and void client data") ); m_clientData = data; m_clientDataType = wxClientData_Void; } void *wxEvtHandler::DoGetClientData() const { // it's not an error to call GetClientData() on a window which doesn't have // client data at all - NULL will be returned wxASSERT_MSG( m_clientDataType != wxClientData_Object, wxT("this window doesn't have void client data") ); return m_clientData; } #if WXWIN_COMPATIBILITY bool wxEvtHandler::OnClose() { if (GetNextHandler()) return GetNextHandler()->OnClose(); else return FALSE; } #endif // WXWIN_COMPATIBILITY #if wxUSE_GUI // Find a window with the focus, that is also a descendant of the given window. // This is used to determine the window to initially send commands to. wxWindow* wxFindFocusDescendant(wxWindow* ancestor) { // Process events starting with the window with the focus, if any. wxWindow* focusWin = wxWindow::FindFocus(); wxWindow* win = focusWin; // Check if this is a descendant of this frame. // If not, win will be set to NULL. while (win) { if (win == ancestor) break; else win = win->GetParent(); } if (win == (wxWindow*) NULL) focusWin = (wxWindow*) NULL; return focusWin; } #endif // wxUSE_GUI
29.493671
87
0.651502
addstone
f242339b31e7cf08ca2b32322798dcfb737dece4
604
cpp
C++
problems/acmicpc_5639.cpp
qawbecrdtey/BOJ-sol
e3f410e8f4e3a6ade51b68ce2024529870edac64
[ "MIT" ]
null
null
null
problems/acmicpc_5639.cpp
qawbecrdtey/BOJ-sol
e3f410e8f4e3a6ade51b68ce2024529870edac64
[ "MIT" ]
null
null
null
problems/acmicpc_5639.cpp
qawbecrdtey/BOJ-sol
e3f410e8f4e3a6ade51b68ce2024529870edac64
[ "MIT" ]
null
null
null
#include <stdio.h> #include <vector> using namespace std; void search(int const root,int const r,vector<int> const &v){ if(root+1>r)return; if(root+1==r){ printf("%d\n",v[root]); return; } int const l=root+1; int const rtv=v[root]; int lv=l,rv=r; while(lv<rv){ int m=(lv+rv)/2; if(rtv>v[m])lv=m+1; else rv=m; } search(l,lv,v); search(lv,r,v); printf("%d\n",v[root]); } int main(){ int n; int t; vector<int> v; while(scanf("%d",&n)!=EOF){ v.push_back(n); } n=v.size(); search(0,n,v); }
19.483871
61
0.503311
qawbecrdtey
f246f1d8b0c25d140c9db185c1e6b4db35705913
13,446
cpp
C++
cpid/distributed.cpp
yuhonghong66/TorchCraftAI
895994989846be829fb0ed823a552008e807bdbe
[ "MIT" ]
1
2018-11-28T01:16:12.000Z
2018-11-28T01:16:12.000Z
cpid/distributed.cpp
MenLonII/TorchCraftAI
6920c6c02ee0043e6aa622fc0e5376cf97bc75e6
[ "MIT" ]
null
null
null
cpid/distributed.cpp
MenLonII/TorchCraftAI
6920c6c02ee0043e6aa622fc0e5376cf97bc75e6
[ "MIT" ]
null
null
null
/* * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "distributed.h" #include "common/utils.h" #include "netutils.h" #include <common/autograd/utils.h> #include <fmt/format.h> #include <glog/logging.h> #include <c10d/FileStore.hpp> #include <c10d/ProcessGroupGloo.hpp> #include <c10d/ProcessGroupNCCL.hpp> #include <c10d/TCPStore.hpp> #include <gloo/transport/tcp/device.h> DEFINE_int64( c10d_rank, -1, "Specify the c10d rank, -1 will autodetect based on SLURM environment " "variables"); DEFINE_int64( c10d_size, -1, "Specify the c10d world size, -1 will autodetect based on SLURM " "environment variables"); DEFINE_string( c10d_rdvu, "file", "file:[location]. " "Using file without a location causes it to try to autosetup based " "on slurm arguments"); namespace { std::shared_ptr<cpid::distributed::Context> globalContext_; std::once_flag contextInitialized_; int cudaDeviceNumber = 0; } // namespace namespace cpid { namespace distributed { Work::Work(std::function<void()> onFinish) : onFinish_(onFinish){}; Work::~Work() { if (!wait()) { LOG(FATAL) << "Distributed operation failed! " << exception().what(); } if (onFinish_) { onFinish_(); } } Work::Work(Work&& other) { std::swap(works_, other.works_); std::swap(onFinish_, other.onFinish_); } bool Work::isCompleted() { for (auto& work : works_) { if (!work->isCompleted()) { return false; } } return true; } bool Work::isSuccess() { for (auto& work : works_) { if (!work->isSuccess()) { return false; } } return true; } void Work::synchronize() { for (auto& work : works_) { work->synchronize(); } } bool Work::wait() { for (auto& work : works_) { if (!work->wait()) { // No need to wait for the remaining work to finish when we find that // one of them failed... return false; } } return true; } const std::exception& Work::exception() const { for (auto& work : works_) { if (!work->isSuccess()) { return work->exception(); } } LOG(FATAL) << "No exception found, perhaps your distributed operation did not fail?"; } Work::Work(std::vector<std::shared_ptr<ProcessGroup::Work>>&& works) : works_(std::move(works)) {} void Work::add(std::shared_ptr<ProcessGroup::Work> work) { works_.push_back(std::move(work)); } void Work::add(Work&& other) { for (auto& work : other.works_) { works_.push_back(std::move(work)); } other.works_.clear(); auto func = [ tof = this->onFinish_, oof = other.onFinish_ ]() { if (tof) { tof(); } if (oof) { oof(); } }; onFinish_ = func; } void init() { auto initializer = [&]() { if (globalContext_ != nullptr) { return; } std::shared_ptr<Store> store; auto jobid = getenv("SLURM_JOB_ID"); auto stepid = getenv("SLURM_STEPID"); auto worldSize = getenv("SLURM_STEP_NUM_TASKS"); if (jobid == nullptr || std::stoi(worldSize) == 1) { // If we're not on slurm, or if we only launch one task, we can just // use /tmp instead if (FLAGS_c10d_rank < 0) { FLAGS_c10d_rank = 0; } if (FLAGS_c10d_size < 0) { FLAGS_c10d_size = 1; } std::string rdvu; if (FLAGS_c10d_rdvu == "file") { if (FLAGS_c10d_size > 1) { throw std::runtime_error( "Cannot automatically determine rdvu without slurm"); } else { // We don't depend on fsutils, so we copy over the implementation of // mktemp here for a random file to "do rdvu" on our single node char tmplt[] = "/tmp/c10d.rdvu.XXXXXX"; auto res = ::mkstemp(tmplt); if (res == -1) { throw std::system_error(errno, std::system_category()); } else { if (close(res) == -1) { throw std::system_error(errno, std::system_category()); } } rdvu = tmplt; } } else { auto split = common::stringSplit(FLAGS_c10d_rdvu, ':', 1); if (split[0] != "file") { throw std::runtime_error("Unknown rendezvous method " + split[0]); } rdvu = std::move(split[1]); } cudaDeviceNumber = FLAGS_c10d_rank; VLOG(2) << "Using filestore at " << rdvu; store = std::make_shared<FileStore>(rdvu, FLAGS_c10d_size); } else { // If we're on slurm, automatically set rank and size based on slurm // variables if (FLAGS_c10d_rank < 0) { FLAGS_c10d_rank = std::stoi(getenv("SLURM_PROCID")); } if (FLAGS_c10d_size < 0) { FLAGS_c10d_size = std::stoi(worldSize); } // Setup the rendezvous. std::string rdvu; if (FLAGS_c10d_rdvu == "file") { rdvu = fmt::format("./c10d.{}.{}.sock", jobid, stepid); } else { // if it looks like file:/path/to/rdvu auto split = common::stringSplit(FLAGS_c10d_rdvu, ':', 1); if (split[0] != "file") { throw std::runtime_error("Unknown rendezvous method" + split[0]); } rdvu = split[1]; } if (char const* localRank = ::getenv("SLURM_LOCALID")) { cudaDeviceNumber = std::stoi(localRank); } VLOG(2) << "Using filestore at " << rdvu; store = std::make_shared<FileStore>(rdvu, FLAGS_c10d_size); } store->setTimeout( std::chrono::duration_cast<std::chrono::seconds>( c10d::Store::kNoTimeout)); // Initialize the Process Groups // The destructor of the global context can conflict with the // de-initialization of the CUDA shared libraries, which can lead to // segmentation fault on exit. This code doesn't really leak any OS // resources like file descriptors, so we depend on the OS to clean up once // the process exits. globalContext_ = std::shared_ptr<Context>( new Context(store, FLAGS_c10d_rank, FLAGS_c10d_size), [](Context*) {}); char hostname[256]; gethostname(hostname, 255); VLOG(0) << "c10d rank: " << globalContext_->rank << " running on host " << hostname << " and size " << globalContext_->size; if (common::gpuAvailable() && torch::cuda::device_count() > 0) { cudaDeviceNumber = cudaDeviceNumber % torch::cuda::device_count(); } setGPUToLocalRank(); }; std::call_once(contextInitialized_, initializer); } void setGPUToLocalRank() { if (common::gpuAvailable()) { cudaSetDevice(cudaDeviceNumber); } } std::shared_ptr<Context> globalContext() { init(); return globalContext_; } #define FOR_ALL_TYPES(FUNC) \ FUNC(uint8_t, torch::kByte); \ FUNC(char, torch::kChar); \ FUNC(int8_t, torch::kChar); \ FUNC(int16_t, torch::kShort); \ FUNC(int32_t, torch::kInt); \ FUNC(int64_t, torch::kLong); \ FUNC(float, torch::kFloat); \ FUNC(double, torch::kDouble); std::shared_ptr<ProcessGroup> Context::devicePG(torch::Tensor x) { if (x.is_cuda()) return ncclPG_; else return glooPG_; } #define ALLREDUCE(FType, DType) \ template <> \ Work Context::allreduce<FType>(FType * ptr, int64_t s, ReduceOp op) { \ auto tensor = torch::from_blob(ptr, {s}, DType); \ return this->allreduce(tensor, op); \ } FOR_ALL_TYPES(ALLREDUCE); #undef ALLREDUCE template <typename T, IsTorchDType<T>*> Work Context::allreduce(std::vector<T>& v, ReduceOp op) { return this->allreduce(v.data(), v.size(), op); } Work Context::allreduce(torch::Tensor x, ReduceOp op) { if (size == 1) { return Work(); } std::vector<torch::Tensor> tensors({x.detach()}); return Work({devicePG(x)->allreduce(tensors, {op})}); } Work Context::allreduceGradients(ag::Container const& model, ReduceOp op) { Work work; for (auto& p : model->parameters()) { if (p.grad().defined()) { work.add(this->allreduce(p.grad(), op)); } } return work; } #define BROADCAST(FType, DType) \ template <> \ Work Context::broadcast<FType>(FType * ptr, int64_t s, int root) { \ auto tensor = torch::from_blob(ptr, {s}, DType); \ return this->broadcast(tensor, root); \ } FOR_ALL_TYPES(BROADCAST) #undef BROADCAST template <typename T, IsTorchDType<T>*> Work Context::broadcast(std::vector<T>& v, int root) { return this->broadcast(v.data(), v.size(), root); } Work Context::broadcast(torch::Tensor x, int root) { if (size == 1) { return Work(); } std::vector<torch::Tensor> tensors({x.detach()}); return Work({devicePG(x)->broadcast(tensors, {root, 0})}); } Work Context::broadcast(ag::Container const& model, int root) { Work work; for (auto& p : model->parameters()) { work.add(this->broadcast(p, root)); } return work; } #define ALLGATHER(FType, DType) \ template <> \ Work Context::allgather<FType>(FType * out, FType * in, int64_t s) { \ auto inTensor = torch::from_blob(in, {s}, DType); \ auto outTensor = torch::from_blob(out, {this->size, s}, DType); \ return this->allgather(outTensor, inTensor); \ } \ template <> \ Work Context::allgather<FType>(FType * out, torch::Tensor in) { \ auto outTensor = \ torch::from_blob(out, {this->size, in.numel()}, in.options()); \ return this->allgather(outTensor, in); \ } FOR_ALL_TYPES(ALLGATHER) #undef ALLGATHER // XXX This is super silly, but allgather is not bound in gloo with c10d, so // we'll have to copy it to GPU, and use NCCL... Once c10d binds gloo allgather, // we can simplify this function a lot Work Context::allgather(torch::Tensor out, torch::Tensor in) { out = out.detach(); if (in.is_cuda()) { std::vector<torch::Tensor> tin({in.detach()}); std::vector<std::vector<torch::Tensor>> tout; tout.emplace_back(); for (auto i = 0; i < out.size(0); i++) { tout.back().emplace_back(out[i]); } return Work({ncclPG_->allgather(tout, tin)}); } else { auto inCopy = in.to(torch::kCUDA); auto outCopy = out.to(torch::kCUDA); std::vector<torch::Tensor> tin({inCopy.detach()}); std::vector<std::vector<torch::Tensor>> tout; tout.emplace_back(); for (auto i = 0; i < out.size(0); i++) { tout.back().emplace_back(outCopy[i]); } auto onFinish = [inCopy, outCopy, in, out]() mutable { in.copy_(inCopy); out.copy_(outCopy); }; Work work(onFinish); work.add(ncclPG_->allgather(tout, tin)); return work; } } Context::Context(std::shared_ptr<Store> store, int rank, int size) : rank(rank), size(size), ncclPG_(std::make_shared<ProcessGroupNCCL>(store, rank, size)) { ProcessGroupGloo::Options opts; opts.timeout = std::chrono::milliseconds(0); // No timeout auto addr = netutils::getInterfaceAddresses(); opts.devices.emplace_back( gloo::transport::tcp::CreateDevice(addr.front().c_str())); glooPG_ = std::make_shared<ProcessGroupGloo>(store, rank, size, opts); } template <typename T, IsTorchDType<T>*> Work allreduce(T* ptr, int64_t s, ReduceOp op) { return globalContext()->allreduce(ptr, s, op); } template <typename T, IsTorchDType<T>*> Work allreduce(std::vector<T>& v, ReduceOp op) { return globalContext()->allreduce(v, op); } Work allreduce(torch::Tensor x, ReduceOp op) { return globalContext()->allreduce(x, op); } Work allreduceGradients(ag::Container const& x, ReduceOp op) { return globalContext()->allreduceGradients(x, op); } template <typename T, IsTorchDType<T>*> Work broadcast(T* ptr, int64_t s, int root) { return globalContext()->broadcast(ptr, s, root); } template <typename T, IsTorchDType<T>*> Work broadcast(std::vector<T>& v, int root) { return globalContext()->broadcast(v, root); } Work broadcast(torch::Tensor x, int root) { return globalContext()->broadcast(x, root); } Work broadcast(ag::Container const& x, int root) { return globalContext()->broadcast(x, root); } template <typename T, IsTorchDType<T>*> Work allgather(T* out, T* in, int64_t s) { return globalContext()->allgather(out, in, s); } template <typename T, IsTorchDType<T>*> Work allgather(T* out, torch::Tensor in) { return globalContext()->allgather(out, in); } Work allgather(torch::Tensor out, torch::Tensor in) { return globalContext()->allgather(out, in); } #define FORCE_INSTANTIATION(T, TORCH_TYPE) \ template Work allreduce(T* ptr, int64_t s, ReduceOp op); \ template Work allreduce(std::vector<T>& v, ReduceOp op); \ template Work broadcast(T* ptr, int64_t s, int root); \ template Work broadcast(std::vector<T>& v, int root); \ template Work allgather(T* out, T* in, int64_t s); \ template Work allgather(T* out, torch::Tensor in); FOR_ALL_TYPES(FORCE_INSTANTIATION); } // namespace distributed } // namespace cpid
30.21573
80
0.60174
yuhonghong66
f24d33dee5c0258ca67149e862ba3f68a91c1437
5,641
cc
C++
tile/codegen/aggrinit.cc
redoclag/plaidml
46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314
[ "Apache-2.0" ]
4,535
2017-10-20T05:03:57.000Z
2022-03-30T15:42:33.000Z
tile/codegen/aggrinit.cc
HOZHENWAI/plaidml
46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314
[ "Apache-2.0" ]
984
2017-10-20T17:16:09.000Z
2022-03-30T05:43:18.000Z
tile/codegen/aggrinit.cc
HOZHENWAI/plaidml
46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314
[ "Apache-2.0" ]
492
2017-10-20T18:22:32.000Z
2022-03-30T09:00:05.000Z
// Copyright 2018, Intel Corporation #include <memory> #include <set> #include <vector> #include "tile/codegen/aggrinit.h" #include "tile/codegen/deps.h" #include "tile/stripe/stripe.h" namespace vertexai { namespace tile { namespace codegen { using namespace stripe; // NOLINT using namespace math; // NOLINT void AggregationBlockOutputInitialization(const stripe::Block* const block, const AggregationBlockOutputInitializationPass* aggregationPass) { if (block == nullptr) { throw new std::runtime_error("AggregationBlockOutputInitialization' block parameter cannot be nullptr."); } // Handle local buffers. // When two same refinements are used in the same stripe block, // do not emit duplicated local declarations. std::set<std::string> dup_ref; // Now, add any new locals that have agg_op. for (const auto& ref : block->refs) { if (ref.dir == stripe::RefDir::None && dup_ref.find(ref.into()) == dup_ref.end() && !ref.has_tag("user")) { std::string aggOp = ref.agg_op; if (!aggOp.empty()) { const_cast<AggregationBlockOutputInitializationPass*>(aggregationPass) ->AddRefinementToInit(const_cast<stripe::Block*>(block), &ref, nullptr, aggOp); } } } const Block* prevBlock = aggregationPass->state.prevBlock; if (prevBlock == nullptr) { // Nothing to do here. return; } std::vector<const Refinement*> outRefs = block->ref_outs(true); for (const Refinement* dest : outRefs) { std::string aggOp = dest->agg_op; if (aggOp != "add" && aggOp != "mul" && aggOp != "max" && aggOp != "min") { continue; } auto prevRefIter = prevBlock->ref_by_into(dest->from); if (prevRefIter == prevBlock->refs.end()) { throw std::runtime_error( "AggregationBlockOutputInitializationPass: Didn't find referenced Refinement from outer block."); } if (prevRefIter->agg_op == "" || prevRefIter->agg_op == "assign") { const_cast<AggregationBlockOutputInitializationPass*>(aggregationPass) ->AddRefinementToInit(const_cast<stripe::Block*>(prevBlock), &(*prevRefIter), block, aggOp); } else { if (prevRefIter->agg_op != aggOp) { // TODO: Create a temp buffer here. throw std::runtime_error("Nested agg ops of different type is not supported at the moment"); } } } } void AggregationBlockOutputInitializationPass::Apply(CompilerState* state) const { auto reqs = stripe::FromProto(options_.reqs()); RunOnBlocksRecurse(state->entry(), reqs, this); // Generate the specials AggInit Calls for (const auto& toInit : this->state.blocksWithInits) { assert(toInit.blockToAddTo != nullptr); assert(toInit.refToInitialize != nullptr); assert(toInit.initType == AggregationInitType::ADD || toInit.initType == AggregationInitType::MUL || toInit.initType == AggregationInitType::MIN || toInit.initType == AggregationInitType::MAX); auto aggInit = std::make_shared<Special>(); std::string aggInitName = ""; switch (toInit.initType) { case AggregationInitType::ADD: aggInitName = "agg_init_add"; break; case AggregationInitType::MUL: aggInitName = "agg_init_mul"; break; case AggregationInitType::MIN: aggInitName = "agg_init_min"; break; case AggregationInitType::MAX: aggInitName = "agg_init_max"; break; default: throw std::runtime_error("Invalid Aggregation Initialization Type value."); } aggInit->name = aggInitName; aggInit->outputs.emplace_back(toInit.refToInitialize->into()); if (toInit.statementToAddBefore == nullptr) { toInit.blockToAddTo->stmts.emplace_front(aggInit); } else { // Insert the element before the toInit.statementToAddBefore element. auto it = toInit.blockToAddTo->stmts.begin(); auto end = toInit.blockToAddTo->stmts.end(); for (; it != end; ++it) { if (it->get() == toInit.statementToAddBefore) { break; } } if (it == end) { throw std::runtime_error("The toInit.statementToAddBefore must be in the list."); } toInit.blockToAddTo->stmts.insert(it, aggInit); } } const_cast<AggregationBlockOutputInitializationState&>(this->state).Clear(); } void AggregationBlockOutputInitializationPass::AddRefinementToInit(stripe::Block* toBlock, const stripe::Refinement* ref, const stripe::Statement* beforeStatement, const std::string initTypeStr) { AggregationInitType initType = AggregationInitType::NONE; if (initTypeStr == "add") { initType = AggregationInitType::ADD; } else if (initTypeStr == "mul") { initType = AggregationInitType::MUL; } else if (initTypeStr == "min") { initType = AggregationInitType::MIN; } else if (initTypeStr == "max") { initType = AggregationInitType::MAX; } else { throw std::runtime_error("Valid initTypeStr must be specified for AggregationInitType."); } state.blocksWithInits.emplace_back(AggregationBlockOutputInitializationNode(toBlock, ref, beforeStatement, initType)); } namespace { [[gnu::unused]] char reg = []() -> char { CompilePassFactory<AggregationBlockOutputInitializationPass, proto::AggregationBlockOutputInitializationPass>::Register(); return 0; }(); } // namespace } // namespace codegen } // namespace tile } // namespace vertexai
36.62987
120
0.650062
redoclag
f24d8f7f0d00429986a372ed51f16f2f4313b8f9
1,248
cpp
C++
baekjoon/1963/source.cpp
qilip/ACMStudy
c4d6f31b01358ead4959c92f1fac59a3826f3f77
[ "CC-BY-3.0" ]
4
2020-02-02T08:34:46.000Z
2021-10-01T11:21:17.000Z
baekjoon/1963/source.cpp
qilip/ACMStudy
c4d6f31b01358ead4959c92f1fac59a3826f3f77
[ "CC-BY-3.0" ]
1
2021-09-04T14:03:50.000Z
2021-09-04T14:03:50.000Z
baekjoon/1963/source.cpp
qilip/ACMStudy
c4d6f31b01358ead4959c92f1fac59a3826f3f77
[ "CC-BY-3.0" ]
null
null
null
#include <stdio.h> #include <queue> #include <utility> #include <tuple> using namespace std; int main(void){ int t; int not_prime[10000] = {0}; scanf("%d", &t); for(int i=2;i<100;i++){ if(not_prime[i]) continue; for(int j=i*i; j<=10000;j+=i){ not_prime[j] = 1; } } for(int T=0;T<t;T++){ int a, b; queue<pair<int, int>> q; int checked[10000] = {0}; scanf("%d %d", &a, &b); q.emplace(0, a); checked[a] = 1; int flg = 1; while(!q.empty()){ int cost, cur; tie(cost, cur) = q.front(); q.pop(); if(cur==b){ printf("%d\n", cost); flg = 0; break; } for(int i=1;i<=1000;i*=10){ int next = cur - cur/i%10*i; for(int j=0;j<=9;j++){ int cnxt = next+i*j; if(!not_prime[cnxt] && cnxt >=1000 && cnxt <=9999 && !checked[cnxt]){ q.emplace(cost+1, cnxt); checked[cnxt] = 1; } } } } if(flg) printf("Impossible\n"); } return 0; }
24.96
89
0.382212
qilip
f25027178d14ec297b6c3d335610e193a2ae3e03
420
cpp
C++
test/tuple_forward.cpp
LB--/tuples
4e1c5ecc1f3d2237050868dd1e895113484de3c6
[ "Unlicense" ]
1
2016-04-13T19:57:54.000Z
2016-04-13T19:57:54.000Z
test/tuple_forward.cpp
LB--/tuples
4e1c5ecc1f3d2237050868dd1e895113484de3c6
[ "Unlicense" ]
null
null
null
test/tuple_forward.cpp
LB--/tuples
4e1c5ecc1f3d2237050868dd1e895113484de3c6
[ "Unlicense" ]
null
null
null
#include "tuple_forward.hpp" #include <functional> #include <tuple> int main() noexcept { using namespace LB::tuples; static constexpr auto t1 = std::make_tuple(1, 1); static constexpr auto t2 = std::make_tuple(1, 2); static_assert(tuple_forward(std::equal_to<int>{}, t1), "t1 doesn't contain the same value twice"); static_assert(!tuple_forward(std::equal_to<int>{}, t2), "t2 contains the same value twice"); }
28
99
0.72381
LB--
f254244cfde391a02b65a69db47a22302c374e6c
6,084
cpp
C++
GLWrapper/GLView.cpp
filipkunc/GLGraphics
fb696948034832e1fbc60b7c6095560a79952875
[ "MIT" ]
6
2015-12-29T11:24:29.000Z
2021-07-17T06:00:30.000Z
GLWrapper/GLView.cpp
filipkunc/GLGraphics
fb696948034832e1fbc60b7c6095560a79952875
[ "MIT" ]
null
null
null
GLWrapper/GLView.cpp
filipkunc/GLGraphics
fb696948034832e1fbc60b7c6095560a79952875
[ "MIT" ]
1
2021-05-27T07:35:57.000Z
2021-05-27T07:35:57.000Z
#include "stdafx.h" #include "DesignModeDevenv.h" #include "GLCanvas.h" #include "EventArgs.h" #include "GLView.h" bool WGLExtensionSupported(const char *extension_name) { // this is pointer to function which returns pointer to string with list of all wgl extensions PFNWGLGETEXTENSIONSSTRINGEXTPROC wglGetExtensionsStringEXT = nullptr; // determine pointer to wglGetExtensionsStringEXT function wglGetExtensionsStringEXT = (PFNWGLGETEXTENSIONSSTRINGEXTPROC) wglGetProcAddress("wglGetExtensionsStringEXT"); if (strstr(wglGetExtensionsStringEXT(), extension_name) == nullptr) { // string was not found return false; } // extension is supported return true; } namespace GLWrapper { GLView::GLView(void) { deviceContext = nullptr; glRenderingContext = nullptr; sharedContextView = nullptr; glCanvas = nullptr; glEnabled = true; neverInitGL = false; testGLErrors = false; } GLView::~GLView() { EndGL(); if (glRenderingContext) { wglDeleteContext(glRenderingContext); glRenderingContext = nullptr; } if (components) { delete components; } } GLView ^GLView::SharedContextView::get() { return sharedContextView; } void GLView::SharedContextView::set(GLView ^value) { sharedContextView = value; } #pragma region OnEvents void GLView::OnLoad(EventArgs ^e) { UserControl::OnLoad(e); try { InitGL(); } catch (Exception ^e) { glEnabled = false; InitGLErrorHandler(this, gcnew ExceptionEventArgs(e)); } } void GLView::OnSizeChanged(EventArgs ^e) { UserControl::OnSizeChanged(e); Invalidate(); } void GLView::OnPaint(PaintEventArgs ^e) { if (DesignModeDevenv::DesignMode) { UserControl::OnPaint(e); return; } if (!glEnabled) UserControl::OnPaint(e); else PaintGL(e); } void GLView::OnPaintBackground(PaintEventArgs ^e) { if (DesignModeDevenv::DesignMode || !glEnabled) UserControl::OnPaintBackground(e); } #pragma endregion GLError GLView::GetGLError() { GLenum errorCode = glGetError(); GLError glError = (GLError)errorCode; return glError; } void GLView::PaintGL(PaintEventArgs ^paintArgs) { if (!deviceContext || !glRenderingContext) return; try { BeginGL(); } catch (Exception ^e) { glEnabled = false; InitGLErrorHandler(this, gcnew ExceptionEventArgs(e)); } DrawGL(paintArgs); if (testGLErrors) { GLenum errorCode = glGetError(); GLError glError = (GLError)errorCode; GLErrorHandler(this, gcnew GLErrorEventArgs(glError)); } SwapBuffers(deviceContext); EndGL(); } void GLView::InitGL() { if (DesignModeDevenv::DesignMode || neverInitGL) return; deviceContext = GetDC((HWND)this->Handle.ToPointer()); // CAUTION: Not doing the following SwapBuffers() on the DC will // result in a failure to subsequently create the RC. SwapBuffers(deviceContext); //Get the pixel format PIXELFORMATDESCRIPTOR pfd; ZeroMemory(&pfd, sizeof(pfd)); pfd.nSize = sizeof(pfd); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 0; pfd.iLayerType = PFD_MAIN_PLANE; int pixelFormatIndex = ChoosePixelFormat(deviceContext, &pfd); if (pixelFormatIndex == 0) { throw gcnew Win32Exception(Marshal::GetLastWin32Error(), "Unable to retrieve pixel format"); } if (SetPixelFormat(deviceContext, pixelFormatIndex, &pfd) == 0) { throw gcnew Win32Exception(Marshal::GetLastWin32Error(), "Unable to set pixel format"); } wglMakeCurrent(0, 0); //Create rendering context glRenderingContext = wglCreateContext(deviceContext); if (sharedContextView != nullptr) { wglShareLists(sharedContextView->glRenderingContext, glRenderingContext); } if (!glRenderingContext) { throw gcnew Win32Exception(Marshal::GetLastWin32Error(), "Unable to get rendering context"); } if (wglMakeCurrent(deviceContext, glRenderingContext) == 0) { throw gcnew Win32Exception(Marshal::GetLastWin32Error(), "Unable to make rendering context current"); } if (WGLExtensionSupported("WGL_EXT_swap_control")) { PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT"); wglSwapIntervalEXT(0); // Disable VSYNC } } void GLView::BeginGL() { if (wglMakeCurrent(deviceContext, glRenderingContext) == 0) { throw gcnew Win32Exception(Marshal::GetLastWin32Error(), "Unable to make rendering context current"); } } void GLView::EndGL() { wglMakeCurrent(NULL, NULL); } void GLView::ReshapeFlippedOrtho2D() { System::Drawing::Rectangle rect = this->ClientRectangle; glViewport(0, 0, rect.Width, rect.Height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, rect.Width, 0, rect.Height, -1.0f, 1.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef((float)-rect.X, (float)rect.Y + (float)rect.Height, 0); glScalef(1, -1, 1); //glTranslatef(0.5f, 0.5f, 0.0f); } void GLView::DrawGL(PaintEventArgs ^paintArgs) { ReshapeFlippedOrtho2D(); if (glCanvas == nullptr) glCanvas = gcnew GLCanvas(this->BackColor); else glCanvas->Clear(this->BackColor); glCanvas->CanvasSize = this->ClientSize; glCanvas->Dpi = PointF(paintArgs->Graphics->DpiX, paintArgs->Graphics->DpiY); glPushMatrix(); CanvasEventArgs ^args = gcnew CanvasEventArgs(glCanvas, paintArgs); PaintCanvas(this, args); glPopMatrix(); } }
24.336
127
0.646121
filipkunc
f2559aebfae3e6270306e8f9d26943ba92a58248
2,392
cpp
C++
src/rtl/JitteredRenderer.cpp
potato3d/rtrt
cac9f2f80d94bf60adf0bbd009f5076973ee10c6
[ "MIT" ]
2
2021-02-13T14:18:39.000Z
2021-11-04T07:21:21.000Z
src/rtl/JitteredRenderer.cpp
potato3d/rtrt
cac9f2f80d94bf60adf0bbd009f5076973ee10c6
[ "MIT" ]
null
null
null
src/rtl/JitteredRenderer.cpp
potato3d/rtrt
cac9f2f80d94bf60adf0bbd009f5076973ee10c6
[ "MIT" ]
null
null
null
#include <rtl/JitteredRenderer.h> #include <rtu/random.h> namespace rtl { static const float TWO_BY_TWO_GRID[] = { -0.25f, -0.25f, // line 0 0.25f, -0.25f, -0.25f, 0.25f, // line 1 0.25f, 0.25f }; static const float FOUR_BY_FOUR_GRID[] = { -0.375f, -0.375f, // line 0 -0.125f, -0.375f, 0.125f, -0.375f, 0.375f, -0.375f, -0.375f, -0.125f, // line 1 -0.125f, -0.125f, 0.125f, -0.125f, 0.375f, -0.125f, -0.375f, 0.125f, // line 2 -0.125f, 0.125f, 0.125f, 0.125f, 0.375f, 0.125f, -0.375f, 0.375f, // line 3 -0.125f, 0.375f, 0.125f, 0.375f, 0.375f, 0.375f }; void JitteredRenderer::init() { rtu::Random::autoSeed(); _gridRes = FOUR_BY_FOUR; } void JitteredRenderer::render() { unsigned int width; unsigned int height; rtsViewport( width, height ); int w = (int)width; int h = (int)height; float* frameBuffer = rtsFrameBuffer(); rts::RTstate sample; rtu::float3 resultColor; int x, y; const float* grid; unsigned int gridSize; float ratio; switch( _gridRes ) { case TWO_BY_TWO: grid = TWO_BY_TWO_GRID; gridSize = 8; ratio = 0.25f; break; case FOUR_BY_FOUR: grid = FOUR_BY_FOUR_GRID; gridSize = 32; ratio = 0.0625f; break; default: return; } int chunk = 16; #pragma omp parallel for shared( frameBuffer, h, w ) private( y ) schedule( dynamic, chunk ) for( y = 0; y < h; ++y ) { #pragma omp parallel for shared( frameBuffer, h, w, y, grid, gridSize, ratio ) private( x, resultColor, sample ) schedule( dynamic, chunk ) for( x = 0; x < w; ++x ) { resultColor.set( 0.0f, 0.0f, 0.0f ); unsigned int i = 0; while( i < gridSize ) { rtsInitPrimaryRayState( sample, (float)x + grid[i++] + rtu::Random::real( -ratio, ratio ), (float)y + grid[i++] + rtu::Random::real( -ratio, ratio ) ); rtsTraceRay( sample ); resultColor += rtsResultColor( sample ); } resultColor *= ratio; frameBuffer[(x+y*w)*3] = resultColor.r; frameBuffer[(x+y*w)*3+1] = resultColor.g; frameBuffer[(x+y*w)*3+2] = resultColor.b; } } } void JitteredRenderer::setGridResolution( GridResolution res ) { _gridRes = res; } } // namespace rtl
23.45098
141
0.557692
potato3d
f256d735ecba0dd959b5201efd90baf39f1f03dc
1,557
cpp
C++
ros-pkg/utility/serializable/src/test/test_serializable.cpp
kunle12/clams
8de99fcdf6cf6bede1de6ed18c4d397bd53b7f32
[ "BSD-3-Clause" ]
1
2018-02-03T08:15:57.000Z
2018-02-03T08:15:57.000Z
ros-pkg/utility/serializable/src/test/test_serializable.cpp
kunle12/clams
8de99fcdf6cf6bede1de6ed18c4d397bd53b7f32
[ "BSD-3-Clause" ]
null
null
null
ros-pkg/utility/serializable/src/test/test_serializable.cpp
kunle12/clams
8de99fcdf6cf6bede1de6ed18c4d397bd53b7f32
[ "BSD-3-Clause" ]
null
null
null
#include <serializable/serializable.h> #include <gtest/gtest.h> using namespace std; // NDC = NoDefaultConstructor // // Typically, Serializable classes have a default ctor so you can create an // uninitialized object, then call load() or deserialize() on it. // // Classes which need to be deserialized but which cannot have a default ctor // should implement an istream constructor. I'd like to provide this // by default via Serializable, but as far as I can tell this is not // possible and you have to do it yourself. // // Fortunately it's pretty easy. class NDC : public Serializable { public: int val_; NDC(int val) : val_(val) {} // This is pretty reasonable. NDC(istream& in) { deserialize(in); } // This isn't necessarily an OK thing to do. Depends on the context. // If you do choose to use this form of deserialization constructor, // definitely make it explicit. explicit NDC(const std::string& path) { load(path); } void serialize(std::ostream& out) const { out.write((char*)&val_, sizeof(int)); } void deserialize(std::istream& in) { cout << "NDC::deserialize" << endl; in.read((char*)&val_, sizeof(int)); } }; TEST(Serializable, Serializable) { int val = 13; NDC ndc(val); ndc.save("ndc"); NDC ndc2((IfstreamWrapper("ndc"))); cout << ndc2.val_ << endl; EXPECT_TRUE(ndc2.val_ == val); NDC ndc3("ndc"); cout << ndc3.val_ << endl; EXPECT_TRUE(ndc3.val_ == val); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
25.112903
77
0.676301
kunle12
f25cb5413f057b26ca6896e89048ff42f13a52af
980
cpp
C++
m68k_trace/musashi.cpp
fredrequin/verilator_helpers
4ff43594f9ddf62d3e6696520623809b59e0b1e1
[ "BSD-3-Clause" ]
null
null
null
m68k_trace/musashi.cpp
fredrequin/verilator_helpers
4ff43594f9ddf62d3e6696520623809b59e0b1e1
[ "BSD-3-Clause" ]
null
null
null
m68k_trace/musashi.cpp
fredrequin/verilator_helpers
4ff43594f9ddf62d3e6696520623809b59e0b1e1
[ "BSD-3-Clause" ]
null
null
null
#ifdef __cplusplus extern "C" { #endif #include <stdio.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include "musashi/m68k.h" #define FLG_C(r) (r & 1) ? '1' : '0' #define FLG_V(r) (r & 2) ? '1' : '0' #define FLG_Z(r) (r & 4) ? '1' : '0' #define FLG_N(r) (r & 8) ? '1' : '0' #define FLG_X(r) (r & 16) ? '1' : '0' void m68k_instr_hook(void) { } unsigned int m68k_read_disassembler_8 (unsigned int addr) { return m68k_read_memory_8(addr); } unsigned int m68k_read_disassembler_16 (unsigned int addr) { return m68k_read_memory_16(addr); } unsigned int m68k_read_disassembler_32 (unsigned int addr) { return m68k_read_memory_32(addr); } // Hack to integrate musashi into the C++ framework that verilator needs #include "musashi/m68kopac.c" #include "musashi/m68kopdm.c" #include "musashi/m68kopnz.c" #include "musashi/m68kops.c" #include "musashi/m68kcpu.c" #include "musashi/m68kdasm.c" #ifdef __cplusplus } #endif
28.823529
97
0.670408
fredrequin
f26bcb26cc4ff77c6d2d9b35e450db33172027db
20,699
cpp
C++
Examples/crosscurrencylgm.cpp
universe1987/QuantLib
bbb0145aff285853755b9f6ed013f53a41163acb
[ "BSD-3-Clause" ]
4
2016-03-28T15:05:23.000Z
2020-02-17T23:05:57.000Z
Examples/crosscurrencylgm.cpp
universe1987/QuantLib
bbb0145aff285853755b9f6ed013f53a41163acb
[ "BSD-3-Clause" ]
1
2015-02-02T20:32:43.000Z
2015-02-02T20:32:43.000Z
Examples/crosscurrencylgm.cpp
pcaspers/quantlib
bbb0145aff285853755b9f6ed013f53a41163acb
[ "BSD-3-Clause" ]
10
2015-01-26T14:50:24.000Z
2015-10-23T07:41:30.000Z
#include <ql/quantlib.hpp> #include <boost/make_shared.hpp> // example / tests for multicurrency lgm model using namespace QuantLib; void nodelete() {} int main() { try { Date referenceDate(30, July, 2015); Settings::instance().evaluationDate() = referenceDate; // the single currency models // they can be calibrated in the usual way Handle<YieldTermStructure> eurYts(boost::make_shared<FlatForward>( referenceDate, 0.02, Actual365Fixed())); Handle<YieldTermStructure> usdYts(boost::make_shared<FlatForward>( referenceDate, 0.05, Actual365Fixed())); std::vector<Date> volstepdates; std::vector<Real> volsteptimes; Array volsteptimes_a(0); std::vector<Real> eurVols(1, atof(getenv("EURVOL"))); std::vector<Real> usdVols(1, atof(getenv("USDVOL"))); std::vector<Real> fxSigmas(1, atof(getenv("FXVOL"))); Array fxSigmas_a(fxSigmas.begin(), fxSigmas.end()); boost::shared_ptr<Lgm1> eurLgm = boost::make_shared<Lgm1>( eurYts, volstepdates, eurVols, atof(getenv("EURMR"))); boost::shared_ptr<Lgm1> usdLgm = boost::make_shared<Lgm1>( usdYts, volstepdates, usdVols, atof(getenv("USDMR"))); std::vector<boost::shared_ptr<Lgm1> > singleModels; singleModels.push_back(eurLgm); singleModels.push_back(usdLgm); std::vector<Handle<YieldTermStructure> > curves; curves.push_back(eurYts); curves.push_back(usdYts); // build cc parametrization from scratch // lgm parametrizations std::vector<boost::shared_ptr<detail::LgmParametrization< detail::LgmPiecewiseAlphaConstantKappa> > > lgmParametrizations; boost::shared_ptr< detail::LgmParametrization<detail::LgmPiecewiseAlphaConstantKappa> > eurParam = eurLgm->parametrization(); boost::shared_ptr< detail::LgmParametrization<detail::LgmPiecewiseAlphaConstantKappa> > usdParam = usdLgm->parametrization(); lgmParametrizations.push_back(eurParam); lgmParametrizations.push_back(usdParam); // fx parametrizations std::vector<boost::shared_ptr<detail::LgmFxParametrization< detail::LgmFxPiecewiseSigma> > > fxParametrizations; boost::shared_ptr<detail::LgmFxParametrization< detail::LgmFxPiecewiseSigma> > fxParam = boost::make_shared<detail::LgmFxPiecewiseSigma>(volsteptimes_a, fxSigmas_a); fxParametrizations.push_back(fxParam); // the fx vols, correlations and the cclgmm parametrization / process / // model std::vector<Handle<Quote> > fxSpots; fxSpots.push_back(Handle<Quote>(boost::make_shared<SimpleQuote>( std::log(0.9090)))); // EUR-USD ~ 1.10 Matrix c(3, 3); // FX EUR USD c[0][0] = 1.0; c[0][1] = 0.99; c[0][2] = 0.99; // FX c[1][0] = 0.99; c[1][1] = 1.0; c[1][2] = 0.99; // EUR c[2][0] = 0.99; c[2][1] = 0.99; c[2][2] = 1.0; // USD boost::shared_ptr<detail::CcLgmPiecewise> ccParam = boost::make_shared<detail::CcLgmPiecewise>(fxParametrizations, lgmParametrizations, c); ccParam->update(); // test parametrization std::clog.precision(12); // std::clog << "H0(0.0) = " << ccParam->H_i(0,0.0) << std::endl; // std::clog << "H0(1.0) = " << ccParam->H_i(0,1.0) << std::endl; // std::clog << "H0(2.0) = " << ccParam->H_i(0,2.0) << std::endl; // std::clog << "H1(0.0) = " << ccParam->H_i(1,0.0) << std::endl; // std::clog << "H1(1.0) = " << ccParam->H_i(1,1.0) << std::endl; // std::clog << "H1(2.0) = " << ccParam->H_i(1,2.0) << std::endl; // std::clog << "zeta0(0.0) = " << ccParam->zeta_i(0,0.0) << std::endl; // std::clog << "zeta0(1.0) = " << ccParam->zeta_i(0,1.0) << std::endl; // std::clog << "zeta0(2.0) = " << ccParam->zeta_i(0,2.0) << std::endl; // std::clog << "zeta0(3.0) = " << ccParam->zeta_i(0,3.0) << std::endl; // std::clog << "zeta1(0.0) = " << ccParam->zeta_i(1,0.0) << std::endl; // std::clog << "zeta1(1.0) = " << ccParam->zeta_i(1,1.0) << std::endl; // std::clog << "zeta1(2.0) = " << ccParam->zeta_i(1,2.0) << std::endl; // std::clog << "zeta1(3.0) = " << ccParam->zeta_i(1,3.0) << std::endl; // std::clog << "alphaialphaj(0.0) = " << // ccParam->alpha_i_alpha_j(0,0,0.0) << std::endl; // std::clog << "alphaialphaj(1.0) = " << // ccParam->alpha_i_alpha_j(0,0,1.0) << std::endl; // std::clog << "alphaialphaj(2.0) = " << // ccParam->alpha_i_alpha_j(0,0,2.0) << std::endl; // std::clog << "alphaialphaj(0.0) = " << // ccParam->alpha_i_alpha_j(1,1,0.0) << std::endl; // std::clog << "alphaialphaj(1.0) = " << // ccParam->alpha_i_alpha_j(1,1,1.0) << std::endl; // std::clog << "alphaialphaj(2.0) = " << // ccParam->alpha_i_alpha_j(1,1,2.0) << std::endl; // std::clog << "alphaialphaj(0.0) = " << // ccParam->alpha_i_alpha_j(0,1,0.0) << std::endl; // std::clog << "alphaialphaj(1.0) = " << // ccParam->alpha_i_alpha_j(0,1,1.0) << std::endl; // std::clog << "alphaialphaj(2.0) = " << // ccParam->alpha_i_alpha_j(0,1,2.0) << std::endl; // std::clog << "alphaialphaj(0.0) = " << // ccParam->alpha_i_alpha_j(1,0,0.0) << std::endl; // std::clog << "alphaialphaj(1.0) = " << // ccParam->alpha_i_alpha_j(1,0,1.0) << std::endl; // std::clog << "alphaialphaj(2.0) = " << // ccParam->alpha_i_alpha_j(1,0,2.0) << std::endl; // std::clog << "sigmaisigmaj(0.0) = " << // ccParam->sigma_i_sigma_j(0,0,0.0) << std::endl; // std::clog << "sigmaisigmaj(1.0) = " << // ccParam->sigma_i_sigma_j(0,0,1.0) << std::endl; // std::clog << "sigmaisigmaj(2.0) = " << // ccParam->sigma_i_sigma_j(0,0,2.0) << std::endl; // std::clog << "alphaisigmaj(0.0) = " << // ccParam->alpha_i_sigma_j(0,0,0.0) << std::endl; // std::clog << "alphaisigmaj(1.0) = " << // ccParam->alpha_i_sigma_j(0,0,1.0) << std::endl; // std::clog << "alphaisigmaj(2.0) = " << // ccParam->alpha_i_sigma_j(0,0,2.0) << std::endl; // std::clog << "alphaisigmaj(0.0) = " << // ccParam->alpha_i_sigma_j(1,0,0.0) << std::endl; // std::clog << "alphaisigmaj(1.0) = " << // ccParam->alpha_i_sigma_j(1,0,1.0) << std::endl; // std::clog << "alphaisigmaj(2.0) = " << // ccParam->alpha_i_sigma_j(1,0,2.0) << std::endl; // std::clog << "HiAlphaIAlphaJ(0.0) = " << // ccParam->H_i_alpha_i_alpha_j(0,0,0.0) << std::endl; // std::clog << "HiAlphaIAlphaJ(0.0) = " << // ccParam->H_i_alpha_i_alpha_j(0,0,1.0) << std::endl; // std::clog << "HiAlphaIAlphaJ(0.0) = " << // ccParam->H_i_alpha_i_alpha_j(0,0,2.0) << std::endl; // std::clog << "HiAlphaIAlphaJ(0.0) = " << // ccParam->H_i_alpha_i_alpha_j(1,1,0.0) << std::endl; // std::clog << "HiAlphaIAlphaJ(0.0) = " << // ccParam->H_i_alpha_i_alpha_j(1,1,1.0) << std::endl; // std::clog << "HiAlphaIAlphaJ(0.0) = " << // ccParam->H_i_alpha_i_alpha_j(1,1,2.0) << std::endl; // std::clog << "HiAlphaIAlphaJ(0.0) = " << // ccParam->H_i_alpha_i_alpha_j(1,0,0.0) << std::endl; // std::clog << "HiAlphaIAlphaJ(0.0) = " << // ccParam->H_i_alpha_i_alpha_j(1,0,1.0) << std::endl; // std::clog << "HiAlphaIAlphaJ(0.0) = " << // ccParam->H_i_alpha_i_alpha_j(1,0,2.0) << std::endl; // std::clog << "HiHjAlphaIAlphaJ(0.0) = " << // ccParam->H_i_H_j_alpha_i_alpha_j(0,0,0.0) << std::endl; // std::clog << "HiHjAlphaIAlphaJ(0.0) = " << // ccParam->H_i_H_j_alpha_i_alpha_j(0,0,1.0) << std::endl; // std::clog << "HiHjAlphaIAlphaJ(0.0) = " << // ccParam->H_i_H_j_alpha_i_alpha_j(0,0,2.0) << std::endl; // std::clog << "HiHjAlphaIAlphaJ(0.0) = " << // ccParam->H_i_H_j_alpha_i_alpha_j(1,1,0.0) << std::endl; // std::clog << "HiHjAlphaIAlphaJ(0.0) = " << // ccParam->H_i_H_j_alpha_i_alpha_j(1,1,1.0) << std::endl; // std::clog << "HiHjAlphaIAlphaJ(0.0) = " << // ccParam->H_i_H_j_alpha_i_alpha_j(1,1,2.0) << std::endl; // std::clog << "HiHjAlphaIAlphaJ(0.0) = " << // ccParam->H_i_H_j_alpha_i_alpha_j(1,0,0.0) << std::endl; // std::clog << "HiHjAlphaIAlphaJ(0.0) = " << // ccParam->H_i_H_j_alpha_i_alpha_j(1,0,1.0) << std::endl; // std::clog << "HiHjAlphaIAlphaJ(0.0) = " << // ccParam->H_i_H_j_alpha_i_alpha_j(1,0,2.0) << std::endl; // std::clog << "HiAlphaISigmaJ(0.0) = " << // ccParam->H_i_alpha_i_sigma_j(0,0,0.0) << std::endl; // std::clog << "HiAlphaISigmaJ(0.0) = " << // ccParam->H_i_alpha_i_sigma_j(0,0,1.0) << std::endl; // std::clog << "HiAlphaISigmaJ(0.0) = " << // ccParam->H_i_alpha_i_sigma_j(0,0,2.0) << std::endl; // std::clog << "HiAlphaISigmaJ(0.0) = " << // ccParam->H_i_alpha_i_sigma_j(1,0,0.0) << std::endl; // std::clog << "HiAlphaISigmaJ(0.0) = " << // ccParam->H_i_alpha_i_sigma_j(1,0,1.0) << std::endl; // std::clog << "HiAlphaISigmaJ(0.0) = " << // ccParam->H_i_alpha_i_sigma_j(1,0,2.0) << std::endl; // std::clog << "int_alphaialphaj(0.0) = " << // ccParam->int_alpha_i_alpha_j(0,0,0.0,0.0) << std::endl; // std::clog << "int_alphaialphaj(1.0) = " << // ccParam->int_alpha_i_alpha_j(0,0,0.0,1.0) << std::endl; // std::clog << "int_alphaialphaj(2.0) = " << // ccParam->int_alpha_i_alpha_j(0,0,0.0,2.0) << std::endl; // std::clog << "int_alphaialphaj(0.0) = " << // ccParam->int_alpha_i_alpha_j(1,1,0.0,0.0) << std::endl; // std::clog << "int_alphaialphaj(1.0) = " << // ccParam->int_alpha_i_alpha_j(1,1,0.0,1.0) << std::endl; // std::clog << "int_alphaialphaj(2.0) = " << // ccParam->int_alpha_i_alpha_j(1,1,0.0,2.0) << std::endl; // std::clog << "int_alphaialphaj(0.0) = " << // ccParam->int_alpha_i_alpha_j(0,1,0.0,0.0) << std::endl; // std::clog << "int_alphaialphaj(1.0) = " << // ccParam->int_alpha_i_alpha_j(0,1,0.0,1.0) << std::endl; // std::clog << "int_alphaialphaj(2.0) = " << // ccParam->int_alpha_i_alpha_j(0,1,0.0,2.0) << std::endl; // std::clog << "int_alphaialphaj(0.0) = " << // ccParam->int_alpha_i_alpha_j(1,0,0.0,0.0) << std::endl; // std::clog << "int_alphaialphaj(1.0) = " << // ccParam->int_alpha_i_alpha_j(1,0,0.0,1.0) << std::endl; // std::clog << "int_alphaialphaj(2.0) = " << // ccParam->int_alpha_i_alpha_j(1,0,0.0,2.0) << std::endl; // std::clog << "int_sigmaisigmaj(0.0) = " << // ccParam->int_sigma_i_sigma_j(0,0,0.0,0.0) << std::endl; // std::clog << "int_sigmaisigmaj(1.0) = " << // ccParam->int_sigma_i_sigma_j(0,0,0.0,1.0) << std::endl; // std::clog << "int_sigmaisigmaj(2.0) = " << // ccParam->int_sigma_i_sigma_j(0,0,0.0,2.0) << std::endl; // std::clog << "int_alphaisigmaj(0.0) = " << // ccParam->int_alpha_i_sigma_j(0,0,0.0,0.0) << std::endl; // std::clog << "int_alphaisigmaj(1.0) = " << // ccParam->int_alpha_i_sigma_j(0,0,0.0,1.0) << std::endl; // std::clog << "int_alphaisigmaj(2.0) = " << // ccParam->int_alpha_i_sigma_j(0,0,0.0,2.0) << std::endl; // std::clog << "int_alphaisigmaj(0.0) = " << // ccParam->int_alpha_i_sigma_j(1,0,0.0,0.0) << std::endl; // std::clog << "int_alphaisigmaj(1.0) = " << // ccParam->int_alpha_i_sigma_j(1,0,0.0,1.0) << std::endl; // std::clog << "int_alphaisigmaj(2.0) = " << // ccParam->int_alpha_i_sigma_j(1,0,0.0,2.0) << std::endl; // std::clog << "int_H_i_alphaialphaj(0.0) = " << // ccParam->int_H_i_alpha_i_alpha_j(0,0,0.0,0.0) << std::endl; // std::clog << "int_H_i_alphaialphaj(1.0) = " << // ccParam->int_H_i_alpha_i_alpha_j(0,0,0.0,1.0) << std::endl; // std::clog << "int_H_i_alphaialphaj(2.0) = " << // ccParam->int_H_i_alpha_i_alpha_j(0,0,0.0,2.0) << std::endl; // std::clog << "int_H_i_alphaialphaj(0.0) = " << // ccParam->int_H_i_alpha_i_alpha_j(1,1,0.0,0.0) << std::endl; // std::clog << "int_H_i_alphaialphaj(1.0) = " << // ccParam->int_H_i_alpha_i_alpha_j(1,1,0.0,1.0) << std::endl; // std::clog << "int_H_i_alphaialphaj(2.0) = " << // ccParam->int_H_i_alpha_i_alpha_j(1,1,0.0,2.0) << std::endl; // std::clog << "int_H_i_alphaialphaj(0.0) = " << // ccParam->int_H_i_alpha_i_alpha_j(0,1,0.0,0.0) << std::endl; // std::clog << "int_H_i_alphaialphaj(1.0) = " << // ccParam->int_H_i_alpha_i_alpha_j(0,1,0.0,1.0) << std::endl; // std::clog << "int_H_i_alphaialphaj(2.0) = " << // ccParam->int_H_i_alpha_i_alpha_j(0,1,0.0,2.0) << std::endl; // std::clog << "int_H_i_alphaialphaj(0.0) = " << // ccParam->int_H_i_alpha_i_alpha_j(1,0,0.0,0.0) << std::endl; // std::clog << "int_H_i_alphaialphaj(1.0) = " << // ccParam->int_H_i_alpha_i_alpha_j(1,0,0.0,1.0) << std::endl; // std::clog << "int_H_i_alphaialphaj(2.0) = " << // ccParam->int_H_i_alpha_i_alpha_j(1,0,0.0,2.0) << std::endl; // std::clog << "int_H_i_H_j_alphaialphaj(0.0) = " << // ccParam->int_H_i_H_j_alpha_i_alpha_j(0,0,0.0,0.0) << std::endl; // std::clog << "int_H_i_H_j_alphaialphaj(1.0) = " << // ccParam->int_H_i_H_j_alpha_i_alpha_j(0,0,0.0,1.0) << std::endl; // std::clog << "int_H_i_H_j_alphaialphaj(2.0) = " << // ccParam->int_H_i_H_j_alpha_i_alpha_j(0,0,0.0,2.0) << std::endl; // std::clog << "int_H_i_H_j_alphaialphaj(0.0) = " << // ccParam->int_H_i_H_j_alpha_i_alpha_j(1,1,0.0,0.0) << std::endl; // std::clog << "int_H_i_H_j_alphaialphaj(1.0) = " << // ccParam->int_H_i_H_j_alpha_i_alpha_j(1,1,0.0,1.0) << std::endl; // std::clog << "int_H_i_H_j_alphaialphaj(2.0) = " << // ccParam->int_H_i_H_j_alpha_i_alpha_j(1,1,0.0,2.0) << std::endl; // std::clog << "int_H_i_H_j_alphaialphaj(0.0) = " << // ccParam->int_H_i_H_j_alpha_i_alpha_j(0,1,0.0,0.0) << std::endl; // std::clog << "int_H_i_H_j_alphaialphaj(1.0) = " << // ccParam->int_H_i_H_j_alpha_i_alpha_j(0,1,0.0,1.0) << std::endl; // std::clog << "int_H_i_H_j_alphaialphaj(2.0) = " << // ccParam->int_H_i_H_j_alpha_i_alpha_j(0,1,0.0,2.0) << std::endl; // std::clog << "int_H_i_H_j_alphaialphaj(0.0) = " << // ccParam->int_H_i_H_j_alpha_i_alpha_j(1,0,0.0,0.0) << std::endl; // std::clog << "int_H_i_H_j_alphaialphaj(1.0) = " << // ccParam->int_H_i_H_j_alpha_i_alpha_j(1,0,0.0,1.0) << std::endl; // std::clog << "int_H_i_H_j_alphaialphaj(2.0) = " << // ccParam->int_H_i_H_j_alpha_i_alpha_j(1,0,0.0,2.0) << std::endl; // std::clog << "int_H_i_alphaisigmaj(0.0) = " << // ccParam->int_H_i_alpha_i_sigma_j(0,0,0.0,0.0) << std::endl; // std::clog << "int_H_i_alphaisigmaj(1.0) = " << // ccParam->int_H_i_alpha_i_sigma_j(0,0,0.0,1.0) << std::endl; // std::clog << "int_H_i_alphaisigmaj(2.0) = " << // ccParam->int_H_i_alpha_i_sigma_j(0,0,0.0,2.0) << std::endl; // std::clog << "int_H_i_alphaisigmaj(0.0) = " << // ccParam->int_H_i_alpha_i_sigma_j(1,0,0.0,0.0) << std::endl; // std::clog << "int_H_i_alphaisigmaj(1.0) = " << // ccParam->int_H_i_alpha_i_sigma_j(1,0,0.0,1.0) << std::endl; // std::clog << "int_H_i_alphaisigmaj(2.0) = " << // ccParam->int_H_i_alpha_i_sigma_j(1,0,0.0,2.0) << std::endl; // std::clog << "rho alpha-alpha 00" << ccParam->rho_alpha_alpha(0,0) << // std::endl; // std::clog << "rho alpha-alpha 01" << ccParam->rho_alpha_alpha(0,1) << // std::endl; // std::clog << "rho alpha-alpha 10" << ccParam->rho_alpha_alpha(1,0) << // std::endl; // std::clog << "rho alpha-alpha 11" << ccParam->rho_alpha_alpha(1,1) << // std::endl; // std::clog << "rho alpha-sigma 00" << ccParam->rho_alpha_sigma(0,0) << // std::endl; // std::clog << "rho alpha-sigma 10" << ccParam->rho_alpha_sigma(1,0) << // std::endl; // std::clog << "rho sigma-sigma 00" << ccParam->rho_sigma_sigma(0,0) << // std::endl; // end test parametrization boost::shared_ptr< CcLgmProcess<detail::CcLgmPiecewise, detail::LgmFxPiecewiseSigma, detail::LgmPiecewiseAlphaConstantKappa> > process = boost::make_shared<CcLgmProcess< detail::CcLgmPiecewise, detail::LgmFxPiecewiseSigma, detail::LgmPiecewiseAlphaConstantKappa> >(ccParam, fxSpots, curves); // generate paths Size n = atoi(getenv("N")); // N paths Time T = atof(getenv("T")); // cashflow time Size steps = static_cast<Size>( T * atof(getenv("STEPS"))); // STEPS steps per year Size seed = atoi(getenv("SEED")); // rng seed TimeGrid grid(T, steps); PseudoRandom::rsg_type sg = PseudoRandom::make_sequence_generator(steps * 3, seed); MultiPathGenerator<PseudoRandom::rsg_type> pg(process, grid, sg, false); PseudoRandom::rsg_type sg2 = PseudoRandom::make_sequence_generator(steps, seed); PathGenerator<PseudoRandom::rsg_type> pg2(usdLgm->stateProcess(), grid, sg2, false); std::vector<Sample<MultiPath> > paths; for (Size j = 0; j < n; ++j) { paths.push_back(pg.next()); } std::vector<Sample<Path> > paths2; for (Size j = 0; j < n; ++j) { paths2.push_back(pg2.next()); } // output paths for visual inspection in gnuplot if (atoi(getenv("OUTPUT"))) { // cc model paths for (Size i = 0; i < paths[0].value[0].length(); ++i) { std::cout << grid[i] << " "; for (Size j = 0; j < n; ++j) { std::cout << std::exp(paths[j].value[0][i]) << " " << paths[j].value[1][i] << " " << paths[j].value[2][i] << " " << paths2[j].value[i] << " "; } std::cout << "\n"; } } // test: 1 USD in 1y, priced in domestic measure Size l = paths[0].value[0].length() - 1; IncrementalStatistics stat, stat2; for (Size j = 0; j < n; ++j) { Real fx = std::exp(paths[j].value[0][l]); Real zeur = paths[j].value[1][l]; Real zusd = paths[j].value[2][l]; Real zusd2 = paths2[j].value[l]; Real stddev = eurLgm->stateProcess()->stdDeviation(0.0, 0.0, T); Real stddev2 = usdLgm->stateProcess()->stdDeviation(0.0, 0.0, T); Real y = (zeur - eurLgm->stateProcess()->expectation(0.0, 0.0, T)) / (!close_enough(stddev, 0.0) ? stddev : 1.0); Real y2 = (zusd2 - usdLgm->stateProcess()->expectation(0.0, 0.0, T)) / (!close_enough(stddev2, 0.0) ? stddev2 : 1.0); stat.add(1.0 * fx / eurLgm->numeraire(T, y)); stat2.add(1.0 / usdLgm->numeraire(T, y2)); } std::clog << "1 USD @ 1y = " << stat.mean() << " EUR +/- " << stat.errorEstimate() << std::endl; ; std::clog << "curve price = " << usdYts->discount(T) << " spot " << std::exp(fxSpots[0]->value()) << " EUR price " << usdYts->discount(T) * std::exp(fxSpots[0]->value()) << "\n"; std::clog << "1 USD @ 1y = " << stat2.mean() << " USD +/-" << stat2.errorEstimate() << std::endl; return 0; } catch (QuantLib::Error e) { std::clog << "ql exception : " << e.what() << "\n"; } catch (std::exception e) { std::clog << "std exception: " << e.what() << "\n"; } }
49.997585
80
0.529977
universe1987
f26bd1be8170507920e279813564d69867ee8aa1
22,112
cpp
C++
unittests/adt/test_sstring_view.cpp
paulhuggett/pstore2
a0c663d10a2e2713fdf39ecdae1f9c1e96041f5c
[ "Apache-2.0" ]
11
2018-02-02T21:24:49.000Z
2020-12-11T04:06:03.000Z
unittests/adt/test_sstring_view.cpp
SNSystems/pstore
74e9dd960245d6bfc125af03ed964d8ad660a62d
[ "Apache-2.0" ]
63
2018-02-05T17:24:59.000Z
2022-03-22T17:26:28.000Z
unittests/adt/test_sstring_view.cpp
paulhuggett/pstore
067be94d87c87fce524c8d76c6f47c347d8f1853
[ "Apache-2.0" ]
5
2020-01-13T22:47:11.000Z
2021-05-14T09:31:15.000Z
//===- unittests/adt/test_sstring_view.cpp --------------------------------===// //* _ _ _ * //* ___ ___| |_ _ __(_)_ __ __ _ __ _(_) _____ __ * //* / __/ __| __| '__| | '_ \ / _` | \ \ / / |/ _ \ \ /\ / / * //* \__ \__ \ |_| | | | | | | (_| | \ V /| | __/\ V V / * //* |___/___/\__|_| |_|_| |_|\__, | \_/ |_|\___| \_/\_/ * //* |___/ * //===----------------------------------------------------------------------===// // // Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions. // See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license // information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "pstore/adt/sstring_view.hpp" // Standard library includes #include <cstring> #include <sstream> // 3rd party #include <gmock/gmock.h> namespace { std::shared_ptr<char> new_shared (std::string const & s) { auto result = std::shared_ptr<char> (new char[s.size ()], [] (char * p) { delete[] p; }); std::copy (std::begin (s), std::end (s), result.get ()); return result; } template <typename T> struct string_maker {}; template <typename CharType> struct string_maker<std::shared_ptr<CharType>> { std::shared_ptr<CharType> operator() (std::string const & str) const { auto ptr = std::shared_ptr<char> (new char[str.length ()], [] (char * p) { delete[] p; }); std::copy (std::begin (str), std::end (str), ptr.get ()); return std::static_pointer_cast<CharType> (ptr); } }; template <typename CharType> struct string_maker<std::unique_ptr<CharType[]>> { std::unique_ptr<CharType[]> operator() (std::string const & str) const { auto ptr = std::make_unique<typename std::remove_const<CharType>::type[]> (str.length ()); std::copy (std::begin (str), std::end (str), ptr.get ()); return std::unique_ptr<CharType[]>{ptr.release ()}; } }; template <> struct string_maker<char const *> { char const * operator() (std::string const & str) const noexcept { return str.data (); } }; template <typename StringType> class SStringViewInit : public ::testing::Test {}; using SStringViewInitTypes = ::testing::Types<string_maker<std::shared_ptr<char>>, string_maker<std::shared_ptr<char const>>, string_maker<std::unique_ptr<char[]>>, string_maker<std::unique_ptr<char const[]>>, string_maker<char const *>>; // The pstore APIs that return shared_ptr<> and unique_ptr<> sstring_views is named // make_shared_sstring_view() and make_unique_sstring_view() respectively to try to avoid // confusion about the ownership of the memory. However, here, I'd like all of the functions to // have the same name. template <typename ValueType> inline pstore::sstring_view<std::shared_ptr<ValueType>> make_sstring_view (std::shared_ptr<ValueType> const & ptr, std::size_t length) { return pstore::make_shared_sstring_view (ptr, length); } template <typename ValueType> inline pstore::sstring_view<std::unique_ptr<ValueType>> make_sstring_view (std::unique_ptr<ValueType> ptr, std::size_t length) { return pstore::make_unique_sstring_view (std::move (ptr), length); } } // end anonymous namespace #ifdef PSTORE_IS_INSIDE_LLVM TYPED_TEST_CASE (SStringViewInit, SStringViewInitTypes); #else TYPED_TEST_SUITE (SStringViewInit, SStringViewInitTypes, ); #endif // PSTORE_IS_INSIDE_LLVM TYPED_TEST (SStringViewInit, Empty) { using namespace pstore; TypeParam t; std::string const src; auto ptr = t (src); auto sv = make_sstring_view (std::move (ptr), src.length ()); EXPECT_EQ (sv.size (), 0U); EXPECT_EQ (sv.length (), 0U); EXPECT_EQ (sv.max_size (), std::numeric_limits<std::size_t>::max ()); EXPECT_TRUE (sv.empty ()); EXPECT_EQ (std::distance (std::begin (sv), std::end (sv)), 0); } TYPED_TEST (SStringViewInit, Short) { using namespace pstore; TypeParam t; std::string const src{"hello"}; auto ptr = t (src); auto sv = make_sstring_view (std::move (ptr), src.length ()); EXPECT_EQ (sv.size (), 5U); EXPECT_EQ (sv.length (), 5U); EXPECT_EQ (sv.max_size (), std::numeric_limits<std::size_t>::max ()); EXPECT_FALSE (sv.empty ()); EXPECT_EQ (std::distance (std::begin (sv), std::end (sv)), 5); } TEST (SStringView, FromSpan) { using namespace pstore; std::array<char, 5> const src{{'a', 'r', 'r', 'a', 'y'}}; auto sv = make_sstring_view (gsl::make_span (src)); EXPECT_THAT (sv, ::testing::ElementsAreArray (src)); } TEST (SStringView, OperatorIndex) { std::string const src{"ABCDE"}; pstore::sstring_view<char const *> sv = pstore::make_sstring_view (src.data (), src.length ()); ASSERT_EQ (sv.length (), src.length ()); EXPECT_FALSE (sv.empty ()); EXPECT_EQ (sv[0], 'A'); EXPECT_EQ (sv[1], 'B'); EXPECT_EQ (sv[4], 'E'); } TEST (SStringView, At) { std::string const src{"ABCDE"}; pstore::sstring_view<char const *> sv = pstore::make_sstring_view (src.data (), src.length ()); ASSERT_EQ (sv.length (), src.length ()); EXPECT_FALSE (sv.empty ()); EXPECT_EQ (sv.at (0), 'A'); EXPECT_EQ (sv.at (1), 'B'); EXPECT_EQ (sv.at (4), 'E'); #ifdef PSTORE_EXCEPTIONS EXPECT_THROW (sv.at (5), std::out_of_range); #endif // PSTORE_EXCEPTIONS } TEST (SStringView, Back) { std::string const src{"ABCDE"}; auto const length = src.length (); std::shared_ptr<char> ptr = new_shared (src); pstore::sstring_view<std::shared_ptr<char>> sv = pstore::make_shared_sstring_view (ptr, length); ASSERT_EQ (sv.length (), length); EXPECT_EQ (sv.back (), src[length - 1]); EXPECT_EQ (&sv.back (), sv.data () + length - 1U); } TEST (SStringView, Data) { std::string const src{"ABCDE"}; auto const length = src.length (); std::shared_ptr<char> ptr = new_shared (src); pstore::sstring_view<std::shared_ptr<char>> sv = pstore::make_shared_sstring_view (ptr, length); ASSERT_EQ (sv.length (), length); EXPECT_EQ (sv.data (), ptr.get ()); } TEST (SStringView, Front) { std::string const src{"ABCDE"}; auto const length = src.length (); std::shared_ptr<char> ptr = new_shared (src); pstore::sstring_view<std::shared_ptr<char>> sv = pstore::make_shared_sstring_view (ptr, length); ASSERT_EQ (sv.length (), length); EXPECT_EQ (sv.front (), src[0]); EXPECT_EQ (&sv.front (), sv.data ()); } TEST (SStringView, Index) { std::string const src{"ABCDE"}; auto const length = src.length (); std::shared_ptr<char> ptr = new_shared (src); pstore::sstring_view<std::shared_ptr<char>> sv = pstore::make_shared_sstring_view (ptr, length); EXPECT_EQ (sv[0], src[0]); EXPECT_EQ (&sv[0], ptr.get () + 0); EXPECT_EQ (sv[1], src[1]); EXPECT_EQ (&sv[1], ptr.get () + 1); EXPECT_EQ (sv[4], src[4]); EXPECT_EQ (&sv[4], ptr.get () + 4); } TEST (SStringView, RBeginEmpty) { std::string const src; using sv_type = pstore::sstring_view<char const *>; sv_type sv = pstore::make_sstring_view (src.data (), src.length ()); sv_type const & csv = sv; sv_type::reverse_iterator rbegin = sv.rbegin (); sv_type::const_reverse_iterator const_rbegin1 = csv.rbegin (); sv_type::const_reverse_iterator const_rbegin2 = sv.crbegin (); EXPECT_EQ (rbegin, const_rbegin1); EXPECT_EQ (rbegin, const_rbegin2); EXPECT_EQ (const_rbegin1, const_rbegin2); } TEST (SStringView, RBegin) { std::string const src{"abc"}; using sv_type = pstore::sstring_view<char const *>; sv_type sv = pstore::make_sstring_view (src.data (), src.length ()); sv_type const & csv = sv; sv_type::reverse_iterator rbegin = sv.rbegin (); sv_type::const_reverse_iterator const_begin1 = csv.rbegin (); sv_type::const_reverse_iterator const_begin2 = sv.crbegin (); std::size_t const last = sv.size () - 1; EXPECT_EQ (*rbegin, sv[last]); EXPECT_EQ (&*rbegin, &sv[last]); EXPECT_EQ (*const_begin1, sv[last]); EXPECT_EQ (&*const_begin1, &sv[last]); EXPECT_EQ (*const_begin2, sv[last]); EXPECT_EQ (&*const_begin2, &sv[last]); EXPECT_EQ (rbegin, const_begin1); EXPECT_EQ (rbegin, const_begin2); EXPECT_EQ (const_begin1, const_begin2); } TEST (SStringView, REndEmpty) { std::string const src{""}; using sv_type = pstore::sstring_view<char const *>; sv_type sv = pstore::make_sstring_view (src.data (), src.length ()); sv_type const & csv = sv; sv_type::reverse_iterator rend = sv.rend (); sv_type::const_reverse_iterator const_rend1 = csv.rend (); sv_type::const_reverse_iterator const_rend2 = sv.crend (); EXPECT_EQ (rend, sv.rbegin ()); EXPECT_EQ (const_rend1, csv.rbegin ()); EXPECT_EQ (const_rend2, sv.rbegin ()); EXPECT_EQ (rend - sv.rbegin (), 0); EXPECT_EQ (const_rend1 - csv.rbegin (), 0); EXPECT_EQ (const_rend2 - sv.crbegin (), 0); EXPECT_EQ (rend, const_rend1); EXPECT_EQ (rend, const_rend2); EXPECT_EQ (const_rend1, const_rend2); } TEST (SStringView, REnd) { std::string const src{"abc"}; using sv_type = pstore::sstring_view<char const *>; sv_type sv = pstore::make_sstring_view (src.data (), src.length ()); sv_type const & csv = sv; sv_type::reverse_iterator rend = sv.rend (); sv_type::const_reverse_iterator const_rend1 = csv.rend (); sv_type::const_reverse_iterator const_rend2 = sv.crend (); EXPECT_NE (rend, sv.rbegin ()); EXPECT_NE (const_rend1, csv.rbegin ()); EXPECT_NE (const_rend2, sv.rbegin ()); EXPECT_EQ (rend - sv.rbegin (), 3); EXPECT_EQ (const_rend1 - csv.rbegin (), 3); EXPECT_EQ (const_rend2 - sv.crbegin (), 3); EXPECT_EQ (rend, const_rend1); EXPECT_EQ (rend, const_rend2); EXPECT_EQ (const_rend1, const_rend2); } TEST (SStringView, Clear) { std::string const empty_str; pstore::sstring_view<char const *> empty = pstore::make_sstring_view (empty_str.data (), empty_str.length ()); { std::string const abc_str{"abc"}; pstore::sstring_view<char const *> sv1 = pstore::make_sstring_view (abc_str.data (), abc_str.length ()); sv1.clear (); EXPECT_EQ (sv1.size (), 0U); EXPECT_EQ (sv1, empty); } { pstore::sstring_view<char const *> sv2 = pstore::make_sstring_view (empty_str.data (), empty_str.length ()); sv2.clear (); EXPECT_EQ (sv2.size (), 0U); EXPECT_EQ (sv2, empty); } } TEST (SStringView, FindChar) { std::string const src{"abc"}; using sv_type = pstore::sstring_view<char const *>; sv_type sv = pstore::make_sstring_view (src.data (), src.length ()); EXPECT_EQ (sv.find ('a'), 0U); EXPECT_EQ (sv.find ('c'), 2U); EXPECT_EQ (sv.find ('d'), sv_type::npos); EXPECT_EQ (sv.find ('c', 1U), 2U); EXPECT_EQ (sv.find ('c', 3U), sv_type::npos); } TEST (SStringView, Substr) { std::string const src{"abc"}; using sv_type = pstore::sstring_view<char const *>; sv_type sv = pstore::make_sstring_view (src.data (), src.length ()); EXPECT_EQ (sv.substr (0U, 1U), "a"); EXPECT_EQ (sv.substr (0U, 4U), "abc"); EXPECT_EQ (sv.substr (1U, 1U), "b"); EXPECT_EQ (sv.substr (3U, 1U), ""); } TEST (SStringView, OperatorWrite) { auto check = [] (std::string const & str) { auto view = pstore::make_sstring_view (str.data (), str.length ()); std::ostringstream stream; stream << view; EXPECT_EQ (stream.str (), str); }; check (""); check ("abcdef"); check ("hello world"); } namespace { template <typename StringType> class SStringViewRelational : public ::testing::Test {}; class sstringview_maker { public: explicit sstringview_maker (char const * s) : view_ (pstore::make_sstring_view (s, std::strlen (s))) {} operator pstore::sstring_view<char const *> () const noexcept { return view_; } private: pstore::sstring_view<char const *> view_; }; using StringTypes = ::testing::Types<sstringview_maker, sstringview_maker const, char const *>; } // end anonymous namespace namespace pstore { template <> struct string_traits<sstringview_maker> { static std::size_t length (sstring_view<char const *> const & s) noexcept { return string_traits<sstring_view<char const *>>::length (s); } static char const * data (sstring_view<char const *> const & s) noexcept { return string_traits<sstring_view<char const *>>::data (s); } }; } // end namespace pstore #ifdef PSTORE_IS_INSIDE_LLVM TYPED_TEST_CASE (SStringViewRelational, StringTypes); #else TYPED_TEST_SUITE (SStringViewRelational, StringTypes, ); #endif TYPED_TEST (SStringViewRelational, Eq) { #define EQ(lhs, rhs, x) \ do { \ auto const lhs_view = pstore::make_sstring_view ((lhs), std::strlen (lhs)); \ EXPECT_EQ (lhs_view == (rhs), (x)); \ EXPECT_EQ ((rhs) == lhs_view, (x)); \ } while (0) EQ ("", TypeParam (""), true); EQ ("", TypeParam ("abcde"), false); EQ ("", TypeParam ("abcdefghij"), false); EQ ("", TypeParam ("abcdefghijklmnopqrst"), false); EQ ("abcde", TypeParam (""), false); EQ ("abcde", TypeParam ("abcde"), true); EQ ("abcde", TypeParam ("abcdefghij"), false); EQ ("abcde", TypeParam ("abcdefghijklmnopqrst"), false); EQ ("abcdefghij", TypeParam (""), false); EQ ("abcdefghij", TypeParam ("abcde"), false); EQ ("abcdefghij", TypeParam ("abcdefghij"), true); EQ ("abcdefghij", TypeParam ("abcdefghijklmnopqrst"), false); EQ ("abcdefghijklmnopqrst", TypeParam (""), false); EQ ("abcdefghijklmnopqrst", TypeParam ("abcde"), false); EQ ("abcdefghijklmnopqrst", TypeParam ("abcdefghij"), false); EQ ("abcdefghijklmnopqrst", TypeParam ("abcdefghijklmnopqrst"), true); #undef EQ } TYPED_TEST (SStringViewRelational, Ne) { #define NE(lhs, rhs, x) \ do { \ auto const lhs_view = pstore::make_sstring_view ((lhs), std::strlen (lhs)); \ EXPECT_EQ (lhs_view != (rhs), (x)); \ EXPECT_EQ ((rhs) != lhs_view, (x)); \ } while (0) NE ("", TypeParam (""), false); NE ("", TypeParam ("abcde"), true); NE ("", TypeParam ("abcdefghij"), true); NE ("", TypeParam ("abcdefghijklmnopqrst"), true); NE ("abcde", TypeParam (""), true); NE ("abcde", TypeParam ("abcde"), false); NE ("abcde", TypeParam ("abcdefghij"), true); NE ("abcde", TypeParam ("abcdefghijklmnopqrst"), true); NE ("abcdefghij", TypeParam (""), true); NE ("abcdefghij", TypeParam ("abcde"), true); NE ("abcdefghij", TypeParam ("abcdefghij"), false); NE ("abcdefghij", TypeParam ("abcdefghijklmnopqrst"), true); NE ("abcdefghijklmnopqrst", TypeParam (""), true); NE ("abcdefghijklmnopqrst", TypeParam ("abcde"), true); NE ("abcdefghijklmnopqrst", TypeParam ("abcdefghij"), true); NE ("abcdefghijklmnopqrst", TypeParam ("abcdefghijklmnopqrst"), false); #undef NE } TYPED_TEST (SStringViewRelational, Ge) { #define GE(lhs, rhs, x, y) \ do { \ auto const lhs_view = pstore::make_sstring_view ((lhs), std::strlen (lhs)); \ EXPECT_EQ (lhs_view >= (rhs), (x)); \ EXPECT_EQ ((rhs) >= lhs_view, (y)); \ } while (0) GE ("", TypeParam (""), true, true); GE ("", TypeParam ("abcde"), false, true); GE ("", TypeParam ("abcdefghij"), false, true); GE ("", TypeParam ("abcdefghijklmnopqrst"), false, true); GE ("abcde", TypeParam (""), true, false); GE ("abcde", TypeParam ("abcde"), true, true); GE ("abcde", TypeParam ("abcdefghij"), false, true); GE ("abcde", TypeParam ("abcdefghijklmnopqrst"), false, true); GE ("abcdefghij", TypeParam (""), true, false); GE ("abcdefghij", TypeParam ("abcde"), true, false); GE ("abcdefghij", TypeParam ("abcdefghij"), true, true); GE ("abcdefghij", TypeParam ("abcdefghijklmnopqrst"), false, true); GE ("abcdefghijklmnopqrst", TypeParam (""), true, false); GE ("abcdefghijklmnopqrst", TypeParam ("abcde"), true, false); GE ("abcdefghijklmnopqrst", TypeParam ("abcdefghij"), true, false); GE ("abcdefghijklmnopqrst", TypeParam ("abcdefghijklmnopqrst"), true, true); #undef GE } TYPED_TEST (SStringViewRelational, Gt) { #define GT(lhs, rhs, x, y) \ do { \ auto const lhs_view = pstore::make_sstring_view ((lhs), std::strlen (lhs)); \ EXPECT_EQ (lhs_view > (rhs), (x)); \ EXPECT_EQ ((rhs) > lhs_view, (y)); \ } while (0) GT ("", TypeParam (""), false, false); GT ("", TypeParam ("abcde"), false, true); GT ("", TypeParam ("abcdefghij"), false, true); GT ("", TypeParam ("abcdefghijklmnopqrst"), false, true); GT ("abcde", TypeParam (""), true, false); GT ("abcde", TypeParam ("abcde"), false, false); GT ("abcde", TypeParam ("abcdefghij"), false, true); GT ("abcde", TypeParam ("abcdefghijklmnopqrst"), false, true); GT ("abcdefghij", TypeParam (""), true, false); GT ("abcdefghij", TypeParam ("abcde"), true, false); GT ("abcdefghij", TypeParam ("abcdefghij"), false, false); GT ("abcdefghij", TypeParam ("abcdefghijklmnopqrst"), false, true); GT ("abcdefghijklmnopqrst", TypeParam (""), true, false); GT ("abcdefghijklmnopqrst", TypeParam ("abcde"), true, false); GT ("abcdefghijklmnopqrst", TypeParam ("abcdefghij"), true, false); GT ("abcdefghijklmnopqrst", TypeParam ("abcdefghijklmnopqrst"), false, false); #undef GT } TYPED_TEST (SStringViewRelational, Le) { #define LE(lhs, rhs, x, y) \ do { \ auto const lhs_view = pstore::make_sstring_view ((lhs), std::strlen (lhs)); \ EXPECT_EQ (lhs_view <= (rhs), bool{(x)}); \ EXPECT_EQ ((rhs) <= lhs_view, bool{(y)}); \ } while (0) LE ("", TypeParam (""), true, true); LE ("", TypeParam ("abcde"), true, false); LE ("", TypeParam ("abcdefghij"), true, false); LE ("", TypeParam ("abcdefghijklmnopqrst"), true, false); LE ("abcde", TypeParam (""), false, true); LE ("abcde", TypeParam ("abcde"), true, true); LE ("abcde", TypeParam ("abcdefghij"), true, false); LE ("abcde", TypeParam ("abcdefghijklmnopqrst"), true, false); LE ("abcdefghij", TypeParam (""), false, true); LE ("abcdefghij", TypeParam ("abcde"), false, true); LE ("abcdefghij", TypeParam ("abcdefghij"), true, true); LE ("abcdefghij", TypeParam ("abcdefghijklmnopqrst"), true, false); LE ("abcdefghijklmnopqrst", TypeParam (""), false, true); LE ("abcdefghijklmnopqrst", TypeParam ("abcde"), false, true); LE ("abcdefghijklmnopqrst", TypeParam ("abcdefghij"), false, true); LE ("abcdefghijklmnopqrst", TypeParam ("abcdefghijklmnopqrst"), true, true); #undef LE } TYPED_TEST (SStringViewRelational, Lt) { #define LT(lhs, rhs, x, y) \ do { \ auto const lhs_view = pstore::make_sstring_view ((lhs), std::strlen (lhs)); \ EXPECT_EQ ((lhs_view < rhs), bool{(x)}); \ EXPECT_EQ ((rhs < lhs_view), bool{(y)}); \ } while (0) LT ("", TypeParam (""), false, false); LT ("", TypeParam ("abcde"), true, false); LT ("", TypeParam ("abcdefghij"), true, false); LT ("", TypeParam ("abcdefghijklmnopqrst"), true, false); LT ("abcde", TypeParam (""), false, true); LT ("abcde", TypeParam ("abcde"), false, false); LT ("abcde", TypeParam ("abcdefghij"), true, false); LT ("abcde", TypeParam ("abcdefghijklmnopqrst"), true, false); LT ("abcdefghij", TypeParam (""), false, true); LT ("abcdefghij", TypeParam ("abcde"), false, true); LT ("abcdefghij", TypeParam ("abcdefghij"), false, false); LT ("abcdefghij", TypeParam ("abcdefghijklmnopqrst"), true, false); LT ("abcdefghijklmnopqrst", TypeParam (""), false, true); LT ("abcdefghijklmnopqrst", TypeParam ("abcde"), false, true); LT ("abcdefghijklmnopqrst", TypeParam ("abcdefghij"), false, true); LT ("abcdefghijklmnopqrst", TypeParam ("abcdefghijklmnopqrst"), false, false); #undef LE }
41.56391
100
0.566751
paulhuggett
f26c090c52e3139604be765557f6fe10cb2b2fd4
9,734
cpp
C++
ModulePlayer2.cpp
Alejandromo125/3DPhysicsProject
89976b0c6f28881c9eb4aac008c010b348cb4dbb
[ "MIT" ]
null
null
null
ModulePlayer2.cpp
Alejandromo125/3DPhysicsProject
89976b0c6f28881c9eb4aac008c010b348cb4dbb
[ "MIT" ]
null
null
null
ModulePlayer2.cpp
Alejandromo125/3DPhysicsProject
89976b0c6f28881c9eb4aac008c010b348cb4dbb
[ "MIT" ]
null
null
null
#include "Globals.h" #include "Application.h" #include "ModulePlayer.h" #include "Primitive.h" #include "PhysVehicle3D.h" #include "PhysBody3D.h" #include "ModuleCamera3D.h" #include "ModuleSceneIntro.h" #include "Timer.h" ModulePlayer2::ModulePlayer2(Application* app, bool start_enabled) : Module(app, start_enabled), vehicle(NULL) { turn = acceleration = brake = 0.0f; jump_coolddown.Start(); } ModulePlayer2::~ModulePlayer2() {} // Load assets bool ModulePlayer2::Start() { LOG("Loading player"); VehicleInfo car; // Car properties ---------------------------------------- car.chassis_size.Set(0.85, 2, 4.5); car.chassis2_size.Set(1.3, 2, 1.5); car.chassis3_size.Set(1, 1.4, 1.3); car.chassis4_size.Set(1.25, 1, 1); car.chassis10_size.Set(2.5, 0.4, 0.6); car.chassis_offset.Set(0, 1, 0); car.chassis2_offset.Set(0, 1.8, -0.2); car.chassis3_offset.Set(0, 0.7, 1.8); car.chassis4_offset.Set(0, 2.2, -2.4); car.chassis10_offset.Set(0, 2.1, 2.3); car.mass = 130.0f; car.suspensionStiffness = 26.10f; car.suspensionCompression = 1.42f; car.suspensionDamping = 2.35f; car.maxSuspensionTravelCm = 510.0f; car.frictionSlip = 100.5; car.maxSuspensionForce = 1000.0f; // Wheel properties --------------------------------------- float connection_height = 0.8f; float wheel_radius = 0.6f; float wheel_width = 0.5f; float suspensionRestLength = 0.8f; // Don't change anything below this line ------------------ float half_width = car.chassis_size.x * 0.65f; float half_length = car.chassis_size.z * 0.65f; vec3 direction(0, -1, 0); vec3 axis(-1, 0, 0); car.num_wheels = 4; car.wheels = new Wheel[4]; // FRONT-LEFT ------------------------ car.wheels[0].connection.Set(half_width - 0.6f * wheel_width, connection_height, half_length - wheel_radius); car.wheels[0].direction = direction; car.wheels[0].axis = axis; car.wheels[0].suspensionRestLength = suspensionRestLength; car.wheels[0].radius = wheel_radius; car.wheels[0].width = wheel_width; car.wheels[0].front = true; car.wheels[0].drive = true; car.wheels[0].brake = false; car.wheels[0].steering = true; // FRONT-RIGHT ------------------------ car.wheels[1].connection.Set(-half_width + 0.6f * wheel_width, connection_height, half_length - wheel_radius); car.wheels[1].direction = direction; car.wheels[1].axis = axis; car.wheels[1].suspensionRestLength = suspensionRestLength; car.wheels[1].radius = wheel_radius; car.wheels[1].width = wheel_width; car.wheels[1].front = true; car.wheels[1].drive = true; car.wheels[1].brake = false; car.wheels[1].steering = true; // REAR-LEFT ------------------------ car.wheels[2].connection.Set(half_width - 0.6f * wheel_width, connection_height, -half_length + wheel_radius); car.wheels[2].direction = direction; car.wheels[2].axis = axis; car.wheels[2].suspensionRestLength = suspensionRestLength; car.wheels[2].radius = wheel_radius; car.wheels[2].width = wheel_width; car.wheels[2].front = false; car.wheels[2].drive = false; car.wheels[2].brake = true; car.wheels[2].steering = false; // REAR-RIGHT ------------------------ car.wheels[3].connection.Set(-half_width + 0.6f * wheel_width, connection_height, -half_length + wheel_radius); car.wheels[3].direction = direction; car.wheels[3].axis = axis; car.wheels[3].suspensionRestLength = suspensionRestLength; car.wheels[3].radius = wheel_radius; car.wheels[3].width = wheel_width; car.wheels[3].front = false; car.wheels[3].drive = false; car.wheels[3].brake = true; car.wheels[3].steering = false; vehicle = App->physics->AddVehicle(car); vehicle->SetPos(4, 5, 0); //vehicle->collision_listeners.add(this); vehicle->collision_listeners.add(App->scene_intro); vehicle->vehicle->getRigidBody()->setUserPointer(vehicle); initialPosition = vehicle->vehicle->getChassisWorldTransform().getOrigin(); currentPlayerPosition = vehicle->vehicle->getChassisWorldTransform().getOrigin(); //App->physics->AddConstraintP2P(*decorBody->body, *vehicle->body, car.rear_chassis_offset, car.rear_chassis_offset); inDirt = false; return true; } // Unload assets bool ModulePlayer2::CleanUp() { LOG("Unloading player"); return true; } // Update: draw background update_status ModulePlayer2::Update(float dt) { if (App->scene_intro->vehicleIndex == 2) { turn = acceleration = brake = 0.0f; if ((winCondition == false && looseCondition == false && App->scene_intro->trueLooseCondition == false) && App->scene_intro->sceneBeginTimer > 220) { if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT && (vehicle->GetKmh() < 120)) { acceleration = MAX_ACCELERATION; } if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT && (vehicle->GetKmh() > -30)) { if (vehicle->GetKmh() > 10) { brake = BRAKE_POWER / 24; } else { if (vehicle->GetKmh() < -30) { acceleration = MAX_ACCELERATION * 5; } acceleration = -MAX_ACCELERATION * 5; } } if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT) { if (turn < TURN_DEGREES) turn += TURN_DEGREES; } if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT) { if (turn > -TURN_DEGREES) turn -= TURN_DEGREES; } if (App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_DOWN) { if ((jump_coolddown.Read() * 0.001) >= JUMP_COOLDOWN) { vehicle->Push(0.0f, JUMP_IMPULSE, 0.0f); jump_coolddown.Start(); } } } if (App->input->GetKey(SDL_SCANCODE_R) == KEY_DOWN) { App->scene_intro->lapSensorActivated = false; App->player->vehicle->SetPos(initialPosition.x(), initialPosition.y(), initialPosition.z()); mat4x4 tr; tr.rotate(0, vec3(0, 1, 0)); vehicle->vehicle->getRigidBody()->setAngularVelocity(btVector3(0, 0, 0)); vehicle->SetTransform(&tr); vehicle->SetLinearVelocity(0, 0, 0); } vehicle->ApplyEngineForce(acceleration); vehicle->Turn(turn); vehicle->Brake(brake); if (!App->input->GetKey(SDL_SCANCODE_UP) && !App->input->GetKey(SDL_SCANCODE_DOWN)) { vehicle->ApplyEngineForce(App->physics->DragForce(vehicle->GetKmh())); } vehicle->Render(); float jump_cooldown_calc = 0.0f; jump_cooldown_calc = JUMP_COOLDOWN - jump_coolddown.Read() * 0.001f; if (jump_cooldown_calc < 0) jump_cooldown_calc = 0; int tiemer_milisec_read = 0; //tiemer_milisec_read = game_timer.Read() - chickens_taken * 2000; if (tiemer_milisec_read <= 0) { tiemer_milisec_read = 0; } if (winCondition == false || looseCondition == false)delay++; if ((delay % 60) == 0 && winCondition == false) { seconds++; } if (seconds == 60 && winCondition == false) { seconds = 0; minutes++; } if (winCondition == true || looseCondition == true) { seconds = seconds; minutes = minutes; } if (App->input->GetKey(SDL_SCANCODE_P) == KEY_DOWN) { winCondition = true; } if (lap1 == true && lapDone == true) { lastSeconds = seconds; lastMinutes = minutes; lap2 = true; lapDone = false; lap1 = false; } if (lap2 == true && lapDone == true) { lastSeconds = seconds; lastMinutes = minutes; lap3 = true; lapDone = false; lap2 = false; } if (lap3 == true && lapDone == true) { lastSeconds = seconds; lastMinutes = minutes; lap4 = true; lapDone = false; lap3 = false; } if (lap4 == true && lapDone == true) { lastSeconds = seconds; lastMinutes = minutes; winCondition = true; lapDone = false; } if (inDirt == true) { if (vehicle->GetKmh() > 50) { vehicle->ApplyEngineForce(App->physics->DragForce(vehicle->GetKmh() + 400.0f)); } } if (inDirt == false) { if (vehicle->GetKmh() > 120) { vehicle->ApplyEngineForce(App->physics->DragForce(vehicle->GetKmh())); } } //AIR CONTROL btVector3 PositionInTheAir; PositionInTheAir = vehicle->vehicle->getChassisWorldTransform().getOrigin(); if (PositionInTheAir.getY() > 1) { Euler angles = vehicle->GetEulerAngles(vehicle->vehicle->getChassisWorldTransform().getRotation()); if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT) { angles.yaw -= (DEGTORAD * 4); btQuaternion q; q.setEulerZYX(btScalar(angles.yaw), btScalar(angles.pitch), btScalar(angles.roll)); vehicle->SetRotation(q); } else if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT) { angles.yaw += (DEGTORAD * 4); btQuaternion q; q.setEulerZYX(btScalar(angles.yaw), btScalar(angles.pitch), btScalar(angles.roll)); vehicle->SetRotation(q); } } else if (PositionInTheAir.getY() < -2) { App->scene_intro->lapSensorActivated = false; App->player->vehicle->SetPos(initialPosition.x(), initialPosition.y(), initialPosition.z()); mat4x4 tr; tr.rotate(0, vec3(0, 1, 0)); vehicle->vehicle->getRigidBody()->setAngularVelocity(btVector3(0, 0, 0)); vehicle->SetTransform(&tr); vehicle->SetLinearVelocity(0, 0, 0); } else { vehicle->SetRotation({0, 0,0,1}); } char title[80]; if (minutes == 4 && seconds == 0) { looseCondition == true; sprintf(title, "You have lost the race"); } if (winCondition == false) { sprintf_s(title, "%.1f Km/h Your Current Time: %d m %d s Your Last Time: %d m %d s", vehicle->GetKmh(), minutes, seconds, lastMinutes, lastSeconds); } if (winCondition == true) { sprintf_s(title, "Your Final Time: %d m %d s", minutes, seconds); } if (winCondition == true) { if (vehicle->GetKmh() > 0) { vehicle->ApplyEngineForce(App->physics->DragForce(vehicle->GetKmh() + 1000.0f)); } } App->window->SetTitle(title); currentPlayerPosition = vehicle->vehicle->getChassisWorldTransform().getOrigin(); } return UPDATE_CONTINUE; }
25.548556
162
0.654818
Alejandromo125
f26ecc78689c1db3b28d14bb7668b1973dcc0f55
12,120
cpp
C++
3_Utilities/stream/pezy.cpp
denjiry/samples
1b97f83cd9077777595b0435c515d0a17701924b
[ "BSD-3-Clause" ]
null
null
null
3_Utilities/stream/pezy.cpp
denjiry/samples
1b97f83cd9077777595b0435c515d0a17701924b
[ "BSD-3-Clause" ]
null
null
null
3_Utilities/stream/pezy.cpp
denjiry/samples
1b97f83cd9077777595b0435c515d0a17701924b
[ "BSD-3-Clause" ]
2
2019-04-13T05:04:32.000Z
2019-04-15T07:59:36.000Z
/*! * @author PEZY Computing, K.K. * @date 2019 * @copyright BSD-3-Clause */ #include "pezy.hpp" #include <chrono> #include <fstream> #include <iostream> #include <sstream> #include <stdexcept> namespace { inline size_t getFileSize(std::ifstream& file) { file.seekg(0, std::ios::end); size_t ret = file.tellg(); file.seekg(0, std::ios::beg); return ret; } inline void loadFile(std::ifstream& file, std::vector<char>& d, size_t size) { d.resize(size); file.read(reinterpret_cast<char*>(d.data()), size); } cl::Program createProgram(cl::Context& context, const std::vector<cl::Device>& devices, const std::string& filename) { std::ifstream file; file.open(filename, std::ios::in | std::ios::binary); if (file.fail()) { throw "can not open kernel file"; } size_t filesize = getFileSize(file); std::vector<char> binary_data; loadFile(file, binary_data, filesize); cl::Program::Binaries binaries; binaries.push_back(std::make_pair(&binary_data[0], filesize)); return cl::Program(context, devices, binaries, nullptr, nullptr); } cl::Program createProgram(cl::Context& context, const cl::Device& device, const std::string& filename) { std::vector<cl::Device> devices { device }; return createProgram(context, devices, filename); } double empty_kernel_execute_time = 0; void checkSTREAMresults(const double* a, const double* b, const double* c, size_t STREAM_ARRAY_SIZE, size_t NTIMES) { using STREAM_TYPE = double; STREAM_TYPE aj, bj, cj, scalar; STREAM_TYPE aSumErr, bSumErr, cSumErr; STREAM_TYPE aAvgErr, bAvgErr, cAvgErr; double epsilon; int ierr, err; /* reproduce initialization */ aj = 1.0; bj = 2.0; cj = 0.0; /* a[] is modified during timing check */ aj = 2.0E0 * aj; /* now execute timing loop */ scalar = 3.0; for (size_t k = 0; k < NTIMES; k++) { cj = aj; bj = scalar * cj; cj = aj + bj; aj = bj + scalar * cj; } /* accumulate deltas between observed and expected results */ aSumErr = 0.0; bSumErr = 0.0; cSumErr = 0.0; for (size_t j = 0; j < STREAM_ARRAY_SIZE; j++) { aSumErr += abs(a[j] - aj); bSumErr += abs(b[j] - bj); cSumErr += abs(c[j] - cj); // if (j == 417) printf("Index 417: c[j]: %f, cj: %f\n",c[j],cj); // MCCALPIN } aAvgErr = aSumErr / (STREAM_TYPE)STREAM_ARRAY_SIZE; bAvgErr = bSumErr / (STREAM_TYPE)STREAM_ARRAY_SIZE; cAvgErr = cSumErr / (STREAM_TYPE)STREAM_ARRAY_SIZE; if (sizeof(STREAM_TYPE) == 4) { epsilon = 1.e-6; } else if (sizeof(STREAM_TYPE) == 8) { epsilon = 1.e-13; } else { printf("WEIRD: sizeof(STREAM_TYPE) = %lu\n", sizeof(STREAM_TYPE)); epsilon = 1.e-6; } err = 0; if (abs(aAvgErr / aj) > epsilon) { err++; printf("Failed Validation on array a[], AvgRelAbsErr > epsilon (%e)\n", epsilon); printf(" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n", aj, aAvgErr, abs(aAvgErr) / aj); ierr = 0; for (size_t j = 0; j < STREAM_ARRAY_SIZE; j++) { if (abs(a[j] / aj - 1.0) > epsilon) { ierr++; #ifdef VERBOSE if (ierr < 10) { printf(" array a: index: %ld, expected: %e, observed: %e, relative error: %e\n", j, aj, a[j], abs((aj - a[j]) / aAvgErr)); } #endif } } printf(" For array a[], %d errors were found.\n", ierr); } if (abs(bAvgErr / bj) > epsilon) { err++; printf("Failed Validation on array b[], AvgRelAbsErr > epsilon (%e)\n", epsilon); printf(" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n", bj, bAvgErr, abs(bAvgErr) / bj); printf(" AvgRelAbsErr > Epsilon (%e)\n", epsilon); ierr = 0; for (size_t j = 0; j < STREAM_ARRAY_SIZE; j++) { if (abs(b[j] / bj - 1.0) > epsilon) { ierr++; #ifdef VERBOSE if (ierr < 10) { printf(" array b: index: %ld, expected: %e, observed: %e, relative error: %e\n", j, bj, b[j], abs((bj - b[j]) / bAvgErr)); } #endif } } printf(" For array b[], %d errors were found.\n", ierr); } if (abs(cAvgErr / cj) > epsilon) { err++; printf("Failed Validation on array c[], AvgRelAbsErr > epsilon (%e)\n", epsilon); printf(" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n", cj, cAvgErr, abs(cAvgErr) / cj); printf(" AvgRelAbsErr > Epsilon (%e)\n", epsilon); ierr = 0; for (size_t j = 0; j < STREAM_ARRAY_SIZE; j++) { if (abs(c[j] / cj - 1.0) > epsilon) { ierr++; #ifdef VERBOSE if (ierr < 10) { printf(" array c: index: %ld, expected: %e, observed: %e, relative error: %e\n", j, cj, c[j], abs((cj - c[j]) / cAvgErr)); } #endif } } printf(" For array c[], %d errors were found.\n", ierr); } if (err == 0) { printf("Solution Validates: avg error less than %e on all three arrays\n", epsilon); } #ifdef VERBOSE printf("Results Validation Verbose Results: \n"); printf(" Expected a(1), b(1), c(1): %f %f %f \n", aj, bj, cj); printf(" Observed a(1), b(1), c(1): %f %f %f \n", a[1], b[1], c[1]); printf(" Rel Errors on a, b, c: %e %e %e \n", abs(aAvgErr / aj), abs(bAvgErr / bj), abs(cAvgErr / cj)); #endif } } pezy::pezy(size_t device_id) { init(device_id); } void pezy::init(size_t device_id) { try { // Get Platform std::vector<cl::Platform> platforms; cl::Platform::get(&platforms); const auto& Platform = platforms[0]; // Get devices std::vector<cl::Device> devices; Platform.getDevices(CL_DEVICE_TYPE_DEFAULT, &devices); if (device_id > devices.size()) { std::cerr << "Invalid device id. Use first device." << std::endl; device_id = 0; } const auto& device = devices[device_id]; context = cl::Context(device); queue = cl::CommandQueue(context, device, 0); auto program = createProgram(context, device, "kernel/kernel.pz"); kernels.push_back(cl::Kernel(program, "Empty")); kernels.push_back(cl::Kernel(program, "Copy")); kernels.push_back(cl::Kernel(program, "Scale")); kernels.push_back(cl::Kernel(program, "Add")); kernels.push_back(cl::Kernel(program, "Triad")); typedef CL_API_ENTRY pzcl_int(CL_API_CALL * pfnPezyExtSetCacheWriteBuffer)(pzcl_context context, size_t index, bool enable); pfnPezyExtSetCacheWriteBuffer clExtSetCacheWriteBuffer = (pfnPezyExtSetCacheWriteBuffer)clGetExtensionFunctionAddress("pezy_set_cache_writebuffer"); if (!clExtSetCacheWriteBuffer) { throw cl::Error(-1, "clGetExtensionFunctionAddress: Can not get pezy_set_cache_writebuffer"); } if ((clExtSetCacheWriteBuffer(context(), 0, CL_TRUE)) != CL_SUCCESS) { throw cl::Error(-1, "clExtSetCacheWriteBuffer failed"); } // Get global work size. // sc1-64: 8192 (1024 PEs * 8 threads) // sc2 : 15782 (1984 PEs * 8 threads) { std::string device_name; device.getInfo(CL_DEVICE_NAME, &device_name); size_t global_work_size_[3] = { 0 }; device.getInfo(CL_DEVICE_MAX_WORK_ITEM_SIZES, &global_work_size_); global_work_size = global_work_size_[0]; if (device_name.find("PEZY-SC2") != std::string::npos) { global_work_size = std::min(global_work_size, (size_t)15872); } std::cout << "Use device : " << device_name << std::endl; std::cout << "workitem : " << global_work_size << std::endl; } } catch (const cl::Error& e) { std::stringstream msg; msg << "CL Error : " << e.what() << " " << e.err(); throw std::runtime_error(msg.str()); } } std::vector<std::vector<double>> pezy::run(size_t STREAM_ARRAY_SIZE, size_t NTIMES, size_t OFFSET) { std::vector<std::vector<double>> times(NTIMES); for (auto& t : times) { t.resize(4); } // create buffer size_t allocate_num = STREAM_ARRAY_SIZE + OFFSET; double* h_a = new double[allocate_num]; double* h_b = new double[allocate_num]; double* h_c = new double[allocate_num]; std::fill(h_a, h_a + allocate_num, 1.0); std::fill(h_b, h_b + allocate_num, 2.0); std::fill(h_c, h_c + allocate_num, 0.0); for (size_t i = 0; i < allocate_num; ++i) { h_a[i] *= 2.0; } double scalar = 3.0; try { // empty kernel run for (size_t i = 0; i < NTIMES; ++i) { empty_kernel_execute_time += Empty(); } empty_kernel_execute_time /= static_cast<double>(NTIMES); // create device buffer & write auto d_a = cl::Buffer(context, CL_MEM_READ_WRITE, sizeof(double) * allocate_num); auto d_b = cl::Buffer(context, CL_MEM_READ_WRITE, sizeof(double) * allocate_num); auto d_c = cl::Buffer(context, CL_MEM_READ_WRITE, sizeof(double) * allocate_num); queue.enqueueWriteBuffer(d_a, true, 0, sizeof(double) * allocate_num, h_a); queue.enqueueWriteBuffer(d_b, true, 0, sizeof(double) * allocate_num, h_b); queue.enqueueWriteBuffer(d_c, true, 0, sizeof(double) * allocate_num, h_c); for (size_t i = 0; i < NTIMES; ++i) { times[i][0] = Copy(d_c, d_a, STREAM_ARRAY_SIZE); times[i][1] = Scale(d_b, d_c, scalar, STREAM_ARRAY_SIZE); times[i][2] = Add(d_c, d_a, d_b, STREAM_ARRAY_SIZE); times[i][3] = Triad(d_a, d_b, d_c, scalar, STREAM_ARRAY_SIZE); } queue.enqueueReadBuffer(d_a, true, 0, sizeof(double) * allocate_num, h_a); queue.enqueueReadBuffer(d_b, true, 0, sizeof(double) * allocate_num, h_b); queue.enqueueReadBuffer(d_c, true, 0, sizeof(double) * allocate_num, h_c); } catch (const cl::Error& e) { std::stringstream msg; msg << "CL Error : " << e.what() << " " << e.err(); throw std::runtime_error(msg.str()); } // verify checkSTREAMresults(h_a, h_b, h_c, STREAM_ARRAY_SIZE, NTIMES); delete[] h_a; delete[] h_b; delete[] h_c; return times; } double pezy::Kick(cl::Kernel& kernel) { auto start = std::chrono::high_resolution_clock::now(); cl::Event event; queue.enqueueNDRangeKernel(kernel, cl::NullRange, cl::NDRange(global_work_size), cl::NDRange(), nullptr, &event); event.wait(); auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double, std::milli> dur = (end - start); return dur.count() / 1000.0; } double pezy::Empty() { auto& kernel = kernels[0]; return Kick(kernel); } double pezy::Copy(cl::Buffer c, cl::Buffer a, size_t num) { auto& kernel = kernels[1]; kernel.setArg(0, c); kernel.setArg(1, a); kernel.setArg(2, num); return Kick(kernel); } double pezy::Scale(cl::Buffer b, cl::Buffer c, double scalar, size_t num) { auto& kernel = kernels[2]; kernel.setArg(0, b); kernel.setArg(1, c); kernel.setArg(2, scalar); kernel.setArg(3, num); return Kick(kernel); } double pezy::Add(cl::Buffer c, cl::Buffer a, cl::Buffer b, size_t num) { auto& kernel = kernels[3]; kernel.setArg(0, c); kernel.setArg(1, a); kernel.setArg(2, b); kernel.setArg(3, num); return Kick(kernel); } double pezy::Triad(cl::Buffer a, cl::Buffer b, cl::Buffer c, double scalar, size_t num) { auto& kernel = kernels[4]; kernel.setArg(0, a); kernel.setArg(1, b); kernel.setArg(2, c); kernel.setArg(3, scalar); kernel.setArg(4, num); return Kick(kernel); }
32.148541
156
0.572607
denjiry
f275977141ce0ab0a9da12f8f20b41b89411457c
730
cpp
C++
hdu/2109.cpp
bashell/oj
9471e32d735168148390d42029998187e0e04e2b
[ "MIT" ]
null
null
null
hdu/2109.cpp
bashell/oj
9471e32d735168148390d42029998187e0e04e2b
[ "MIT" ]
null
null
null
hdu/2109.cpp
bashell/oj
9471e32d735168148390d42029998187e0e04e2b
[ "MIT" ]
null
null
null
#include <cstdio> #include <algorithm> using namespace std; int china[101]; int japan[101]; int main() { //freopen("in.txt", "r", stdin); int n; while(scanf("%d", &n) && n) { for(int i = 0; i < n; ++i) scanf("%d", &china[i]); for(int i = 0; i < n; ++i) scanf("%d", &japan[i]); sort(china, china+n); sort(japan, japan+n); int score1 = 0, score2 = 0; for(int i = 0; i < n; ++i) { if(china[i] > japan[i]) score1 += 2; else if(china[i] < japan[i]) score2 += 2; else ++score1, ++score2; } printf("%d vs %d\n", score1, score2); } return 0; }
22.8125
45
0.419178
bashell
f276e5ae0dc07829c7d03206726169e309cd3e57
1,590
cpp
C++
test.cpp
yuanzhubi/mpsc_wait_free
5a1f966c228756dbed6f8ec4d3cdc63833d20540
[ "MIT" ]
2
2018-08-27T11:43:51.000Z
2019-03-28T08:41:31.000Z
test.cpp
yuanzhubi/mpsc_wait_free
5a1f966c228756dbed6f8ec4d3cdc63833d20540
[ "MIT" ]
null
null
null
test.cpp
yuanzhubi/mpsc_wait_free
5a1f966c228756dbed6f8ec4d3cdc63833d20540
[ "MIT" ]
null
null
null
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include "mpsc.h" #include <time.h> size_t produce_failed_count = 0; struct X { clock_t start; X(){ start = clock(); } ~X(){ char buf[32]; snprintf(buf, 32,"%f %f",(double)(clock()-start), double(produce_failed_count)); perror(buf); } }timer; __thread int gindex = 0; #define BUF_STRING2(x) #x #define BUF_STRING(x) BUF_STRING2(x) #define LOG_PATTERN "File: " __FILE__ ", line: " BUF_STRING(__LINE__) ", " bool produce(char* dest, unsigned int length){ snprintf(dest, length, LOG_PATTERN "|%d\r\n", gindex++); return true; } void consume(char* dest, unsigned int length){ printf(dest); } /* void consume(char* dest, unsigned int length){ write(1, dest, length); memset(dest, ' ', length); } */ mpsc_queue mpsc_er(1<<12, 18); void* producer(void*){ while(gindex < 1000000){ if(!mpsc_er.produce(produce, 64)){ ++produce_failed_count; } } return 0; } volatile bool bisexit = false; void* consumer(void*){ while(!bisexit){ mpsc_er.consume(consume); } return 0; } #include <pthread.h> int main(){ const int max_threads = 18; pthread_t ntid[max_threads + 1]; pthread_create(ntid, NULL, consumer, NULL); for(int i = 1; i<=max_threads;++i){ pthread_create(ntid + i, NULL, producer, NULL); } for(int i = 1; i<=max_threads;++i){ pthread_join(ntid[i], NULL); } bisexit = true; pthread_join(ntid[0], NULL); return 0; }
21.2
96
0.603145
yuanzhubi
f278783eae90475a9e5168c3ee0dd453cd94d86f
12,290
cpp
C++
Classes/Player.cpp
thiagofigcosta/The.COM-Game
653b7174767b6dc2351807a44c2c4ac67c7dc1d6
[ "MIT" ]
null
null
null
Classes/Player.cpp
thiagofigcosta/The.COM-Game
653b7174767b6dc2351807a44c2c4ac67c7dc1d6
[ "MIT" ]
null
null
null
Classes/Player.cpp
thiagofigcosta/The.COM-Game
653b7174767b6dc2351807a44c2c4ac67c7dc1d6
[ "MIT" ]
null
null
null
#include "Player.hpp" #include "GL.hpp" #include "Mechanics.hpp" #include "Enemy.hpp" #include "Bullet.hpp" #include "../Libs/Globals.h" #include "Blocks.hpp" Player::Player(float life,nTPoint spawn,nTPoint size,vector<vector<GLuint> > animations,bool isHuman) { this->pos=spawn; this->size=size; this->animations=animations; this->vSpeed=0; this->hSpeed=0; this->currentState=0; this->currentIndex=0; this->nextState=-1; if(life>3) life=3; if(life<1) life=1; this->life=life; this->defaultOrientation=1; this->isHuman=isHuman; this->damageState=false; this->sword=(int)life-1; this->atackDirection=Util::right; this->orientation=Util::right; this->GLlist=glGenLists(1); this->canJump=true; this->isVisible=true; this->swordPos=spawn; this->atacking=false; this->haveBulletSword=0; this->haveBulletSpec=0; this->canWalk=1; this->swordSize=Util::nTPointSet(30,12,1); this->canTp=false; this->superMan=false; this->god=false; Mechanics::players.push_back(this); Entity::players.push_back(this); self.push_back(this); selfIsPlayer.push_back(true); this->id=self.size()-1; }; Player::Player(const Player& orig) { } Player::~Player() { Player* pl; Enemy* en; for(int i=id+1;i<self.size();i++){ if(selfIsPlayer[i]){ pl=(Player*)self[i]; pl->id--; }else{ en=(Enemy*)self[i]; en->id--; } } self.erase(self.begin()+this->id); selfIsPlayer.erase(selfIsPlayer.begin()+this->id); for(int i=0;i<Mechanics::players.size();i++){ if(Mechanics::players[i]==this){ Mechanics::players.erase(Mechanics::players.begin()+i); break; } } for(int i=0;i<Entity::players.size();i++){ if(Entity::players[i]==this){ Entity::players.erase(Entity::players.begin()+i); break; } } } int Player::lives=3; int Player::ranged=64651; int Player::meleeProjectile=16165; int Player::melee=165165; float Player::imunityTime=900; float Player::swordBaseDamage=2; int Player::checkpoint=0; int Player::stage=0; int Player::defaultLife=3; float Player::coeficiente=0; float Player::globalCoeficiente=0; int Player::enemysKilled=0; int Player::powerUpsActiveted=0; nTPoint Player::defaultPSize=Util::nTPointSet(28,60,0); ostream& operator<<(ostream &strm, const Player &player){ Player *pl=(Player*)&player; if(Util::DEBUG) return strm <<"Player:["<<"Pos("<<"x:"<<pl->pos.x<<" y:"<<pl->pos.y<<"),"<<"Speed("<<"hSpeed:"<<pl->hSpeed<<" vSpeed:"<<pl->vSpeed<<"),"<<"]\n"; return strm; } void playerChangeDamageState(int id){ Player *pl; try{ pl=(Player*)Player::self[id]; pl->damageState=false; }catch(const std::exception& e){ cout<<"pCDS-catch error: "<<e.what()<<endl; } } void Player::stateControl(){ if(GL::getGameMs()>=timeToVunerability){ if((superMan&&!damageState)&&!god) al->stopSound(AL::getSoundByName("cafeSong")); damageState=false; superMan=false; } Entity::stateControl(); if(nextState!=6&&nextState!=7&&currentState!=6&&currentState!=7&&atacking){ if(atacking==Player::melee){ if(vSpeed!=0){//air if(atackDirection==Util::down) currentState=9; else if(atackDirection==Util::up) currentState=11; else currentState=10; }else{//ground if(atackDirection==Util::up) currentState=13; else currentState=12; } nextState=-1; currentIndex=0; }else{ if(!haveBulletSpec)currentIndex=0; if(vSpeed!=0){//air if(atackDirection==Util::down) currentState=14; else if(atackDirection==Util::up) currentState=16; else currentState=15; }else{//ground if(atackDirection==Util::up) currentState=18; else currentState=17; } nextState=-1; } } if(atacking) atack(atacking); Blocks *bl; vector <mapCollision> var; bool condition=false; nTPoint point; point=pos; point.y=pos.y+2; var=Map::checkCollision(point,size); for(int i=0; i<var.size(); i++){ if(var[i].blockRef>=Map::staticBlocks.size()&&var[i].blockRef>0){ bl=(Blocks*) Map::dynamicBlocks[var[i].blockRef-Map::staticBlocks.size()]; if(var[i].collision.firstObj){ if(bl->type>=376&&bl->type<=400) condition=true; if(bl->type==377||bl->type==379){ if(!god) life=0; } if(bl->type<0&&canTp){ Blocks* tp; for(int j=0;j<Map::dynamicBlocks.size();j++){ tp=(Blocks*)Map::dynamicBlocks[j]; if(tp->type==bl->type&&bl!=tp){ canTp=false; player->pos=tp->pos; al->playSoundByName("TP"); if(tp->type>-200) player->pos.y-=Blocks::defaultBlockSize.y*1.4; else player->pos.y-=15; player->pos.z=0.9; if(Map::currentMap.size()>23)Scenes::lookAt(player->pos); } } } } } } itsInTheWater=condition; if(itsInTheWater) al->playSoundByName("agua"); execAnimation(); } void Player::makeInvencible(float time){ sword=life-1; if(sword<0) sword=0; superMan=true; //glutTimerFunc(time,playerChangeDamageState,id); timeToVunerability=GL::getGameMs()+time; } void Player::spawn(nTPoint spawn,float life){ if(life>3) life=3; if(life<1) life=1; this->pos=spawn; this->vSpeed=0; this->hSpeed=0; this->currentState=8; this->nextState=0; this->life=life; this->sword=(int)life-1; this->defaultOrientation=1; this->damageState=false; this->superMan=false; this->atackDirection=Util::right; this->orientation=1; this->isVisible=true; this->reducing=false; this->swordPos=spawn; this->atacking=false; this->haveBulletSword=0; this->haveBulletSpec=0; this->canWalk=1; this->god=false; this->canTp=false; this->canJump=false; this->forceNormalForce=false; alReadyAtacked=false; enemysKilled=0; powerUpsActiveted=0; Scenes::lookAt(this->pos); } void Player::especificDraw(){ if(god){ al->playSoundByName("cafeSong"); life=5; sword=2; if(lives<3) lives=3; superMan=true; Entity::jumpSpeed=Entity::finalJumpSpeed*2.2; }else if(Entity::jumpSpeed!=Entity::finalJumpSpeed) Entity::jumpSpeed=Entity::finalJumpSpeed; Player::refreshCoeficiente(); char buffer[5]; snprintf(buffer,5,"%d",sword); string sID(buffer); if(atacking){ swordCollision.p0.z=1; swordCollision.p1.z=1; if(atackDirection==Util::up||atackDirection==Util::down) GL::drawTexture(swordCollision,GL::getColorByName("white"),GL::getTextureByName("Sword"+sID),2); else GL::drawTexture(swordCollision,GL::getColorByName("white"),GL::getTextureByName("Sword"+sID),1); } // if(fmod(GL::framesInGame,GL::getFPS())==0) // cout<<*player; } void Player::atack(int type){ if(type==Player::ranged){ canJump=true; atacking=false; float cof; if(Player::globalCoeficiente==0) cof=Player::coeficiente; else cof=Player::globalCoeficiente; Bullet *bu; nTPoint tmp=swordSize; tmp.x*=orientation; if(!haveBulletSpec&&(cof>=75||Scenes::freeGameMode)){ al->playSoundByName("SpecialAtk"); if(cof>=85||Scenes::freeGameMode){ bu=new Bullet(2,orientation*Bullet::baseSpeed,pos,tmp); }else{ bu=new Bullet(3,orientation*Bullet::baseSpeed,pos,tmp); } haveBulletSpec=true; } }else if(type==Player::meleeProjectile){ if(sword>1&&!haveBulletSword){ Bullet *bu; nTPoint tmp=swordSize; tmp.x*=orientation; bu=new Bullet(1,orientation*Bullet::baseSpeed,pos,tmp); haveBulletSword=true; } canWalk=true; atacking=false; alReadyAtacked=false; swordCollision=Util::getCollisionRectangle(Util::nTPointSet(0,0,0),swordSize); }else if(type==Player::melee){// int angle; if(orientation>0) swordPos.setPoint(pos.x+20,pos.y,1); else swordPos.setPoint(pos.x+(swordSize.x-10),pos.y,1); if(atackDirection==Util::right){ angle=0; }else if(atackDirection==Util::up){ angle=3; swordPos.setPoint(pos.x,pos.y,1); }else if(atackDirection==Util::left){ angle=2; }else if(atackDirection==Util::down){ if(canJump&&!itsInTheWater){ atacking=false; return; } angle=1; swordPos.setPoint(pos.x,pos.y,1); } canJump=false; canWalk=false; swordCollision=Util::getCollisionRectangle(swordPos,swordSize); swordCollision.p0=GL::rotatePoint(swordCollision.p0,player->pos,90*angle); swordCollision.p1=GL::rotatePoint(swordCollision.p1,player->pos,90*angle); swordCollision.p0.z=1; swordCollision.p1.z=1; if(atackDirection==Util::up){ swordCollision.p0.y-=swordSize.y*3; swordCollision.p1.y-=swordSize.y*3; }else if(atackDirection==Util::down){ swordCollision.p0.y+=swordSize.y*3; swordCollision.p1.y+=swordSize.y*3; } if(!alReadyAtacked){ int SS=rand()%6; char buffer[5]; snprintf(buffer,5,"%d",SS); string strS(buffer); al->playSoundByName("sword"+strS); alReadyAtacked=true; } Enemy *en; objCollision col; for(int i=0;i<Entity::enemys.size();i++){ en=(Enemy*)enemys[i]; col=Mechanics::getCollision(swordCollision,Util::getCollisionRectangle(en->pos,en->size)); if(col.firstObj){ en->applyDamage(swordBaseDamage*(sword+1)); if(atackDirection==Util::down) player->vSpeed=-Entity::jumpSpeed/2.3; else if(atackDirection==Util::right) player->move(Util::left,-Entity::walkSpeed*2/GL::getFPS()); else if(atackDirection==Util::left) player->move(Util::left,Entity::walkSpeed*2/GL::getFPS()); } } } } void Player::refreshCoeficiente(){ coeficiente=0; if(Scenes::freeGameMode) return; if(Map::nOfEnemys) coeficiente+=100*Player::enemysKilled/Map::nOfEnemys *3; if(Map::totalPowerUps) coeficiente+=100*Player::powerUpsActiveted/Map::totalPowerUps*2; if(GL::getGameMs()){ float temp=100000*Map::expetedTime/GL::getGameMs() *1; if(temp>100) temp=100; coeficiente+=temp; } coeficiente/=6; } void Player::refreshGlobalcoeficiente(){ refreshCoeficiente(); if(globalCoeficiente!=0){ globalCoeficiente+=coeficiente; globalCoeficiente/=2; }else{ globalCoeficiente=coeficiente; } coeficiente=0; }
31.272265
152
0.541823
thiagofigcosta
f279615f091ad90091fa5d3a87f44aabaa739bd1
2,588
cpp
C++
library/baselib/source/LogMessageManager.cpp
KOMMYHAP/Minigame
6bb0c826b33310b0930fa5193f55e538eec7ad88
[ "MIT" ]
null
null
null
library/baselib/source/LogMessageManager.cpp
KOMMYHAP/Minigame
6bb0c826b33310b0930fa5193f55e538eec7ad88
[ "MIT" ]
null
null
null
library/baselib/source/LogMessageManager.cpp
KOMMYHAP/Minigame
6bb0c826b33310b0930fa5193f55e538eec7ad88
[ "MIT" ]
null
null
null
#include "basic_defs.h" #include "LogMessageManager.h" #define _AMD64_ #include <processthreadsapi.h> #include <debugapi.h> #include <filesystem> #include <fstream> #include <iostream> #include <ctime> LogMessageManager::LogMessageManager() { namespace fs = std::filesystem; auto path = fs::current_path() / fs::path("minigame_log.txt"); /*if (fs::exists(path)) { fs::path to; for (size_t i = 0; i < 999999; ++i) { auto && name = path.stem().string() + "_" + std::to_string(i) + ".txt"; to = path.parent_path() / name; if (!fs::exists(to)) { break; } } if (fs::copy_file(path, to)) { fs::remove(path); } }*/ auto filename = path.string(); m_logFilename = filename; m_output = [filename](const string & message) { std::ofstream f(filename, std::ios_base::app | std::ios_base::out); assert(f.is_open()); if (f.is_open()) { f << message << std::endl; } }; } string LogMessageManager::GetMessagePrefix() const { string prefix; auto _id = GetCurrentThreadId(); auto id = std::to_string(static_cast<uint64_t>(_id)) + ": "; auto _time = std::time(nullptr); string time(50, 0); tm tm; auto err = localtime_s(&tm, &_time); if (!err) { auto bytes = std::strftime(time.data(), time.size() - 1, "[%T]: ", &tm); time.resize(bytes); } auto place = "[file: \"" + m_file + "\", line: " + std::to_string(m_line) + "] "; switch (m_messageType) { case Type::PLAIN: return time + ""; case Type::WARNING: return time + "WARNING: "; case Type::ERROR: return time + place + "ERROR: "; case Type::FATAL_ERROR: return time + id + place + "FATAL ERROR: "; default: return ""; } } LogMessageManager::~LogMessageManager() { } void LogMessageManager::PrepareMessage(Type messageType, size_t line, const string& file) { m_messageType = messageType; m_line = line; m_file = file; } void LogMessageManager::WriteMessage(const string& message) { if (m_isFirstMessage) { string time(250, 0); auto _time = std::time(nullptr); std::tm tm; localtime_s(&tm, &_time); auto bytes = std::strftime(time.data(), time.size(), "%c", &tm); time.resize(bytes); string prefix(25, '='); string header = prefix + " " + time + " " + prefix + "\n"; m_output(header); m_isFirstMessage = false; } auto && prefix = GetMessagePrefix(); if (m_output) { m_output(prefix + message); #ifdef _DEBUG auto t = prefix + message + "\n"; OutputDebugStringA(t.c_str()); #endif } }
20.539683
90
0.600464
KOMMYHAP
f27ccfa1b535d9d345fd932c705412b6330f4cfb
337
cpp
C++
sbookqt/myqfiledialog.cpp
hasandiwan/SBook5
a4bf61692c3b180ca5d0652e951ed1f82ea4cad7
[ "MIT" ]
1
2015-08-29T23:13:26.000Z
2015-08-29T23:13:26.000Z
sbookqt/myqfiledialog.cpp
hasandiwan/SBook5
a4bf61692c3b180ca5d0652e951ed1f82ea4cad7
[ "MIT" ]
4
2018-04-30T12:44:32.000Z
2019-09-27T21:12:21.000Z
sbookqt/myqfiledialog.cpp
hasandiwan/SBook5
a4bf61692c3b180ca5d0652e951ed1f82ea4cad7
[ "MIT" ]
4
2015-05-08T22:35:01.000Z
2020-10-05T18:48:49.000Z
#include "myqfiledialog.h" MyQFileDialog::MyQFileDialog( const QString& dirName, const QString& filter, QWidget *parent, const char *name, bool modal) { QFileDialog(dirName,filter,parent,name,true); } void MyQFileDialog::setFilter(const QString &filter) { QFileDialog::setFilter(filter); }
19.823529
53
0.673591
hasandiwan
f27db8c1608ff04c208c7649dcf094f57cb0291a
24,870
cc
C++
chrome/browser/chromeos/status/input_method_menu.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
1
2016-03-10T09:13:57.000Z
2016-03-10T09:13:57.000Z
chrome/browser/chromeos/status/input_method_menu.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
1
2022-03-13T08:39:05.000Z
2022-03-13T08:39:05.000Z
chrome/browser/chromeos/status/input_method_menu.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "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/chromeos/status/input_method_menu.h" #include <string> #include <vector> #include "base/string_split.h" #include "base/string_util.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/input_method/input_method_util.h" #include "chrome/browser/chromeos/language_preferences.h" #include "chrome/browser/chromeos/status/status_area_view_chromeos.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/pref_names.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/user_metrics.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/models/simple_menu_model.h" #include "ui/base/resource/resource_bundle.h" #include "ui/views/controls/menu/menu_model_adapter.h" #include "ui/views/controls/menu/menu_runner.h" #include "ui/views/controls/menu/submenu_view.h" #include "ui/views/widget/widget.h" using content::UserMetricsAction; // The language menu consists of 3 parts (in this order): // // (1) input method names. The size of the list is always >= 1. // (2) input method properties. This list might be empty. // (3) "Customize language and input..." button. // // Example of the menu (Japanese): // // ============================== (border of the popup window) // [ ] English (|index| in the following functions is 0) // [*] Japanese // [ ] Chinese (Simplified) // ------------------------------ (separator) // [*] Hiragana (index = 5, The property has 2 radio groups) // [ ] Katakana // [ ] HalfWidthKatakana // [*] Roman // [ ] Kana // ------------------------------ (separator) // Customize language and input...(index = 11) // ============================== (border of the popup window) // // Example of the menu (Simplified Chinese): // // ============================== (border of the popup window) // [ ] English // [ ] Japanese // [*] Chinese (Simplified) // ------------------------------ (separator) // Switch to full letter mode (The property has 2 command buttons) // Switch to half punctuation mode // ------------------------------ (separator) // Customize language and input... // ============================== (border of the popup window) // namespace { // Constants to specify the type of items in |model_|. enum { COMMAND_ID_INPUT_METHODS = 0, // English, Chinese, Japanese, Arabic, ... COMMAND_ID_IME_PROPERTIES, // Hiragana, Katakana, ... COMMAND_ID_CUSTOMIZE_LANGUAGE, // "Customize language and input..." button. }; // A group ID for IME properties starts from 0. We use the huge value for the // input method list to avoid conflict. const int kRadioGroupLanguage = 1 << 16; const int kRadioGroupNone = -1; // Returns the language name for the given |language_code|. string16 GetLanguageName(const std::string& language_code) { const string16 language_name = l10n_util::GetDisplayNameForLocale( language_code, g_browser_process->GetApplicationLocale(), true); return language_name; } PrefService* GetPrefService() { Profile* profile = ProfileManager::GetDefaultProfile(); if (profile) return profile->GetPrefs(); return NULL; } } // namespace namespace chromeos { using input_method::InputMethodManager; //////////////////////////////////////////////////////////////////////////////// // InputMethodMenu InputMethodMenu::InputMethodMenu() : initialized_prefs_(false), initialized_observers_(false), input_method_descriptors_(InputMethodManager::GetInstance()-> GetActiveInputMethods()), model_(new ui::SimpleMenuModel(NULL)), ALLOW_THIS_IN_INITIALIZER_LIST(input_method_menu_delegate_( new views::MenuModelAdapter(this))), input_method_menu_( new views::MenuItemView(input_method_menu_delegate_.get())), input_method_menu_runner_(new views::MenuRunner(input_method_menu_)), minimum_input_method_menu_width_(0), menu_alignment_(views::MenuItemView::TOPRIGHT) { DCHECK(input_method_descriptors_.get() && !input_method_descriptors_->empty()); // Sync current and previous input methods on Chrome prefs with ibus-daemon. if (StatusAreaViewChromeos::IsBrowserMode()) InitializePrefMembers(); if (StatusAreaViewChromeos::IsLoginMode()) { registrar_.Add(this, chrome::NOTIFICATION_LOGIN_USER_CHANGED, content::NotificationService::AllSources()); // On Aura status area is not recreated on sign in. Instead, 2 notifications // are sent to Chrome on sign in: NOTIFICATION_LOGIN_USER_CHANGED with // StatusAreaViewChromeos::IsLoginMode() and NOTIFICATION_SESSION_STARTED // with StatusAreaViewChromeos::IsBrowserMode(). // In case of Chrome crash, Chrome will be reloaded but IsLoginMode() will // return false at this point so NOTIFICATION_SESSION_STARTED will be // ignored and all initialization will happen in ctor. registrar_.Add(this, chrome::NOTIFICATION_SESSION_STARTED, content::NotificationService::AllSources()); } AddObservers(); } InputMethodMenu::~InputMethodMenu() { // RemoveObservers() is no-op if |this| object is already removed from the // observer list RemoveObservers(); } //////////////////////////////////////////////////////////////////////////////// // ui::MenuModel implementation: int InputMethodMenu::GetCommandIdAt(int index) const { return index; } bool InputMethodMenu::IsItemDynamicAt(int index) const { // Menu content for the language button could change time by time. return true; } bool InputMethodMenu::GetAcceleratorAt( int index, ui::Accelerator* accelerator) const { // Views for Chromium OS does not support accelerators yet. return false; } bool InputMethodMenu::IsItemCheckedAt(int index) const { DCHECK_GE(index, 0); DCHECK(input_method_descriptors_.get()); if (IndexIsInInputMethodList(index)) { const input_method::InputMethodDescriptor& input_method = input_method_descriptors_->at(index); return input_method == InputMethodManager::GetInstance()-> GetCurrentInputMethod(); } if (GetPropertyIndex(index, &index)) { const input_method::InputMethodPropertyList& property_list = InputMethodManager::GetInstance()->GetCurrentInputMethodProperties(); return property_list.at(index).is_selection_item_checked; } // Separator(s) or the "Customize language and input..." button. return false; } int InputMethodMenu::GetGroupIdAt(int index) const { DCHECK_GE(index, 0); if (IndexIsInInputMethodList(index)) return kRadioGroupLanguage; if (GetPropertyIndex(index, &index)) { const input_method::InputMethodPropertyList& property_list = InputMethodManager::GetInstance()->GetCurrentInputMethodProperties(); return property_list.at(index).selection_item_id; } return kRadioGroupNone; } bool InputMethodMenu::HasIcons() const { // We don't support icons on Chrome OS. return false; } bool InputMethodMenu::GetIconAt(int index, SkBitmap* icon) { return false; } ui::ButtonMenuItemModel* InputMethodMenu::GetButtonMenuItemAt( int index) const { return NULL; } bool InputMethodMenu::IsEnabledAt(int index) const { // Just return true so all input method names and input method propertie names // could be clicked. return true; } ui::MenuModel* InputMethodMenu::GetSubmenuModelAt(int index) const { // We don't use nested menus. return NULL; } void InputMethodMenu::HighlightChangedTo(int index) { // Views for Chromium OS does not support this interface yet. } void InputMethodMenu::MenuWillShow() { // Views for Chromium OS does not support this interface yet. } void InputMethodMenu::SetMenuModelDelegate(ui::MenuModelDelegate* delegate) { // Not needed for current usage. } int InputMethodMenu::GetItemCount() const { if (!model_.get()) { // Model is not constructed yet. This means that // InputMethodMenu is being constructed. Return zero. return 0; } return model_->GetItemCount(); } ui::MenuModel::ItemType InputMethodMenu::GetTypeAt(int index) const { DCHECK_GE(index, 0); if (IndexPointsToConfigureImeMenuItem(index)) { return ui::MenuModel::TYPE_COMMAND; // "Customize language and input" } if (IndexIsInInputMethodList(index)) return ui::MenuModel::TYPE_RADIO; if (GetPropertyIndex(index, &index)) { const input_method::InputMethodPropertyList& property_list = InputMethodManager::GetInstance()->GetCurrentInputMethodProperties(); if (property_list.at(index).is_selection_item) { return ui::MenuModel::TYPE_RADIO; } return ui::MenuModel::TYPE_COMMAND; } return ui::MenuModel::TYPE_SEPARATOR; } string16 InputMethodMenu::GetLabelAt(int index) const { DCHECK_GE(index, 0); DCHECK(input_method_descriptors_.get()); // We use IDS_OPTIONS_SETTINGS_LANGUAGES_CUSTOMIZE here as the button // opens the same dialog that is opened from the main options dialog. if (IndexPointsToConfigureImeMenuItem(index)) { return l10n_util::GetStringUTF16(IDS_OPTIONS_SETTINGS_LANGUAGES_CUSTOMIZE); } string16 name; if (IndexIsInInputMethodList(index)) { name = GetTextForMenu(input_method_descriptors_->at(index)); } else if (GetPropertyIndex(index, &index)) { InputMethodManager* manager = InputMethodManager::GetInstance(); const input_method::InputMethodPropertyList& property_list = manager->GetCurrentInputMethodProperties(); return manager->GetInputMethodUtil()->TranslateString( property_list.at(index).label); } return name; } void InputMethodMenu::ActivatedAt(int index) { DCHECK_GE(index, 0); DCHECK(input_method_descriptors_.get()); if (IndexPointsToConfigureImeMenuItem(index)) { OpenConfigUI(); return; } if (IndexIsInInputMethodList(index)) { // Inter-IME switching. const input_method::InputMethodDescriptor& input_method = input_method_descriptors_->at(index); InputMethodManager::GetInstance()->ChangeInputMethod( input_method.id()); content::RecordAction( UserMetricsAction("LanguageMenuButton_InputMethodChanged")); return; } if (GetPropertyIndex(index, &index)) { // Intra-IME switching (e.g. Japanese-Hiragana to Japanese-Katakana). const input_method::InputMethodPropertyList& property_list = InputMethodManager::GetInstance()->GetCurrentInputMethodProperties(); const std::string key = property_list.at(index).key; if (property_list.at(index).is_selection_item) { // Radio button is clicked. const int id = property_list.at(index).selection_item_id; // First, deactivate all other properties in the same radio group. for (int i = 0; i < static_cast<int>(property_list.size()); ++i) { if (i != index && id == property_list.at(i).selection_item_id) { InputMethodManager::GetInstance()->SetImePropertyActivated( property_list.at(i).key, false); } } // Then, activate the property clicked. InputMethodManager::GetInstance()->SetImePropertyActivated( key, true); } else { // Command button like "Switch to half punctuation mode" is clicked. // We can always use "Deactivate" for command buttons. InputMethodManager::GetInstance()->SetImePropertyActivated( key, false); } return; } LOG(ERROR) << "Unexpected index: " << index; } //////////////////////////////////////////////////////////////////////////////// // views::MenuButtonListener implementation: void InputMethodMenu::OnMenuButtonClicked(views::View* source, const gfx::Point& point) { PrepareForMenuOpen(); if (minimum_input_method_menu_width_ > 0) { DCHECK(input_method_menu_->HasSubmenu()); views::SubmenuView* submenu = input_method_menu_->GetSubmenu(); submenu->set_minimum_preferred_width(minimum_input_method_menu_width_); } gfx::Point screen_location; views::View::ConvertPointToScreen(source, &screen_location); gfx::Rect bounds(screen_location, source->size()); if (input_method_menu_runner_->RunMenuAt( source->GetWidget()->GetTopLevelWidget(), NULL, bounds, menu_alignment_, views::MenuRunner::HAS_MNEMONICS) == views::MenuRunner::MENU_DELETED) return; } //////////////////////////////////////////////////////////////////////////////// // InputMethodManager::Observer implementation: void InputMethodMenu::InputMethodChanged( InputMethodManager* manager, const input_method::InputMethodDescriptor& current_input_method, size_t num_active_input_methods) { UpdateUIFromInputMethod(current_input_method, num_active_input_methods); } // TODO(yusukes): Move code for handling preferences to chromeos/input_method/. void InputMethodMenu::PreferenceUpdateNeeded( InputMethodManager* manager, const input_method::InputMethodDescriptor& previous_input_method, const input_method::InputMethodDescriptor& current_input_method) { if (StatusAreaViewChromeos::IsBrowserMode()) { if (initialized_prefs_) { // make sure we're not in unit tests. // Sometimes (e.g. initial boot) |previous_input_method.id()| is empty. previous_input_method_pref_.SetValue(previous_input_method.id()); current_input_method_pref_.SetValue(current_input_method.id()); } } else if (StatusAreaViewChromeos::IsLoginMode()) { if (g_browser_process && g_browser_process->local_state()) { g_browser_process->local_state()->SetString( language_prefs::kPreferredKeyboardLayout, current_input_method.id()); } } } void InputMethodMenu::PropertyListChanged( InputMethodManager* manager, const input_method::InputMethodPropertyList& current_ime_properties) { // Usual order of notifications of input method change is: // 1. RegisterProperties(empty) // 2. RegisterProperties(list-of-new-properties) // 3. GlobalInputMethodChanged // However, due to the asynchronicity, we occasionally (but rarely) face to // 1. RegisterProperties(empty) // 2. GlobalInputMethodChanged // 3. RegisterProperties(list-of-new-properties) // this order. On this unusual case, we must rebuild the menu after the last // RegisterProperties. For the other cases, no rebuild is needed. Actually // it is better to be avoided. Otherwise users can sometimes observe the // awkward clear-then-register behavior. if (!current_ime_properties.empty()) { const input_method::InputMethodDescriptor& input_method = manager->GetCurrentInputMethod(); size_t num_active_input_methods = manager->GetNumActiveInputMethods(); UpdateUIFromInputMethod(input_method, num_active_input_methods); } } void InputMethodMenu::FirstObserverIsAdded(InputMethodManager* manager) { // NOTICE: Since this function might be called from the constructor of this // class, it's better to avoid calling virtual functions. if (initialized_prefs_ && StatusAreaViewChromeos::IsBrowserMode()) { // Get the input method name in the Preferences file which was in use last // time, and switch to the method. We remember two input method names in the // preference so that the Control+space hot-key could work fine from the // beginning. InputMethodChanged() will be called soon and the indicator // will be updated. const std::string previous_input_method_id = previous_input_method_pref_.GetValue(); if (!previous_input_method_id.empty()) { manager->ChangeInputMethod(previous_input_method_id); } const std::string current_input_method_id = current_input_method_pref_.GetValue(); if (!current_input_method_id.empty()) { manager->ChangeInputMethod(current_input_method_id); } } } void InputMethodMenu::PrepareForMenuOpen() { content::RecordAction(UserMetricsAction("LanguageMenuButton_Open")); PrepareMenuModel(); } void InputMethodMenu::PrepareMenuModel() { input_method_descriptors_.reset(InputMethodManager::GetInstance()-> GetActiveInputMethods()); RebuildModel(); } void InputMethodMenu::ActiveInputMethodsChanged( InputMethodManager* manager, const input_method::InputMethodDescriptor& current_input_method, size_t num_active_input_methods) { // Update the icon if active input methods are changed. See also // comments in UpdateUI() in input_method_menu_button.cc. UpdateUIFromInputMethod(current_input_method, num_active_input_methods); } void InputMethodMenu::UpdateUIFromInputMethod( const input_method::InputMethodDescriptor& input_method, size_t num_active_input_methods) { InputMethodManager* manager = InputMethodManager::GetInstance(); const string16 name = manager->GetInputMethodUtil()-> GetInputMethodShortName(input_method); const string16 tooltip = GetTextForMenu(input_method); UpdateUI(input_method.id(), name, tooltip, num_active_input_methods); } void InputMethodMenu::RebuildModel() { model_->Clear(); string16 dummy_label = UTF8ToUTF16(""); // Indicates if separator's needed before each section. bool need_separator = false; if (!input_method_descriptors_->empty()) { // We "abuse" the command_id and group_id arguments of AddRadioItem method. // A COMMAND_ID_XXX enum value is passed as command_id, and array index of // |input_method_descriptors_| or |property_list| is passed as group_id. for (size_t i = 0; i < input_method_descriptors_->size(); ++i) { model_->AddRadioItem(COMMAND_ID_INPUT_METHODS, dummy_label, i); } need_separator = true; } const input_method::InputMethodPropertyList& property_list = InputMethodManager::GetInstance()->GetCurrentInputMethodProperties(); if (!property_list.empty()) { if (need_separator) { model_->AddSeparator(); } for (size_t i = 0; i < property_list.size(); ++i) { model_->AddRadioItem(COMMAND_ID_IME_PROPERTIES, dummy_label, i); } need_separator = true; } if (ShouldSupportConfigUI()) { // Note: We use AddSeparator() for separators, and AddRadioItem() for all // other items even if an item is not actually a radio item. if (need_separator) { model_->AddSeparator(); } model_->AddRadioItem(COMMAND_ID_CUSTOMIZE_LANGUAGE, dummy_label, 0 /* dummy */); } // Rebuild the menu from the model. input_method_menu_delegate_->BuildMenu(input_method_menu_); } bool InputMethodMenu::IndexIsInInputMethodList(int index) const { DCHECK_GE(index, 0); DCHECK(model_.get()); if (index >= model_->GetItemCount()) { return false; } return ((model_->GetTypeAt(index) == ui::MenuModel::TYPE_RADIO) && (model_->GetCommandIdAt(index) == COMMAND_ID_INPUT_METHODS) && input_method_descriptors_.get() && (index < static_cast<int>(input_method_descriptors_->size()))); } bool InputMethodMenu::GetPropertyIndex(int index, int* property_index) const { DCHECK_GE(index, 0); DCHECK(property_index); DCHECK(model_.get()); if (index >= model_->GetItemCount()) { return false; } if ((model_->GetTypeAt(index) == ui::MenuModel::TYPE_RADIO) && (model_->GetCommandIdAt(index) == COMMAND_ID_IME_PROPERTIES)) { const int tmp_property_index = model_->GetGroupIdAt(index); const input_method::InputMethodPropertyList& property_list = InputMethodManager::GetInstance()->GetCurrentInputMethodProperties(); if (tmp_property_index < static_cast<int>(property_list.size())) { *property_index = tmp_property_index; return true; } } return false; } bool InputMethodMenu::IndexPointsToConfigureImeMenuItem(int index) const { DCHECK_GE(index, 0); DCHECK(model_.get()); if (index >= model_->GetItemCount()) { return false; } return ((model_->GetTypeAt(index) == ui::MenuModel::TYPE_RADIO) && (model_->GetCommandIdAt(index) == COMMAND_ID_CUSTOMIZE_LANGUAGE)); } string16 InputMethodMenu::GetTextForMenu( const input_method::InputMethodDescriptor& input_method) { if (!input_method.name().empty()) { // If the descriptor has a name, use it. return UTF8ToUTF16(input_method.name()); } // We don't show language here. Name of keyboard layout or input method // usually imply (or explicitly include) its language. input_method::InputMethodManager* manager = input_method::InputMethodManager::GetInstance(); // Special case for German, French and Dutch: these languages have multiple // keyboard layouts and share the same layout of keyboard (Belgian). We need // to show explicitly the language for the layout. For Arabic, Amharic, and // Indic languages: they share "Standard Input Method". const string16 standard_input_method_text = l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_LANGUAGES_M17N_STANDARD_INPUT_METHOD); const std::string language_code = input_method.language_code(); string16 text = manager->GetInputMethodUtil()->TranslateString(input_method.id()); if (text == standard_input_method_text || language_code == "de" || language_code == "fr" || language_code == "nl") { text = GetLanguageName(language_code) + UTF8ToUTF16(" - ") + text; } DCHECK(!text.empty()); return text; } void InputMethodMenu::RegisterPrefs(PrefService* local_state) { // We use an empty string here rather than a hardware keyboard layout name // since input_method::GetHardwareInputMethodId() might return a fallback // layout name if local_state->RegisterStringPref(kHardwareKeyboardLayout) // is not called yet. local_state->RegisterStringPref(language_prefs::kPreferredKeyboardLayout, "", PrefService::UNSYNCABLE_PREF); } void InputMethodMenu::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (type == chrome::NOTIFICATION_LOGIN_USER_CHANGED) { // When a user logs in, we should remove |this| object from the observer // list so that PreferenceUpdateNeeded() does not update the local state // anymore. RemoveObservers(); } if (type == chrome::NOTIFICATION_SESSION_STARTED) { InitializePrefMembers(); AddObservers(); InputMethodManager* manager = InputMethodManager::GetInstance(); UpdateUIFromInputMethod(manager->GetCurrentInputMethod(), manager->GetNumActiveInputMethods()); } } void InputMethodMenu::SetMinimumWidth(int width) { // On the OOBE network selection screen, fixed width menu would be preferable. minimum_input_method_menu_width_ = width; } void InputMethodMenu::AddObservers() { if (initialized_observers_) return; InputMethodManager* manager = InputMethodManager::GetInstance(); if (StatusAreaViewChromeos::IsLoginMode()) { manager->AddPreLoginPreferenceObserver(this); } else if (StatusAreaViewChromeos::IsBrowserMode()) { manager->AddPostLoginPreferenceObserver(this); } // AddObserver() should be called after AddXXXLoginPreferenceObserver. This is // because when the function is called FirstObserverIsAdded might be called // back, and FirstObserverIsAdded might then might call ChangeInputMethod() in // InputMethodManager. We have to prevent the manager function from calling // callback functions like InputMethodChanged since they touch (yet // uninitialized) UI elements. manager->AddObserver(this); initialized_observers_ = true; } void InputMethodMenu::RemoveObservers() { InputMethodManager* manager = InputMethodManager::GetInstance(); if (StatusAreaViewChromeos::IsLoginMode()) { manager->RemovePreLoginPreferenceObserver(this); } else if (StatusAreaViewChromeos::IsBrowserMode()) { manager->RemovePostLoginPreferenceObserver(this); } manager->RemoveObserver(this); initialized_observers_ = false; } void InputMethodMenu::InitializePrefMembers() { if (!initialized_prefs_) { PrefService* pref_service = GetPrefService(); if (pref_service) { initialized_prefs_ = true; previous_input_method_pref_.Init( prefs::kLanguagePreviousInputMethod, pref_service, this); current_input_method_pref_.Init( prefs::kLanguageCurrentInputMethod, pref_service, this); } } } } // namespace chromeos
36.735598
80
0.707921
gavinp
f27eb4c04270cd8b81e5c1f1060b6409f925c671
48,677
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/speech/tts/TextToSpeech.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/speech/tts/TextToSpeech.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/speech/tts/TextToSpeech.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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 "elastos/droid/speech/tts/TextToSpeech.h" #include "elastos/droid/speech/tts/CTtsEngines.h" #include "elastos/droid/speech/tts/UtteranceProgressListener.h" #include "elastos/droid/os/CBundle.h" #include "elastos/droid/content/CIntent.h" #include "elastos/droid/text/TextUtils.h" //#include "elastos/droid/net/Uri.h" //#include "elastos/droid/net/CUriBuilder.h" #include <elastos/utility/logging/Logger.h> #include <elastos/core/StringUtils.h> #include <elastos/core/AutoLock.h> #include <Elastos.CoreLibrary.Utility.h> #include <elastos/core/AutoLock.h> using Elastos::Core::AutoLock; using Elastos::Core::StringUtils; using Elastos::Utility::CLocale; using Elastos::Core::CString; using Elastos::Utility::Logging::Logger; using Elastos::Droid::Os::CBundle; using Elastos::Droid::Os::/*IIBinder*/IBinder; using Elastos::Droid::Content::EIID_IServiceConnection; using Elastos::Droid::Content::CIntent; using Elastos::Droid::Content::IContentResolver; using Elastos::Droid::Text::TextUtils; using Elastos::Droid::Net::IUriBuilder; namespace Elastos { namespace Droid { namespace Speech { namespace Tts { /****************** * TextToSpeech::TextToSpeechEngineInfo *******************************************************************************************************/ CAR_INTERFACE_IMPL(TextToSpeech::TextToSpeechEngineInfo, Object, ITextToSpeechEngineInfo) TextToSpeech::TextToSpeechEngineInfo::TextToSpeechEngineInfo() : icon(0) , system(FALSE) , priority(0) {} ECode TextToSpeech::TextToSpeechEngineInfo::ToString( /* [out] */ String* ret) { VALIDATE_NOT_NULL(ret) *ret = String("EngineInfo{name=") + name + String("}"); return NOERROR; } /******************************TextToSpeech::TextToSpeechActionR*************************/ //None /******************************TextToSpeech::TextToSpeechActionRShutdown*************************/ TextToSpeech::TextToSpeechActionRShutdown::TextToSpeechActionRShutdown( /* [in] */ TextToSpeech* tts) { mTts = tts; } Handle32 TextToSpeech::TextToSpeechActionRShutdown::Run( /* [in] */ IITextToSpeechService* service) { service->SetCallback((/*IIBinder*/IBinder*)((mTts->GetCallerIdentity()).Get()), NULL); Int32 stopRet; service->Stop((/*IIBinder*/IBinder*)((mTts->GetCallerIdentity()).Get()), &stopRet); (mTts->mServiceConnection)->Disconnect(); // Context#unbindService does not result in a call to // ServiceConnection#onServiceDisconnected. As a result, the // service ends up being destroyed (if there are no other open // connections to it) but the process lives on and the // ServiceConnection continues to refer to the destroyed service. // // This leads to tons of log spam about SynthThread being dead. (mTts->mServiceConnection) = NULL; (mTts->mCurrentEngine) = String(NULL); return (Handle32)NULL; } /******************************TextToSpeech::TextToSpeechActionRSpeak*************************/ TextToSpeech::TextToSpeechActionRSpeak::TextToSpeechActionRSpeak( /* [in] */ TextToSpeech* tts, /* [in] */ const String& text, /* [in] */ Int32 queueMode, /* [in] */ IHashMap* params) { mTts = tts; mText = text; mQueueMode = queueMode; mParams = params; } Handle32 TextToSpeech::TextToSpeechActionRSpeak::Run( /* [in] */ IITextToSpeechService* service) { #if 0 AutoPtr<IUri> utteranceUri = (*((mTts->mUtterances).Find(mText))).mSecond; if (utteranceUri != NULL) { Int32 nRet; service->PlayAudio((/*IIBinder*/IBinder*)((mTts->GetCallerIdentity()).Get()), utteranceUri.Get(), mQueueMode, (mTts->ConvertParamsHashMaptoBundle(mParams)).Get(), &nRet); return (Handle32)nRet; } else { Int32 nRet; service->Speak((/*IIBinder*/IBinder*)((mTts->GetCallerIdentity()).Get()), mText, mQueueMode, (mTts->ConvertParamsHashMaptoBundle(mParams)).Get(), &nRet); return (Handle32)nRet; } #endif return (Handle32)NULL; } /******************************TextToSpeech::TextToSpeechActionRPlayEarcon*************************/ TextToSpeech::TextToSpeechActionRPlayEarcon::TextToSpeechActionRPlayEarcon( /* [in] */ TextToSpeech* tts, /* [in] */ const String& earcon, /* [in] */ Int32 queueMode, /* [in] */ IHashMap* params) { mTts = tts; mEarcon = earcon; mQueueMode = queueMode; mParams = params; } Handle32 TextToSpeech::TextToSpeechActionRPlayEarcon::Run( /* [in] */ IITextToSpeechService* service) { #if 0 AutoPtr<IUri> earconUri = (*((mTts->mEarcons).Find(mEarcon))).mSecond; if (earconUri == NULL) { return (Handle32)ITextToSpeech::TTS_ERROR; } Int32 nRet; service->PlayAudio((/*IIBinder*/IBinder*)((mTts->GetCallerIdentity()).Get()), earconUri, mQueueMode, (mTts->ConvertParamsHashMaptoBundle(mParams)).Get(), &nRet); return (Handle32)nRet; #endif return (Handle32)NULL; } /******************************TextToSpeech::TextToSpeechActionRPlaySilence*************************/ TextToSpeech::TextToSpeechActionRPlaySilence::TextToSpeechActionRPlaySilence( /* [in] */ TextToSpeech* tts, /* [in] */ Int64 durationInMs, /* [in] */ Int32 queueMode, /* [in] */ IHashMap* params) { mTts = tts; mDurationInMs = durationInMs; mQueueMode = queueMode; mParams = params; } Handle32 TextToSpeech::TextToSpeechActionRPlaySilence::Run( /* [in] */ IITextToSpeechService* service) { Int32 nRet; #if 0 service->PlaySilence((/*IIBinder*/IBinder*)((mTts->GetCallerIdentity()).Get()), mDurationInMs, mQueueMode, mTts->ConvertParamsHashMaptoBundle(mParams), &nRet); #endif return (Handle32)nRet; } /******************************TextToSpeech::TextToSpeechActionRGetFeatures*************************/ TextToSpeech::TextToSpeechActionRGetFeatures::TextToSpeechActionRGetFeatures( /* [in] */ TextToSpeech* tts, /* [in] */ ILocale* locale) { mTts = tts; mLocale = locale; } Handle32 TextToSpeech::TextToSpeechActionRGetFeatures::Run( /* [in] */ IITextToSpeechService* service) { #if 0 String strISO3Language, strISO3Country, strVariant; mLocale->GetISO3Language(&strISO3Language); mLocale->GetISO3Country(&strISO3Country); mLocale->GetVariant(&strVariant); AutoPtr< ArrayOf<String> > features; service->GetFeaturesForLanguage(strISO3Language, strISO3Country, strVariant, (ArrayOf<String>**)&features); if (features != NULL) { AutoPtr<IObjectContainer> oc; CObjectContainer::New((IObjectContainer**)&oc); Int32 aryLen = features->GetLength(); String strTemp; for(Int32 i = 0; i<aryLen; i++) { strTemp = (*features)[i]; AutoPtr<ICharSequence> cs; CString::New(strTemp, (ICharSequence**)&cs); oc->Add((IInterface*)(cs.Get())); } return (Handle32)(oc.Get()); } #endif return (Handle32)NULL; } /******************************TextToSpeech::TextToSpeechActionRIsSpeaking*************************/ TextToSpeech::TextToSpeechActionRIsSpeaking::TextToSpeechActionRIsSpeaking( /* [in] */ TextToSpeech* tts) { mTts = tts; } Handle32 TextToSpeech::TextToSpeechActionRIsSpeaking::Run( /* [in] */ IITextToSpeechService* service) { Boolean bRet; service->IsSpeaking(&bRet); return (Handle32)bRet; } /******************************TextToSpeech::TextToSpeechActionRStop*************************/ TextToSpeech::TextToSpeechActionRStop::TextToSpeechActionRStop( /* [in] */ TextToSpeech* tts) { mTts = tts; } Handle32 TextToSpeech::TextToSpeechActionRStop::Run( /* [in] */ IITextToSpeechService* service) { Int32 nRet; service->Stop((/*IIBinder*/IBinder*)((mTts->GetCallerIdentity()).Get()), &nRet); return (Handle32)nRet; } /******************************TextToSpeech::TextToSpeechActionRSetLanguage*************************/ TextToSpeech::TextToSpeechActionRSetLanguage::TextToSpeechActionRSetLanguage( /* [in] */ TextToSpeech* tts, /* [in] */ ILocale* locale) { mTts = tts; mLocale = locale; } Handle32 TextToSpeech::TextToSpeechActionRSetLanguage::Run( /* [in] */ IITextToSpeechService* service) { #if 0 if (mLocale == NULL) { return ITextToSpeech::LANG_NOT_SUPPORTED; } String language, country, variant; mLocale->GetISO3Language(&language); mLocale->GetISO3Country(&country); mLocale->GetVariant(&variant); // Check if the language, country, variant are available, and cache // the available parts. // Note that the language is not actually set here, instead it is cached so it // will be associated with all upcoming utterances. Int32 result; service->LoadLanguage(language, country, variant, &result); if (result >= ITextToSpeech::LANG_AVAILABLE){ if (result < ITextToSpeech::LANG_COUNTRY_VAR_AVAILABLE) { variant = ""; if (result < ITextToSpeech::LANG_COUNTRY_AVAILABLE) { country = ""; } } (mTts->mParams)->PutString(ITextToSpeechEngine::KEY_PARAM_LANGUAGE, language); (mTts->mParams)->PutString(ITextToSpeechEngine::KEY_PARAM_COUNTRY, country); (mTts->mParams)->PutString(ITextToSpeechEngine::KEY_PARAM_VARIANT, variant); } return (Handle32)result; #endif return (Handle32)NULL; } /******************************TextToSpeech::TextToSpeechActionRGetLanguage*************************/ TextToSpeech::TextToSpeechActionRGetLanguage::TextToSpeechActionRGetLanguage( /* [in] */ TextToSpeech* tts) { mTts = tts; } Handle32 TextToSpeech::TextToSpeechActionRGetLanguage::Run( /* [in] */ IITextToSpeechService* service) { AutoPtr< ArrayOf<String> > locStrings; service->GetLanguage((ArrayOf<String>**)&locStrings); if (locStrings != NULL && locStrings->GetLength() == 3) { AutoPtr<ILocale> localeRet; CLocale::New((*locStrings)[0], (*locStrings)[1], (*locStrings)[2], (ILocale**)&localeRet); return (Handle32)(localeRet.Get()); } return (Handle32)NULL; } /******************************TextToSpeech::TextToSpeechActionRIsLanguageAvailable*************************/ TextToSpeech::TextToSpeechActionRIsLanguageAvailable::TextToSpeechActionRIsLanguageAvailable( /* [in] */ TextToSpeech* tts, /* [in] */ ILocale* locale) { mTts = tts; mLocale = locale; } Handle32 TextToSpeech::TextToSpeechActionRIsLanguageAvailable::Run( /* [in] */ IITextToSpeechService* service) { String language, country, variant; mLocale->GetISO3Language(&language); mLocale->GetISO3Country(&country); mLocale->GetVariant(&variant); Int32 nRet; service->IsLanguageAvailable(language, country, variant, &nRet); return (Handle32)nRet; } /******************************TextToSpeech::TextToSpeechActionRSynthesizeToFile*************************/ TextToSpeech::TextToSpeechActionRSynthesizeToFile::TextToSpeechActionRSynthesizeToFile( /* [in] */ TextToSpeech* tts, /* [in] */ const String& text, /* [in] */ IHashMap* params, /* [in] */ const String& filename) { mTts = tts; mText = text; mParams = params; mFilename = filename; } Handle32 TextToSpeech::TextToSpeechActionRSynthesizeToFile::Run( /* [in] */ IITextToSpeechService* service) { Int32 nRet; #if 0 service->SynthesizeToFile((/*IIBinder*/IBinder*)((mTts->GetCallerIdentity()).Get()), mText, mFilename, (mTts->ConvertParamsHashMaptoBundle(mParams)).Get(), &nRet); #endif return (Handle32)nRet; } /****************** * TextToSpeech::TextToSpeechConnection::TextToSpeechConnectionCallback *******************************************************************************************************/ CAR_INTERFACE_IMPL(TextToSpeech::TextToSpeechConnection::TextToSpeechConnectionCallback, Object, IITextToSpeechCallback) TextToSpeech::TextToSpeechConnection::TextToSpeechConnectionCallback::TextToSpeechConnectionCallback() {} TextToSpeech::TextToSpeechConnection::TextToSpeechConnectionCallback::~TextToSpeechConnectionCallback() {} ECode TextToSpeech::TextToSpeechConnection::TextToSpeechConnectionCallback::constructor() { return NOERROR; } ECode TextToSpeech::TextToSpeechConnection::TextToSpeechConnectionCallback::constructor( /* [in] */ TextToSpeech* tts) { mTts = tts; return NOERROR; } ECode TextToSpeech::TextToSpeechConnection::TextToSpeechConnectionCallback::OnStop( /* [in] */ const String& utteranceId) { AutoPtr<IUtteranceProgressListener> listener = mTts->mUtteranceProgressListener; if (listener != NULL) { listener->OnDone(utteranceId); } return NOERROR; } ECode TextToSpeech::TextToSpeechConnection::TextToSpeechConnectionCallback::OnSuccess( /* [in] */ const String& utteranceId) { AutoPtr<IUtteranceProgressListener> listener = mTts->mUtteranceProgressListener; if (listener != NULL) { return listener->OnDone(utteranceId); } return NOERROR; } ECode TextToSpeech::TextToSpeechConnection::TextToSpeechConnectionCallback::OnError( /* [in] */ const String& utteranceId, /* [in] */ Int32 errorCode) { AutoPtr<IUtteranceProgressListener> listener = mTts->mUtteranceProgressListener; if (listener != NULL) { return listener->OnError(utteranceId); } return NOERROR; } ECode TextToSpeech::TextToSpeechConnection::TextToSpeechConnectionCallback::OnStart( /* [in] */ const String& utteranceId) { AutoPtr<IUtteranceProgressListener> listener = mTts->mUtteranceProgressListener; if (listener != NULL) { return listener->OnStart(utteranceId); } return NOERROR; } /****************** * TextToSpeech::TextToSpeechConnection *******************************************************************************************************/ CAR_INTERFACE_IMPL(TextToSpeech::TextToSpeechConnection, Object, IServiceConnection) TextToSpeech::TextToSpeechConnection::TextToSpeechConnection() {} TextToSpeech::TextToSpeechConnection::~TextToSpeechConnection() {} ECode TextToSpeech::TextToSpeechConnection::constructor() { return NOERROR; } ECode TextToSpeech::TextToSpeechConnection::constructor( /* [in] */ TextToSpeech* pTts) { AutoPtr<TextToSpeechConnectionCallback> ttscc; mTts = pTts; ttscc = new TextToSpeechConnectionCallback(); ttscc->constructor(mTts); mCallback = ttscc; return NOERROR; } ECode TextToSpeech::TextToSpeechConnection::OnServiceConnected( /* [in] */ IComponentName* name, /* [in] */ IBinder* service) { //Java: Log.i(TAG, "Connected to " + name); String shortStringComponentName; name -> ToString(&shortStringComponentName); Logger::I(mTts->TAG, String("Connected to ")+shortStringComponentName+String("\n")); AutoLock lock(mTts->mStartLock); if (mTts->mServiceConnection != NULL) { // Disconnect any previous service connection (mTts->mServiceConnection)->Disconnect(); } mTts->mServiceConnection = this; // mService = (IITextToSpeechService*)(service); //try { mService->SetCallback((/*IIBinder*/IBinder*)(GetCallerIdentity().Get()), mCallback); mTts->DispatchOnInit(ITextToSpeech::TTS_SUCCESS); //} catch (RemoteException re) { //Java: Log.e(TAG, "Error connecting to service, setCallback() failed"); /* Logger::E(mTts->TAG, String("Error connecting to service, setCallback() failed\n")); mTts->DispatchOnInit(ERROR); */ //} return NOERROR; } /*AutoPtr<IIBinder>*/AutoPtr<IInterface> TextToSpeech::TextToSpeechConnection::GetCallerIdentity() { return mCallback; } Boolean TextToSpeech::TextToSpeechConnection::ClearServiceConnection() { AutoLock lock(mTts->mStartLock); Boolean result = false; #if 0 if (mOnSetupConnectionAsyncTask != NULL) { result = mOnSetupConnectionAsyncTask->Cancel(FALSE); mOnSetupConnectionAsyncTask = NULL; } mService = NULL; // If this is the active connection, clear it if (mServiceConnection == this) { mServiceConnection = NULL; } #endif return result; } ECode TextToSpeech::TextToSpeechConnection::OnServiceDisconnected( /* [in] */ IComponentName* name) { AutoLock lock(mTts->mStartLock); mService = NULL; // If this is the active connection, clear it if ((mTts->mServiceConnection).Get() == this) { mTts->mServiceConnection = NULL; } Logger::I(TAG, String("Asked to disconnect from ") + ToString(name)); if (ClearServiceConnection()) { /* We need to protect against a rare case where engine * dies just after successful connection - and we process onServiceDisconnected * before OnServiceConnectedAsyncTask.onPostExecute. onServiceDisconnected cancels * OnServiceConnectedAsyncTask.onPostExecute and we don't call dispatchOnInit * with ERROR as argument. */ mTts->DispatchOnInit(TTS_ERROR); } return NOERROR; } void TextToSpeech::TextToSpeechConnection::Disconnect() { (mTts->mContext)->UnbindService(this); ClearServiceConnection(); } Boolean TextToSpeech::TextToSpeechConnection::IsEstablished() { return mService != NULL && mEstablished; } Handle32 TextToSpeech::TextToSpeechConnection::RunAction( /* [in] */ TextToSpeechActionR* action, /* [in] */ Handle32 errorResult, /* [in] */ const String& method, /* [in] */ Boolean reconnect, /* [in] */ Boolean onlyEstablishedConnection) { AutoLock lock(mTts->mStartLock); //try { if (mService == NULL) { //Java: Log.w(TAG, method + " failed: not connected to TTS engine"); Logger::W(mTts->TAG, method + String(" failed: not connected to TTS engine\n")); return errorResult; } if (onlyEstablishedConnection && !IsEstablished()) { Logger::W(TAG, method + String(" failed: TTS engine connection not fully set up")); return errorResult; } return action->Run(mService); //} catch (RemoteException ex) { //Java: Log.e(TAG, method + " failed", ex); Logger::E(mTts->TAG, method + String(" failed\n")); if (reconnect) { Disconnect(); mTts->InitTts(); } return errorResult; //} } /******************************TextToSpeech*************************/ const Int32 TextToSpeech::QUEUE_DESTROY = 2; const String TextToSpeech::TAG("TextToSpeech"); CAR_INTERFACE_IMPL(TextToSpeech, Object, ITextToSpeech) TextToSpeech::TextToSpeech() {} TextToSpeech::~TextToSpeech() {} ECode TextToSpeech::constructor() { return NOERROR; } ECode TextToSpeech::constructor( /* [in] */ IContext* context, /* [in] */ ITextToSpeechOnInitListener* listener) { return constructor(context, listener, String(NULL)); } ECode TextToSpeech::constructor( /* [in] */ IContext* context, /* [in] */ ITextToSpeechOnInitListener* listener, /* [in] */ const String& engine) { return constructor(context, listener, engine, String(NULL), TRUE); } ECode TextToSpeech::constructor( /* [in] */ IContext* context, /* [in] */ ITextToSpeechOnInitListener* listener, /* [in] */ const String& engine, /* [in] */ const String& packageName, /* [in] */ Boolean useFallback) { mContext = context; mInitListener = listener; mRequestedEngine = engine; mUseFallback = useFallback; //Java: mEarcons = new HashMap<String, Uri>(); //Java: mUtterances = new HashMap<String, Uri>(); mUtteranceProgressListener = NULL; AutoPtr<CTtsEngines> cttsEngines; CTtsEngines::NewByFriend(mContext, (CTtsEngines**)&cttsEngines); //Java: mEnginesHelper = new TtsEngines(mContext); mEnginesHelper = cttsEngines; if (!packageName.IsNull()) { mPackageName = packageName; } else { mContext->GetPackageName(&mPackageName); } InitTts(); return NOERROR; } Handle32 TextToSpeech::RunActionNoReconnect( /* [in] */ TextToSpeechActionR* action, /* [in] */ Handle32 errorResult, /* [in] */ const String& method, /* [in] */ Boolean onlyEstablishedConnection) { return RunAction(action, errorResult, method, FALSE, onlyEstablishedConnection); } Handle32 TextToSpeech::RunAction( /* [in] */ TextToSpeechActionR* action, /* [in] */ Handle32 errorResult, /* [in] */ const String& method) { return RunAction(action, errorResult, method, TRUE, TRUE); } Handle32 TextToSpeech::RunAction( /* [in] */ TextToSpeechActionR* action, /* [in] */ Handle32 errorResult, /* [in] */ const String& method, /* [in] */ Boolean reconnect, /* [in] */ Boolean onlyEstablishedConnection) { AutoLock lock(mStartLock); if (mServiceConnection == NULL) { //Java: Log.w(TAG, method + " failed: not bound to TTS engine"); Logger::W(TAG, method + String(" failed: not bound to TTS engine\n")); return errorResult; } return mServiceConnection->RunAction(action, errorResult, method, reconnect, onlyEstablishedConnection); } Int32 TextToSpeech::InitTts() { // Step 1: Try connecting to the engine that was requested. if (!mRequestedEngine.IsNull()) { Boolean bIsEngineInstalled; if ((mEnginesHelper->IsEngineInstalled(mRequestedEngine, &bIsEngineInstalled), bIsEngineInstalled)) { if (ConnectToEngine(mRequestedEngine)) { mCurrentEngine = mRequestedEngine; return ITextToSpeech::TTS_SUCCESS; } else if (!mUseFallback) { mCurrentEngine = String(NULL); DispatchOnInit(ITextToSpeech::TTS_ERROR); return ITextToSpeech::TTS_ERROR; } } else if (!mUseFallback) { //Java: Log.i(TAG, "Requested engine not installed: " + mRequestedEngine); Logger::I(TAG, String("Requested engine not installed: ")+mRequestedEngine+String("\n")); mCurrentEngine = String(NULL); DispatchOnInit(ITextToSpeech::TTS_ERROR); return ITextToSpeech::TTS_ERROR; } } // Step 2: Try connecting to the user's default engine. String defaultEngine; GetDefaultEngine(&defaultEngine); if (!defaultEngine.IsNull() && !defaultEngine.Equals(mRequestedEngine)) { if (ConnectToEngine(defaultEngine)) { mCurrentEngine = defaultEngine; return ITextToSpeech::TTS_SUCCESS; } } // Step 3: Try connecting to the highest ranked engine in the // system. String highestRanked; mEnginesHelper->GetHighestRankedEngineName(&highestRanked); if (!highestRanked.IsNull() && !highestRanked.Equals(mRequestedEngine) && !highestRanked.Equals(defaultEngine)) { if (ConnectToEngine(highestRanked)) { mCurrentEngine = highestRanked; return ITextToSpeech::TTS_SUCCESS; } } // NOTE: The API currently does not allow the caller to query whether // they are actually connected to any engine. This might fail for various // reasons like if the user disables all her TTS engines. mCurrentEngine = String(NULL); DispatchOnInit(ITextToSpeech::TTS_ERROR); return ITextToSpeech::TTS_ERROR; } Boolean TextToSpeech::ConnectToEngine( /* [in] */ const String& engine) { AutoPtr<TextToSpeechConnection> connection = /*new TextToSpeechConnection(this)*/NULL; AutoPtr<IIntent> intent; CIntent::New(ITextToSpeechEngine::INTENT_ACTION_TTS_SERVICE, (IIntent**)&intent); intent->SetPackage(engine); Boolean bound; mContext->BindService(intent.Get(), connection.Get(), IContext::BIND_AUTO_CREATE, &bound); if (!bound) { //Java: Log.e(TAG, "Failed to bind to " + engine); Logger::E(TAG, String("Failed to bind to ")+engine+String("\n")); return FALSE; } else { //Java: Log.i(TAG, "Sucessfully bound to " + engine); Logger::I(TAG, String("Sucessfully bound to ")+engine+String("\n")); return TRUE; } } void TextToSpeech::DispatchOnInit( /* [in] */ Int32 result) { AutoLock lock(mStartLock); if (mInitListener != NULL) { mInitListener->OnInit(result); mInitListener = NULL; } } /*AutoPtr<IIBinder>*/AutoPtr<IInterface> TextToSpeech::GetCallerIdentity() { return mServiceConnection->GetCallerIdentity(); } ECode TextToSpeech::Shutdown() { AutoPtr<TextToSpeechActionR> ttsActionR = new TextToSpeechActionRShutdown(this); RunActionNoReconnect(ttsActionR.Get(), (Handle32)NULL, String("shutdown"), FALSE); return NOERROR; } ECode TextToSpeech::AddSpeech( /* [in] */ const String& text, /* [in] */ const String& packagename, /* [in] */ Int32 resourceId, /* [out] */ Int32 *ret) { AutoLock lock(mStartLock); mUtterances.Insert(Map<String, AutoPtr<IUri> >::ValueType(text, MakeResourceUri(packagename, resourceId)) ); *ret = ITextToSpeech::TTS_SUCCESS; return NOERROR; } ECode TextToSpeech::AddSpeech( /* [in] */ ICharSequence* text, /* [in] */ const String& packagename, /* [in] */ Int32 resourceId, /* [out] */ Int32 *ret) { AutoLock lock(mStartLock); String str; text->ToString(&str); mUtterances.Insert(Map<String, AutoPtr<IUri> >::ValueType(str, MakeResourceUri(packagename, resourceId)) ); *ret = ITextToSpeech::TTS_SUCCESS; return NOERROR; } ECode TextToSpeech::AddSpeech( /* [in] */ const String& text, /* [in] */ const String& filename, /* [out] */ Int32 *ret) { AutoLock lock(mStartLock); AutoPtr<IUri> uri = /*Uri::Parse(filename)*/NULL; mUtterances.Insert(Map<String, AutoPtr<IUri> >::ValueType(text, uri.Get() ) ); *ret = ITextToSpeech::TTS_SUCCESS; return NOERROR; } ECode TextToSpeech::AddSpeech( /* [in] */ ICharSequence* text, /* [in] */ IFile* file, /* [out] */ Int32 *ret) { AutoLock lock(mStartLock); String str; text->ToString(&str); AutoPtr<IUri> uri = /*Uri::fromFile(file)*/NULL; mUtterances.Insert(Map<String, AutoPtr<IUri> >::ValueType(str, uri.Get() ) ); *ret = ITextToSpeech::TTS_SUCCESS; return NOERROR; } ECode TextToSpeech::AddEarcon( /* [in] */ const String& earcon, /* [in] */ const String& packagename, /* [in] */ Int32 resourceId, /* [out] */ Int32 *ret) { AutoLock lock(mStartLock); mEarcons.Insert(Map<String, AutoPtr<IUri> >::ValueType(earcon, MakeResourceUri(packagename, resourceId) ) ); *ret = ITextToSpeech::TTS_SUCCESS; return NOERROR; } ECode TextToSpeech::AddEarcon( /* [in] */ const String& earcon, /* [in] */ const String& filename, /* [out] */ Int32 *ret) { AutoLock lock(mStartLock); AutoPtr<IUri> uri = /*Uri::Parse(filename)*/NULL; mEarcons.Insert(Map<String, AutoPtr<IUri> >::ValueType(earcon, uri.Get() ) ); *ret = ITextToSpeech::TTS_SUCCESS; return NOERROR; } ECode TextToSpeech::AddEarcon( /* [in] */ const String& earcon, /* [in] */ IFile* file, /* [out] */ Int32* ret) { AutoLock lock(mStartLock); AutoPtr<IUri> uri = /*Uri::FromFile(file)*/NULL; mEarcons.Insert(Map<String, AutoPtr<IUri> >::ValueType(earcon, uri.Get() ) ); *ret = ITextToSpeech::TTS_SUCCESS; return NOERROR; } AutoPtr<IUri> TextToSpeech::MakeResourceUri( /* [in] */ const String& packageName, /* [in] */ Int32 resourceId) { //Java: return new Uri.Builder().scheme(ContentResolver.SCHEME_ANDROID_RESOURCE).encodedAuthority(packageName).appendEncodedPath(String.valueOf(resourceId)).build(); AutoPtr<IUriBuilder> ub; // CUriBuilder::New((IUriBuilder**)&ub); // ub -> Scheme(IContentResolver::SCHEME_ANDROID_RESOURCE); // ub -> EncodedAuthority(packageName); // ub -> AppendEncodedPath(StringUtils::Int32ToString(resourceId)); AutoPtr<IUri> uRet; // ub -> Build((IUri**)&uRet); return uRet; } ECode TextToSpeech::Speak( /* [in] */ ICharSequence* text, /* [in] */ Int32 queueMode, /* [in] */ IBundle* params, /* [in] */ const String& utteranceId, /* [in] */ Int32* ret) { String str; text->ToString(&str); /* AutoPtr<TextToSpeechActionR> ttsActionR = new TextToSpeechActionRSpeak(this, str, queueMode, params); *ret = (Int32)RunAction(ttsActionR.Get(), ITextToSpeech::TTS_ERROR, String("speak") ); */ return NOERROR; } ECode TextToSpeech::Speak( /* [in] */ const String& text, /* [in] */ Int32 queueMode, /* [in] */ IHashMap* params, /* [in] */ Int32* ret) { /* AutoPtr<TextToSpeechActionR> ttsActionR = new TextToSpeechActionRSpeak(this, text, queueMode, params, utteranceId); *ret = (Int32)RunAction(ttsActionR.Get(), ITextToSpeech::TTS_ERROR, String("speak") ); */ return NOERROR; } ECode TextToSpeech::PlayEarcon( /* [in] */ const String& earcon, /* [in] */ Int32 queueMode, /* [in] */ IBundle* params, /* [in] */ const String& utteranceld, /* [out] */ Int32* ret) { /* *ret = PlayEarcon(earcon, queueMode, ConvertParamsHashMaptoBundle(params), params == NULL ? NULL : params->Get(Engine.KEY_PARAM_UTTERANCE_ID)); */ return NOERROR; } ECode TextToSpeech::PlayEarcon( /* [in] */ const String& earcon, /* [in] */ Int32 queueMode, /* [in] */ IHashMap* params, /* [out] */ Int32* ret) { AutoPtr<TextToSpeechActionR> ttsActionR = new TextToSpeechActionRPlayEarcon(this, earcon, queueMode, params); *ret = (Int32)RunAction(ttsActionR.Get(), ITextToSpeech::TTS_ERROR, String("playEarcon") ); return NOERROR; } ECode TextToSpeech::PlaySilentUtterance( /* [in] */ Int64 durationInMs, /* [in] */ Int32 queueMode, /* [in] */ const String& utteranceId, /* [out] */ Int32* ret) { VALIDATE_NOT_NULL(ret) assert(0 && "TODO"); // return runAction(new Action<Integer>() { // @Override // public Integer run(ITextToSpeechService service) throws RemoteException { // return service.playSilence(getCallerIdentity(), durationInMs, // queueMode, utteranceId); // } // }, ERROR, "playSilentUtterance"); return NOERROR; } ECode TextToSpeech::PlaySilence( /* [in] */ Int64 durationInMs, /* [in] */ Int32 queueMode, /* [in] */ IHashMap* params, /* [out] */ Int32* ret) { AutoPtr<TextToSpeechActionR> ttsActionR = new TextToSpeechActionRPlaySilence(this, durationInMs, queueMode, params); *ret = (Int32)RunAction(ttsActionR.Get(), ITextToSpeech::TTS_ERROR, String("playSilence") ); return NOERROR; } ECode TextToSpeech::GetFeatures( /* [in] */ ILocale* locale, /* [out] */ ISet** ret) { #if 0 AutoPtr<TextToSpeechActionR> ttsActionR = new TextToSpeechActionRGetFeatures(this, locale); AutoPtr<IObjectContainer> oc; oc = RunAction(ttsActionR.Get(), (Handle32)NULL, String("getFeatures") ); AutoPtr<Set<String> > sRet = new Set<String>(); if(oc != NULL) { AutoPtr<IObjectEnumerator> it; oc->GetObjectEnumerator((IObjectEnumerator**)&it); Boolean succeeded = FALSE; String strTemp; while(it->MoveNext(&succeeded), succeeded) { AutoPtr<IInterface> cs; it->Current((IInterface**)&cs); ICharSequence::Probe(cs)->ToString(&strTemp); sRet->Insert(strTemp); } } return sRet; #endif return NOERROR; } ECode TextToSpeech::IsSpeaking( /* [out] */ Boolean* ret) { AutoPtr<TextToSpeechActionR> ttsActionR = new TextToSpeechActionRIsSpeaking(this); *ret = (Boolean)RunAction(ttsActionR.Get(), FALSE, String("isSpeaking") ); return NOERROR; } ECode TextToSpeech::Stop( /* [out] */ Int32* ret) { AutoPtr<TextToSpeechActionR> ttsActionR = new TextToSpeechActionRStop(this); *ret = (Int32)RunAction(ttsActionR.Get(), ITextToSpeech::TTS_ERROR, String("stop") ); return NOERROR; } ECode TextToSpeech::SetSpeechRate( /* [in] */ Float speechRate, /* [out] */ Int32* ret) { if (speechRate > 0.0f) { Int32 intRate = (Int32)(speechRate * 100); if (intRate > 0) { if(TRUE){ AutoLock lock(mStartLock); mParams->PutInt32(ITextToSpeechEngine::KEY_PARAM_RATE, intRate); } *ret = ITextToSpeech::TTS_SUCCESS; return NOERROR; } } *ret = ITextToSpeech::TTS_ERROR; return NOERROR; } ECode TextToSpeech::SetPitch( /* [in] */ Float pitch, /* [out] */ Int32* ret) { if (pitch > 0.0f) { Int32 intPitch = (Int32)(pitch * 100); if (intPitch > 0) { if(TRUE){ AutoLock lock(mStartLock); mParams->PutInt32(ITextToSpeechEngine::KEY_PARAM_PITCH, intPitch); } *ret = ITextToSpeech::TTS_SUCCESS; return NOERROR; } } *ret = ITextToSpeech::TTS_ERROR; return NOERROR; } ECode TextToSpeech::SetAudioAttributes( /* [in] */ IAudioAttributes* audioAttributes, /* [out] */ Int32* ret) { VALIDATE_NOT_NULL(ret) assert(0 && "TODO"); // if (audioAttributes != null) { // { AutoLock syncLock(mStartLock); // mParams.putParcelable(Engine.KEY_PARAM_AUDIO_ATTRIBUTES, // audioAttributes); // } // return SUCCESS; // } // return ERROR; return NOERROR; } ECode TextToSpeech::GetCurrentEngine( /* [out] */ String* ret) { VALIDATE_NOT_NULL(ret) *ret = mCurrentEngine; return NOERROR; } ECode TextToSpeech::GetDefaultLanguage( /* [out] */ ILocale** ret) { VALIDATE_NOT_NULL(ret) assert(0 && "TODO"); // return runAction(new Action<Locale>() { // @Override // public Locale run(ITextToSpeechService service) throws RemoteException { // String[] defaultLanguage = service.getClientDefaultLanguage(); // return new Locale(defaultLanguage[0], defaultLanguage[1], defaultLanguage[2]); // } // }, null, "getDefaultLanguage"); return NOERROR; } ECode TextToSpeech::SetLanguage( /* [in] */ ILocale* loc, /* [out] */ Int32* ret) { AutoPtr<TextToSpeechActionR> ttsActionR = new TextToSpeechActionRSetLanguage(this, loc); *ret = (Int32)RunAction(ttsActionR.Get(), ITextToSpeech::LANG_NOT_SUPPORTED, String("setLanguage") ); return NOERROR; } ECode TextToSpeech::GetLanguage( /* [out] */ ILocale** language) { AutoPtr<TextToSpeechActionR> ttsActionR = new TextToSpeechActionRGetLanguage(this); AutoPtr<ILocale> lRet = (ILocale*)RunAction(ttsActionR.Get(), (Handle32)0, String("getLanguage") ); assert(0 && "TODO"); *language = lRet; REFCOUNT_ADD(*language) return NOERROR; } ECode TextToSpeech::GetAvailableLanguages( /* [out] */ ISet** languages) { VALIDATE_NOT_NULL(languages) assert(0 && "TODO"); // return runAction(new Action<Set<Locale>>() { // @Override // public Set<Locale> run(ITextToSpeechService service) throws RemoteException { // List<Voice> voices = service.getVoices(); // if (voices == null) { // return new HashSet<Locale>(); // } // HashSet<Locale> locales = new HashSet<Locale>(); // for (Voice voice : voices) { // locales.add(voice.getLocale()); // } // return locales; // } // }, null, "getAvailableLanguages"); return NOERROR; } ECode TextToSpeech::GetVoices( /* [out] */ ISet** voices) { VALIDATE_NOT_NULL(voices) assert(0 && "TODO"); // return runAction(new Action<Set<Voice>>() { // @Override // public Set<Voice> run(ITextToSpeechService service) throws RemoteException { // List<Voice> voices = service.getVoices(); // return (voices != null) ? new HashSet<Voice>(voices) : new HashSet<Voice>(); // } // }, null, "getVoices"); return NOERROR; } ECode TextToSpeech::SetVoice( /* [in] */ IVoice* voice, /* [out] */ Int32* ret) { assert(0 && "TODO"); // return runAction(new Action<Integer>() { // @Override // public Integer run(ITextToSpeechService service) throws RemoteException { // int result = service.loadVoice(getCallerIdentity(), voice.getName()); // if (result == SUCCESS) { // mParams.putString(Engine.KEY_PARAM_VOICE_NAME, voice.getName()); // // Set the language/country/variant, so #getLanguage will return the voice // // locale when called. // String language = ""; // try { // language = voice.getLocale().getISO3Language(); // } catch (MissingResourceException e) { // Log.w(TAG, "Couldn't retrieve ISO 639-2/T language code for locale: " + // voice.getLocale(), e); // } // String country = ""; // try { // country = voice.getLocale().getISO3Country(); // } catch (MissingResourceException e) { // Log.w(TAG, "Couldn't retrieve ISO 3166 country code for locale: " + // voice.getLocale(), e); // } // mParams.putString(Engine.KEY_PARAM_LANGUAGE, language); // mParams.putString(Engine.KEY_PARAM_COUNTRY, country); // mParams.putString(Engine.KEY_PARAM_VARIANT, voice.getLocale().getVariant()); // } // return result; // } // }, LANG_NOT_SUPPORTED, "setVoice"); return NOERROR; } ECode TextToSpeech::GetVoice( /* [out] */ IVoice** voice) { VALIDATE_NOT_NULL(voice) assert(0 && "TODO"); // return runAction(new Action<Voice>() { // @Override // public Voice run(ITextToSpeechService service) throws RemoteException { // String voiceName = mParams.getString(Engine.KEY_PARAM_VOICE_NAME, ""); // if (TextUtils.isEmpty(voiceName)) { // return null; // } // List<Voice> voices = service.getVoices(); // if (voices == null) { // return null; // } // for (Voice voice : voices) { // if (voice.getName().equals(voiceName)) { // return voice; // } // } // return null; // } // }, null, "getVoice"); return NOERROR; } ECode TextToSpeech::GetDefaultVoice( /* [out] */ IVoice** voice) { VALIDATE_NOT_NULL(voice) assert(0 && "TODO"); // return runAction(new Action<Voice>() { // @Override // public Voice run(ITextToSpeechService service) throws RemoteException { // String[] defaultLanguage = service.getClientDefaultLanguage(); // if (defaultLanguage == null || defaultLanguage.length == 0) { // Log.e(TAG, "service.getClientDefaultLanguage() returned empty array"); // return null; // } // String language = defaultLanguage[0]; // String country = (defaultLanguage.length > 1) ? defaultLanguage[1] : ""; // String variant = (defaultLanguage.length > 2) ? defaultLanguage[2] : ""; // // Sanitize the locale using isLanguageAvailable. // int result = service.isLanguageAvailable(language, country, variant); // if (result >= LANG_AVAILABLE){ // if (result < LANG_COUNTRY_VAR_AVAILABLE) { // variant = ""; // if (result < LANG_COUNTRY_AVAILABLE) { // country = ""; // } // } // } else { // // The default language is not supported. // return null; // } // // Get the default voice name // String voiceName = service.getDefaultVoiceNameFor(language, country, variant); // if (TextUtils.isEmpty(voiceName)) { // return null; // } // // Find it // List<Voice> voices = service.getVoices(); // if (voices == null) { // return null; // } // for (Voice voice : voices) { // if (voice.getName().equals(voiceName)) { // return voice; // } // } // return null; // } // }, null, "getDefaultVoice"); return NOERROR; } ECode TextToSpeech::IsLanguageAvailable( /* [in] */ ILocale* loc, /* [out] */ Int32* ret) { AutoPtr<TextToSpeechActionR> ttsActionR = new TextToSpeechActionRIsLanguageAvailable(this, loc); *ret = RunAction(ttsActionR.Get(), ITextToSpeech::LANG_NOT_SUPPORTED, String("isLanguageAvailable") ); return NOERROR; } ECode TextToSpeech::SynthesizeToFile( /* [in] */ ICharSequence* text, /* [in] */ IBundle* params, /* [in] */ IFile* filename, /* [in] */ const String& utteranceld, /* [out] */ Int32* ret) { #if 0 return runAction(new Action<Integer>() { @Override public Integer run(ITextToSpeechService service) throws RemoteException { ParcelFileDescriptor fileDescriptor; int returnValue; try { if(file.exists() && !file.canWrite()) { Log.e(TAG, "Can't write to " + file); return ERROR; } fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE); returnValue = service.synthesizeToFileDescriptor(getCallerIdentity(), text, fileDescriptor, getParams(params), utteranceId); fileDescriptor.close(); return returnValue; } catch (FileNotFoundException e) { Log.e(TAG, "Opening file " + file + " failed", e); return ERROR; } catch (IOException e) { Log.e(TAG, "Closing file " + file + " failed", e); return ERROR; } } }, ERROR, "synthesizeToFile"); #endif return NOERROR; } ECode TextToSpeech::SynthesizeToFile( /* [in] */ const String& text, /* [in] */ IHashMap* params, /* [in] */ const String& filename, /* [out] */ Int32* ret) { AutoPtr<TextToSpeechActionR> ttsActionR = new TextToSpeechActionRSynthesizeToFile(this, text, params, filename); *ret = (Int32)RunAction(ttsActionR.Get(), ITextToSpeech::TTS_ERROR, String("synthesizeToFile") ); return NOERROR; } AutoPtr<IBundle> TextToSpeech::ConvertParamsHashMaptoBundle( /* [in] */ IMap* params) { #if 0 Int32 paramsLen; if (params != NULL && ((params->GetSize(&paramsLen), paramsLen)!=0)) { AutoPtr<IBundle> bundle; CBundle::New(mParams, (IBundle**)&bundle); CopyIntParam(bundle.Get(), params, ITextToSpeechEngine::KEY_PARAM_STREAM ); CopyStringParam(bundle.Get(), params, ITextToSpeechEngine::KEY_PARAM_UTTERANCE_ID ); CopyFloatParam(bundle.Get(), params, ITextToSpeechEngine::KEY_PARAM_VOLUME ); CopyFloatParam(bundle.Get(), params, ITextToSpeechEngine::KEY_PARAM_PAN ); // Copy feature strings defined by the framework. CopyStringParam(bundle.Get(), params, ITextToSpeechEngine::KEY_FEATURE_NETWORK_SYNTHESIS ); CopyStringParam(bundle.Get(), params, ITextToSpeechEngine::KEY_FEATURE_EMBEDDED_SYNTHESIS ); // Copy over all parameters that start with the name of the // engine that we are currently connected to. The engine is // free to interpret them as it chooses. AutoPtr<ICharSequence> cs; CString::New(mCurrentEngine, (ICharSequence**)&cs); if (!TextUtils::IsEmpty(cs)) { AutoPtr< ArrayOf<String> > keys; AutoPtr<IObjectContainer> values; params -> GetAllItems((ArrayOf<String>**)&keys, (IObjectContainer**)&values); Int32 keysLen = keys->GetLength(); for(Int32 i=0; i<keysLen; i++) { if( ((*keys)[i]).StartWith(mCurrentEngine) ) { String val; AutoPtr<IInterface> csEx; params->Get((*keys)[i], (IInterface**)&csEx); bundle->PutString((*keys)[i], (ICharSequence::Probe(csEx)->ToString(&val), val)); } } } return bundle; } else { return mParams; } #endif return NULL; } void TextToSpeech::CopyStringParam( /* [in] */ IBundle* bundle, /* [in] */ IMap* params, /* [in] */ const String& key) { AutoPtr<IInterface> cs; AutoPtr<ICharSequence> skey; CString::New(key, (ICharSequence**)&skey); params->Get(skey, (IInterface**)&cs); String value; ICharSequence::Probe(cs)->ToString(&value); if (!value.IsNull()) { bundle->PutString(key, value); } } void TextToSpeech::CopyIntParam( /* [in] */ IBundle* bundle, /* [in] */ IMap* params, /* [in] */ const String& key) { AutoPtr<IInterface> cs; AutoPtr<ICharSequence> skey; CString::New(key, (ICharSequence**)&skey); params->Get(skey, (IInterface**)&cs); String valueString; ICharSequence::Probe(cs)->ToString(&valueString); if (!TextUtils::IsEmpty(valueString)) { //try { Int32 value = StringUtils::ParseInt32(valueString); bundle->PutInt32(key, value); //} catch (NumberFormatException ex) { // don't set the value in the bundle //} } } void TextToSpeech::CopyFloatParam( /* [in] */ IBundle* bundle, /* [in] */ IMap* params, /* [in] */ const String& key) { AutoPtr<IInterface> cs; AutoPtr<ICharSequence> skey; CString::New(key, (ICharSequence**)&skey); params->Get(skey, (IInterface**)&cs); String valueString; ICharSequence::Probe(cs)->ToString(&valueString); if (!TextUtils::IsEmpty(valueString)) { //try { Float value = StringUtils::ParseFloat(valueString); bundle->PutFloat(key, value); //} catch (NumberFormatException ex) { // don't set the value in the bundle //} } } ECode TextToSpeech::SetOnUtteranceCompletedListener( /* [in] */ ITextToSpeechOnUtteranceCompletedListener* listener, /* [out] */ Int32* ret) { mUtteranceProgressListener = UtteranceProgressListener::From(listener); *ret = ITextToSpeech::TTS_SUCCESS; return NOERROR; } ECode TextToSpeech::SetOnUtteranceProgressListener( /* [in] */ IUtteranceProgressListener* listener, /* [out] */ Int32* ret) { mUtteranceProgressListener = listener; *ret = ITextToSpeech::TTS_SUCCESS; return NOERROR; } ECode TextToSpeech::SetEngineByPackageName( /* [in] */ const String& enginePackageName, /* [out] */ Int32* ret) { mRequestedEngine = enginePackageName; *ret = InitTts(); return NOERROR; } ECode TextToSpeech::GetDefaultEngine( /* [out] */ String* engine) { //mEnginesHelper->GetDefaultEngine(&engine); return NOERROR; } ECode TextToSpeech::AreDefaultsEnforced( /* [out] */ Boolean* enforced) { *enforced = FALSE; return NOERROR; } ECode TextToSpeech::GetEngines( /* [out] */ IList** ret) { mEnginesHelper->GetEngines(ret); return NOERROR; } Int32 TextToSpeech::GetMaxSpeechInputLength() { return 4000; } } // namespace Tts } // namespace Speech } // namepsace Droid } // namespace Elastos
32.956669
178
0.61943
jingcao80
f27fbf234d770d6edc4402b271a95e0a0599243b
6,068
cpp
C++
Source/ComputeEngine/Cuda/Buffers/CudaHostBuffer.cpp
Fillo7/KTT
a0c252efb75a8366450e2df589f0ae641f015312
[ "MIT" ]
32
2017-09-12T23:52:52.000Z
2020-12-09T07:13:24.000Z
Source/ComputeEngine/Cuda/Buffers/CudaHostBuffer.cpp
Fillo7/KTT
a0c252efb75a8366450e2df589f0ae641f015312
[ "MIT" ]
23
2017-05-11T14:38:45.000Z
2021-02-03T13:45:14.000Z
Source/ComputeEngine/Cuda/Buffers/CudaHostBuffer.cpp
Fillo7/KTT
a0c252efb75a8366450e2df589f0ae641f015312
[ "MIT" ]
5
2017-11-06T12:40:05.000Z
2020-06-16T13:11:24.000Z
#ifdef KTT_API_CUDA #include <algorithm> #include <Api/KttException.h> #include <ComputeEngine/Cuda/Actions/CudaTransferAction.h> #include <ComputeEngine/Cuda/Buffers/CudaHostBuffer.h> #include <ComputeEngine/Cuda/CudaStream.h> #include <ComputeEngine/Cuda/CudaUtility.h> #include <Utility/ErrorHandling/Assert.h> #include <Utility/Logger/Logger.h> namespace ktt { CudaHostBuffer::CudaHostBuffer(KernelArgument& argument, IdGenerator<TransferActionId>& generator) : CudaBuffer(argument, generator), m_RawBuffer(nullptr) { Logger::LogDebug("Initializing CUDA host buffer with id " + std::to_string(m_Argument.GetId())); KttAssert(GetMemoryLocation() == ArgumentMemoryLocation::Host || GetMemoryLocation() == ArgumentMemoryLocation::HostZeroCopy, "Argument memory location mismatch"); if (GetMemoryLocation() == ArgumentMemoryLocation::Host) { CheckError(cuMemAllocHost(&m_RawBuffer, m_BufferSize), "cuMemAllocHost"); } else { m_RawBuffer = argument.GetData(); CheckError(cuMemHostRegister(m_RawBuffer, m_BufferSize, CU_MEMHOSTREGISTER_DEVICEMAP), "cuMemHostRegister"); } CheckError(cuMemHostGetDevicePointer(&m_Buffer, m_RawBuffer, 0), "cuMemHostGetDevicePointer"); } CudaHostBuffer::CudaHostBuffer(KernelArgument& argument, IdGenerator<TransferActionId>& generator, ComputeBuffer userBuffer) : CudaBuffer(argument, generator, userBuffer), m_RawBuffer(nullptr) { Logger::LogDebug("Initializing CUDA host buffer with id " + std::to_string(m_Argument.GetId())); KttAssert(GetMemoryLocation() == ArgumentMemoryLocation::Host || GetMemoryLocation() == ArgumentMemoryLocation::HostZeroCopy, "Argument memory location mismatch"); if (userBuffer == nullptr) { throw KttException("The provided user CUDA buffer is not valid"); } m_Buffer = reinterpret_cast<CUdeviceptr>(userBuffer); } CudaHostBuffer::~CudaHostBuffer() { Logger::LogDebug("Releasing CUDA host buffer with id " + std::to_string(m_Argument.GetId())); if (m_UserOwned) { return; } if (GetMemoryLocation() == ArgumentMemoryLocation::Host) { CheckError(cuMemFreeHost(m_RawBuffer), "cuMemFreeHost"); } else { CheckError(cuMemHostUnregister(m_RawBuffer), "cuMemHostUnregister"); } } std::unique_ptr<CudaTransferAction> CudaHostBuffer::UploadData(const CudaStream& stream, const void* source, const size_t dataSize) { Logger::LogDebug("Uploading data into CUDA host buffer with id " + std::to_string(m_Argument.GetId())); if (m_BufferSize < dataSize) { throw KttException("Size of data to upload is larger than size of buffer"); } const auto id = m_Generator.GenerateId(); auto action = std::make_unique<CudaTransferAction>(id); CheckError(cuEventRecord(action->GetStartEvent(), stream.GetStream()), "cuEventRecord"); CheckError(cuMemcpyHtoDAsync(m_Buffer, source, dataSize, stream.GetStream()), "cuMemcpyHtoDAsync"); CheckError(cuEventRecord(action->GetEndEvent(), stream.GetStream()), "cuEventRecord"); return action; } std::unique_ptr<CudaTransferAction> CudaHostBuffer::DownloadData(const CudaStream& stream, void* destination, const size_t dataSize) const { Logger::LogDebug("Downloading data from CUDA host buffer with id " + std::to_string(m_Argument.GetId())); if (m_BufferSize < dataSize) { throw KttException("Size of data to download is larger than size of buffer"); } const auto id = m_Generator.GenerateId(); auto action = std::make_unique<CudaTransferAction>(id); CheckError(cuEventRecord(action->GetStartEvent(), stream.GetStream()), "cuEventRecord"); CheckError(cuMemcpyDtoHAsync(destination, m_Buffer, dataSize, stream.GetStream()), "cuMemcpyDtoHAsync"); CheckError(cuEventRecord(action->GetEndEvent(), stream.GetStream()), "cuEventRecord"); return action; } std::unique_ptr<CudaTransferAction> CudaHostBuffer::CopyData(const CudaStream& stream, const CudaBuffer& source, const size_t dataSize) { Logger::LogDebug("Copying data into CUDA host buffer with id " + std::to_string(m_Argument.GetId()) + " from buffer with id " + std::to_string(source.GetArgumentId())); if (m_BufferSize < dataSize) { throw KttException("Size of data to copy is larger than size of target buffer"); } if (source.GetSize() < dataSize) { throw KttException("Size of data to copy is larger than size of source buffer"); } const auto id = m_Generator.GenerateId(); auto action = std::make_unique<CudaTransferAction>(id); CheckError(cuEventRecord(action->GetStartEvent(), stream.GetStream()), "cuEventRecord"); CheckError(cuMemcpyDtoDAsync(m_Buffer, *source.GetBuffer(), dataSize, stream.GetStream()), "cuMemcpyDtoDAsync"); CheckError(cuEventRecord(action->GetEndEvent(), stream.GetStream()), "cuEventRecord"); return action; } void CudaHostBuffer::Resize(const size_t newSize, const bool preserveData) { Logger::LogDebug("Resizing CUDA host buffer with id " + std::to_string(m_Argument.GetId())); if (m_UserOwned) { throw KttException("Resize operation on user owned buffer is not supported"); } if (GetMemoryLocation() == ArgumentMemoryLocation::HostZeroCopy) { throw KttException("Resize operation on registered host buffer is not supported"); } if (m_BufferSize == newSize) { return; } void* newRawBuffer = nullptr; CUdeviceptr newBuffer; CheckError(cuMemAllocHost(&newRawBuffer, newSize), "cuMemAllocHost"); CheckError(cuMemHostGetDevicePointer(&newBuffer, newRawBuffer, 0), "cuMemHostGetDevicePointer"); if (preserveData) { CheckError(cuMemcpyDtoD(newBuffer, m_Buffer, std::min(m_BufferSize, newSize)), "cuMemcpyDtoD"); } CheckError(cuMemFreeHost(m_RawBuffer), "cuMemFreeHost"); m_RawBuffer = newRawBuffer; m_Buffer = newBuffer; m_BufferSize = newSize; } } // namespace ktt #endif // KTT_API_CUDA
34.477273
129
0.718029
Fillo7
f28063be1c33da920e061d3032c0093b2f9306ad
28
cpp
C++
PGTProject/Source/PGTProject/MouseController.cpp
dylanpiera/IVGT6
b5696222d53a0d3a8369b8c5eb9e35c03e8afab8
[ "MIT" ]
null
null
null
PGTProject/Source/PGTProject/MouseController.cpp
dylanpiera/IVGT6
b5696222d53a0d3a8369b8c5eb9e35c03e8afab8
[ "MIT" ]
null
null
null
PGTProject/Source/PGTProject/MouseController.cpp
dylanpiera/IVGT6
b5696222d53a0d3a8369b8c5eb9e35c03e8afab8
[ "MIT" ]
null
null
null
#include "MouseController.h"
28
28
0.821429
dylanpiera
f281acac1787036957d6edba0581e7c13580b91f
24,586
cpp
C++
Documents/RacimoAire/RacimoAire3/racimo3.cpp
JoseSalamancaCoy/RACIMO_AIRE
628d6ff184a30af0efd25bff675b0006500d4ba2
[ "MIT" ]
null
null
null
Documents/RacimoAire/RacimoAire3/racimo3.cpp
JoseSalamancaCoy/RACIMO_AIRE
628d6ff184a30af0efd25bff675b0006500d4ba2
[ "MIT" ]
null
null
null
Documents/RacimoAire/RacimoAire3/racimo3.cpp
JoseSalamancaCoy/RACIMO_AIRE
628d6ff184a30af0efd25bff675b0006500d4ba2
[ "MIT" ]
null
null
null
#include "racimo3.h" Racimo3::Racimo3(QObject *parent) : QObject(parent) { blinkLed = false; AlertRAM = false; AlertTemperatura = false; NewData = false; InitAPP =true; AlertWifi =false; _timeoutlectura =false; AlertPMS=false; AlertOPC=false; ShutdownManual=false; RebootManual=false; _CerrarApp=false; Delta_muestra_muestra = 10000; contReboot_rstApp = 0; MetaData._StatusWIFI =false; contReboot_rstApp = 0; BlinkLeds = new QTimer; BlinkLeds->setInterval(250); BlinkLeds->start(); connect(BlinkLeds,&QTimer::timeout,this, &Racimo3::Blink); RA_cGPIO1 = new Crpigpio(true,this); RA_cGPIO2 = new Crpigpio(false,this); RA_cGPIO3 = new Crpigpio(false,this); _DataJson2 = new DataJson2("/home/pi/RACIMOAIRE/Configuracion/JsonBase.json","/home/pi/RACIMOAIRE/"); RA_cGPIO1->SetPinMode(GPIOWiFi,PI_OUTPUT); RA_cGPIO1->SetPinMode(GPIOTransmision,PI_OUTPUT); RA_cGPIO1->SetPinMode(GPIOButton,PI_INPUT); //Configura como entrada RA_cGPIO1->SetPullUpDown(GPIOButton,PI_PUD_DOWN); //Abilita resistencias de positivo RA_cGPIO1->SetISRgpio(GPIOButton,2,100000); //Configura la interrupcion (pin,flanco,timeout uS) flanco=0 = rising connect(RA_cGPIO1,&Crpigpio::OnCallBackISR, this, &Racimo3::OnISR); RA_cPMS = new PMS(RA_cGPIO1,GPIOPMSSet, GPIOPMSReSet, GPIOPMSRX,Delta_muestra_muestra); RA_cGPS = new GPS(RA_cGPIO1, GPIOGPSRX, GPIOGPSPPS); RA_cOPC = new OPCN2(RA_cGPIO1,0,0); RA_cBME280 = new Adafruit_BME280(RA_cGPIO1,0x77); RA_cOPC->setFanAndLaserOff(); RA_cPMS->sleep(); RA_cGADC = new ADS1115(RA_cGPIO2); RA_cGADC->setGain(GAIN_TWOTHIRDS); RA_cGADC->setRate(RATE_128); // 128SPS (default) RA_cGADC->setOSMode(OSMODE_SINGLE); // Set to start a single-conversion RA_cCorriente = new Adafruit_INA219(RA_cGPIO3); uint32_t MuestraPromedio = (3*60000) + 20000 ; RA_cDataParticulado1 = new DataParticulado(RA_cOPC , RA_cPMS ,Delta_muestra_muestra, MuestraPromedio,this); RA_cDataParticulado1->Pasivo(); DateTimer = new CDateTimer("/home/pi/RACIMOAIRE/Configuracion/TimeConfig.txt",this); connect(DateTimer,&CDateTimer::timeout, this, &Racimo3::Muestra); TimeoutLectura = new QTimer(); TimeoutLectura->setInterval(250000); connect(TimeoutLectura,&QTimer::timeout, this, &Racimo3::setTimeoutlectura); TimerAlertWifi = new QTimer; TimerAlertWifi->setInterval(60000); connect(TimerAlertWifi, &QTimer::timeout, this, &Racimo3::timeoutAlertWifi); Timer = new QTimer(); Timer->setInterval(500); Timer->start(); connect(RA_cDataParticulado1,&DataParticulado::DataOk,this, &Racimo3::DataOk1); connect(RA_cDataParticulado1,&DataParticulado::DataOkPMS,this, &Racimo3::DataParticuladoOkPMS1); connect(RA_cDataParticulado1,&DataParticulado::DataOkOPC,this, &Racimo3::DataParticuladoOkOPC1); connect(Timer, &QTimer::timeout, this, &Racimo3::Show); TimeDataLogs =new QTimer; TimeDataLogs->setInterval(5000); TimeDataLogs->start(); LogsThread = new LogsSystem(this); connect(TimeDataLogs,&QTimer::timeout, this, &Racimo3::DataLogs); connect(LogsThread,&LogsSystem::SignalTemperatura,this, &Racimo3::SlotTemperatura); connect(LogsThread,&LogsSystem::SignalRAM,this, &Racimo3::SlotRAM); connect(LogsThread,&LogsSystem::SignalProcesos,this, &Racimo3::SlotProcesos); connect(LogsThread,&LogsSystem::SignalSOCKET,this, &Racimo3::SlotSOCKET); connect(LogsThread,&LogsSystem::SignalStatusWIFI,this, &Racimo3::SlotStatusWIFI); connect(LogsThread,&LogsSystem::SignalEspacioDisco,this, &Racimo3::SlotEspacioDisco); connect(RA_cGPS, &GPS::newData,this, &Racimo3::newDataGPS); LogsThread->start(QThread::HighPriority); RstData(); Serial =new NextionRaspberrypi(RA_cGPIO1,9600,15); nexInit(Serial); txt_temp = new NexText(Serial,0,9,"t7"); txt_Presion = new NexText(Serial,0,10,"t8"); txt_hum = new NexText(Serial,0,13,"t11"); txt_longitud = new NexText(Serial,0,15,"t13"); txt_latitud = new NexText(Serial,0,18,"t16"); txt_Altitud = new NexText(Serial,0,19,"t17"); txt_Fix = new NexText(Serial,0,17,"t15"); txt_wifi = new NexText(Serial,0,20,"t18"); txt_PM25_P = new NexText(Serial,0,25,"t23"); txt_PM25_O = new NexText(Serial,0,29,"t27"); txt_PM10_P = new NexText(Serial,0,26,"t24"); txt_PM10_0 = new NexText(Serial,0,30,"t28"); txt_temp->setText("null");QThread::msleep(10); txt_Presion->setText("null");QThread::msleep(10); txt_hum->setText("null");QThread::msleep(10); txt_longitud->setText("null");QThread::msleep(10); txt_latitud->setText("null");QThread::msleep(10); txt_Altitud->setText("null");QThread::msleep(10); txt_Fix->setText("0");QThread::msleep(10); txt_wifi->setText("No");QThread::msleep(10); txt_PM25_P->setText("null");QThread::msleep(10); txt_PM25_O->setText("null");QThread::msleep(10); txt_PM10_P->setText("null");QThread::msleep(10); txt_PM10_0->setText("null");QThread::msleep(10); QTimer::singleShot(4*1000,this,SLOT(check_InitAPP())); } Racimo3::~Racimo3() { RA_cOPC->setFanAndLaserOff(); RA_cPMS->sleep(); delete RA_cBME280; delete RA_cGPS; delete _DataJson2; delete RA_cDataParticulado1; delete RA_cOPC; delete RA_cPMS; delete RA_cGADC; delete RA_cCorriente; delete txt_hum; delete txt_Presion; delete txt_temp; delete txt_longitud; delete txt_latitud; delete txt_Altitud; delete txt_Fix; delete txt_wifi; delete txt_PM25_P; delete txt_PM25_O; delete txt_PM10_P; delete txt_PM10_0; delete Serial; delete RA_cGPIO1; delete this; } bool Racimo3:: POSTHttp(char *charjson) { CURL *hnd = curl_easy_init(); if(hnd) { curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); curl_easy_setopt(hnd, CURLOPT_URL, "http://racimo.mpsig.com:3000/racimohub/v013dev/datasets"); struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "Postman-Token: d75df676-a5e1-448a-8b70-177609f83454"); headers = curl_slist_append(headers, "Cache-Control: no-cache"); headers = curl_slist_append(headers, "Content-Type: application/json"); curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, charjson ); //Envio CURLcode ret = curl_easy_perform(hnd); if(ret != CURLE_OK) return false; curl_easy_cleanup(hnd); curl_global_cleanup(); return true; } return false; } void Racimo3::SetHora() { system("GetHttpCurl >/home/pi/RACIMOAIRE/DataIntercambio/FechaHora.json"); QFile ArchivoFechaHora("/home/pi/RACIMOAIRE/DataIntercambio/FechaHora.json"); if(!ArchivoFechaHora.open(QIODevice::ReadOnly | QIODevice::Text)) { return; } QJsonObject obj; QJsonDocument doc = QJsonDocument::fromJson(QString(ArchivoFechaHora.readAll()).toUtf8()); // check validity of the document if(!doc.isNull()) { if(doc.isObject()) { obj = doc.object(); } else { qDebug() << "Document is not an object" << endl; } } else { qDebug() << "Invalid JSON...\n" << QString(ArchivoFechaHora.readAll()) << endl; } QDateTime DateTime = QDateTime::fromString(obj.value("fechahora").toString(),Qt::DateFormat::ISODate); QString StringFechaHora =DateTime.toLocalTime().toString(Qt::DateFormat::ISODate).replace('T',' '); char SetHora[38]; sprintf(SetHora,"sudo date --set \"%s\"",StringFechaHora.toStdString().c_str()); qDebug() <<"SetHora en "<<StringFechaHora; system(SetHora); } void Racimo3::check_InitAPP() { if(RA_cBME280->InitOk() < 0) { _DataJson2->SetDato("alert","Falla al iniciar BME280"); StateBME280 =false; NewData =true; } else StateBME280 =true; if(RA_cCorriente->getInitOK() < 0) { _DataJson2->SetDato("alert","Falla al iniciar IN219"); NewData =true; StateINA219 =false; } else StateINA219 =true; if(RA_cGADC->getInitOk() < 0) { _DataJson2->SetDato("alert","Falla al iniciar ADS1115"); NewData =true; StateADS1115 =false; } else StateADS1115 =true; QFile file("/home/pi/RACIMOAIRE/RSTRaspi.txt"); if(!file.open(QIODevice::ReadOnly|QIODevice::Text)) { _DataJson2->SetDato("alert","Inicio de App por cierre inesperado"); qDebug() << "Inicio de App por cierre inesperado"; NewData = true; //habilita la transmision } else { _DataJson2->SetDato("alert","Inicio de App por reboot"); file.close(); system("rm /home/pi/RACIMOAIRE/RSTRaspi.txt"); qDebug() << "Inicio de App por rst inesperado"; NewData = true; //habilita la transmision } _DataJson2->WriteJson(); // genera un .json _DataJson2->ClearArray(); //elimino cualquier dato cargado en el buffer DateTimer->StartTimer(); } bool Racimo3::Transmision() {\ QStringList _DataJsonString; if(_DataJson2->readJson(&_DataJsonString)) qDebug() << "Se leyeron los archivos Json"; else qDebug() << "Problemas al leer los archivo Json"; for(int i=0;i<_DataJsonString.length() ; i++) { std::string STR = QString(_DataJsonString.operator [](i)).toStdString(); char *String = new char[STR.length() + 1]; strcpy(String, STR.c_str());; qDebug() << String; if(!POSTHttp(String)) return false; delete [] String; } return true; } void Racimo3::SabeDataCsv() { /* QFile file("/home/pi/PMS.csv"); if(!file.open(QIODevice::Append|QIODevice::Text)) { qDebug() << "Error al abrir el archivo"; return; } QString str; str=""; str += QString::number(PMS_PM1) + ";"; str += QString::number(PMS_PM2_5) + ";"; str += QString::number(PMS_PM10) + ";"; str+= QDateTime::currentDateTimeUtc().toString(Qt::ISODate).replace("Z","."+QString::number(QTime::currentTime().msec())+"Z"); str+="\n"; QTextStream Strem(&file); Strem << str; file.close(); QFile file2("/home/pi/OPC.csv"); if(!file2.open(QIODevice::Append|QIODevice::Text)) { qDebug() << "Error al abrir el archivo"; return; } QString str2; str2=""; str2 += QString::number(OPC_PM1) + ";"; str2 += QString::number(OPC_PM2_5) + ";"; str2 += QString::number(OPC_PM10) + ";"; str2+= QDateTime::currentDateTimeUtc().toString(Qt::ISODate).replace("Z","."+QString::number(QTime::currentTime().msec())+"Z"); str2+="\n"; QTextStream Strem2(&file2); Strem2 << str2; file2.close();*/ } void Racimo3::RstData() { PMS_PM1 = 0.0; PMS_PM2_5 = 0.0; PMS_PM10 =0.0; OPC_PM1 = 0.0; OPC_PM2_5 = 0.0; OPC_PM10 =0.0; Check_PMS = false; Check_OPC =false; } void Racimo3::checkRst_App_Raspi() { if(contReboot_rstApp == 2) { _CerrarApp = true; _DataJson2->SetDato("alert", "Alerta Cerrando app manualmente"); _DataJson2->WriteJson(); _DataJson2->ClearArray(); NewData = true; BlinkLeds->stop(); QTimer::singleShot(20*1000,this,SLOT(CerrarApp())); Blink(); } else { if(contReboot_rstApp == 3) { NewData = true; BlinkLeds->stop(); RebootManual=true; _DataJson2->SetDato("alert", "Alerta Reboot manual inminente"); _DataJson2->WriteJson(); _DataJson2->ClearArray(); QTimer::singleShot(20*1000,this,SLOT(ReinicioRaspi())); Blink(); } } contReboot_rstApp = 0; } void Racimo3::OnISR(int gpio,int level,quint32 timeout) { switch (gpio) { case GPIOButton: if(level) { TimePushButton.start(); if(contReboot_rstApp == 0) QTimer::singleShot(4*1000,this,SLOT(checkRst_App_Raspi())); } else { int mseconds = TimePushButton.elapsed(); if(mseconds>=2000 && mseconds<=5000) { _DataJson2->SetDato("alert", "Alerta apagado manual inminente"); _DataJson2->WriteJson(); _DataJson2->ClearArray(); ShutdownManual =true; BlinkLeds->stop(); NewData = true; QTimer::singleShot(20*1000,this,SLOT(ShutdownRaspi())); Blink(); } if(mseconds<=1500) contReboot_rstApp++; qDebug() << contReboot_rstApp; } break; default: break; } return; qDebug()<< timeout; } void Racimo3::Blink() { if(RebootManual) { for(int i=0; i<18; i++){ RA_cGPIO1->WriteGpio(GPIOWiFi,PI_OFF); RA_cGPIO1->WriteGpio(GPIOTransmision,PI_ON); QThread::msleep(200); RA_cGPIO1->WriteGpio(GPIOWiFi,PI_ON); RA_cGPIO1->WriteGpio(GPIOTransmision,PI_OFF); QThread::msleep(200); RA_cGPIO1->WriteGpio(GPIOWiFi,PI_OFF); RA_cGPIO1->WriteGpio(GPIOTransmision,PI_OFF); QThread::msleep(500); } } if(ShutdownManual) { for(int i=0; i<50;i++){ RA_cGPIO1->WriteGpio(GPIOWiFi,PI_ON); RA_cGPIO1->WriteGpio(GPIOTransmision,PI_ON); QThread::msleep(200); RA_cGPIO1->WriteGpio(GPIOWiFi,PI_OFF); RA_cGPIO1->WriteGpio(GPIOTransmision,PI_OFF); QThread::msleep(200); } } if(_CerrarApp) { for(int i=0; i <8 ; i++){ RA_cGPIO1->WriteGpio(GPIOWiFi,PI_OFF); RA_cGPIO1->WriteGpio(GPIOTransmision,PI_ON); QThread::msleep(200); RA_cGPIO1->WriteGpio(GPIOTransmision,PI_OFF); QThread::msleep(200); RA_cGPIO1->WriteGpio(GPIOTransmision,PI_ON); QThread::msleep(200); RA_cGPIO1->WriteGpio(GPIOTransmision,PI_OFF); QThread::msleep(200); RA_cGPIO1->WriteGpio(GPIOWiFi,PI_ON); QThread::msleep(200); RA_cGPIO1->WriteGpio(GPIOWiFi,PI_OFF); QThread::msleep(200); RA_cGPIO1->WriteGpio(GPIOTransmision,PI_ON); QThread::msleep(200); RA_cGPIO1->WriteGpio(GPIOTransmision,PI_OFF); QThread::msleep(500); } } blinkLed = !blinkLed; if(AlertWifi) RA_cGPIO1->WriteGpio(GPIOWiFi,PI_OFF); else RA_cGPIO1->WriteGpio(GPIOWiFi,blinkLed); if(NewData) RA_cGPIO1->WriteGpio(GPIOTransmision,PI_ON); else RA_cGPIO1->WriteGpio(GPIOTransmision,PI_OFF); } void Racimo3::timeoutAlertWifi() { AlertWifi = true; TimerAlertWifi->stop(); _DataJson2->SetDato("alert", "Alerta sin acceso a internet"); } void Racimo3::DataOk1() { } void Racimo3::DataParticuladoOkPMS1(float PM1Promedio, float PM2_5Promedio, float PM10Promedio) { PMS_PM1 = PM1Promedio; PMS_PM2_5 = PM2_5Promedio; PMS_PM10 = PM10Promedio; Check_PMS=true; qDebug() << QString("Data PMS1 PM1 = %1 PM2_5 = %2 PM10 = %3 ").arg(PM1Promedio).arg(PM2_5Promedio).arg(PM10Promedio); _DataJson2->SetDato(_DataJson2->PM10_A,PMS_PM10); _DataJson2->SetDato(_DataJson2->PM2_5_A,PMS_PM2_5); _DataJson2->SetDato(_DataJson2->PM1_A,PMS_PM1); txt_PM25_P->setText(QString::number(static_cast<int>(PM2_5Promedio)).toStdString().c_str()); txt_PM10_P->setText(QString::number(static_cast<int>(PM10Promedio)).toStdString().c_str()); } void Racimo3::DataParticuladoOkOPC1(float PM1Promedio, float PM2_5Promedio, float PM10Promedio) { OPC_PM1 = PM1Promedio; OPC_PM2_5 = PM2_5Promedio; OPC_PM10 = PM10Promedio; qDebug() << QString("Data OPC1 PM1 = %1 PM2_5 = %2 PM10 = %3 ").arg(PM1Promedio).arg(PM2_5Promedio).arg(PM10Promedio); Check_OPC= true; _DataJson2->SetDato(_DataJson2->PM10,OPC_PM10); _DataJson2->SetDato(_DataJson2->PM2_5, OPC_PM2_5); _DataJson2->SetDato(_DataJson2->PM1,OPC_PM1); txt_PM25_O->setText(QString::number(PM2_5Promedio).toStdString().c_str()); txt_PM10_0->setText(QString::number(PM10Promedio).toStdString().c_str()); } void Racimo3::setTimeoutlectura() { _timeoutlectura = true; } void Racimo3::Muestra() { RA_cDataParticulado1->Muestra(); TimeoutLectura->start(); QThread::msleep(300); uint16_t CH1 = RA_cGADC->Measure_SingleEnded(0); uint16_t CH2 = RA_cGADC->Measure_SingleEnded(1); uint16_t CH3 = RA_cGADC->Measure_SingleEnded(2); uint16_t CH4 = RA_cGADC->Measure_SingleEnded(3); int16_t Corriente =RA_cCorriente->getCurrent_mA(); qDebug() << "Corriente" << Corriente; if(RA_cCorriente->getInitOK() >= 0) { _DataJson2->SetDato("c",Corriente*-1); if(!StateINA219) { _DataJson2->SetDato("alert", "Alerta INA219 Reconectado"); StateINA219 =true; } } else { if(StateINA219) { _DataJson2->SetDato("alert", "Alerta INA219 Desconectado"); StateINA219 =false; } if(RA_cCorriente->getInitOK() >= 0) _DataJson2->SetDato("alert", "INA219 Reconectado"); } if(RA_cGADC->getInitOk()>= 0) { _DataJson2->SetDato("v_O",CH1*(6.144/32767)*1.6666); _DataJson2->SetDato("v_P",CH2*(6.144/32767)*1.6666); _DataJson2->SetDato("v_B",CH3*(6.144/32767)); _DataJson2->SetDato("v_G",CH4*(6.144/32767)); if(!StateADS1115) { _DataJson2->SetDato("alert", "Alerta ADS115 Reconectado"); StateADS1115 =true; } } else { if(StateADS1115) { _DataJson2->SetDato("alert", "Alerta ADS1115 Desconectado"); StateADS1115 =false; } } } //Despliegue de datos void Racimo3::Show() { if( _timeoutlectura || (Check_PMS && Check_OPC)) { if(_timeoutlectura) { if(!Check_PMS){ if(!AlertPMS) _DataJson2->SetDato("alert", "Fallo PMS no responde"); AlertPMS = true; } else { if(AlertPMS) _DataJson2->SetDato("alert", "Alerta PMS activo"); AlertPMS = false; } if(!Check_OPC){ if(!AlertOPC) _DataJson2->SetDato("alert", "Fallo OPC no responde"); AlertOPC = true; } else { if(AlertOPC) _DataJson2->SetDato("alert", "Alerta OPC activo"); AlertOPC = false; } } TimeoutLectura->stop(); _timeoutlectura= false; RA_cBME280->takeForcedMeasurement(); float Humedad = RA_cBME280->readHumidity(); RA_cBME280->takeForcedMeasurement(); float Temperatura = RA_cBME280->readTemperature(); RA_cBME280->takeForcedMeasurement(); float Presion = RA_cBME280->readPressure()/100.0F; RA_cBME280->takeForcedMeasurement(); float Altura = RA_cBME280->readAltitude(1013.25); if(Humedad!=0 && Temperatura!=0 && Presion!=0 && (RA_cBME280->InitOk() >= 0) ) { _DataJson2->SetDato(_DataJson2->Temperatura,Temperatura); _DataJson2->SetDato(_DataJson2->Humedad, Humedad); _DataJson2->SetDato(_DataJson2->Presion, Presion); _DataJson2->SetDato("a_BME", Altura); txt_temp->setText(QString::number(Temperatura).toStdString().c_str()); txt_Presion->setText(QString::number(Presion).toStdString().c_str()); txt_hum->setText(QString::number(Humedad).toStdString().c_str()); if(!StateBME280) { _DataJson2->SetDato("alert", "Alerta BME280 Reconectado"); StateBME280 =true; } } else { txt_temp->setText("null"); txt_Presion->setText("null"); txt_hum->setText("null"); if(StateBME280) { _DataJson2->SetDato("alert", "Alerta BME280 Desconectado"); StateBME280 =false; } } if(_DataGPS.fix !=0) { _DataGPS.fix = 0; _DataJson2->SetDato(_DataJson2->longitud, _DataGPS.longitud); _DataJson2->SetDato(_DataJson2->latitud, _DataGPS.latitud); _DataJson2->SetDato("a_GPS", _DataGPS.altura); _DataJson2->SetDato("fixgps", _DataGPS.fix); } else txt_Fix->setText("null"); _DataJson2->SetDato("l_t",MetaData._Temperatura); _DataJson2->SetDato("l_r",MetaData._RAM); _DataJson2->SetDato("l_s",MetaData._SOCKET); _DataJson2->SetDato("l_p",MetaData._Procesos); _DataJson2->SetDato("l_e",MetaData._EspacioDisco); if(_DataJson2->WriteJson()) { qDebug() << "Escribio archivo Json \n"; } else qDebug() << "Problemas al escribir archivo JSon \n"; _DataJson2->ClearArray(); NewData=true; SabeDataCsv(); RstData(); DateTimer->StartTimer(); } } void Racimo3::DataLogs() { LogsThread->CheckESpacioDisco(); LogsThread->CheckProcesos(); LogsThread->CheckRAM(); LogsThread->CheckSOCKET(); LogsThread->CheckStatusWIFI(); LogsThread->CheckTemperatura(); if(MetaData._StatusWIFI) { txt_wifi->setText("Si"); if(InitAPP){ SetHora(); InitAPP =false; DateTimer->StartTimer(); } TimerAlertWifi->stop(); if(AlertWifi) _DataJson2->SetDato("alert", "Alerta con acceso a internet"); AlertWifi =false; if(NewData) { if(Transmision()) { _DataJson2->ClearJson(); RA_cGPIO1->WriteGpio(GPIOTransmision,PI_OFF); NewData=false; } else _DataJson2->SetDato("alert", "Falla al transmitir datos"); } } else { txt_wifi->setText("No"); if(!AlertWifi && !TimerAlertWifi->isActive()) TimerAlertWifi->start(); // solo se inicia una vez cada que se queda sin internet por mas de 1 minuto } } void Racimo3::newDataGPS() { txt_longitud->setText(QString::number(RA_cGPS->longitudeDegrees).toStdString().c_str()); txt_latitud->setText(QString::number(RA_cGPS->latitudeDegrees).toStdString().c_str()); txt_Altitud->setText(QString::number(RA_cGPS->altitude).toStdString().c_str()); txt_Fix->setText(QString::number(static_cast<int>(RA_cGPS->fixquality)).toStdString().c_str()); _DataGPS.fix = RA_cGPS->fixquality; _DataGPS.longitud = QString::number(RA_cGPS->longitudeDegrees); _DataGPS.longitud = QString::number(RA_cGPS->longitudeDegrees); _DataGPS.altura = RA_cGPS->altitude; } void Racimo3::SlotTemperatura(float temperatura) { //qDebug() << "temperatura =" << temperatura; MetaData._Temperatura =temperatura; if(temperatura > 75){ if(!AlertTemperatura)QTimer::singleShot(40*1000,this,SLOT(check_AlertTemperatura())); AlertTemperatura = true; } } void Racimo3::SlotRAM(float RAM) { //qDebug() << "RAM =" << RAM; MetaData._RAM =RAM; if(RAM > 60){ if(!AlertRAM)QTimer::singleShot(4*1000,this,SLOT(check_AlertRAM())); AlertRAM = true; } } void Racimo3::SlotSOCKET(int SOCKET) { //qDebug() << "SOCKET =" << SOCKET; MetaData._SOCKET =SOCKET; } void Racimo3::SlotProcesos(int Procesos) { //qDebug() << "Procesos =" << Procesos; MetaData._Procesos = Procesos; } void Racimo3::SlotStatusWIFI(bool StatusWIFI) { //qDebug() << "StatusWIFI =" << StatusWIFI; MetaData._StatusWIFI =StatusWIFI; } void Racimo3::SlotEspacioDisco(int EspacioDisco) { //qDebug() << "EspacioDisco =" << EspacioDisco; MetaData._EspacioDisco =EspacioDisco; } void Racimo3::check_AlertRAM() { if(MetaData._RAM > 60) { _DataJson2->SetDato("alert", "Alerta excesivo consumo de RAM reinicio inminente!"); _DataJson2->WriteJson(); NewData= true; QTimer::singleShot(30*1000,this,SLOT(ReinicioRaspi())); } else AlertRAM =false; } void Racimo3::check_AlertTemperatura() { if(MetaData._Temperatura > 75 ) { _DataJson2->SetDato("alert", "Alerta temperatura muy alta reinicio inminente!"); _DataJson2->WriteJson(); NewData= true; QTimer::singleShot(30*1000,this,SLOT(ReinicioRaspi())); } else AlertTemperatura =false; } void Racimo3::ReinicioRaspi() { system("sudo reboot now"); } void Racimo3::ShutdownRaspi() { system("sudo shutdown now"); } void Racimo3::CerrarApp() { this->~Racimo3(); }
30.093023
155
0.630684
JoseSalamancaCoy
f28555de74b1b2fb5fa20b7fd70783d3c45f9e84
3,116
cpp
C++
code_reading/oceanbase-master/deps/oblib/src/common/row/ob_row_util.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/deps/oblib/src/common/row/ob_row_util.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/deps/oblib/src/common/row/ob_row_util.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
1
2020-10-18T12:59:31.000Z
2020-10-18T12:59:31.000Z
/** * Copyright (c) 2021 OceanBase * OceanBase CE is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #define USING_LOG_PREFIX COMMON #include "common/row/ob_row_util.h" #include "common/cell/ob_cell_reader.h" namespace oceanbase { namespace common { int ObRowUtil::convert(const ObString& compact_row, ObNewRow& row) { return convert(compact_row.ptr(), compact_row.length(), row); } int ObRowUtil::convert(const char* compact_row, int64_t buf_len, ObNewRow& row) { int ret = OB_SUCCESS; ObCellReader cell_reader; bool is_row_finished = false; uint64_t column_id = OB_INVALID_ID; int64_t cell_idx = 0; ObObj cell; if (OB_FAIL(cell_reader.init(compact_row, buf_len, DENSE))) { LOG_WARN("fail to init cell reader", K(ret)); } while (OB_SUCC(ret) && !is_row_finished && OB_SUCC(cell_reader.next_cell())) { if (OB_FAIL(cell_reader.get_cell(column_id, cell, &is_row_finished))) { LOG_WARN("failed to get cell", K(column_id), K(ret)); } else if (is_row_finished) { ret = OB_SUCCESS; } else if (cell_idx < row.count_) { row.cells_[cell_idx++] = cell; } else { ret = OB_ERR_UNEXPECTED; LOG_WARN("accept row column count is not enough", K(ret), K(cell_idx), K_(row.count)); } } return ret; } int ObRowUtil::compare_row(const ObNewRow& lrow, const ObNewRow& rrow, int& cmp) { int ret = OB_SUCCESS; if (OB_UNLIKELY(lrow.is_invalid()) || OB_UNLIKELY(rrow.is_invalid())) { ret = OB_ERR_UNEXPECTED; LOG_WARN("lrow or rrow is invalid", K(lrow.is_invalid()), K(rrow.is_invalid())); } else { int64_t cmp_cnt = lrow.get_count() >= rrow.get_count() ? lrow.get_count() : rrow.get_count(); int64_t min_cnt = lrow.get_count() < rrow.get_count() ? lrow.get_count() : rrow.get_count(); for (int64_t i = 0; 0 == cmp && i < cmp_cnt; ++i) { if (i < min_cnt) { // Oracle compatible range partition, the null value is only allowed to be inserted when the range partition // defines maxvalue, so the null value is regarded as max if (lib::is_oracle_mode() && lrow.get_cell(i).is_null() && !rrow.get_cell(i).is_max_value()) { cmp = 1; } else if (lib::is_oracle_mode() && rrow.get_cell(i).is_null() && !lrow.get_cell(i).is_max_value()) { cmp = -1; } else { cmp = lrow.get_cell(i).compare(rrow.get_cell(i)); } } else if (i < lrow.get_count()) { cmp = lrow.get_cell(i).is_min_value() ? 0 : 1; } else { // i < rrow.get_count() && i >= lrow.get_count() cmp = rrow.get_cell(i).is_min_value() ? 0 : -1; } } } return ret; } } // end namespace common } // end namespace oceanbase
37.095238
116
0.655969
wangcy6
f288f316e84250c8338dbd3aa811a652e0fb2ae5
901
hpp
C++
src/cpp/ee/adjust/AdjustConfig.hpp
enrevol/ee-x
60a66ad3dc6e14802a7c5d8d585a8499be13f5b8
[ "MIT" ]
null
null
null
src/cpp/ee/adjust/AdjustConfig.hpp
enrevol/ee-x
60a66ad3dc6e14802a7c5d8d585a8499be13f5b8
[ "MIT" ]
null
null
null
src/cpp/ee/adjust/AdjustConfig.hpp
enrevol/ee-x
60a66ad3dc6e14802a7c5d8d585a8499be13f5b8
[ "MIT" ]
null
null
null
// // AdjustConfig.hpp // Adjust // // Created by eps on 8/19/20. // #ifndef EE_X_ADJUST_CONFIG_HPP #define EE_X_ADJUST_CONFIG_HPP #ifdef __cplusplus #include <string> #include "ee/adjust/AdjustFwd.hpp" namespace ee { namespace adjust { class Config final { private: using Self = Config; public: Self& setToken(const std::string& token); Self& setEnvironment(Environment environment); Self& setLogLevel(LogLevel logLevel); /// If your app makes heavy use of event tracking, you might want to delay /// some network requests in order to send them in one batch every minute. Self& setEventBufferingEnabled(bool enabled); private: friend Bridge; std::string token_; Environment environment_; LogLevel logLevel_; bool eventBufferingEnabled_; }; } // namespace adjust } // namespace ee #endif // __cplusplus #endif /* EE_X_ADJUST_CONFIG_HPP */
19.586957
78
0.715871
enrevol
f289d09358b32968f0bbb4c848d8b910b9fd0490
3,023
cpp
C++
src/HttpCURL.cpp
Daivuk/onut
b02c5969b36897813de9c574a26d9437b67f189e
[ "MIT" ]
50
2015-06-01T19:23:24.000Z
2021-12-22T02:14:23.000Z
src/HttpCURL.cpp
Daivuk/onut
b02c5969b36897813de9c574a26d9437b67f189e
[ "MIT" ]
109
2015-07-20T07:43:03.000Z
2021-01-31T21:52:36.000Z
src/HttpCURL.cpp
Daivuk/onut
b02c5969b36897813de9c574a26d9437b67f189e
[ "MIT" ]
9
2015-07-02T21:36:20.000Z
2019-10-19T04:18:02.000Z
// Onut #include <onut/Async.h> #include <onut/Dispatcher.h> #include <onut/Strings.h> #include <onut/Texture.h> // Internal #include "HttpCURL.h" // Third party #include <curl/curl.h> // STL #include <locale> namespace onut { OHttpRef Http::create() { return std::shared_ptr<Http>(new HttpCURL()); } HttpCURL::HttpCURL() { curl_global_init(CURL_GLOBAL_SSL); } HttpCURL::~HttpCURL() { curl_global_cleanup(); } static size_t curlWrite(void *buffer, size_t size, size_t nmemb, void *userp) { auto& ret = *(Http::Body*)userp; auto totalSize = size * nmemb; auto pos = ret.size(); ret.resize(pos + totalSize); memcpy(ret.data() + pos, buffer, totalSize); return totalSize; } std::string HttpCURL::post(const std::string& url, const Body& body, const ErrorCallback& onError) { auto easyhandle = curl_easy_init(); if (!easyhandle) { if (onError) { onError(0, "curl_easy_init failed"); } return {}; } Body ret; curl_easy_setopt(easyhandle, CURLOPT_URL, url.c_str()); curl_easy_setopt(easyhandle, CURLOPT_POST, 1); curl_easy_setopt(easyhandle, CURLOPT_POSTFIELDSIZE, (long)body.size()); curl_easy_setopt(easyhandle, CURLOPT_POSTFIELDS, (char*)body.data()); curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &ret); curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, curlWrite); auto performRet = curl_easy_perform(easyhandle); curl_easy_cleanup(easyhandle); if (performRet != CURLE_OK) { if (onError) { onError(0, "curl_easy_perform failed"); } return {}; } if (ret.empty()) return ""; if (ret[ret.size() - 1] != 0) ret.push_back(0); return (char*)ret.data(); } Http::Body HttpCURL::get(const std::string& url, const Arguments& arguments, const ErrorCallback& onError) { auto args = packArguments(arguments); auto fullUrl = url; if (!args.empty()) { fullUrl = url + "?" + args; } auto easyhandle = curl_easy_init(); if (!easyhandle) { if (onError) { onError(0, "curl_easy_init failed"); } return {}; } Body ret; curl_easy_setopt(easyhandle, CURLOPT_URL, fullUrl.c_str()); curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &ret); curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, curlWrite); auto performRet = curl_easy_perform(easyhandle); curl_easy_cleanup(easyhandle); if (performRet != CURLE_OK) { if (onError) { onError(0, "curl_easy_perform failed"); } return {}; } return std::move(ret); } }
25.191667
110
0.556732
Daivuk
f28a84be683355d46fe86e4074c33d12c0bc0ef1
1,165
hpp
C++
Source/DequeSearcher.hpp
jamesfer/Pathfinder
c1e770624a3b163f2dd173f38228e93d7eb80367
[ "MIT" ]
null
null
null
Source/DequeSearcher.hpp
jamesfer/Pathfinder
c1e770624a3b163f2dd173f38228e93d7eb80367
[ "MIT" ]
null
null
null
Source/DequeSearcher.hpp
jamesfer/Pathfinder
c1e770624a3b163f2dd173f38228e93d7eb80367
[ "MIT" ]
null
null
null
#ifndef DequeSearcher_hpp #define DequeSearcher_hpp #include "Searcher.hpp" #include <deque> /** * Utility class that implements a deque as the frontier structure. * Does not implement the nextInFrontier method as it depends on the * search strategy */ template <class State_type, class Success_functor = IsGoalCheck<State_type>> class DequeSearcher : public Searcher<State_type, Success_functor> { public: typedef Searcher<State_type, Success_functor> Super; typedef typename Super::Node_ptr Node_ptr; typedef typename Super::Path_ptr Path_ptr; protected: deque<Node_ptr> frontier; public: DequeSearcher(Success_functor functor = Success_functor()) : Super(functor) { } virtual ~DequeSearcher() { } /** * Overrides to also clear the frontier */ virtual void reset() override { Super::reset(); frontier.clear(); } /** * Adds a node to the frontier */ virtual void addToFrontier(Node_ptr node) override { frontier.push_back(node); } /** * Returns the size of the frontier */ virtual unsigned long frontierSize() const override { return frontier.size(); } }; #endif /* DequeSearcher_hpp */
17.651515
76
0.718455
jamesfer
f28f7ae21fa286ce46810fe1a6c1496d73e0529c
987
cpp
C++
GetLowEngine.Engine/PSOManager.cpp
ticticboooom/GetLowEngine
3303bc414a8b89c605161193d7284b6f91c4a5b6
[ "MIT" ]
3
2021-03-05T01:56:44.000Z
2021-08-01T10:18:47.000Z
GetLowEngine.Engine/PSOManager.cpp
ticticboooom/GetLowEngine
3303bc414a8b89c605161193d7284b6f91c4a5b6
[ "MIT" ]
null
null
null
GetLowEngine.Engine/PSOManager.cpp
ticticboooom/GetLowEngine
3303bc414a8b89c605161193d7284b6f91c4a5b6
[ "MIT" ]
null
null
null
#include "pch.h" #include "PSOManager.h" #include "DirectXHelper.h" #include "DeviceResources.h" #define _ATL_DEBUG_INTERFACES /** * @brief Construct a new PSOManager::PSOManager object * init with default values, this stores the shaders and renderer pipeline data * @param deviceResources */ PSOManager::PSOManager(const std::shared_ptr<DX::DeviceResources> deviceResources) : m_deviceResources(deviceResources) { m_desc = {}; m_desc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT); m_desc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT); m_desc.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT); m_desc.SampleMask = UINT_MAX; m_desc.SampleDesc.Count = 1; } /** * @brief Destroy the PSOManager::PSOManager object * */ PSOManager::~PSOManager() { } /** * @brief finalises and creates the PSO * */ void PSOManager::Finalise() { ThrowIfFailed(m_deviceResources->GetD3DDevice()->CreateGraphicsPipelineState(&m_desc, IID_PPV_ARGS(&m_pipelineState))); }
28.2
120
0.77305
ticticboooom
f29096fcc997deeb21771d7b3c73af0ec9321e64
454
cc
C++
Adapter/Adapter.cc
Yescafe/pattern_demo
b87d8d588683773cd37efff0e9e12fc70b13f187
[ "MIT" ]
1
2020-07-11T04:36:14.000Z
2020-07-11T04:36:14.000Z
Adapter/Adapter.cc
Yescafe/pattern_demo
b87d8d588683773cd37efff0e9e12fc70b13f187
[ "MIT" ]
null
null
null
Adapter/Adapter.cc
Yescafe/pattern_demo
b87d8d588683773cd37efff0e9e12fc70b13f187
[ "MIT" ]
null
null
null
#include "Adapter.hpp" #include <iostream> Target::Target() { } Target::~Target() { } void Target::Request() { std::cout << "Target::Request..." << std::endl; } Adaptee::Adaptee() { } Adaptee::~Adaptee() { } void Adaptee::SpecificRequest() { std::cout << "Adaptee::SpecificRequest..." << std::endl; } Adapter::Adapter(Adaptee* ade) { this->ade = ade; } Adapter::~Adapter() { } void Adapter::Request() { ade->SpecificRequest(); }
11.947368
60
0.603524
Yescafe
f29208998beb649cd770d4a51c70d109bd7c1cac
737
cpp
C++
mlir/lib/Interfaces/ViewLikeInterface.cpp
rarutyun/llvm
76fa6b3bcade074bdedef740001c4528e1aa08a8
[ "Apache-2.0" ]
305
2019-09-14T17:16:05.000Z
2022-03-31T15:05:20.000Z
mlir/lib/Interfaces/ViewLikeInterface.cpp
rarutyun/llvm
76fa6b3bcade074bdedef740001c4528e1aa08a8
[ "Apache-2.0" ]
11
2019-10-17T21:11:52.000Z
2022-02-17T20:10:00.000Z
mlir/lib/Interfaces/ViewLikeInterface.cpp
rarutyun/llvm
76fa6b3bcade074bdedef740001c4528e1aa08a8
[ "Apache-2.0" ]
24
2019-10-03T11:22:11.000Z
2022-01-25T09:59:30.000Z
//===- ViewLikeInterface.cpp - View-like operations in MLIR ---------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "mlir/Interfaces/ViewLikeInterface.h" using namespace mlir; //===----------------------------------------------------------------------===// // ViewLike Interfaces //===----------------------------------------------------------------------===// /// Include the definitions of the loop-like interfaces. #include "mlir/Interfaces/ViewLikeInterface.cpp.inc"
38.789474
80
0.489824
rarutyun
f2971416f9f158bb2a68da0a246ec15394aacc06
587
cpp
C++
compiler/tst_flowchartcompiler.cpp
UnnamedCompany/UnnamedSoftware
3251dc9844f35622f616fd3d5a40cb8c89ac0b28
[ "MIT" ]
4
2016-02-18T00:48:10.000Z
2016-03-02T23:41:54.000Z
compiler/tst_flowchartcompiler.cpp
UnnamedCompany/UnnamedSoftware
3251dc9844f35622f616fd3d5a40cb8c89ac0b28
[ "MIT" ]
null
null
null
compiler/tst_flowchartcompiler.cpp
UnnamedCompany/UnnamedSoftware
3251dc9844f35622f616fd3d5a40cb8c89ac0b28
[ "MIT" ]
1
2016-02-29T18:13:34.000Z
2016-02-29T18:13:34.000Z
#include <QTest> #include <QString> #include "flowchart.h" class TestFlowChartCompiler : public QObject { Q_OBJECT public: TestFlowChartCompiler() { } private Q_SLOTS: void testIsExpandable() { QWARN("No test implemented"); } void testExtractUniqueBlockNames() { QWARN("No test implemented"); } void testExtractInputBlocks() { QWARN("No test implemented"); } void testGeneratePicCode() { QWARN("No test implemented"); } }; QTEST_APPLESS_MAIN(TestFlowChartCompiler) #include "tst_flowchartcompiler.moc"
15.864865
46
0.662692
UnnamedCompany
f2990f0ecaebf3f073258a45108df106a7411240
16,892
cpp
C++
alienfx-cli/alienfx-cli.cpp
T-Troll/alienfx-tools
70d3b4be158b9ff2cafd87cc3c09b695fdab384c
[ "MIT" ]
55
2020-07-24T13:50:59.000Z
2022-03-31T02:15:09.000Z
alienfx-cli/alienfx-cli.cpp
T-Troll/alienfx-tools
70d3b4be158b9ff2cafd87cc3c09b695fdab384c
[ "MIT" ]
41
2020-07-25T14:37:25.000Z
2022-03-28T02:36:15.000Z
alienfx-cli/alienfx-cli.cpp
T-Troll/alienfx-tools
70d3b4be158b9ff2cafd87cc3c09b695fdab384c
[ "MIT" ]
9
2020-12-24T05:19:35.000Z
2022-03-30T01:52:32.000Z
#define WIN32_LEAN_AND_MEAN #include <iostream> #include "stdafx.h" #include "LFXUtil.h" #include "LFXDecl.h" #include "AlienFX_SDK.h" namespace { LFXUtil::LFXUtilC lfxUtil; } using namespace std; unsigned GetZoneCode(string name, int mode) { switch (mode) { case 1: return atoi(name.c_str()) | 0x10000; case 0: if (name == "left") return LFX_ALL_LEFT; if (name == "right") return LFX_ALL_RIGHT; if (name == "top") return LFX_ALL_UPPER; if (name == "bottom") return LFX_ALL_LOWER; if (name == "front") return LFX_ALL_FRONT; if (name == "rear") return LFX_ALL_REAR; } return LFX_ALL; } unsigned GetActionCode(string name, int mode) { if (name == "pulse") { return mode ? AlienFX_SDK::Action::AlienFX_A_Pulse : LFX_ACTION_PULSE; } if (name == "morph") { return mode ? AlienFX_SDK::Action::AlienFX_A_Morph : LFX_ACTION_MORPH; } if (name == "breath") { return mode ? AlienFX_SDK::Action::AlienFX_A_Breathing : LFX_ACTION_MORPH; } else if (name == "spectrum") { return mode ? AlienFX_SDK::Action::AlienFX_A_Spectrum : LFX_ACTION_MORPH; } else if (name == "rainbow") { return mode ? AlienFX_SDK::Action::AlienFX_A_Rainbow : LFX_ACTION_MORPH; } return mode ? AlienFX_SDK::Action::AlienFX_A_Color : LFX_ACTION_COLOR; } void SetBrighness(ColorS *color) { color->red = ((unsigned) color->red * color->brightness) / 255;// >> 8; color->green = ((unsigned) color->green * color->brightness) / 255;// >> 8; color->blue = ((unsigned) color->blue * color->brightness) / 255;// >> 8; } void printUsage() { cerr << "Usage: alienfx-cli [command=option,option,option] ... [command=option,option,option] [loop]" << endl << "Commands:\tOptions:" << endl << "set-all\t\tr,g,b[,br] - set all device lights." << endl << "set-one\t\tpid,light,r,g,b[,br] - set one light." << endl << "set-zone\tzone,r,g,b[,br] - set one zone lights." << endl << "set-action\tpid,light,action,r,g,b[,br,[action,r,g,b,br]] - set light and enable it's action." << endl << "set-zone-action\tzone,action,r,g,b[,br,[action,r,g,b,br]] - set all zone lights and enable it's action." << endl << "set-power\tlight,r,g,b,r2,g2,b2 - set power button colors (low-level only)." << endl << "set-tempo\ttempo - set light action tempo (in milliseconds)." << endl << "set-dev\t\tpid - set active device for low-level." << endl << "set-dim\t\tbr - set active device dim level." << endl << "low-level\tswitch to low-level SDK (USB driver)." << endl << "high-level\tswitch to high-level SDK (Alienware LightFX)." << endl << "status\t\tshows devices and lights id's, names and statuses." << endl << "lightson\tturn all current device lights on." << endl << "lightsoff\tturn all current device lights off." << endl << "update\t\tupdates light status (for looped commands or old devices)." << endl << "reset\t\treset device state." << endl << "loop\t\trepeat all commands endlessly, until user press ^c. Should be the last command." << endl << endl << "Zones:\tleft, right, top, bottom, front, rear (high-level) or ID of the Group (low-level)." << endl << "Actions:color (disable action), pulse, morph (you need 2 colors)," << endl << "\t(only for low-level v4) breath, spectrum, rainbow (up to 9 colors each)." << endl; } int main(int argc, char* argv[]) { int devType = -1; bool have_low = false, have_high = false; UINT sleepy = 0; cerr << "alienfx-cli v5.0.6" << endl; if (argc < 2) { printUsage(); return 1; } AlienFX_SDK::Mappings* afx_map = new AlienFX_SDK::Mappings(); AlienFX_SDK::Functions* afx_dev = new AlienFX_SDK::Functions(); int res = -1; vector<pair<DWORD,DWORD>> devs = afx_map->AlienFXEnumDevices(); int pid = -1; if (devs.size() > 0) { pid = afx_dev->AlienFXInitialize(devs[0].first, devs[0].second); if (pid > 0) { for (int rcount = 0; rcount < 10 && !afx_dev->IsDeviceReady(); rcount++) Sleep(20); if (!afx_dev->IsDeviceReady()) { afx_dev->Reset(); } afx_map->LoadMappings(); cout << "Low-level device ready" << endl; have_low = true; devType = 1; } } else { cerr << "No low-level devices found, trying high-level..." << endl; } if (res = lfxUtil.InitLFX() != -1) { switch (res) { case 0: cerr << "Dell library DLL not found (no library?)!" << endl; break; case 1: cerr << "Can't init Dell library!" << endl; break; case 2: cerr << "No high-level devices found!" << endl; break; default: cerr << "Dell library unknown error!" << endl; break; } } else { cout << "Dell API ready" << endl; have_high = true; if (!have_low) devType = 0; } if (devType == -1) { cout << "Both low-levl and high-level devices not found, exiting!" << endl; goto deinit; } const char* command = argv[1]; for (int cc = 1; cc < argc; cc++) { if (devType > 0 && cc > 1) { Sleep(sleepy); } else Sleep(100); string arg = string(argv[cc]); size_t vid = arg.find_first_of('='); string command = arg.substr(0, vid); string values; vector<string> args; if (vid != string::npos) { size_t vpos = 0; values = arg.substr(vid + 1, arg.size()); while (vpos < values.size()) { size_t tvpos = values.find(',', vpos); args.push_back(values.substr(vpos, tvpos-vpos)); vpos = tvpos == string::npos ? values.size() : tvpos+1; } } //cerr << "Executing " << command << " with " << values << endl; if (command == "low-level") { if (have_low) devType = 1; continue; } if (command == "high-level") { if (have_high) devType = 0; continue; } if (command == "loop") { cc = 1; switch (devType) { case 1: afx_dev->UpdateColors(); break; case 0: lfxUtil.Update(); break; } continue; } if (command == "status") { switch (devType) { case 1: for (int i = 0; i < devs.size(); i++) { cout << "Device VID#" << devs[i].first << ", PID#" << devs[i].second; int dn; for (dn = 0; dn < afx_map->GetDevices()->size(); dn++) { if (devs[i].second == afx_map->GetDevices()->at(i).devid) { cout << " - " << afx_map->GetDevices()->at(i).name; if (devs[i].second == afx_dev->GetPID()) { cout << " (Active, V" << afx_dev->GetVersion() << ")"; } break; } } cout << endl; for (int k = 0; k < afx_map->GetMappings()->size(); k++) { AlienFX_SDK::mapping *lgh = afx_map->GetMappings()->at(k); if (devs[i].second == lgh->devid) { cout << " Light ID#" << lgh->lightid << " - " << lgh->name; if (lgh->flags & ALIENFX_FLAG_POWER) cout << " (Power button)"; if (lgh->flags & ALIENFX_FLAG_INACTIVE) cout << " (Indicator)"; cout << endl; } } } // now groups... for (int i = 0; i < afx_map->GetGroups()->size(); i++) cout << "Group #" << (afx_map->GetGroups()->at(i).gid & 0xffff) << " - " << afx_map->GetGroups()->at(i).name << " (" << afx_map->GetGroups()->at(i).lights.size() << " lights)" << endl; break; case 0: lfxUtil.GetStatus(); break; } continue; } if (command == "set-tempo") { if (args.size() < 1) { cerr << "set-tempo: Incorrect argument" << endl; continue; } switch (devType) { case 1: sleepy = atoi(args.at(0).c_str()); break; case 0: { unsigned tempo = atoi(args.at(0).c_str()); lfxUtil.SetTempo(tempo); lfxUtil.Update(); } break; } continue; } if (command == "set-dev") { if (args.size() < 1) { cerr << "set-dev: Incorrect argument" << endl; continue; } if (devType) { int newDev = atoi(args.at(0).c_str()); if (newDev == afx_dev->GetPID()) continue; pid = afx_dev->AlienFXChangeDevice(0, newDev);// devs[i].first, devs[i].second); //for (int i = 0; i < devs.size(); i++) // if (devs[i].second == newDev) { // afx_dev->UpdateColors(); // afx_dev->AlienFXClose(); // pid = afx_dev->AlienFXChangeDevice(devs[i].first, devs[i].second); if (pid < 0) { cerr << "Can't init device ID#" << newDev << ", exiting!" << endl; continue; } // break; //} } continue; } if (command == "reset") { switch (devType) { case 1: afx_dev->Reset(); break; case 0: lfxUtil.Reset(); break; } continue; } if (command == "update") { switch (devType) { case 1: afx_dev->UpdateColors(); break; case 0: lfxUtil.Update(); break; } continue; } if (command == "set-dim") { byte dim = atoi(args.at(0).c_str()); if (devType) afx_dev->ToggleState(dim, afx_map->GetMappings(), false); continue; } if (command == "lightson") { if (devType) afx_dev->ToggleState(255, afx_map->GetMappings(), false); continue; } if (command == "lightsoff") { if (devType) afx_dev->ToggleState(0, afx_map->GetMappings(), false); continue; } if (command == "set-all") { if (args.size() < 3) { cerr << "set-all: Incorrect arguments" << endl; continue; } unsigned zoneCode = LFX_ALL; static ColorU color; color.cs.red = atoi(args.at(0).c_str()); color.cs.green = atoi(args.at(1).c_str()); color.cs.blue = atoi(args.at(2).c_str()); color.cs.brightness = args.size() > 3 ? atoi(args.at(3).c_str()) : 255; switch (devType) { case 1: { SetBrighness(&color.cs); vector<UCHAR> lights; for (int i = 0; i < afx_map->GetMappings()->size(); i++) { AlienFX_SDK::mapping *lgh = afx_map->GetMappings()->at(i); if (lgh->devid == pid && !(lgh->flags & ALIENFX_FLAG_POWER)) lights.push_back((UCHAR) lgh->lightid); } afx_dev->SetMultiLights((int) lights.size(), lights.data(), color.cs.red, color.cs.green, color.cs.blue); afx_dev->UpdateColors(); } break; case 0: lfxUtil.SetLFXColor(zoneCode, color.ci); lfxUtil.Update(); break; } continue; } if (command == "set-one") { if (args.size() < 5) { cerr << "set-one: Incorrect arguments" << endl; continue; } static ColorU color; int devid = atoi(args.at(0).c_str()); color.cs.red = atoi(args.at(4).c_str()); color.cs.green = atoi(args.at(3).c_str()); color.cs.blue = atoi(args.at(2).c_str()); color.cs.brightness = args.size() > 5 ? atoi(args.at(5).c_str()) : 255; switch (devType) { case 1: { SetBrighness(&color.cs); if (devid != 0 && devid != afx_dev->GetPID()) { afx_dev->UpdateColors(); afx_dev->AlienFXClose(); //pair<DWORD, DWORD>* dev = LocateDev(&devs, devid); afx_dev->AlienFXChangeDevice(0, devid);// dev->first, dev->second); } afx_dev->SetColor(atoi(args.at(1).c_str()), color.cs.blue, color.cs.green, color.cs.red); } break; case 0: lfxUtil.SetOneLFXColor(devid, atoi(args.at(1).c_str()), &color.ci); lfxUtil.Update(); break; } continue; } if (command == "set-zone") { if (args.size() < 4) { cerr << "set-zone: Incorrect arguments" << endl; continue; } static ColorU color; unsigned zoneCode = LFX_ALL; color.cs.red = atoi(args.at(1).c_str()); color.cs.green = atoi(args.at(2).c_str()); color.cs.blue = atoi(args.at(3).c_str()); color.cs.brightness = args.size() > 4 ? atoi(args.at(4).c_str()) : 255; zoneCode = GetZoneCode(args[0], devType); switch (devType) { case 1: { SetBrighness(&color.cs); AlienFX_SDK::group* grp = afx_map->GetGroupById(zoneCode); if (grp) { int oldPid = afx_dev->GetPID(), oldVid = afx_dev->GetVid(); for (int j = 0; j < devs.size(); j++) { vector<UCHAR> lights; afx_dev->AlienFXChangeDevice(devs[j].first, devs[j].second); for (int i = 0; i < grp->lights.size(); i++) { if (grp->lights[i]->devid == afx_dev->GetPID()) lights.push_back((UCHAR) afx_map->GetMappings()->at(i)->lightid); } afx_dev->SetMultiLights((int) lights.size(), lights.data(), color.cs.red, color.cs.green, color.cs.blue); afx_dev->UpdateColors(); } afx_dev->AlienFXChangeDevice(oldVid, oldPid); } } break; case 0: { lfxUtil.SetLFXColor(zoneCode, color.ci); lfxUtil.Update(); } break; } continue; } if (command == "set-power") { if (args.size() != 7) { cerr << "set-power: Incorrect arguments" << endl; continue; } static ColorU color, color2; color.cs.red = atoi(args.at(1).c_str()); color.cs.green = atoi(args.at(2).c_str()); color.cs.blue = atoi(args.at(3).c_str()); color2.cs.red = atoi(args.at(4).c_str()); color2.cs.green = atoi(args.at(5).c_str()); color2.cs.blue = atoi(args.at(6).c_str()); if (devType) { afx_dev->SetPowerAction(atoi(args.at(0).c_str()), color.cs.red, color.cs.green, color.cs.blue, color2.cs.red, color2.cs.green, color2.cs.blue); } else { cerr << "High-level API doesn't support set-power!" << endl; } continue; } if (command == "set-action") { if (args.size() < 6) { cerr << "set-action: Incorrect arguments" << endl; continue; } unsigned actionCode = LFX_ACTION_COLOR; std::vector<AlienFX_SDK::afx_act> act; std::vector<ColorU> clrs; int argPos = 2; int devid = atoi(args.at(0).c_str()), lightid = atoi(args.at(1).c_str()); while (argPos + 3 < args.size()) { ColorU c; actionCode = GetActionCode(args[argPos], devType); c.cs.blue = atoi(args.at(argPos+1).c_str()); c.cs.green = atoi(args.at(argPos + 2).c_str()); c.cs.red = atoi(args.at(argPos + 3).c_str()); c.cs.brightness = argPos + 4 < args.size() ? atoi(args.at(argPos + 4).c_str()) : 255; if (devType) { SetBrighness(&c.cs); act.push_back(AlienFX_SDK::afx_act({(BYTE) actionCode, (BYTE) sleepy, 7, (BYTE) c.cs.blue, (BYTE) c.cs.green, (BYTE) c.cs.red})); } else clrs.push_back(c); argPos += 5; } switch (devType) { case 1: if (devid != 0 && devid != afx_dev->GetPID()) { afx_dev->UpdateColors(); afx_dev->AlienFXClose(); afx_dev->AlienFXChangeDevice(0, devid);// dev->first, dev->second); } if (act.size() < 2) { act.push_back(AlienFX_SDK::afx_act({(BYTE) actionCode, (BYTE) sleepy, 7, 0, 0, 0})); } afx_dev->SetAction(lightid, act); break; case 0: if (clrs.size() < 2) { clrs.push_back(ColorU({0})); } lfxUtil.SetLFXAction(actionCode, devid, lightid, &clrs[0].ci, &clrs[1].ci); lfxUtil.Update(); break; } continue; } if (command == "set-zone-action") { if (args.size() < 5) { cerr << "set-zone-action: Incorrect arguments" << endl; continue; } unsigned zoneCode = GetZoneCode(args[0], devType); unsigned actionCode = LFX_ACTION_COLOR; std::vector<AlienFX_SDK::afx_act> act; std::vector<ColorU> clrs; int argPos = 1; while (argPos + 3 < args.size()) { ColorU c; actionCode = GetActionCode(args[argPos], devType); c.cs.red = atoi(args.at(argPos+1).c_str()); c.cs.green = atoi(args.at(argPos + 2).c_str()); c.cs.blue = atoi(args.at(argPos + 3).c_str()); c.cs.brightness = argPos + 4 < args.size() ? atoi(args.at(argPos + 4).c_str()) : 255; if (devType) { SetBrighness(&c.cs); act.push_back(AlienFX_SDK::afx_act({(BYTE) actionCode, (BYTE) sleepy, 7, (BYTE) c.cs.red, (BYTE) c.cs.green, (BYTE) c.cs.blue})); } else clrs.push_back(c); argPos += 5; } switch (devType) { case 1: { AlienFX_SDK::group* grp = afx_map->GetGroupById(zoneCode); int oldPid = afx_dev->GetPID(), oldVid = afx_dev->GetVid(); if (act.size() < 2) { act.push_back(AlienFX_SDK::afx_act({(BYTE) actionCode, (BYTE) sleepy, 7, 0, 0, 0})); } if (grp) { for (int j = 0; j < devs.size(); j++) { afx_dev->AlienFXChangeDevice(devs[j].first, devs[j].second); for (int i = 0; i < grp->lights.size(); i++) if (grp->lights[i]->devid == afx_dev->GetPID()) afx_dev->SetAction(grp->lights[i]->lightid, act); afx_dev->UpdateColors(); } } else { // set all! for (int j = 0; j < devs.size(); j++) { afx_dev->AlienFXChangeDevice(devs[j].first, devs[j].second); for (int i = 0; i < afx_map->GetMappings()->size(); i++) { AlienFX_SDK::mapping *lgh = afx_map->GetMappings()->at(i); if (lgh->devid == afx_dev->GetPID() && !(lgh->flags & ALIENFX_FLAG_POWER)) afx_dev->SetAction(lgh->lightid, act); } afx_dev->UpdateColors(); } } afx_dev->AlienFXChangeDevice(oldVid, oldPid); } break; case 0: if (clrs.size() < 2) clrs.push_back(ColorU({0})); lfxUtil.SetLFXZoneAction(actionCode, zoneCode, clrs[0].ci, clrs[1].ci); lfxUtil.Update(); break; } continue; } cerr << "Unknown command: " << command << endl; } cout << "Done." << endl; deinit: if (have_low) afx_dev->UpdateColors(); afx_dev->AlienFXClose(); if (have_high) lfxUtil.Release(); delete afx_map; delete afx_dev; return 0; }
30.994495
134
0.590753
T-Troll
f29b05a35709c839a7fe8cf70b351995e71a9f04
1,181
cpp
C++
S-Digit_Sum.cpp
geegatomar/Educational-DP-contest-Atcoder
f32cb87cc58609e3c0cd51b9d54b632dd215b6ef
[ "MIT" ]
null
null
null
S-Digit_Sum.cpp
geegatomar/Educational-DP-contest-Atcoder
f32cb87cc58609e3c0cd51b9d54b632dd215b6ef
[ "MIT" ]
null
null
null
S-Digit_Sum.cpp
geegatomar/Educational-DP-contest-Atcoder
f32cb87cc58609e3c0cd51b9d54b632dd215b6ef
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define int long long const int M = 1e9 + 7; const int N = (int)1e4; // Concept used: Digit DP int dp[N][2][100]; int f(int ind, int is_tight, int sum_of_dig, string &k, int &d) { sum_of_dig %= d; if(ind >= k.size()) return ((sum_of_dig % d == 0) ? 1 : 0); if(dp[ind][is_tight][sum_of_dig] != -1) return dp[ind][is_tight][sum_of_dig]; int ans = 0; int curr_dig = k[ind] - '0'; if(is_tight) { for(int i = 0; i <= curr_dig; i++) { if(i == curr_dig) ans += f(ind + 1, 1, i + sum_of_dig, k, d); else ans += f(ind + 1, 0, i + sum_of_dig, k, d); ans %= M; } } else { for(int i = 0; i <= 9; i++) { ans += f(ind + 1, 0, i + sum_of_dig, k, d); ans %= M; } } return dp[ind][is_tight][sum_of_dig] = ans % M; } int32_t main() { string k; int d; cin >> k >> d; memset(dp, -1, sizeof(dp)); cout << (f(0, 1, 0, k, d) - 1 + M) % M; // subtracting 1 because '0' would have been counted as an answer too }
20.016949
73
0.461473
geegatomar
f2a0a3cfd5f3ff212cb788c6b2b6b7f6bd5660ed
1,206
cpp
C++
code_process/src/RCB.cpp
NewtonVan/OS2020
223bc0d190ddad352777587792f4bf12d4d0081d
[ "MIT" ]
1
2021-12-16T07:49:37.000Z
2021-12-16T07:49:37.000Z
code_process/src/RCB.cpp
NewtonVan/OS2020
223bc0d190ddad352777587792f4bf12d4d0081d
[ "MIT" ]
null
null
null
code_process/src/RCB.cpp
NewtonVan/OS2020
223bc0d190ddad352777587792f4bf12d4d0081d
[ "MIT" ]
null
null
null
#include "RCB.h" RCB::RCB() : rid_(-1), available_(0), total_(0) {} RCB::RCB(int rid, int available, int total) : rid_(rid), available_(available), total_(total) {} RCB::RCB(int rid, int total) : rid_(rid), available_(total), total_(total) {} RCB::~RCB()= default; // get the member of RCB int RCB::getRid() { return rid_; } int RCB::getAvailable() { return available_; } int RCB::getTotal() { return total_; } // set the member int RCB::setRid(int rid) { return rid_= rid; } int RCB::setAvailable(int available) { return available_= available; } int RCB::setTotal(int total) { return total_= total; } /** * @available: positive means increase, negative means decrease */ int RCB::changeAvailable(int available) { available_+= available; return available_; } void RCB::inLine(PCB* wait) { wait_l_.push_back(wait); } void RCB::outLine(PCB* wait) { for (std::list<PCB*>::iterator w_iter= wait_l_.begin(); wait_l_.end()!= w_iter; ++w_iter){ if (wait== *w_iter){ wait_l_.erase(w_iter); break; } } } int RCB::waitEmpty() { return wait_l_.empty(); } PCB* RCB::waitFront() { return wait_l_.front(); }
14.707317
63
0.624378
NewtonVan
f2a2164401b9df5cb867f9e81692410f1cb60e3e
3,169
hpp
C++
OptiX-Path-Tracer/programs/vec.hpp
trevortheblack/OptiX-Path-Tracer
e52394a80966057f8968c008078f0372277fdc8e
[ "Apache-2.0" ]
77
2018-11-27T12:17:52.000Z
2022-02-22T23:25:06.000Z
OptiX-Path-Tracer/programs/vec.hpp
trevortheblack/OptiX-Path-Tracer
e52394a80966057f8968c008078f0372277fdc8e
[ "Apache-2.0" ]
1
2019-06-14T18:43:07.000Z
2019-06-14T18:43:07.000Z
OptiX-Path-Tracer/programs/vec.hpp
trevortheblack/OptiX-Path-Tracer
e52394a80966057f8968c008078f0372277fdc8e
[ "Apache-2.0" ]
3
2019-06-14T15:28:58.000Z
2021-10-13T16:32:09.000Z
// ======================================================================== // // Copyright 2018 Ingo Wald // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #pragma once #include "common.hpp" inline __host__ __device__ float squared_length(const float3 &a) { return length(a) * length(a); } // returns true if all components are zero inline __host__ __device__ bool isNull(const float3 &a) { return (a.x == 0.f) && (a.y == 0.f) && (a.z == 0.f); } /*! return absolute value of each component */ inline __host__ __device__ float3 abs(const float3 &v) { return make_float3(fabsf(v.x), fabsf(v.y), fabsf(v.z)); } /*! return sqrt value of each component */ inline __host__ __device__ float3 sqrt(const float3 &v) { return make_float3(sqrt(v.x), sqrt(v.y), sqrt(v.z)); } /*! return sqr value of each component */ inline __host__ __device__ float3 sqr(const float3 &v) { return make_float3(v.x * v.x, v.y * v.y, v.z * v.z); } /* return unit vector */ inline __host__ __device__ float3 unit_vector(const float3 &v) { return v / length(v); } /*! return mod between two vectors */ inline __host__ __device__ float3 mod(const float3 &a, const float3 &b) { return make_float3(fmodf(a.x, b.x), fmodf(a.y, b.y), fmodf(a.z, b.z)); } // if (a < b), return a, else return b inline __host__ __device__ float ffmin(const float &a, const float &b) { return a < b ? a : b; } // if (a > b), return a, else return b inline __host__ __device__ float ffmax(const float &a, const float &b) { return a > b ? a : b; } // return pairwise min vector inline __host__ __device__ float3 min_vec(const float3 &a, const float3 &b) { return make_float3(ffmin(a.x, b.x), ffmin(a.y, b.y), ffmin(a.z, b.z)); } // return pairwise max vector inline __host__ __device__ float3 max_vec(float3 a, float3 b) { return make_float3(ffmax(a.x, b.x), ffmax(a.y, b.y), ffmax(a.z, b.z)); } // return max component of vector inline __host__ __device__ float max_component(float3 a) { return ffmax(ffmax(a.x, a.y), a.z); } // return max component of vector inline __host__ __device__ float min_component(float3 a) { return ffmin(ffmin(a.x, a.y), a.z); }
37.72619
78
0.565478
trevortheblack
f2a822ce0f18fc221e92014cb95187deeff85435
2,986
cc
C++
src/poly/string.cc
jdarpinian/xenia
609d7c755f260e86a865703dc1dcd6df064b1fa0
[ "BSD-3-Clause" ]
1
2016-11-18T23:12:53.000Z
2016-11-18T23:12:53.000Z
src/poly/string.cc
jdarpinian/xenia
609d7c755f260e86a865703dc1dcd6df064b1fa0
[ "BSD-3-Clause" ]
null
null
null
src/poly/string.cc
jdarpinian/xenia
609d7c755f260e86a865703dc1dcd6df064b1fa0
[ "BSD-3-Clause" ]
null
null
null
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2014 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include <poly/string.h> #include <codecvt> #include <locale> namespace poly { std::string to_string(const std::wstring& source) { static std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; return converter.to_bytes(source); } std::wstring to_wstring(const std::string& source) { static std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; return converter.from_bytes(source); } std::string::size_type find_first_of_case(const std::string& target, const std::string& search) { const char* str = target.c_str(); while (*str) { if (!strncasecmp(str, search.c_str(), search.size())) { break; } str++; } if (*str) { return str - target.c_str(); } else { return std::string::npos; } } std::wstring to_absolute_path(const std::wstring& path) { #if XE_LIKE_WIN32 wchar_t buffer[poly::max_path]; _wfullpath(buffer, path.c_str(), sizeof(buffer) / sizeof(wchar_t)); return buffer; #else char buffer[poly::max_path]; realpath(poly::to_string(path).c_str(), buffer); return poly::to_wstring(buffer); #endif // XE_LIKE_WIN32 } std::vector<std::string> split_path(const std::string& path) { std::vector<std::string> parts; size_t n = 0; size_t last = 0; while ((n = path.find_first_of("\\/", last)) != path.npos) { if (last != n) { parts.push_back(path.substr(last, n - last)); } last = n + 1; } if (last != path.size()) { parts.push_back(path.substr(last)); } return parts; } std::wstring join_paths(const std::wstring& left, const std::wstring& right, wchar_t sep) { if (!left.size()) { return right; } else if (!right.size()) { return left; } if (left[left.size() - 1] == sep) { return left + right; } else { return left + sep + right; } } std::wstring fix_path_separators(const std::wstring& source, wchar_t new_sep) { // Swap all separators to new_sep. wchar_t old_sep = new_sep == '\\' ? '/' : '\\'; std::wstring::size_type pos = 0; std::wstring dest = source; while ((pos = source.find_first_of(old_sep, pos)) != std::wstring::npos) { dest[pos] = new_sep; ++pos; } // Replace redundant separators. pos = 0; while ((pos = dest.find_first_of(new_sep, pos)) != std::wstring::npos) { if (pos < dest.size() - 1) { if (dest[pos + 1] == new_sep) { dest.erase(pos + 1, 1); } } ++pos; } return dest; } } // namespace poly
27.648148
79
0.558607
jdarpinian
f2a85ae7f29b22e347a92f289e2f6ccdb9467e76
12,793
cxx
C++
main/chart2/source/model/template/StockDataInterpreter.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/chart2/source/model/template/StockDataInterpreter.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/chart2/source/model/template/StockDataInterpreter.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "StockDataInterpreter.hxx" #include "DataSeries.hxx" #include "macros.hxx" #include "DataSeriesHelper.hxx" #include "CommonConverters.hxx" #include "ContainerHelper.hxx" #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/chart2/data/XDataSink.hpp> // #include <deque> #include <vector> #include <algorithm> #include <iterator> using namespace ::com::sun::star; using namespace ::com::sun::star::chart2; using namespace ::std; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; using ::rtl::OUString; using namespace ::chart::ContainerHelper; namespace chart { // explicit StockDataInterpreter::StockDataInterpreter( StockChartTypeTemplate::StockVariant eVariant, const Reference< uno::XComponentContext > & xContext ) : DataInterpreter( xContext ), m_eStockVariant( eVariant ) {} StockDataInterpreter::~StockDataInterpreter() {} StockChartTypeTemplate::StockVariant StockDataInterpreter::GetStockVariant() const { return m_eStockVariant; } // ____ XDataInterpreter ____ InterpretedData SAL_CALL StockDataInterpreter::interpretDataSource( const Reference< data::XDataSource >& xSource, const Sequence< beans::PropertyValue >& rArguments, const Sequence< Reference< XDataSeries > >& rSeriesToReUse ) throw (uno::RuntimeException) { if( ! xSource.is()) return InterpretedData(); Reference< data::XLabeledDataSequence > xCategories; Sequence< Reference< data::XLabeledDataSequence > > aData( xSource->getDataSequences() ); const sal_Int32 nDataCount( aData.getLength()); // sub-type properties const StockChartTypeTemplate::StockVariant eVar( GetStockVariant()); const bool bHasOpenValues (( eVar == StockChartTypeTemplate::OPEN_LOW_HI_CLOSE ) || ( eVar == StockChartTypeTemplate::VOL_OPEN_LOW_HI_CLOSE )); const bool bHasVolume (( eVar == StockChartTypeTemplate::VOL_LOW_HI_CLOSE ) || ( eVar == StockChartTypeTemplate::VOL_OPEN_LOW_HI_CLOSE )); const bool bHasCategories( HasCategories( rArguments, aData )); // necessary roles for "full series" // low/high/close sal_Int32 nNumberOfNecessarySequences( 3 ); if( bHasOpenValues ) ++nNumberOfNecessarySequences; if( bHasVolume ) ++nNumberOfNecessarySequences; // calculate number of full series (nNumOfFullSeries) and the number of remaining // sequences used for additional "incomplete series" (nRemaining) sal_Int32 nNumOfFullSeries( 0 ); sal_Int32 nRemaining( 0 ); { sal_Int32 nAvailableSequences( nDataCount ); if( bHasCategories ) --nAvailableSequences; nNumOfFullSeries = nAvailableSequences / nNumberOfNecessarySequences; nRemaining = nAvailableSequences % nNumberOfNecessarySequences; } sal_Int32 nCandleStickSeries = nNumOfFullSeries; sal_Int32 nVolumeSeries = nNumOfFullSeries; sal_Int32 nNumberOfGroups( bHasVolume ? 2 : 1 ); // sequences of data::XLabeledDataSequence per series per group Sequence< Sequence< Sequence< Reference< data::XLabeledDataSequence > > > > aSequences( nNumberOfGroups ); sal_Int32 nBarGroupIndex( 0 ); sal_Int32 nCandleStickGroupIndex( nNumberOfGroups - 1 ); // allocate space for labeled sequences if( nRemaining > 0 ) ++nCandleStickSeries; aSequences[nCandleStickGroupIndex].realloc( nCandleStickSeries ); if( bHasVolume ) { // if there are remaining sequences, the first one is taken for // additional close values, the second one is taken as volume, if volume // is used if( nRemaining > 1 ) ++nVolumeSeries; aSequences[nBarGroupIndex].realloc( nVolumeSeries ); } // create data sal_Int32 nSourceIndex = 0; // index into aData sequence // 1. categories if( bHasCategories ) { xCategories.set( aData[nSourceIndex] ); ++nSourceIndex; } // 2. create "full" series for( sal_Int32 nLabeledSeqIdx=0; nLabeledSeqIdx<nNumOfFullSeries; ++nLabeledSeqIdx ) { // bar if( bHasVolume ) { aSequences[nBarGroupIndex][nLabeledSeqIdx].realloc( 1 ); aSequences[nBarGroupIndex][nLabeledSeqIdx][0].set( aData[nSourceIndex] ); if( aData[nSourceIndex].is()) SetRole( aData[nSourceIndex]->getValues(), C2U("values-y")); ++nSourceIndex; } sal_Int32 nSeqIdx = 0; if( bHasOpenValues ) { aSequences[nCandleStickGroupIndex][nLabeledSeqIdx].realloc( 4 ); aSequences[nCandleStickGroupIndex][nLabeledSeqIdx][nSeqIdx].set( aData[nSourceIndex] ); if( aData[nSourceIndex].is()) SetRole( aData[nSourceIndex]->getValues(), C2U("values-first")); ++nSourceIndex, ++nSeqIdx; } else aSequences[nCandleStickGroupIndex][nLabeledSeqIdx].realloc( 3 ); aSequences[nCandleStickGroupIndex][nLabeledSeqIdx][nSeqIdx].set( aData[nSourceIndex] ); if( aData[nSourceIndex].is()) SetRole( aData[nSourceIndex]->getValues(), C2U("values-min")); ++nSourceIndex, ++nSeqIdx; aSequences[nCandleStickGroupIndex][nLabeledSeqIdx][nSeqIdx].set( aData[nSourceIndex] ); if( aData[nSourceIndex].is()) SetRole( aData[nSourceIndex]->getValues(), C2U("values-max")); ++nSourceIndex, ++nSeqIdx; aSequences[nCandleStickGroupIndex][nLabeledSeqIdx][nSeqIdx].set( aData[nSourceIndex] ); if( aData[nSourceIndex].is()) SetRole( aData[nSourceIndex]->getValues(), C2U("values-last")); ++nSourceIndex, ++nSeqIdx; } // 3. create series with remaining sequences if( bHasVolume && nRemaining > 1 ) { OSL_ASSERT( nVolumeSeries > nNumOfFullSeries ); aSequences[nBarGroupIndex][nVolumeSeries - 1].realloc( 1 ); OSL_ASSERT( nDataCount > nSourceIndex ); if( aData[nSourceIndex].is()) SetRole( aData[nSourceIndex]->getValues(), C2U("values-y")); aSequences[nBarGroupIndex][nVolumeSeries - 1][0].set( aData[nSourceIndex] ); ++nSourceIndex; --nRemaining; OSL_ENSURE( nRemaining, "additional bar should only be used if there is at least one more sequence for a candle stick" ); } // candle-stick if( nRemaining > 0 ) { OSL_ASSERT( nCandleStickSeries > nNumOfFullSeries ); const sal_Int32 nSeriesIndex = nCandleStickSeries - 1; aSequences[nCandleStickGroupIndex][nSeriesIndex].realloc( nRemaining ); OSL_ASSERT( nDataCount > nSourceIndex ); // 1. low sal_Int32 nSeqIdx( 0 ); aSequences[nCandleStickGroupIndex][nSeriesIndex][nSeqIdx].set( aData[nSourceIndex] ); if( aData[nSourceIndex].is()) SetRole( aData[nSourceIndex]->getValues(), C2U("values-min")); ++nSourceIndex, ++nSeqIdx; // 2. high if( nSeqIdx < nRemaining ) { aSequences[nCandleStickGroupIndex][nSeriesIndex][nSeqIdx].set( aData[nSourceIndex] ); if( aData[nSourceIndex].is()) SetRole( aData[nSourceIndex]->getValues(), C2U("values-max")); ++nSourceIndex, ++nSeqIdx; } // 3. close OSL_ENSURE( bHasOpenValues || nSeqIdx >= nRemaining, "could have created full series" ); if( nSeqIdx < nRemaining ) { aSequences[nCandleStickGroupIndex][nSeriesIndex][nSeqIdx].set( aData[nSourceIndex] ); if( aData[nSourceIndex].is()) SetRole( aData[nSourceIndex]->getValues(), C2U("values-last")); ++nSourceIndex, ++nSeqIdx; } // 4. open OSL_ENSURE( nSeqIdx >= nRemaining, "could have created full series" ); } // create DataSeries Sequence< Sequence< Reference< XDataSeries > > > aResultSeries( nNumberOfGroups ); sal_Int32 nGroupIndex, nReUsedSeriesIdx = 0; for( nGroupIndex=0; nGroupIndex<nNumberOfGroups; ++nGroupIndex ) { const sal_Int32 nNumSeriesData = aSequences[nGroupIndex].getLength(); aResultSeries[nGroupIndex].realloc( nNumSeriesData ); for( sal_Int32 nSeriesIdx = 0; nSeriesIdx < nNumSeriesData; ++nSeriesIdx, ++nReUsedSeriesIdx ) { try { Reference< XDataSeries > xSeries; if( nReUsedSeriesIdx < rSeriesToReUse.getLength()) xSeries.set( rSeriesToReUse[nReUsedSeriesIdx] ); else xSeries.set( new DataSeries( GetComponentContext() ) ); OSL_ASSERT( xSeries.is() ); Reference< data::XDataSink > xSink( xSeries, uno::UNO_QUERY_THROW ); OSL_ASSERT( xSink.is() ); xSink->setData( aSequences[nGroupIndex][nSeriesIdx] ); aResultSeries[nGroupIndex][nSeriesIdx].set( xSeries ); } catch( uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } } } return InterpretedData( aResultSeries, xCategories ); } // criterion: there must be two groups for stock-charts with volume and all // series must have the correct number of data::XLabeledDataSequences // todo: skip first criterion? (to allow easy switch from stock-chart without // volume to one with volume) sal_Bool SAL_CALL StockDataInterpreter::isDataCompatible( const InterpretedData& aInterpretedData ) throw (uno::RuntimeException) { // high/low/close sal_Int32 nNumberOfNecessarySequences = 3; // open StockChartTypeTemplate::StockVariant eVar( GetStockVariant()); if( ( eVar == StockChartTypeTemplate::OPEN_LOW_HI_CLOSE ) || ( eVar == StockChartTypeTemplate::VOL_OPEN_LOW_HI_CLOSE )) ++nNumberOfNecessarySequences; // volume bool bHasVolume = (( eVar == StockChartTypeTemplate::VOL_LOW_HI_CLOSE ) || ( eVar == StockChartTypeTemplate::VOL_OPEN_LOW_HI_CLOSE )); // 1. correct number of sub-types if( aInterpretedData.Series.getLength() < (bHasVolume ? 2 : 1 )) return sal_False; // 2. a. volume -- use default check if( bHasVolume ) { if( ! DataInterpreter::isDataCompatible( InterpretedData( Sequence< Sequence< Reference< XDataSeries > > >( aInterpretedData.Series.getConstArray(), 1 ), aInterpretedData.Categories ))) return sal_False; } // 2. b. candlestick { OSL_ASSERT( aInterpretedData.Series.getLength() > (bHasVolume ? 1 : 0)); Sequence< Reference< XDataSeries > > aSeries( aInterpretedData.Series[(bHasVolume ? 1 : 0)] ); if(!aSeries.getLength()) return sal_False; for( sal_Int32 i=0; i<aSeries.getLength(); ++i ) { try { Reference< data::XDataSource > xSrc( aSeries[i], uno::UNO_QUERY_THROW ); Sequence< Reference< data::XLabeledDataSequence > > aSeq( xSrc->getDataSequences()); if( aSeq.getLength() != nNumberOfNecessarySequences ) return sal_False; } catch( uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } } } // 2. c. additional series // ignore return sal_True; } InterpretedData SAL_CALL StockDataInterpreter::reinterpretDataSeries( const InterpretedData& aInterpretedData ) throw (uno::RuntimeException) { // prerequisite: StockDataInterpreter::isDataCompatible() returned true return aInterpretedData; } } // namespace chart
37.516129
129
0.641601
Grosskopf
f2a9d07a41acfc84fd8f119e5fa61f252cefb836
1,091
cpp
C++
hw2/q1/Date.cpp
BenEf97/BarBenCPP
556eebfeeadd210cc9552915d58c274b8f881eb7
[ "MIT" ]
1
2022-03-01T19:09:52.000Z
2022-03-01T19:09:52.000Z
hw2/q1/Date.cpp
BenEf97/BarBenCPP
556eebfeeadd210cc9552915d58c274b8f881eb7
[ "MIT" ]
1
2022-03-01T19:14:11.000Z
2022-03-01T19:14:34.000Z
hw2/q1/Date.cpp
BenEf97/BarBenCPP
556eebfeeadd210cc9552915d58c274b8f881eb7
[ "MIT" ]
null
null
null
#include "Date.h" #include <iostream> using namespace std; //Work on date, all the functions. Date::Date(int d, int m, int y) { setDay(d); setMonth(m); setYear(y); } //Empty constructor Date::Date() { day = 1; month = 1; year = 2000; } //returns the day int Date::getDay() const { return day; } //returns the month int Date::getMonth() const { return month; } //returns the year int Date::getYear() const { return year; } //setting the day, checks for valid input. void Date::setDay(int d) { //Checks for valid input, assuming month has 30 days. If the input is invalid, will set day=0. if (d < 1 || d > 30) day = 0; else day = d; } //setting the month, checks for valid input. void Date::setMonth(int m) { //Checks for valid inout, if there is invalid input will be set month=0 if (m < 1 || m > 12) month = 0 ; else month = m; } //setting the year void Date::setYear(int y) { if (y>0) year = y; else year = 2000; } //Prints the date in dd/mm/yy format. void Date::PrintDate() const { cout << "The Date: "<<day<<"/"<<month<<"/"<<year<<"\n"<<endl; }
14.168831
95
0.629698
BenEf97
f2ab7d41580507baa21e49b214b9807de8575698
742
cpp
C++
src/autoc4player.cpp
ghostdart/connect-four
5910c7e5952b1f1dbeafb0eb0f9eb94fc6bd0f69
[ "MIT" ]
null
null
null
src/autoc4player.cpp
ghostdart/connect-four
5910c7e5952b1f1dbeafb0eb0f9eb94fc6bd0f69
[ "MIT" ]
null
null
null
src/autoc4player.cpp
ghostdart/connect-four
5910c7e5952b1f1dbeafb0eb0f9eb94fc6bd0f69
[ "MIT" ]
null
null
null
#include "autoc4player.h" AutoC4Player::AutoC4Player(char Color) : Player("Auto:Random", Color) { // Just call the base constructor } double AutoC4Player::EvaluateState(GameBoard *Board) { // Board Evaluation Area; // This auto-player is not using it. return 0; } Connect4Move *AutoC4Player::SuggestMove(GameState *State) { Connect4Move *Move = new Connect4Move; std::vector<GameMove *> Moves = State->GetPossibleMoves(); int Total = int(Moves.size()); if (Total == 0) { return nullptr; } int MoveIndex = int(float(rand()) / RAND_MAX * Total); Move->SetMove(static_cast<Connect4Move *>(Moves[MoveIndex])->GetMove()); for (int i = 0; i < Total; i++) delete Moves[i]; Moves.clear(); return Move; }
20.611111
74
0.673854
ghostdart
f2aba9e999a6b84c6f9dd7cdfa8d600bd785d8b8
18,712
cpp
C++
lib/Front/Input.cpp
axia-sw/Doll
a5846a6553d9809e9a0ea50db2dc18b95eb21921
[ "Zlib" ]
1
2021-07-19T14:40:15.000Z
2021-07-19T14:40:15.000Z
lib/Front/Input.cpp
axia-sw/Doll
a5846a6553d9809e9a0ea50db2dc18b95eb21921
[ "Zlib" ]
null
null
null
lib/Front/Input.cpp
axia-sw/Doll
a5846a6553d9809e9a0ea50db2dc18b95eb21921
[ "Zlib" ]
null
null
null
#define DOLL_TRACE_FACILITY doll::kLog_FrontendInput #include "../BuildSettings.hpp" #include "doll/Front/Input.hpp" #include "doll/Front/Frontend.hpp" #include "doll/Core/Logger.hpp" #include "doll/OS/App.hpp" #include "doll/OS/Window.hpp" namespace doll { struct SWndInputState { static const UPtr kNumFieldBits = sizeof(UPtr)*8; static const UPtr kNumKeyFields = 0x100/kNumFieldBits; static const UPtr kNumMouseBtns = 8; UPtr keys[ kNumKeyFields ]; UPtr mouse; MutStr entry; Bool entryEnabled; S32 mouseX, mouseY; F32 mouseZ; Bool mouseInWindow; S32 mouseDeltaX, mouseDeltaY; F32 mouseDeltaZ; Bool mouseDeltaDirty; U8 keyHits[ 0x100 ]; U8 keyRels[ 0x100 ]; U8 mouseHits[ kNumMouseBtns ]; U8 mouseRels[ kNumMouseBtns ]; U8 keyPressed; U32 cActions; SCoreInputAction actions[ kMaxInputActions ]; inline SWndInputState() : mouse(0) , entry() , entryEnabled( false ) , mouseX( 0 ) , mouseY( 0 ) , mouseZ( 0.0f ) , mouseInWindow( false ) , mouseDeltaX( 0 ) , mouseDeltaY( 0 ) , mouseDeltaZ( 0.0f ) , mouseDeltaDirty( true ) , keyPressed( 0 ) , cActions( 0 ) { memset( &keys[0], 0, sizeof(keys) ); memset( &keyHits[0], 0, sizeof(keyHits) ); memset( &keyRels[0], 0, sizeof(keyRels) ); memset( &mouseHits[0], 0, sizeof(mouseHits) ); memset( &mouseRels[0], 0, sizeof(mouseRels) ); } inline Void setKey( U8 index ) { const U8 i = index/kNumFieldBits; const U8 j = index%kNumFieldBits; keys[i] |= UPtr(1)<<j; } inline Void clearKey( U8 index ) { const U8 i = index/kNumFieldBits; const U8 j = index%kNumFieldBits; keys[i] &= ~(UPtr(1)<<j); } inline Bool testKey( U8 index ) const { const U8 i = index/kNumFieldBits; const U8 j = index%kNumFieldBits; return ( keys[i] & (UPtr(1)<<j) ) != 0; } inline Void hitKey( U8 index ) { if( keyHits[index] < 0xFF ) { ++keyHits[index]; } } inline Void relKey( U8 index ) { if( keyRels[ index ] < 0xFF ) { ++keyRels[index]; } } inline Void hitMouse( U8 index ) { if( index >= kNumMouseBtns ) { return; } if( mouseHits[ index ] < 0xFF ) { ++mouseHits[index]; } } inline Void relMouse( U8 index ) { if( index >= kNumMouseBtns ) { return; } if( mouseRels[ index ] < 0xFF ) { ++mouseRels[index]; } } inline Void setMouse( U8 index ) { mouse |= UPtr(1)<<index; } inline Void clearMouse( U8 index ) { mouse &= ~(UPtr(1)<<index); } inline Bool testMouse( U8 index ) const { return ( mouse & (UPtr(1)<<index) ) != 0; } inline Bool setEntry( const Str &newEntry ) { return entry.tryAssign( newEntry ); } inline Void entryBackspace() { U8 x; do { x = entry.lastByte(); entry.dropMe(); } while( ( x & 0x80 ) != 0 ); } inline Bool handleEntryChar( U32 utf32Char ) { if( !utf32Char ) { return true; } if( utf32Char == '\b' ) { entryBackspace(); return true; } axstr_utf8_t buf[ 5 ] = { 0, 0, 0, 0, 0 }; const axstr_utf32_t src[ 2 ] = { utf32Char, 0 }; axstr_utf32_to_utf8( buf, sizeof( buf ), src ); return entry.tryAppend( Str( ( char * )buf ) ); } inline Void handleMouseMove( S32 clientPosX, S32 clientPosY ) { if( mouseDeltaDirty ) { mouseDeltaDirty = false; } else { mouseDeltaX += clientPosX - mouseX; mouseDeltaY += clientPosY - mouseY; } mouseX = clientPosX; mouseY = clientPosY; } SCoreInputAction *findAction( ECoreInputAction cmd ) { for( U32 i = 0; i < cActions; ++i ) { if( actions[ i ].command == cmd ) { return &actions[ i ]; } } return nullptr; } const SCoreInputAction *findAction( EKey key, U32 uMods ) const { for( U32 i = 0; i < cActions; ++i ) { const SCoreInputAction &act = actions[ i ]; if( act.key == key && act.uMods == uMods ) { return &act; } } return nullptr; } Bool addAction( const SCoreInputAction &act ) { // Don't add exact duplicates for( U32 i = 0; i < cActions; ++i ) { const SCoreInputAction &cmpAct = actions[ i ]; if( act.command == cmpAct.command && act.key == cmpAct.key && act.uMods == cmpAct.uMods ) { return true; } } // Check if we're at the limit if( cActions >= kMaxInputActions ) { return false; } actions[ cActions++ ] = act; return true; } Bool setAction( const SCoreInputAction &act ) { SCoreInputAction *pAct = findAction( act.command ); if( !pAct ) { return addAction( act ); } *pAct = act; return true; } Void removeAction( const SCoreInputAction &act ) { for( U32 i = 0; i < cActions; ++i ) { SCoreInputAction &cmpAct = actions[ i ]; if( act.command != cmpAct.command || act.key != cmpAct.key || act.uMods != cmpAct.uMods ) { continue; } if( i < --cActions ) { cmpAct = actions[ cActions ]; } } } Bool hasAction( const SCoreInputAction &act ) const { for( U32 i = 0; i < cActions; ++i ) { const SCoreInputAction &cmpAct = actions[ i ]; if( act.command == cmpAct.command && act.key == cmpAct.key && act.uMods == cmpAct.uMods ) { return true; } } return false; } Void issueCommand( ECoreInputAction cmd ) { switch( cmd ) { case ECoreInputAction::Quit: g_DebugLog += "'Quit' action issued. (Probably pressed the 'Esc' key.)"; os_submitQuitEvent(); return; case ECoreInputAction::ToggleFullscreen: DOLL_WARNING_LOG += "'ToggleFullscreen' action not implemented"; return; case ECoreInputAction::CaptureScreenshot: DOLL_WARNING_LOG += "'CaptureScreenshot' action not implemented"; return; case ECoreInputAction::OpenDevcon: DOLL_WARNING_LOG += "'OpenDevcon' action not implemented"; return; case ECoreInputAction::ToggleGraphs: DOLL_WARNING_LOG += "'ToggleGraphs' action not implemented"; return; } char szBuf[128]; DOLL_ERROR_LOG += (axspf(szBuf,"Unknown action '%u'",U32(cmd)),szBuf); } Bool checkCommand( EKey key, U32 uMods ) { const SCoreInputAction *const pAct = findAction( key, uMods ); if( !pAct ) { return false; } issueCommand( pAct->command ); return true; } }; static SWndInputState *getWndInput( OSWindow wnd ) { static SWndInputState mainWndInputState; if( ~g_core.input.uFlags & kCoreInF_Enabled ) { return nullptr; } #if DOLL__USE_GLFW if( !wnd ) { return &mainWndInputState; } #else if( !wnd || wnd == g_core.view.window ) { return &mainWndInputState; } #endif return nullptr; } // ------------------------------------------------------------------ // DOLL_FUNC EWndReply in_onAcceptKey_f( OSWindow wnd ) { SWndInputState *const p = getWndInput( wnd ); if( !p ) { return EWndReply::NotHandled; } // FIXME: Load all current key state up here (at the time of the // message's delivery) return EWndReply::Handled; } DOLL_FUNC EWndReply in_onResignKey_f( OSWindow wnd ) { SWndInputState *const p = getWndInput( wnd ); if( !p ) { return EWndReply::NotHandled; } // FIXME: This should probably do something useful or be removed return EWndReply::Handled; } DOLL_FUNC EWndReply in_onKeyPress_f( OSWindow wnd, EKey key, U32 uModFlags, Bool isRepeat ) { SWndInputState *const p = getWndInput( wnd ); if( !p ) { return EWndReply::NotHandled; } if( !isRepeat ) { if( p->checkCommand( key, uModFlags ) ) { return EWndReply::Handled; } p->hitKey( (U8)key ); p->keyPressed = (U8)key; } p->setKey( (U8)key ); return EWndReply::Handled; } DOLL_FUNC EWndReply in_onKeyRelease_f( OSWindow wnd, EKey key, U32 uModFlags ) { SWndInputState *const p = getWndInput( wnd ); if( !p ) { return EWndReply::NotHandled; } ( Void )uModFlags; p->relKey( (U8)key ); if( p->keyPressed == ( U8 )key ) { p->keyPressed = 0; } p->clearKey( (U8)key ); return EWndReply::Handled; } DOLL_FUNC EWndReply in_onKeyChar_f( OSWindow wnd, U32 utf32Char ) { SWndInputState *const p = getWndInput( wnd ); if( !p ) { return EWndReply::NotHandled; } // FIXME: Check return value and do something useful (like notify the user) p->handleEntryChar( utf32Char ); return EWndReply::Handled; } DOLL_FUNC EWndReply in_onMousePress_f( OSWindow wnd, EMouse button, S32 clientPosX, S32 clientPosY, U32 uModFlags ) { SWndInputState *const p = getWndInput( wnd ); if( !p || button == EMouse::None ) { return EWndReply::NotHandled; } ( Void )uModFlags; p->setMouse( U8(button) - 1 ); p->handleMouseMove( clientPosX, clientPosY ); p->mouseInWindow = true; p->hitMouse( U8(button) - 1 ); return EWndReply::Handled; } DOLL_FUNC EWndReply in_onMouseRelease_f( OSWindow wnd, EMouse button, S32 clientPosX, S32 clientPosY, U32 uModFlags ) { SWndInputState *const p = getWndInput( wnd ); if( !p || button == EMouse::None ) { return EWndReply::NotHandled; } ( Void )uModFlags; p->clearMouse( U8(button) - 1 ); p->handleMouseMove( clientPosX, clientPosY ); p->mouseInWindow = true; p->relMouse( U8(button) - 1 ); return EWndReply::Handled; } DOLL_FUNC EWndReply in_onMouseWheel_f( OSWindow wnd, F32 fDelta, S32 clientPosX, S32 clientPosY, U32 uModFlags ) { SWndInputState *const p = getWndInput( wnd ); if( !p ) { return EWndReply::NotHandled; } ( Void )uModFlags; p->mouseZ += fDelta; p->mouseDeltaZ += fDelta; p->handleMouseMove( clientPosX, clientPosY ); p->mouseInWindow = true; return EWndReply::Handled; } DOLL_FUNC EWndReply in_onMouseMove_f( OSWindow wnd, S32 clientPosX, S32 clientPosY, U32 uModFlags ) { SWndInputState *const p = getWndInput( wnd ); if( !p ) { return EWndReply::NotHandled; } ( void )uModFlags; p->handleMouseMove( clientPosX, clientPosY ); p->mouseInWindow = true; return EWndReply::Handled; } DOLL_FUNC EWndReply in_onMouseExit_f( OSWindow wnd, U32 uModFlags ) { SWndInputState *const p = getWndInput( wnd ); if( !p ) { return EWndReply::NotHandled; } ( Void )uModFlags; p->mouseInWindow = false; return EWndReply::Handled; } // ------------------------------------------------------------------ // DOLL_FUNC Void DOLL_API in_enableAll() { g_core.input.uFlags |= kCoreInF_Enabled; } DOLL_FUNC Void DOLL_API in_disableAll() { g_core.input.uFlags &= ~kCoreInF_Enabled; } DOLL_FUNC Bool DOLL_API in_allEnabled() { return ( g_core.input.uFlags & kCoreInF_Enabled ) != 0; } DOLL_FUNC Bool DOLL_API in_keyState( EKey key, OSWindow wnd ) { SWndInputState const *const p = getWndInput( wnd ); if( !p ) { return false; } return p->testKey( (U8)key ); } DOLL_FUNC Bool DOLL_API in_keyHit( EKey key, OSWindow wnd ) { SWndInputState *const p = getWndInput( wnd ); if( !p ) { return false; } if( p->keyHits[ ( U8 )key ] > 0 ) { --p->keyHits[ (U8)key ]; return true; } return false; } DOLL_FUNC Bool DOLL_API in_keyReleased( EKey key, OSWindow wnd ) { SWndInputState *const p = getWndInput( wnd ); if( !p ) { return false; } if( p->keyRels[ ( U8 )key ] > 0 ) { --p->keyRels[ (U8)key ]; return true; } return false; } DOLL_FUNC U8 DOLL_API in_scancode( OSWindow wnd ) { SWndInputState const *const p = getWndInput( wnd ); if( !p ) { return 0; } return p->keyPressed; } DOLL_FUNC Bool DOLL_API in_mouseState( EMouse button, OSWindow wnd ) { SWndInputState const *const p = getWndInput( wnd ); if( !p || button == EMouse::None ) { return false; } return p->testMouse( U8(button) - 1 ); } DOLL_FUNC Bool DOLL_API in_mouseHit( EMouse button, OSWindow wnd ) { SWndInputState *const p = getWndInput( wnd ); if( !p || button == EMouse::None ) { return false; } const U8 index = U8( button ) - 1; if( index >= SWndInputState::kNumMouseBtns ) { return false; } if( p->mouseHits[ index ] > 0 ) { --p->mouseHits[ index ]; return true; } return false; } DOLL_FUNC Bool DOLL_API in_mouseReleased( EMouse button, OSWindow wnd ) { SWndInputState *const p = getWndInput( wnd ); if( !p || button == EMouse::None ) { return false; } const U8 index = U8( button ) - 1; if( index >= SWndInputState::kNumMouseBtns ) { return false; } if( p->mouseRels[ index ] > 0 ) { --p->mouseRels[ index ]; return true; } return false; } DOLL_FUNC S32 DOLL_API in_mouseX( OSWindow wnd ) { SWndInputState const *const p = getWndInput( wnd ); if( !p ) { return 0; } return p->mouseX; } DOLL_FUNC S32 DOLL_API in_mouseY( OSWindow wnd ) { SWndInputState const *const p = getWndInput( wnd ); if( !p ) { return 0; } return p->mouseY; } DOLL_FUNC F32 DOLL_API in_mouseZ( OSWindow wnd ) { SWndInputState const *const p = getWndInput( wnd ); if( !p ) { return 0.0f; } return p->mouseZ; } DOLL_FUNC Void DOLL_API in_setMouseZ( F32 z, OSWindow wnd ) { SWndInputState *const p = getWndInput( wnd ); if( !p ) { return; } p->mouseZ = z; } DOLL_FUNC S32 DOLL_API in_mouseMoveX( OSWindow wnd ) { SWndInputState const *const p = getWndInput( wnd ); if( !p ) { return 0; } return p->mouseDeltaX; } DOLL_FUNC S32 DOLL_API in_mouseMoveY( OSWindow wnd ) { SWndInputState const *const p = getWndInput( wnd ); if( !p ) { return 0; } return p->mouseDeltaY; } DOLL_FUNC F32 DOLL_API in_mouseMoveZ( OSWindow wnd ) { SWndInputState const *const p = getWndInput( wnd ); if( !p ) { return 0.0f; } return p->mouseDeltaZ; } DOLL_FUNC Void DOLL_API in_resetMouseMove( OSWindow wnd ) { SWndInputState *const p = getWndInput( wnd ); if( !p ) { return; } p->mouseDeltaX = 0; p->mouseDeltaY = 0; p->mouseDeltaZ = 0; } DOLL_FUNC Void DOLL_API in_enableEntry( OSWindow wnd ) { SWndInputState *const p = getWndInput( wnd ); if( !p ) { return; } p->entryEnabled = true; } DOLL_FUNC Void DOLL_API in_disableEntry( OSWindow wnd ) { SWndInputState *const p = getWndInput( wnd ); if( !p ) { return; } p->entryEnabled = false; } DOLL_FUNC Bool DOLL_API in_isEntryEnabled( OSWindow wnd ) { SWndInputState const *const p = getWndInput( wnd ); if( !p ) { return false; } return p->entryEnabled; } DOLL_FUNC Bool DOLL_API in_setEntry( Str entry, OSWindow wnd ) { SWndInputState *const p = getWndInput( wnd ); if( !p ) { return false; } return p->entry.tryAssign( entry ); } DOLL_FUNC Bool DOLL_API in_getEntry( Str &dst, OSWindow wnd ) { SWndInputState const *const p = getWndInput( wnd ); if( !p ) { dst = Str(); return false; } dst = p->entry; return true; } DOLL_FUNC Bool DOLL_API in_addAction( const SCoreInputAction &act, OSWindow wnd ) { SWndInputState *const p = getWndInput( wnd ); if( !p ) { return false; } return p->addAction( act ); } DOLL_FUNC Bool DOLL_API in_setAction( const SCoreInputAction &act, OSWindow wnd ) { SWndInputState *const p = getWndInput( wnd ); if( !p ) { return false; } return p->setAction( act ); } DOLL_FUNC Void DOLL_API in_removeAction( const SCoreInputAction &act, OSWindow wnd ) { SWndInputState *const p = getWndInput( wnd ); if( !p ) { return; } p->removeAction( act ); } DOLL_FUNC Bool DOLL_API in_hasAction( const SCoreInputAction &act, OSWindow wnd ) { const SWndInputState *const p = getWndInput( wnd ); if( !p ) { return false; } return p->hasAction( act ); } static const SCoreInputAction g_escapeAct = { EKey::Esc, 0, ECoreInputAction::Quit }; DOLL_FUNC Void DOLL_API in_enableEscapeKey( OSWindow wnd ) { in_setAction( g_escapeAct, wnd ); } DOLL_FUNC Void DOLL_API in_disableEscapeKey( OSWindow wnd ) { in_removeAction( g_escapeAct, wnd ); } DOLL_FUNC Bool DOLL_API in_escapeKeyEnabled( OSWindow wnd ) { return in_hasAction( g_escapeAct, wnd ); } static const SCoreInputAction g_togfullAct1 = { EKey::Enter, kMF_Shift, ECoreInputAction::ToggleFullscreen }; static const SCoreInputAction g_togfullAct2 = { EKey::F11, 0, ECoreInputAction::ToggleFullscreen }; DOLL_FUNC Void DOLL_API in_enableToggleFullscreen( OSWindow wnd ) { in_setAction( g_togfullAct1, wnd ); in_setAction( g_togfullAct2, wnd ); } DOLL_FUNC Void DOLL_API in_disableToggleFullscreen( OSWindow wnd ) { in_removeAction( g_togfullAct2, wnd ); in_removeAction( g_togfullAct1, wnd ); } DOLL_FUNC Bool DOLL_API in_toggleFullscreenEnabled( OSWindow wnd ) { return in_hasAction( g_togfullAct1, wnd ) || in_hasAction( g_togfullAct2, wnd ); } static const SCoreInputAction g_screencapAct = { EKey::F2, 0, ECoreInputAction::CaptureScreenshot }; DOLL_FUNC Void DOLL_API in_enableScreenshot( OSWindow wnd ) { in_setAction( g_screencapAct, wnd ); } DOLL_FUNC Void DOLL_API in_disableScreenshot( OSWindow wnd ) { in_removeAction( g_screencapAct, wnd ); } DOLL_FUNC Bool DOLL_API in_screenshotEnabled( OSWindow wnd ) { return in_hasAction( g_screencapAct, wnd ); } static const SCoreInputAction g_devconAct = { EKey::Grave, 0, ECoreInputAction::OpenDevcon }; DOLL_FUNC Void DOLL_API in_enableDevcon( OSWindow wnd ) { in_setAction( g_devconAct, wnd ); } DOLL_FUNC Void DOLL_API in_disableDevcon( OSWindow wnd ) { in_removeAction( g_devconAct, wnd ); } DOLL_FUNC Bool DOLL_API in_devconEnabled( OSWindow wnd ) { return in_hasAction( g_devconAct, wnd ); } static const SCoreInputAction g_devdbgAct = { EKey::F3, 0, ECoreInputAction::ToggleGraphs }; DOLL_FUNC Void DOLL_API in_enableDevDebug( OSWindow wnd ) { in_setAction( g_devdbgAct, wnd ); } DOLL_FUNC Void DOLL_API in_disableDevDebug( OSWindow wnd ) { in_removeAction( g_devdbgAct, wnd ); } DOLL_FUNC Bool DOLL_API in_devDebugEnabled( OSWindow wnd ) { return in_hasAction( g_devdbgAct, wnd ); } }
23.01599
119
0.617946
axia-sw
f2acb8641b7513b5eb33a587f8578d5016fe58aa
2,657
hpp
C++
project/cpp/console.hpp
umamibeef/UBC-ELEC-542-Coursework
33145e95730a5c9d9cfb1252cc67ebe6820c58c4
[ "MIT" ]
null
null
null
project/cpp/console.hpp
umamibeef/UBC-ELEC-542-Coursework
33145e95730a5c9d9cfb1252cc67ebe6820c58c4
[ "MIT" ]
null
null
null
project/cpp/console.hpp
umamibeef/UBC-ELEC-542-Coursework
33145e95730a5c9d9cfb1252cc67ebe6820c58c4
[ "MIT" ]
null
null
null
/** MIT License Copyright (c) [2022] [Michel Kakulphimp] 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. **/ #pragma once extern int program_verbosity; // Console ANSI colors #define ANSI_FG_COLOR_RED "\x1b[31m" #define ANSI_FG_COLOR_GREEN "\x1b[32m" #define ANSI_FG_COLOR_YELLOW "\x1b[33m" #define ANSI_FG_COLOR_BLUE "\x1b[34m" #define ANSI_FG_COLOR_MAGENTA "\x1b[35m" #define ANSI_FG_COLOR_CYAN "\x1b[36m" #define ANSI_BG_COLOR_BLACK "\x1b[40m" #define ANSI_BG_COLOR_RED "\x1b[41m" #define ANSI_BG_COLOR_GREEN "\x1b[42m" #define ANSI_BG_COLOR_YELLOW "\x1b[43m" #define ANSI_BG_COLOR_BLUE "\x1b[44m" #define ANSI_BG_COLOR_MAGENTA "\x1b[45m" #define ANSI_BG_COLOR_CYAN "\x1b[46m" #define ANSI_BG_COLOR_WHITE "\x1b[47m" #define ANSI_COLOR_RESET "\x1b[0m" #define ERASE_SCREEN "\x1b[2J" #define TAB1 " " #define TAB2 " " typedef enum { CLIENT_NONE = 0, CLIENT_SIM, CLIENT_CUDA, CLIENT_CUSOLVER, CLIENT_LAPACK, } client_e; typedef enum { LEVEL_NONE = 0, LEVEL_INFO, LEVEL_WARNING, LEVEL_ERROR, LEVEL_RULE, } level_e; // Headers #include <iostream> // Functions void console_print(int verbose_level, std::string input_string, client_e client); void console_print_err(int verbose_level, std::string input_string, client_e client); void console_print_warn(int verbose_level, std::string input_string, client_e client); void console_print_spacer(int verbose_level, client_e client); void console_print_hr(int verbose_level, client_e client);
34.064103
87
0.723372
umamibeef
f2aced26cc0b0822d6a78a499e7cb8f779b3bb62
348
cpp
C++
native/src/iid.cpp
kekekeks/prowingen
35585859cca66c2b1c4d865570b6ca1debf7ff60
[ "MIT" ]
6
2015-03-13T20:27:58.000Z
2017-09-26T07:01:37.000Z
native/src/iid.cpp
kekekeks/prowingen
35585859cca66c2b1c4d865570b6ca1debf7ff60
[ "MIT" ]
null
null
null
native/src/iid.cpp
kekekeks/prowingen
35585859cca66c2b1c4d865570b6ca1debf7ff60
[ "MIT" ]
null
null
null
#include "api.h" // [Guid("918cfa9b-a766-41e7-9c4b-330954d01b47")] const GUID IID_IHttpServer = { 0x918cfa9b, 0xa766, 0x41e7, { 0x9c, 0x4b, 0x33, 0x9, 0x54, 0xd0, 0x1b, 0x47 } }; // [Guid("e4ea9822-30c8-4319-9d80-5a0e48de0be5")] const GUID IID_IProwingenFactory = { 0xe4ea9822, 0x30c8, 0x4319, { 0x9d, 0x80, 0x5a, 0xe, 0x48, 0xde, 0xb, 0xe5 } };
43.5
116
0.695402
kekekeks
f2ad4fd1c7dff9f2980a2baded3de67d538948d9
3,438
hxx
C++
opencascade/ApproxInt_SvSurfaces.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/ApproxInt_SvSurfaces.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/ApproxInt_SvSurfaces.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 1993-03-17 // Created by: Laurent BUCHARD // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _ApproxInt_SvSurfaces_HeaderFile #define _ApproxInt_SvSurfaces_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Boolean.hxx> #include <Standard_Real.hxx> class gp_Pnt; class gp_Vec; class gp_Vec2d; class IntSurf_PntOn2S; class ApproxInt_SvSurfaces { public: DEFINE_STANDARD_ALLOC //! returns True if Tg,Tguv1 Tguv2 can be computed. Standard_EXPORT virtual Standard_Boolean Compute (Standard_Real& u1, Standard_Real& v1, Standard_Real& u2, Standard_Real& v2, gp_Pnt& Pt, gp_Vec& Tg, gp_Vec2d& Tguv1, gp_Vec2d& Tguv2) = 0; Standard_EXPORT virtual void Pnt (const Standard_Real u1, const Standard_Real v1, const Standard_Real u2, const Standard_Real v2, gp_Pnt& P) = 0; //! computes point on curve and parameters on the surfaces Standard_EXPORT virtual Standard_Boolean SeekPoint(const Standard_Real u1, const Standard_Real v1, const Standard_Real u2, const Standard_Real v2, IntSurf_PntOn2S& Point) = 0; Standard_EXPORT virtual Standard_Boolean Tangency (const Standard_Real u1, const Standard_Real v1, const Standard_Real u2, const Standard_Real v2, gp_Vec& Tg) = 0; Standard_EXPORT virtual Standard_Boolean TangencyOnSurf1 (const Standard_Real u1, const Standard_Real v1, const Standard_Real u2, const Standard_Real v2, gp_Vec2d& Tg) = 0; Standard_EXPORT virtual Standard_Boolean TangencyOnSurf2 (const Standard_Real u1, const Standard_Real v1, const Standard_Real u2, const Standard_Real v2, gp_Vec2d& Tg) = 0; Standard_EXPORT virtual ~ApproxInt_SvSurfaces(); protected: private: }; #endif // _ApproxInt_SvSurfaces_HeaderFile
35.443299
100
0.550611
valgur
f2ae01098e156f31bd614060b130104bbfb76693
2,164
cpp
C++
raw-examples/cpp11/doublebufferedqueue/main.cpp
paoqi1997/pqnet
3413916bdc355b0a4eea8ef934a3ff658b047b19
[ "BSD-3-Clause" ]
null
null
null
raw-examples/cpp11/doublebufferedqueue/main.cpp
paoqi1997/pqnet
3413916bdc355b0a4eea8ef934a3ff658b047b19
[ "BSD-3-Clause" ]
null
null
null
raw-examples/cpp11/doublebufferedqueue/main.cpp
paoqi1997/pqnet
3413916bdc355b0a4eea8ef934a3ff658b047b19
[ "BSD-3-Clause" ]
null
null
null
#include <chrono> #include <iostream> #include <thread> #include "doublebufferedqueue.h" using std::cout; using std::endl; using std::chrono::system_clock; using std::chrono::time_point; using std::chrono::time_point_cast; using us_type = std::chrono::microseconds; std::uint64_t now() { time_point<system_clock, us_type> tp = time_point_cast<us_type>(system_clock::now()); return tp.time_since_epoch().count(); } int cnt1 = 0, cnt2 = 0; int sum = 10000; void producerFunc1(Queue<int> *queue); void producerFunc2(DoubleBufferedQueue<int> *queue); void consumerFunc1(Queue<int> *queue); void consumerFunc2(DoubleBufferedQueue<int> *queue); int main() { std::uint64_t t1, t2; for (int i = 0; i < 5; ++i) { // Queue { Queue<int> queue; auto beginTime = now(); std::thread producer(producerFunc1, &queue); std::thread consumer(consumerFunc1, &queue); producer.join(); consumer.join(); t1 = now() - beginTime; } // DoubleBufferedQueue { DoubleBufferedQueue<int> queue; auto beginTime = now(); std::thread producer(producerFunc2, &queue); std::thread consumer(consumerFunc2, &queue); producer.join(); consumer.join(); t2 = now() - beginTime; } // 输出耗时 cout << t1 << ' ' << t2 << endl; } return 0; } void producerFunc1(Queue<int> *queue) { for (int i = 0; i < sum; ++i) { queue->push(i); } } void producerFunc2(DoubleBufferedQueue<int> *queue) { for (int i = 0; i < sum; ++i) { queue->push(i); } } void consumerFunc1(Queue<int> *queue) { for (;;) { if (cnt1 == sum) { cnt1 = 0; break; } else if (!queue->empty()) { queue->pop(); ++cnt1; } } } void consumerFunc2(DoubleBufferedQueue<int> *queue) { for (;;) { if (cnt2 == sum) { cnt2 = 0; break; } else if (!queue->empty()) { queue->pop(); ++cnt2; } } }
20.807692
89
0.530961
paoqi1997
f2b11ebe42929f3001cb71231fe45ac346fd57fc
23,364
cxx
C++
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimWallParams.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
3
2016-05-30T15:12:16.000Z
2022-03-22T08:11:13.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimWallParams.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
21
2016-06-13T11:33:45.000Z
2017-05-23T09:46:52.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimWallParams.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
null
null
null
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // // Begin prologue. // // // End prologue. #include <xsd/cxx/pre.hxx> #include "SimWallParams.hxx" namespace schema { namespace simxml { namespace ResourcesGeneral { // SimWallParams // const SimWallParams::Thickness_optional& SimWallParams:: Thickness () const { return this->Thickness_; } SimWallParams::Thickness_optional& SimWallParams:: Thickness () { return this->Thickness_; } void SimWallParams:: Thickness (const Thickness_type& x) { this->Thickness_.set (x); } void SimWallParams:: Thickness (const Thickness_optional& x) { this->Thickness_ = x; } const SimWallParams::Length_optional& SimWallParams:: Length () const { return this->Length_; } SimWallParams::Length_optional& SimWallParams:: Length () { return this->Length_; } void SimWallParams:: Length (const Length_type& x) { this->Length_.set (x); } void SimWallParams:: Length (const Length_optional& x) { this->Length_ = x; } const SimWallParams::Height_optional& SimWallParams:: Height () const { return this->Height_; } SimWallParams::Height_optional& SimWallParams:: Height () { return this->Height_; } void SimWallParams:: Height (const Height_type& x) { this->Height_.set (x); } void SimWallParams:: Height (const Height_optional& x) { this->Height_ = x; } const SimWallParams::BaseElevation_optional& SimWallParams:: BaseElevation () const { return this->BaseElevation_; } SimWallParams::BaseElevation_optional& SimWallParams:: BaseElevation () { return this->BaseElevation_; } void SimWallParams:: BaseElevation (const BaseElevation_type& x) { this->BaseElevation_.set (x); } void SimWallParams:: BaseElevation (const BaseElevation_optional& x) { this->BaseElevation_ = x; } const SimWallParams::RefLinePosition_optional& SimWallParams:: RefLinePosition () const { return this->RefLinePosition_; } SimWallParams::RefLinePosition_optional& SimWallParams:: RefLinePosition () { return this->RefLinePosition_; } void SimWallParams:: RefLinePosition (const RefLinePosition_type& x) { this->RefLinePosition_.set (x); } void SimWallParams:: RefLinePosition (const RefLinePosition_optional& x) { this->RefLinePosition_ = x; } void SimWallParams:: RefLinePosition (::std::auto_ptr< RefLinePosition_type > x) { this->RefLinePosition_.set (x); } const SimWallParams::RefLinePath_optional& SimWallParams:: RefLinePath () const { return this->RefLinePath_; } SimWallParams::RefLinePath_optional& SimWallParams:: RefLinePath () { return this->RefLinePath_; } void SimWallParams:: RefLinePath (const RefLinePath_type& x) { this->RefLinePath_.set (x); } void SimWallParams:: RefLinePath (const RefLinePath_optional& x) { this->RefLinePath_ = x; } void SimWallParams:: RefLinePath (::std::auto_ptr< RefLinePath_type > x) { this->RefLinePath_.set (x); } const SimWallParams::DegreeOfNormal_optional& SimWallParams:: DegreeOfNormal () const { return this->DegreeOfNormal_; } SimWallParams::DegreeOfNormal_optional& SimWallParams:: DegreeOfNormal () { return this->DegreeOfNormal_; } void SimWallParams:: DegreeOfNormal (const DegreeOfNormal_type& x) { this->DegreeOfNormal_.set (x); } void SimWallParams:: DegreeOfNormal (const DegreeOfNormal_optional& x) { this->DegreeOfNormal_ = x; } const SimWallParams::CompassNsewDirection_optional& SimWallParams:: CompassNsewDirection () const { return this->CompassNsewDirection_; } SimWallParams::CompassNsewDirection_optional& SimWallParams:: CompassNsewDirection () { return this->CompassNsewDirection_; } void SimWallParams:: CompassNsewDirection (const CompassNsewDirection_type& x) { this->CompassNsewDirection_.set (x); } void SimWallParams:: CompassNsewDirection (const CompassNsewDirection_optional& x) { this->CompassNsewDirection_ = x; } void SimWallParams:: CompassNsewDirection (::std::auto_ptr< CompassNsewDirection_type > x) { this->CompassNsewDirection_.set (x); } const SimWallParams::WallIsExternal_optional& SimWallParams:: WallIsExternal () const { return this->WallIsExternal_; } SimWallParams::WallIsExternal_optional& SimWallParams:: WallIsExternal () { return this->WallIsExternal_; } void SimWallParams:: WallIsExternal (const WallIsExternal_type& x) { this->WallIsExternal_.set (x); } void SimWallParams:: WallIsExternal (const WallIsExternal_optional& x) { this->WallIsExternal_ = x; } const SimWallParams::Justify_optional& SimWallParams:: Justify () const { return this->Justify_; } SimWallParams::Justify_optional& SimWallParams:: Justify () { return this->Justify_; } void SimWallParams:: Justify (const Justify_type& x) { this->Justify_.set (x); } void SimWallParams:: Justify (const Justify_optional& x) { this->Justify_ = x; } const SimWallParams::ContainedWinArrayParams_optional& SimWallParams:: ContainedWinArrayParams () const { return this->ContainedWinArrayParams_; } SimWallParams::ContainedWinArrayParams_optional& SimWallParams:: ContainedWinArrayParams () { return this->ContainedWinArrayParams_; } void SimWallParams:: ContainedWinArrayParams (const ContainedWinArrayParams_type& x) { this->ContainedWinArrayParams_.set (x); } void SimWallParams:: ContainedWinArrayParams (const ContainedWinArrayParams_optional& x) { this->ContainedWinArrayParams_ = x; } void SimWallParams:: ContainedWinArrayParams (::std::auto_ptr< ContainedWinArrayParams_type > x) { this->ContainedWinArrayParams_.set (x); } const SimWallParams::ContainedWindowParams_optional& SimWallParams:: ContainedWindowParams () const { return this->ContainedWindowParams_; } SimWallParams::ContainedWindowParams_optional& SimWallParams:: ContainedWindowParams () { return this->ContainedWindowParams_; } void SimWallParams:: ContainedWindowParams (const ContainedWindowParams_type& x) { this->ContainedWindowParams_.set (x); } void SimWallParams:: ContainedWindowParams (const ContainedWindowParams_optional& x) { this->ContainedWindowParams_ = x; } void SimWallParams:: ContainedWindowParams (::std::auto_ptr< ContainedWindowParams_type > x) { this->ContainedWindowParams_.set (x); } const SimWallParams::ContainedDoorArrayParams_optional& SimWallParams:: ContainedDoorArrayParams () const { return this->ContainedDoorArrayParams_; } SimWallParams::ContainedDoorArrayParams_optional& SimWallParams:: ContainedDoorArrayParams () { return this->ContainedDoorArrayParams_; } void SimWallParams:: ContainedDoorArrayParams (const ContainedDoorArrayParams_type& x) { this->ContainedDoorArrayParams_.set (x); } void SimWallParams:: ContainedDoorArrayParams (const ContainedDoorArrayParams_optional& x) { this->ContainedDoorArrayParams_ = x; } void SimWallParams:: ContainedDoorArrayParams (::std::auto_ptr< ContainedDoorArrayParams_type > x) { this->ContainedDoorArrayParams_.set (x); } const SimWallParams::ContainedDoorParams_optional& SimWallParams:: ContainedDoorParams () const { return this->ContainedDoorParams_; } SimWallParams::ContainedDoorParams_optional& SimWallParams:: ContainedDoorParams () { return this->ContainedDoorParams_; } void SimWallParams:: ContainedDoorParams (const ContainedDoorParams_type& x) { this->ContainedDoorParams_.set (x); } void SimWallParams:: ContainedDoorParams (const ContainedDoorParams_optional& x) { this->ContainedDoorParams_ = x; } void SimWallParams:: ContainedDoorParams (::std::auto_ptr< ContainedDoorParams_type > x) { this->ContainedDoorParams_.set (x); } const SimWallParams::ProfilePath_optional& SimWallParams:: ProfilePath () const { return this->ProfilePath_; } SimWallParams::ProfilePath_optional& SimWallParams:: ProfilePath () { return this->ProfilePath_; } void SimWallParams:: ProfilePath (const ProfilePath_type& x) { this->ProfilePath_.set (x); } void SimWallParams:: ProfilePath (const ProfilePath_optional& x) { this->ProfilePath_ = x; } void SimWallParams:: ProfilePath (::std::auto_ptr< ProfilePath_type > x) { this->ProfilePath_.set (x); } } } } #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; } namespace schema { namespace simxml { namespace ResourcesGeneral { // SimWallParams // SimWallParams:: SimWallParams () : ::schema::simxml::SimModelCore::SimBldgModelParams (), Thickness_ (this), Length_ (this), Height_ (this), BaseElevation_ (this), RefLinePosition_ (this), RefLinePath_ (this), DegreeOfNormal_ (this), CompassNsewDirection_ (this), WallIsExternal_ (this), Justify_ (this), ContainedWinArrayParams_ (this), ContainedWindowParams_ (this), ContainedDoorArrayParams_ (this), ContainedDoorParams_ (this), ProfilePath_ (this) { } SimWallParams:: SimWallParams (const RefId_type& RefId) : ::schema::simxml::SimModelCore::SimBldgModelParams (RefId), Thickness_ (this), Length_ (this), Height_ (this), BaseElevation_ (this), RefLinePosition_ (this), RefLinePath_ (this), DegreeOfNormal_ (this), CompassNsewDirection_ (this), WallIsExternal_ (this), Justify_ (this), ContainedWinArrayParams_ (this), ContainedWindowParams_ (this), ContainedDoorArrayParams_ (this), ContainedDoorParams_ (this), ProfilePath_ (this) { } SimWallParams:: SimWallParams (const SimWallParams& x, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::SimModelCore::SimBldgModelParams (x, f, c), Thickness_ (x.Thickness_, f, this), Length_ (x.Length_, f, this), Height_ (x.Height_, f, this), BaseElevation_ (x.BaseElevation_, f, this), RefLinePosition_ (x.RefLinePosition_, f, this), RefLinePath_ (x.RefLinePath_, f, this), DegreeOfNormal_ (x.DegreeOfNormal_, f, this), CompassNsewDirection_ (x.CompassNsewDirection_, f, this), WallIsExternal_ (x.WallIsExternal_, f, this), Justify_ (x.Justify_, f, this), ContainedWinArrayParams_ (x.ContainedWinArrayParams_, f, this), ContainedWindowParams_ (x.ContainedWindowParams_, f, this), ContainedDoorArrayParams_ (x.ContainedDoorArrayParams_, f, this), ContainedDoorParams_ (x.ContainedDoorParams_, f, this), ProfilePath_ (x.ProfilePath_, f, this) { } SimWallParams:: SimWallParams (const ::xercesc::DOMElement& e, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::SimModelCore::SimBldgModelParams (e, f | ::xml_schema::flags::base, c), Thickness_ (this), Length_ (this), Height_ (this), BaseElevation_ (this), RefLinePosition_ (this), RefLinePath_ (this), DegreeOfNormal_ (this), CompassNsewDirection_ (this), WallIsExternal_ (this), Justify_ (this), ContainedWinArrayParams_ (this), ContainedWindowParams_ (this), ContainedDoorArrayParams_ (this), ContainedDoorParams_ (this), ProfilePath_ (this) { if ((f & ::xml_schema::flags::base) == 0) { ::xsd::cxx::xml::dom::parser< char > p (e, true, false, true); this->parse (p, f); } } void SimWallParams:: parse (::xsd::cxx::xml::dom::parser< char >& p, ::xml_schema::flags f) { this->::schema::simxml::SimModelCore::SimBldgModelParams::parse (p, f); for (; p.more_content (); p.next_content (false)) { const ::xercesc::DOMElement& i (p.cur_element ()); const ::xsd::cxx::xml::qualified_name< char > n ( ::xsd::cxx::xml::dom::name< char > (i)); // Thickness // if (n.name () == "Thickness" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->Thickness_) { this->Thickness_.set (Thickness_traits::create (i, f, this)); continue; } } // Length // if (n.name () == "Length" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->Length_) { this->Length_.set (Length_traits::create (i, f, this)); continue; } } // Height // if (n.name () == "Height" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->Height_) { this->Height_.set (Height_traits::create (i, f, this)); continue; } } // BaseElevation // if (n.name () == "BaseElevation" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->BaseElevation_) { this->BaseElevation_.set (BaseElevation_traits::create (i, f, this)); continue; } } // RefLinePosition // if (n.name () == "RefLinePosition" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< RefLinePosition_type > r ( RefLinePosition_traits::create (i, f, this)); if (!this->RefLinePosition_) { this->RefLinePosition_.set (r); continue; } } // RefLinePath // if (n.name () == "RefLinePath" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< RefLinePath_type > r ( RefLinePath_traits::create (i, f, this)); if (!this->RefLinePath_) { this->RefLinePath_.set (r); continue; } } // DegreeOfNormal // if (n.name () == "DegreeOfNormal" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->DegreeOfNormal_) { this->DegreeOfNormal_.set (DegreeOfNormal_traits::create (i, f, this)); continue; } } // CompassNsewDirection // if (n.name () == "CompassNsewDirection" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< CompassNsewDirection_type > r ( CompassNsewDirection_traits::create (i, f, this)); if (!this->CompassNsewDirection_) { this->CompassNsewDirection_.set (r); continue; } } // WallIsExternal // if (n.name () == "WallIsExternal" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->WallIsExternal_) { this->WallIsExternal_.set (WallIsExternal_traits::create (i, f, this)); continue; } } // Justify // if (n.name () == "Justify" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->Justify_) { this->Justify_.set (Justify_traits::create (i, f, this)); continue; } } // ContainedWinArrayParams // if (n.name () == "ContainedWinArrayParams" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< ContainedWinArrayParams_type > r ( ContainedWinArrayParams_traits::create (i, f, this)); if (!this->ContainedWinArrayParams_) { this->ContainedWinArrayParams_.set (r); continue; } } // ContainedWindowParams // if (n.name () == "ContainedWindowParams" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< ContainedWindowParams_type > r ( ContainedWindowParams_traits::create (i, f, this)); if (!this->ContainedWindowParams_) { this->ContainedWindowParams_.set (r); continue; } } // ContainedDoorArrayParams // if (n.name () == "ContainedDoorArrayParams" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< ContainedDoorArrayParams_type > r ( ContainedDoorArrayParams_traits::create (i, f, this)); if (!this->ContainedDoorArrayParams_) { this->ContainedDoorArrayParams_.set (r); continue; } } // ContainedDoorParams // if (n.name () == "ContainedDoorParams" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< ContainedDoorParams_type > r ( ContainedDoorParams_traits::create (i, f, this)); if (!this->ContainedDoorParams_) { this->ContainedDoorParams_.set (r); continue; } } // ProfilePath // if (n.name () == "ProfilePath" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< ProfilePath_type > r ( ProfilePath_traits::create (i, f, this)); if (!this->ProfilePath_) { this->ProfilePath_.set (r); continue; } } break; } } SimWallParams* SimWallParams:: _clone (::xml_schema::flags f, ::xml_schema::container* c) const { return new class SimWallParams (*this, f, c); } SimWallParams& SimWallParams:: operator= (const SimWallParams& x) { if (this != &x) { static_cast< ::schema::simxml::SimModelCore::SimBldgModelParams& > (*this) = x; this->Thickness_ = x.Thickness_; this->Length_ = x.Length_; this->Height_ = x.Height_; this->BaseElevation_ = x.BaseElevation_; this->RefLinePosition_ = x.RefLinePosition_; this->RefLinePath_ = x.RefLinePath_; this->DegreeOfNormal_ = x.DegreeOfNormal_; this->CompassNsewDirection_ = x.CompassNsewDirection_; this->WallIsExternal_ = x.WallIsExternal_; this->Justify_ = x.Justify_; this->ContainedWinArrayParams_ = x.ContainedWinArrayParams_; this->ContainedWindowParams_ = x.ContainedWindowParams_; this->ContainedDoorArrayParams_ = x.ContainedDoorArrayParams_; this->ContainedDoorParams_ = x.ContainedDoorParams_; this->ProfilePath_ = x.ProfilePath_; } return *this; } SimWallParams:: ~SimWallParams () { } } } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace schema { namespace simxml { namespace ResourcesGeneral { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
27.715302
130
0.581279
EnEff-BIM