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
7ca2edc706e3f9101e9f413ff912cd851a79facb
388
cc
C++
net/socket/unix_domain_socket.cc
mayah/base
aec046929938d2aaebaadce5c5abb58b5cf342b4
[ "MIT" ]
115
2015-02-21T15:08:26.000Z
2022-02-05T01:38:10.000Z
net/socket/unix_domain_socket.cc
mayah/base
aec046929938d2aaebaadce5c5abb58b5cf342b4
[ "MIT" ]
214
2015-01-16T04:53:35.000Z
2019-03-23T11:39:59.000Z
net/socket/unix_domain_socket.cc
mayah/base
aec046929938d2aaebaadce5c5abb58b5cf342b4
[ "MIT" ]
56
2015-01-16T05:14:13.000Z
2020-09-22T07:22:49.000Z
#include "net/socket/unix_domain_socket.h" #include <utility> namespace net { UnixDomainSocket::UnixDomainSocket(UnixDomainSocket&& socket) noexcept : Socket(std::move(socket)) { } UnixDomainSocket::~UnixDomainSocket() { } UnixDomainSocket& UnixDomainSocket::operator=(UnixDomainSocket&& socket) noexcept { std::swap(sd_, socket.sd_); return *this; } } // namespace net
16.869565
81
0.734536
mayah
7ca33ce40e3e4bf32850d92930ca4948c6d60dfa
501
cpp
C++
abc186/abc186b.cpp
kogepanh/atcoder-cpp
cc8d0f54d89ac1a8f20d261a358f736fcf43f9ce
[ "MIT" ]
null
null
null
abc186/abc186b.cpp
kogepanh/atcoder-cpp
cc8d0f54d89ac1a8f20d261a358f736fcf43f9ce
[ "MIT" ]
null
null
null
abc186/abc186b.cpp
kogepanh/atcoder-cpp
cc8d0f54d89ac1a8f20d261a358f736fcf43f9ce
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { // cout << fixed << setprecision(15); int H, W; cin >> H >> W; vector<vector<int>> A(H, vector<int>(W)); int minimum = 100; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { cin >> A[i][j]; minimum = min(minimum, A[i][j]); } } long long ans = 0; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { ans += A[i][j] - minimum; } } cout << ans << endl; return 0; }
17.275862
43
0.451098
kogepanh
7ca6cf8f8c8509a7cd0a4ec6ee70327bd7865f5a
2,937
cpp
C++
lib/cpptest-lite/src/TextOutput.cpp
Kaayy-J/OHMComm-Light
08a67e20da3369d199a285071105404daeb33d6c
[ "MIT" ]
null
null
null
lib/cpptest-lite/src/TextOutput.cpp
Kaayy-J/OHMComm-Light
08a67e20da3369d199a285071105404daeb33d6c
[ "MIT" ]
1
2016-01-31T16:12:10.000Z
2016-01-31T16:12:10.000Z
lib/cpptest-lite/src/TextOutput.cpp
Kaayy-J/OHMComm
08a67e20da3369d199a285071105404daeb33d6c
[ "MIT" ]
null
null
null
/* * File: TextOutput.cpp * Author: daniel * * Created on September 11, 2015, 7:07 PM */ #include "TextOutput.h" #include <iostream> #include <string.h> #include <errno.h> using namespace Test; TextOutput::TextOutput(const unsigned int mode) : TextOutput(mode, std::cout) { } TextOutput::TextOutput(const unsigned int mode, std::ostream& stream) : Output(), mode(mode), stream(stream) { } TextOutput::~TextOutput() { stream.flush(); } void TextOutput::initializeSuite(const std::string& suiteName, const unsigned int numTests) { if(mode <= Verbose) stream << "Running suite '" << suiteName << "' with " << numTests << " tests..." << std::endl; } void TextOutput::finishSuite(const std::string& suiteName, const unsigned int numTests, const unsigned int numPositiveTests, const std::chrono::microseconds totalDuration) { if(mode <= Verbose || numTests != numPositiveTests) stream << "Suite '" << suiteName << "' finished, " << numPositiveTests << '/' << numTests << " successful (" << prettifyPercentage(numPositiveTests, numTests) << "%) in " << totalDuration.count() << " microseconds (" << totalDuration.count()/1000.0 << " ms)." << std::endl; } void TextOutput::initializeTestMethod(const std::string& suiteName, const std::string& methodName, const std::string& argString) { if(mode <= Debug) stream << "Running method '" << methodName << "'" << (argString.empty() ? "" : "with argument: ") << argString << "..." << std::endl;; } void TextOutput::finishTestMethod(const std::string& suiteName, const std::string& methodName, const bool withSuccess) { if(mode <= Debug || (mode <= Verbose && !withSuccess)) stream << "Test-method '" << methodName << "' finished with " << (withSuccess ? "success!" : "errors!") << std::endl; } void TextOutput::printSuccess(const Assertion& assertion) { if(mode <= Debug) stream << "Test '" << assertion.method << "' line " << assertion.lineNumber << " successful!" << std::endl; } void TextOutput::printFailure(const Assertion& assertion) { stream << "Test '" << assertion.method << "' failed!" << std::endl; stream << "\tSuite: " << assertion.suite << std::endl; stream << "\tFile: " << Private::getFileName(assertion.file) << std::endl; stream << "\tLine: " << assertion.lineNumber << std::endl; if(!assertion.errorMessage.empty()) stream << "\tFailure: " << assertion.errorMessage << std::endl; if(!assertion.userMessage.empty()) stream << "\tMessage: " << assertion.userMessage << std::endl; } void TextOutput::printException(const std::string& suiteName, const std::string& methodName, const std::exception& ex) { stream << "Test-method '" << methodName << "' failed with exception!" << std::endl; stream << "\tException: " << ex.what() << std::endl; stream << "\tErrno: " << errno << std::endl; stream << "\tError: " << strerror(errno) << std::endl; }
37.177215
277
0.64113
Kaayy-J
7cab9341a9aac0df178a6cd1eb864ef4da61d67a
5,215
cxx
C++
pdfwiz/parsemake/macro_expander.cxx
kit-transue/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
2
2015-11-24T03:31:12.000Z
2015-11-24T16:01:57.000Z
pdfwiz/parsemake/macro_expander.cxx
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
null
null
null
pdfwiz/parsemake/macro_expander.cxx
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
1
2019-05-19T02:26:08.000Z
2019-05-19T02:26:08.000Z
/************************************************************************* * Copyright (c) 2015, Synopsys, Inc. * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are * * met: * * * * 1. Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ // macro_expander.cxx // wrapper for lexer to expand macros in strings // oct.97 kit transue #include <cassert> #include "pipebuf.h" #include "macro_node.h" #include "variabletable.h" #include "message.h" #include "macro_expander.h" // global variables static macro_expander GlobalMacroExpander; macro_expander * global_macroexpander = &GlobalMacroExpander; // macroexpander implementation // construct/copy/destroy macro_expander::macro_expander() { inpipe = new iostream(new pipebuf); outpipe = new iostream(new pipebuf); } macro_expander::~macro_expander() { streambuf * pipebufptr = inpipe->rdbuf(); delete inpipe; delete pipebufptr; pipebufptr = outpipe->rdbuf(); delete outpipe; delete pipebufptr; } void macro_expander::expand_macros_using_streams(variabletable *vt) { int const MAX_LEVEL = 20; int status; int level = 0; while( (status = do_expand(vt)) == 2 && (++level < MAX_LEVEL)) { inpipe->clear(); swap(inpipe, outpipe); } if (level >= MAX_LEVEL) msgid("Too many levels in macro expansion") << eom; } void macro_expander::expand_one_macro_in_string(string &value, string const &name, variabletable *vt) { string::size_type pos = 0; for (pos = value.find('$', pos); pos != string::npos; pos = value.find('$', pos)) { if (value.size() > pos) { string::size_type pattern_start = pos + 1; string::size_type pattern_end = pos + 1; string::size_type subs_end = pattern_end; if (value[pattern_start] == '(') { ++pattern_start; subs_end = value.find(')', pattern_start); pattern_end = subs_end - 1; } else if (value[pattern_start] == '*' && value[pattern_start + 1] == '*') { ++pattern_end; ++subs_end; } if (name == value.substr(pattern_start, pattern_end - pattern_start + 1)) { value.replace(pos, subs_end - pos + 1, (vt->lookup(name)).value); } ++pos; } } } string macro_expander::expand_macros_in_string(string const &s, variabletable *vt) { string ret; // make sure all pending stuff has been properly consumed assert(inpipe->peek() == EOF); assert(outpipe->peek() == EOF); inpipe->clear(); outpipe->clear(); *inpipe << s; expand_macros_using_streams(vt); getline(*outpipe, ret, (char) 0); return ret; } int macro_expander::do_expand(variabletable *vt) { // replacement for lexer. returns 2 if macro expanded; 0 on eof. bool expansionmade = false; char c; while (inpipe->get(c)) { // get returns stream reference, convert to bool if (c == '$') { expansionmade = true; string macro; // macro referenced, and macros don't nest! if (inpipe->peek() == '(') { inpipe->ignore(); // consume open paren getline(*inpipe, macro, ')'); // get macro text if (inpipe->peek() == ')') inpipe->ignore(); } else { // just a single character: inpipe->get(c); macro += c; // well, usually: may be $**: if (c == '*' && inpipe->peek() == '*') { macro += '*'; inpipe->ignore(); } } // macro established. Now expand: macro_node const &expanded = vt->lookup(macro); if (&expanded != macro_node::null_macro) *outpipe << expanded.value; } else *outpipe << c; } return (expansionmade) ? 2 : 0; }
32.59375
96
0.601151
kit-transue
7cb3c971694646e9bda191fd319f85d87787ed07
3,050
cpp
C++
app/PluginManager.cpp
ospray/ospray_studio
1549ac72c7c561b4aafdea976189bbe95bd32ff2
[ "Apache-2.0" ]
52
2018-10-09T23:56:32.000Z
2022-03-25T09:27:40.000Z
app/PluginManager.cpp
ospray/ospray_studio
1549ac72c7c561b4aafdea976189bbe95bd32ff2
[ "Apache-2.0" ]
11
2018-11-19T18:51:47.000Z
2022-03-28T14:03:57.000Z
app/PluginManager.cpp
ospray/ospray_studio
1549ac72c7c561b4aafdea976189bbe95bd32ff2
[ "Apache-2.0" ]
8
2019-02-10T00:16:24.000Z
2022-02-17T19:50:15.000Z
// Copyright 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #include "PluginManager.h" #include <iterator> void PluginManager::loadPlugin(const std::string &name) { std::cout << "...attempting to load plugin '" << name << "'\n"; std::string libName = "ospray_studio_plugin_" + name; try { rkcommon::loadLibrary(libName, false); } catch (std::runtime_error &e) { std::cout << "...failed to load plugin '" << name << "'!" << " (plugin was not found). Please verify the name of the plugin" << " is correct and that it is on your LD_LIBRARY_PATH." << e.what() << std::endl; return; } std::string initSymName = "init_plugin_" + name; void *initSym = rkcommon::getSymbol(initSymName); if (!initSym) { std::cout << "...failed to load plugin, could not find init function!\n"; return; } Plugin *(*initMethod)() = (Plugin * (*)()) initSym; try { auto pluginInstance = std::unique_ptr<Plugin>(static_cast<Plugin *>(initMethod())); addPlugin(std::move(pluginInstance)); } catch (const std::exception &e) { std::cout << "...failed to initialize plugin '" << name << "'!\n"; std::cout << " " << e.what() << std::endl; } catch (...) { std::cout << "...failed to initialize plugin '" << name << "'!\n"; } } void PluginManager::addPlugin(std::unique_ptr<Plugin> plugin) { plugins.emplace_back(LoadedPlugin{std::move(plugin), true}); } void PluginManager::removePlugin(const std::string &name) { plugins.erase(std::remove_if(plugins.begin(), plugins.end(), [&](auto &p) { return p.instance->name() == name; })); } void PluginManager::removeAllPlugins() { plugins.clear(); } bool PluginManager::hasPlugin(const std::string &pluginName) { for (auto &p : plugins) if (p.instance->name() == pluginName) return true; return false; } LoadedPlugin* PluginManager::getPlugin(std::string &pluginName) { for (auto &l : plugins) if (l.instance->name() == pluginName) return &l; return nullptr; } void PluginManager::main( std::shared_ptr<StudioContext> ctx, PanelList *allPanels) const { if (!plugins.empty()) for (auto &plugin : plugins) { plugin.instance->mainMethod(ctx); if (!plugin.instance->panels.empty() && allPanels) { auto &pluginPanels = plugin.instance->panels; std::move(pluginPanels.begin(), pluginPanels.end(), std::back_inserter(*allPanels)); } } } void PluginManager::mainPlugin(std::shared_ptr<StudioContext> ctx, std::string &pluginName, PanelList *allPanels) const { if (!plugins.empty()) for (auto &plugin : plugins) { if (plugin.instance->name() == pluginName) { plugin.instance->mainMethod(ctx); if (!plugin.instance->panels.empty() && allPanels) { auto &pluginPanels = plugin.instance->panels; std::move(pluginPanels.begin(), pluginPanels.end(), std::back_inserter(*allPanels)); } } } }
27.981651
80
0.615738
ospray
7cb7021c2d107fcd32e181297eade1899e8b0b5a
33,314
cpp
C++
day24/main.cpp
kjelloh/advent_of_code_2021
656c26a418a4b379ef48a45ac6ffd978c17a744f
[ "CC0-1.0" ]
null
null
null
day24/main.cpp
kjelloh/advent_of_code_2021
656c26a418a4b379ef48a45ac6ffd978c17a744f
[ "CC0-1.0" ]
null
null
null
day24/main.cpp
kjelloh/advent_of_code_2021
656c26a418a4b379ef48a45ac6ffd978c17a744f
[ "CC0-1.0" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <utility> #include <sstream> #include <algorithm> #include <vector> #include <map> #include <variant> #include <optional> #include <ranges> #include <unordered_set> #include <unordered_map> extern std::vector<std::string> pData; using Result = std::string; using Answers = std::vector<std::pair<std::string,Result>>; /* inp a - Read an input value and write it to variable a. add a b - Add the value of a to the value of b, then store the result in variable a. mul a b - Multiply the value of a by the value of b, then store the result in variable a. div a b - Divide the value of a by the value of b, truncate the result to an integer, then store the result in variable a. (Here, "truncate" means to round the value toward zero.) mod a b - Divide the value of a by the value of b, then store the remainder in variable a. (This is also called the modulo operation.) eql a b - If the value of a and b are equal, then store the value 1 in variable a. Otherwise, store the value 0 in variable a. */ enum Operation { op_unknown ,op_inp ,op_add ,op_mul ,op_div ,op_mod ,op_eql ,op_undefined }; using Operand = std::variant<char,int>; using Operands = std::vector<Operand>; std::optional<Operand> to_operand(std::string const& s) { try { return std::stoi(s); } catch (std::exception const& e) {} if (s.size()==1) return s[0]; else return std::nullopt; } std::string to_string(Operation const& op) { switch (op) { case op_inp: return "inp"; case op_add: return "add"; case op_mul: return "mul"; case op_div: return "div"; case op_mod: return "mod"; case op_eql: return "eql"; default: return std::string{"op ?? "} + std::to_string(static_cast<int>(op)); } } template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>; std::string to_string(Operand const& opr) { std::string result{}; std::visit(overloaded { [&result](char arg) { result = arg;} ,[&result](int arg) { result = std::to_string(arg);} }, opr); return result; } class Statement { public: Statement(std::string const& sOp,std::string const& sopr1,std::string const& sopr2) { this->m_op = op_undefined; bool done{false}; for (int op = op_unknown;op<op_undefined;op++) { switch (op) { case op_inp: done = (sOp=="inp"); break; case op_add: done = (sOp=="add"); break; case op_mul: done = (sOp=="mul"); break; case op_div: done = (sOp=="div"); break; case op_mod: done = (sOp=="mod"); break; case op_eql: done = (sOp=="eql"); break; } if (done) { m_op = static_cast<Operation>(op); break; } } if (auto opr = to_operand(sopr1);opr) m_operands.push_back(*opr); if (auto opr = to_operand(sopr2);opr) m_operands.push_back(*opr); } Operation const& op() const {return m_op;} Operands const& operands() const {return m_operands;} private: Operation m_op; Operands m_operands; }; using Program = std::vector<Statement>; using Model = Program; using Environment = std::map<char,int>; // custom specialization of std::hash for Environment injected into namespace std template<> struct std::hash<Environment> { std::size_t operator()(Environment const& env) const noexcept { std::size_t result; for (auto const me : env) { result ^= std::hash<char>{}(me.first); result ^= std::hash<int>{}(me.second); } return result; } }; // custom specialization of std::hash for std::pair<int,size_t> injected into namespace std template<> struct std::hash<std::pair<int,size_t>> { std::size_t operator()(std::pair<int,size_t> const& pair) const noexcept { std::size_t result; result ^= std::hash<int>{}(pair.first); result ^= std::hash<int>{}(pair.second); return result; } }; std::string to_string(Environment const& env) { std::ostringstream os{}; os << "<environment>"; for (auto const me : env) { os << " " << me.first << " = " << me.second; } return os.str(); } class ALU { public: ALU(std::istream& in) : m_in{in} {} ALU& execute(Program const& program,bool verbose=false) { for (auto const& statement : program) { // log if (verbose){ std::cout << "\nexecute: " << to_string(statement.op()) << "|" << to_string(statement.operands()[0]); if (statement.operands().size()>1) std::cout << "|" << to_string(statement.operands()[1]); } char a = std::get<char>(statement.operands()[0]); int b; if (statement.operands().size()==2) { std::visit(overloaded { [this,&b](char arg) {b = this->environment()[arg];} ,[this,&b](int arg) { b = arg;} }, statement.operands()[1]); } switch (statement.op()) { case op_inp: { int b; if (verbose) std::cout << " >"; if (m_in >> b) { m_environment[a] = b; } else { std::cout << " ERROR: insufficient input"; } } break; case op_add: { m_environment[a] += b; } break; case op_mul: { m_environment[a] *= b; } break; case op_div: { m_environment[a] /= b; } break; case op_mod: { m_environment[a] %= b; } break; case op_eql: { int val_a = m_environment[a]; m_environment[a] = (val_a==b)?1:0; } break; } if (verbose) std::cout << "\t" << a << " = " << m_environment[a]; } if (verbose) std::cout << "\n" << this->env_dump(); return *this; } std::string env_dump() { return to_string(m_environment); } Environment& environment() {return m_environment;} private: std::istream& m_in; Environment m_environment; }; std::pair<std::string,std::string> split(std::string const& token,std::string const& delim) { auto pos = token.find(delim); auto left = token.substr(0,pos); auto right = token.substr(pos+delim.size()); if (pos == std::string::npos) return {left,""}; else return {left,right}; } Model parse(auto& in) { Model result{}; std::string line{}; while (std::getline(in,line)) { auto [sOp,sOperands] = split(line," "); // std::cout << "\n" << sOp << " | " << sOperands; auto [sopr1,sopr2] = split(sOperands," "); // std::cout << "\n[" << sOp << "|" << sopr1 << "|" << sopr2 << "]"; Statement statement{sOp,sopr1,sopr2}; result.push_back(statement); } return result; } // Memoize on visitied state {digit index 13..0 int, z so far size_t} mapped to best digit string from here to z=0 // Use std::optional for the result to handle that there may be NO passable digits from current state using Visited = std::unordered_map<std::pair<int,size_t>,std::optional<std::string>>; std::optional<std::string> best_digits(bool part1, int ix,std::vector<Program> const& snippets,size_t z,Visited& visited) { // Get the best digits i..0 for z so far // Init with ix=13, z=0 // Expands to ix=12, z= one for each digit 13 '9','8',... // Victory if ix==0 and next z for a digit == 0 ==> return the victory digit static int call_count{0}; call_count++; // Log { if (ix>10) std::cout << "\n" << call_count << " " << ix << " " << visited.size() << " " << z; } if (ix<0) return std::nullopt; // Give up else if (visited.find({ix,z}) != visited.end()) return visited[{ix,z}]; else { // Not memoized - run program for step 13-ix (step 13 for digit index 0 = last one) static auto base_digits_1 = {'9','8','7','6','5','4','3','2','1'}; // Search high to low static auto base_digits_2 = {'1','2','3','4','5','6','7','8','9'}; // Search low to high auto& digits = base_digits_1; if (!part1) digits = base_digits_2; // search low to high for (char digit : digits) { std::string input{digit}; std::istringstream d_in{input}; ALU alu{d_in}; alu.environment()['z'] = z; // Run with provided in z alu.execute(snippets[13-ix]); auto next_z = alu.environment()['z']; // Get next z if (ix==0 and next_z==0) return std::string{digit}; // VICTORY else { // pass the new z along down the chain unless we are done auto result = best_digits(part1,ix-1,snippets,next_z,visited); // Recurse down visited[{ix-1,next_z}] = result; // Memoize best digit down from this state if (result) return std::string{digit} + result.value(); else continue; // Try next digit } } } return std::nullopt; } namespace part1 { // Contains different investigate code (impl last in this sorurce file) void investigate(std::string const& sData); Result solve_for(std::string const& sData, std::string sIn) { std::cout << "\nsolve_for in: " << sIn; Result result{}; std::stringstream in{ sData }; auto program = parse(in); if (sIn == "REPL") { // Provide user with a REPL :) bool done{false}; size_t call_count{0}; do { std::cout << "\nNOMAD>"; ALU alu{std::cin}; alu.execute(program); std::cout << "\n" << alu.env_dump(); int z = alu.environment()['z']; done = (z == 0); call_count++; } while (!done); } else if (sIn.size()>0) { // compute Test data std::istringstream d_in{sIn}; ALU alu{d_in}; bool verbose=true; alu.execute(program,verbose); result = to_string(alu.environment()); } else { // Split the program into snippets for each digit processing std::vector<Program> snippets{}; for (auto const& statement : program) { if (statement.op() == op_inp) snippets.push_back({}); snippets.back().push_back(statement); } std::cout << "\nsnippets count " << snippets.size(); Visited visited{}; bool part1=true; auto opt_result = best_digits(part1,13,snippets,0,visited); // Get the best digits 13..0 for z=0 so far if (opt_result) result = opt_result.value(); else result = "FAILED"; } return result; } } namespace part2 { Result solve_for(std::string const sData) { Result result{}; std::stringstream in{ sData }; auto program = parse(in); // Split the program into snippets for each digit processing std::vector<Program> snippets{}; for (auto const& statement : program) { if (statement.op() == op_inp) snippets.push_back({}); snippets.back().push_back(statement); } std::cout << "\nsnippets count " << snippets.size(); Visited visited{}; bool part1=false; auto opt_result = best_digits(part1,13,snippets,0,visited); // Get the best digits 13..0 for z=0 so far if (opt_result) result = opt_result.value(); else result = "FAILED"; return result; } } int main(int argc, char *argv[]) { Answers answers{}; answers.push_back({"Part 1 Test 0",part1::solve_for(pData[0],"-17")}); answers.push_back({"Part 1 Test 1",part1::solve_for(pData[1],"3 9")}); answers.push_back({"Part 1 Test 2",part1::solve_for(pData[2],"10")}); // I interpreted the program and... // Each digit is processed by the program so that z(i+1) = 0 for w(i) = z(i)%26 + N(i) // So if we identify N(i) in the program for each step and enters them for input // we actually get a z=0. They are: 11 13 11 10 -3 -4 12 -8 -3 -12 14 -6 11 -12 // BUT - This is of course invalid as the actual input must be digits 1..9 // ==> Can we use this knowledge somehow though? answers.push_back({"Part 1 Test 3",part1::solve_for(pData[3],"11 13 11 10 -3 -4 12 -8 -3 -12 14 -6 11 -12")}); // part1::investigate(pData[3]); // Activate appropriate part in "investigate" to see my try to understand this problem // answers.push_back({"Part 1 ",part1::solve_for(pData[3],"REPL")}); // A REPL to try different NOMAD inputs (ctrl-c to end) answers.push_back({"Part 1 ",part1::solve_for(pData[3],"")}); answers.push_back({"Part 2 ",part2::solve_for(pData[3])}); for (auto const& answer : answers) { std::cout << "\nanswer[" << answer.first << "] : " << answer.second; } // std::cout << "\nPress <enter>..."; // std::cin.get(); std::cout << "\n"; return 0; } std::vector<std::string> pData{ R"(inp x mul x -1)" ,R"(inp z inp x mul z 3 eql z x)" ,R"(inp w add z w mod z 2 div w 2 add y w mod y 2 div w 2 add x w mod x 2 div w 2 mod w 2)" ,R"(inp w mul x 0 add x z mod x 26 div z 1 add x 11 eql x w eql x 0 mul y 0 add y 25 mul y x add y 1 mul z y mul y 0 add y w add y 14 mul y x add z y inp w mul x 0 add x z mod x 26 div z 1 add x 13 eql x w eql x 0 mul y 0 add y 25 mul y x add y 1 mul z y mul y 0 add y w add y 8 mul y x add z y inp w mul x 0 add x z mod x 26 div z 1 add x 11 eql x w eql x 0 mul y 0 add y 25 mul y x add y 1 mul z y mul y 0 add y w add y 4 mul y x add z y inp w mul x 0 add x z mod x 26 div z 1 add x 10 eql x w eql x 0 mul y 0 add y 25 mul y x add y 1 mul z y mul y 0 add y w add y 10 mul y x add z y inp w mul x 0 add x z mod x 26 div z 26 add x -3 eql x w eql x 0 mul y 0 add y 25 mul y x add y 1 mul z y mul y 0 add y w add y 14 mul y x add z y inp w mul x 0 add x z mod x 26 div z 26 add x -4 eql x w eql x 0 mul y 0 add y 25 mul y x add y 1 mul z y mul y 0 add y w add y 10 mul y x add z y inp w mul x 0 add x z mod x 26 div z 1 add x 12 eql x w eql x 0 mul y 0 add y 25 mul y x add y 1 mul z y mul y 0 add y w add y 4 mul y x add z y inp w mul x 0 add x z mod x 26 div z 26 add x -8 eql x w eql x 0 mul y 0 add y 25 mul y x add y 1 mul z y mul y 0 add y w add y 14 mul y x add z y inp w mul x 0 add x z mod x 26 div z 26 add x -3 eql x w eql x 0 mul y 0 add y 25 mul y x add y 1 mul z y mul y 0 add y w add y 1 mul y x add z y inp w mul x 0 add x z mod x 26 div z 26 add x -12 eql x w eql x 0 mul y 0 add y 25 mul y x add y 1 mul z y mul y 0 add y w add y 6 mul y x add z y inp w mul x 0 add x z mod x 26 div z 1 add x 14 eql x w eql x 0 mul y 0 add y 25 mul y x add y 1 mul z y mul y 0 add y w add y 0 mul y x add z y inp w mul x 0 add x z mod x 26 div z 26 add x -6 eql x w eql x 0 mul y 0 add y 25 mul y x add y 1 mul z y mul y 0 add y w add y 9 mul y x add z y inp w mul x 0 add x z mod x 26 div z 1 add x 11 eql x w eql x 0 mul y 0 add y 25 mul y x add y 1 mul z y mul y 0 add y w add y 13 mul y x add z y inp w mul x 0 add x z mod x 26 div z 26 add x -12 eql x w eql x 0 mul y 0 add y 25 mul y x add y 1 mul z y mul y 0 add y w add y 12 mul y x add z y)" }; // custom specialization of std::hash for std::tuple<int,char,Environment> injected into namespace std template<> struct std::hash<std::tuple<int,char,Environment>> { std::size_t operator()(std::tuple<int,char,Environment> const& triad) const noexcept { std::size_t result; result ^= std::hash<int>{}(std::get<int>(triad)); result ^= std::hash<int>{}(std::get<char>(triad)); for (auto const me : std::get<Environment>(triad)) { result ^= std::hash<char>{}(me.first); result ^= std::hash<int>{}(me.second); } return result; } }; // NOT part of the solution (kept for historical reasons...) // See solutions in main() above namespace part1 { void investigate(std::string const& sData) { std::stringstream in{ sData }; auto program = parse(in); // Observation: The program reads one digit input at a time and performs // a set of computations on that input before reading and processing the next digit. // Split the program into snippets for each digit processing std::vector<Program> snippets{}; for (auto const& statement : program) { if (statement.op() == op_inp) snippets.push_back({}); snippets.back().push_back(statement); } std::cout << "\nsnippets count " << snippets.size(); // 1. What are the possible program states after the first digit processing? if (false) { std::vector<Environment> envs{}; for (char digit : {'9','8','7','6','5','4','3','2','1'}) { // Run the program from the start state with the digit and store the resulting state std::string input{digit}; std::istringstream d_in{input}; // Run snippet[0] ALU alu{d_in}; alu.execute(snippets[0]); envs.push_back(alu.environment()); } // Log { std::cout << "\n<possible states after first digit>"; for (auto const& env : envs) std::cout << "\n" << to_string(env); } } // 2. What possible states after each step (if we run each step/snippet in isolation) if (false) { std::vector<std::tuple<int,char,Environment>> envs{}; for (int i=0;i<14;i++) { for (char digit : {'9','8','7','6','5','4','3','2','1'}) { // Run the program from the start state with the digit and store the resulting state std::string input{digit}; std::istringstream d_in{input}; // Run snippet[0] ALU alu{d_in}; alu.execute(snippets[i]); envs.push_back({i,digit,alu.environment()}); } } // Log { std::cout << "\n<possible states after each snippet in isolation per digit>"; for (auto const& tripple : envs) std::cout << "\n" << std::get<int>(tripple) << " " << std::get<char>(tripple) << " " << to_string(std::get<Environment>(tripple)); } } // 3. How does each step/snippet process a large input z? if (false) { std::vector<std::tuple<int,char,Environment>> envs{}; for (int i=0;i<14;i++) { for (char digit : {'9','8','7','6','5','4','3','2','1'}) { // Run the program from the start state with the digit and store the resulting state std::string input{digit}; std::istringstream d_in{input}; // Run snippet[0] ALU alu{d_in}; // alu.environment()['z'] = 1000000; // large z alu.environment()['z'] = 10000000; // even largee z alu.execute(snippets[i]); envs.push_back({i,digit,alu.environment()}); } } // Log { std::cout << "\n<possible states after each snippet in isolation per digit for LARGE in-z>"; for (auto const& tripple : envs) std::cout << "\n" << std::get<int>(tripple) << " " << std::get<char>(tripple) << " " << to_string(std::get<Environment>(tripple)); /* These steps drastically reduced z 4 7 <environment> w = 7 x = 0 y = 0 z = 384615 5 6 <environment> w = 6 x = 0 y = 0 z = 384615 7 2 <environment> w = 2 x = 0 y = 0 z = 384615 8 7 <environment> w = 7 x = 0 y = 0 z = 384615 11 4 <environment> w = 4 x = 0 y = 0 z = 384615 ==> Seems we MUST choose digit 4 = '7' digit 5 = '6' digit 7 = '2' digit 8 = '7' digit 11 = '4' to have any chance of reducing z down to 0? These steps also reduced z, although just a little bit 9 3 <environment> w = 3 x = 1 y = 9 z = 9999999 9 2 <environment> w = 2 x = 1 y = 8 z = 9999998 9 1 <environment> w = 1 x = 1 y = 7 z = 9999997 This step increased z very little 13 1 <environment> w = 1 x = 1 y = 13 z = 10000003 Lowest increase for the really bad steps 0 1 <environment> w = 1 x = 1 y = 15 z = 260000015 1 1 <environment> w = 1 x = 1 y = 9 z = 260000009 2 1 <environment> w = 1 x = 1 y = 5 z = 260000005 3 1 <environment> w = 1 x = 1 y = 11 z = 260000011 6 1 <environment> w = 1 x = 1 y = 5 z = 260000005 10 1 <environment> w = 1 x = 1 y = 1 z = 260000001 12 1 <environment> w = 1 x = 1 y = 14 z = 260000014 Speculation: The digits affects z very bad to very kindly in the following way digit z affect 0 BAD 1 BAD 2 BAD 3 BAD 4 '7' good 5 '6' good 6 BAD 7 '2' good 8 '7' good 9 kind. '3','2','1' reduces z a little 10 BAD 11 '4' good 12 BAD 13 kind. all increase z but a small amount We have 7 very BAD digits. We have 2 kind digits We have 5 fixed digits! [Future me] For my input... max monad: 74929995999389 min monad: 11118151637112 ==> So - Nope, We do NOT need to fix those digits... (Brute force with memoisation was the way to go) */ } } // 4. Lets try the whole program for all possible BAD digits // with 4,5,7,8,11 fixated // 9 set to the kind '1' and 13 to the kind '1' // NOMAD = NNNN76N271N4N1 where N is '9' for this test if (false) { //NOMAD = xNNN76N271N4N1 where N is '9' for this test std::string nomad="9 9 9 9 7 6 9 2 7 1 9 4 9 1"; std::vector<std::tuple<int,char,Environment>> envs{}; for (int i : {0,1,2,3,6,10,12}) { for (char digit : {'9','8','7','6','5','4','3','2','1'}) { // Run the program from the start state with the digit and store the resulting state nomad[2*i] = digit; std::string input{nomad}; std::istringstream d_in{input}; ALU alu{d_in}; alu.execute(program); envs.push_back({i,digit,alu.environment()}); } } // Log { std::cout << "\n<possible states after each nomad xNNN76N271N4N1 (x='1'..'9'"; for (auto const& tripple : envs) std::cout << "\n" << std::get<int>(tripple) << " " << std::get<char>(tripple) << " " << to_string(std::get<Environment>(tripple)); /* Ok, quite unconclosive but for digit 0 where we can control z to both negative and positive! 0 9 <environment> w = 1 x = 1 y = 13 z = -1276661321 0 8 <environment> w = 1 x = 1 y = 13 z = -1585577097 0 7 <environment> w = 1 x = 1 y = 13 z = -1894492873 0 6 <environment> w = 1 x = 1 y = 13 z = 2091558625 0 5 <environment> w = 1 x = 1 y = 13 z = 1782642849 0 4 <environment> w = 1 x = 1 y = 13 z = 1473727073 0 3 <environment> w = 1 x = 1 y = 13 z = 1164811297 0 2 <environment> w = 1 x = 1 y = 13 z = 855895521 0 1 <environment> w = 1 x = 1 y = 13 z = 546979745 */ } } // What can we learn by brute force the 7 BAD digits? // If we store the environmet after each step we can get a grasp of the search space? if (false) { // Brute force digit with index {0,1,2,3,6,10,12} std::unordered_set<Environment> visited{}; size_t call_count{0}; std::string nomad="9 9 9 9 7 6 9 2 7 1 9 4 9 1"; for (auto i0 : {1,2,3,4,5,6,7,8,9}) { for (auto i1 : {1,2,3,4,5,6,7,8,9}) { for (auto i2 : {1,2,3,4,5,6,7,8,9}) { for (auto i3 : {1,2,3,4,5,6,7,8,9}) { for (auto i6 : {1,2,3,4,5,6,7,8,9}) { for (auto i10 : {1,2,3,4,5,6,7,8,9}) { for (auto i12 : {1,2,3,4,5,6,7,8,9}) { ++call_count; nomad[0] = '0'+i0; nomad[2] = '0'+i1; nomad[4] = '0'+i2; nomad[6] = '0'+i3; nomad[12] = '0'+i6; nomad[20] = '0'+i10; nomad[24] = '0'+i12; std::string input{nomad}; std::istringstream d_in{input}; ALU alu{d_in}; alu.execute(program); visited.insert(alu.environment()); if (call_count%10000==0) std::cout << "\n" << call_count << std::flush; } } } } } } } // Log { std::cout << "\n" << call_count << std::flush; std::cout << "\n" << visited.size(); // 2187 unique states only! (Should be correct even with a sloppy hash function)? // Note: I implemented a quick-and-dirty hash function for Envronment. // But the unordered set should still keep track if unique elements // even if the hash but them in buckets defined by the same hash? } } // What can we learn by brute force the 7 BAD digits and map the environment to the tested nomad? if (false) { // Brute force BAD digits,i.e., those with index {0,1,2,3,6,10,12} std::unordered_map<Environment,std::string> visited{}; size_t call_count{0}; std::string nomad="9 9 9 9 7 6 9 2 7 1 9 4 9 1"; for (auto i0 : {1,2,3,4,5,6,7,8,9}) { for (auto i1 : {1,2,3,4,5,6,7,8,9}) { for (auto i2 : {1,2,3,4,5,6,7,8,9}) { for (auto i3 : {1,2,3,4,5,6,7,8,9}) { for (auto i6 : {1,2,3,4,5,6,7,8,9}) { for (auto i10 : {1,2,3,4,5,6,7,8,9}) { for (auto i12 : {1,2,3,4,5,6,7,8,9}) { ++call_count; nomad[0] = '0'+i0; nomad[2] = '0'+i1; nomad[4] = '0'+i2; nomad[6] = '0'+i3; nomad[12] = '0'+i6; nomad[20] = '0'+i10; nomad[24] = '0'+i12; std::string input{nomad}; std::istringstream d_in{input}; ALU alu{d_in}; alu.execute(program); visited[alu.environment()] = nomad; if (call_count%10000==0) std::cout << "\n" << call_count << " " << nomad << std::flush; } } } } } } } // Log { std::cout << "\n" << call_count << std::flush; std::cout << "\n" << visited.size(); // 2187 for (auto const& em : visited) { if (em.first.at('z') == 0) std::cout << "\nvalid:" << em.second; } // But none of them are z=0. } // How low z have we found (Note that we have two kind digits to find also) std::vector<Environment> qv{}; std::transform(visited.begin(),visited.end(),std::back_inserter(qv),[](auto em) { return em.first; }); std::sort(qv.begin(),qv.end(),[](auto em1,auto em2){ return (em1['z'] < em2['z']); }); for (auto const& env : qv) { std::cout << "\n" << to_string(env); } /* Observation: For some reason we get the same w,x and y for the input we generated. Probably because the last digit processed is the same and w,x and y does NOT propagate between "steps" (digit processing) And we basically get two chunks of z, negative and one positive (large in any case) ==> So much for getting close to a low z this way... ... <environment> w = 1 x = 1 y = 13 z = -1277575273 <environment> w = 1 x = 1 y = 13 z = -1277118323 <environment> w = 1 x = 1 y = 13 z = -1277118297 <environment> w = 1 x = 1 y = 13 z = -1276661347 <environment> w = 1 x = 1 y = 13 z = -1276661321 <environment> w = 1 x = 1 y = 13 z = 182426387 <environment> w = 1 x = 1 y = 13 z = 182443963 <environment> w = 1 x = 1 y = 13 z = 182461539 <environment> w = 1 x = 1 y = 13 z = 182479115 <environment> w = 1 x = 1 y = 13 z = 182496691 <environment> w = 1 x = 1 y = 13 z = 182514267 ... Still, for out input 9pow7 = 4782969 We get only 2187 possible environments. We should be able to leverage that? ==> Even if we save all intermediate states we only get 14*2187 = 30618 states. Does this men we can brute force all 9 unknown digits by memoize encountered states to short-cut the evaluation? */ } // *) Lets asume w,x and y does not affekt the "cost" to z for each "step" (digit in the input)? // We are thyen interested in the possible space of z-changes for each step // given some z-input. if (false) { size_t const Z = 10000; std::unordered_map<std::tuple<int,char,Environment>,size_t> visited{}; for (int i=0;i<14;i++) { // Run program snippet i for digit '9'..'1' for some range of input z 0..Z // count the number each state is reached // Note: Requires a specialisation to hash std::tuple<int,char,Environment> injected into // the std namespace (see code below Environment type above) for (auto digit : {'9','8','7','6','5','4','3','2','1'}) { for (size_t z = 0;z<Z;z++) { std::string input{digit}; std::istringstream d_in{input}; ALU alu{d_in}; alu.environment()['z'] = z; alu.execute(snippets[i]); visited[{i,digit,alu.environment()}] += 1; // count reach of this state } } } // Log { std::cout << "\nstate count: " << visited.size(); auto max_e_z = std::max_element(visited.begin(),visited.end(),[](auto const& entry1, auto const& entry2){ auto z1 = std::get<Environment>(entry1.first).at('z'); auto z2 = std::get<Environment>(entry2.first).at('z'); return z1<z2; }); auto max_z = std::get<Environment>(max_e_z->first).at('z'); auto min_e_z = std::min_element(visited.begin(),visited.end(),[](auto const& entry1, auto const& entry2){ auto z1 = std::get<Environment>(entry1.first).at('z'); auto z2 = std::get<Environment>(entry2.first).at('z'); return z1<z2; }); auto min_z = std::get<Environment>(min_e_z->first).at('z'); auto max_e_c = std::max_element(visited.begin(),visited.end(),[](auto const& entry1, auto const& entry2){ auto c1 = entry1.second; auto c2 = entry2.second; return c1<c2; }); auto max_c = max_e_c->second; auto min_e_c = std::min_element(visited.begin(),visited.end(),[](auto const& entry1, auto const& entry2){ auto c1 = entry1.second; auto c2 = entry2.second; return c1<c2; }); auto min_c = max_e_c->second; std::cout << "\nmin z :" << std::get<int>(min_e_z->first) << " " << std::get<char>(min_e_z->first) << " " << to_string(std::get<Environment>(min_e_z->first)) << " " << min_e_z->second; std::cout << "\nmax z :" << std::get<int>(max_e_z->first) << " " << std::get<char>(max_e_z->first) << " " << to_string(std::get<Environment>(max_e_z->first)) << " " << max_e_z->second; std::cout << "\nmin count:" << std::get<int>(min_e_c->first) << " " << std::get<char>(min_e_c->first) << " " << to_string(std::get<Environment>(min_e_c->first)) << " " << min_e_c->second; std::cout << "\nmax count:" << std::get<int>(max_e_c->first) << " " << std::get<char>(max_e_c->first) << " " << to_string(std::get<Environment>(max_e_c->first)) << " " << max_e_c->second; /* state count: 678496 min z :11 1 <environment> w = 1 x = 0 y = 0 z = 0 1 max z :0 9 <environment> w = 9 x = 1 y = 23 z = 259997 1 min count:12 1 <environment> w = 1 x = 1 y = 14 z = 259988 1 max count:13 2 <environment> w = 2 x = 1 y = 14 z = 9920 25 So still, we have tried 10 000 z and 9 digits for each step and only got 678496 different states Worst case would have been 14*9*10000 = 1 260 000 (we have half the expected state counts...) We actually got one snippet to produce a zero z output (digit 11 input '1') Digit 12 = '1' is hit only once Digit 13 = '2' is hit 25 times (there are 25 input z:s for digit '2' that produce the same output z 9920) */ } } // So, are we ready to just tey and brute force this? // It seems we care only about z at each step (digit). Adn we are looking for the highest sequence of 14 digits // that causes z to become 0. // And we know the space of states {digit index, z} are limited so we can memoize on this state. if (false) { // So, what question can we iterate? // Lets try - Given digit index i and z so far, what are the highets remaining digits to get z down to 0? // This qiestion can be asked at every level of digit index. // And at each level we can return the digit seuqence below us with the current digit at the front. // What is a good name for this function? // What about best_digits(i,z) Visited visited{}; bool part1{true}; auto result = best_digits(part1,13,snippets,0,visited); // Get the best digits 13..0 for z=0 so far if (result) std::cout << "\nbest monad: " << result.value(); else std::cout << "\nFAILED - no monad found"; } } }
31.280751
195
0.557453
kjelloh
7cbb1347cce1d40c6aca97055352e6f1381187e9
2,465
cpp
C++
core/args_parser.cpp
SmallJoker/NyisBotCPP
48ec353d103ac09f1c538578543d99e9d205f47a
[ "MIT" ]
null
null
null
core/args_parser.cpp
SmallJoker/NyisBotCPP
48ec353d103ac09f1c538578543d99e9d205f47a
[ "MIT" ]
1
2021-03-28T09:49:33.000Z
2021-03-28T09:49:33.000Z
core/args_parser.cpp
SmallJoker/NyisBotCPP
48ec353d103ac09f1c538578543d99e9d205f47a
[ "MIT" ]
null
null
null
#include "args_parser.h" #include "logger.h" #include <map> std::map<std::string, CLIArg *> g_args; CLIArg::CLIArg(cstr_t &pfx, bool *out) : CLIArg(pfx) { m_handler = &CLIArg::parseFlag; m_dst.b = out; } CLIArg::CLIArg(cstr_t &pfx, long *out) : CLIArg(pfx) { m_handler = &CLIArg::parseLong; m_dst.l = out; } CLIArg::CLIArg(cstr_t &pfx, float *out) : CLIArg(pfx) { m_handler = &CLIArg::parseFloat; m_dst.f = out; } CLIArg::CLIArg(cstr_t &pfx, std::string *out) : CLIArg(pfx) { m_handler = &CLIArg::parseString; m_dst.s = out; } CLIArg::CLIArg(cstr_t &pfx) { g_args.insert({"--" + pfx, this}); } static const std::string HELPCMD("--help"); void CLIArg::parseArgs(int argc, char **argv) { for (int i = 1; i < argc; ++i) { if (argv[i] == HELPCMD) { showHelp(); exit(EXIT_SUCCESS); } auto it = g_args.find(argv[i]); if (it == g_args.end()) { WARN("Unknown argument '" << argv[i] << "'"); continue; } bool has_argv = (it->second->m_handler != &CLIArg::parseFlag); bool ok = (i + 1 < argc) || !has_argv; if (ok) { // Note: argv is NULL-terminated ok = (it->second->*(it->second)->m_handler)(argv[i + 1]); if (ok && has_argv) i++; } if (!ok) WARN("Cannot parse argument '" << argv[i] << "'"); } g_args.clear(); } void CLIArg::showHelp() { LoggerAssistant la(LL_NORMAL); la << "Available commands:\n"; for (const auto &it : g_args) { const CLIArg *a = it.second; const char *type = "invalid"; std::string initval; // Switch-case does not work .... if (a->m_handler == &CLIArg::parseFlag) { type = "flag"; } else if (a->m_handler == &CLIArg::parseLong) { type = "integer"; initval = std::to_string(*a->m_dst.l); } else if (a->m_handler == &CLIArg::parseFloat) { type = "float"; initval = std::to_string(*a->m_dst.f); } else if (a->m_handler == &CLIArg::parseString) { type = "string"; initval = '"' + *a->m_dst.s + '"'; } la << "\t" << it.first << "\t (Type: " << type; if (!initval.empty()) la << ", Default: " << initval; la << ")\n"; } } bool CLIArg::parseFlag(const char *str) { *m_dst.b ^= true; return 1; } bool CLIArg::parseLong(const char *str) { int status = sscanf(str, "%li", m_dst.l); return status == 1; } bool CLIArg::parseFloat(const char *str) { int status = sscanf(str, "%f", m_dst.f); return status == 1; } bool CLIArg::parseString(const char *str) { if (!str[0]) return false; m_dst.s->assign(str); return true; }
20.04065
64
0.594726
SmallJoker
7cbd20eb092cb13f1d9665f3c5d822248b12b2da
2,426
cpp
C++
aws-cpp-sdk-iotanalytics/source/model/Variable.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-iotanalytics/source/model/Variable.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-iotanalytics/source/model/Variable.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/iotanalytics/model/Variable.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace IoTAnalytics { namespace Model { Variable::Variable() : m_nameHasBeenSet(false), m_stringValueHasBeenSet(false), m_doubleValue(0.0), m_doubleValueHasBeenSet(false), m_datasetContentVersionValueHasBeenSet(false), m_outputFileUriValueHasBeenSet(false) { } Variable::Variable(JsonView jsonValue) : m_nameHasBeenSet(false), m_stringValueHasBeenSet(false), m_doubleValue(0.0), m_doubleValueHasBeenSet(false), m_datasetContentVersionValueHasBeenSet(false), m_outputFileUriValueHasBeenSet(false) { *this = jsonValue; } Variable& Variable::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("name")) { m_name = jsonValue.GetString("name"); m_nameHasBeenSet = true; } if(jsonValue.ValueExists("stringValue")) { m_stringValue = jsonValue.GetString("stringValue"); m_stringValueHasBeenSet = true; } if(jsonValue.ValueExists("doubleValue")) { m_doubleValue = jsonValue.GetDouble("doubleValue"); m_doubleValueHasBeenSet = true; } if(jsonValue.ValueExists("datasetContentVersionValue")) { m_datasetContentVersionValue = jsonValue.GetObject("datasetContentVersionValue"); m_datasetContentVersionValueHasBeenSet = true; } if(jsonValue.ValueExists("outputFileUriValue")) { m_outputFileUriValue = jsonValue.GetObject("outputFileUriValue"); m_outputFileUriValueHasBeenSet = true; } return *this; } JsonValue Variable::Jsonize() const { JsonValue payload; if(m_nameHasBeenSet) { payload.WithString("name", m_name); } if(m_stringValueHasBeenSet) { payload.WithString("stringValue", m_stringValue); } if(m_doubleValueHasBeenSet) { payload.WithDouble("doubleValue", m_doubleValue); } if(m_datasetContentVersionValueHasBeenSet) { payload.WithObject("datasetContentVersionValue", m_datasetContentVersionValue.Jsonize()); } if(m_outputFileUriValueHasBeenSet) { payload.WithObject("outputFileUriValue", m_outputFileUriValue.Jsonize()); } return payload; } } // namespace Model } // namespace IoTAnalytics } // namespace Aws
19.885246
92
0.734542
Neusoft-Technology-Solutions
7cbe5492978a198a96c652b2c7b7b5e4b066da5e
39
cpp
C++
src/Events/ButtonClickEvent.cpp
DarthGeek01/TowerDefense
c1421c04c6bc05c73b39084106fd6a17b7fee4e5
[ "MIT" ]
null
null
null
src/Events/ButtonClickEvent.cpp
DarthGeek01/TowerDefense
c1421c04c6bc05c73b39084106fd6a17b7fee4e5
[ "MIT" ]
null
null
null
src/Events/ButtonClickEvent.cpp
DarthGeek01/TowerDefense
c1421c04c6bc05c73b39084106fd6a17b7fee4e5
[ "MIT" ]
null
null
null
// // Created by ariel on 11/6/16. //
7.8
31
0.538462
DarthGeek01
7cbf3abc676be906a676d25d721cf95df84cab21
11,015
cpp
C++
src/opengl/xGSGLutil.cpp
livingcreative/xgs
2fc51c8b8f04e23740466414092f0ca1e0acb436
[ "BSD-3-Clause" ]
6
2016-03-17T16:11:39.000Z
2021-02-08T18:03:23.000Z
src/opengl/xGSGLutil.cpp
livingcreative/xgs
2fc51c8b8f04e23740466414092f0ca1e0acb436
[ "BSD-3-Clause" ]
6
2016-07-15T07:02:44.000Z
2018-05-24T20:39:57.000Z
src/opengl/xGSGLutil.cpp
livingcreative/xgs
2fc51c8b8f04e23740466414092f0ca1e0acb436
[ "BSD-3-Clause" ]
4
2016-03-20T11:43:11.000Z
2022-01-21T21:07:54.000Z
/* xGS 3D Low-level rendering API Low-level 3D rendering wrapper API with multiple back-end support (c) livingcreative, 2015 - 2018 https://github.com/livingcreative/xgs opengl/xGSGLutil.cpp OpenGL specific utility functions and classes */ #include "xGSGLutil.h" #include "xGSimpl.h" #include "xGSstate.h" #include "xGStexture.h" #include "xGSdatabuffer.h" using namespace xGS; #ifdef _DEBUG const char* xGS::uniform_type(GLenum type) { switch (type) { case GL_SAMPLER_1D: return "SAMPLER_1D"; case GL_SAMPLER_1D_ARRAY: return "SAMPLER_1D_ARRAY"; case GL_SAMPLER_2D: return "SAMPLER_2D"; case GL_SAMPLER_2D_MULTISAMPLE: return "SAMPLER_2D_MULTISAMPLE"; case GL_SAMPLER_2D_ARRAY: return "SAMPLER_2D_ARRAY"; case GL_SAMPLER_3D: return "SAMPLER_3D"; case GL_SAMPLER_CUBE: return "SAMPLER_CUBE"; case GL_SAMPLER_CUBE_MAP_ARRAY: return "SAMPLER_CUBE_MAP_ARRAY"; case GL_SAMPLER_1D_SHADOW: return "SAMPLER_1D_SHADOW"; case GL_SAMPLER_1D_ARRAY_SHADOW: return "SAMPLER_1D_ARRAY_SHADOW"; case GL_SAMPLER_2D_SHADOW: return "SAMPLER_2D_SHADOW"; case GL_SAMPLER_2D_ARRAY_SHADOW: return "SAMPLER_2D_ARRAY_SHADOW"; case GL_SAMPLER_CUBE_SHADOW: return "SAMPLER_CUBE_SHADOW"; case GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW: return "SAMPLER_CUBE_MAP_ARRAY_SHADOW"; case GL_SAMPLER_2D_RECT: return "GL_SAMPLER_2D_RECT"; case GL_SAMPLER_2D_RECT_SHADOW: return "GL_SAMPLER_2D_RECT_SHADOW"; case GL_SAMPLER_BUFFER: return "SAMPLER_BUFFER"; case GL_FLOAT: return "FLOAT"; case GL_FLOAT_VEC2: return "FLOAT_VEC2"; case GL_FLOAT_VEC3: return "FLOAT_VEC3"; case GL_FLOAT_VEC4: return "FLOAT_VEC4"; case GL_FLOAT_MAT2: return "FLOAT_MAT2"; case GL_FLOAT_MAT3: return "FLOAT_MAT3"; case GL_FLOAT_MAT4: return "FLOAT_MAT4"; case GL_INT: return "INT"; case GL_INT_VEC2: return "INT_VEC2"; case GL_INT_VEC3: return "INT_VEC3"; case GL_INT_VEC4: return "INT_VEC4"; case GL_BOOL: return "BOOL"; case GL_BOOL_VEC2: return "BOOL_VEC2"; case GL_BOOL_VEC3: return "BOOL_VEC3"; case GL_BOOL_VEC4: return "BOOL_VEC4"; } return "? uniform"; } #endif GSParametersState::GSParametersState() : p_uniformblockdata(), p_textures(), p_firstslot(0), p_texture_targets(), p_texture_binding(), p_texture_samplers() {} GSerror GSParametersState::allocate(xGSImpl *impl, xGSStateImpl *state, const GSParameterSet &set, const GSuniformbinding *uniforms, const GStexturebinding *textures, const GSconstantvalue *constants) { // TODO: think about what to do with slots which weren't present in state program // so their samplers weren't allocated GSuint slotcount = set.onepastlast - set.first; GSuint samplercount = set.onepastlastsampler - set.firstsampler; GSuint blockscount = slotcount - samplercount - set.constantcount; p_firstslot = set.firstsampler; p_uniformblockdata.clear(); p_uniformblockdata.reserve(blockscount); // bind uniform blocks if (uniforms) { const GSuniformbinding *binding = uniforms; while (binding->slot != GSPS_END) { GSuint slotindex = binding->slot - GSPS_0; if (slotindex >= slotcount) { return GSE_INVALIDVALUE; } const xGSStateImpl::ParameterSlot &slot = state->parameterSlot(slotindex + set.first); if (slot.type != GSPD_BLOCK) { return GSE_INVALIDENUM; } if (slot.location != GS_DEFAULT) { xGSDataBufferImpl *buffer = static_cast<xGSDataBufferImpl*>(binding->buffer); if (binding->block >= buffer->blockCount()) { return GSE_INVALIDVALUE; } const xGSDataBufferImpl::UniformBlock &block = buffer->block(binding->block); UniformBlockData ub = { GLuint(slot.location), block.offset + block.size * binding->index, block.size, buffer }; p_uniformblockdata.push_back(ub); } ++binding; } } p_textures.clear(); p_texture_targets.clear(); p_texture_binding.clear(); p_texture_samplers.clear(); p_textures.reserve(samplercount); p_texture_targets.resize(samplercount); p_texture_binding.resize(samplercount); p_texture_samplers.resize(samplercount); // bind textures & samplers if (textures) { const GStexturebinding *binding = textures; while (binding->slot != GSPS_END) { GSuint slotindex = binding->slot - GSPS_0; if (slotindex >= slotcount) { return GSE_INVALIDVALUE; } const xGSStateImpl::ParameterSlot &slot = state->parameterSlot(slotindex + set.first); if (slot.type != GSPD_TEXTURE) { return GSE_INVALIDENUM; } if (slot.location != GS_DEFAULT) { xGSTextureImpl *texture = static_cast<xGSTextureImpl*>(binding->texture); GSuint sampler = binding->sampler - GSS_0; if (sampler >= impl->samplerCount()) { return GSE_INVALIDVALUE; } TextureSlot t = { texture, sampler }; p_textures.push_back(t); p_texture_targets[slot.location] = texture->target(); p_texture_binding[slot.location] = texture->getID(); p_texture_samplers[slot.location] = impl->sampler(sampler); } ++binding; } } // copy constant values if (constants) { p_constants.reserve(set.constantcount); size_t memoffset = 0; const GSconstantvalue *constval = constants; while (constval->slot != GSPS_END) { GSuint slotindex = constval->slot - GSPS_0; if (slotindex >= slotcount) { return GSE_INVALIDVALUE; } const xGSStateImpl::ParameterSlot &slot = state->parameterSlot(slotindex + set.first); if (slot.type != GSPD_CONSTANT) { return GSE_INVALIDENUM; } if (slot.location != GS_DEFAULT) { ConstantValue cv = { constval->type, slot.location, memoffset }; size_t size = 0; switch (constval->type) { case GSU_SCALAR: size = sizeof(float) * 1; break; case GSU_VEC2: size = sizeof(float) * 2; break; case GSU_VEC3: size = sizeof(float) * 3; break; case GSU_VEC4: size = sizeof(float) * 4; break; case GSU_MAT2: size = sizeof(float) * 4; break; case GSU_MAT3: size = sizeof(float) * 9; break; case GSU_MAT4: size = sizeof(float) * 16; break; default: return GSE_INVALIDENUM; } // TODO: optimize constant memory, change for more robust container p_constantmemory.resize(p_constantmemory.size() + size); memcpy(p_constantmemory.data() + cv.offset, constval->value, size); memoffset += size; p_constants.push_back(cv); } ++constval; } } for (auto &b : p_uniformblockdata) { b.buffer->AddRef(); } for (auto &t : p_textures) { t.texture->AddRef(); impl->referenceSampler(t.sampler); } return GS_OK; } void GSParametersState::apply(const GScaps &caps, xGSImpl *impl, xGSStateImpl *state) { // set up uniform blocks for (auto u : p_uniformblockdata) { glBindBufferRange(GL_UNIFORM_BUFFER, u.index, u.buffer->getID(), u.offset, u.size); } if (p_textures.size()) { if (caps.multi_bind) { GLuint count = GLuint(p_texture_binding.size()); glBindTextures(p_firstslot, count, p_texture_binding.data()); glBindSamplers(p_firstslot, count, p_texture_samplers.data()); } else { // set up textures for (size_t n = 0; n < p_texture_binding.size(); ++n) { glActiveTexture(GL_TEXTURE0 + p_firstslot + GLenum(n)); if (p_texture_binding[n]) { glBindTexture( p_texture_targets[n], p_texture_binding[n] ); glBindSampler(GLuint(n) + p_firstslot, p_texture_samplers[n]); #ifdef _DEBUG } else { xGSTextureImpl::bindNullTexture(); glBindSampler(GLuint(n) + p_firstslot, 0); #endif } } } } for (auto c : p_constants) { // TODO: copypasta - similar code in Impl::SetUniformValue const GLfloat *value = reinterpret_cast<const GLfloat*>(p_constantmemory.data() + c.offset); switch (c.type) { case GSU_SCALAR: glUniform1fv(c.location, 1, value); break; case GSU_VEC2: glUniform2fv(c.location, 1, value); break; case GSU_VEC3: glUniform3fv(c.location, 1, value); break; case GSU_VEC4: glUniform4fv(c.location, 1, value); break; case GSU_MAT2: glUniformMatrix2fv(c.location, 1, GL_FALSE, value); break; case GSU_MAT3: glUniformMatrix3fv(c.location, 1, GL_FALSE, value); break; case GSU_MAT4: glUniformMatrix4fv(c.location, 1, GL_FALSE, value); break; } } #ifdef _DEBUG for (size_t n = 0; n < p_textures.size(); ++n) { xGSTextureImpl *texture = p_textures[n].texture; bool depthtexture = texture->format() == GS_DEPTH_16 || texture->format() == GS_DEPTH_24 || texture->format() == GS_DEPTH_32 || texture->format() == GS_DEPTH_32_FLOAT || texture->format() == GS_DEPTHSTENCIL_D24S8; if (texture->boundAsRT() && (!depthtexture || state->depthMask())) { //impl->debug(DebugMessageLevel::Warning, "Texture bound as RT is being used as source [id=%i]\n", p_textures[n].texture->getID()); } } #endif } void GSParametersState::ReleaseRendererResources(xGSImpl *impl) { for (auto &u : p_uniformblockdata) { if (u.buffer) { u.buffer->Release(); } } for (auto &t : p_textures) { if (t.texture) { t.texture->Release(); } impl->dereferenceSampler(t.sampler); } }
32.68546
200
0.578484
livingcreative
7cc17e094b97871d82c1a87abdfc70a311414c91
341
cpp
C++
src/op/grid5.cpp
pfuchs/riesling
2e0f12f5cd1943cb6e96eca40f4e68ef88e12130
[ "MIT" ]
null
null
null
src/op/grid5.cpp
pfuchs/riesling
2e0f12f5cd1943cb6e96eca40f4e68ef88e12130
[ "MIT" ]
null
null
null
src/op/grid5.cpp
pfuchs/riesling
2e0f12f5cd1943cb6e96eca40f4e68ef88e12130
[ "MIT" ]
null
null
null
#include "grid.hpp" std::unique_ptr<GridBase> make_5_e(Kernel const *k, Mapping const &m, bool const fg) { if (k->throughPlane() == 1) { return std::make_unique<Grid<5, 1>>(dynamic_cast<SizedKernel<5, 1> const *>(k), m, fg); } else { return std::make_unique<Grid<5, 5>>(dynamic_cast<SizedKernel<5, 5> const *>(k), m, fg); } }
31
91
0.642229
pfuchs
7cc1b0c066fe51564b4db7a66c005b01880a24a8
2,851
cc
C++
demo/misc/uri_demo.cc
Rokid/mingutils
b0c7865b928c8c46fdf769bfda0f05b1965b5372
[ "MIT" ]
1,144
2018-12-18T09:46:47.000Z
2022-03-07T14:51:46.000Z
demo/misc/uri_demo.cc
Rokid/mingutils
b0c7865b928c8c46fdf769bfda0f05b1965b5372
[ "MIT" ]
16
2019-01-28T06:08:40.000Z
2019-12-04T10:26:41.000Z
demo/misc/uri_demo.cc
Rokid/mingutils
b0c7865b928c8c46fdf769bfda0f05b1965b5372
[ "MIT" ]
129
2018-12-18T09:46:50.000Z
2022-03-30T07:30:13.000Z
#include "uri.h" using namespace rokid; using namespace std; #define URI_COUNT 7 static const char* test_uris[] = { "https://john.doe@www.example.com:123/forum/questions/?tag=networking&order=newest#top", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "unix:rokid-flora#foo" }; typedef struct { string scheme; string user; string host; int32_t port = 0; string path; string query; string fragment; } UriResult; static UriResult correct_results[URI_COUNT]; static void prepare_correct_results() { correct_results[0].scheme = "https"; correct_results[0].user = "john.doe"; correct_results[0].host = "www.example.com"; correct_results[0].port = 123; correct_results[0].path = "/forum/questions/"; correct_results[0].query = "tag=networking&order=newest"; correct_results[0].fragment = "top"; correct_results[1].scheme = "mailto"; correct_results[1].path = "John.Doe@example.com"; correct_results[2].scheme = "news"; correct_results[2].path = "comp.infosystems.www.servers.unix"; correct_results[3].scheme = "tel"; correct_results[3].path = "+1-816-555-1212"; correct_results[4].scheme = "telnet"; correct_results[4].host = "192.0.2.16"; correct_results[4].port = 80; correct_results[4].path = "/"; correct_results[5].scheme = "urn"; correct_results[5].path = "oasis:names:specification:docbook:dtd:xml:4.1.2"; correct_results[6].scheme = "unix"; correct_results[6].path = "rokid-flora"; correct_results[6].fragment = "foo"; } static bool check_result(Uri& uri, UriResult& r) { if (uri.scheme != r.scheme) { printf("scheme incorrect: %s != %s\n", uri.scheme.c_str(), r.scheme.c_str()); return false; } if (uri.user != r.user) { printf("user incorrect: %s != %s\n", uri.user.c_str(), r.user.c_str()); return false; } if (uri.host != r.host) { printf("host incorrect: %s != %s\n", uri.host.c_str(), r.host.c_str()); return false; } if (uri.port != r.port) { printf("port incorrect: %d != %d\n", uri.port, r.port); return false; } if (uri.path != r.path) { printf("path incorrect: %s != %s\n", uri.path.c_str(), r.path.c_str()); return false; } if (uri.query != r.query) { printf("query incorrect: %s != %s\n", uri.query.c_str(), r.query.c_str()); return false; } if (uri.fragment != r.fragment) { printf("fragment incorrect: %s != %s\n", uri.fragment.c_str(), r.fragment.c_str()); return false; } return true; } int main(int argc, char** argv) { prepare_correct_results(); int32_t i; Uri uri; for (i = 0; i < URI_COUNT; ++i) { if (!uri.parse(test_uris[i])) { printf("parse uri %s failed\n", test_uris[i]); return 1; } if (!check_result(uri, correct_results[i])) return 1; } printf("uri test success\n"); return 0; }
27.679612
89
0.668888
Rokid
7cc25f769f8089c602d3de999ea8e8d20d710a88
2,189
cpp
C++
Tests/unit-tests/Source/opennwa/namespace-query/states-overlap.cpp
jusito/WALi-OpenNWA
2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99
[ "MIT" ]
15
2015-03-07T17:25:57.000Z
2022-02-04T20:17:00.000Z
src/wpds/Tests/unit-tests/Source/opennwa/namespace-query/states-overlap.cpp
ucd-plse/mpi-error-prop
4367df88bcdc4d82c9a65b181d0e639d04962503
[ "BSD-3-Clause" ]
1
2018-03-03T05:58:55.000Z
2018-03-03T12:26:10.000Z
src/wpds/Tests/unit-tests/Source/opennwa/namespace-query/states-overlap.cpp
ucd-plse/mpi-error-prop
4367df88bcdc4d82c9a65b181d0e639d04962503
[ "BSD-3-Clause" ]
15
2015-09-25T17:44:35.000Z
2021-07-18T18:25:38.000Z
#include "gtest/gtest.h" #include "opennwa/Nwa.hpp" #include "opennwa/query/automaton.hpp" #include "Tests/unit-tests/Source/opennwa/fixtures.hpp" #include "Tests/unit-tests/Source/opennwa/class-NWA/supporting.hpp" namespace opennwa { namespace query { TEST(opennwa$query$$statesOverlap, emptyDoesNotOverlap) { OddNumEvenGroupsNwa fixture; Nwa empty; EXPECT_FALSE(statesOverlap(empty, empty)); EXPECT_FALSE(statesOverlap(empty, fixture.nwa)); } TEST(opennwa$query$$statesOverlap, oddEvenOverlapsWithItself) { OddNumEvenGroupsNwa f1, f2; EXPECT_TRUE(statesOverlap(f1.nwa, f2.nwa)); } TEST(opennwa$query$$statesOverlap, subsetsOverlap) { OddNumEvenGroupsNwa fixture; Nwa nwa; // 1 element overlap ASSERT_TRUE(nwa.addState(fixture.q0)); EXPECT_TRUE(statesOverlap(fixture.nwa, nwa)); // 2 element overlap ASSERT_TRUE(nwa.addState(fixture.q1)); EXPECT_TRUE(statesOverlap(fixture.nwa, nwa)); // Large overlap nwa = fixture.nwa; ASSERT_TRUE(nwa.removeState(fixture.dummy)); EXPECT_TRUE(statesOverlap(fixture.nwa, nwa)); } TEST(opennwa$query$$statesOverlap, largeDisjointLargeDoNotOverlap) { OddNumEvenGroupsNwa fixture; SomeElements e; Nwa nwa; e.add_to_nwa(&nwa); EXPECT_FALSE(statesOverlap(fixture.nwa, nwa)); } TEST(opennwa$query$$statesOverlap, incomparableDoNotOverlap) { OddNumEvenGroupsNwa fixture; Nwa nwa1 = fixture.nwa; Nwa nwa2 = fixture.nwa; ASSERT_TRUE(nwa1.removeState(fixture.dummy)); ASSERT_TRUE(nwa2.removeState(fixture.q0)); EXPECT_TRUE(statesOverlap(nwa1, nwa2)); } } }
28.428571
78
0.539516
jusito
7cc6f8b65c023da7b5d1209a6c254884081e3697
77,980
cpp
C++
EBUCoreProcessor/src/EBUCore_1_4/EBUCoreMapping.cpp
Limecraft/ebu-mxfsdk
d2461c778f7980c4e116a53123c2ba744b1362a0
[ "Apache-2.0" ]
20
2015-02-24T23:54:23.000Z
2022-03-29T12:42:32.000Z
EBUCoreProcessor/src/EBUCore_1_4/EBUCoreMapping.cpp
ebu/ebu-mxfsdk
d66e4b05354ec2b80365f1956f14678c6f7f6514
[ "Apache-2.0" ]
1
2018-10-26T00:44:05.000Z
2018-10-26T00:44:05.000Z
EBUCoreProcessor/src/EBUCore_1_4/EBUCoreMapping.cpp
ebu/ebu-mxfsdk
d66e4b05354ec2b80365f1956f14678c6f7f6514
[ "Apache-2.0" ]
6
2015-02-05T09:54:14.000Z
2022-02-26T20:56:32.000Z
/* * Copyright 2012-2013 European Broadcasting Union and Limecraft, NV. * * 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 "EBUCore_1_4/EBUCoreMapping.h" #include "AppUtils.h" #include <xercesc/util/TransService.hpp> using namespace ebuCore_2012; using namespace mxfpp; //using namespace bmx; namespace EBUSDK { namespace EBUCore { namespace EBUCore_1_4 { #define SIMPLE_MAP(source, sourceProperty, dest, destProperty) \ dest->destProperty(source.sourceProperty().get()); #define SIMPLE_MAP_NO_GET(source, sourceProperty, dest, destProperty) \ dest->destProperty(source.sourceProperty()); #define SIMPLE_MAP_OPTIONAL(source, sourceProperty, dest, destProperty) \ if (source.sourceProperty().present()) \ dest->destProperty(source.sourceProperty().get()); #define SIMPLE_MAP_OPTIONAL_CONVERT(source, sourceProperty, dest, destProperty, convertFunction) \ if (source.sourceProperty().present()) \ dest->destProperty(convertFunction(source.sourceProperty().get())); #define NEW_OBJECT_AND_ASSIGN(source, sourceProperty, destType, mapMethod, dest, destProperty) \ { \ destType *obj = newAndModifyObject<destType>(dest->getHeaderMetadata(), mod); \ mapMethod(source.sourceProperty(), obj, mod); \ dest->destProperty(obj); \ } #define NEW_OBJECT_AND_ASSIGN_DIRECT(source, destType, mapMethod, dest, destProperty) \ { \ destType *obj = newAndModifyObject<destType>(dest->getHeaderMetadata(), mod); \ mapMethod(source, obj, mod); \ dest->destProperty(obj); \ } #define NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, sourceProperty, destType, mapMethod, dest, destProperty) \ if (source.sourceProperty().present()) { \ destType *obj = newAndModifyObject<destType>(dest->getHeaderMetadata(), mod); \ mapMethod(source.sourceProperty().get(), obj, mod); \ dest->destProperty(obj); \ } #define NEW_VECTOR_AND_ASSIGN(source, sourceProperty, destType, iteratorType, mapMethod, dest, destProperty) \ if (source.sourceProperty().size() > 0) \ { std::vector<destType*> vec_dest_destProperty; \ for (iteratorType it = source.sourceProperty().begin(); it != source.sourceProperty().end(); it++) { \ destType *obj = newAndModifyObject<destType>(dest->getHeaderMetadata(), mod); \ mapMethod(*it, obj, mod); \ vec_dest_destProperty.push_back(obj); \ } \ dest->destProperty(vec_dest_destProperty); } #define NEW_VECTOR_AND_APPEND(source, sourceProperty, destType, iteratorType, mapMethod, dest, destVector) \ { \ for (iteratorType it = source.sourceProperty().begin(); it != source.sourceProperty().end(); it++) { \ destType *obj = newAndModifyObject<destType>(dest->getHeaderMetadata(), mod); \ mapMethod(*it, obj, mod); \ destVector.push_back(obj); \ } } #define SIMPLE_MAP_OPTIONAL_TO_NEW_VECTOR_AND_ASSIGN(source, sourceProperty, destType, mapMethod, dest, destProperty) \ if (source.sourceProperty().present()) { \ destType *obj = newAndModifyObject<destType>(dest->getHeaderMetadata(), mod); \ mapMethod(source.sourceProperty().get(), obj, mod); \ std::vector<destType*> v_dest_destProperty; \ v_dest_destProperty.push_back(obj); \ dest->destProperty(v_dest_destProperty); \ } #define MAP_TYPE_GROUP(source, dest) \ SIMPLE_MAP_OPTIONAL(source, typeDefinition, dest, settypeGroupDefinition) \ SIMPLE_MAP_OPTIONAL(source, typeLabel, dest, settypeGroupLabel) \ SIMPLE_MAP_OPTIONAL(source, typeLink, dest, settypeGroupLink) \ SIMPLE_MAP_OPTIONAL(source, typeLanguage, dest, settypeGroupLanguage) /* This macro is not defined as a function since typeGroups are not separate types but are more like duck typing (just a group of included attributes). Same for other such groups (format-, status-) */ #define MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, destProperty) \ ebucoreTypeGroup *typeGroup = newAndModifyObject<ebucoreTypeGroup>(dest->getHeaderMetadata(), mod); \ MAP_TYPE_GROUP(source, typeGroup) \ dest->destProperty(typeGroup); \ #define MAP_STATUS_GROUP(source, dest) \ SIMPLE_MAP_OPTIONAL(source, statusDefinition, dest, setstatusGroupDefinition) \ SIMPLE_MAP_OPTIONAL(source, statusLabel, dest, setstatusGroupLabel) \ SIMPLE_MAP_OPTIONAL(source, statusLink, dest, setstatusGroupLink) \ SIMPLE_MAP_OPTIONAL(source, statusLanguage, dest, setstatusGroupLanguage) #define MAP_NEW_STATUS_GROUP_AND_ASSIGN(source, dest, destProperty) \ ebucoreStatusGroup *statusGroup = newAndModifyObject<ebucoreStatusGroup>(dest->getHeaderMetadata(), mod); \ MAP_STATUS_GROUP(source, statusGroup) \ dest->destProperty(statusGroup); #define MAP_FORMAT_GROUP(source, dest) \ SIMPLE_MAP_OPTIONAL(source, formatDefinition, dest, setformatGroupDefinition) \ SIMPLE_MAP_OPTIONAL(source, formatLabel, dest, setformatGroupLabel) \ SIMPLE_MAP_OPTIONAL(source, formatLink, dest, setformatGroupLink) \ SIMPLE_MAP_OPTIONAL(source, formatLanguage, dest, setformatGroupLanguage) #define MAP_NEW_FORMAT_GROUP_AND_ASSIGN(source, dest, destProperty) \ ebucoreFormatGroup *statusGroup = newAndModifyObject<ebucoreFormatGroup>(dest->getHeaderMetadata(), mod); \ MAP_FORMAT_GROUP(source, statusGroup) \ dest->destProperty(statusGroup); template <class T> T* newAndModifyObject(HeaderMetadata *headerMetadata, ObjectModifier *mod) { T *obj = new T(headerMetadata); if (mod != NULL) mod->Modify(obj); return obj; } void mapRole(role& source, ebucoreRole *dest, ObjectModifier* mod = NULL) { // [TODO] // [XSD] Fix attribute type of costcenter to string so we can map it here MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setroleTypeGroup) } void mapTextualAnnotation(std::string source, ebucoreTextualAnnotation *dest, ObjectModifier* mod = NULL) { /* cannot deal with lang as source is single string */ dest->settext(source); } void mapTextualAnnotation(dc::elementType source, ebucoreTextualAnnotation *dest, ObjectModifier* mod = NULL) { dest->settext(source); dest->settextLanguage(source.lang()); } void mapCountry(country& source, ebucoreCountry *dest, ObjectModifier* mod = NULL) { MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setcountryTypeGroup) } void mapCountry(regionType::country_type& source, ebucoreCountry *dest, ObjectModifier* mod = NULL) { MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setcountryTypeGroup) } void mapAddress(addressType& source, ebucoreAddress *dest, ObjectModifier* mod = NULL) { if (source.addressLine().size() > 0) { NEW_VECTOR_AND_ASSIGN(source, addressLine, ebucoreTextualAnnotation, addressType::addressLine_iterator, mapTextualAnnotation, dest, setaddressLines) } SIMPLE_MAP_OPTIONAL_TO_NEW_VECTOR_AND_ASSIGN(source, addressTownCity, ebucoreTextualAnnotation, mapTextualAnnotation, dest, settownCity) SIMPLE_MAP_OPTIONAL_TO_NEW_VECTOR_AND_ASSIGN(source, addressCountyState, ebucoreTextualAnnotation, mapTextualAnnotation, dest, setcountyState) SIMPLE_MAP_OPTIONAL(source, addressDeliveryCode, dest, setdeliveryCode) SIMPLE_MAP_OPTIONAL_TO_NEW_VECTOR_AND_ASSIGN(source, country, ebucoreCountry, mapCountry, dest, setcountry) } void mapDetails(detailsType& source, ebucoreContactDetails *dest, ObjectModifier* mod = NULL) { if (source.emailAddress().size() > 0) { dest->setemailAddress(source.emailAddress()[0]); } SIMPLE_MAP_OPTIONAL(source, webAddress, dest, setwebAddress) // map address NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, address, ebucoreAddress, mapAddress, dest, setaddress) SIMPLE_MAP_OPTIONAL(source, telephoneNumber, dest, settelephoneNumber) SIMPLE_MAP_OPTIONAL(source, mobileTelephoneNumber, dest, setmobileTelephoneNumber) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setdetailsType) } void mapName(compoundNameType& source, ebucoreCompoundName *dest, ObjectModifier* mod = NULL) { dest->setcompoundName(source); MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setcompoundNameTypeGroup) MAP_NEW_FORMAT_GROUP_AND_ASSIGN(source, dest, setcompoundNameFormatGroup) } void mapIdentifier(identifierType& source, ebucoreIdentifier *dest, ObjectModifier* mod = NULL); void mapBasicLink(relatedInformationLink& source, ebucoreBasicLink *dest, ObjectModifier* mod = NULL) { dest->setbasicLinkURI(source); } void mapBasicLink(relatedInformationLink1& source, ebucoreBasicLink *dest, ObjectModifier* mod = NULL) { dest->setbasicLinkURI(source); } void mapContact(contactDetailsType& source, ebucoreContact *dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, contactId, dest, setcontactId) NEW_VECTOR_AND_ASSIGN(source, name, ebucoreCompoundName, contactDetailsType::name_iterator, mapName, dest, setcontactName) SIMPLE_MAP_OPTIONAL(source, givenName, dest, setgivenName) SIMPLE_MAP_OPTIONAL(source, familyName, dest, setfamilyName) SIMPLE_MAP_OPTIONAL(source, suffix, dest, setsuffix) SIMPLE_MAP_OPTIONAL(source, salutation, dest, setsalutation) SIMPLE_MAP_OPTIONAL(source, guest, dest, setguestFlag) NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, gender, ebucoreTextualAnnotation, mapTextualAnnotation, dest, setgender) NEW_VECTOR_AND_ASSIGN(source, otherGivenName, ebucoreTextualAnnotation, contactDetailsType::otherGivenName_iterator, mapTextualAnnotation, dest, setotherGivenName) if (source.username().size() > 0) { dest->setusername(source.username()[0]); } SIMPLE_MAP_OPTIONAL(source, occupation, dest, setoccupation) NEW_VECTOR_AND_ASSIGN(source, details, ebucoreContactDetails, contactDetailsType::details_sequence::iterator, mapDetails, dest, setcontactDetails) NEW_VECTOR_AND_ASSIGN(source, stageName, ebucoreTextualAnnotation, contactDetailsType::stageName_iterator, mapTextualAnnotation, dest, setstageName) NEW_VECTOR_AND_ASSIGN(source, relatedContacts, ebucoreEntity, contactDetailsType::relatedContacts_iterator, mapEntity, dest, setcontactRelatedContacts) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setcontactType) NEW_VECTOR_AND_ASSIGN(source, relatedInformationLink, ebucoreBasicLink, contactDetailsType::relatedInformationLink_iterator, mapBasicLink, dest, setcontactRelatedInformationLink) } void mapOrganisationDepartment(organisationDepartment& source, ebucoreOrganisationDepartment *dest, ObjectModifier* mod = NULL) { dest->setdepartmentName(source); SIMPLE_MAP_OPTIONAL(source, departmentId, dest, setdepartmentId) } void mapOrganisation(organisationDetailsType& source, ebucoreOrganisation *dest, ObjectModifier* mod = NULL) { // [TODO] The KLV mapping is somewhat inconsistent at this point with the XSD: // - XSD departmentId is not present in KLV SIMPLE_MAP_OPTIONAL(source, organisationId, dest, setorganisationId) NEW_VECTOR_AND_ASSIGN(source, organisationName, ebucoreCompoundName, organisationDetailsType::organisationName_iterator, mapName, dest, setorganisationName) NEW_VECTOR_AND_ASSIGN(source, organisationCode, ebucoreIdentifier, organisationDetailsType::organisationCode_iterator, mapIdentifier, dest, setorganisationCode) NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, organisationDepartment, ebucoreOrganisationDepartment, mapOrganisationDepartment, dest, setorganisationDepartment) NEW_VECTOR_AND_ASSIGN(source, details, ebucoreContactDetails, contactDetailsType::details_sequence::iterator, mapDetails, dest, setorganisationDetails) NEW_VECTOR_AND_ASSIGN(source, contacts, ebucoreEntity, organisationDetailsType::contacts_iterator, mapEntity, dest, setorganisationRelatedContacts) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setorganisationType) NEW_VECTOR_AND_ASSIGN(source, relatedInformationLink, ebucoreBasicLink, organisationDetailsType::relatedInformationLink_iterator, mapBasicLink, dest, setorganisationRelatedInformationLink) } void mapEntity(entityType& source, ebucoreEntity *dest, ObjectModifier* mod) { SIMPLE_MAP_OPTIONAL(source, entityId, dest, setentityId) NEW_VECTOR_AND_ASSIGN(source, contactDetails, ebucoreContact, entityType::contactDetails_iterator, mapContact, dest, setentityContact) NEW_VECTOR_AND_ASSIGN(source, organisationDetails, ebucoreOrganisation, entityType::organisationDetails_iterator, mapOrganisation, dest, setentityOrganisation) NEW_VECTOR_AND_ASSIGN(source, role, ebucoreRole, entityType::role_iterator, mapRole, dest, setentityRole) } void mapMetadataSchemeInformation(ebuCoreMainType& source, ebucoreMetadataSchemeInformation *dest, ObjectModifier* mod) { /* <sequence> <element name="coreMetadata" type="ebucore:coreMetadataType"> </element> <element name="metadataProvider" type="ebucore:entityType" minOccurs="0"> </element> </sequence> <attribute name="schema" default="EBU_CORE_20110531.xsd"> </attribute> <attribute name="version" default="1.3"> </attribute> <attribute name="dateLastModified" type="date"> </attribute> <attribute name="documentId" type="NMTOKEN"> </attribute> <attribute ref="xml:lang"> </attribute> */ NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, metadataProvider, ebucoreEntity, mapEntity, dest, setebucoreMetadataProvider) // is there a version node? appearently, no easier way to check than // to look through the attributes of the source node and see if there // is a matching attribute xercesc::DOMNamedNodeMap* attrs = source._node()->getAttributes(); XMLCh* str_version = xercesc::XMLString::transcode("version"); const xercesc::DOMNode* version_node = attrs->getNamedItem(str_version); xercesc::XMLString::release(&str_version); if (version_node != NULL) { xercesc::TranscodeToStr version(source.version()._node()->getTextContent(), "UTF-8"); std::string std_version((char*)version.str()); dest->setebucoreMetadataSchemeVersion(std_version); } /* EBUCore1.4: XMLCh* str_schema = xercesc_3_1::XMLString::transcode("schema"); const xercesc_3_1::DOMNode* schema_node = attrs->getNamedItem(str_schema); xercesc_3_1::XMLString::release(&str_schema); if (schema_node != NULL) { xercesc_3_1::TranscodeToStr schema(source.schema()._node()->getTextContent(), "UTF-8"); std::string std_schema((char*)schema.str()); dest->setebucoreMetadataScheme(std_schema); }*/ } mxfTimestamp convert_timestamp(xml_schema::date& source) { mxfTimestamp ts = {0,0,0,0,0,0,0}; ts.day = source.day(); ts.month = source.month(); ts.year = source.year(); return ts; } mxfTimestamp convert_timestamp(xml_schema::gyear& source) { mxfTimestamp ts = {0,0,0,0,0,0,0}; ts.year = source.year(); return ts; } std::string convert(xml_schema::gyear& source) { std::stringstream ss; ss << source.year(); return ss.str(); } std::string convert(xml_schema::date& source) { std::stringstream ss; ss << source.day() << '/' << source.month() << '/' << source.year(); return ss.str(); } std::string convert(xml_schema::time& source) { std::stringstream ss; ss << source.hours() << ':' << source.minutes() << ':' << source.seconds(); return ss.str(); } mxfTimestamp convert_timestamp(xml_schema::time& source) { mxfTimestamp ts = {0,0,0,0,0,0,0}; ts.hour = source.hours(); ts.min = source.minutes(); ts.sec = source.seconds(); return ts; } std::string convert(xml_schema::idrefs& source) { std::stringstream ss; size_t l = source.size(); size_t i = 0; for (xml_schema::idrefs::iterator it = source.begin(); it != source.end(); it++) { i++; ss << (*it); if (i < l) ss << ' '; } return ss.str(); } mxfRational convert(xml_schema::long_& source) { mxfRational r = {source, 1}; return r; } mxfRational convert(rationalType& source) { mxfRational r = {source.factorNumerator(), source.factorDenominator()}; return r; } std::string convert_to_string(::xml_schema::integer& source) { std::stringstream ss; ss << source; return ss.str(); } mxfRational convert_rational(xml_schema::duration& source) { mxfRational r = { (source.years() * 365 * 86400 + source.months() * 30 * 86400 + source.days() * 86400 + source.hours() * 3600 + source.minutes() * 60 + source.seconds()) * 100, 100}; return r; } mxfRational convert_rational(xml_schema::time& source) { mxfRational r = { (source.hours() * 3600 + source.minutes() * 60 + source.seconds()) * 100, 100}; return r; } void mapTitle(titleType& source, ebucoreTitle *dest, ObjectModifier* mod = NULL) { NEW_VECTOR_AND_ASSIGN(source, title, ebucoreTextualAnnotation, titleType::title_iterator, mapTextualAnnotation, dest, settitleValue) SIMPLE_MAP_OPTIONAL(source, note, dest, settitleNote) SIMPLE_MAP_OPTIONAL_CONVERT(source, attributiondate, dest, settitleAttributionDate, convert_timestamp) } void mapAlternativeTitle(alternativeTitleType& source, ebucoreAlternativeTitle *dest, ObjectModifier* mod = NULL) { NEW_VECTOR_AND_ASSIGN(source, title, ebucoreTextualAnnotation, alternativeTitleType::title_iterator, mapTextualAnnotation, dest, setalternativeTitleValue) SIMPLE_MAP_OPTIONAL(source, note, dest, setalternativeTitleNote) SIMPLE_MAP_OPTIONAL_CONVERT(source, startDate, dest, setalternativeTitleAttributionDate, convert_timestamp) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setalternativeTitleTypeGroup) MAP_NEW_STATUS_GROUP_AND_ASSIGN(source, dest, setalternativeTitleStatusGroup) } void mapIdentifier(identifierType& source, ebucoreIdentifier *dest, ObjectModifier* mod) { SIMPLE_MAP_NO_GET(source, identifier, dest, setidentifierValue) SIMPLE_MAP_OPTIONAL(source, note, dest, setidentifierNote) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setidentifierTypeGroup) MAP_NEW_FORMAT_GROUP_AND_ASSIGN(source, dest, setidentifierFormatGroup) NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, attributor, ebucoreEntity, mapEntity, dest, setidentifierAttributorEntity) } void mapDescription(descriptionType& source, ebucoreDescription *dest, ObjectModifier* mod = NULL) { NEW_VECTOR_AND_ASSIGN(source, description, ebucoreTextualAnnotation, descriptionType::description_iterator, mapTextualAnnotation, dest, setdescriptionValue) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setdescriptionTypeGroup) SIMPLE_MAP_OPTIONAL(source, note, dest, setdescriptionNote) } void mapSubject(subjectType& source, ebucoreSubject *dest, ObjectModifier* mod = NULL) { NEW_VECTOR_AND_ASSIGN(source, subject, ebucoreTextualAnnotation, subjectType::subject_const_iterator, mapTextualAnnotation, dest, setsubjectValue) SIMPLE_MAP_OPTIONAL(source, subjectCode, dest, setsubjectCode) NEW_VECTOR_AND_ASSIGN(source, subjectDefinition, ebucoreTextualAnnotation, subjectType::subjectDefinition_const_iterator, mapTextualAnnotation, dest, setsubjectDefinition) SIMPLE_MAP_OPTIONAL(source, note, dest, setsubjectNote) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setsubjectTypeGroup) NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, attributor, ebucoreEntity, mapEntity, dest, setsubjectAttributorEntity) } void mapRegion(regionType& source, ebucoreRegion *dest, ObjectModifier* mod = NULL) { NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, country, ebucoreCountry, mapCountry, dest, setcountry) if (source.countryRegion().size() > 0) { MAP_NEW_TYPE_GROUP_AND_ASSIGN(source.countryRegion()[0], dest, setcountryRegion) } } void mapRating(ratingType& source, ebucoreRating *dest, ObjectModifier* mod = NULL) { NEW_VECTOR_AND_ASSIGN(source, ratingValue, ebucoreTextualAnnotation, ratingType::ratingValue_const_iterator, mapTextualAnnotation, dest, setratingValue) NEW_VECTOR_AND_ASSIGN(source, ratingScaleMaxValue, ebucoreTextualAnnotation, ratingType::ratingScaleMaxValue_const_iterator, mapTextualAnnotation, dest, setratingScaleMaxValue) NEW_VECTOR_AND_ASSIGN(source, ratingScaleMinValue, ebucoreTextualAnnotation, ratingType::ratingScaleMinValue_const_iterator, mapTextualAnnotation, dest, setratingScaleMinValue) SIMPLE_MAP_OPTIONAL(source, reason, dest, setratingReason) SIMPLE_MAP_OPTIONAL(source, linkToLogo, dest, setratingLinkToLogo) SIMPLE_MAP_OPTIONAL(source, notRated, dest, setratingNotRatedFlag) SIMPLE_MAP_OPTIONAL(source, adultContent, dest, setratingAdultContentFlag) NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, ratingProvider, ebucoreEntity, mapEntity, dest, setratingProviderEntity) if (source.ratingRegion().size() > 0) { NEW_OBJECT_AND_ASSIGN_DIRECT(source.ratingRegion()[0], ebucoreRegion, mapRegion, dest, setratingRegion) } MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setratingTypeGroup) MAP_NEW_FORMAT_GROUP_AND_ASSIGN(source, dest, setratingFormatGroup) } void mapVersion(coreMetadataType::version_type& source, ebucoreVersion *dest, ObjectModifier* mod = NULL) { ebucoreTextualAnnotation *obj = newAndModifyObject<ebucoreTextualAnnotation>(dest->getHeaderMetadata(), mod); mapTextualAnnotation(source, obj, mod); std::vector<ebucoreTextualAnnotation*> v_dest_destProperty; v_dest_destProperty.push_back(obj); dest->setversionValue(v_dest_destProperty); MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setversionTypeGroup) } void mapLanguage(languageType& source, ebucoreLanguage *dest, ObjectModifier* mod = NULL) { // TODO: KLV Language has an indirection for languagepurpose via a languagepurposeset which contains // only a reference to the typegroup, required? SIMPLE_MAP_OPTIONAL(source, language, dest, setlanguageCode) if (source.language().present()) { dest->setlanguageLanguageCode(source.language().get().lang()); } MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setlanguagePurposeSet) SIMPLE_MAP_OPTIONAL(source, note, dest, setlanguageNote) } void mapTargetAudience(targetAudience& source, ebucoreTargetAudience *dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, reason, dest, settargetAudienceReason) SIMPLE_MAP_OPTIONAL(source, linkToLogo, dest, settargetAudienceLinkToLogo) SIMPLE_MAP_OPTIONAL(source, notRated, dest, settargetAudienceNotRatedFlag) SIMPLE_MAP_OPTIONAL(source, adultContent, dest, settargetAudienceAdultContentFlag) NEW_VECTOR_AND_ASSIGN(source, targetRegion, ebucoreRegion, targetAudience::targetRegion_iterator, mapRegion, dest, settargetAudienceRegion) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, settargetAudienceTypeGroup) } void mapGenre(genre& source, ebucoreGenre *dest, ObjectModifier* mod = NULL) { MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setgenreKindGroup) } void mapType(typeType& source, ebucoreType *dest, ObjectModifier* mod = NULL) { NEW_VECTOR_AND_ASSIGN(source, type, ebucoreTextualAnnotation, typeType::type_iterator, mapTextualAnnotation, dest, settypeValue) std::vector<ebucoreObjectType*> vec_dest_objecttype; for (typeType::objectType_iterator it = source.objectType().begin(); it != source.objectType().end(); it++) { ebucoreObjectType *obj = newAndModifyObject<ebucoreObjectType>(dest->getHeaderMetadata(), mod); MAP_NEW_TYPE_GROUP_AND_ASSIGN(source.objectType().front(), obj, setobjectTypeGroup) vec_dest_objecttype.push_back(obj); } dest->setobjectType(vec_dest_objecttype); NEW_VECTOR_AND_ASSIGN(source, targetAudience, ebucoreTargetAudience, typeType::targetAudience_iterator, mapTargetAudience, dest, settargetAudience) NEW_VECTOR_AND_ASSIGN(source, genre, ebucoreGenre, typeType::genre_iterator, mapGenre, dest, setgenre) SIMPLE_MAP_OPTIONAL(source, note, dest, settypeNote) } void mapDateType(alternative& source, ebucoreDateType *dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL_CONVERT(source, startDate, dest, setdateValue, convert_timestamp) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setdateTypeGroup) } void mapDate(dateType& source, ebucoreDate* dest, ObjectModifier* mod = NULL) { // no valid mapping currently for a single note element (DC date is candidate, but cardinality is wrong) if (source.created().present()) { dateType::created_type& date = source.created().get(); SIMPLE_MAP_OPTIONAL_CONVERT(date, startYear, dest, setyearCreated, convert_timestamp) SIMPLE_MAP_OPTIONAL_CONVERT(date, startDate, dest, setdateCreated, convert_timestamp) } if (source.issued().present()) { dateType::issued_type& date = source.issued().get(); SIMPLE_MAP_OPTIONAL_CONVERT(date, startYear, dest, setyearIssued, convert_timestamp) SIMPLE_MAP_OPTIONAL_CONVERT(date, startDate, dest, setdateIssued, convert_timestamp) } if (source.modified().present()) { dateType::modified_type& date = source.modified().get(); SIMPLE_MAP_OPTIONAL_CONVERT(date, startYear, dest, setyearModified, convert_timestamp) SIMPLE_MAP_OPTIONAL_CONVERT(date, startDate, dest, setdateModified, convert_timestamp) } if (source.digitised().present()) { dateType::digitised_type& date = source.digitised().get(); SIMPLE_MAP_OPTIONAL_CONVERT(date, startYear, dest, setyearDigitized, convert_timestamp) SIMPLE_MAP_OPTIONAL_CONVERT(date, startDate, dest, setdateDigitized, convert_timestamp) } if (source.released().present()) { dateType::released_type& date = source.released().get(); SIMPLE_MAP_OPTIONAL_CONVERT(date, startYear, dest, setyearReleased, convert_timestamp) SIMPLE_MAP_OPTIONAL_CONVERT(date, startDate, dest, setdateReleased, convert_timestamp) } if (source.copyrighted().present()) { dateType::copyrighted_type& date = source.copyrighted().get(); SIMPLE_MAP_OPTIONAL_CONVERT(date, startYear, dest, setyearCopyrighted, convert_timestamp) SIMPLE_MAP_OPTIONAL_CONVERT(date, startDate, dest, setdateCopyrighted, convert_timestamp) } NEW_VECTOR_AND_ASSIGN(source, alternative, ebucoreDateType, dateType::alternative_iterator, mapDateType, dest, setalternativeDate) } void mapPeriodOfTime(periodOfTimeType& source, ebucorePeriodOfTime* dest, ObjectModifier* mod = NULL) { // [TODO] PeriodId is at temporal level //SIMPLE_MAP_OPTIONAL(source, period, dest, setperiodId) SIMPLE_MAP_OPTIONAL_TO_NEW_VECTOR_AND_ASSIGN(source, periodName, ebucoreTextualAnnotation, mapTextualAnnotation, dest, setperiodName) SIMPLE_MAP_OPTIONAL_CONVERT(source, startYear, dest, setperiodStartYear, convert_timestamp) SIMPLE_MAP_OPTIONAL_CONVERT(source, startDate, dest, setperiodStartDate, convert_timestamp) SIMPLE_MAP_OPTIONAL_CONVERT(source, startTime, dest, setperiodStartTime, convert_timestamp) SIMPLE_MAP_OPTIONAL_CONVERT(source, endYear, dest, setperiodEndYear, convert_timestamp) SIMPLE_MAP_OPTIONAL_CONVERT(source, endDate, dest, setperiodEndDate, convert_timestamp) SIMPLE_MAP_OPTIONAL_CONVERT(source, endTime, dest, setperiodEndTime, convert_timestamp) } void mapTemporal(temporal& source, ebucoreTemporal *dest, ObjectModifier* mod = NULL) { // [EBUCore1.4] PeriodId in temporal?? NEW_VECTOR_AND_ASSIGN(source, PeriodOfTime, ebucorePeriodOfTime, temporal::PeriodOfTime_iterator, mapPeriodOfTime, dest, setperiodOfTime) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, settemporalTypeGroup) SIMPLE_MAP_OPTIONAL(source, note, dest, settemporalDefinitionNote) } void mapCoordinates(coordinates& source, ebucoreCoordinates *dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_NO_GET(source, posx, dest, setposX) SIMPLE_MAP_NO_GET(source, posy, dest, setposY) MAP_NEW_FORMAT_GROUP_AND_ASSIGN(source, dest, setcoordinatesFormatGroup) } void mapLocation(spatial::location_type& source, ebucoreLocation *dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, locationId, dest, setlocationId) SIMPLE_MAP_OPTIONAL(source, code, dest, setlocationCode) SIMPLE_MAP_OPTIONAL(source, note, dest, setlocationDefinitionNote) SIMPLE_MAP_OPTIONAL_TO_NEW_VECTOR_AND_ASSIGN(source, name, ebucoreTextualAnnotation, mapTextualAnnotation, dest, setlocationName) NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, region, ebucoreRegion, mapRegion, dest, setlocationRegion) NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, coordinates, ebucoreCoordinates, mapCoordinates, dest, setlocationCoordinates) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setlocationTypeGroup) } void mapSpatial(spatial& source, ebucoreSpatial *dest, ObjectModifier* mod = NULL) { NEW_VECTOR_AND_ASSIGN(source, location, ebucoreLocation, spatial::location_iterator, mapLocation, dest, setlocation) } void mapMetadataCoverage(coverageType& source, ebucoreCoverage *dest, ObjectModifier* mod = NULL) { NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, coverage, ebucoreTextualAnnotation, mapTextualAnnotation, dest, setcoverageValue) NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, temporal, ebucoreTemporal, mapTemporal, dest, settemporal) NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, spatial, ebucoreSpatial, mapSpatial, dest, setspatial) } void mapRights(rightsType& source, ebucoreRights *dest, std::map<xml_schema::id, ebucoreFormat*>& formatMap, std::map<xml_schema::id, ebucoreRights*>& rightsMap, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, rightsID, dest, setrightsId) NEW_VECTOR_AND_ASSIGN(source, rightsAttributedId, ebucoreIdentifier, rightsType::rightsAttributedId_iterator, mapIdentifier, dest, setrightsAttributeID) NEW_VECTOR_AND_ASSIGN(source, rights, ebucoreTextualAnnotation, rightsType::rights_iterator, mapTextualAnnotation, dest, setrightsValue) SIMPLE_MAP_OPTIONAL(source, rightsClearanceFlag, dest, setrightsClearanceFlag) NEW_VECTOR_AND_ASSIGN(source, exploitationIssues, ebucoreTextualAnnotation, rightsType::exploitationIssues_iterator, mapTextualAnnotation, dest, setexploitationIssues) NEW_VECTOR_AND_ASSIGN(source, copyrightStatement, ebucoreTextualAnnotation, rightsType::copyrightStatement_iterator, mapTextualAnnotation, dest, setcopyrightStatement) SIMPLE_MAP_OPTIONAL(source, rightsLink, dest, setrightsLink) SIMPLE_MAP_OPTIONAL(source, note, dest, setrightsNote) NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, coverage, ebucoreCoverage, mapMetadataCoverage, dest, setrightsCoverage) NEW_VECTOR_AND_ASSIGN(source, rightsHolder, ebucoreEntity, rightsType::rightsHolder_iterator, mapEntity, dest, setrightsHolderEntity) NEW_VECTOR_AND_ASSIGN(source, contactDetails, ebucoreContact, rightsType::contactDetails_sequence::iterator, mapContact, dest, setrightsContacts) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setrightsTypeGroup) // [TODO] Deal with format references //SIMPLE_MAP_OPTIONAL_CONVERT(source, formatIDRefs, dest, setrightsFormatIDRef, convert) // find this formatIdRef in the map of formats if (source.formatIDRefs().present()) { std::vector<ebucoreFormat*> destRefs; rightsType::formatIDRefs_type& refs = source.formatIDRefs().get(); for (xml_schema::idrefs::iterator it = refs.begin(); it != refs.end(); it++) { if (formatMap.find(*it) != formatMap.end()) { // present! destRefs.push_back(formatMap[*it]); } } if (destRefs.size() > 0) dest->setrightsFormatReferences(destRefs); } // and put the rights object in the map for further use if (source.rightsID().present()) { rightsMap[source.rightsID().get()] = dest; } } void mapPublicationChannel(publicationChannelType& source, ebucorePublicationChannel* dest, ObjectModifier* mod = NULL) { dest->setpublicationChannelName(source); SIMPLE_MAP_OPTIONAL(source, publicationChannelId, dest, setpublicationChannelId) SIMPLE_MAP_OPTIONAL(source, linkToLogo, dest, setpublicationChannelLinkToLogo) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setpublicationChannelType) } void mapPublicationMedium(publicationMediumType& source, ebucorePublicationMedium* dest, ObjectModifier* mod = NULL) { dest->setpublicationMediumName(source); SIMPLE_MAP_OPTIONAL(source, publicationMediumId, dest, setpublicationMediumName) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setpublicationMediumType) } void mapPublicationService(publicationServiceType& source, ebucorePublicationService* dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, publicationServiceName, dest, setpublicationServiceName) SIMPLE_MAP_OPTIONAL(source, linkToLogo, dest, setpublicationServiceLinkToLogo) NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, publicationSource, ebucoreOrganisation, mapOrganisation, dest, setpublicationServiceSource) } void mapPublicationHistoryEvent(publicationEventType& source, ebucorePublicationHistoryEvent* dest, std::map<xml_schema::id, ebucoreFormat*>& formatMap, std::map<xml_schema::id, ebucoreRights*>& rightsMap, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, publicationEventName, dest, setpublicationEventName) SIMPLE_MAP_OPTIONAL(source, publicationEventId, dest, setpublicationEventId) SIMPLE_MAP_OPTIONAL(source, firstShowing, dest, setfirstPublicationFlag) SIMPLE_MAP_OPTIONAL(source, free, dest, setfreePublicationFlag) SIMPLE_MAP_OPTIONAL(source, live, dest, setlivePublicationFlag) SIMPLE_MAP_OPTIONAL(source, note, dest, setpublicationNote) SIMPLE_MAP_OPTIONAL_CONVERT(source, publicationDate, dest, setpublicationDate, convert_timestamp) SIMPLE_MAP_OPTIONAL_CONVERT(source, publicationTime, dest, setpublicationDate, convert_timestamp) NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, publicationChannel, ebucorePublicationChannel, mapPublicationChannel, dest, setpublicationChannel) NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, publicationMedium, ebucorePublicationMedium, mapPublicationMedium, dest, setpublicationMedium) NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, publicationService, ebucorePublicationService, mapPublicationService, dest, setpublicationService) NEW_VECTOR_AND_ASSIGN(source, publicationRegion, ebucoreRegion, publicationEventType::publicationRegion_iterator, mapRegion, dest, setpublicationRegion) if (source.formatIdRef().present()) { // find this formatIdRef in the map of formats if (formatMap.find(source.formatIdRef().get()) != formatMap.end()) { // present! dest->setpublicationFormatReference(formatMap[source.formatIdRef().get()]); } } if (source.rightsIDRefs().present()) { publicationEventType::rightsIDRefs_type& rightsrefs = source.rightsIDRefs().get(); if (rightsrefs.size() > 0) { // for each of the references to a rights object, locate it in the rights map std::vector<ebucoreRights*> vec_rights; for (publicationEventType::rightsIDRefs_type::const_iterator it = rightsrefs.begin(); it != rightsrefs.end(); it++) { if (rightsMap.find(*it) != rightsMap.end()) { // present! vec_rights.push_back(rightsMap[*it]); } } dest->setpublicationRightsReference(vec_rights); // find this formatIdRef in the map of formats } } } void mapPublicationHistory(publicationHistoryType& source, ebucorePublicationHistory *dest, mxfpp::HeaderMetadata *header_metadata, std::map<xml_schema::id, ebucoreFormat*>& formatMap, std::map<xml_schema::id, ebucoreRights*>& rightsMap, ObjectModifier* mod = NULL) { std::vector<ebucorePublicationHistoryEvent*> vec_dest_hist; for (publicationHistoryType::publicationEvent_iterator it = source.publicationEvent().begin(); it != source.publicationEvent().end(); it++) { ebucorePublicationHistoryEvent *obj = newAndModifyObject<ebucorePublicationHistoryEvent>(header_metadata, mod); // special case of conversion using the format map mapPublicationHistoryEvent(*it, obj, formatMap, rightsMap, mod); vec_dest_hist.push_back(obj); } dest->setpublicationEvent(vec_dest_hist); } #define MAP_BASIC_RELATION_FUNCTION(destProperty) \ void mapBasicRelation_##destProperty(relationType& source, ebucoreBasicRelation *dest, ObjectModifier* mod = NULL) { \ SIMPLE_MAP_OPTIONAL(source, relationLink, dest, destProperty) \ } MAP_BASIC_RELATION_FUNCTION(setisVersionOf) MAP_BASIC_RELATION_FUNCTION(sethasVersion) MAP_BASIC_RELATION_FUNCTION(setisReplacedBy) MAP_BASIC_RELATION_FUNCTION(setreplaces) MAP_BASIC_RELATION_FUNCTION(setisRequiredBy) MAP_BASIC_RELATION_FUNCTION(setrequires) MAP_BASIC_RELATION_FUNCTION(setisPartOf) MAP_BASIC_RELATION_FUNCTION(sethasPart) MAP_BASIC_RELATION_FUNCTION(setisReferencedBy) MAP_BASIC_RELATION_FUNCTION(setreferences) MAP_BASIC_RELATION_FUNCTION(setisFormatOf) MAP_BASIC_RELATION_FUNCTION(sethasFormat) MAP_BASIC_RELATION_FUNCTION(setisEpisodeOf) MAP_BASIC_RELATION_FUNCTION(setisMemberOf) void mapBasicRelations(coreMetadataType& source, ebucoreCoreMetadata *dest, ObjectModifier* mod = NULL) { std::vector<ebucoreBasicRelation*> rels; NEW_VECTOR_AND_APPEND(source, isVersionOf, ebucoreBasicRelation, coreMetadataType::isVersionOf_iterator, mapBasicRelation_setisVersionOf, dest, rels) NEW_VECTOR_AND_APPEND(source, hasVersion, ebucoreBasicRelation, coreMetadataType::hasVersion_iterator, mapBasicRelation_sethasVersion, dest, rels) NEW_VECTOR_AND_APPEND(source, isReplacedBy, ebucoreBasicRelation, coreMetadataType::isReplacedBy_iterator, mapBasicRelation_setisReplacedBy, dest, rels) NEW_VECTOR_AND_APPEND(source, replaces, ebucoreBasicRelation, coreMetadataType::replaces_iterator, mapBasicRelation_setreplaces, dest, rels) NEW_VECTOR_AND_APPEND(source, isRequiredBy, ebucoreBasicRelation, coreMetadataType::isRequiredBy_iterator, mapBasicRelation_setisRequiredBy, dest, rels) NEW_VECTOR_AND_APPEND(source, requires, ebucoreBasicRelation, coreMetadataType::requires_iterator, mapBasicRelation_setrequires, dest, rels) NEW_VECTOR_AND_APPEND(source, isPartOf, ebucoreBasicRelation, coreMetadataType::isPartOf_iterator, mapBasicRelation_setisPartOf, dest, rels) NEW_VECTOR_AND_APPEND(source, hasPart, ebucoreBasicRelation, coreMetadataType::hasPart_iterator, mapBasicRelation_sethasVersion, dest, rels) NEW_VECTOR_AND_APPEND(source, isReferencedBy, ebucoreBasicRelation, coreMetadataType::isReferencedBy_iterator, mapBasicRelation_setisReferencedBy, dest, rels) NEW_VECTOR_AND_APPEND(source, references, ebucoreBasicRelation, coreMetadataType::references_iterator, mapBasicRelation_setreferences, dest, rels) NEW_VECTOR_AND_APPEND(source, isFormatOf, ebucoreBasicRelation, coreMetadataType::isFormatOf_iterator, mapBasicRelation_setisFormatOf, dest, rels) NEW_VECTOR_AND_APPEND(source, hasFormat, ebucoreBasicRelation, coreMetadataType::hasFormat_iterator, mapBasicRelation_sethasFormat, dest, rels) NEW_VECTOR_AND_APPEND(source, isEpisodeOf, ebucoreBasicRelation, coreMetadataType::isEpisodeOf_iterator, mapBasicRelation_setisEpisodeOf, dest, rels) NEW_VECTOR_AND_APPEND(source, isMemberOf, ebucoreBasicRelation, coreMetadataType::isMemberOf_iterator, mapBasicRelation_setisMemberOf, dest, rels) dest->setbasicRelation(rels); } void mapCustomRelation(relationType& source, ebucoreCustomRelation *dest, ObjectModifier* mod = NULL) { // [TODO] XSD relationIdentifier is identifierType, KLV identifier is a UMID, how do we resolve? SIMPLE_MAP_OPTIONAL(source, relation, dest, setrelationByName) SIMPLE_MAP_OPTIONAL(source, relationLink, dest, setrelationLink) SIMPLE_MAP_OPTIONAL(source, runningOrderNumber, dest, setrunningOrderNumber) SIMPLE_MAP_OPTIONAL(source, totalNumberOfGroupMembers, dest, settotalNumberOfGroupMembers) SIMPLE_MAP_OPTIONAL(source, orderedGroupFlag, dest, setorderedGroupFlag) SIMPLE_MAP_OPTIONAL(source, note, dest, setrelationNote) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setcustomRelationTypeGroup) NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, relationIdentifier, ebucoreIdentifier, mapIdentifier, dest, setrelationIdentifier) } #define MAP_TECHNICAL_ATTRIBUTE_FUNCTION(functionName, sourceType, destType, destProperty) \ void functionName(sourceType& source, destType *dest, ObjectModifier* mod) { \ dest->destProperty(source); \ MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, settechnicalAttributeTypeGroup) \ } MAP_TECHNICAL_ATTRIBUTE_FUNCTION(mapTechnicalAttributeString, String, ebucoreTechnicalAttributeString, settechnicalAttributeStringValue) MAP_TECHNICAL_ATTRIBUTE_FUNCTION(mapTechnicalAttributeInt8, Int8, ebucoreTechnicalAttributeInt8, settechnicalAttributeInt8Value) MAP_TECHNICAL_ATTRIBUTE_FUNCTION(mapTechnicalAttributeInt16, Int16, ebucoreTechnicalAttributeInt16, settechnicalAttributeInt16Value) MAP_TECHNICAL_ATTRIBUTE_FUNCTION(mapTechnicalAttributeInt32, Int32, ebucoreTechnicalAttributeInt32, settechnicalAttributeInt32Value) MAP_TECHNICAL_ATTRIBUTE_FUNCTION(mapTechnicalAttributeInt64, Int64, ebucoreTechnicalAttributeInt64, settechnicalAttributeInt64Value) MAP_TECHNICAL_ATTRIBUTE_FUNCTION(mapTechnicalAttributeUInt8, UInt8, ebucoreTechnicalAttributeUInt8, settechnicalAttributeUInt8Value) MAP_TECHNICAL_ATTRIBUTE_FUNCTION(mapTechnicalAttributeUInt16, UInt16, ebucoreTechnicalAttributeUInt16, settechnicalAttributeUInt16Value) MAP_TECHNICAL_ATTRIBUTE_FUNCTION(mapTechnicalAttributeUInt32, UInt32, ebucoreTechnicalAttributeUInt32, settechnicalAttributeUInt32Value) MAP_TECHNICAL_ATTRIBUTE_FUNCTION(mapTechnicalAttributeUInt64, UInt64, ebucoreTechnicalAttributeUInt64, settechnicalAttributeUInt64Value) MAP_TECHNICAL_ATTRIBUTE_FUNCTION(mapTechnicalAttributeFloat, Float, ebucoreTechnicalAttributeFloat, settechnicalAttributeFloatValue) MAP_TECHNICAL_ATTRIBUTE_FUNCTION(mapTechnicalAttributeAnyURI, technicalAttributeUriType, ebucoreTechnicalAttributeAnyURI, settechnicalAttributeAnyURIValue) MAP_TECHNICAL_ATTRIBUTE_FUNCTION(mapTechnicalAttributeBoolean, Boolean, ebucoreTechnicalAttributeBoolean, settechnicalAttributeBooleanValue) void mapTechnicalAttributeRational(technicalAttributeRationalType& source, ebucoreTechnicalAttributeRational *dest, ObjectModifier* mod) { mxfRational r = { source.factorNumerator(), source.factorDenominator() }; dest->settechnicalAttributeRationalValue(r); MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, settechnicalAttributeTypeGroup) } void mapMedium(medium& source, ebucoreMedium *dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, mediumId, dest, setmediumID) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setmediumTypeGroup) } void mapPackageInfo(formatType& source, ebucorePackageInfo *dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, fileName, dest, setpackageName) SIMPLE_MAP_OPTIONAL(source, fileSize, dest, setpackageSize) if (source.locator().size() > 0) { dest->setpackageLocator( source.locator()[0] ); } } void mapSigningFormat(signingFormat& source, ebucoreSigningFormat *dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, trackId, dest, setsigningTrackID) SIMPLE_MAP_OPTIONAL(source, trackName, dest, setsigningTrackName) SIMPLE_MAP_OPTIONAL(source, language, dest, setsigningTrackLanguageCode) SIMPLE_MAP_OPTIONAL(source, signingSourceUri, dest, setsigningSourceUri) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setsigningTypeGroup) MAP_NEW_FORMAT_GROUP_AND_ASSIGN(source, dest, setsigningFormatGroup) } void mapCodec(codecType& source, ebucoreCodec *dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, name, dest, setname) SIMPLE_MAP_OPTIONAL(source, vendor, dest, setvendor) SIMPLE_MAP_OPTIONAL(source, version, dest, setversion) SIMPLE_MAP_OPTIONAL(source, family, dest, setfamily) // [TODO] XSD Codec identifier is an identifiertype, KLV is string //SIMPLE_MAP_OPTIONAL(source, codecIdentifier, dest, setcodecIdentifier) } void mapAudioTrack(audioTrack& source, ebucoreTrack *dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, trackId, dest, settrackID) SIMPLE_MAP_OPTIONAL(source, trackName, dest, settrackName) SIMPLE_MAP_OPTIONAL(source, trackLanguage, dest, settrackLanguageCode) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, settrackTypeGroup) } void mapVideoTrack(videoTrack& source, ebucoreTrack *dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, trackId, dest, settrackID) SIMPLE_MAP_OPTIONAL(source, trackName, dest, settrackName) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, settrackTypeGroup) } void mapAudioFormat(audioFormatType& source, ebucoreAudioFormat *dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, audioFormatId, dest, setaudioFormatID) SIMPLE_MAP_OPTIONAL(source, audioFormatName, dest, setaudioFormatName) SIMPLE_MAP_OPTIONAL(source, audioFormatDefinition, dest, setaudioFormatDefinition) if (source.audioTrackConfiguration().present()) { MAP_NEW_TYPE_GROUP_AND_ASSIGN(source.audioTrackConfiguration().get(), dest, setaudioTrackConfiguration) } SIMPLE_MAP_OPTIONAL(source, sampleSize, dest, setaudioSamplingSize) SIMPLE_MAP_OPTIONAL(source, sampleType, dest, setaudioSamplingType) SIMPLE_MAP_OPTIONAL(source, channels, dest, setaudioTotalNumberOfChannels) SIMPLE_MAP_OPTIONAL(source, bitRate, dest, setaudioBitRate) SIMPLE_MAP_OPTIONAL(source, bitRateMax, dest, setaudioMaxBitRate) SIMPLE_MAP_OPTIONAL(source, bitRateMode, dest, setaudioBitRateMode) SIMPLE_MAP_OPTIONAL_CONVERT(source, samplingRate, dest, setaudioSamplingRate, convert) if (source.audioEncoding().present()) { MAP_NEW_TYPE_GROUP_AND_ASSIGN(source.audioEncoding().get(), dest, setaudioEncoding) } NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, codec, ebucoreCodec, mapCodec, dest, setaudioCodec) NEW_VECTOR_AND_ASSIGN(source, audioTrack, ebucoreTrack, audioFormatType::audioTrack_iterator, mapAudioTrack, dest, setaudioTrack) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeString, ebucoreTechnicalAttributeString, audioFormatType::technicalAttributeString_iterator, mapTechnicalAttributeString, dest, setaudioTechnicalAttributeString) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeByte, ebucoreTechnicalAttributeInt8, audioFormatType::technicalAttributeByte_iterator, mapTechnicalAttributeInt8, dest, setaudioTechnicalAttributeInt8) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeShort, ebucoreTechnicalAttributeInt16, audioFormatType::technicalAttributeShort_iterator, mapTechnicalAttributeInt16, dest, setaudioTechnicalAttributeInt16) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeInteger, ebucoreTechnicalAttributeInt32, audioFormatType::technicalAttributeInteger_iterator, mapTechnicalAttributeInt32, dest, setaudioTechnicalAttributeInt32) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeLong, ebucoreTechnicalAttributeInt64, audioFormatType::technicalAttributeLong_iterator, mapTechnicalAttributeInt64, dest, setaudioTechnicalAttributeInt64) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedByte, ebucoreTechnicalAttributeUInt8, audioFormatType::technicalAttributeUnsignedByte_iterator, mapTechnicalAttributeUInt8, dest, setaudioTechnicalAttributeUInt8) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedShort, ebucoreTechnicalAttributeUInt16, audioFormatType::technicalAttributeUnsignedShort_iterator, mapTechnicalAttributeUInt16, dest, setaudioTechnicalAttributeUInt16) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedInteger, ebucoreTechnicalAttributeUInt32, audioFormatType::technicalAttributeUnsignedInteger_iterator, mapTechnicalAttributeUInt32, dest, setaudioTechnicalAttributeUInt32) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedLong, ebucoreTechnicalAttributeUInt64, audioFormatType::technicalAttributeUnsignedLong_iterator, mapTechnicalAttributeUInt64, dest, setaudioTechnicalAttributeUInt64) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeFloat, ebucoreTechnicalAttributeFloat, audioFormatType::technicalAttributeFloat_iterator, mapTechnicalAttributeFloat, dest, setaudioTechnicalAttributeFloat) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeRational, ebucoreTechnicalAttributeRational, audioFormatType::technicalAttributeRational_iterator, mapTechnicalAttributeRational, dest, setaudioTechnicalAttributeRational) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUri, ebucoreTechnicalAttributeAnyURI, audioFormatType::technicalAttributeUri_iterator, mapTechnicalAttributeAnyURI, dest, setaudioTechnicalAttributeAnyURI) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeBoolean, ebucoreTechnicalAttributeBoolean, audioFormatType::technicalAttributeBoolean_iterator, mapTechnicalAttributeBoolean, dest, setaudioTechnicalAttributeBoolean) } void mapAspectRatio(aspectRatioType& source, ebucoreAspectRatio *dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_NO_GET(source, factorNumerator, dest, setaspectRatioFactorNumerator) SIMPLE_MAP_NO_GET(source, factorDenominator, dest, setaspectRatioFactorDenominator) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setaspectRatioTypeGroup) } void mapDimension(lengthType& source, ebucoreDimension *dest, ObjectModifier* mod = NULL) { dest->setdimensionValue(source); SIMPLE_MAP_OPTIONAL(source, unit, dest, setdimensionUnit) } void mapDimension(dimensionType& source, ebucoreDimension *dest, ObjectModifier* mod = NULL) { dest->setdimensionValue(source); SIMPLE_MAP_OPTIONAL(source, unit, dest, setdimensionUnit) } void mapWidth(width& source, ebucoreWidth *dest, ObjectModifier* mod = NULL) { ebucoreDimension *obj = newAndModifyObject<ebucoreDimension>(dest->getHeaderMetadata(), mod); mapDimension(source, obj, mod); MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setwidthTypeGroup) } void mapHeight(height& source, ebucoreHeight *dest, ObjectModifier* mod = NULL) { ebucoreDimension *obj = newAndModifyObject<ebucoreDimension>(dest->getHeaderMetadata(), mod); mapDimension(source, obj, mod); MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setheightTypeGroup) } void mapImageFormat(imageFormatType& source, ebucoreImageFormat *dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, imageFormatId, dest, setimageFormatID) SIMPLE_MAP_OPTIONAL(source, imageFormatName, dest, setimageFormatName) SIMPLE_MAP_OPTIONAL(source, imageFormatDefinition, dest, setimageFormatDefinition) SIMPLE_MAP_OPTIONAL(source, orientation, dest, setimageOrientation) NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, aspectRatio, ebucoreAspectRatio, mapAspectRatio, dest, setimageAspectRatio) if (source.imageEncoding().present()) { MAP_NEW_TYPE_GROUP_AND_ASSIGN(source.imageEncoding().get(), dest, setimageEncoding) } /* [TODO] XSD is missing image codec!! NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, codec, ebucoreCodec, mapCodec, dest, setimageCodec) */ NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, width, ebucoreDimension, mapDimension, dest, setimageWidth) NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, height, ebucoreDimension, mapDimension, dest, setimageHeight) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeString, ebucoreTechnicalAttributeString, imageFormatType::technicalAttributeString_iterator, mapTechnicalAttributeString, dest, setimageTechnicalAttributeString) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeByte, ebucoreTechnicalAttributeInt8, imageFormatType::technicalAttributeByte_iterator, mapTechnicalAttributeInt8, dest, setimageTechnicalAttributeInt8) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeShort, ebucoreTechnicalAttributeInt16, imageFormatType::technicalAttributeShort_iterator, mapTechnicalAttributeInt16, dest, setimageTechnicalAttributeInt16) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeInteger, ebucoreTechnicalAttributeInt32, imageFormatType::technicalAttributeInteger_iterator, mapTechnicalAttributeInt32, dest, setimageTechnicalAttributeInt32) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeLong, ebucoreTechnicalAttributeInt64, imageFormatType::technicalAttributeLong_iterator, mapTechnicalAttributeInt64, dest, setimageTechnicalAttributeInt64) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedByte, ebucoreTechnicalAttributeUInt8, imageFormatType::technicalAttributeUnsignedByte_iterator, mapTechnicalAttributeUInt8, dest, setimageTechnicalAttributeUInt8) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedShort, ebucoreTechnicalAttributeUInt16, imageFormatType::technicalAttributeUnsignedShort_iterator, mapTechnicalAttributeUInt16, dest, setimageTechnicalAttributeUInt16) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedInteger, ebucoreTechnicalAttributeUInt32, imageFormatType::technicalAttributeUnsignedInteger_iterator, mapTechnicalAttributeUInt32, dest, setimageTechnicalAttributeUInt32) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedLong, ebucoreTechnicalAttributeUInt64, imageFormatType::technicalAttributeUnsignedLong_iterator, mapTechnicalAttributeUInt64, dest, setimageTechnicalAttributeUInt64) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeFloat, ebucoreTechnicalAttributeFloat, imageFormatType::technicalAttributeFloat_iterator, mapTechnicalAttributeFloat, dest, setimageTechnicalAttributeFloat) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeRational, ebucoreTechnicalAttributeRational, imageFormatType::technicalAttributeRational_iterator, mapTechnicalAttributeRational, dest, setimageTechnicalAttributeRational) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUri, ebucoreTechnicalAttributeAnyURI, imageFormatType::technicalAttributeUri_iterator, mapTechnicalAttributeAnyURI, dest, setimageTechnicalAttributeAnyURI) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeBoolean, ebucoreTechnicalAttributeBoolean, imageFormatType::technicalAttributeBoolean_iterator, mapTechnicalAttributeBoolean, dest, setimageTechnicalAttributeBoolean) } void mapVideoFormat(videoFormatType& source, ebucoreVideoFormat *dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, videoFormatId, dest, setvideoFormatID) SIMPLE_MAP_OPTIONAL(source, videoFormatName, dest, setvideoFormatName) SIMPLE_MAP_OPTIONAL(source, videoFormatDefinition, dest, setvideoFormatDefinition) SIMPLE_MAP_OPTIONAL(source, bitRate, dest, setvideoBitRate) SIMPLE_MAP_OPTIONAL(source, bitRateMax, dest, setvideoMaxBitRate) SIMPLE_MAP_OPTIONAL(source, bitRateMode, dest, setvideoBitRateMode) SIMPLE_MAP_OPTIONAL(source, scanningFormat, dest, setvideoSamplingFormat) SIMPLE_MAP_OPTIONAL(source, scanningOrder, dest, setvideoScanningOrder) SIMPLE_MAP_OPTIONAL(source, lines, dest, setvideoActiveLines) SIMPLE_MAP_OPTIONAL(source, noiseFilter, dest, setvideoNoiseFilterFlag) SIMPLE_MAP_OPTIONAL(source, flag_3D, dest, setvideo3DFlag) NEW_VECTOR_AND_ASSIGN(source, aspectRatio, ebucoreAspectRatio, videoFormatType::aspectRatio_iterator, mapAspectRatio, dest, setvideoAspectRatio) SIMPLE_MAP_OPTIONAL_CONVERT(source, frameRate, dest, setvideoFrameRate, convert) if (source.width().size() > 0) { NEW_OBJECT_AND_ASSIGN_DIRECT(source.width()[0], ebucoreWidth, mapWidth, dest, setvideoWidth) } if (source.height().size() > 0) { NEW_OBJECT_AND_ASSIGN_DIRECT(source.height()[0], ebucoreHeight, mapHeight, dest, setvideoHeight) } if (source.videoEncoding().present()) { MAP_NEW_TYPE_GROUP_AND_ASSIGN(source.videoEncoding().get(), dest, setvideoEncoding) } NEW_OBJECT_AND_ASSIGN_OPTIONAL(source, codec, ebucoreCodec, mapCodec, dest, setvideoCodec) NEW_VECTOR_AND_ASSIGN(source, videoTrack, ebucoreTrack, videoFormatType::videoTrack_iterator, mapVideoTrack, dest, setvideoTrack) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeString, ebucoreTechnicalAttributeString, videoFormatType::technicalAttributeString_iterator, mapTechnicalAttributeString, dest, setvideoTechnicalAttributeString) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeByte, ebucoreTechnicalAttributeInt8, videoFormatType::technicalAttributeByte_iterator, mapTechnicalAttributeInt8, dest, setvideoTechnicalAttributeInt8) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeShort, ebucoreTechnicalAttributeInt16, videoFormatType::technicalAttributeShort_iterator, mapTechnicalAttributeInt16, dest, setvideoTechnicalAttributeInt16) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeInteger, ebucoreTechnicalAttributeInt32, videoFormatType::technicalAttributeInteger_iterator, mapTechnicalAttributeInt32, dest, setvideoTechnicalAttributeInt32) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeLong, ebucoreTechnicalAttributeInt64, videoFormatType::technicalAttributeLong_iterator, mapTechnicalAttributeInt64, dest, setvideoTechnicalAttributeInt64) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedByte, ebucoreTechnicalAttributeUInt8, videoFormatType::technicalAttributeUnsignedByte_iterator, mapTechnicalAttributeUInt8, dest, setvideoTechnicalAttributeUInt8) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedShort, ebucoreTechnicalAttributeUInt16, videoFormatType::technicalAttributeUnsignedShort_iterator, mapTechnicalAttributeUInt16, dest, setvideoTechnicalAttributeUInt16) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedInteger, ebucoreTechnicalAttributeUInt32, videoFormatType::technicalAttributeUnsignedInteger_iterator, mapTechnicalAttributeUInt32, dest, setvideoTechnicalAttributeUInt32) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedLong, ebucoreTechnicalAttributeUInt64, videoFormatType::technicalAttributeUnsignedLong_iterator, mapTechnicalAttributeUInt64, dest, setvideoTechnicalAttributeUInt64) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeFloat, ebucoreTechnicalAttributeFloat, videoFormatType::technicalAttributeFloat_iterator, mapTechnicalAttributeFloat, dest, setvideoTechnicalAttributeFloat) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeRational, ebucoreTechnicalAttributeRational, videoFormatType::technicalAttributeRational_iterator, mapTechnicalAttributeRational, dest, setvideoTechnicalAttributeRational) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUri, ebucoreTechnicalAttributeAnyURI, videoFormatType::technicalAttributeUri_iterator, mapTechnicalAttributeAnyURI, dest, setvideoTechnicalAttributeAnyURI) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeBoolean, ebucoreTechnicalAttributeBoolean, videoFormatType::technicalAttributeBoolean_iterator, mapTechnicalAttributeBoolean, dest, setvideoTechnicalAttributeBoolean) } void mapCaptioning(captioningFormat& source, ebucoreCaptioning* dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, captioningFormatId, dest, setcaptioningFormatID) SIMPLE_MAP_OPTIONAL(source, captioningFormatName, dest, setcaptioningFormatName) SIMPLE_MAP_OPTIONAL(source, captioningSourceUri, dest, setcaptioningSourceUri) SIMPLE_MAP_OPTIONAL(source, trackId, dest, setcaptioningTrackID) SIMPLE_MAP_OPTIONAL(source, trackName, dest, setcaptioningTrackName) SIMPLE_MAP_OPTIONAL(source, language, dest, setcaptioningLanguageCode) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setcaptioningTypeGroup) MAP_NEW_FORMAT_GROUP_AND_ASSIGN(source, dest, setcaptioningFormatGroup) } void mapSubtitling(subtitlingFormat& source, ebucoreSubtitling* dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, subtitlingFormatId, dest, setsubtitlingFormatID) SIMPLE_MAP_OPTIONAL(source, subtitlingFormatName, dest, setsubtitlingFormatName) SIMPLE_MAP_OPTIONAL(source, subtitlingSourceUri, dest, setsubtitlingSourceUri) SIMPLE_MAP_OPTIONAL(source, trackId, dest, setsubtitlingTrackID) SIMPLE_MAP_OPTIONAL(source, trackName, dest, setsubtitlingTrackName) SIMPLE_MAP_OPTIONAL(source, language, dest, setsubtitlingLanguageCode) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setsubtitlingTypeGroup) MAP_NEW_FORMAT_GROUP_AND_ASSIGN(source, dest, setsubtitlingFormatGroup) } void mapSigning(signingFormat& source, ebucoreSigningFormat* dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, signingFormatId, dest, setsigningFormatID) SIMPLE_MAP_OPTIONAL(source, signingFormatName, dest, setsigningFormatName) SIMPLE_MAP_OPTIONAL(source, signingSourceUri, dest, setsigningSourceUri) SIMPLE_MAP_OPTIONAL(source, trackId, dest, setsigningTrackID) SIMPLE_MAP_OPTIONAL(source, trackName, dest, setsigningTrackName) SIMPLE_MAP_OPTIONAL(source, language, dest, setsigningTrackLanguageCode) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setsigningTypeGroup) MAP_NEW_FORMAT_GROUP_AND_ASSIGN(source, dest, setsigningFormatGroup) } void mapAncillaryData(ancillaryDataFormat& source, ebucoreAncillaryData* dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, DID, dest, setDID) SIMPLE_MAP_OPTIONAL(source, SDID, dest, setSDID) std::vector<uint32_t> vec_lines; for (ancillaryDataFormat::lineNumber_const_iterator it = source.lineNumber().begin(); it != source.lineNumber().end(); it++) { vec_lines.push_back(*it); } dest->setlineNumber(vec_lines); ebucoreTypeGroup *obj = newAndModifyObject<ebucoreTypeGroup>(dest->getHeaderMetadata(), mod); // source is only an integer to map from, lets be creative SIMPLE_MAP_OPTIONAL(source, ancillaryDataFormatName, obj, settypeGroupLabel) SIMPLE_MAP_OPTIONAL(source, ancillaryDataFormatId, obj, settypeGroupLink) SIMPLE_MAP_OPTIONAL_CONVERT(source, wrappingType, obj, settypeGroupDefinition, convert_to_string) } void mapDataFormat(dataFormatType& source, ebucoreDataFormat *dest, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, dataFormatId, dest, setdataFormatID) SIMPLE_MAP_OPTIONAL(source, dataFormatVersionId, dest, setdataFormatVersionID) SIMPLE_MAP_OPTIONAL(source, dataFormatName, dest, setdataFormatName) SIMPLE_MAP_OPTIONAL(source, dataFormatDefinition, dest, setdataFormatDefinition) SIMPLE_MAP_OPTIONAL(source, dataTrackId, dest, setdataTrackId) SIMPLE_MAP_OPTIONAL(source, dataTrackName, dest, setdataTrackName) SIMPLE_MAP_OPTIONAL(source, dataTrackLanguage, dest, setdataTrackLanguageCode) NEW_VECTOR_AND_ASSIGN(source, captioningFormat, ebucoreCaptioning, dataFormatType::captioningFormat_iterator, mapCaptioning, dest, setcaptioning) NEW_VECTOR_AND_ASSIGN(source, subtitlingFormat, ebucoreSubtitling, dataFormatType::subtitlingFormat_iterator, mapSubtitling, dest, setsubtitling) NEW_VECTOR_AND_ASSIGN(source, ancillaryDataFormat, ebucoreAncillaryData, dataFormatType::ancillaryDataFormat_iterator, mapAncillaryData, dest, setancillaryData) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeString, ebucoreTechnicalAttributeString, dataFormatType::technicalAttributeString_iterator, mapTechnicalAttributeString, dest, setdataTechnicalAttributeString) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeByte, ebucoreTechnicalAttributeInt8, dataFormatType::technicalAttributeByte_iterator, mapTechnicalAttributeInt8, dest, setdataTechnicalAttributeInt8) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeShort, ebucoreTechnicalAttributeInt16, dataFormatType::technicalAttributeShort_iterator, mapTechnicalAttributeInt16, dest, setdataTechnicalAttributeInt16) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeInteger, ebucoreTechnicalAttributeInt32, dataFormatType::technicalAttributeInteger_iterator, mapTechnicalAttributeInt32, dest, setdataTechnicalAttributeInt32) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeLong, ebucoreTechnicalAttributeInt64, dataFormatType::technicalAttributeLong_iterator, mapTechnicalAttributeInt64, dest, setdataTechnicalAttributeInt64) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedByte, ebucoreTechnicalAttributeUInt8, dataFormatType::technicalAttributeUnsignedByte_iterator, mapTechnicalAttributeUInt8, dest, setdataTechnicalAttributeUInt8) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedShort, ebucoreTechnicalAttributeUInt16, dataFormatType::technicalAttributeUnsignedShort_iterator, mapTechnicalAttributeUInt16, dest, setdataTechnicalAttributeUInt16) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedInteger, ebucoreTechnicalAttributeUInt32, dataFormatType::technicalAttributeUnsignedInteger_iterator, mapTechnicalAttributeUInt32, dest, setdataTechnicalAttributeUInt32) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedLong, ebucoreTechnicalAttributeUInt64, dataFormatType::technicalAttributeUnsignedLong_iterator, mapTechnicalAttributeUInt64, dest, setdataTechnicalAttributeUInt64) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeFloat, ebucoreTechnicalAttributeFloat, dataFormatType::technicalAttributeFloat_iterator, mapTechnicalAttributeFloat, dest, setdataTechnicalAttributeFloat) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeRational, ebucoreTechnicalAttributeRational, dataFormatType::technicalAttributeRational_iterator, mapTechnicalAttributeRational, dest, setdataTechnicalAttributeRational) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUri, ebucoreTechnicalAttributeAnyURI, dataFormatType::technicalAttributeUri_iterator, mapTechnicalAttributeAnyURI, dest, setdataTechnicalAttributeAnyURI) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeBoolean, ebucoreTechnicalAttributeBoolean, dataFormatType::technicalAttributeBoolean_iterator, mapTechnicalAttributeBoolean, dest, setdataTechnicalAttributeBoolean) } void mapFormat(formatType& source, ebucoreFormat *dest, std::map<xml_schema::id, ebucoreFormat*>& formatMap, ObjectModifier* mod = NULL) { SIMPLE_MAP_OPTIONAL(source, formatId, dest, setformatID) SIMPLE_MAP_OPTIONAL(source, formatVersionId, dest, setformatVersionID) SIMPLE_MAP_OPTIONAL(source, formatName, dest, setformatName) SIMPLE_MAP_OPTIONAL(source, formatDefinition, dest, setformatDefinition) if (source.dateCreated().present()) { SIMPLE_MAP_OPTIONAL_CONVERT(source, dateCreated().get().startYear, dest, setformatYearCreated, convert_timestamp) SIMPLE_MAP_OPTIONAL_CONVERT(source, dateCreated().get().startDate, dest, setformatDateCreated, convert_timestamp) } if (source.duration().present()) { // [NOTE] Mapped playtime as duration because we need a numeric value (rational) # of seconds. // [NOTE] We just map the timecode as a string to the KLV representation SIMPLE_MAP_OPTIONAL(source, duration().get().editUnitNumber, dest, setoverallDurationEditUnit) SIMPLE_MAP_OPTIONAL(source, duration().get().timecode, dest, setoverallDurationTimecode) SIMPLE_MAP_OPTIONAL_CONVERT(source, duration().get().normalPlayTime, dest, setoverallDurationTime, convert_rational) } if (source.containerFormat().size() > 0) { MAP_NEW_FORMAT_GROUP_AND_ASSIGN(source.containerFormat()[0], dest, setcontainerFormat) } if (source.medium().size() > 0) { NEW_OBJECT_AND_ASSIGN_DIRECT(source.medium()[0], ebucoreMedium, mapMedium, dest, setmedium) } ebucorePackageInfo *obj = newAndModifyObject<ebucorePackageInfo>(dest->getHeaderMetadata(), mod); mapPackageInfo(source, obj, mod); dest->setpackageInfo(obj); if (source.mimeType().size() > 0) { MAP_NEW_TYPE_GROUP_AND_ASSIGN(source.mimeType()[0], dest, setmimeType) } NEW_VECTOR_AND_ASSIGN(source, audioFormat, ebucoreAudioFormat, formatType::audioFormat_iterator, mapAudioFormat, dest, setmaterialAudioFormat) NEW_VECTOR_AND_ASSIGN(source, videoFormat, ebucoreVideoFormat, formatType::videoFormat_iterator, mapVideoFormat, dest, setmaterialVideoFormat) NEW_VECTOR_AND_ASSIGN(source, imageFormat, ebucoreImageFormat, formatType::imageFormat_iterator, mapImageFormat, dest, setmaterialImageFormat) NEW_VECTOR_AND_ASSIGN(source, dataFormat, ebucoreDataFormat, formatType::dataFormat_iterator, mapDataFormat, dest, setmaterialDataFormat) NEW_VECTOR_AND_ASSIGN(source, signingFormat, ebucoreSigningFormat, formatType::signingFormat_iterator, mapSigningFormat, dest, setmaterialSigningFormat) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeString, ebucoreTechnicalAttributeString, formatType::technicalAttributeString_iterator, mapTechnicalAttributeString, dest, setmaterialTechnicalAttributeString) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeByte, ebucoreTechnicalAttributeInt8, formatType::technicalAttributeByte_iterator, mapTechnicalAttributeInt8, dest, setmaterialTechnicalAttributeInt8) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeShort, ebucoreTechnicalAttributeInt16, formatType::technicalAttributeShort_iterator, mapTechnicalAttributeInt16, dest, setmaterialTechnicalAttributeInt16) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeInteger, ebucoreTechnicalAttributeInt32, formatType::technicalAttributeInteger_iterator, mapTechnicalAttributeInt32, dest, setmaterialTechnicalAttributeInt32) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeLong, ebucoreTechnicalAttributeInt64, formatType::technicalAttributeLong_iterator, mapTechnicalAttributeInt64, dest, setmaterialTechnicalAttributeInt64) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedByte, ebucoreTechnicalAttributeUInt8, formatType::technicalAttributeUnsignedByte_iterator, mapTechnicalAttributeUInt8, dest, setmaterialTechnicalAttributeUInt8) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedShort, ebucoreTechnicalAttributeUInt16, formatType::technicalAttributeUnsignedShort_iterator, mapTechnicalAttributeUInt16, dest, setmaterialTechnicalAttributeUInt16) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedInteger, ebucoreTechnicalAttributeUInt32, formatType::technicalAttributeUnsignedInteger_iterator, mapTechnicalAttributeUInt32, dest, setmaterialTechnicalAttributeUInt32) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUnsignedLong, ebucoreTechnicalAttributeUInt64, formatType::technicalAttributeUnsignedLong_iterator, mapTechnicalAttributeUInt64, dest, setmaterialTechnicalAttributeUInt64) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeFloat, ebucoreTechnicalAttributeFloat, formatType::technicalAttributeFloat_iterator, mapTechnicalAttributeFloat, dest, setmaterialTechnicalAttributeFloat) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeRational, ebucoreTechnicalAttributeRational, formatType::technicalAttributeRational_iterator, mapTechnicalAttributeRational, dest, setmaterialTechnicalAttributeRational) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeUri, ebucoreTechnicalAttributeAnyURI, formatType::technicalAttributeUri_iterator, mapTechnicalAttributeAnyURI, dest, setmaterialTechnicalAttributeAnyURI) NEW_VECTOR_AND_ASSIGN(source, technicalAttributeBoolean, ebucoreTechnicalAttributeBoolean, formatType::technicalAttributeBoolean_iterator, mapTechnicalAttributeBoolean, dest, setmaterialTechnicalAttributeBoolean) // add this format element to the list if (source.formatId().present()) { formatMap[source.formatId().get()] = dest; } } void mapPart(partType& source, ebucorePartMetadata *dest, mxfRational overallFrameRate, std::vector<ebucorePartMetadata*>& timelineParts, ObjectModifier* mod) { SIMPLE_MAP_OPTIONAL(source, partId, dest, setpartId) SIMPLE_MAP_OPTIONAL(source, partName, dest, setpartName) SIMPLE_MAP_OPTIONAL(source, partDefinition, dest, setpartDefinition) MAP_NEW_TYPE_GROUP_AND_ASSIGN(source, dest, setpartTypeGroup) if (source.partStartTime().present()) { timeType& start = source.partStartTime().get(); SIMPLE_MAP_OPTIONAL(start, editUnitNumber, dest, setpartStartEditUnitNumber) SIMPLE_MAP_OPTIONAL(start, timecode, dest, setpartStartTimecode) SIMPLE_MAP_OPTIONAL_CONVERT(start, normalPlayTime, dest, setpartStartTime, convert_rational) } if (source.partDuration().present()) { durationType& dur = source.partDuration().get(); // [NOTE] Mapped playtime as duration because we need a numeric value (rational) # of seconds. // [NOTE] We just map the timecode as a string to the KLV representation SIMPLE_MAP_OPTIONAL(dur, editUnitNumber, dest, setpartDurationEditUnitNumber) SIMPLE_MAP_OPTIONAL(dur, timecode, dest, setpartDurationTimecode) SIMPLE_MAP_OPTIONAL_CONVERT(dur, normalPlayTime, dest, setpartDurationTime, convert_rational) } // map ourselves (we are an extension of the coreMetadataType) onto a new ebucoreCoreMetadata object ebucoreCoreMetadata *obj = newAndModifyObject<ebucoreCoreMetadata>(dest->getHeaderMetadata(), mod); mapCoreMetadata(source, obj, overallFrameRate, timelineParts, mod); dest->setpartMeta(obj); } void mapCoreMetadata(coreMetadataType& source, ebucoreCoreMetadata *dest, mxfRational overallFrameRate, std::vector<ebucorePartMetadata*>& timelineParts, ObjectModifier* mod) { std::map<xml_schema::id, ebucoreFormat*> formatMap; std::map<xml_schema::id, ebucoreRights*> rightsMap; NEW_VECTOR_AND_ASSIGN(source, title, ebucoreTitle, coreMetadataType::title_iterator, mapTitle, dest, settitle) NEW_VECTOR_AND_ASSIGN(source, alternativeTitle, ebucoreAlternativeTitle, coreMetadataType::alternativeTitle_iterator, mapAlternativeTitle, dest, setalternativeTitle) NEW_VECTOR_AND_ASSIGN(source, creator, ebucoreEntity, coreMetadataType::creator_iterator, mapEntity, dest, setcreator) NEW_VECTOR_AND_ASSIGN(source, subject, ebucoreSubject, coreMetadataType::subject_iterator, mapSubject, dest, setsubject) NEW_VECTOR_AND_ASSIGN(source, description, ebucoreDescription, coreMetadataType::description_iterator, mapDescription, dest, setdescription) NEW_VECTOR_AND_ASSIGN(source, publisher, ebucoreEntity, coreMetadataType::publisher_iterator, mapEntity, dest, setpublisher) NEW_VECTOR_AND_ASSIGN(source, contributor, ebucoreEntity, coreMetadataType::contributor_iterator, mapEntity, dest, setcontributor) NEW_VECTOR_AND_ASSIGN(source, date, ebucoreDate, coreMetadataType::date_iterator, mapDate, dest, setdate) NEW_VECTOR_AND_ASSIGN(source, type, ebucoreType, coreMetadataType::type_iterator, mapType, dest, settype) NEW_VECTOR_AND_ASSIGN(source, identifier, ebucoreIdentifier, coreMetadataType::identifier_iterator, mapIdentifier, dest, setidentifier) NEW_VECTOR_AND_ASSIGN(source, language, ebucoreLanguage, coreMetadataType::language_iterator, mapLanguage, dest, setlanguage) NEW_VECTOR_AND_ASSIGN(source, coverage, ebucoreCoverage, coreMetadataType::coverage_iterator, mapMetadataCoverage, dest, setcoverage) // do formats before rights and publicationhistory to make sure references are available in the map std::vector<ebucoreFormat*> vec_dest_fmt; for (coreMetadataType::format_iterator it = source.format().begin(); it != source.format().end(); it++) { ebucoreFormat *obj = newAndModifyObject<ebucoreFormat>(dest->getHeaderMetadata(), mod); mapFormat(*it, obj, formatMap, mod); vec_dest_fmt.push_back(obj); } dest->setformat(vec_dest_fmt); //NEW_VECTOR_AND_ASSIGN(source, format, ebucoreFormat, coreMetadataType::format_iterator, mapFormat, dest, setformat) std::vector<ebucoreRights*> vec_dest_rights; for (coreMetadataType::rights_iterator it = source.rights().begin(); it != source.rights().end(); it++) { ebucoreRights *obj = newAndModifyObject<ebucoreRights>(dest->getHeaderMetadata(), mod); mapRights(*it, obj, formatMap, rightsMap, mod); vec_dest_rights.push_back(obj); } dest->setrights(vec_dest_rights); //NEW_VECTOR_AND_ASSIGN(source, rights, ebucoreRights, coreMetadataType::rights_iterator, mapRights, dest, setrights) NEW_VECTOR_AND_ASSIGN(source, rating, ebucoreRating, coreMetadataType::rating_iterator, mapRating, dest, setrating) if (source.version().size() > 0) { NEW_OBJECT_AND_ASSIGN_DIRECT(source.version()[0], ebucoreVersion, mapVersion, dest, setversion) } if (source.publicationHistory().present()) { ebucorePublicationHistory *obj = newAndModifyObject<ebucorePublicationHistory>(dest->getHeaderMetadata(), mod); mapPublicationHistory(source.publicationHistory().get(), obj, dest->getHeaderMetadata(), formatMap, rightsMap, mod); dest->setpublicationHistory(obj); } mapBasicRelations(source, dest, mod); NEW_VECTOR_AND_ASSIGN(source, relation, ebucoreCustomRelation, coreMetadataType::relation_iterator, mapCustomRelation, dest, setcustomRelation) std::vector<ebucorePartMetadata*> vec_parts; for (coreMetadataType::part_iterator it = source.part().begin(); it != source.part().end(); it++) { ebucorePartMetadata *obj = newAndModifyObject<ebucorePartMetadata>(dest->getHeaderMetadata(), mod); mapPart(*it, obj, overallFrameRate, timelineParts, mod); vec_parts.push_back(obj); // set extremes to start with mxfPosition partStart = -1; mxfLength partDuration = -1; // determine which of our parts belong on a timeline partType& part = *it; if (part.partStartTime().present() && part.partDuration().present()) { timeType &start = part.partStartTime().get(); // sensible values are present! mxfPosition formatStart; mxfLength formatDuration; if (start.editUnitNumber().present()) { partStart = start.editUnitNumber().get(); } else if (start.normalPlayTime().present()) { // convert a duration mxfRational d = convert_rational(start.normalPlayTime().get()); partStart = (d.numerator * overallFrameRate.numerator) / (d.denominator * overallFrameRate.denominator); } else { // convert a time code bmx::Timecode tc; bmx::parse_timecode(start.timecode().get().c_str(), overallFrameRate, &tc); partStart = tc.GetOffset(); } formatType::duration_type &dur = part.partDuration().get(); if (dur.editUnitNumber().present()) { partDuration = dur.editUnitNumber().get(); } else if (dur.normalPlayTime().present()) { // convert a duration mxfRational d = convert_rational(dur.normalPlayTime().get()); partDuration = (d.numerator * overallFrameRate.numerator) / (d.denominator * overallFrameRate.denominator); } else { // convert a time code bmx::Timecode tc; bmx::parse_timecode(dur.timecode().get().c_str(), overallFrameRate, &tc); partDuration = tc.GetOffset(); } if (partStart != -1 && partDuration != -1) { // this goes onto the timeline! obj->setpartStartEditUnitNumber(partStart); obj->setpartDurationEditUnitNumber(partDuration); timelineParts.push_back(obj); } } } dest->setpart(vec_parts); } } // namespace EBUCore_1_4 } // namespace EBUCore } // namespace EBUSDK
56.712727
192
0.812054
Limecraft
7cc8140fb18d6f0563cbe2c37353ade3e04c7ede
3,266
hpp
C++
cpp/include/cugraph/visitors/ret_terased.hpp
BradReesWork/cugraph
9ddea03a724e9b32950ed6282120007c76482cbc
[ "Apache-2.0" ]
991
2018-12-05T22:07:52.000Z
2022-03-31T10:45:45.000Z
cpp/include/cugraph/visitors/ret_terased.hpp
BradReesWork/cugraph
9ddea03a724e9b32950ed6282120007c76482cbc
[ "Apache-2.0" ]
1,929
2018-12-06T14:06:18.000Z
2022-03-31T20:01:00.000Z
cpp/include/cugraph/visitors/ret_terased.hpp
BradReesWork/cugraph
9ddea03a724e9b32950ed6282120007c76482cbc
[ "Apache-2.0" ]
227
2018-12-06T18:10:15.000Z
2022-03-28T19:03:15.000Z
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Andrei Schaffer, aschaffer@nvidia.com // #pragma once #include <memory> #include <stdexcept> #include <type_traits> namespace cugraph { namespace visitors { struct return_t { struct base_return_t { virtual ~base_return_t(void) {} virtual void copy(return_t&&) = 0; virtual std::unique_ptr<base_return_t> clone(void) const = 0; }; template <typename T> struct generic_return_t : base_return_t { generic_return_t(T const& t) : return_(t) {} generic_return_t(T&& t) : return_(std::move(t)) {} void copy(return_t&& r) override { if constexpr (std::is_copy_constructible_v<T>) { base_return_t const* p_B = static_cast<base_return_t const*>(r.p_impl_.get()); return_ = *(dynamic_cast<T const*>(p_B)); } else { base_return_t* p_B = static_cast<base_return_t*>(r.p_impl_.get()); return_ = std::move(*(dynamic_cast<T*>(p_B))); } } std::unique_ptr<base_return_t> clone(void) const override { if constexpr (std::is_copy_constructible_v<T>) return std::make_unique<generic_return_t<T>>(return_); else throw std::runtime_error("ERROR: cannot clone object that is not copy constructible."); } T const& get(void) const { return return_; } private: T return_; }; return_t(void) = default; template <typename T> return_t(T const& t) : p_impl_(std::make_unique<generic_return_t<T>>(t)) { } template <typename T> return_t(T&& t) : p_impl_(std::make_unique<generic_return_t<T>>(std::move(t))) { } return_t(return_t const& r) : p_impl_{r.clone()} {} return_t& operator=(return_t const& r) { p_impl_ = r.clone(); return *this; } return_t(return_t&& other) : p_impl_(std::move(other.p_impl_)) {} return_t& operator=(return_t&& other) { p_impl_ = std::move(other.p_impl_); return *this; } std::unique_ptr<base_return_t> clone(void) const { if (p_impl_) return p_impl_->clone(); else return nullptr; } template <typename T> T const& get(void) const { if (p_impl_) { generic_return_t<T> const* p = static_cast<generic_return_t<T> const*>(p_impl_.get()); return p->get(); } else throw std::runtime_error("ERROR: nullptr impl."); } void const* get_ptr(void) const { if (p_impl_) return static_cast<void const*>(p_impl_.get()); else return nullptr; } void* release(void) { return static_cast<void*>(p_impl_.release()); } private: std::unique_ptr<base_return_t> p_impl_; }; } // namespace visitors } // namespace cugraph
25.515625
95
0.6485
BradReesWork
7cc881ca9d8eb9c7830f50428c601664cc8ab31e
945
cpp
C++
src/1114/1114-Print-In-Order-UnitTest.cpp
coldnew/leetcode-solutions
3bc7943f8341397840ecd34aefc5af6e52b09b4e
[ "Unlicense" ]
2
2022-03-10T17:06:18.000Z
2022-03-11T08:52:00.000Z
src/1114/1114-Print-In-Order-UnitTest.cpp
coldnew/leetcode-solutions
3bc7943f8341397840ecd34aefc5af6e52b09b4e
[ "Unlicense" ]
null
null
null
src/1114/1114-Print-In-Order-UnitTest.cpp
coldnew/leetcode-solutions
3bc7943f8341397840ecd34aefc5af6e52b09b4e
[ "Unlicense" ]
null
null
null
#include <gtest/gtest.h> #include <thread> #include "1114-Print-In-Order.cpp" TEST(PrintInOrderTest, Foo) { { testing::internal::CaptureStdout(); Foo foo; std::thread t1([&foo]() { foo.first([]() { std::cout << "first"; }); }); std::thread t2([&foo]() { foo.second([]() { std::cout << "second"; }); }); std::thread t3([&foo]() { foo.third([]() { std::cout << "third"; }); }); t1.join(); t2.join(); t3.join(); EXPECT_EQ("firstsecondthird", testing::internal::GetCapturedStdout()); } { testing::internal::CaptureStdout(); Foo foo; std::thread t3([&foo]() { foo.third([]() { std::cout << "third"; }); }); std::thread t2([&foo]() { foo.second([]() { std::cout << "second"; }); }); std::thread t1([&foo]() { foo.first([]() { std::cout << "first"; }); }); t3.join(); t2.join(); t1.join(); EXPECT_EQ("firstsecondthird", testing::internal::GetCapturedStdout()); } }
27
78
0.53545
coldnew
7cc999ec9ec8ff3cbd566a4119fc6e0615d39717
29,791
cpp
C++
artifact/storm/src/storm-pomdp-cli/storm-pomdp.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm-pomdp-cli/storm-pomdp.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm-pomdp-cli/storm-pomdp.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
1
2022-02-05T12:39:53.000Z
2022-02-05T12:39:53.000Z
#include "storm/utility/initialize.h" #include "storm/settings/modules/GeneralSettings.h" #include "storm/settings/modules/DebugSettings.h" #include "storm-pomdp-cli/settings/modules/POMDPSettings.h" #include "storm-pomdp-cli/settings/modules/QualitativePOMDPAnalysisSettings.h" #include "storm-pomdp-cli/settings/modules/BeliefExplorationSettings.h" #include "storm-pomdp-cli/settings/modules/ToParametricSettings.h" #include "storm-pomdp-cli/settings/PomdpSettings.h" #include "storm/analysis/GraphConditions.h" #include "storm-cli-utilities/cli.h" #include "storm-cli-utilities/model-handling.h" #include "storm-pomdp/transformer/KnownProbabilityTransformer.h" #include "storm-pomdp/transformer/ApplyFiniteSchedulerToPomdp.h" #include "storm-pomdp/transformer/GlobalPOMDPSelfLoopEliminator.h" #include "storm-pomdp/transformer/GlobalPomdpMecChoiceEliminator.h" #include "storm-pomdp/transformer/PomdpMemoryUnfolder.h" #include "storm-pomdp/transformer/BinaryPomdpTransformer.h" #include "storm-pomdp/transformer/MakePOMDPCanonic.h" #include "storm-pomdp/analysis/UniqueObservationStates.h" #include "storm-pomdp/analysis/QualitativeAnalysisOnGraphs.h" #include "storm-pomdp/modelchecker/BeliefExplorationPomdpModelChecker.h" #include "storm-pomdp/analysis/FormulaInformation.h" #include "storm-pomdp/analysis/IterativePolicySearch.h" #include "storm-pomdp/analysis/OneShotPolicySearch.h" #include "storm/api/storm.h" #include "storm/modelchecker/results/ExplicitQuantitativeCheckResult.h" #include "storm/modelchecker/results/ExplicitQualitativeCheckResult.h" #include "storm/utility/NumberTraits.h" #include "storm/utility/Stopwatch.h" #include "storm/utility/SignalHandler.h" #include "storm/exceptions/UnexpectedException.h" #include "storm/exceptions/NotSupportedException.h" #include <typeinfo> namespace storm { namespace pomdp { namespace cli { /// Perform preprocessings based on the graph structure (if requested or necessary). Return true, if some preprocessing has been done template<typename ValueType, storm::dd::DdType DdType> bool performPreprocessing(std::shared_ptr<storm::models::sparse::Pomdp<ValueType>>& pomdp, storm::pomdp::analysis::FormulaInformation& formulaInfo, storm::logic::Formula const& formula) { auto const& pomdpSettings = storm::settings::getModule<storm::settings::modules::POMDPSettings>(); bool preprocessingPerformed = false; if (pomdpSettings.isSelfloopReductionSet()) { storm::transformer::GlobalPOMDPSelfLoopEliminator<ValueType> selfLoopEliminator(*pomdp); if (selfLoopEliminator.preservesFormula(formula)) { STORM_PRINT_AND_LOG("Eliminating self-loop choices ..."); uint64_t oldChoiceCount = pomdp->getNumberOfChoices(); pomdp = selfLoopEliminator.transform(); STORM_PRINT_AND_LOG(oldChoiceCount - pomdp->getNumberOfChoices() << " choices eliminated through self-loop elimination." << std::endl); preprocessingPerformed = true; } else { STORM_PRINT_AND_LOG("Not eliminating self-loop choices as it does not preserve the formula." << std::endl); } } if (pomdpSettings.isQualitativeReductionSet() && formulaInfo.isNonNestedReachabilityProbability()) { storm::analysis::QualitativeAnalysisOnGraphs<ValueType> qualitativeAnalysis(*pomdp); STORM_PRINT_AND_LOG("Computing states with probability 0 ..."); storm::storage::BitVector prob0States = qualitativeAnalysis.analyseProb0(formula.asProbabilityOperatorFormula()); std::cout << prob0States << std::endl; STORM_PRINT_AND_LOG(" done. " << prob0States.getNumberOfSetBits() << " states found." << std::endl); STORM_PRINT_AND_LOG("Computing states with probability 1 ..."); storm::storage::BitVector prob1States = qualitativeAnalysis.analyseProb1(formula.asProbabilityOperatorFormula()); STORM_PRINT_AND_LOG(" done. " << prob1States.getNumberOfSetBits() << " states found." << std::endl); storm::pomdp::transformer::KnownProbabilityTransformer<ValueType> kpt = storm::pomdp::transformer::KnownProbabilityTransformer<ValueType>(); pomdp = kpt.transform(*pomdp, prob0States, prob1States); // Update formulaInfo to changes from Preprocessing formulaInfo.updateTargetStates(*pomdp, std::move(prob1States)); formulaInfo.updateSinkStates(*pomdp, std::move(prob0States)); preprocessingPerformed = true; } return preprocessingPerformed; } template<typename ValueType> void printResult(ValueType const& lowerBound, ValueType const& upperBound) { if (lowerBound == upperBound) { if (storm::utility::isInfinity(lowerBound)) { STORM_PRINT_AND_LOG("inf"); } else { STORM_PRINT_AND_LOG(lowerBound); } } else if (storm::utility::isInfinity<ValueType>(-lowerBound)) { if (storm::utility::isInfinity(upperBound)) { STORM_PRINT_AND_LOG("[-inf, inf] (width=inf)"); } else { // Only upper bound is known STORM_PRINT_AND_LOG("≤ " << upperBound); } } else if (storm::utility::isInfinity(upperBound)) { STORM_PRINT_AND_LOG("≥ " << lowerBound); } else { STORM_PRINT_AND_LOG("[" << lowerBound << ", " << upperBound << "] (width=" << ValueType(upperBound - lowerBound) << ")"); } if (storm::NumberTraits<ValueType>::IsExact) { STORM_PRINT_AND_LOG(" (approx. "); double roundedLowerBound = storm::utility::isInfinity<ValueType>(-lowerBound) ? -storm::utility::infinity<double>() : storm::utility::convertNumber<double>(lowerBound); double roundedUpperBound = storm::utility::isInfinity(upperBound) ? storm::utility::infinity<double>() : storm::utility::convertNumber<double>(upperBound); printResult(roundedLowerBound, roundedUpperBound); STORM_PRINT_AND_LOG(")"); } } MemlessSearchOptions fillMemlessSearchOptionsFromSettings() { storm::pomdp::MemlessSearchOptions options; auto const& qualSettings = storm::settings::getModule<storm::settings::modules::QualitativePOMDPAnalysisSettings>(); options.onlyDeterministicStrategies = qualSettings.isOnlyDeterministicSet(); uint64_t loglevel = 0; // TODO a big ugly, but we have our own loglevels (for technical reasons) if(storm::utility::getLogLevel() == l3pp::LogLevel::INFO) { loglevel = 1; } else if(storm::utility::getLogLevel() == l3pp::LogLevel::DEBUG) { loglevel = 2; } else if(storm::utility::getLogLevel() == l3pp::LogLevel::TRACE) { loglevel = 3; } options.setDebugLevel(loglevel); options.validateEveryStep = qualSettings.validateIntermediateSteps(); options.validateResult = qualSettings.validateFinalResult(); options.pathVariableType = storm::pomdp::pathVariableTypeFromString(qualSettings.getLookaheadType()); if (qualSettings.isExportSATCallsSet()) { options.setExportSATCalls(qualSettings.getExportSATCallsPath()); } return options; } template<typename ValueType> void performQualitativeAnalysis(std::shared_ptr<storm::models::sparse::Pomdp<ValueType>> const& origpomdp, storm::pomdp::analysis::FormulaInformation const& formulaInfo, storm::logic::Formula const& formula) { auto const& qualSettings = storm::settings::getModule<storm::settings::modules::QualitativePOMDPAnalysisSettings>(); auto const& coreSettings = storm::settings::getModule<storm::settings::modules::CoreSettings>(); std::stringstream sstr; origpomdp->printModelInformationToStream(sstr); STORM_LOG_INFO(sstr.str()); STORM_LOG_THROW(formulaInfo.isNonNestedReachabilityProbability(), storm::exceptions::NotSupportedException, "Qualitative memoryless scheduler search is not implemented for this property type."); STORM_LOG_TRACE("Run qualitative preprocessing..."); storm::models::sparse::Pomdp<ValueType> pomdp(*origpomdp); storm::analysis::QualitativeAnalysisOnGraphs<ValueType> qualitativeAnalysis(pomdp); // After preprocessing, this might be done cheaper. storm::storage::BitVector surelyNotAlmostSurelyReachTarget = qualitativeAnalysis.analyseProbSmaller1( formula.asProbabilityOperatorFormula()); pomdp.getTransitionMatrix().makeRowGroupsAbsorbing(surelyNotAlmostSurelyReachTarget); storm::storage::BitVector targetStates = qualitativeAnalysis.analyseProb1(formula.asProbabilityOperatorFormula()); storm::expressions::ExpressionManager expressionManager; std::shared_ptr<storm::utility::solver::SmtSolverFactory> smtSolverFactory = std::make_shared<storm::utility::solver::Z3SmtSolverFactory>(); storm::pomdp::MemlessSearchOptions options = fillMemlessSearchOptionsFromSettings(); uint64_t lookahead = qualSettings.getLookahead(); if (lookahead == 0) { lookahead = pomdp.getNumberOfStates(); } if (qualSettings.getMemlessSearchMethod() == "one-shot") { storm::pomdp::OneShotPolicySearch<ValueType> memlessSearch(pomdp, targetStates, surelyNotAlmostSurelyReachTarget, smtSolverFactory); if (qualSettings.isWinningRegionSet()) { STORM_LOG_ERROR("Computing winning regions is not supported by ccd-memless."); } else { memlessSearch.analyzeForInitialStates(lookahead); } } else if (qualSettings.getMemlessSearchMethod() == "iterative") { storm::pomdp::IterativePolicySearch<ValueType> search(pomdp, targetStates, surelyNotAlmostSurelyReachTarget, smtSolverFactory, options); if (qualSettings.isWinningRegionSet()) { search.computeWinningRegion(lookahead); } else { search.analyzeForInitialStates(lookahead); } if (qualSettings.isPrintWinningRegionSet()) { search.getLastWinningRegion().print(); std::cout << std::endl; } if (qualSettings.isExportWinningRegionSet()) { std::size_t hash = pomdp.hash(); search.getLastWinningRegion().storeToFile(qualSettings.exportWinningRegionPath(), "model hash: " + std::to_string(hash)); } search.finalizeStatistics(); if(pomdp.getInitialStates().getNumberOfSetBits() == 1) { uint64_t initialState = pomdp.getInitialStates().getNextSetIndex(0); uint64_t initialObservation = pomdp.getObservation(initialState); // TODO this is inefficient. uint64_t offset = 0; for (uint64_t state = 0; state < pomdp.getNumberOfStates(); ++state) { if (state == initialState) { break; } if (pomdp.getObservation(state) == initialObservation) { ++offset; } } STORM_PRINT_AND_LOG("Initial state is safe: " << search.getLastWinningRegion().isWinning(initialObservation, offset)); } else { STORM_LOG_WARN("Output for multiple initial states is incomplete"); } std::cout << "Number of belief support states: " << search.getLastWinningRegion().beliefSupportStates() << std::endl; if (coreSettings.isShowStatisticsSet() && qualSettings.computeExpensiveStats()) { auto wbss = search.getLastWinningRegion().computeNrWinningBeliefs(); STORM_PRINT_AND_LOG( "Number of winning belief support states: [" << wbss.first << "," << wbss.second << "]"); } if (coreSettings.isShowStatisticsSet()) { search.getStatistics().print(); } } else { STORM_LOG_ERROR("This method is not implemented."); } } template<typename ValueType, storm::dd::DdType DdType> bool performAnalysis(std::shared_ptr<storm::models::sparse::Pomdp<ValueType>> const& pomdp, storm::pomdp::analysis::FormulaInformation const& formulaInfo, storm::logic::Formula const& formula) { auto const& pomdpSettings = storm::settings::getModule<storm::settings::modules::POMDPSettings>(); bool analysisPerformed = false; if (pomdpSettings.isBeliefExplorationSet()) { STORM_PRINT_AND_LOG("Exploring the belief MDP... "); auto options = storm::pomdp::modelchecker::BeliefExplorationPomdpModelCheckerOptions<ValueType>(pomdpSettings.isBeliefExplorationDiscretizeSet(), pomdpSettings.isBeliefExplorationUnfoldSet()); auto const& beliefExplorationSettings = storm::settings::getModule<storm::settings::modules::BeliefExplorationSettings>(); beliefExplorationSettings.setValuesInOptionsStruct(options); storm::pomdp::modelchecker::BeliefExplorationPomdpModelChecker<storm::models::sparse::Pomdp<ValueType>> checker(pomdp, options); auto result = checker.check(formula); checker.printStatisticsToStream(std::cout); if (storm::utility::resources::isTerminate()) { STORM_PRINT_AND_LOG("\nResult till abort: ") } else { STORM_PRINT_AND_LOG("\nResult: ") } printResult(result.lowerBound, result.upperBound); STORM_PRINT_AND_LOG(std::endl); analysisPerformed = true; } if (pomdpSettings.isQualitativeAnalysisSet()) { performQualitativeAnalysis(pomdp, formulaInfo, formula); analysisPerformed = true; } if (pomdpSettings.isCheckFullyObservableSet()) { STORM_PRINT_AND_LOG("Analyzing the formula on the fully observable MDP ... "); auto resultPtr = storm::api::verifyWithSparseEngine<ValueType>(pomdp->template as<storm::models::sparse::Mdp<ValueType>>(), storm::api::createTask<ValueType>(formula.asSharedPointer(), true)); if (resultPtr) { auto result = resultPtr->template asExplicitQuantitativeCheckResult<ValueType>(); result.filter(storm::modelchecker::ExplicitQualitativeCheckResult(pomdp->getInitialStates())); if (storm::utility::resources::isTerminate()) { STORM_PRINT_AND_LOG("\nResult till abort: ") } else { STORM_PRINT_AND_LOG("\nResult: ") } printResult(result.getMin(), result.getMax()); STORM_PRINT_AND_LOG(std::endl); } else { STORM_PRINT_AND_LOG("\nResult: Not available." << std::endl); } analysisPerformed = true; } return analysisPerformed; } template<typename ValueType, storm::dd::DdType DdType> bool performTransformation(std::shared_ptr<storm::models::sparse::Pomdp<ValueType>>& pomdp, storm::logic::Formula const& formula) { auto const& pomdpSettings = storm::settings::getModule<storm::settings::modules::POMDPSettings>(); auto const& ioSettings = storm::settings::getModule<storm::settings::modules::IOSettings>(); auto const& transformSettings = storm::settings::getModule<storm::settings::modules::ToParametricSettings>(); bool transformationPerformed = false; bool memoryUnfolded = false; if (pomdpSettings.getMemoryBound() > 1) { STORM_PRINT_AND_LOG("Computing the unfolding for memory bound " << pomdpSettings.getMemoryBound() << " and memory pattern '" << storm::storage::toString(pomdpSettings.getMemoryPattern()) << "' ..."); storm::storage::PomdpMemory memory = storm::storage::PomdpMemoryBuilder().build(pomdpSettings.getMemoryPattern(), pomdpSettings.getMemoryBound()); std::cout << memory.toString() << std::endl; storm::transformer::PomdpMemoryUnfolder<ValueType> memoryUnfolder(*pomdp, memory); pomdp = memoryUnfolder.transform(); STORM_PRINT_AND_LOG(" done." << std::endl); pomdp->printModelInformationToStream(std::cout); transformationPerformed = true; memoryUnfolded = true; } // From now on the pomdp is considered memoryless if (transformSettings.isMecReductionSet()) { STORM_PRINT_AND_LOG("Eliminating mec choices ..."); // Note: Elimination of mec choices only preserves memoryless schedulers. uint64_t oldChoiceCount = pomdp->getNumberOfChoices(); storm::transformer::GlobalPomdpMecChoiceEliminator<ValueType> mecChoiceEliminator(*pomdp); pomdp = mecChoiceEliminator.transform(formula); STORM_PRINT_AND_LOG(" done." << std::endl); STORM_PRINT_AND_LOG(oldChoiceCount - pomdp->getNumberOfChoices() << " choices eliminated through MEC choice elimination." << std::endl); pomdp->printModelInformationToStream(std::cout); transformationPerformed = true; } if (transformSettings.isTransformBinarySet() || transformSettings.isTransformSimpleSet()) { if (transformSettings.isTransformSimpleSet()) { STORM_PRINT_AND_LOG("Transforming the POMDP to a simple POMDP."); pomdp = storm::transformer::BinaryPomdpTransformer<ValueType>().transform(*pomdp, true); } else { STORM_PRINT_AND_LOG("Transforming the POMDP to a binary POMDP."); pomdp = storm::transformer::BinaryPomdpTransformer<ValueType>().transform(*pomdp, false); } pomdp->printModelInformationToStream(std::cout); STORM_PRINT_AND_LOG(" done." << std::endl); transformationPerformed = true; } if (pomdpSettings.isExportToParametricSet()) { STORM_PRINT_AND_LOG("Transforming memoryless POMDP to pMC..."); storm::transformer::ApplyFiniteSchedulerToPomdp<ValueType> toPMCTransformer(*pomdp); std::string transformMode = transformSettings.getFscApplicationTypeString(); auto pmc = toPMCTransformer.transform(storm::transformer::parsePomdpFscApplicationMode(transformMode)); STORM_PRINT_AND_LOG(" done." << std::endl); pmc->printModelInformationToStream(std::cout); if (transformSettings.allowPostSimplifications()) { STORM_PRINT_AND_LOG("Simplifying pMC..."); pmc = storm::api::performBisimulationMinimization<storm::RationalFunction>(pmc->template as<storm::models::sparse::Dtmc<storm::RationalFunction>>(),{formula.asSharedPointer()}, storm::storage::BisimulationType::Strong)->template as<storm::models::sparse::Dtmc<storm::RationalFunction>>(); STORM_PRINT_AND_LOG(" done." << std::endl); pmc->printModelInformationToStream(std::cout); } STORM_PRINT_AND_LOG("Exporting pMC..."); storm::analysis::ConstraintCollector<storm::RationalFunction> constraints(*pmc); auto const& parameterSet = constraints.getVariables(); std::vector<storm::RationalFunctionVariable> parameters(parameterSet.begin(), parameterSet.end()); std::vector<std::string> parameterNames; for (auto const& parameter : parameters) { parameterNames.push_back(parameter.name()); } storm::api::exportSparseModelAsDrn(pmc, pomdpSettings.getExportToParametricFilename(), parameterNames, !ioSettings.isExplicitExportPlaceholdersDisabled()); STORM_PRINT_AND_LOG(" done." << std::endl); transformationPerformed = true; } if (transformationPerformed && !memoryUnfolded) { STORM_PRINT_AND_LOG("Implicitly assumed restriction to memoryless schedulers for at least one transformation." << std::endl); } return transformationPerformed; } template<typename ValueType, storm::dd::DdType DdType> void processOptionsWithValueTypeAndDdLib(storm::cli::SymbolicInput const& symbolicInput, storm::cli::ModelProcessingInformation const& mpi) { auto const& pomdpSettings = storm::settings::getModule<storm::settings::modules::POMDPSettings>(); auto model = storm::cli::buildPreprocessExportModelWithValueTypeAndDdlib<DdType, ValueType>(symbolicInput, mpi); if (!model) { STORM_PRINT_AND_LOG("No input model given." << std::endl); return; } STORM_LOG_THROW(model->getType() == storm::models::ModelType::Pomdp && model->isSparseModel(), storm::exceptions::WrongFormatException, "Expected a POMDP in sparse representation."); std::shared_ptr<storm::models::sparse::Pomdp<ValueType>> pomdp = model->template as<storm::models::sparse::Pomdp<ValueType>>(); if (!pomdpSettings.isNoCanonicSet()) { storm::transformer::MakePOMDPCanonic<ValueType> makeCanonic(*pomdp); pomdp = makeCanonic.transform(); } std::shared_ptr<storm::logic::Formula const> formula; if (!symbolicInput.properties.empty()) { formula = symbolicInput.properties.front().getRawFormula(); STORM_PRINT_AND_LOG("Analyzing property '" << *formula << "'" << std::endl); STORM_LOG_WARN_COND(symbolicInput.properties.size() == 1, "There is currently no support for multiple properties. All other properties will be ignored."); } if (pomdpSettings.isAnalyzeUniqueObservationsSet()) { STORM_PRINT_AND_LOG("Analyzing states with unique observation ..." << std::endl); storm::analysis::UniqueObservationStates<ValueType> uniqueAnalysis(*pomdp); std::cout << uniqueAnalysis.analyse() << std::endl; } if (formula) { auto formulaInfo = storm::pomdp::analysis::getFormulaInformation(*pomdp, *formula); STORM_LOG_THROW(!formulaInfo.isUnsupported(), storm::exceptions::InvalidPropertyException, "The formula '" << *formula << "' is not supported by storm-pomdp."); storm::utility::Stopwatch sw(true); // Note that formulaInfo contains state-based information which potentially needs to be updated during preprocessing if (performPreprocessing<ValueType, DdType>(pomdp, formulaInfo, *formula)) { sw.stop(); STORM_PRINT_AND_LOG("Time for graph-based POMDP (pre-)processing: " << sw << "." << std::endl); pomdp->printModelInformationToStream(std::cout); } sw.restart(); if (performTransformation<ValueType, DdType>(pomdp, *formula)) { sw.stop(); STORM_PRINT_AND_LOG("Time for POMDP transformation(s): " << sw << "s." << std::endl); } sw.restart(); if (performAnalysis<ValueType, DdType>(pomdp, formulaInfo, *formula)) { sw.stop(); STORM_PRINT_AND_LOG("Time for POMDP analysis: " << sw << "s." << std::endl); } } else { STORM_LOG_WARN("Nothing to be done. Did you forget to specify a formula?"); } } template <storm::dd::DdType DdType> void processOptionsWithDdLib(storm::cli::SymbolicInput const& symbolicInput, storm::cli::ModelProcessingInformation const& mpi) { STORM_LOG_ERROR_COND(mpi.buildValueType == mpi.verificationValueType, "Build value type differs from verification value type. Will ignore Verification value type."); switch (mpi.buildValueType) { case storm::cli::ModelProcessingInformation::ValueType::FinitePrecision: processOptionsWithValueTypeAndDdLib<double, DdType>(symbolicInput, mpi); break; case storm::cli::ModelProcessingInformation::ValueType::Exact: STORM_LOG_THROW(DdType == storm::dd::DdType::Sylvan, storm::exceptions::UnexpectedException, "Exact arithmetic is only supported with Dd library Sylvan."); processOptionsWithValueTypeAndDdLib<storm::RationalNumber, storm::dd::DdType::Sylvan>(symbolicInput, mpi); break; default: STORM_LOG_THROW(false, storm::exceptions::UnexpectedException, "Unexpected ValueType for model building."); } } void processOptions() { auto symbolicInput = storm::cli::parseSymbolicInput(); storm::cli::ModelProcessingInformation mpi; std::tie(symbolicInput, mpi) = storm::cli::preprocessSymbolicInput(symbolicInput); switch (mpi.ddType) { case storm::dd::DdType::CUDD: processOptionsWithDdLib<storm::dd::DdType::CUDD>(symbolicInput, mpi); break; case storm::dd::DdType::Sylvan: processOptionsWithDdLib<storm::dd::DdType::Sylvan>(symbolicInput, mpi); break; default: STORM_LOG_THROW(false, storm::exceptions::UnexpectedException, "Unexpected Dd Type."); } } } } } /*! * Entry point for the pomdp backend. * * @param argc The argc argument of main(). * @param argv The argv argument of main(). * @return Return code, 0 if successfull, not 0 otherwise. */ int main(const int argc, const char** argv) { //try { storm::utility::setUp(); storm::cli::printHeader("Storm-pomdp", argc, argv); storm::settings::initializePomdpSettings("Storm-POMDP", "storm-pomdp"); bool optionsCorrect = storm::cli::parseOptions(argc, argv); if (!optionsCorrect) { return -1; } storm::cli::setUrgentOptions(); // Invoke storm-pomdp with obtained settings storm::pomdp::cli::processOptions(); // All operations have now been performed, so we clean up everything and terminate. storm::utility::cleanUp(); return 0; // } catch (storm::exceptions::BaseException const &exception) { // STORM_LOG_ERROR("An exception caused Storm-pomdp to terminate. The message of the exception is: " << exception.what()); // return 1; //} catch (std::exception const &exception) { // STORM_LOG_ERROR("An unexpected exception occurred and caused Storm-pomdp to terminate. The message of this exception is: " << exception.what()); // return 2; //} }
62.586134
312
0.59095
glatteis
7cca78ed78b804f3fe0a2650607ff302d300686d
4,150
cpp
C++
rest/src/parser/tests/TestBookDirectoryBuilder.cpp
cisocrgroup/pocoweb
93546d026321744602f6ee90fd82503da56da3b7
[ "Apache-2.0" ]
10
2018-04-09T20:46:49.000Z
2021-08-07T17:29:02.000Z
rest/src/parser/tests/TestBookDirectoryBuilder.cpp
cisocrgroup/pocoweb
93546d026321744602f6ee90fd82503da56da3b7
[ "Apache-2.0" ]
61
2018-01-03T09:49:16.000Z
2022-02-18T12:26:11.000Z
rest/src/parser/tests/TestBookDirectoryBuilder.cpp
cisocrgroup/pocoweb
93546d026321744602f6ee90fd82503da56da3b7
[ "Apache-2.0" ]
3
2020-01-10T15:44:18.000Z
2021-05-19T13:39:53.000Z
#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE BookDirectoryBuilderTest #include "core/Book.hpp" #include "core/BookDirectoryBuilder.hpp" #include "core/Page.hpp" #include "utils/TmpDir.hpp" #include <boost/filesystem/operations.hpp> #include <boost/test/unit_test.hpp> #include <crow/logging.h> #include <fstream> #include <functional> #include <iostream> #include <vector> using namespace pcw; struct ZipFile { public: ZipFile(const std::string &file) : file_(file) { system(("wget --quiet -nc http://www.cis.lmu.de/~finkf/pocoweb/" + file_) .data()); } ~ZipFile() { boost::system::error_code ec; boost::filesystem::remove(file_, ec); } const std::string &file() { return file_; } private: const std::string file_; }; struct Fixture { Fixture() : tmpdir(), dir("testdir"), builder(tmpdir.dir(), dir) { // static crow::CerrLogHandler cerrlogger; // crow::logger::setHandler(&cerrlogger); // crow::logger::setLogLevel(crow::LogLevel::Debug); } TmpDir tmpdir; Path dir; BookDirectoryBuilder builder; void add_zip_file(const char *file) { std::ifstream is(file); is >> std::noskipws; BOOST_REQUIRE(is.good()); std::string content; std::copy(std::istream_iterator<char>(is), std::istream_iterator<char>(), std::back_inserter(content)); builder.add_zip_file_content(content); } }; //////////////////////////////////////////////////////////////////////////////// BOOST_FIXTURE_TEST_SUITE(BookDirectoryBuilderTest, Fixture) //////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_CASE(Ocropus) { ZipFile zip("hobbes-ocropus.zip"); add_zip_file(zip.file().data()); auto book = builder.build(); BOOST_REQUIRE(book); BOOST_CHECK_EQUAL(book->size(), 2); // page 42 auto p1 = book->find(42); BOOST_REQUIRE(p1); auto line = p1->find(0x27); BOOST_REQUIRE(line); BOOST_CHECK_EQUAL(line->ocr(), "ſlanti Finis alicujus propoſiti. Contrà, " "imaginatiotarda Defectum ani-"); BOOST_CHECK_EQUAL(line->img, dir / "ocropus-book" / "0042" / "010027.bin.png"); // page 100 auto p2 = book->find(100); BOOST_REQUIRE(p2); line = p2->find(0x8); BOOST_REQUIRE(line); BOOST_CHECK_EQUAL( line->ocr(), "ea contribuere quæ ad Pacem & Deſenſionem ſuam neceſſaria ſunt,"); BOOST_CHECK_EQUAL(line->img, dir / "ocropus-book" / "0100" / "010008.bin.png"); // no such page auto p3 = book->find(200); BOOST_REQUIRE(not p3); } //////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_CASE(Alto) { ZipFile zip("rollenhagen_reysen_1603.zip"); add_zip_file(zip.file().data()); auto book = builder.build(); BOOST_REQUIRE(book); BOOST_CHECK_EQUAL(book->size(), 3); // first page const auto p1 = book->find(1); BOOST_REQUIRE(p1); BOOST_CHECK_EQUAL(p1->img, dir / "rollenhagen_reysen_1603/rollenhagen_reysen_1603/" "rollenhagen_reysen_1603_0007.tif"); auto line = p1->find(1); BOOST_REQUIRE(line); BOOST_CHECK_EQUAL(line->ocr(), "Vnd daſſelb im Bluthroten Felde/"); BOOST_CHECK_EQUAL(line->img, dir / "line-images" / "0000000001" / "0000000001.png"); // second page const auto p2 = book->find(2); BOOST_REQUIRE(p2); line = p2->find(6); BOOST_REQUIRE(line); BOOST_CHECK_EQUAL(line->ocr(), "vnd des Jndianiſchen Landes/ auch von"); BOOST_CHECK_EQUAL(line->img, dir / "line-images" / "0000000002" / "0000000006.png"); // third page const auto p3 = book->find(3); BOOST_REQUIRE(p2); line = p3->find(14); BOOST_REQUIRE(line); BOOST_CHECK_EQUAL(line->ocr(), "in je einem Land ſo viel ſeltzame wunder wehrẽ/ wen"); BOOST_CHECK_EQUAL(line->img, dir / "line-images" / "0000000003" / "000000000e.png"); // no such page const auto p4 = book->find(4); BOOST_REQUIRE(not p4); } //////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_SUITE_END()
30.291971
80
0.600241
cisocrgroup
7ccb4ad509d2aec2592a7b1458ddb2436e6ca652
561
cc
C++
cpp/leetcode/153.find-minimum-in-rotated-sorted-array.cc
liubang/laboratory
747f239a123cd0c2e5eeba893b9a4d1536555b1e
[ "MIT" ]
3
2021-03-03T13:18:23.000Z
2022-02-09T07:49:24.000Z
cpp/leetcode/153.find-minimum-in-rotated-sorted-array.cc
liubang/laboratory
747f239a123cd0c2e5eeba893b9a4d1536555b1e
[ "MIT" ]
null
null
null
cpp/leetcode/153.find-minimum-in-rotated-sorted-array.cc
liubang/laboratory
747f239a123cd0c2e5eeba893b9a4d1536555b1e
[ "MIT" ]
1
2021-03-29T15:21:42.000Z
2021-03-29T15:21:42.000Z
#include <gtest/gtest.h> #include <vector> namespace { class Solution { public: int findMin(const std::vector<int>& nums) { int s = 0, e = nums.size() - 1; while (s < e) { int m = (s + e) / 2; if (nums[m] < nums[e]) { e = m; } else { s = m + 1; } } return nums[s]; } }; } // namespace TEST(Leetcode, find_minimum_in_rotated_sorted_array) { Solution s; EXPECT_EQ(0, s.findMin({4, 5, 6, 7, 0, 1, 2})); EXPECT_EQ(1, s.findMin({3, 4, 5, 1, 2})); EXPECT_EQ(11, s.findMin({11, 13, 15, 17})); }
19.344828
54
0.520499
liubang
7cd0fe7d92d1caf1a13914a8428202ce0fce3c65
699
hpp
C++
Source/WinSandbox/Physics/Collision/Collider.hpp
wradley/Freight
91eda2ca0af64036202309f6adbf2d80c406e031
[ "MIT" ]
null
null
null
Source/WinSandbox/Physics/Collision/Collider.hpp
wradley/Freight
91eda2ca0af64036202309f6adbf2d80c406e031
[ "MIT" ]
null
null
null
Source/WinSandbox/Physics/Collision/Collider.hpp
wradley/Freight
91eda2ca0af64036202309f6adbf2d80c406e031
[ "MIT" ]
null
null
null
#pragma once #include <Freight/Math.hpp> class Rigidbody; struct Collider { std::shared_ptr<Rigidbody> body; enum class Type { HALF_SPACE, SPHERE, BOX, }; virtual Type getType() const = 0; }; struct SphereCollider : public Collider { fr::Vec3 position; fr::Real radius; inline virtual Type getType() const { return Type::SPHERE; } }; struct HalfSpace : public Collider { fr::Vec3 normal; fr::Real offset; inline virtual Type getType() const { return Type::HALF_SPACE; } }; struct BoxCollider : public Collider { fr::Vec3 halfSizes; fr::Transform offset; inline virtual Type getType() const { return Type::BOX; } };
17.475
68
0.648069
wradley
7cd21489770eaa88635076b6ff2d7e5bfdad942a
1,422
hpp
C++
include/Client/PlayerMovementSystem.hpp
maximaximal/BomberPi
365c806e3feda7296fc10d5f9655ec696f0ab491
[ "Zlib" ]
null
null
null
include/Client/PlayerMovementSystem.hpp
maximaximal/BomberPi
365c806e3feda7296fc10d5f9655ec696f0ab491
[ "Zlib" ]
null
null
null
include/Client/PlayerMovementSystem.hpp
maximaximal/BomberPi
365c806e3feda7296fc10d5f9655ec696f0ab491
[ "Zlib" ]
null
null
null
#ifndef CLIENT_PLAYERMOVEMENTSYSTEM_HPP_INCLUDED #define CLIENT_PLAYERMOVEMENTSYSTEM_HPP_INCLUDED #include <anax/System.hpp> #include <map> #include <Client/BombermanMap.hpp> #include <Client/BodyComponent.hpp> #include <Client/CollisionSystem.hpp> #include <Client/PositionComponent.hpp> #include <Client/PlayerInputComponent.hpp> #include <Client/SpriteComponent.hpp> #include <Client/BodyComponent.hpp> #include <Client/BombLayerComponent.hpp> #include <Client/SpeedComponent.hpp> namespace Client { class PositionComponent; class PlayerMovementSystem : public anax::System<anax::Requires<PositionComponent, PlayerInputComponent, SpriteComponent, BodyComponent, BombLayerComponent, SpeedComponent>> { public: PlayerMovementSystem(BombermanMap *bombermanMap, CollisionSystem *collisionSystem); virtual ~PlayerMovementSystem(); void setMap(BombermanMap *map); void update(float frameTime); void onPlayerCollision(std::shared_ptr<Collision> collision); protected: virtual void onEntityRemoved(anax::Entity &e); void calculateTarget(PlayerInputEnum dir, BodyComponent &body, Client::PositionComponent &pos); private: BombermanMap *m_bombermanMap; CollisionSystem *m_collisionSystem; std::map<anax::Entity::Id, sigc::connection> m_collisionConnections; }; } #endif
33.069767
177
0.73699
maximaximal
7cd356fd0e27b6a0958aa5f0985faeae1eb4a94e
23
cpp
C++
src/collider.cpp
trevorGalivan/lavaGameEngine
9a8ce6845a8e1fd728a376d5665c5b57abcfed4c
[ "MIT" ]
1
2021-03-04T23:39:46.000Z
2021-03-04T23:39:46.000Z
src/collider.cpp
trevorGalivan/lavaGameEngine
9a8ce6845a8e1fd728a376d5665c5b57abcfed4c
[ "MIT" ]
null
null
null
src/collider.cpp
trevorGalivan/lavaGameEngine
9a8ce6845a8e1fd728a376d5665c5b57abcfed4c
[ "MIT" ]
null
null
null
#include "collider.h"
11.5
22
0.695652
trevorGalivan
7cd5bc778ceaf5a9aa1d1181dafa0d9b48770328
3,487
cpp
C++
lanchonete-array.cpp
jonasnunes/Cpp
f58c03ee63e37285b4a1455cc55f184672fdaf5c
[ "MIT" ]
null
null
null
lanchonete-array.cpp
jonasnunes/Cpp
f58c03ee63e37285b4a1455cc55f184672fdaf5c
[ "MIT" ]
null
null
null
lanchonete-array.cpp
jonasnunes/Cpp
f58c03ee63e37285b4a1455cc55f184672fdaf5c
[ "MIT" ]
null
null
null
#include <iostream> #include <locale> using namespace std; int main() { setlocale(LC_CTYPE, "Portuguese"); // mesmo exemplo da lanchonete, mas usando array ao invés de struct. string comboNome[] = {"Prata da Casa", "+ Light", "Lanche Pobre"}; int numeroItens[] = {4, 3, 2}; string comboItens[] = {"X-Tudo", "Batata Frita", "Pastel", "Coca lata", "X-Frango", "Batata Frita", "Fanta Laranja", "Hamburguer", "Coca lata"}; double comboValor[] = {49.90, 32.50, 19.90}; string nome; long long int codigoCliente; int opc, qtd; double valorTotal; cout << "Bem vindo ao Big Lanches!" << endl; cout << "Não perca tempo... Faça já o seu pedido!" << endl; cout << "Qual é o seu nome? "; cin.ignore(); getline(cin, nome); cout << "Digite o código do cliente.: "; cin >> codigoCliente; cout << "Pressione 1 para ver o nosso cardápio.: "; cin >> opc; switch(opc) { case 1: cout << "\nCombo 1" << endl; cout << "Nome do combo.: " << comboNome[0] << "\n" << "Número de Itens.: " << numeroItens[0] << "\n" << "Itens.: " << comboItens[0] << ", " << comboItens[1] << ", " << comboItens[2] << ", " << comboItens[3] << ".\n"; cout << "-----------------------------------------------------" << endl; cout << "\nCombo 2" << endl; cout << "Nome do combo.: " << comboNome[1] << "\n" << "Número de Itens.: " << numeroItens[1] << "\n" << "Itens.: " << comboItens[4] << ", " << comboItens[5] << ", " << comboItens[6] << ".\n"; cout << "-----------------------------------------------------" << endl; cout << "\nCombo 3" << endl; cout << "Nome do combo.: " << comboNome[2] << "\n" << "Número de Itens.: " << numeroItens[2] << "\n" << "Itens.: " << comboItens[7] << ", " << comboItens[8] << ".\n"; cout << "-----------------------------------------------------" << endl; cout << "\nQual desses o(a) Senhor(a) deseja?" << endl; cin >> opc; switch(opc) { case 1: cout << "\nProduto escolhido.: Combo 1" << endl; cout << "Quantos o(a) Senhor(a) vai querer? " << endl; cin >> qtd; valorTotal = qtd * comboValor[0]; cout << "\nSeu pedido irá custar R$ " << valorTotal << ". Dirija-se ao caixa mais próximo." << endl; break; case 2: cout << "\nProduto escolhido.: Combo 2" << endl; cout << "Quantos o(a) Senhor(a) vai querer? " << endl; cin >> qtd; valorTotal = qtd * comboValor[1]; cout << "\nSeu pedido irá custar R$ " << valorTotal << ". Dirija-se ao caixa mais próximo." << endl; break; case 3: cout << "\nProduto escolhido.: Combo 3" << endl; cout << "Quantos o(a) Senhor(a) vai querer? " << endl; cin >> qtd; valorTotal = qtd * comboValor[2]; cout << "\nSeu pedido irá custar R$ " << valorTotal << ". Dirija-se ao caixa mais próximo." << endl; break; default: cout << "\nOpção Inválida!" << endl; } } cout << "\nMuito obrigado! Volte sempre...\n\n"; system("pause"); return 0; }
39.625
228
0.443648
jonasnunes
7cd936262513cfad24e74c8d2ef95e84c78d425c
327
cpp
C++
AT-Task3-OpenGL/VoxelTextureAtlas.cpp
gualtyphone/AT-Task3-OpenGL
b14461f71b1766882082cd1481d21bd00f49cdb5
[ "MIT" ]
1
2018-11-25T10:52:57.000Z
2018-11-25T10:52:57.000Z
AT-Task3-OpenGL/VoxelTextureAtlas.cpp
gualtyphone/AT-Task3-OpenGL
b14461f71b1766882082cd1481d21bd00f49cdb5
[ "MIT" ]
null
null
null
AT-Task3-OpenGL/VoxelTextureAtlas.cpp
gualtyphone/AT-Task3-OpenGL
b14461f71b1766882082cd1481d21bd00f49cdb5
[ "MIT" ]
null
null
null
#include "VoxelTextureData.h" // UV Structure // 0--1 // | | // 3--2 Vector2 VoxelTextureAtlas::UVOffsets[4] = { Vector2(0, 0), Vector2(1.0f / (float)numberOfTexturesWidth, 0), Vector2(1.0f / (float)numberOfTexturesWidth, (1.0f / (float)numberOfTexturesHeight)), Vector2(0, (1.0f / (float)numberOfTexturesHeight)), };
20.4375
86
0.681957
gualtyphone
7cdf666b3b837a4683272fd4dbcef1e9ec646b7f
4,315
cpp
C++
thread/task/task_scheduler.cpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
1
2017-08-11T19:12:24.000Z
2017-08-11T19:12:24.000Z
thread/task/task_scheduler.cpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
11
2018-07-07T20:09:44.000Z
2020-02-16T22:45:09.000Z
thread/task/task_scheduler.cpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
null
null
null
//------------------------------------------------------------ // snakeoil (c) Alexis Constantin Link // Distributed under the MIT license //------------------------------------------------------------ #include "task_graph.h" #include "task_scheduler.h" #include "serial_executor.h" #include "async_executor.h" using namespace so_thread ; //************************************************************************************* task_scheduler::task_scheduler( void_t ) { } //************************************************************************************* task_scheduler::task_scheduler( this_rref_t rhv ) { _asyncs = std::move(rhv._asyncs) ; _serials = std::move(rhv._serials) ; } //************************************************************************************* task_scheduler::~task_scheduler( void_t ) { } //************************************************************************************* task_scheduler::this_ptr_t task_scheduler::create( so_memory::purpose_cref_t p ) { return so_thread::memory::alloc( this_t(), p ) ; } //************************************************************************************* task_scheduler::this_ptr_t task_scheduler::create( this_rref_t rhv, so_memory::purpose_cref_t p ) { return so_thread::memory::alloc( std::move(rhv), p ) ; } //************************************************************************************* void_t task_scheduler::destroy( this_ptr_t ptr ) { so_thread::memory::dealloc( ptr ) ; } //************************************************************************************* void_t task_scheduler::update( void_t ) { // update all serial tasks { tasks_t serials ; { so_thread::lock_guard_t lk(_mtx_serial) ; serials = std::move( _serials ) ; } so_thread::serial_executor se ; se.consume( std::move(serials) ) ; } // update all async tasks { tasks_t asyncs ; { so_thread::lock_guard_t lk( _mtx_async ) ; asyncs = std::move( _asyncs ) ; } so_thread::async_executor ae ; ae.consume_and_wait( std::move( asyncs ) ) ; } } //************************************************************************************* void_t task_scheduler::async_now( so_thread::itask_ptr_t tptr, so_thread::sync_object_ptr_t sptr ) { /* std::async( std::launch::async, [=]( void_t ) { so_thread::async_executor_t ae ; ae.consume_and_wait( tptr ) ; so_thread::sync_object::set_and_signal( sptr ) ; } ) ; */ // @todo make async again. future will block on destruction std::thread t( [=] ( void_t ) { so_thread::async_executor_t ae ; ae.consume_and_wait( tptr ) ; so_thread::sync_object::set_and_signal( sptr ) ; } ) ; t.detach( ) ; } //************************************************************************************* void_t task_scheduler::async_now( so_thread::task_graph_rref_t tg, so_thread::sync_object_ptr_t sptr ) { // invalidate the end task pointer. tg.end_moved() ; this->async_now( tg.begin_moved(), sptr ) ; } //************************************************************************************* void_t task_scheduler::serial_now( so_thread::itask_ptr_t tptr, so_thread::sync_object_ptr_t sptr ) { std::thread t([=] (void_t) { so_thread::serial_executor_t se ; se.consume( tptr ) ; so_thread::sync_object::set_and_signal( sptr ) ; } ) ; t.detach() ; } //************************************************************************************* void_t task_scheduler::async_on_update( so_thread::itask_ptr_t ptr ) { if( so_core::is_nullptr(ptr) ) return ; so_thread::lock_guard_t lk(_mtx_async) ; _asyncs.push_back( ptr ) ; } //************************************************************************************* void_t task_scheduler::serial_on_update( so_thread::itask_ptr_t ptr ) { if( so_core::is_nullptr( ptr ) ) return ; so_thread::lock_guard_t lk( _mtx_serial ) ; _serials.push_back( ptr ) ; } //************************************************************************************* void_t task_scheduler::destroy( void_t ) { this_t::destroy( this ) ; }
28.959732
103
0.451217
aconstlink
7ce0cbb964131aceceaac4ea3928030614fc9209
157
cpp
C++
clang/test/CXX/module/module.unit/p7/t7.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
605
2019-10-18T01:15:54.000Z
2022-03-31T14:31:04.000Z
clang/test/CXX/module/module.unit/p7/t7.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
3,180
2019-10-18T01:21:21.000Z
2022-03-31T23:25:41.000Z
clang/test/CXX/module/module.unit/p7/t7.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
275
2019-10-18T05:27:22.000Z
2022-03-30T09:04:21.000Z
// RUN: rm -fr %t // RUN: mkdir %t // RUN: %clang_cc1 -std=c++20 -I%S/Inputs/ %s -verify // expected-no-diagnostics module; #include "h7.h" export module X;
19.625
53
0.636943
LaudateCorpus1
7ce36e0a29e0abf213c345f6ad29a83274348bc8
2,016
hpp
C++
libraries/app/include/graphene/app/api_access.hpp
siwelo/bitshares-2
03561bfcf97801b44863bd51c400aae3ba51e3b0
[ "MIT" ]
null
null
null
libraries/app/include/graphene/app/api_access.hpp
siwelo/bitshares-2
03561bfcf97801b44863bd51c400aae3ba51e3b0
[ "MIT" ]
null
null
null
libraries/app/include/graphene/app/api_access.hpp
siwelo/bitshares-2
03561bfcf97801b44863bd51c400aae3ba51e3b0
[ "MIT" ]
null
null
null
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Any modified source or binaries are used only with the BitShares network. * * 2. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 3. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #pragma once #include <fc/reflect/reflect.hpp> #include <map> #include <string> #include <vector> namespace graphene { namespace app { struct api_access_info { std::string password_hash_b64; std::string password_salt_b64; std::vector< std::string > allowed_apis; }; struct api_access { std::map< std::string, api_access_info > permission_map; }; } } // graphene::app FC_REFLECT( graphene::app::api_access_info, (password_hash_b64) (password_salt_b64) (allowed_apis) ) FC_REFLECT( graphene::app::api_access, (permission_map) )
37.333333
208
0.761905
siwelo
7ce48eaa8a35c604b4165f73d7b9b328bef2d88f
4,822
cpp
C++
Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2022-03-03T12:03:32.000Z
2022-03-03T12:03:32.000Z
Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2021-12-22T10:19:02.000Z
2021-12-22T10:19:02.000Z
Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.cpp
zhaomengxiao/MITK_lancet
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2020-11-27T09:41:18.000Z
2020-11-27T09:41:18.000Z
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkFileOpenAction.h" #include "internal/org_mitk_gui_qt_application_Activator.h" #include <mitkIDataStorageService.h> #include <mitkNodePredicateProperty.h> #include <mitkWorkbenchUtil.h> #include <QmitkIOUtil.h> #include <berryIPreferences.h> #include <QFileDialog> namespace { mitk::DataStorage::Pointer GetDataStorage() { auto context = mitk::org_mitk_gui_qt_application_Activator::GetContext(); if (nullptr == context) return nullptr; auto dataStorageServiceReference = context->getServiceReference<mitk::IDataStorageService>(); if (!dataStorageServiceReference) return nullptr; auto dataStorageService = context->getService<mitk::IDataStorageService>(dataStorageServiceReference); if (nullptr == dataStorageService) return nullptr; auto dataStorageReference = dataStorageService->GetDataStorage(); if (dataStorageReference.IsNull()) return nullptr; return dataStorageReference->GetDataStorage(); } mitk::DataNode::Pointer GetFirstSelectedNode() { auto dataStorage = GetDataStorage(); if (dataStorage.IsNull()) return nullptr; auto selectedNodes = dataStorage->GetSubset(mitk::NodePredicateProperty::New("selected", mitk::BoolProperty::New(true))); if (selectedNodes->empty()) return nullptr; return selectedNodes->front(); } QString GetPathOfFirstSelectedNode() { auto firstSelectedNode = GetFirstSelectedNode(); if (firstSelectedNode.IsNull()) return ""; auto data = firstSelectedNode->GetData(); if (nullptr == data) return ""; auto pathProperty = data->GetConstProperty("path"); if (pathProperty.IsNull()) return ""; return QFileInfo(QString::fromStdString(pathProperty->GetValueAsString())).canonicalPath(); } } class QmitkFileOpenActionPrivate { public: void Init(berry::IWorkbenchWindow* window, QmitkFileOpenAction* action) { m_Window = window; action->setText("&Open File..."); action->setToolTip("Open data files (images, surfaces,...)"); QObject::connect(action, SIGNAL(triggered(bool)), action, SLOT(Run())); } berry::IPreferences::Pointer GetPreferences() const { berry::IPreferencesService* prefService = mitk::PluginActivator::GetInstance()->GetPreferencesService(); if (prefService != nullptr) { return prefService->GetSystemPreferences()->Node("/General"); } return berry::IPreferences::Pointer(nullptr); } QString GetLastFileOpenPath() const { berry::IPreferences::Pointer prefs = GetPreferences(); if (prefs.IsNotNull()) { return prefs->Get("LastFileOpenPath", ""); } return QString(); } void SetLastFileOpenPath(const QString& path) const { berry::IPreferences::Pointer prefs = GetPreferences(); if (prefs.IsNotNull()) { prefs->Put("LastFileOpenPath", path); prefs->Flush(); } } bool GetOpenEditor() const { berry::IPreferences::Pointer prefs = GetPreferences(); if (prefs.IsNotNull()) { return prefs->GetBool("OpenEditor", true); } return true; } berry::IWorkbenchWindow* m_Window; }; QmitkFileOpenAction::QmitkFileOpenAction(berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) , d(new QmitkFileOpenActionPrivate) { d->Init(window.GetPointer(), this); } QmitkFileOpenAction::QmitkFileOpenAction(const QIcon& icon, berry::IWorkbenchWindow::Pointer window) : QAction(nullptr) , d(new QmitkFileOpenActionPrivate) { d->Init(window.GetPointer(), this); setIcon(icon); } QmitkFileOpenAction::QmitkFileOpenAction(const QIcon& icon, berry::IWorkbenchWindow* window) : QAction(nullptr), d(new QmitkFileOpenActionPrivate) { d->Init(window, this); setIcon(icon); } QmitkFileOpenAction::~QmitkFileOpenAction() { } void QmitkFileOpenAction::Run() { auto path = GetPathOfFirstSelectedNode(); if (path.isEmpty()) path = d->GetLastFileOpenPath(); // Ask the user for a list of files to open QStringList fileNames = QFileDialog::getOpenFileNames(nullptr, "Open", path, QmitkIOUtil::GetFileOpenFilterString()); if (fileNames.empty()) { return; } d->SetLastFileOpenPath(fileNames.front()); mitk::WorkbenchUtil::LoadFiles(fileNames, berry::IWorkbenchWindow::Pointer(d->m_Window), d->GetOpenEditor()); }
25.114583
125
0.669432
zhaomengxiao
7ce77ec9347b82ef01455f6a7ab6f1304b65f116
605
cpp
C++
Strings/Words/Reverse the String.cpp
cenation092/InterviewBit-Solutions
ac4510a10d965fb681f7b3c80990407e18bc2668
[ "MIT" ]
7
2019-06-29T08:57:07.000Z
2021-02-13T06:43:40.000Z
Strings/Words/Reverse the String.cpp
cenation092/InterviewBit-Solutions
ac4510a10d965fb681f7b3c80990407e18bc2668
[ "MIT" ]
null
null
null
Strings/Words/Reverse the String.cpp
cenation092/InterviewBit-Solutions
ac4510a10d965fb681f7b3c80990407e18bc2668
[ "MIT" ]
3
2020-06-17T04:26:26.000Z
2021-02-12T04:51:40.000Z
void Solution::reverseWords(string &A) { reverse(A.begin(), A.end()); string s = ""; int i = 0; while( A[i] == ' ')i++; string temp = ""; while( i < A.size() && A[i] != ' ' ){ temp += A[i]; i++; } reverse(temp.begin(), temp.end()); s += temp; while( i < A.size() ){ temp = ""; while( i < A.size() && A[i] != ' ' ){ temp += A[i]; i++; } if( temp.size() > 0 ){ s += ' '; reverse(temp.begin(), temp.end()); s += temp; } i++; } A = s; }
21.607143
46
0.33719
cenation092
7ce9280eba22cc0b6b5fa464cec9212ece3cc0f2
5,930
cpp
C++
Sample18_2/app/src/main/cpp/util/LoadUtil.cpp
luopan007/Vulkan_Develpment_Samples
1be40631e3b2d44aae7140f0ef17c5643a86545e
[ "Unlicense" ]
5
2020-11-20T00:06:30.000Z
2021-12-07T11:39:17.000Z
Sample18_2/app/src/main/cpp/util/LoadUtil.cpp
luopan007/Vulkan_Develpment_Samples
1be40631e3b2d44aae7140f0ef17c5643a86545e
[ "Unlicense" ]
null
null
null
Sample18_2/app/src/main/cpp/util/LoadUtil.cpp
luopan007/Vulkan_Develpment_Samples
1be40631e3b2d44aae7140f0ef17c5643a86545e
[ "Unlicense" ]
7
2021-01-01T10:54:58.000Z
2022-01-13T02:21:54.000Z
#include "LoadUtil.h" #include <iostream> #include <string> #include <string.h> #include <math.h> #include <vector> #include <map> #include <set> #include <fstream> #include <sstream> #include <stdlib.h> #include <vulkan/vulkan.h> #include "FileUtil.h" using namespace std; size_t splitString(const string& strSrc, const string& strDelims, vector<string>& strDest) { string delims = strDelims; string STR; if (delims.empty()) delims = " **"; string::size_type pos = 0; string::size_type LEN = strSrc.size(); while (pos < LEN) { STR = ""; while ((delims.find(strSrc[pos]) != std::string::npos) && (pos < LEN)) { ++pos; } if (pos == LEN) { return strDest.size(); } while ((delims.find(strSrc[pos]) == std::string::npos) && (pos < LEN)) { STR += strSrc[pos++]; } if (!STR.empty()) { strDest.push_back(STR); } } return strDest.size(); } bool tryParseDouble(const char *s, const char *s_end, double *result) { if (s >= s_end) { return false; } double mantissa = 0.0; int exponent = 0; char sign = '+'; char exp_sign = '+'; char const *curr = s; int read = 0; bool end_not_reached = false; if (*curr == '+' || *curr == '-') { sign = *curr; curr++; } else if (isdigit(*curr)) { /* Pass through. */ } else { goto fail; } while ((end_not_reached = (curr != s_end)) && isdigit(*curr)) { mantissa *= 10; mantissa += static_cast<int>(*curr - 0x30); curr++; read++; } if (read == 0) goto fail; if (!end_not_reached) goto assemble; if (*curr == '.') { curr++; read = 1; while ((end_not_reached = (curr != s_end)) && isdigit(*curr)) { mantissa += static_cast<int>(*curr - 0x30) * pow(10.0, -read); read++; curr++; } } else if (*curr == 'e' || *curr == 'E') {} else { goto assemble; } if (!end_not_reached) goto assemble; if (*curr == 'e' || *curr == 'E') { curr++; if ((end_not_reached = (curr != s_end)) && (*curr == '+' || *curr == '-')) { exp_sign = *curr; curr++; } else if (isdigit(*curr)) { /* Pass through. */ } else { goto fail; } read = 0; while ((end_not_reached = (curr != s_end)) && isdigit(*curr)) { exponent *= 10; exponent += static_cast<int>(*curr - 0x30); curr++; read++; } exponent *= (exp_sign == '+' ? 1 : -1); if (read == 0) goto fail; } assemble: *result = (sign == '+' ? 1 : -1) * ldexp(mantissa * pow(5.0, exponent), exponent); return true; fail: return false; } float parseFloat(const char* token) { token += strspn(token, " \t"); #ifdef TINY_OBJ_LOADER_OLD_FLOAT_PARSER float f = atof(token); #else const char *end = token + strcspn(token, " \t\r"); double val = 0.0; tryParseDouble(token, end, &val); float f = static_cast<float>(val); #endif return f; } int parseInt(const char *token) { token += strspn(token, " \t"); int i = atoi(token); return i; } ObjObject* LoadUtil::loadFromFile(const string& vname, VkDevice& device, VkPhysicalDeviceMemoryProperties& memoryroperties) { ObjObject * lo; vector<float> alv; vector<float> alvResult; vector<float> aln; vector<float>alnResult; std::string resultStr = FileUtil::loadAssetStr(vname); vector<string> lines; splitString(resultStr, "\n", lines); vector<string> splitStrs; vector<string> splitStrsF; string tempContents; for (int i = 0; i<lines.size(); i++) { tempContents = lines[i]; if (tempContents.compare("") == 0) { continue; } string delims = "[ ]+"; splitStrs.clear(); splitString(tempContents, delims, splitStrs); if (splitStrs[0] == "v") { alv.push_back(parseFloat(splitStrs[1].c_str())); alv.push_back(parseFloat(splitStrs[2].c_str())); alv.push_back(parseFloat(splitStrs[3].c_str())); } else if (splitStrs[0] == "vn") { aln.push_back(parseFloat(splitStrs[1].c_str())); aln.push_back(parseFloat(splitStrs[2].c_str())); aln.push_back(parseFloat(splitStrs[3].c_str())); } else if (splitStrs[0] == "f") { int index[3]; string delimsF = "/"; splitStrsF.clear(); splitString(splitStrs[1].c_str(), delimsF, splitStrsF); index[0] = parseInt(splitStrsF[0].c_str()) - 1; alvResult.push_back(alv[3 * index[0]]); alvResult.push_back(alv[3 * index[0] + 1]); alvResult.push_back(alv[3 * index[0] + 2]); int indexN = parseInt(splitStrsF[2].c_str()) - 1; alnResult.push_back(aln[3 * indexN]); alnResult.push_back(aln[3 * indexN + 1]); alnResult.push_back(aln[3 * indexN + 2]); splitStrsF.clear(); splitString(splitStrs[2].c_str(), delimsF, splitStrsF); index[1] = parseInt(splitStrsF[0].c_str()) - 1; alvResult.push_back(alv[3 * index[1]]); alvResult.push_back(alv[3 * index[1] + 1]); alvResult.push_back(alv[3 * index[1] + 2]); indexN = parseInt(splitStrsF[2].c_str()) - 1; alnResult.push_back(aln[3 * indexN]); alnResult.push_back(aln[3 * indexN + 1]); alnResult.push_back(aln[3 * indexN + 2]); splitStrsF.clear(); splitString(splitStrs[3].c_str(), delimsF, splitStrsF); index[2] = parseInt(splitStrsF[0].c_str()) - 1; alvResult.push_back(alv[3 * index[2]]); alvResult.push_back(alv[3 * index[2] + 1]); alvResult.push_back(alv[3 * index[2] + 2]); indexN = parseInt(splitStrsF[2].c_str()) - 1; alnResult.push_back(aln[3 * indexN]); alnResult.push_back(aln[3 * indexN + 1]); alnResult.push_back(aln[3 * indexN + 2]); } splitStrs.clear(); } int vCount = (int)alvResult.size() / 3; int dataByteCount = vCount * 6 * sizeof(float); float* vdataIn = new float[vCount * 6]; int indexTemp = 0; for (int i = 0; i<vCount; i++) { vdataIn[indexTemp++] = alvResult[i * 3 + 0]; vdataIn[indexTemp++] = alvResult[i * 3 + 1]; vdataIn[indexTemp++] = alvResult[i * 3 + 2]; vdataIn[indexTemp++] = alnResult[i * 3 + 0]; vdataIn[indexTemp++] = alnResult[i * 3 + 1]; vdataIn[indexTemp++] = alnResult[i * 3 + 2]; } lo = new ObjObject(vdataIn, dataByteCount, vCount, device, memoryroperties); return lo; }
26.238938
125
0.616863
luopan007
7cec34c9a68fd99cd10d58595333207bf912a1d2
1,659
hpp
C++
src/common/interfaces/models/ibrush.hpp
squeevee/Addle
20ec4335669fbd88d36742f586899d8416920959
[ "MIT" ]
3
2020-03-05T06:36:51.000Z
2020-06-20T03:25:02.000Z
src/common/interfaces/models/ibrush.hpp
squeevee/Addle
20ec4335669fbd88d36742f586899d8416920959
[ "MIT" ]
13
2020-03-11T17:43:42.000Z
2020-12-11T03:36:05.000Z
src/common/interfaces/models/ibrush.hpp
squeevee/Addle
20ec4335669fbd88d36742f586899d8416920959
[ "MIT" ]
1
2020-09-28T06:53:46.000Z
2020-09-28T06:53:46.000Z
/** * Addle source code * @file * @copyright Copyright 2020 Eleanor Hawk * @copyright Modification and distribution permitted under the terms of the * MIT License. See "LICENSE" for full details. */ #ifndef IBRUSH_HPP #define IBRUSH_HPP #include <QIcon> #include <QList> #include "idtypes/brushid.hpp" #include "idtypes/brushengineid.hpp" #include "interfaces/traits.hpp" namespace Addle { class BrushBuilder; class IBrush { public: enum PreviewHint { Subtractive = 1 }; Q_DECLARE_FLAGS(PreviewHints, PreviewHint); virtual ~IBrush() = default; virtual void initialize(const BrushBuilder& builder) = 0; virtual BrushId id() const = 0; virtual BrushEngineId engineId() const = 0; virtual QIcon icon() const = 0; // Common engine parameters, like pressure and velocity dynamics, will be // given properties here. // virtual QVariantHash& customEngineParameters() = 0; virtual QVariantHash customEngineParameters() const = 0; virtual bool isSizeInvariant() const = 0; virtual bool isPixelAliased() const = 0; virtual bool eraserMode() const = 0; virtual bool copyMode() const = 0; virtual double minSize() const = 0; virtual double maxSize() const = 0; virtual QList<double> preferredSizes() const = 0; virtual bool strictSizing() const = 0; virtual double preferredStartingSize() const = 0; virtual PreviewHints previewHints() const = 0; }; Q_DECLARE_OPERATORS_FOR_FLAGS(IBrush::PreviewHints); DECL_PERSISTENT_OBJECT_TYPE(IBrush, BrushId); } // namespace Addle Q_DECLARE_INTERFACE(Addle::IBrush, "org.addle.IBrush") #endif // IBRUSH_HPP
24.043478
77
0.711272
squeevee
7cee371914c24f9202b2793f3b361442889bd441
12,268
cpp
C++
src/AdmittanceController.cpp
nbfigueroa-rlic/robot_admittance_controller
1136d0af2584d91f21416a0a5b5997f936fcba4a
[ "MIT" ]
25
2020-05-21T03:17:32.000Z
2022-03-18T07:16:08.000Z
src/AdmittanceController.cpp
nbfigueroa-rlic/robot_admittance_controller
1136d0af2584d91f21416a0a5b5997f936fcba4a
[ "MIT" ]
1
2020-08-14T02:49:21.000Z
2020-08-14T02:49:21.000Z
src/AdmittanceController.cpp
nbfigueroa-rlic/robot_admittance_controller
1136d0af2584d91f21416a0a5b5997f936fcba4a
[ "MIT" ]
9
2020-06-02T17:27:59.000Z
2021-12-18T08:56:38.000Z
#include "AdmittanceController.h" AdmittanceController::AdmittanceController(ros::NodeHandle &n, double frequency, std::string topic_arm_pose, std::string topic_arm_twist, std::string topic_external_wrench, std::string topic_control_wrench, std::string topic_arm_command, std::vector<double> M_a, std::vector<double> D_a, std::vector<double> workspace_limits, double arm_max_vel, double arm_max_acc) : nh_(n), loop_rate_(frequency), M_a_(M_a.data()), D_a_(D_a.data()), workspace_limits_(workspace_limits.data()), arm_max_vel_(arm_max_vel), arm_max_acc_(arm_max_acc){ // --- Subscribers --- // sub_arm_pose_ = nh_.subscribe(topic_arm_pose, 10, &AdmittanceController::pose_arm_callback, this, ros::TransportHints().reliable().tcpNoDelay()); std::string topic_arm_pose_arm = "/UR10arm/ee_pose_arm"; sub_arm_pose_arm_ = nh_.subscribe(topic_arm_pose_arm, 10, &AdmittanceController::pose_arm_arm_callback, this, ros::TransportHints().reliable().tcpNoDelay()); sub_arm_twist_ = nh_.subscribe(topic_arm_twist, 10, &AdmittanceController::twist_arm_callback, this, ros::TransportHints().reliable().tcpNoDelay()); sub_wrench_external_ = nh_.subscribe(topic_external_wrench, 5, &AdmittanceController::wrench_external_callback, this, ros::TransportHints().reliable().tcpNoDelay()); sub_wrench_control_ = nh_.subscribe(topic_control_wrench, 5, &AdmittanceController::wrench_control_callback, this, ros::TransportHints().reliable().tcpNoDelay()); // --- Publishers --- // pub_arm_cmd_ = nh_.advertise<geometry_msgs::Twist>(topic_arm_command, 5); // pub_wrench_external_ = nh_.advertise<geometry_msgs::WrenchStamped>( // topic_external_wrench_arm_frame, 5); // pub_wrench_control_ = nh_.advertise<geometry_msgs::WrenchStamped>( // topic_control_wrench_arm_frame, 5); ROS_INFO_STREAM("Arm max vel:" << arm_max_vel_ << " max acc:" << arm_max_acc_); // initializing the class variables wrench_external_.setZero(); wrench_control_.setZero(); ee_pose_world_.setZero(); ee_twist_world_.setZero(); // setting the robot state to zero and wait for data arm_real_position_.setZero(); while (nh_.ok() && !arm_real_position_(0)) { ROS_WARN_THROTTLE(1, "Waiting for the state of the arm..."); ros::spinOnce(); loop_rate_.sleep(); } // Init integrator arm_desired_twist_.setZero(); ft_arm_ready_ = false; arm_world_ready_ = false; world_arm_ready_ = false; wait_for_transformations(); } /////////////////////////////////////////////////////////////// ///////////////////// Control Loop //////////////////////////// /////////////////////////////////////////////////////////////// void AdmittanceController::run() { ROS_INFO("Running the admittance control loop ................."); while (nh_.ok()) { // Admittance Dynamics computation compute_admittance(); // sum the vel from admittance to DS in this function limit_to_workspace(); // Here I can do the "workspace-modulation" idea // Copy commands to messages send_commands_to_robot(); ros::spinOnce(); loop_rate_.sleep(); } } /////////////////////////////////////////////////////////////// ///////////////////// Admittance Dynamics ///////////////////// /////////////////////////////////////////////////////////////// void AdmittanceController::compute_admittance() { // Vector6d platform_desired_acceleration; Vector6d arm_desired_accelaration; arm_desired_accelaration = M_a_.inverse() * ( - D_a_ * arm_desired_twist_ + wrench_external_ + wrench_control_); // limiting the accelaration for better stability and safety double a_acc_norm = (arm_desired_accelaration.segment(0, 3)).norm(); if (a_acc_norm > arm_max_acc_) { ROS_WARN_STREAM_THROTTLE(1, "Admittance generates high arm accelaration!" << " norm: " << a_acc_norm); arm_desired_accelaration.segment(0, 3) *= (arm_max_acc_ / a_acc_norm); } // Integrate for velocity based interface ros::Duration duration = loop_rate_.expectedCycleTime(); arm_desired_twist_ += arm_desired_accelaration * duration.toSec(); } /////////////////////////////////////////////////////////////// ////////////////////////// Callbacks ////////////////////////// /////////////////////////////////////////////////////////////// void AdmittanceController::pose_arm_callback( const geometry_msgs::PoseConstPtr msg) { arm_real_position_ << msg->position.x, msg->position.y, msg->position.z; arm_real_orientation_.coeffs() << msg->orientation.x, msg->orientation.y, msg->orientation.z, msg->orientation.w; } void AdmittanceController::pose_arm_arm_callback( const geometry_msgs::PoseConstPtr msg) { arm_real_position_arm_ << msg->position.x, msg->position.y, msg->position.z; arm_real_orientation_arm_.coeffs() << msg->orientation.x, msg->orientation.y, msg->orientation.z, msg->orientation.w; } void AdmittanceController::twist_arm_callback( const geometry_msgs::TwistConstPtr msg) { arm_real_twist_ << msg->linear.x, msg->linear.y, msg->linear.z, msg->angular.x, msg->angular.y, msg->angular.z; } void AdmittanceController::wrench_external_callback( const geometry_msgs::WrenchStampedConstPtr msg) { Vector6d wrench_ft_frame; if (ft_arm_ready_) { // Reading the FT-sensor in its own frame (robotiq_force_torque_frame_id) wrench_ft_frame << msg->wrench.force.x, msg->wrench.force.y, msg->wrench.force.z, msg->wrench.torque.x, msg->wrench.torque.y, msg->wrench.torque.z; // --- This can be a callback! --- // get_rotation_matrix(rotation_tool_, listener_ft_, "base_link", "robotiq_force_torque_frame_id", 0 ); wrench_external_ << rotation_tool_ * wrench_ft_frame; } } void AdmittanceController::wrench_control_callback( const geometry_msgs::WrenchStampedConstPtr msg) { if (msg->header.frame_id == "arm_base_link") { wrench_control_ << msg->wrench.force.x, msg->wrench.force.y, msg->wrench.force.z, msg->wrench.torque.x, msg->wrench.torque.y, msg->wrench.torque.z; } else { ROS_WARN_THROTTLE(5, "wrench_control_callback: The frame_id is not specified as ur5_arm_base_link"); } } /////////////////////////////////////////////////////////////// //////////////////// COMMANDING THE ROBOT ///////////////////// /////////////////////////////////////////////////////////////// void AdmittanceController::send_commands_to_robot() { // for the arm geometry_msgs::Twist arm_twist_cmd; arm_twist_cmd.linear.x = arm_desired_twist_(0); arm_twist_cmd.linear.y = arm_desired_twist_(1); arm_twist_cmd.linear.z = arm_desired_twist_(2); arm_twist_cmd.angular.x = arm_desired_twist_(3); arm_twist_cmd.angular.y = arm_desired_twist_(4); arm_twist_cmd.angular.z = arm_desired_twist_(5); ROS_WARN_STREAM_THROTTLE(0.1,"Desired linear velocity: " << arm_twist_cmd.linear.x << " " << arm_twist_cmd.linear.y << " " << arm_twist_cmd.linear.z); ROS_WARN_STREAM_THROTTLE(0.1,"Desired angular velocity: " << arm_twist_cmd.angular.x << " " << arm_twist_cmd.angular.y << " " << arm_twist_cmd.angular.z); pub_arm_cmd_.publish(arm_twist_cmd); } void AdmittanceController::limit_to_workspace() { // velocity of the arm along x, y, and z axis double norm_vel_des = (arm_desired_twist_.segment(0, 3)).norm(); if (norm_vel_des > arm_max_vel_) { ROS_WARN_STREAM_THROTTLE(1, "Admittance generate fast arm movements! velocity norm: " << norm_vel_des); arm_desired_twist_.segment(0, 3) *= (arm_max_vel_ / norm_vel_des); } if (norm_vel_des < 1e-5) arm_desired_twist_.segment(0,3).setZero(); if (arm_desired_twist_(3) < 1e-5) arm_desired_twist_(3) = 0; if (arm_desired_twist_(4)< 1e-5) arm_desired_twist_(4) = 0; if (arm_desired_twist_(5) < 1e-5) arm_desired_twist_(5) = 0; // velocity of the arm along x, y, and z angles if (arm_desired_twist_(3) > 0.3) arm_desired_twist_(3) = 0.3; if (arm_desired_twist_(4) > 0.3) arm_desired_twist_(4) = 0.3; if (arm_desired_twist_(5) > 0.3) arm_desired_twist_(5) = 0.3; // Impose workspace constraints on desired velocities double ee_base_norm = (arm_real_position_arm_).norm(); double rec_operating_limit = 1.15; // simulated robot // double rec_operating_limit = 1; // real robot double dist_limit = rec_operating_limit - ee_base_norm; ROS_WARN_STREAM_THROTTLE(0.1, "||x_ee-w_limit||: " << dist_limit) ; if (ee_base_norm >= rec_operating_limit){ ROS_WARN_STREAM_THROTTLE(0.1, "Out of operational workspace limit!") ; base_position_ << 0.33000, 0.00000, 0.48600; Vector3d repulsive_field = -(arm_real_position_- base_position_); arm_desired_twist_.segment(0,3) = 0.05*(repulsive_field/ee_base_norm); ROS_WARN_STREAM_THROTTLE(0.1, "Bringing robot back slowly with uniform repulsive velocity field!") ; } if (arm_real_position_(2) < workspace_limits_(4)) arm_desired_twist_(2) += 0.3; // Continuous modulation of velocity to follow the surface (try walid/sina's modulation) double workspace_fct = dist_limit; if (dist_limit > 0.05) workspace_fct = 1; // workspace_fct *= norm_vel_des; // repulsive_field = workspace_fct * (repulsive_field/ee_base_norm); // ROS_WARN_STREAM_THROTTLE(0.1,"Repulsive velocity field: " << repulsive_field(0) << " " << repulsive_field(1) << " " << repulsive_field(2)); ROS_WARN_STREAM_THROTTLE(0.1,"Workspace Scaling function: " << workspace_fct); // arm_desired_twist_.segment(0,3) = workspace_fct*arm_desired_twist_.segment(0,3); } ////////////////////// /// INITIALIZATION /// ////////////////////// void AdmittanceController::wait_for_transformations() { tf::TransformListener listener; Matrix6d rot_matrix; rotation_base_.setZero(); rotation_tool_.setZero(); // Makes sure all TFs exists before enabling all transformations in the callbacks while (!get_rotation_matrix(rotation_base_, listener, "base_link", "arm_base_link", 1)) { sleep(1); } arm_world_ready_ = true; while (!get_rotation_matrix(rot_matrix, listener, "arm_base_link", "base_link", 0)) { sleep(1); } world_arm_ready_ = true; while (!get_rotation_matrix(rotation_tool_, listener, "base_link", "robotiq_force_torque_frame_id", 0)) { sleep(1); } ft_arm_ready_ = true; ROS_INFO("The Force/Torque sensor is ready to use."); } //////////// /// UTIL /// //////////// // Add a "get transformation" bool AdmittanceController::get_rotation_matrix(Matrix6d & rotation_matrix, tf::TransformListener & listener, std::string from_frame, std::string to_frame, bool getT) { tf::StampedTransform transform; Matrix3d rotation_from_to; try { listener.lookupTransform(from_frame, to_frame, ros::Time(0), transform); tf::matrixTFToEigen(transform.getBasis(), rotation_from_to); rotation_matrix.setZero(); rotation_matrix.topLeftCorner(3, 3) = rotation_from_to; rotation_matrix.bottomRightCorner(3, 3) = rotation_from_to; if (getT==1) base_position_ << transform.getOrigin().x(), transform.getOrigin().y(), transform.getOrigin().z() ; } catch (tf::TransformException ex) { rotation_matrix.setZero(); ROS_WARN_STREAM_THROTTLE(1, "Waiting for TF from: " << from_frame << " to: " << to_frame ); return false; } return true; }
36.082353
157
0.621536
nbfigueroa-rlic
7cf2a97a5b01882b2de3acf43af4fc9e2525da7d
2,166
cc
C++
IOMultiplexing/poll/poll_srv.cc
HONGYU-LEE/NetWorkProgram
0ce15d2211c56f635f8fde948632c16009d8d96f
[ "MIT" ]
null
null
null
IOMultiplexing/poll/poll_srv.cc
HONGYU-LEE/NetWorkProgram
0ce15d2211c56f635f8fde948632c16009d8d96f
[ "MIT" ]
null
null
null
IOMultiplexing/poll/poll_srv.cc
HONGYU-LEE/NetWorkProgram
0ce15d2211c56f635f8fde948632c16009d8d96f
[ "MIT" ]
null
null
null
#include<poll.h> #include<vector> #include <sys/socket.h> #include"TcpSocket.hpp" #define MAX_SIZE 10 using namespace std; int main(int argc, char* argv[]) { if(argc != 3) { cerr << "正确输入方式: ./select_srv.cc ip port\n" << endl; return -1; } string srv_ip = argv[1]; uint16_t srv_port = stoi(argv[2]); TcpSocket lst_socket; //创建监听套接字 CheckSafe(lst_socket.Socket()); //绑定地址信息 CheckSafe(lst_socket.Bind(srv_ip, srv_port)); //开始监听 CheckSafe(lst_socket.Listen()); struct pollfd poll_fd[MAX_SIZE]; poll_fd[0].fd = lst_socket.GetFd(); poll_fd[0].events = POLLIN; int i = 0, maxi = 0; for(i = 1; i < MAX_SIZE; i++) { poll_fd[i].fd = -1; } while(1) { int ret = poll(poll_fd, maxi + 1, 2000); if(ret < 0) { cerr << "not ready" << endl; continue; } else if(ret == 0) { cerr << "wait timeout" << endl; continue; } //监听套接字就绪则增加新连接 if(poll_fd[0].revents & (POLLIN | POLLERR)) { struct sockaddr_in addr; socklen_t len = sizeof(sockaddr_in); //创建一个新的套接字与客户端建立连接 int new_fd = accept(lst_socket.GetFd(), (sockaddr*)&addr, &len); for(i = 1; i < MAX_SIZE; i++) { if(poll_fd[i].fd == -1) { poll_fd[i].fd = new_fd; poll_fd[i].events = POLLIN; break; } } if(i > maxi) { maxi = i; } if(--ret <= 0) { continue; } } for(i = 1; i <= maxi; i++) { if(poll_fd[i].fd == -1) { continue; } if(poll_fd[i].revents & (POLLIN | POLLERR)) { //新数据到来 char buff[4096] = { 0 }; int ret = recv(poll_fd[i].fd, buff, 4096, 0); if(ret == 0) { std::cerr << "connect error" << std::endl; close(poll_fd[i].fd); poll_fd[i].fd = -1; } else if(ret < 0) { std::cerr << "recv error" << std::endl; close(poll_fd[i].fd); poll_fd[i].fd = -1; } else { cout << "cli send message: " << buff << endl; } if(--ret <= 0) { break; } } } } lst_socket.Close(); return 0; }
16.661538
67
0.495845
HONGYU-LEE
7cf504084893fb79c4ca0e3a7d8686499d78e081
5,719
hpp
C++
include/elemental/blas-like/level2/Syr.hpp
ahmadia/Elemental-1
f9a82c76a06728e9e04a4316e41803efbadb5a19
[ "BSD-3-Clause" ]
null
null
null
include/elemental/blas-like/level2/Syr.hpp
ahmadia/Elemental-1
f9a82c76a06728e9e04a4316e41803efbadb5a19
[ "BSD-3-Clause" ]
null
null
null
include/elemental/blas-like/level2/Syr.hpp
ahmadia/Elemental-1
f9a82c76a06728e9e04a4316e41803efbadb5a19
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2009-2013, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #pragma once #ifndef BLAS_SYR_HPP #define BLAS_SYR_HPP namespace elem { template<typename T> inline void Syr ( UpperOrLower uplo, T alpha, const Matrix<T>& x, Matrix<T>& A, bool conjugate=false ) { #ifndef RELEASE CallStackEntry entry("Syr"); if( A.Height() != A.Width() ) throw std::logic_error("A must be square"); if( x.Width() != 1 && x.Height() != 1 ) throw std::logic_error("x must be a vector"); const int xLength = ( x.Width()==1 ? x.Height() : x.Width() ); if( xLength != A.Height() ) throw std::logic_error("x must conform with A"); #endif const char uploChar = UpperOrLowerToChar( uplo ); const int m = A.Height(); const int incx = ( x.Width()==1 ? 1 : x.LDim() ); if( conjugate ) { blas::Her ( uploChar, m, alpha, x.LockedBuffer(), incx, A.Buffer(), A.LDim() ); } else { blas::Syr ( uploChar, m, alpha, x.LockedBuffer(), incx, A.Buffer(), A.LDim() ); } } template<typename T> inline void Syr ( UpperOrLower uplo, T alpha, const DistMatrix<T>& x, DistMatrix<T>& A, bool conjugate=false ) { #ifndef RELEASE CallStackEntry entry("Syr"); if( A.Grid() != x.Grid() ) throw std::logic_error ("A and x must be distributed over the same grid"); if( A.Height() != A.Width() ) throw std::logic_error("A must be square"); const int xLength = ( x.Width()==1 ? x.Height() : x.Width() ); if( A.Height() != xLength ) { std::ostringstream msg; msg << "A must conform with x: \n" << " A ~ " << A.Height() << " x " << A.Width() << "\n" << " x ~ " << x.Height() << " x " << x.Width() << "\n"; throw std::logic_error( msg.str() ); } #endif const Grid& g = A.Grid(); const int localHeight = A.LocalHeight(); const int localWidth = A.LocalWidth(); const int r = g.Height(); const int c = g.Width(); const int colShift = A.ColShift(); const int rowShift = A.RowShift(); if( x.Width() == 1 ) { DistMatrix<T,MC,STAR> x_MC_STAR(g); DistMatrix<T,MR,STAR> x_MR_STAR(g); x_MC_STAR.AlignWith( A ); x_MR_STAR.AlignWith( A ); //--------------------------------------------------------------------// x_MC_STAR = x; x_MR_STAR = x_MC_STAR; const T* xBuffer = x_MC_STAR.LockedBuffer(); if( uplo == LOWER ) { for( int jLocal=0; jLocal<localWidth; ++jLocal ) { const int j = rowShift + jLocal*c; const int heightAboveDiag = Length(j,colShift,r); const T beta = x_MR_STAR.GetLocal(jLocal,0); const T gamma = ( conjugate ? alpha*Conj(beta) : alpha*beta ); T* ACol = A.Buffer(0,jLocal); for( int iLocal=heightAboveDiag; iLocal<localHeight; ++iLocal ) ACol[iLocal] += gamma*xBuffer[iLocal]; } } else { for( int jLocal=0; jLocal<localWidth; ++jLocal ) { const int j = rowShift + jLocal*c; const int heightToDiag = Length(j+1,colShift,r); const T beta = x_MR_STAR.GetLocal(jLocal,0); const T gamma = ( conjugate ? alpha*Conj(beta) : alpha*beta ); T* ACol = A.Buffer(0,jLocal); for( int iLocal=0; iLocal<heightToDiag; ++iLocal ) ACol[iLocal] += gamma*xBuffer[iLocal]; } } //--------------------------------------------------------------------// x_MC_STAR.FreeAlignments(); x_MR_STAR.FreeAlignments(); } else { DistMatrix<T,STAR,MC> x_STAR_MC(g); DistMatrix<T,STAR,MR> x_STAR_MR(g); x_STAR_MC.AlignWith( A ); x_STAR_MR.AlignWith( A ); //--------------------------------------------------------------------// x_STAR_MR = x; x_STAR_MC = x_STAR_MR; const T* xBuffer = x_STAR_MC.LockedBuffer(); const int incx = x_STAR_MC.LDim(); if( uplo == LOWER ) { for( int jLocal=0; jLocal<localWidth; ++jLocal ) { const int j = rowShift + jLocal*c; const int heightAboveDiag = Length(j,colShift,r); const T beta = x_STAR_MR.GetLocal(0,jLocal); const T gamma = ( conjugate ? alpha*Conj(beta) : alpha*beta ); T* ACol = A.Buffer(0,jLocal); for( int iLocal=heightAboveDiag; iLocal<localHeight; ++iLocal ) ACol[iLocal] += gamma*xBuffer[iLocal*incx]; } } else { for( int jLocal=0; jLocal<localWidth; ++jLocal ) { const int j = rowShift + jLocal*c; const int heightToDiag = Length(j+1,colShift,r); const T beta = x_STAR_MR.GetLocal(0,jLocal); const T gamma = ( conjugate ? alpha*Conj(beta) : alpha*beta ); T* ACol = A.Buffer(0,jLocal); for( int iLocal=0; iLocal<heightToDiag; ++iLocal ) ACol[iLocal] += gamma*xBuffer[iLocal*incx]; } } //--------------------------------------------------------------------// x_STAR_MC.FreeAlignments(); x_STAR_MR.FreeAlignments(); } } } // namespace elem #endif // ifndef BLAS_SYR_HPP
32.867816
80
0.503934
ahmadia
7cf553e2bf5442978a22d937f8e2cf5584a52da9
2,018
cpp
C++
libs/base/src/ring_log.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
libs/base/src/ring_log.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
libs/base/src/ring_log.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
// This file is part of the Yttrium toolkit. // Copyright (C) Sergei Blagodarin. // SPDX-License-Identifier: Apache-2.0 #include "ring_log.h" #include <seir_base/int_utils.hpp> #include <algorithm> #include <cassert> #include <cstring> namespace { static_assert(seir::isPowerOf2(Yt::RingLog::BufferSize)); // If BufferSize is a power of two, we can wrap offsets using masking. constexpr auto OffsetMask = Yt::RingLog::BufferSize - 1; } namespace Yt { bool RingLog::pop(std::string& text) { if (_size == 0) return false; const auto text_offset = (_offset + 1) & OffsetMask; const auto text_size = size_t{ _buffer[_offset] }; _offset = (text_offset + text_size) & OffsetMask; assert(_size >= text_size + 1); _size -= text_size + 1; if (const auto continuous_size = _buffer.size() - text_offset; continuous_size < text_size) { text.assign(reinterpret_cast<const char*>(_buffer.data() + text_offset), continuous_size); text.append(reinterpret_cast<const char*>(_buffer.data()), text_size - continuous_size); } else text.assign(reinterpret_cast<const char*>(_buffer.data() + text_offset), text_size); return true; } void RingLog::push(std::string_view text) noexcept { const auto text_size = std::min(text.size(), MaxStringSize); while (text_size >= _buffer.size() - _size) { const auto skip = 1 + size_t{ _buffer[_offset] }; _offset = (_offset + skip) & OffsetMask; assert(_size >= skip); _size -= skip; } _buffer[(_offset + _size++) & OffsetMask] = static_cast<uint8_t>(text_size); const auto text_offset = (_offset + _size) & OffsetMask; if (const auto continuous_size = _buffer.size() - text_offset; continuous_size < text_size) { std::memcpy(_buffer.data() + text_offset, text.data(), continuous_size); std::memcpy(_buffer.data(), text.data() + continuous_size, text_size - continuous_size); } else std::memcpy(_buffer.data() + text_offset, text.data(), text_size); _size += text_size; assert(_size <= _buffer.size()); } }
31.046154
93
0.697721
blagodarin
7cf6473f1e8501b080c2e6ec1449e8cb4db9fe60
1,478
hpp
C++
HN_DateTime/HN_Clock.hpp
Jusdetalent/JT_Utility
2dec8ff0e8a0263a589f0829d63cf01dcae46d79
[ "MIT" ]
null
null
null
HN_DateTime/HN_Clock.hpp
Jusdetalent/JT_Utility
2dec8ff0e8a0263a589f0829d63cf01dcae46d79
[ "MIT" ]
null
null
null
HN_DateTime/HN_Clock.hpp
Jusdetalent/JT_Utility
2dec8ff0e8a0263a589f0829d63cf01dcae46d79
[ "MIT" ]
null
null
null
#ifndef HN_CLOCK_HPP_INCLUDED #define HN_CLOCK_HPP_INCLUDED #include <sys/time.h> #include <string> #include "HN_TimePoint.hpp" namespace hnapi { namespace datetime { // Time category definition enum HN_ClockMode{ HN_YEARS_MODE = 1, HN_MOUTHS_MODE = 2, HN_WEEKS_MODE = 3, HN_DAYS_MODE = 4, HN_HOURS_MODE = 5, HN_MINUTES_MODE = 6, HN_SECONDS_MODE = 7, HN_MILLISECONDS_MODE = 8, HN_MICROSECONDS_MODE = 9, HN_NANOSECONDS_MODE = 10, HN_TIMESTAMP_MODE = 11 }; // define ticks pointer us long long typedef long long HN_ClockPoint; // Clock class class HN_Clock { public: // Static Methods static HN_ClockPoint now(HN_ClockMode _mode); static HN_TimePoint makeNowTimePoint(void); static HN_TimePoint makeTimePoint( // Date data int _mday, int _mon, int _year, // Time data int _hour = 0, int _min = 0, int _sec = 0 ); static HN_TimePoint makeTimePoint(std::string date_time); static HN_TimePoint makeTimePoint(time_t timestamp); }; } } #endif // HN_CLOCK_H_INCLUDED
28.423077
74
0.504736
Jusdetalent
7cf7da24a72b18a9f275569f4b62621b471c2f10
6,386
cpp
C++
transport_catalogue/json/__tests__/json__tests.cpp
oleg-nazarov/cpp-yandex-praktikum
a09781c198b0aff469c4d1175c91d72800909bf2
[ "MIT" ]
1
2022-03-15T19:01:03.000Z
2022-03-15T19:01:03.000Z
transport_catalogue/json/__tests__/json__tests.cpp
oleg-nazarov/cpp-yandex-praktikum
a09781c198b0aff469c4d1175c91d72800909bf2
[ "MIT" ]
1
2022-03-15T19:11:59.000Z
2022-03-15T19:11:59.000Z
transport_catalogue/json/__tests__/json__tests.cpp
oleg-nazarov/cpp-yandex-praktikum
a09781c198b0aff469c4d1175c91d72800909bf2
[ "MIT" ]
null
null
null
#include <cassert> #include <chrono> #include <iostream> #include <sstream> #include <string_view> #include "../../../helpers/run_test.h" #include "../json.h" using namespace json; using namespace std::literals; namespace { json::Document LoadJSON(const std::string& s) { std::istringstream strm(s); return json::Load(strm); } std::string Print(const Node& node) { std::ostringstream out; Print(Document{node}, out); return out.str(); } void MustFailToLoad(const std::string& s) { try { LoadJSON(s); std::cerr << "ParsingError exception is expected on '"sv << s << "'"sv << std::endl; assert(false); } catch (const json::ParsingError&) { // ok } catch (const std::exception& e) { std::cerr << "exception thrown: "sv << e.what() << std::endl; assert(false); } catch (...) { std::cerr << "Unexpected error"sv << std::endl; assert(false); } } template <typename Fn> void MustThrowLogicError(Fn fn) { try { fn(); std::cerr << "logic_error is expected"sv << std::endl; assert(false); } catch (const std::logic_error&) { // ok } catch (const std::exception& e) { std::cerr << "exception thrown: "sv << e.what() << std::endl; assert(false); } catch (...) { std::cerr << "Unexpected error"sv << std::endl; assert(false); } } void TestNull() { Node null_node; assert(null_node.IsNull()); Node null_node1{nullptr}; assert(null_node1.IsNull()); assert(Print(null_node) == "null"s); const Node node = LoadJSON("null"s).GetRoot(); assert(node.IsNull()); assert(node == null_node); } void TestNumbers() { Node int_node{42}; assert(int_node.IsInt()); assert(int_node.AsInt() == 42); // целые числа являются подмножеством чисел с плавающей запятой assert(int_node.IsDouble()); // Когда узел хранит int, можно получить соответствующее ему double-значение assert(int_node.AsDouble() == 42.0); assert(!int_node.IsPureDouble()); Node dbl_node{123.45}; assert(dbl_node.IsDouble()); assert(dbl_node.AsDouble() == 123.45); assert(dbl_node.IsPureDouble()); // Значение содержит число с плавающей запятой assert(!dbl_node.IsInt()); assert(Print(int_node) == "42"s); assert(Print(dbl_node) == "123.45"s); assert(LoadJSON("42"s).GetRoot() == int_node); assert(LoadJSON("123.45"s).GetRoot() == dbl_node); assert(LoadJSON("0.25"s).GetRoot().AsDouble() == 0.25); assert(LoadJSON("3e5"s).GetRoot().AsDouble() == 3e5); assert(LoadJSON("1.2e-5"s).GetRoot().AsDouble() == 1.2e-5); assert(LoadJSON("1.2e+5"s).GetRoot().AsDouble() == 1.2e5); assert(LoadJSON("-123456"s).GetRoot().AsInt() == -123456); } void TestStrings() { Node str_node{"Hello, \"everybody\""s}; assert(str_node.IsString()); assert(str_node.AsString() == "Hello, \"everybody\""s); assert(!str_node.IsInt()); assert(!str_node.IsDouble()); assert(Print(str_node) == "\"Hello, \\\"everybody\\\"\""s); assert(LoadJSON(Print(str_node)).GetRoot() == str_node); } void TestStringEscapeSequences() { Node str_node = LoadJSON("\" \\r\\n \\\" \\t\\t \\\\ \""s).GetRoot(); assert(str_node.AsString() == " \r\n \" \t\t \\ "s); } void TestBool() { Node true_node{true}; assert(true_node.IsBool()); assert(true_node.AsBool()); Node false_node{false}; assert(false_node.IsBool()); assert(!false_node.AsBool()); assert(Print(true_node) == "true"s); assert(Print(false_node) == "false"s); assert(LoadJSON("true"s).GetRoot() == true_node); assert(LoadJSON("false"s).GetRoot() == false_node); } void TestArray() { Node arr_node{Array{1, 1.23, "Hello"s}}; assert(arr_node.IsArray()); const Array& arr = arr_node.AsArray(); assert(arr.size() == 3); assert(arr.at(0).AsInt() == 1); assert(LoadJSON("[1, 1.23, \"Hello\"]"s).GetRoot() == arr_node); assert(LoadJSON(Print(arr_node)).GetRoot() == arr_node); } void TestMap() { Node dict_node{Dict{{"key1"s, "value1"s}, {"key2"s, 42}}}; assert(dict_node.IsDict()); const Dict& dict = dict_node.AsDict(); assert(dict.size() == 2); assert(dict.at("key1"s).AsString() == "value1"s); assert(dict.at("key2"s).AsInt() == 42); assert(LoadJSON("{ \"key1\": \"value1\", \"key2\": 42 }"s).GetRoot() == dict_node); assert(LoadJSON(Print(dict_node)).GetRoot() == dict_node); } void TestErrorHandling() { MustFailToLoad("["s); MustFailToLoad("]"s); MustFailToLoad("{"s); MustFailToLoad("}"s); MustFailToLoad("\"hello"s); // незакрытая кавычка MustFailToLoad("tru"s); MustFailToLoad("fals"s); MustFailToLoad("nul"s); Node dbl_node{3.5}; MustThrowLogicError([&dbl_node] { dbl_node.AsInt(); }); MustThrowLogicError([&dbl_node] { dbl_node.AsString(); }); MustThrowLogicError([&dbl_node] { dbl_node.AsArray(); }); Node array_node{Array{}}; MustThrowLogicError([&array_node] { array_node.AsDict(); }); MustThrowLogicError([&array_node] { array_node.AsDouble(); }); MustThrowLogicError([&array_node] { array_node.AsBool(); }); } void Benchmark() { const auto start = std::chrono::steady_clock::now(); Array arr; arr.reserve(1'000); for (int i = 0; i < 1'000; ++i) { arr.emplace_back(Dict{ {"int"s, 42}, {"double"s, 42.1}, {"null"s, nullptr}, {"string"s, "hello"s}, {"array"s, Array{1, 2, 3}}, {"bool"s, true}, {"map"s, Dict{{"key"s, "value"s}}}, }); } std::stringstream strm; json::Print(Document{arr}, strm); const auto doc = json::Load(strm); assert(doc.GetRoot().AsArray() == arr); const auto duration = std::chrono::steady_clock::now() - start; std::cout << "Benchmark: "s << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() << "ms"sv << std::endl; } } // namespace int main() { RUN_TEST(TestNull); RUN_TEST(TestNumbers); RUN_TEST(TestStrings); RUN_TEST(TestStringEscapeSequences); RUN_TEST(TestBool); RUN_TEST(TestArray); RUN_TEST(TestMap); RUN_TEST(TestErrorHandling); RUN_TEST(Benchmark); return 0; } // namespace
27.407725
130
0.596461
oleg-nazarov
7cf85529ae0d2819353905e342e817e744fec06c
4,434
cxx
C++
main/basebmp/source/polypolygonrenderer.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/basebmp/source/polypolygonrenderer.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/basebmp/source/polypolygonrenderer.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. * *************************************************************/ #include "basebmp/polypolygonrenderer.hxx" #include <algorithm> namespace basebmp { namespace detail { sal_uInt32 setupGlobalEdgeTable( VectorOfVectorOfVertices& rGET, basegfx::B2DPolyPolygon const& rPolyPoly, sal_Int32 nMinY ) { sal_Int32 const nNumScanlines( (sal_Int32)rGET.size() ); // add all polygons to GET for( sal_uInt32 i(0), nCount(rPolyPoly.count()); i<nCount; ++i ) { // add all vertices to GET const basegfx::B2DPolygon& rPoly( rPolyPoly.getB2DPolygon(i) ); for( sal_uInt32 k(0), nVertices(rPoly.count()); k<nVertices; ++k ) { const basegfx::B2DPoint& rP1( rPoly.getB2DPoint(k) ); const basegfx::B2DPoint& rP2( rPoly.getB2DPoint( (k + 1) % nVertices ) ); const sal_Int32 nVertexYP1( basegfx::fround(rP1.getY()) ); const sal_Int32 nVertexYP2( basegfx::fround(rP2.getY()) ); // insert only vertices which are not strictly // horizontal. Strictly horizontal vertices don't add // any information that is not already present - due // to their adjacent vertices. if(nVertexYP1 != nVertexYP2) { if( nVertexYP2 < nVertexYP1 ) { const sal_Int32 nStartScanline(nVertexYP2 - nMinY); // edge direction is upwards - add with swapped vertices if( nStartScanline < nNumScanlines ) rGET[ nStartScanline ].push_back( Vertex(rP2, rP1, false) ); } else { const sal_Int32 nStartScanline(nVertexYP1 - nMinY); if( nStartScanline < nNumScanlines ) rGET[ nStartScanline ].push_back( Vertex(rP1, rP2, true) ); } } } } // now sort all scanlines individually, with increasing x // coordinates VectorOfVectorOfVertices::iterator aIter( rGET.begin() ); const VectorOfVectorOfVertices::iterator aEnd( rGET.end() ); sal_uInt32 nVertexCount(0); RasterConvertVertexComparator aComp; while( aIter != aEnd ) { std::sort( aIter->begin(), aIter->end(), aComp ); nVertexCount += aIter->size(); ++aIter; } return nVertexCount; } void sortAET( VectorOfVertexPtr& rAETSrc, VectorOfVertexPtr& rAETDest ) { static RasterConvertVertexComparator aComp; rAETDest.clear(); // prune AET from ended edges VectorOfVertexPtr::iterator iter( rAETSrc.begin() ); VectorOfVertexPtr::iterator const end( rAETSrc.end() ); while( iter != end ) { if( (*iter)->mnYCounter > 0 ) rAETDest.push_back( *iter ); ++iter; } // stable sort is necessary, to avoid segment crossing where // none was intended. std::stable_sort( rAETDest.begin(), rAETDest.end(), aComp ); } } // namespace detail } // namespace basebmp
35.758065
89
0.533829
Grosskopf
7cf87a8d1cc883576c03473d174f297c4087aaa3
81,920
cpp
C++
T3000/T3000CO2_NET/CT3000CO2_NET.cpp
DHSERVICE56/T3000_Building_Automation_System
77bd47a356211b1c8ad09fb8d785e9f880d3cd26
[ "MIT" ]
1
2019-12-11T05:14:08.000Z
2019-12-11T05:14:08.000Z
T3000/T3000CO2_NET/CT3000CO2_NET.cpp
DHSERVICE56/T3000_Building_Automation_System
77bd47a356211b1c8ad09fb8d785e9f880d3cd26
[ "MIT" ]
null
null
null
T3000/T3000CO2_NET/CT3000CO2_NET.cpp
DHSERVICE56/T3000_Building_Automation_System
77bd47a356211b1c8ad09fb8d785e9f880d3cd26
[ "MIT" ]
1
2021-05-31T18:56:31.000Z
2021-05-31T18:56:31.000Z
///////////////////////////////// Includes ////////////////////////////////// #include "stdafx.h" #include "CT3000CO2_NET.h" //////////////////////////////// Statics / Macros ///////////////////////////// #ifdef _DEBUG #define new DEBUG_NEW #endif ////////////////////////////////// Implementation ///////////////////////////// IMPLEMENT_DYNAMIC(CCT3000CO2_NET, CWnd) CCT3000CO2_NET::CCT3000CO2_NET() : m_DirectFunction(0), m_DirectPointer(0) { } BOOL CCT3000CO2_NET::Create(DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, DWORD dwExStyle, LPVOID lpParam) { //Call our base class implementation of CWnd::CreateEx BOOL bSuccess = CreateEx(dwExStyle, _T("scintilla"), NULL, dwStyle, rect, pParentWnd, nID, lpParam); //Setup the direct access data if (bSuccess) SetupDirectAccess(); //If we are running as Unicode, then use the UTF8 codepage #ifdef _UNICODE SetCodePage(SC_CP_UTF8); #endif return bSuccess; } void CCT3000CO2_NET::SetupDirectAccess() { //Setup the direct access data m_DirectFunction = GetDirectFunction(); m_DirectPointer = GetDirectPointer(); } CCT3000CO2_NET::~CCT3000CO2_NET() { DestroyWindow(); } inline LRESULT CCT3000CO2_NET::Call(UINT message, WPARAM wParam, LPARAM lParam, BOOL bDirect) { ASSERT(::IsWindow(m_hWnd)); //Window must be valid if (bDirect) { ASSERT(m_DirectFunction); //Direct function must be valid return (reinterpret_cast<SciFnDirect>(m_DirectFunction))(m_DirectPointer, message, wParam, lParam); } else return SendMessage(message, wParam, lParam); } LRESULT CCT3000CO2_NET::GetDirectFunction() { return SendMessage(SCI_GETDIRECTFUNCTION, 0, 0); } LRESULT CCT3000CO2_NET::GetDirectPointer() { return SendMessage(SCI_GETDIRECTPOINTER, 0, 0); } CString CCT3000CO2_NET::GetSelText() { //Call the function which does the work CString sSelText; GetSelText(sSelText.GetBufferSetLength(GetSelectionEnd() - GetSelectionStart())); sSelText.ReleaseBuffer(); return sSelText; } #ifdef _UNICODE int CCT3000CO2_NET::W2UTF8(const wchar_t* pszText, int nLength, char*& pszUTF8Text) { //Validate our parameters ASSERT(pszText); //First call the function to determine how much heap space we need to allocate int nUTF8Length = WideCharToMultiByte(CP_UTF8, 0, pszText, nLength, NULL, 0, NULL, NULL); //If the calculated length is zero, then ensure we have at least room for a NULL terminator if (nUTF8Length == 0) nUTF8Length = 1; //Now allocate the heap space pszUTF8Text = new char[nUTF8Length]; pszUTF8Text[0] = '\0'; //And now recall with the buffer to get the converted text int nCharsWritten = WideCharToMultiByte(CP_UTF8, 0, pszText, nLength, pszUTF8Text, nUTF8Length, NULL, NULL); if (nLength != -1) return nCharsWritten; //Trust the return value else return nCharsWritten ? nCharsWritten - 1 : 0; //Exclude the NULL terminator written } int CCT3000CO2_NET::UTF82W(const char* pszText, int nLength, wchar_t*& pszWText) { //Validate our parameters ASSERT(pszText); //First call the function to determine how much heap space we need to allocate int nWideLength = MultiByteToWideChar(CP_UTF8, 0, pszText, nLength, NULL, 0); //If the calculated length is zero, then ensure we have at least room for a NULL terminator if (nWideLength == 0) nWideLength = 1; //Now allocate the heap space pszWText = new wchar_t[nWideLength]; pszWText[0] = '\0'; //And now recall with the buffer to get the converted text int nCharsWritten = MultiByteToWideChar(CP_UTF8, 0, pszText, nLength, pszWText, nWideLength); if (nLength != -1) return nCharsWritten; //Trust the return value else return nCharsWritten ? nCharsWritten - 1 : 0; //Exclude the NULL terminator written } void CCT3000CO2_NET::AddText(int length, const wchar_t* text, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; int nUTF8Length = W2UTF8(text, length, pszUTF8); //Call the native scintilla version of the function with the UTF8 text AddText(nUTF8Length, pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; } void CCT3000CO2_NET::InsertText(long pos, const wchar_t* text, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; W2UTF8(text, -1, pszUTF8); //Call the native scintilla version of the function with the UTF8 text InsertText(pos, pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; } int CCT3000CO2_NET::GetSelText(wchar_t* text, BOOL bDirect) { //Allocate some heap memory to contain the UTF8 text char* pszUTF8 = new char[GetSelectionEnd() - GetSelectionStart() + 1]; //Call the function which does the work GetSelText(pszUTF8, bDirect); //Now convert the UTF8 text back to Unicode wchar_t* pszWText; int nWLength = UTF82W(pszUTF8, -1, pszWText); ASSERT(text); #if (_MSC_VER >= 1400) wcscpy_s(text, nWLength+1, pszWText); #else wcscpy(text, pszWText); #endif //Tidy up the heap memory before we return delete [] pszWText; delete [] pszUTF8; return nWLength; } int CCT3000CO2_NET::GetCurLine(int length, wchar_t* text, BOOL bDirect) { //Allocate some heap memory to contain the UTF8 text int nUTF8Length = text ? length*4 : GetCurLine(0, static_cast<char*>(NULL), bDirect)*4; char* pszUTF8 = new char[nUTF8Length]; //A Unicode character can take up to 4 octets when expressed as UTF8 //Call the function which does the work int nOriginalReturn = GetCurLine(nUTF8Length, pszUTF8, bDirect); //Now convert the UTF8 text back to Unicode wchar_t* pszWText; int nReturnLength = UTF82W(pszUTF8, -1, pszWText); int nReturn = nReturnLength + 1; if (text) { //Copy as much text as possible into the output parameter int i; for (i=0; i<length-1 && i<nReturnLength; i++) text[i] = pszWText[i]; text[i] = L'\0'; //What we have text to return, use the original return value nReturn = nOriginalReturn; } //Tidy up the heap memory before we return delete [] pszWText; delete [] pszUTF8; return nReturn; } void CCT3000CO2_NET::StyleSetFont(int style, const wchar_t* fontName, BOOL bDirect) { char* pszUTF8; W2UTF8(fontName, -1, pszUTF8); StyleSetFont(style, pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; } void CCT3000CO2_NET::SetWordChars(const wchar_t* characters, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; W2UTF8(characters, -1, pszUTF8); SetWordChars(pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; } void CCT3000CO2_NET::AutoCShow(int lenEntered, const wchar_t* itemList, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; W2UTF8(itemList, -1, pszUTF8); //Call the native scintilla version of the function with the UTF8 text AutoCShow(lenEntered, pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; } void CCT3000CO2_NET::AutoCStops(const wchar_t* characterSet, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; W2UTF8(characterSet, -1, pszUTF8); //Call the native scintilla version of the function with the UTF8 text AutoCStops(pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; } void CCT3000CO2_NET::AutoCSelect(const wchar_t* text, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; W2UTF8(text, -1, pszUTF8); //Call the native scintilla version of the function with the UTF8 text AutoCSelect(pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; } void CCT3000CO2_NET::AutoCSetFillUps(const wchar_t* characterSet, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; W2UTF8(characterSet, -1, pszUTF8); //Call the native scintilla version of the function with the UTF8 text AutoCSetFillUps(pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; } void CCT3000CO2_NET::UserListShow(int listType, const wchar_t* itemList, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; W2UTF8(itemList, -1, pszUTF8); //Call the native scintilla version of the function with the UTF8 text UserListShow(listType, pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; } int CCT3000CO2_NET::GetLine(int line, wchar_t* text, BOOL bDirect) { //Validate our parameters ASSERT(text); //Work out how big the input buffer is (for details on this, see the EM_GETLINE documentation) WORD* wBuffer = reinterpret_cast<WORD*>(text); WORD wInputBufferSize = wBuffer[0]; //Allocate some heap memory to contain the UTF8 text int nUTF8Length = wInputBufferSize*4; char* pszUTF8 = new char[nUTF8Length]; //A Unicode character can take up to 4 octets when expressed as UTF8 //Set the buffer size in the new buffer wBuffer = reinterpret_cast<WORD*>(pszUTF8); wBuffer[0] = wInputBufferSize; //Call the function which does the work int nChars = GetLine(line, pszUTF8, bDirect); //Now convert the UTF8 text back to Unicode wchar_t* pszWText; int nWLength = UTF82W(pszUTF8, nChars, pszWText); for (int i=0; i<=nWLength && i<=wInputBufferSize; i++) text[i] = pszWText[i]; //Tidy up the heap memory before we return delete [] pszWText; delete [] pszUTF8; return nWLength; } void CCT3000CO2_NET::ReplaceSel(const wchar_t* text, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; W2UTF8(text, -1, pszUTF8); //Call the native scintilla version of the function with the UTF8 text ReplaceSel(pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; } void CCT3000CO2_NET::SetText(const wchar_t* text, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; W2UTF8(text, -1, pszUTF8); //Call the native scintilla version of the function with the UTF8 text SetText(pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; } int CCT3000CO2_NET::GetText(int length, wchar_t* text, BOOL bDirect) { //Allocate some heap memory to contain the UTF8 text int nUTF8Length = length*4; char* pszUTF8 = new char[nUTF8Length]; //A Unicode character can take up to 4 octets when expressed as UTF8 //Call the function which does the work GetText(nUTF8Length, pszUTF8, bDirect); //Now convert the UTF8 text back to Unicode wchar_t* pszWText; int nWLength = UTF82W(pszUTF8, -1, pszWText); //Copy as much text as possible into the output parameter ASSERT(text); int i; for (i=0; i<length-1 && i<nWLength; i++) text[i] = pszWText[i]; text[i] = L'\0'; //Tidy up the heap memory before we return delete [] pszWText; delete [] pszUTF8; return nWLength; } int CCT3000CO2_NET::ReplaceTarget(int length, const wchar_t* text, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; int nUTF8Length = W2UTF8(text, length, pszUTF8); //Call the native scintilla version of the function with the UTF8 text int nReturn = ReplaceTarget(nUTF8Length, pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; return nReturn; } int CCT3000CO2_NET::ReplaceTargetRE(int length, const wchar_t* text, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; int nUTF8Length = W2UTF8(text, length, pszUTF8); //Call the native scintilla version of the function with the UTF8 text int nReturn = ReplaceTargetRE(nUTF8Length, pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; return nReturn; } int CCT3000CO2_NET::SearchInTarget(int length, const wchar_t* text, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; int nUTF8Length = W2UTF8(text, length, pszUTF8); //Call the native scintilla version of the function with the UTF8 text int nReturn = SearchInTarget(nUTF8Length, pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; return nReturn; } void CCT3000CO2_NET::CallTipShow(long pos, const wchar_t* definition, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; W2UTF8(definition, -1, pszUTF8); //Call the native scintilla version of the function with the UTF8 text CallTipShow(pos, pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; } int CCT3000CO2_NET::TextWidth(int style, const wchar_t* text, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; W2UTF8(text, -1, pszUTF8); //Call the native scintilla version of the function with the UTF8 text int nReturn = TextWidth(style, pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; return nReturn; } void CCT3000CO2_NET::AppendText(int length, const wchar_t* text, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; int nUTF8Length = W2UTF8(text, length, pszUTF8); //Call the native scintilla version of the function with the UTF8 text AppendText(nUTF8Length, pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; } int CCT3000CO2_NET::SearchNext(int flags, const wchar_t* text, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; W2UTF8(text, -1, pszUTF8); //Call the native scintilla version of the function with the UTF8 text int nReturn = SearchNext(flags, pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; return nReturn; } int CCT3000CO2_NET::SearchPrev(int flags, const wchar_t* text, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; W2UTF8(text, -1, pszUTF8); //Call the native scintilla version of the function with the UTF8 text int nReturn = SearchPrev(flags, pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; return nReturn; } void CCT3000CO2_NET::CopyText(int length, const wchar_t* text, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; int nUTF8Length = W2UTF8(text, length, pszUTF8); //Call the native scintilla version of the function with the UTF8 text CopyText(nUTF8Length, pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; } void CCT3000CO2_NET::SetWhitespaceChars(const wchar_t* characters, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; W2UTF8(characters, -1, pszUTF8); //Call the native scintilla version of the function with the UTF8 text SetWhitespaceChars(pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; } void CCT3000CO2_NET::SetProperty(const wchar_t* key, const wchar_t* value, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8Key; W2UTF8(key, -1, pszUTF8Key); char* pszUTF8Value; W2UTF8(value, -1, pszUTF8Value); //Call the native scintilla version of the function with the UTF8 text SetProperty(pszUTF8Key, pszUTF8Value, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8Value; delete [] pszUTF8Key; } void CCT3000CO2_NET::SetKeyWords(int keywordSet, const wchar_t* keyWords, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; W2UTF8(keyWords, -1, pszUTF8); //Call the native scintilla version of the function with the UTF8 text SetKeyWords(keywordSet, pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; } void CCT3000CO2_NET::SetLexerLanguage(const wchar_t* language, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; W2UTF8(language, -1, pszUTF8); //Call the native scintilla version of the function with the UTF8 text SetLexerLanguage(pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; } void CCT3000CO2_NET::LoadLexerLibrary(const wchar_t* path, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; W2UTF8(path, -1, pszUTF8); //Call the native scintilla version of the function with the UTF8 text LoadLexerLibrary(pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; } int CCT3000CO2_NET::GetProperty(const wchar_t* key, wchar_t* buf, BOOL bDirect) { //Validate our parameters ASSERT(key); //Convert the Key value to UTF8 char* pszUTF8Key; W2UTF8(key, -1, pszUTF8Key); //Allocate some heap memory to contain the UTF8 text int nUTF8ValueLength = GetProperty(pszUTF8Key, 0, bDirect); char* pszUTF8Value = new char[nUTF8ValueLength + 1]; //Don't forget the NULL terminator //Call the function which does the work GetProperty(pszUTF8Key, pszUTF8Value, bDirect); //Now convert the UTF8 text back to Unicode wchar_t* pszWText; int nWLength = UTF82W(pszUTF8Value, -1, pszWText); if (buf) #if (_MSC_VER >= 1400) wcscpy_s(buf, nWLength+1, pszWText); #else wcscpy(buf, pszWText); #endif //Tidy up the heap memory before we return delete [] pszWText; delete [] pszUTF8Value; delete [] pszUTF8Key; return nWLength; } int CCT3000CO2_NET::GetPropertyExpanded(const wchar_t* key, wchar_t* buf, BOOL bDirect) { //Validate our parameters ASSERT(key); //Convert the Key value to UTF8 char* pszUTF8Key; W2UTF8(key, -1, pszUTF8Key); //Allocate some heap memory to contain the UTF8 text int nUTF8ValueLength = GetPropertyExpanded(pszUTF8Key, 0, bDirect); char* pszUTF8Value = new char[nUTF8ValueLength + 1]; //Don't forget the NULL terminator //Call the function which does the work GetPropertyExpanded(pszUTF8Key, pszUTF8Value, bDirect); //Now convert the UTF8 text back to Unicode wchar_t* pszWText; int nWLength = UTF82W(pszUTF8Value, -1, pszWText); if (buf) #if (_MSC_VER >= 1400) wcscpy_s(buf, nWLength+1, pszWText); #else wcscpy(buf, pszWText); #endif //Tidy up the heap memory before we return delete [] pszWText; delete [] pszUTF8Value; delete [] pszUTF8Key; return nWLength; } int CCT3000CO2_NET::GetPropertyInt(const wchar_t* key, BOOL bDirect) { //Convert the unicode text to UTF8 char* pszUTF8; W2UTF8(key, -1, pszUTF8); //Call the native scintilla version of the function with the UTF8 text int nReturn = GetPropertyInt(pszUTF8, bDirect); //Tidy up the heap memory before we return delete [] pszUTF8; return nReturn; } int CCT3000CO2_NET::StyleGetFont(int style, wchar_t* fontName, BOOL bDirect) { //Allocate a UTF8 buffer to contain the font name. See the notes for //SCI_STYLEGETFONT / SCI_STYLESETFONT on the reasons why we can use //a statically sized buffer of 32 characters in size. Note it is 33 below //to include space for the NULL terminator char szUTF8FontName[33*4]; //A Unicode character can take up to 4 octets when expressed as UTF8 //Call the native scintilla version of the function with a UTF8 text buffer int nReturn = StyleGetFont(style, szUTF8FontName, bDirect); //Now convert the UTF8 text back to Unicode wchar_t* pszWFontName; int nWLength = UTF82W(szUTF8FontName, -1, pszWFontName); if (fontName) #if (_MSC_VER >= 1400) wcscpy_s(fontName, nWLength+1, pszWFontName); #else wcscpy(fontName, pszWFontName); nWLength; //To get rid of "local variable is initialized but not referenced" warning when compiled in VC 6 #endif //Tidy up the heap memory before we return delete [] pszWFontName; return nReturn; } #endif //#ifdef _UNICODE int CCT3000CO2_NET::GetLineEx(int line, TCHAR* text, int nMaxChars, BOOL bDirect) { //Validate out parameters ASSERT(text); //Explicitly set the first value of text to nMaxChars (for details on this, see the EM_GETLINE documentation) WORD* wBuffer = reinterpret_cast<WORD*>(text); wBuffer[0] = nMaxChars; //now call off to the other implementation to do the real work return GetLine(line, text, bDirect); } //Everything else after this point was auto generated using the "ConvertScintillaiface.js" script void CCT3000CO2_NET::AddText(int length, const char* text, BOOL bDirect) { Call(SCI_ADDTEXT, static_cast<WPARAM>(length), reinterpret_cast<LPARAM>(text), bDirect); } void CCT3000CO2_NET::AddStyledText(int length, char* c, BOOL bDirect) { Call(SCI_ADDSTYLEDTEXT, static_cast<WPARAM>(length), reinterpret_cast<LPARAM>(c), bDirect); } void CCT3000CO2_NET::InsertText(long pos, const char* text, BOOL bDirect) { Call(SCI_INSERTTEXT, static_cast<WPARAM>(pos), reinterpret_cast<LPARAM>(text), bDirect); } void CCT3000CO2_NET::ClearAll(BOOL bDirect) { Call(SCI_CLEARALL, 0, 0, bDirect); } void CCT3000CO2_NET::ClearDocumentStyle(BOOL bDirect) { Call(SCI_CLEARDOCUMENTSTYLE, 0, 0, bDirect); } int CCT3000CO2_NET::GetLength(BOOL bDirect) { return Call(SCI_GETLENGTH, 0, 0, bDirect); } int CCT3000CO2_NET::GetCharAt(long pos, BOOL bDirect) { return Call(SCI_GETCHARAT, static_cast<WPARAM>(pos), 0, bDirect); } long CCT3000CO2_NET::GetCurrentPos(BOOL bDirect) { return Call(SCI_GETCURRENTPOS, 0, 0, bDirect); } long CCT3000CO2_NET::GetAnchor(BOOL bDirect) { return Call(SCI_GETANCHOR, 0, 0, bDirect); } int CCT3000CO2_NET::GetStyleAt(long pos, BOOL bDirect) { return Call(SCI_GETSTYLEAT, static_cast<WPARAM>(pos), 0, bDirect); } void CCT3000CO2_NET::Redo(BOOL bDirect) { Call(SCI_REDO, 0, 0, bDirect); } void CCT3000CO2_NET::SetUndoCollection(BOOL collectUndo, BOOL bDirect) { Call(SCI_SETUNDOCOLLECTION, static_cast<WPARAM>(collectUndo), 0, bDirect); } void CCT3000CO2_NET::SelectAll(BOOL bDirect) { Call(SCI_SELECTALL, 0, 0, bDirect); } void CCT3000CO2_NET::SetSavePoint(BOOL bDirect) { Call(SCI_SETSAVEPOINT, 0, 0, bDirect); } int CCT3000CO2_NET::GetStyledText(TextRange* tr, BOOL bDirect) { return Call(SCI_GETSTYLEDTEXT, 0, reinterpret_cast<LPARAM>(tr), bDirect); } BOOL CCT3000CO2_NET::CanRedo(BOOL bDirect) { return Call(SCI_CANREDO, 0, 0, bDirect); } int CCT3000CO2_NET::MarkerLineFromHandle(int handle, BOOL bDirect) { return Call(SCI_MARKERLINEFROMHANDLE, static_cast<WPARAM>(handle), 0, bDirect); } void CCT3000CO2_NET::MarkerDeleteHandle(int handle, BOOL bDirect) { Call(SCI_MARKERDELETEHANDLE, static_cast<WPARAM>(handle), 0, bDirect); } BOOL CCT3000CO2_NET::GetUndoCollection(BOOL bDirect) { return Call(SCI_GETUNDOCOLLECTION, 0, 0, bDirect); } int CCT3000CO2_NET::GetViewWS(BOOL bDirect) { return Call(SCI_GETVIEWWS, 0, 0, bDirect); } void CCT3000CO2_NET::SetViewWS(int viewWS, BOOL bDirect) { Call(SCI_SETVIEWWS, static_cast<WPARAM>(viewWS), 0, bDirect); } long CCT3000CO2_NET::PositionFromPoint(int x, int y, BOOL bDirect) { return Call(SCI_POSITIONFROMPOINT, static_cast<WPARAM>(x), static_cast<LPARAM>(y), bDirect); } long CCT3000CO2_NET::PositionFromPointClose(int x, int y, BOOL bDirect) { return Call(SCI_POSITIONFROMPOINTCLOSE, static_cast<WPARAM>(x), static_cast<LPARAM>(y), bDirect); } void CCT3000CO2_NET::GotoLine(int line, BOOL bDirect) { Call(SCI_GOTOLINE, static_cast<WPARAM>(line), 0, bDirect); } void CCT3000CO2_NET::GotoPos(long pos, BOOL bDirect) { Call(SCI_GOTOPOS, static_cast<WPARAM>(pos), 0, bDirect); } void CCT3000CO2_NET::SetAnchor(long posAnchor, BOOL bDirect) { Call(SCI_SETANCHOR, static_cast<WPARAM>(posAnchor), 0, bDirect); } int CCT3000CO2_NET::GetCurLine(int length, char* text, BOOL bDirect) { return Call(SCI_GETCURLINE, static_cast<WPARAM>(length), reinterpret_cast<LPARAM>(text), bDirect); } long CCT3000CO2_NET::GetEndStyled(BOOL bDirect) { return Call(SCI_GETENDSTYLED, 0, 0, bDirect); } void CCT3000CO2_NET::ConvertEOLs(int eolMode, BOOL bDirect) { Call(SCI_CONVERTEOLS, static_cast<WPARAM>(eolMode), 0, bDirect); } int CCT3000CO2_NET::GetEOLMode(BOOL bDirect) { return Call(SCI_GETEOLMODE, 0, 0, bDirect); } void CCT3000CO2_NET::SetEOLMode(int eolMode, BOOL bDirect) { Call(SCI_SETEOLMODE, static_cast<WPARAM>(eolMode), 0, bDirect); } void CCT3000CO2_NET::StartStyling(long pos, int mask, BOOL bDirect) { Call(SCI_STARTSTYLING, static_cast<WPARAM>(pos), static_cast<LPARAM>(mask), bDirect); } void CCT3000CO2_NET::SetStyling(int length, int style, BOOL bDirect) { Call(SCI_SETSTYLING, static_cast<WPARAM>(length), static_cast<LPARAM>(style), bDirect); } BOOL CCT3000CO2_NET::GetBufferedDraw(BOOL bDirect) { return Call(SCI_GETBUFFEREDDRAW, 0, 0, bDirect); } void CCT3000CO2_NET::SetBufferedDraw(BOOL buffered, BOOL bDirect) { Call(SCI_SETBUFFEREDDRAW, static_cast<WPARAM>(buffered), 0, bDirect); } void CCT3000CO2_NET::SetTabWidth(int tabWidth, BOOL bDirect) { Call(SCI_SETTABWIDTH, static_cast<WPARAM>(tabWidth), 0, bDirect); } int CCT3000CO2_NET::GetTabWidth(BOOL bDirect) { return Call(SCI_GETTABWIDTH, 0, 0, bDirect); } void CCT3000CO2_NET::SetCodePage(int codePage, BOOL bDirect) { Call(SCI_SETCODEPAGE, static_cast<WPARAM>(codePage), 0, bDirect); } void CCT3000CO2_NET::SetUsePalette(BOOL usePalette, BOOL bDirect) { Call(SCI_SETUSEPALETTE, static_cast<WPARAM>(usePalette), 0, bDirect); } void CCT3000CO2_NET::MarkerDefine(int markerNumber, int markerSymbol, BOOL bDirect) { Call(SCI_MARKERDEFINE, static_cast<WPARAM>(markerNumber), static_cast<LPARAM>(markerSymbol), bDirect); } void CCT3000CO2_NET::MarkerSetFore(int markerNumber, COLORREF fore, BOOL bDirect) { Call(SCI_MARKERSETFORE, static_cast<WPARAM>(markerNumber), static_cast<LPARAM>(fore), bDirect); } void CCT3000CO2_NET::MarkerSetBack(int markerNumber, COLORREF back, BOOL bDirect) { Call(SCI_MARKERSETBACK, static_cast<WPARAM>(markerNumber), static_cast<LPARAM>(back), bDirect); } int CCT3000CO2_NET::MarkerAdd(int line, int markerNumber, BOOL bDirect) { return Call(SCI_MARKERADD, static_cast<WPARAM>(line), static_cast<LPARAM>(markerNumber), bDirect); } void CCT3000CO2_NET::MarkerDelete(int line, int markerNumber, BOOL bDirect) { Call(SCI_MARKERDELETE, static_cast<WPARAM>(line), static_cast<LPARAM>(markerNumber), bDirect); } void CCT3000CO2_NET::MarkerDeleteAll(int markerNumber, BOOL bDirect) { Call(SCI_MARKERDELETEALL, static_cast<WPARAM>(markerNumber), 0, bDirect); } int CCT3000CO2_NET::MarkerGet(int line, BOOL bDirect) { return Call(SCI_MARKERGET, static_cast<WPARAM>(line), 0, bDirect); } int CCT3000CO2_NET::MarkerNext(int lineStart, int markerMask, BOOL bDirect) { return Call(SCI_MARKERNEXT, static_cast<WPARAM>(lineStart), static_cast<LPARAM>(markerMask), bDirect); } int CCT3000CO2_NET::MarkerPrevious(int lineStart, int markerMask, BOOL bDirect) { return Call(SCI_MARKERPREVIOUS, static_cast<WPARAM>(lineStart), static_cast<LPARAM>(markerMask), bDirect); } void CCT3000CO2_NET::MarkerDefinePixmap(int markerNumber, const char* pixmap, BOOL bDirect) { Call(SCI_MARKERDEFINEPIXMAP, static_cast<WPARAM>(markerNumber), reinterpret_cast<LPARAM>(pixmap), bDirect); } void CCT3000CO2_NET::MarkerAddSet(int line, int set, BOOL bDirect) { Call(SCI_MARKERADDSET, static_cast<WPARAM>(line), static_cast<LPARAM>(set), bDirect); } void CCT3000CO2_NET::MarkerSetAlpha(int markerNumber, int alpha, BOOL bDirect) { Call(SCI_MARKERSETALPHA, static_cast<WPARAM>(markerNumber), static_cast<LPARAM>(alpha), bDirect); } void CCT3000CO2_NET::SetMarginTypeN(int margin, int marginType, BOOL bDirect) { Call(SCI_SETMARGINTYPEN, static_cast<WPARAM>(margin), static_cast<LPARAM>(marginType), bDirect); } int CCT3000CO2_NET::GetMarginTypeN(int margin, BOOL bDirect) { return Call(SCI_GETMARGINTYPEN, static_cast<WPARAM>(margin), 0, bDirect); } void CCT3000CO2_NET::SetMarginWidthN(int margin, int pixelWidth, BOOL bDirect) { Call(SCI_SETMARGINWIDTHN, static_cast<WPARAM>(margin), static_cast<LPARAM>(pixelWidth), bDirect); } int CCT3000CO2_NET::GetMarginWidthN(int margin, BOOL bDirect) { return Call(SCI_GETMARGINWIDTHN, static_cast<WPARAM>(margin), 0, bDirect); } void CCT3000CO2_NET::SetMarginMaskN(int margin, int mask, BOOL bDirect) { Call(SCI_SETMARGINMASKN, static_cast<WPARAM>(margin), static_cast<LPARAM>(mask), bDirect); } int CCT3000CO2_NET::GetMarginMaskN(int margin, BOOL bDirect) { return Call(SCI_GETMARGINMASKN, static_cast<WPARAM>(margin), 0, bDirect); } void CCT3000CO2_NET::SetMarginSensitiveN(int margin, BOOL sensitive, BOOL bDirect) { Call(SCI_SETMARGINSENSITIVEN, static_cast<WPARAM>(margin), static_cast<LPARAM>(sensitive), bDirect); } BOOL CCT3000CO2_NET::GetMarginSensitiveN(int margin, BOOL bDirect) { return Call(SCI_GETMARGINSENSITIVEN, static_cast<WPARAM>(margin), 0, bDirect); } void CCT3000CO2_NET::StyleClearAll(BOOL bDirect) { Call(SCI_STYLECLEARALL, 0, 0, bDirect); } void CCT3000CO2_NET::StyleSetFore(int style, COLORREF fore, BOOL bDirect) { Call(SCI_STYLESETFORE, static_cast<WPARAM>(style), static_cast<LPARAM>(fore), bDirect); } void CCT3000CO2_NET::StyleSetBack(int style, COLORREF back, BOOL bDirect) { Call(SCI_STYLESETBACK, static_cast<WPARAM>(style), static_cast<LPARAM>(back), bDirect); } void CCT3000CO2_NET::StyleSetBold(int style, BOOL bold, BOOL bDirect) { Call(SCI_STYLESETBOLD, static_cast<WPARAM>(style), static_cast<LPARAM>(bold), bDirect); } void CCT3000CO2_NET::StyleSetItalic(int style, BOOL italic, BOOL bDirect) { Call(SCI_STYLESETITALIC, static_cast<WPARAM>(style), static_cast<LPARAM>(italic), bDirect); } void CCT3000CO2_NET::StyleSetSize(int style, int sizePoints, BOOL bDirect) { Call(SCI_STYLESETSIZE, static_cast<WPARAM>(style), static_cast<LPARAM>(sizePoints), bDirect); } void CCT3000CO2_NET::StyleSetFont(int style, const char* fontName, BOOL bDirect) { Call(SCI_STYLESETFONT, static_cast<WPARAM>(style), reinterpret_cast<LPARAM>(fontName), bDirect); } void CCT3000CO2_NET::StyleSetEOLFilled(int style, BOOL filled, BOOL bDirect) { Call(SCI_STYLESETEOLFILLED, static_cast<WPARAM>(style), static_cast<LPARAM>(filled), bDirect); } void CCT3000CO2_NET::StyleResetDefault(BOOL bDirect) { Call(SCI_STYLERESETDEFAULT, 0, 0, bDirect); } void CCT3000CO2_NET::StyleSetUnderline(int style, BOOL underline, BOOL bDirect) { Call(SCI_STYLESETUNDERLINE, static_cast<WPARAM>(style), static_cast<LPARAM>(underline), bDirect); } COLORREF CCT3000CO2_NET::StyleGetFore(int style, BOOL bDirect) { return Call(SCI_STYLEGETFORE, static_cast<WPARAM>(style), 0, bDirect); } COLORREF CCT3000CO2_NET::StyleGetBack(int style, BOOL bDirect) { return Call(SCI_STYLEGETBACK, static_cast<WPARAM>(style), 0, bDirect); } BOOL CCT3000CO2_NET::StyleGetBold(int style, BOOL bDirect) { return Call(SCI_STYLEGETBOLD, static_cast<WPARAM>(style), 0, bDirect); } BOOL CCT3000CO2_NET::StyleGetItalic(int style, BOOL bDirect) { return Call(SCI_STYLEGETITALIC, static_cast<WPARAM>(style), 0, bDirect); } int CCT3000CO2_NET::StyleGetSize(int style, BOOL bDirect) { return Call(SCI_STYLEGETSIZE, static_cast<WPARAM>(style), 0, bDirect); } int CCT3000CO2_NET::StyleGetFont(int style, char* fontName, BOOL bDirect) { return Call(SCI_STYLEGETFONT, static_cast<WPARAM>(style), reinterpret_cast<LPARAM>(fontName), bDirect); } BOOL CCT3000CO2_NET::StyleGetEOLFilled(int style, BOOL bDirect) { return Call(SCI_STYLEGETEOLFILLED, static_cast<WPARAM>(style), 0, bDirect); } BOOL CCT3000CO2_NET::StyleGetUnderline(int style, BOOL bDirect) { return Call(SCI_STYLEGETUNDERLINE, static_cast<WPARAM>(style), 0, bDirect); } int CCT3000CO2_NET::StyleGetCase(int style, BOOL bDirect) { return Call(SCI_STYLEGETCASE, static_cast<WPARAM>(style), 0, bDirect); } int CCT3000CO2_NET::StyleGetCharacterSet(int style, BOOL bDirect) { return Call(SCI_STYLEGETCHARACTERSET, static_cast<WPARAM>(style), 0, bDirect); } BOOL CCT3000CO2_NET::StyleGetVisible(int style, BOOL bDirect) { return Call(SCI_STYLEGETVISIBLE, static_cast<WPARAM>(style), 0, bDirect); } BOOL CCT3000CO2_NET::StyleGetChangeable(int style, BOOL bDirect) { return Call(SCI_STYLEGETCHANGEABLE, static_cast<WPARAM>(style), 0, bDirect); } BOOL CCT3000CO2_NET::StyleGetHotSpot(int style, BOOL bDirect) { return Call(SCI_STYLEGETHOTSPOT, static_cast<WPARAM>(style), 0, bDirect); } void CCT3000CO2_NET::StyleSetCase(int style, int caseForce, BOOL bDirect) { Call(SCI_STYLESETCASE, static_cast<WPARAM>(style), static_cast<LPARAM>(caseForce), bDirect); } void CCT3000CO2_NET::StyleSetCharacterSet(int style, int characterSet, BOOL bDirect) { Call(SCI_STYLESETCHARACTERSET, static_cast<WPARAM>(style), static_cast<LPARAM>(characterSet), bDirect); } void CCT3000CO2_NET::StyleSetHotSpot(int style, BOOL hotspot, BOOL bDirect) { Call(SCI_STYLESETHOTSPOT, static_cast<WPARAM>(style), static_cast<LPARAM>(hotspot), bDirect); } void CCT3000CO2_NET::SetSelFore(BOOL useSetting, COLORREF fore, BOOL bDirect) { Call(SCI_SETSELFORE, static_cast<WPARAM>(useSetting), static_cast<LPARAM>(fore), bDirect); } void CCT3000CO2_NET::SetSelBack(BOOL useSetting, COLORREF back, BOOL bDirect) { Call(SCI_SETSELBACK, static_cast<WPARAM>(useSetting), static_cast<LPARAM>(back), bDirect); } int CCT3000CO2_NET::GetSelAlpha(BOOL bDirect) { return Call(SCI_GETSELALPHA, 0, 0, bDirect); } void CCT3000CO2_NET::SetSelAlpha(int alpha, BOOL bDirect) { Call(SCI_SETSELALPHA, static_cast<WPARAM>(alpha), 0, bDirect); } BOOL CCT3000CO2_NET::GetSelEOLFilled(BOOL bDirect) { return Call(SCI_GETSELEOLFILLED, 0, 0, bDirect); } void CCT3000CO2_NET::SetSelEOLFilled(BOOL filled, BOOL bDirect) { Call(SCI_SETSELEOLFILLED, static_cast<WPARAM>(filled), 0, bDirect); } void CCT3000CO2_NET::SetCaretFore(COLORREF fore, BOOL bDirect) { Call(SCI_SETCARETFORE, static_cast<WPARAM>(fore), 0, bDirect); } void CCT3000CO2_NET::AssignCmdKey(DWORD km, int msg, BOOL bDirect) { Call(SCI_ASSIGNCMDKEY, static_cast<WPARAM>(km), static_cast<LPARAM>(msg), bDirect); } void CCT3000CO2_NET::ClearCmdKey(DWORD km, BOOL bDirect) { Call(SCI_CLEARCMDKEY, static_cast<WPARAM>(km), 0, bDirect); } void CCT3000CO2_NET::ClearAllCmdKeys(BOOL bDirect) { Call(SCI_CLEARALLCMDKEYS, 0, 0, bDirect); } void CCT3000CO2_NET::SetStylingEx(int length, const char* styles, BOOL bDirect) { Call(SCI_SETSTYLINGEX, static_cast<WPARAM>(length), reinterpret_cast<LPARAM>(styles), bDirect); } void CCT3000CO2_NET::StyleSetVisible(int style, BOOL visible, BOOL bDirect) { Call(SCI_STYLESETVISIBLE, static_cast<WPARAM>(style), static_cast<LPARAM>(visible), bDirect); } int CCT3000CO2_NET::GetCaretPeriod(BOOL bDirect) { return Call(SCI_GETCARETPERIOD, 0, 0, bDirect); } void CCT3000CO2_NET::SetCaretPeriod(int periodMilliseconds, BOOL bDirect) { Call(SCI_SETCARETPERIOD, static_cast<WPARAM>(periodMilliseconds), 0, bDirect); } void CCT3000CO2_NET::SetWordChars(const char* characters, BOOL bDirect) { Call(SCI_SETWORDCHARS, 0, reinterpret_cast<LPARAM>(characters), bDirect); } void CCT3000CO2_NET::BeginUndoAction(BOOL bDirect) { Call(SCI_BEGINUNDOACTION, 0, 0, bDirect); } void CCT3000CO2_NET::EndUndoAction(BOOL bDirect) { Call(SCI_ENDUNDOACTION, 0, 0, bDirect); } void CCT3000CO2_NET::IndicSetStyle(int indic, int style, BOOL bDirect) { Call(SCI_INDICSETSTYLE, static_cast<WPARAM>(indic), static_cast<LPARAM>(style), bDirect); } int CCT3000CO2_NET::IndicGetStyle(int indic, BOOL bDirect) { return Call(SCI_INDICGETSTYLE, static_cast<WPARAM>(indic), 0, bDirect); } void CCT3000CO2_NET::IndicSetFore(int indic, COLORREF fore, BOOL bDirect) { Call(SCI_INDICSETFORE, static_cast<WPARAM>(indic), static_cast<LPARAM>(fore), bDirect); } COLORREF CCT3000CO2_NET::IndicGetFore(int indic, BOOL bDirect) { return Call(SCI_INDICGETFORE, static_cast<WPARAM>(indic), 0, bDirect); } void CCT3000CO2_NET::IndicSetUnder(int indic, BOOL under, BOOL bDirect) { Call(SCI_INDICSETUNDER, static_cast<WPARAM>(indic), static_cast<LPARAM>(under), bDirect); } BOOL CCT3000CO2_NET::IndicGetUnder(int indic, BOOL bDirect) { return Call(SCI_INDICGETUNDER, static_cast<WPARAM>(indic), 0, bDirect); } void CCT3000CO2_NET::SetWhitespaceFore(BOOL useSetting, COLORREF fore, BOOL bDirect) { Call(SCI_SETWHITESPACEFORE, static_cast<WPARAM>(useSetting), static_cast<LPARAM>(fore), bDirect); } void CCT3000CO2_NET::SetWhitespaceBack(BOOL useSetting, COLORREF back, BOOL bDirect) { Call(SCI_SETWHITESPACEBACK, static_cast<WPARAM>(useSetting), static_cast<LPARAM>(back), bDirect); } void CCT3000CO2_NET::SetStyleBits(int bits, BOOL bDirect) { Call(SCI_SETSTYLEBITS, static_cast<WPARAM>(bits), 0, bDirect); } int CCT3000CO2_NET::GetStyleBits(BOOL bDirect) { return Call(SCI_GETSTYLEBITS, 0, 0, bDirect); } void CCT3000CO2_NET::SetLineState(int line, int state, BOOL bDirect) { Call(SCI_SETLINESTATE, static_cast<WPARAM>(line), static_cast<LPARAM>(state), bDirect); } int CCT3000CO2_NET::GetLineState(int line, BOOL bDirect) { return Call(SCI_GETLINESTATE, static_cast<WPARAM>(line), 0, bDirect); } int CCT3000CO2_NET::GetMaxLineState(BOOL bDirect) { return Call(SCI_GETMAXLINESTATE, 0, 0, bDirect); } BOOL CCT3000CO2_NET::GetCaretLineVisible(BOOL bDirect) { return Call(SCI_GETCARETLINEVISIBLE, 0, 0, bDirect); } void CCT3000CO2_NET::SetCaretLineVisible(BOOL show, BOOL bDirect) { Call(SCI_SETCARETLINEVISIBLE, static_cast<WPARAM>(show), 0, bDirect); } COLORREF CCT3000CO2_NET::GetCaretLineBack(BOOL bDirect) { return Call(SCI_GETCARETLINEBACK, 0, 0, bDirect); } void CCT3000CO2_NET::SetCaretLineBack(COLORREF back, BOOL bDirect) { Call(SCI_SETCARETLINEBACK, static_cast<WPARAM>(back), 0, bDirect); } void CCT3000CO2_NET::StyleSetChangeable(int style, BOOL changeable, BOOL bDirect) { Call(SCI_STYLESETCHANGEABLE, static_cast<WPARAM>(style), static_cast<LPARAM>(changeable), bDirect); } void CCT3000CO2_NET::AutoCShow(int lenEntered, const char* itemList, BOOL bDirect) { Call(SCI_AUTOCSHOW, static_cast<WPARAM>(lenEntered), reinterpret_cast<LPARAM>(itemList), bDirect); } void CCT3000CO2_NET::AutoCCancel(BOOL bDirect) { Call(SCI_AUTOCCANCEL, 0, 0, bDirect); } BOOL CCT3000CO2_NET::AutoCActive(BOOL bDirect) { return Call(SCI_AUTOCACTIVE, 0, 0, bDirect); } long CCT3000CO2_NET::AutoCPosStart(BOOL bDirect) { return Call(SCI_AUTOCPOSSTART, 0, 0, bDirect); } void CCT3000CO2_NET::AutoCComplete(BOOL bDirect) { Call(SCI_AUTOCCOMPLETE, 0, 0, bDirect); } void CCT3000CO2_NET::AutoCStops(const char* characterSet, BOOL bDirect) { Call(SCI_AUTOCSTOPS, 0, reinterpret_cast<LPARAM>(characterSet), bDirect); } void CCT3000CO2_NET::AutoCSetSeparator(int separatorCharacter, BOOL bDirect) { Call(SCI_AUTOCSETSEPARATOR, static_cast<WPARAM>(separatorCharacter), 0, bDirect); } int CCT3000CO2_NET::AutoCGetSeparator(BOOL bDirect) { return Call(SCI_AUTOCGETSEPARATOR, 0, 0, bDirect); } void CCT3000CO2_NET::AutoCSelect(const char* text, BOOL bDirect) { Call(SCI_AUTOCSELECT, 0, reinterpret_cast<LPARAM>(text), bDirect); } void CCT3000CO2_NET::AutoCSetCancelAtStart(BOOL cancel, BOOL bDirect) { Call(SCI_AUTOCSETCANCELATSTART, static_cast<WPARAM>(cancel), 0, bDirect); } BOOL CCT3000CO2_NET::AutoCGetCancelAtStart(BOOL bDirect) { return Call(SCI_AUTOCGETCANCELATSTART, 0, 0, bDirect); } void CCT3000CO2_NET::AutoCSetFillUps(const char* characterSet, BOOL bDirect) { Call(SCI_AUTOCSETFILLUPS, 0, reinterpret_cast<LPARAM>(characterSet), bDirect); } void CCT3000CO2_NET::AutoCSetChooseSingle(BOOL chooseSingle, BOOL bDirect) { Call(SCI_AUTOCSETCHOOSESINGLE, static_cast<WPARAM>(chooseSingle), 0, bDirect); } BOOL CCT3000CO2_NET::AutoCGetChooseSingle(BOOL bDirect) { return Call(SCI_AUTOCGETCHOOSESINGLE, 0, 0, bDirect); } void CCT3000CO2_NET::AutoCSetIgnoreCase(BOOL ignoreCase, BOOL bDirect) { Call(SCI_AUTOCSETIGNORECASE, static_cast<WPARAM>(ignoreCase), 0, bDirect); } BOOL CCT3000CO2_NET::AutoCGetIgnoreCase(BOOL bDirect) { return Call(SCI_AUTOCGETIGNORECASE, 0, 0, bDirect); } void CCT3000CO2_NET::UserListShow(int listType, const char* itemList, BOOL bDirect) { Call(SCI_USERLISTSHOW, static_cast<WPARAM>(listType), reinterpret_cast<LPARAM>(itemList), bDirect); } void CCT3000CO2_NET::AutoCSetAutoHide(BOOL autoHide, BOOL bDirect) { Call(SCI_AUTOCSETAUTOHIDE, static_cast<WPARAM>(autoHide), 0, bDirect); } BOOL CCT3000CO2_NET::AutoCGetAutoHide(BOOL bDirect) { return Call(SCI_AUTOCGETAUTOHIDE, 0, 0, bDirect); } void CCT3000CO2_NET::AutoCSetDropRestOfWord(BOOL dropRestOfWord, BOOL bDirect) { Call(SCI_AUTOCSETDROPRESTOFWORD, static_cast<WPARAM>(dropRestOfWord), 0, bDirect); } BOOL CCT3000CO2_NET::AutoCGetDropRestOfWord(BOOL bDirect) { return Call(SCI_AUTOCGETDROPRESTOFWORD, 0, 0, bDirect); } void CCT3000CO2_NET::RegisterImage(int type, const char* xpmData, BOOL bDirect) { Call(SCI_REGISTERIMAGE, static_cast<WPARAM>(type), reinterpret_cast<LPARAM>(xpmData), bDirect); } void CCT3000CO2_NET::ClearRegisteredImages(BOOL bDirect) { Call(SCI_CLEARREGISTEREDIMAGES, 0, 0, bDirect); } int CCT3000CO2_NET::AutoCGetTypeSeparator(BOOL bDirect) { return Call(SCI_AUTOCGETTYPESEPARATOR, 0, 0, bDirect); } void CCT3000CO2_NET::AutoCSetTypeSeparator(int separatorCharacter, BOOL bDirect) { Call(SCI_AUTOCSETTYPESEPARATOR, static_cast<WPARAM>(separatorCharacter), 0, bDirect); } void CCT3000CO2_NET::AutoCSetMaxWidth(int characterCount, BOOL bDirect) { Call(SCI_AUTOCSETMAXWIDTH, static_cast<WPARAM>(characterCount), 0, bDirect); } int CCT3000CO2_NET::AutoCGetMaxWidth(BOOL bDirect) { return Call(SCI_AUTOCGETMAXWIDTH, 0, 0, bDirect); } void CCT3000CO2_NET::AutoCSetMaxHeight(int rowCount, BOOL bDirect) { Call(SCI_AUTOCSETMAXHEIGHT, static_cast<WPARAM>(rowCount), 0, bDirect); } int CCT3000CO2_NET::AutoCGetMaxHeight(BOOL bDirect) { return Call(SCI_AUTOCGETMAXHEIGHT, 0, 0, bDirect); } void CCT3000CO2_NET::SetIndent(int indentSize, BOOL bDirect) { Call(SCI_SETINDENT, static_cast<WPARAM>(indentSize), 0, bDirect); } int CCT3000CO2_NET::GetIndent(BOOL bDirect) { return Call(SCI_GETINDENT, 0, 0, bDirect); } void CCT3000CO2_NET::SetUseTabs(BOOL useTabs, BOOL bDirect) { Call(SCI_SETUSETABS, static_cast<WPARAM>(useTabs), 0, bDirect); } BOOL CCT3000CO2_NET::GetUseTabs(BOOL bDirect) { return Call(SCI_GETUSETABS, 0, 0, bDirect); } void CCT3000CO2_NET::SetLineIndentation(int line, int indentSize, BOOL bDirect) { Call(SCI_SETLINEINDENTATION, static_cast<WPARAM>(line), static_cast<LPARAM>(indentSize), bDirect); } int CCT3000CO2_NET::GetLineIndentation(int line, BOOL bDirect) { return Call(SCI_GETLINEINDENTATION, static_cast<WPARAM>(line), 0, bDirect); } long CCT3000CO2_NET::GetLineIndentPosition(int line, BOOL bDirect) { return Call(SCI_GETLINEINDENTPOSITION, static_cast<WPARAM>(line), 0, bDirect); } int CCT3000CO2_NET::GetColumn(long pos, BOOL bDirect) { return Call(SCI_GETCOLUMN, static_cast<WPARAM>(pos), 0, bDirect); } void CCT3000CO2_NET::SetHScrollBar(BOOL show, BOOL bDirect) { Call(SCI_SETHSCROLLBAR, static_cast<WPARAM>(show), 0, bDirect); } BOOL CCT3000CO2_NET::GetHScrollBar(BOOL bDirect) { return Call(SCI_GETHSCROLLBAR, 0, 0, bDirect); } void CCT3000CO2_NET::SetIndentationGuides(int indentView, BOOL bDirect) { Call(SCI_SETINDENTATIONGUIDES, static_cast<WPARAM>(indentView), 0, bDirect); } int CCT3000CO2_NET::GetIndentationGuides(BOOL bDirect) { return Call(SCI_GETINDENTATIONGUIDES, 0, 0, bDirect); } void CCT3000CO2_NET::SetHighlightGuide(int column, BOOL bDirect) { Call(SCI_SETHIGHLIGHTGUIDE, static_cast<WPARAM>(column), 0, bDirect); } int CCT3000CO2_NET::GetHighlightGuide(BOOL bDirect) { return Call(SCI_GETHIGHLIGHTGUIDE, 0, 0, bDirect); } int CCT3000CO2_NET::GetLineEndPosition(int line, BOOL bDirect) { return Call(SCI_GETLINEENDPOSITION, static_cast<WPARAM>(line), 0, bDirect); } int CCT3000CO2_NET::GetCodePage(BOOL bDirect) { return Call(SCI_GETCODEPAGE, 0, 0, bDirect); } COLORREF CCT3000CO2_NET::GetCaretFore(BOOL bDirect) { return Call(SCI_GETCARETFORE, 0, 0, bDirect); } BOOL CCT3000CO2_NET::GetUsePalette(BOOL bDirect) { return Call(SCI_GETUSEPALETTE, 0, 0, bDirect); } BOOL CCT3000CO2_NET::GetReadOnly(BOOL bDirect) { return Call(SCI_GETREADONLY, 0, 0, bDirect); } void CCT3000CO2_NET::SetCurrentPos(long pos, BOOL bDirect) { Call(SCI_SETCURRENTPOS, static_cast<WPARAM>(pos), 0, bDirect); } void CCT3000CO2_NET::SetSelectionStart(long pos, BOOL bDirect) { Call(SCI_SETSELECTIONSTART, static_cast<WPARAM>(pos), 0, bDirect); } long CCT3000CO2_NET::GetSelectionStart(BOOL bDirect) { return Call(SCI_GETSELECTIONSTART, 0, 0, bDirect); } void CCT3000CO2_NET::SetSelectionEnd(long pos, BOOL bDirect) { Call(SCI_SETSELECTIONEND, static_cast<WPARAM>(pos), 0, bDirect); } long CCT3000CO2_NET::GetSelectionEnd(BOOL bDirect) { return Call(SCI_GETSELECTIONEND, 0, 0, bDirect); } void CCT3000CO2_NET::SetPrintMagnification(int magnification, BOOL bDirect) { Call(SCI_SETPRINTMAGNIFICATION, static_cast<WPARAM>(magnification), 0, bDirect); } int CCT3000CO2_NET::GetPrintMagnification(BOOL bDirect) { return Call(SCI_GETPRINTMAGNIFICATION, 0, 0, bDirect); } void CCT3000CO2_NET::SetPrintColourMode(int mode, BOOL bDirect) { Call(SCI_SETPRINTCOLOURMODE, static_cast<WPARAM>(mode), 0, bDirect); } int CCT3000CO2_NET::GetPrintColourMode(BOOL bDirect) { return Call(SCI_GETPRINTCOLOURMODE, 0, 0, bDirect); } long CCT3000CO2_NET::FindText(int flags, TextToFind* ft, BOOL bDirect) { return Call(SCI_FINDTEXT, static_cast<WPARAM>(flags), reinterpret_cast<LPARAM>(ft), bDirect); } long CCT3000CO2_NET::FormatRange(BOOL draw, RangeToFormat* fr, BOOL bDirect) { return Call(SCI_FORMATRANGE, static_cast<WPARAM>(draw), reinterpret_cast<LPARAM>(fr), bDirect); } int CCT3000CO2_NET::GetFirstVisibleLine(BOOL bDirect) { return Call(SCI_GETFIRSTVISIBLELINE, 0, 0, bDirect); } int CCT3000CO2_NET::GetLine(int line, char* text, BOOL bDirect) { return Call(SCI_GETLINE, static_cast<WPARAM>(line), reinterpret_cast<LPARAM>(text), bDirect); } int CCT3000CO2_NET::GetLineCount(BOOL bDirect) { return Call(SCI_GETLINECOUNT, 0, 0, bDirect); } void CCT3000CO2_NET::SetMarginLeft(int pixelWidth, BOOL bDirect) { Call(SCI_SETMARGINLEFT, 0, static_cast<LPARAM>(pixelWidth), bDirect); } int CCT3000CO2_NET::GetMarginLeft(BOOL bDirect) { return Call(SCI_GETMARGINLEFT, 0, 0, bDirect); } void CCT3000CO2_NET::SetMarginRight(int pixelWidth, BOOL bDirect) { Call(SCI_SETMARGINRIGHT, 0, static_cast<LPARAM>(pixelWidth), bDirect); } int CCT3000CO2_NET::GetMarginRight(BOOL bDirect) { return Call(SCI_GETMARGINRIGHT, 0, 0, bDirect); } BOOL CCT3000CO2_NET::GetModify(BOOL bDirect) { return Call(SCI_GETMODIFY, 0, 0, bDirect); } void CCT3000CO2_NET::SetSel(long start, long end, BOOL bDirect) { Call(SCI_SETSEL, static_cast<WPARAM>(start), static_cast<LPARAM>(end), bDirect); } int CCT3000CO2_NET::GetSelText(char* text, BOOL bDirect) { return Call(SCI_GETSELTEXT, 0, reinterpret_cast<LPARAM>(text), bDirect); } int CCT3000CO2_NET::GetTextRange(TextRange* tr, BOOL bDirect) { return Call(SCI_GETTEXTRANGE, 0, reinterpret_cast<LPARAM>(tr), bDirect); } void CCT3000CO2_NET::HideSelection(BOOL normal, BOOL bDirect) { Call(SCI_HIDESELECTION, static_cast<WPARAM>(normal), 0, bDirect); } int CCT3000CO2_NET::PointXFromPosition(long pos, BOOL bDirect) { return Call(SCI_POINTXFROMPOSITION, 0, static_cast<LPARAM>(pos), bDirect); } int CCT3000CO2_NET::PointYFromPosition(long pos, BOOL bDirect) { return Call(SCI_POINTYFROMPOSITION, 0, static_cast<LPARAM>(pos), bDirect); } int CCT3000CO2_NET::LineFromPosition(long pos, BOOL bDirect) { return Call(SCI_LINEFROMPOSITION, static_cast<WPARAM>(pos), 0, bDirect); } long CCT3000CO2_NET::PositionFromLine(int line, BOOL bDirect) { return Call(SCI_POSITIONFROMLINE, static_cast<WPARAM>(line), 0, bDirect); } void CCT3000CO2_NET::LineScroll(int columns, int lines, BOOL bDirect) { Call(SCI_LINESCROLL, static_cast<WPARAM>(columns), static_cast<LPARAM>(lines), bDirect); } void CCT3000CO2_NET::ScrollCaret(BOOL bDirect) { Call(SCI_SCROLLCARET, 0, 0, bDirect); } void CCT3000CO2_NET::ReplaceSel(const char* text, BOOL bDirect) { Call(SCI_REPLACESEL, 0, reinterpret_cast<LPARAM>(text), bDirect); } void CCT3000CO2_NET::SetReadOnly(BOOL readOnly, BOOL bDirect) { Call(SCI_SETREADONLY, static_cast<WPARAM>(readOnly), 0, bDirect); } void CCT3000CO2_NET::Null(BOOL bDirect) { Call(SCI_NULL, 0, 0, bDirect); } BOOL CCT3000CO2_NET::CanPaste(BOOL bDirect) { return Call(SCI_CANPASTE, 0, 0, bDirect); } BOOL CCT3000CO2_NET::CanUndo(BOOL bDirect) { return Call(SCI_CANUNDO, 0, 0, bDirect); } void CCT3000CO2_NET::EmptyUndoBuffer(BOOL bDirect) { Call(SCI_EMPTYUNDOBUFFER, 0, 0, bDirect); } void CCT3000CO2_NET::Undo(BOOL bDirect) { Call(SCI_UNDO, 0, 0, bDirect); } void CCT3000CO2_NET::Cut(BOOL bDirect) { Call(SCI_CUT, 0, 0, bDirect); } void CCT3000CO2_NET::Copy(BOOL bDirect) { Call(SCI_COPY, 0, 0, bDirect); } void CCT3000CO2_NET::Paste(BOOL bDirect) { Call(SCI_PASTE, 0, 0, bDirect); } void CCT3000CO2_NET::Clear(BOOL bDirect) { Call(SCI_CLEAR, 0, 0, bDirect); } void CCT3000CO2_NET::SetText(const char* text, BOOL bDirect) { Call(SCI_SETTEXT, 0, reinterpret_cast<LPARAM>(text), bDirect); } int CCT3000CO2_NET::GetText(int length, char* text, BOOL bDirect) { return Call(SCI_GETTEXT, static_cast<WPARAM>(length), reinterpret_cast<LPARAM>(text), bDirect); } int CCT3000CO2_NET::GetTextLength(BOOL bDirect) { return Call(SCI_GETTEXTLENGTH, 0, 0, bDirect); } void CCT3000CO2_NET::SetOvertype(BOOL overtype, BOOL bDirect) { Call(SCI_SETOVERTYPE, static_cast<WPARAM>(overtype), 0, bDirect); } BOOL CCT3000CO2_NET::GetOvertype(BOOL bDirect) { return Call(SCI_GETOVERTYPE, 0, 0, bDirect); } void CCT3000CO2_NET::SetCaretWidth(int pixelWidth, BOOL bDirect) { Call(SCI_SETCARETWIDTH, static_cast<WPARAM>(pixelWidth), 0, bDirect); } int CCT3000CO2_NET::GetCaretWidth(BOOL bDirect) { return Call(SCI_GETCARETWIDTH, 0, 0, bDirect); } void CCT3000CO2_NET::SetTargetStart(long pos, BOOL bDirect) { Call(SCI_SETTARGETSTART, static_cast<WPARAM>(pos), 0, bDirect); } long CCT3000CO2_NET::GetTargetStart(BOOL bDirect) { return Call(SCI_GETTARGETSTART, 0, 0, bDirect); } void CCT3000CO2_NET::SetTargetEnd(long pos, BOOL bDirect) { Call(SCI_SETTARGETEND, static_cast<WPARAM>(pos), 0, bDirect); } long CCT3000CO2_NET::GetTargetEnd(BOOL bDirect) { return Call(SCI_GETTARGETEND, 0, 0, bDirect); } int CCT3000CO2_NET::ReplaceTarget(int length, const char* text, BOOL bDirect) { return Call(SCI_REPLACETARGET, static_cast<WPARAM>(length), reinterpret_cast<LPARAM>(text), bDirect); } int CCT3000CO2_NET::ReplaceTargetRE(int length, const char* text, BOOL bDirect) { return Call(SCI_REPLACETARGETRE, static_cast<WPARAM>(length), reinterpret_cast<LPARAM>(text), bDirect); } int CCT3000CO2_NET::SearchInTarget(int length, const char* text, BOOL bDirect) { return Call(SCI_SEARCHINTARGET, static_cast<WPARAM>(length), reinterpret_cast<LPARAM>(text), bDirect); } void CCT3000CO2_NET::SetSearchFlags(int flags, BOOL bDirect) { Call(SCI_SETSEARCHFLAGS, static_cast<WPARAM>(flags), 0, bDirect); } int CCT3000CO2_NET::GetSearchFlags(BOOL bDirect) { return Call(SCI_GETSEARCHFLAGS, 0, 0, bDirect); } void CCT3000CO2_NET::CallTipShow(long pos, const char* definition, BOOL bDirect) { Call(SCI_CALLTIPSHOW, static_cast<WPARAM>(pos), reinterpret_cast<LPARAM>(definition), bDirect); } void CCT3000CO2_NET::CallTipCancel(BOOL bDirect) { Call(SCI_CALLTIPCANCEL, 0, 0, bDirect); } BOOL CCT3000CO2_NET::CallTipActive(BOOL bDirect) { return Call(SCI_CALLTIPACTIVE, 0, 0, bDirect); } long CCT3000CO2_NET::CallTipPosStart(BOOL bDirect) { return Call(SCI_CALLTIPPOSSTART, 0, 0, bDirect); } void CCT3000CO2_NET::CallTipSetHlt(int start, int end, BOOL bDirect) { Call(SCI_CALLTIPSETHLT, static_cast<WPARAM>(start), static_cast<LPARAM>(end), bDirect); } void CCT3000CO2_NET::CallTipSetBack(COLORREF back, BOOL bDirect) { Call(SCI_CALLTIPSETBACK, static_cast<WPARAM>(back), 0, bDirect); } void CCT3000CO2_NET::CallTipSetFore(COLORREF fore, BOOL bDirect) { Call(SCI_CALLTIPSETFORE, static_cast<WPARAM>(fore), 0, bDirect); } void CCT3000CO2_NET::CallTipSetForeHlt(COLORREF fore, BOOL bDirect) { Call(SCI_CALLTIPSETFOREHLT, static_cast<WPARAM>(fore), 0, bDirect); } void CCT3000CO2_NET::CallTipUseStyle(int tabSize, BOOL bDirect) { Call(SCI_CALLTIPUSESTYLE, static_cast<WPARAM>(tabSize), 0, bDirect); } int CCT3000CO2_NET::VisibleFromDocLine(int line, BOOL bDirect) { return Call(SCI_VISIBLEFROMDOCLINE, static_cast<WPARAM>(line), 0, bDirect); } int CCT3000CO2_NET::DocLineFromVisible(int lineDisplay, BOOL bDirect) { return Call(SCI_DOCLINEFROMVISIBLE, static_cast<WPARAM>(lineDisplay), 0, bDirect); } int CCT3000CO2_NET::WrapCount(int line, BOOL bDirect) { return Call(SCI_WRAPCOUNT, static_cast<WPARAM>(line), 0, bDirect); } void CCT3000CO2_NET::SetFoldLevel(int line, int level, BOOL bDirect) { Call(SCI_SETFOLDLEVEL, static_cast<WPARAM>(line), static_cast<LPARAM>(level), bDirect); } int CCT3000CO2_NET::GetFoldLevel(int line, BOOL bDirect) { return Call(SCI_GETFOLDLEVEL, static_cast<WPARAM>(line), 0, bDirect); } int CCT3000CO2_NET::GetLastChild(int line, int level, BOOL bDirect) { return Call(SCI_GETLASTCHILD, static_cast<WPARAM>(line), static_cast<LPARAM>(level), bDirect); } int CCT3000CO2_NET::GetFoldParent(int line, BOOL bDirect) { return Call(SCI_GETFOLDPARENT, static_cast<WPARAM>(line), 0, bDirect); } void CCT3000CO2_NET::ShowLines(int lineStart, int lineEnd, BOOL bDirect) { Call(SCI_SHOWLINES, static_cast<WPARAM>(lineStart), static_cast<LPARAM>(lineEnd), bDirect); } void CCT3000CO2_NET::HideLines(int lineStart, int lineEnd, BOOL bDirect) { Call(SCI_HIDELINES, static_cast<WPARAM>(lineStart), static_cast<LPARAM>(lineEnd), bDirect); } BOOL CCT3000CO2_NET::GetLineVisible(int line, BOOL bDirect) { return Call(SCI_GETLINEVISIBLE, static_cast<WPARAM>(line), 0, bDirect); } void CCT3000CO2_NET::SetFoldExpanded(int line, BOOL expanded, BOOL bDirect) { Call(SCI_SETFOLDEXPANDED, static_cast<WPARAM>(line), static_cast<LPARAM>(expanded), bDirect); } BOOL CCT3000CO2_NET::GetFoldExpanded(int line, BOOL bDirect) { return Call(SCI_GETFOLDEXPANDED, static_cast<WPARAM>(line), 0, bDirect); } void CCT3000CO2_NET::ToggleFold(int line, BOOL bDirect) { Call(SCI_TOGGLEFOLD, static_cast<WPARAM>(line), 0, bDirect); } void CCT3000CO2_NET::EnsureVisible(int line, BOOL bDirect) { Call(SCI_ENSUREVISIBLE, static_cast<WPARAM>(line), 0, bDirect); } void CCT3000CO2_NET::SetFoldFlags(int flags, BOOL bDirect) { Call(SCI_SETFOLDFLAGS, static_cast<WPARAM>(flags), 0, bDirect); } void CCT3000CO2_NET::EnsureVisibleEnforcePolicy(int line, BOOL bDirect) { Call(SCI_ENSUREVISIBLEENFORCEPOLICY, static_cast<WPARAM>(line), 0, bDirect); } void CCT3000CO2_NET::SetTabIndents(BOOL tabIndents, BOOL bDirect) { Call(SCI_SETTABINDENTS, static_cast<WPARAM>(tabIndents), 0, bDirect); } BOOL CCT3000CO2_NET::GetTabIndents(BOOL bDirect) { return Call(SCI_GETTABINDENTS, 0, 0, bDirect); } void CCT3000CO2_NET::SetBackSpaceUnIndents(BOOL bsUnIndents, BOOL bDirect) { Call(SCI_SETBACKSPACEUNINDENTS, static_cast<WPARAM>(bsUnIndents), 0, bDirect); } BOOL CCT3000CO2_NET::GetBackSpaceUnIndents(BOOL bDirect) { return Call(SCI_GETBACKSPACEUNINDENTS, 0, 0, bDirect); } void CCT3000CO2_NET::SetMouseDwellTime(int periodMilliseconds, BOOL bDirect) { Call(SCI_SETMOUSEDWELLTIME, static_cast<WPARAM>(periodMilliseconds), 0, bDirect); } int CCT3000CO2_NET::GetMouseDwellTime(BOOL bDirect) { return Call(SCI_GETMOUSEDWELLTIME, 0, 0, bDirect); } int CCT3000CO2_NET::WordStartPosition(long pos, BOOL onlyWordCharacters, BOOL bDirect) { return Call(SCI_WORDSTARTPOSITION, static_cast<WPARAM>(pos), static_cast<LPARAM>(onlyWordCharacters), bDirect); } int CCT3000CO2_NET::WordEndPosition(long pos, BOOL onlyWordCharacters, BOOL bDirect) { return Call(SCI_WORDENDPOSITION, static_cast<WPARAM>(pos), static_cast<LPARAM>(onlyWordCharacters), bDirect); } void CCT3000CO2_NET::SetWrapMode(int mode, BOOL bDirect) { Call(SCI_SETWRAPMODE, static_cast<WPARAM>(mode), 0, bDirect); } int CCT3000CO2_NET::GetWrapMode(BOOL bDirect) { return Call(SCI_GETWRAPMODE, 0, 0, bDirect); } void CCT3000CO2_NET::SetWrapVisualFlags(int wrapVisualFlags, BOOL bDirect) { Call(SCI_SETWRAPVISUALFLAGS, static_cast<WPARAM>(wrapVisualFlags), 0, bDirect); } int CCT3000CO2_NET::GetWrapVisualFlags(BOOL bDirect) { return Call(SCI_GETWRAPVISUALFLAGS, 0, 0, bDirect); } void CCT3000CO2_NET::SetWrapVisualFlagsLocation(int wrapVisualFlagsLocation, BOOL bDirect) { Call(SCI_SETWRAPVISUALFLAGSLOCATION, static_cast<WPARAM>(wrapVisualFlagsLocation), 0, bDirect); } int CCT3000CO2_NET::GetWrapVisualFlagsLocation(BOOL bDirect) { return Call(SCI_GETWRAPVISUALFLAGSLOCATION, 0, 0, bDirect); } void CCT3000CO2_NET::SetWrapStartIndent(int indent, BOOL bDirect) { Call(SCI_SETWRAPSTARTINDENT, static_cast<WPARAM>(indent), 0, bDirect); } int CCT3000CO2_NET::GetWrapStartIndent(BOOL bDirect) { return Call(SCI_GETWRAPSTARTINDENT, 0, 0, bDirect); } void CCT3000CO2_NET::SetLayoutCache(int mode, BOOL bDirect) { Call(SCI_SETLAYOUTCACHE, static_cast<WPARAM>(mode), 0, bDirect); } int CCT3000CO2_NET::GetLayoutCache(BOOL bDirect) { return Call(SCI_GETLAYOUTCACHE, 0, 0, bDirect); } void CCT3000CO2_NET::SetScrollWidth(int pixelWidth, BOOL bDirect) { Call(SCI_SETSCROLLWIDTH, static_cast<WPARAM>(pixelWidth), 0, bDirect); } int CCT3000CO2_NET::GetScrollWidth(BOOL bDirect) { return Call(SCI_GETSCROLLWIDTH, 0, 0, bDirect); } void CCT3000CO2_NET::SetScrollWidthTracking(BOOL tracking, BOOL bDirect) { Call(SCI_SETSCROLLWIDTHTRACKING, static_cast<WPARAM>(tracking), 0, bDirect); } BOOL CCT3000CO2_NET::GetScrollWidthTracking(BOOL bDirect) { return Call(SCI_GETSCROLLWIDTHTRACKING, 0, 0, bDirect); } int CCT3000CO2_NET::TextWidth(int style, const char* text, BOOL bDirect) { return Call(SCI_TEXTWIDTH, static_cast<WPARAM>(style), reinterpret_cast<LPARAM>(text), bDirect); } void CCT3000CO2_NET::SetEndAtLastLine(BOOL endAtLastLine, BOOL bDirect) { Call(SCI_SETENDATLASTLINE, static_cast<WPARAM>(endAtLastLine), 0, bDirect); } BOOL CCT3000CO2_NET::GetEndAtLastLine(BOOL bDirect) { return Call(SCI_GETENDATLASTLINE, 0, 0, bDirect); } int CCT3000CO2_NET::TextHeight(int line, BOOL bDirect) { return Call(SCI_TEXTHEIGHT, static_cast<WPARAM>(line), 0, bDirect); } void CCT3000CO2_NET::SetVScrollBar(BOOL show, BOOL bDirect) { Call(SCI_SETVSCROLLBAR, static_cast<WPARAM>(show), 0, bDirect); } BOOL CCT3000CO2_NET::GetVScrollBar(BOOL bDirect) { return Call(SCI_GETVSCROLLBAR, 0, 0, bDirect); } void CCT3000CO2_NET::AppendText(int length, const char* text, BOOL bDirect) { Call(SCI_APPENDTEXT, static_cast<WPARAM>(length), reinterpret_cast<LPARAM>(text), bDirect); } BOOL CCT3000CO2_NET::GetTwoPhaseDraw(BOOL bDirect) { return Call(SCI_GETTWOPHASEDRAW, 0, 0, bDirect); } void CCT3000CO2_NET::SetTwoPhaseDraw(BOOL twoPhase, BOOL bDirect) { Call(SCI_SETTWOPHASEDRAW, static_cast<WPARAM>(twoPhase), 0, bDirect); } void CCT3000CO2_NET::TargetFromSelection(BOOL bDirect) { Call(SCI_TARGETFROMSELECTION, 0, 0, bDirect); } void CCT3000CO2_NET::LinesJoin(BOOL bDirect) { Call(SCI_LINESJOIN, 0, 0, bDirect); } void CCT3000CO2_NET::LinesSplit(int pixelWidth, BOOL bDirect) { Call(SCI_LINESSPLIT, static_cast<WPARAM>(pixelWidth), 0, bDirect); } void CCT3000CO2_NET::SetFoldMarginColour(BOOL useSetting, COLORREF back, BOOL bDirect) { Call(SCI_SETFOLDMARGINCOLOUR, static_cast<WPARAM>(useSetting), static_cast<LPARAM>(back), bDirect); } void CCT3000CO2_NET::SetFoldMarginHiColour(BOOL useSetting, COLORREF fore, BOOL bDirect) { Call(SCI_SETFOLDMARGINHICOLOUR, static_cast<WPARAM>(useSetting), static_cast<LPARAM>(fore), bDirect); } void CCT3000CO2_NET::LineDown(BOOL bDirect) { Call(SCI_LINEDOWN, 0, 0, bDirect); } void CCT3000CO2_NET::LineDownExtend(BOOL bDirect) { Call(SCI_LINEDOWNEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::LineUp(BOOL bDirect) { Call(SCI_LINEUP, 0, 0, bDirect); } void CCT3000CO2_NET::LineUpExtend(BOOL bDirect) { Call(SCI_LINEUPEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::CharLeft(BOOL bDirect) { Call(SCI_CHARLEFT, 0, 0, bDirect); } void CCT3000CO2_NET::CharLeftExtend(BOOL bDirect) { Call(SCI_CHARLEFTEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::CharRight(BOOL bDirect) { Call(SCI_CHARRIGHT, 0, 0, bDirect); } void CCT3000CO2_NET::CharRightExtend(BOOL bDirect) { Call(SCI_CHARRIGHTEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::WordLeft(BOOL bDirect) { Call(SCI_WORDLEFT, 0, 0, bDirect); } void CCT3000CO2_NET::WordLeftExtend(BOOL bDirect) { Call(SCI_WORDLEFTEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::WordRight(BOOL bDirect) { Call(SCI_WORDRIGHT, 0, 0, bDirect); } void CCT3000CO2_NET::WordRightExtend(BOOL bDirect) { Call(SCI_WORDRIGHTEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::Home(BOOL bDirect) { Call(SCI_HOME, 0, 0, bDirect); } void CCT3000CO2_NET::HomeExtend(BOOL bDirect) { Call(SCI_HOMEEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::LineEnd(BOOL bDirect) { Call(SCI_LINEEND, 0, 0, bDirect); } void CCT3000CO2_NET::LineEndExtend(BOOL bDirect) { Call(SCI_LINEENDEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::DocumentStart(BOOL bDirect) { Call(SCI_DOCUMENTSTART, 0, 0, bDirect); } void CCT3000CO2_NET::DocumentStartExtend(BOOL bDirect) { Call(SCI_DOCUMENTSTARTEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::DocumentEnd(BOOL bDirect) { Call(SCI_DOCUMENTEND, 0, 0, bDirect); } void CCT3000CO2_NET::DocumentEndExtend(BOOL bDirect) { Call(SCI_DOCUMENTENDEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::PageUp(BOOL bDirect) { Call(SCI_PAGEUP, 0, 0, bDirect); } void CCT3000CO2_NET::PageUpExtend(BOOL bDirect) { Call(SCI_PAGEUPEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::PageDown(BOOL bDirect) { Call(SCI_PAGEDOWN, 0, 0, bDirect); } void CCT3000CO2_NET::PageDownExtend(BOOL bDirect) { Call(SCI_PAGEDOWNEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::EditToggleOvertype(BOOL bDirect) { Call(SCI_EDITTOGGLEOVERTYPE, 0, 0, bDirect); } void CCT3000CO2_NET::Cancel(BOOL bDirect) { Call(SCI_CANCEL, 0, 0, bDirect); } void CCT3000CO2_NET::DeleteBack(BOOL bDirect) { Call(SCI_DELETEBACK, 0, 0, bDirect); } void CCT3000CO2_NET::Tab(BOOL bDirect) { Call(SCI_TAB, 0, 0, bDirect); } void CCT3000CO2_NET::BackTab(BOOL bDirect) { Call(SCI_BACKTAB, 0, 0, bDirect); } void CCT3000CO2_NET::NewLine(BOOL bDirect) { Call(SCI_NEWLINE, 0, 0, bDirect); } void CCT3000CO2_NET::FormFeed(BOOL bDirect) { Call(SCI_FORMFEED, 0, 0, bDirect); } void CCT3000CO2_NET::VCHome(BOOL bDirect) { Call(SCI_VCHOME, 0, 0, bDirect); } void CCT3000CO2_NET::VCHomeExtend(BOOL bDirect) { Call(SCI_VCHOMEEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::ZoomIn(BOOL bDirect) { Call(SCI_ZOOMIN, 0, 0, bDirect); } void CCT3000CO2_NET::ZoomOut(BOOL bDirect) { Call(SCI_ZOOMOUT, 0, 0, bDirect); } void CCT3000CO2_NET::DelWordLeft(BOOL bDirect) { Call(SCI_DELWORDLEFT, 0, 0, bDirect); } void CCT3000CO2_NET::DelWordRight(BOOL bDirect) { Call(SCI_DELWORDRIGHT, 0, 0, bDirect); } void CCT3000CO2_NET::DelWordRightEnd(BOOL bDirect) { Call(SCI_DELWORDRIGHTEND, 0, 0, bDirect); } void CCT3000CO2_NET::LineCut(BOOL bDirect) { Call(SCI_LINECUT, 0, 0, bDirect); } void CCT3000CO2_NET::LineDelete(BOOL bDirect) { Call(SCI_LINEDELETE, 0, 0, bDirect); } void CCT3000CO2_NET::LineTranspose(BOOL bDirect) { Call(SCI_LINETRANSPOSE, 0, 0, bDirect); } void CCT3000CO2_NET::LineDuplicate(BOOL bDirect) { Call(SCI_LINEDUPLICATE, 0, 0, bDirect); } void CCT3000CO2_NET::LowerCase(BOOL bDirect) { Call(SCI_LOWERCASE, 0, 0, bDirect); } void CCT3000CO2_NET::UpperCase(BOOL bDirect) { Call(SCI_UPPERCASE, 0, 0, bDirect); } void CCT3000CO2_NET::LineScrollDown(BOOL bDirect) { Call(SCI_LINESCROLLDOWN, 0, 0, bDirect); } void CCT3000CO2_NET::LineScrollUp(BOOL bDirect) { Call(SCI_LINESCROLLUP, 0, 0, bDirect); } void CCT3000CO2_NET::DeleteBackNotLine(BOOL bDirect) { Call(SCI_DELETEBACKNOTLINE, 0, 0, bDirect); } void CCT3000CO2_NET::HomeDisplay(BOOL bDirect) { Call(SCI_HOMEDISPLAY, 0, 0, bDirect); } void CCT3000CO2_NET::HomeDisplayExtend(BOOL bDirect) { Call(SCI_HOMEDISPLAYEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::LineEndDisplay(BOOL bDirect) { Call(SCI_LINEENDDISPLAY, 0, 0, bDirect); } void CCT3000CO2_NET::LineEndDisplayExtend(BOOL bDirect) { Call(SCI_LINEENDDISPLAYEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::HomeWrap(BOOL bDirect) { Call(SCI_HOMEWRAP, 0, 0, bDirect); } void CCT3000CO2_NET::HomeWrapExtend(BOOL bDirect) { Call(SCI_HOMEWRAPEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::LineEndWrap(BOOL bDirect) { Call(SCI_LINEENDWRAP, 0, 0, bDirect); } void CCT3000CO2_NET::LineEndWrapExtend(BOOL bDirect) { Call(SCI_LINEENDWRAPEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::VCHomeWrap(BOOL bDirect) { Call(SCI_VCHOMEWRAP, 0, 0, bDirect); } void CCT3000CO2_NET::VCHomeWrapExtend(BOOL bDirect) { Call(SCI_VCHOMEWRAPEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::LineCopy(BOOL bDirect) { Call(SCI_LINECOPY, 0, 0, bDirect); } void CCT3000CO2_NET::MoveCaretInsideView(BOOL bDirect) { Call(SCI_MOVECARETINSIDEVIEW, 0, 0, bDirect); } int CCT3000CO2_NET::LineLength(int line, BOOL bDirect) { return Call(SCI_LINELENGTH, static_cast<WPARAM>(line), 0, bDirect); } void CCT3000CO2_NET::BraceHighlight(long pos1, long pos2, BOOL bDirect) { Call(SCI_BRACEHIGHLIGHT, static_cast<WPARAM>(pos1), static_cast<LPARAM>(pos2), bDirect); } void CCT3000CO2_NET::BraceBadLight(long pos, BOOL bDirect) { Call(SCI_BRACEBADLIGHT, static_cast<WPARAM>(pos), 0, bDirect); } long CCT3000CO2_NET::BraceMatch(long pos, BOOL bDirect) { return Call(SCI_BRACEMATCH, static_cast<WPARAM>(pos), 0, bDirect); } BOOL CCT3000CO2_NET::GetViewEOL(BOOL bDirect) { return Call(SCI_GETVIEWEOL, 0, 0, bDirect); } void CCT3000CO2_NET::SetViewEOL(BOOL visible, BOOL bDirect) { Call(SCI_SETVIEWEOL, static_cast<WPARAM>(visible), 0, bDirect); } int CCT3000CO2_NET::GetDocPointer(BOOL bDirect) { return Call(SCI_GETDOCPOINTER, 0, 0, bDirect); } void CCT3000CO2_NET::SetDocPointer(int pointer, BOOL bDirect) { Call(SCI_SETDOCPOINTER, 0, static_cast<LPARAM>(pointer), bDirect); } void CCT3000CO2_NET::SetModEventMask(int mask, BOOL bDirect) { Call(SCI_SETMODEVENTMASK, static_cast<WPARAM>(mask), 0, bDirect); } int CCT3000CO2_NET::GetEdgeColumn(BOOL bDirect) { return Call(SCI_GETEDGECOLUMN, 0, 0, bDirect); } void CCT3000CO2_NET::SetEdgeColumn(int column, BOOL bDirect) { Call(SCI_SETEDGECOLUMN, static_cast<WPARAM>(column), 0, bDirect); } int CCT3000CO2_NET::GetEdgeMode(BOOL bDirect) { return Call(SCI_GETEDGEMODE, 0, 0, bDirect); } void CCT3000CO2_NET::SetEdgeMode(int mode, BOOL bDirect) { Call(SCI_SETEDGEMODE, static_cast<WPARAM>(mode), 0, bDirect); } COLORREF CCT3000CO2_NET::GetEdgeColour(BOOL bDirect) { return Call(SCI_GETEDGECOLOUR, 0, 0, bDirect); } void CCT3000CO2_NET::SetEdgeColour(COLORREF edgeColour, BOOL bDirect) { Call(SCI_SETEDGECOLOUR, static_cast<WPARAM>(edgeColour), 0, bDirect); } void CCT3000CO2_NET::SearchAnchor(BOOL bDirect) { Call(SCI_SEARCHANCHOR, 0, 0, bDirect); } int CCT3000CO2_NET::SearchNext(int flags, const char* text, BOOL bDirect) { return Call(SCI_SEARCHNEXT, static_cast<WPARAM>(flags), reinterpret_cast<LPARAM>(text), bDirect); } int CCT3000CO2_NET::SearchPrev(int flags, const char* text, BOOL bDirect) { return Call(SCI_SEARCHPREV, static_cast<WPARAM>(flags), reinterpret_cast<LPARAM>(text), bDirect); } int CCT3000CO2_NET::LinesOnScreen(BOOL bDirect) { return Call(SCI_LINESONSCREEN, 0, 0, bDirect); } void CCT3000CO2_NET::UsePopUp(BOOL allowPopUp, BOOL bDirect) { Call(SCI_USEPOPUP, static_cast<WPARAM>(allowPopUp), 0, bDirect); } BOOL CCT3000CO2_NET::SelectionIsRectangle(BOOL bDirect) { return Call(SCI_SELECTIONISRECTANGLE, 0, 0, bDirect); } void CCT3000CO2_NET::SetZoom(int zoom, BOOL bDirect) { Call(SCI_SETZOOM, static_cast<WPARAM>(zoom), 0, bDirect); } int CCT3000CO2_NET::GetZoom(BOOL bDirect) { return Call(SCI_GETZOOM, 0, 0, bDirect); } int CCT3000CO2_NET::CreateDocument(BOOL bDirect) { return Call(SCI_CREATEDOCUMENT, 0, 0, bDirect); } void CCT3000CO2_NET::AddRefDocument(int doc, BOOL bDirect) { Call(SCI_ADDREFDOCUMENT, 0, static_cast<LPARAM>(doc), bDirect); } void CCT3000CO2_NET::ReleaseDocument(int doc, BOOL bDirect) { Call(SCI_RELEASEDOCUMENT, 0, static_cast<LPARAM>(doc), bDirect); } int CCT3000CO2_NET::GetModEventMask(BOOL bDirect) { return Call(SCI_GETMODEVENTMASK, 0, 0, bDirect); } void CCT3000CO2_NET::SCISetFocus(BOOL focus, BOOL bDirect) { Call(SCI_SETFOCUS, static_cast<WPARAM>(focus), 0, bDirect); } BOOL CCT3000CO2_NET::GetFocus(BOOL bDirect) { return Call(SCI_GETFOCUS, 0, 0, bDirect); } void CCT3000CO2_NET::SetStatus(int statusCode, BOOL bDirect) { Call(SCI_SETSTATUS, static_cast<WPARAM>(statusCode), 0, bDirect); } int CCT3000CO2_NET::GetStatus(BOOL bDirect) { return Call(SCI_GETSTATUS, 0, 0, bDirect); } void CCT3000CO2_NET::SetMouseDownCaptures(BOOL captures, BOOL bDirect) { Call(SCI_SETMOUSEDOWNCAPTURES, static_cast<WPARAM>(captures), 0, bDirect); } BOOL CCT3000CO2_NET::GetMouseDownCaptures(BOOL bDirect) { return Call(SCI_GETMOUSEDOWNCAPTURES, 0, 0, bDirect); } void CCT3000CO2_NET::SetCursor(int cursorType, BOOL bDirect) { Call(SCI_SETCURSOR, static_cast<WPARAM>(cursorType), 0, bDirect); } int CCT3000CO2_NET::GetCursor(BOOL bDirect) { return Call(SCI_GETCURSOR, 0, 0, bDirect); } void CCT3000CO2_NET::SetControlCharSymbol(int symbol, BOOL bDirect) { Call(SCI_SETCONTROLCHARSYMBOL, static_cast<WPARAM>(symbol), 0, bDirect); } int CCT3000CO2_NET::GetControlCharSymbol(BOOL bDirect) { return Call(SCI_GETCONTROLCHARSYMBOL, 0, 0, bDirect); } void CCT3000CO2_NET::WordPartLeft(BOOL bDirect) { Call(SCI_WORDPARTLEFT, 0, 0, bDirect); } void CCT3000CO2_NET::WordPartLeftExtend(BOOL bDirect) { Call(SCI_WORDPARTLEFTEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::WordPartRight(BOOL bDirect) { Call(SCI_WORDPARTRIGHT, 0, 0, bDirect); } void CCT3000CO2_NET::WordPartRightExtend(BOOL bDirect) { Call(SCI_WORDPARTRIGHTEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::SetVisiblePolicy(int visiblePolicy, int visibleSlop, BOOL bDirect) { Call(SCI_SETVISIBLEPOLICY, static_cast<WPARAM>(visiblePolicy), static_cast<LPARAM>(visibleSlop), bDirect); } void CCT3000CO2_NET::DelLineLeft(BOOL bDirect) { Call(SCI_DELLINELEFT, 0, 0, bDirect); } void CCT3000CO2_NET::DelLineRight(BOOL bDirect) { Call(SCI_DELLINERIGHT, 0, 0, bDirect); } void CCT3000CO2_NET::SetXOffset(int newOffset, BOOL bDirect) { Call(SCI_SETXOFFSET, static_cast<WPARAM>(newOffset), 0, bDirect); } int CCT3000CO2_NET::GetXOffset(BOOL bDirect) { return Call(SCI_GETXOFFSET, 0, 0, bDirect); } void CCT3000CO2_NET::ChooseCaretX(BOOL bDirect) { Call(SCI_CHOOSECARETX, 0, 0, bDirect); } void CCT3000CO2_NET::GrabFocus(BOOL bDirect) { Call(SCI_GRABFOCUS, 0, 0, bDirect); } void CCT3000CO2_NET::SetXCaretPolicy(int caretPolicy, int caretSlop, BOOL bDirect) { Call(SCI_SETXCARETPOLICY, static_cast<WPARAM>(caretPolicy), static_cast<LPARAM>(caretSlop), bDirect); } void CCT3000CO2_NET::SetYCaretPolicy(int caretPolicy, int caretSlop, BOOL bDirect) { Call(SCI_SETYCARETPOLICY, static_cast<WPARAM>(caretPolicy), static_cast<LPARAM>(caretSlop), bDirect); } void CCT3000CO2_NET::SetPrintWrapMode(int mode, BOOL bDirect) { Call(SCI_SETPRINTWRAPMODE, static_cast<WPARAM>(mode), 0, bDirect); } int CCT3000CO2_NET::GetPrintWrapMode(BOOL bDirect) { return Call(SCI_GETPRINTWRAPMODE, 0, 0, bDirect); } void CCT3000CO2_NET::SetHotspotActiveFore(BOOL useSetting, COLORREF fore, BOOL bDirect) { Call(SCI_SETHOTSPOTACTIVEFORE, static_cast<WPARAM>(useSetting), static_cast<LPARAM>(fore), bDirect); } COLORREF CCT3000CO2_NET::GetHotspotActiveFore(BOOL bDirect) { return Call(SCI_GETHOTSPOTACTIVEFORE, 0, 0, bDirect); } void CCT3000CO2_NET::SetHotspotActiveBack(BOOL useSetting, COLORREF back, BOOL bDirect) { Call(SCI_SETHOTSPOTACTIVEBACK, static_cast<WPARAM>(useSetting), static_cast<LPARAM>(back), bDirect); } COLORREF CCT3000CO2_NET::GetHotspotActiveBack(BOOL bDirect) { return Call(SCI_GETHOTSPOTACTIVEBACK, 0, 0, bDirect); } void CCT3000CO2_NET::SetHotspotActiveUnderline(BOOL underline, BOOL bDirect) { Call(SCI_SETHOTSPOTACTIVEUNDERLINE, static_cast<WPARAM>(underline), 0, bDirect); } BOOL CCT3000CO2_NET::GetHotspotActiveUnderline(BOOL bDirect) { return Call(SCI_GETHOTSPOTACTIVEUNDERLINE, 0, 0, bDirect); } void CCT3000CO2_NET::SetHotspotSingleLine(BOOL singleLine, BOOL bDirect) { Call(SCI_SETHOTSPOTSINGLELINE, static_cast<WPARAM>(singleLine), 0, bDirect); } BOOL CCT3000CO2_NET::GetHotspotSingleLine(BOOL bDirect) { return Call(SCI_GETHOTSPOTSINGLELINE, 0, 0, bDirect); } void CCT3000CO2_NET::ParaDown(BOOL bDirect) { Call(SCI_PARADOWN, 0, 0, bDirect); } void CCT3000CO2_NET::ParaDownExtend(BOOL bDirect) { Call(SCI_PARADOWNEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::ParaUp(BOOL bDirect) { Call(SCI_PARAUP, 0, 0, bDirect); } void CCT3000CO2_NET::ParaUpExtend(BOOL bDirect) { Call(SCI_PARAUPEXTEND, 0, 0, bDirect); } long CCT3000CO2_NET::PositionBefore(long pos, BOOL bDirect) { return Call(SCI_POSITIONBEFORE, static_cast<WPARAM>(pos), 0, bDirect); } long CCT3000CO2_NET::PositionAfter(long pos, BOOL bDirect) { return Call(SCI_POSITIONAFTER, static_cast<WPARAM>(pos), 0, bDirect); } void CCT3000CO2_NET::CopyRange(long start, long end, BOOL bDirect) { Call(SCI_COPYRANGE, static_cast<WPARAM>(start), static_cast<LPARAM>(end), bDirect); } void CCT3000CO2_NET::CopyText(int length, const char* text, BOOL bDirect) { Call(SCI_COPYTEXT, static_cast<WPARAM>(length), reinterpret_cast<LPARAM>(text), bDirect); } void CCT3000CO2_NET::SetSelectionMode(int mode, BOOL bDirect) { Call(SCI_SETSELECTIONMODE, static_cast<WPARAM>(mode), 0, bDirect); } int CCT3000CO2_NET::GetSelectionMode(BOOL bDirect) { return Call(SCI_GETSELECTIONMODE, 0, 0, bDirect); } long CCT3000CO2_NET::GetLineSelStartPosition(int line, BOOL bDirect) { return Call(SCI_GETLINESELSTARTPOSITION, static_cast<WPARAM>(line), 0, bDirect); } long CCT3000CO2_NET::GetLineSelEndPosition(int line, BOOL bDirect) { return Call(SCI_GETLINESELENDPOSITION, static_cast<WPARAM>(line), 0, bDirect); } void CCT3000CO2_NET::LineDownRectExtend(BOOL bDirect) { Call(SCI_LINEDOWNRECTEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::LineUpRectExtend(BOOL bDirect) { Call(SCI_LINEUPRECTEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::CharLeftRectExtend(BOOL bDirect) { Call(SCI_CHARLEFTRECTEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::CharRightRectExtend(BOOL bDirect) { Call(SCI_CHARRIGHTRECTEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::HomeRectExtend(BOOL bDirect) { Call(SCI_HOMERECTEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::VCHomeRectExtend(BOOL bDirect) { Call(SCI_VCHOMERECTEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::LineEndRectExtend(BOOL bDirect) { Call(SCI_LINEENDRECTEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::PageUpRectExtend(BOOL bDirect) { Call(SCI_PAGEUPRECTEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::PageDownRectExtend(BOOL bDirect) { Call(SCI_PAGEDOWNRECTEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::StutteredPageUp(BOOL bDirect) { Call(SCI_STUTTEREDPAGEUP, 0, 0, bDirect); } void CCT3000CO2_NET::StutteredPageUpExtend(BOOL bDirect) { Call(SCI_STUTTEREDPAGEUPEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::StutteredPageDown(BOOL bDirect) { Call(SCI_STUTTEREDPAGEDOWN, 0, 0, bDirect); } void CCT3000CO2_NET::StutteredPageDownExtend(BOOL bDirect) { Call(SCI_STUTTEREDPAGEDOWNEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::WordLeftEnd(BOOL bDirect) { Call(SCI_WORDLEFTEND, 0, 0, bDirect); } void CCT3000CO2_NET::WordLeftEndExtend(BOOL bDirect) { Call(SCI_WORDLEFTENDEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::WordRightEnd(BOOL bDirect) { Call(SCI_WORDRIGHTEND, 0, 0, bDirect); } void CCT3000CO2_NET::WordRightEndExtend(BOOL bDirect) { Call(SCI_WORDRIGHTENDEXTEND, 0, 0, bDirect); } void CCT3000CO2_NET::SetWhitespaceChars(const char* characters, BOOL bDirect) { Call(SCI_SETWHITESPACECHARS, 0, reinterpret_cast<LPARAM>(characters), bDirect); } void CCT3000CO2_NET::SetCharsDefault(BOOL bDirect) { Call(SCI_SETCHARSDEFAULT, 0, 0, bDirect); } int CCT3000CO2_NET::AutoCGetCurrent(BOOL bDirect) { return Call(SCI_AUTOCGETCURRENT, 0, 0, bDirect); } void CCT3000CO2_NET::Allocate(int bytes, BOOL bDirect) { Call(SCI_ALLOCATE, static_cast<WPARAM>(bytes), 0, bDirect); } int CCT3000CO2_NET::TargetAsUTF8(char* s, BOOL bDirect) { return Call(SCI_TARGETASUTF8, 0, reinterpret_cast<LPARAM>(s), bDirect); } void CCT3000CO2_NET::SetLengthForEncode(int bytes, BOOL bDirect) { Call(SCI_SETLENGTHFORENCODE, static_cast<WPARAM>(bytes), 0, bDirect); } int CCT3000CO2_NET::EncodedFromUTF8(const char* utf8, char* encoded, BOOL bDirect) { return Call(SCI_ENCODEDFROMUTF8, reinterpret_cast<WPARAM>(utf8), reinterpret_cast<LPARAM>(encoded), bDirect); } int CCT3000CO2_NET::FindColumn(int line, int column, BOOL bDirect) { return Call(SCI_FINDCOLUMN, static_cast<WPARAM>(line), static_cast<LPARAM>(column), bDirect); } BOOL CCT3000CO2_NET::GetCaretSticky(BOOL bDirect) { return Call(SCI_GETCARETSTICKY, 0, 0, bDirect); } void CCT3000CO2_NET::SetCaretSticky(BOOL useCaretStickyBehaviour, BOOL bDirect) { Call(SCI_SETCARETSTICKY, static_cast<WPARAM>(useCaretStickyBehaviour), 0, bDirect); } void CCT3000CO2_NET::ToggleCaretSticky(BOOL bDirect) { Call(SCI_TOGGLECARETSTICKY, 0, 0, bDirect); } void CCT3000CO2_NET::SetPasteConvertEndings(BOOL convert, BOOL bDirect) { Call(SCI_SETPASTECONVERTENDINGS, static_cast<WPARAM>(convert), 0, bDirect); } BOOL CCT3000CO2_NET::GetPasteConvertEndings(BOOL bDirect) { return Call(SCI_GETPASTECONVERTENDINGS, 0, 0, bDirect); } void CCT3000CO2_NET::SelectionDuplicate(BOOL bDirect) { Call(SCI_SELECTIONDUPLICATE, 0, 0, bDirect); } void CCT3000CO2_NET::SetCaretLineBackAlpha(int alpha, BOOL bDirect) { Call(SCI_SETCARETLINEBACKALPHA, static_cast<WPARAM>(alpha), 0, bDirect); } int CCT3000CO2_NET::GetCaretLineBackAlpha(BOOL bDirect) { return Call(SCI_GETCARETLINEBACKALPHA, 0, 0, bDirect); } void CCT3000CO2_NET::SetCaretStyle(int caretStyle, BOOL bDirect) { Call(SCI_SETCARETSTYLE, static_cast<WPARAM>(caretStyle), 0, bDirect); } int CCT3000CO2_NET::GetCaretStyle(BOOL bDirect) { return Call(SCI_GETCARETSTYLE, 0, 0, bDirect); } void CCT3000CO2_NET::SetIndicatorCurrent(int indicator, BOOL bDirect) { Call(SCI_SETINDICATORCURRENT, static_cast<WPARAM>(indicator), 0, bDirect); } int CCT3000CO2_NET::GetIndicatorCurrent(BOOL bDirect) { return Call(SCI_GETINDICATORCURRENT, 0, 0, bDirect); } void CCT3000CO2_NET::SetIndicatorValue(int value, BOOL bDirect) { Call(SCI_SETINDICATORVALUE, static_cast<WPARAM>(value), 0, bDirect); } int CCT3000CO2_NET::GetIndicatorValue(BOOL bDirect) { return Call(SCI_GETINDICATORVALUE, 0, 0, bDirect); } void CCT3000CO2_NET::IndicatorFillRange(int position, int fillLength, BOOL bDirect) { Call(SCI_INDICATORFILLRANGE, static_cast<WPARAM>(position), static_cast<LPARAM>(fillLength), bDirect); } void CCT3000CO2_NET::IndicatorClearRange(int position, int clearLength, BOOL bDirect) { Call(SCI_INDICATORCLEARRANGE, static_cast<WPARAM>(position), static_cast<LPARAM>(clearLength), bDirect); } int CCT3000CO2_NET::IndicatorAllOnFor(int position, BOOL bDirect) { return Call(SCI_INDICATORALLONFOR, static_cast<WPARAM>(position), 0, bDirect); } int CCT3000CO2_NET::IndicatorValueAt(int indicator, int position, BOOL bDirect) { return Call(SCI_INDICATORVALUEAT, static_cast<WPARAM>(indicator), static_cast<LPARAM>(position), bDirect); } int CCT3000CO2_NET::IndicatorStart(int indicator, int position, BOOL bDirect) { return Call(SCI_INDICATORSTART, static_cast<WPARAM>(indicator), static_cast<LPARAM>(position), bDirect); } int CCT3000CO2_NET::IndicatorEnd(int indicator, int position, BOOL bDirect) { return Call(SCI_INDICATOREND, static_cast<WPARAM>(indicator), static_cast<LPARAM>(position), bDirect); } void CCT3000CO2_NET::SetPositionCache(int size, BOOL bDirect) { Call(SCI_SETPOSITIONCACHE, static_cast<WPARAM>(size), 0, bDirect); } int CCT3000CO2_NET::GetPositionCache(BOOL bDirect) { return Call(SCI_GETPOSITIONCACHE, 0, 0, bDirect); } void CCT3000CO2_NET::CopyAllowLine(BOOL bDirect) { Call(SCI_COPYALLOWLINE, 0, 0, bDirect); } void CCT3000CO2_NET::StartRecord(BOOL bDirect) { Call(SCI_STARTRECORD, 0, 0, bDirect); } void CCT3000CO2_NET::StopRecord(BOOL bDirect) { Call(SCI_STOPRECORD, 0, 0, bDirect); } void CCT3000CO2_NET::SetLexer(int lexer, BOOL bDirect) { Call(SCI_SETLEXER, static_cast<WPARAM>(lexer), 0, bDirect); } int CCT3000CO2_NET::GetLexer(BOOL bDirect) { return Call(SCI_GETLEXER, 0, 0, bDirect); } void CCT3000CO2_NET::Colourise(long start, long end, BOOL bDirect) { Call(SCI_COLOURISE, static_cast<WPARAM>(start), static_cast<LPARAM>(end), bDirect); } void CCT3000CO2_NET::SetProperty(const char* key, const char* value, BOOL bDirect) { Call(SCI_SETPROPERTY, reinterpret_cast<WPARAM>(key), reinterpret_cast<LPARAM>(value), bDirect); } void CCT3000CO2_NET::SetKeyWords(int keywordSet, const char* keyWords, BOOL bDirect) { Call(SCI_SETKEYWORDS, static_cast<WPARAM>(keywordSet), reinterpret_cast<LPARAM>(keyWords), bDirect); } void CCT3000CO2_NET::SetLexerLanguage(const char* language, BOOL bDirect) { Call(SCI_SETLEXERLANGUAGE, 0, reinterpret_cast<LPARAM>(language), bDirect); } void CCT3000CO2_NET::LoadLexerLibrary(const char* path, BOOL bDirect) { Call(SCI_LOADLEXERLIBRARY, 0, reinterpret_cast<LPARAM>(path), bDirect); } int CCT3000CO2_NET::GetProperty(const char* key, char* buf, BOOL bDirect) { return Call(SCI_GETPROPERTY, reinterpret_cast<WPARAM>(key), reinterpret_cast<LPARAM>(buf), bDirect); } int CCT3000CO2_NET::GetPropertyExpanded(const char* key, char* buf, BOOL bDirect) { return Call(SCI_GETPROPERTYEXPANDED, reinterpret_cast<WPARAM>(key), reinterpret_cast<LPARAM>(buf), bDirect); } int CCT3000CO2_NET::GetPropertyInt(const char* key, BOOL bDirect) { return Call(SCI_GETPROPERTYINT, reinterpret_cast<WPARAM>(key), 0, bDirect); } int CCT3000CO2_NET::GetStyleBitsNeeded(BOOL bDirect) { return Call(SCI_GETSTYLEBITSNEEDED, 0, 0, bDirect); }
26.408769
121
0.758801
DHSERVICE56
7cf90679a996e3f5739e32c797498b44e4d14691
1,320
cpp
C++
code-forces/Educational 87/DCopy.cpp
ErickJoestar/competitive-programming
76afb766dbc18e16315559c863fbff19a955a569
[ "MIT" ]
1
2020-04-23T00:35:38.000Z
2020-04-23T00:35:38.000Z
code-forces/Educational 87/DCopy.cpp
ErickJoestar/competitive-programming
76afb766dbc18e16315559c863fbff19a955a569
[ "MIT" ]
null
null
null
code-forces/Educational 87/DCopy.cpp
ErickJoestar/competitive-programming
76afb766dbc18e16315559c863fbff19a955a569
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define ENDL '\n' #define deb(u) cout << #u " : " << (u) << ENDL; #define deba(alias, u) cout << alias << ": " << (u) << ENDL; #define debp(u, v) cout << u << " : " << v << ENDL; #define pb push_back #define F first #define S second #define lli long long #define pii pair<int, int> #define pll pair<lli, lli> #define ALL(a) (a).begin(), (a).end() #define ALLR(a) (a).rbegin(), (a).rend() #define FOR(i, a, n) for (int i = (a); i < (n); ++i) #define FORN(i, a, n) for (int i = (a - 1); i >= n; --i) #define IO \ ios_base::sync_with_stdio(false); \ cin.tie(0); \ cout.tie(0) using namespace std; int main() { IO; int n, q; cin >> n >> q; vector<pii> v; vector<int> queries; ///Reasing all the numbers FOR(i, 0, n) { pii aux = {0, -1}; cin >> aux.F; v.pb(aux); } //Asigning the initial position sort(ALL(v)); FOR(i, 0, n) v[i].S = i; //Reading all the queries FOR(i, 0, q) { int opt; cin >> opt; if (opt < 0) queries.pb(-opt); else v.pb(make_pair(opt, -1)); } /// Reasigning position in the array sort(ALL(v)); FOR(i, 1, v.size()) { v[i].S = max(v[i].S, v[i - 1].S); } /* -- > Debug for (auto p : v) { debp(p.F, p.S); } */ return 0; }
19.411765
60
0.496212
ErickJoestar
cfaa4a625fb4a16b09240046624c037b68a315b6
1,834
cpp
C++
src/data/long_distance_social_distancing_ii.cpp
ACM-UCI/ACM-UCI-Website
6092db56b50f5c6d26a6e9ad65adb553f44ccb5f
[ "MIT" ]
3
2019-02-02T02:46:23.000Z
2020-08-14T14:04:04.000Z
src/data/long_distance_social_distancing_ii.cpp
ACM-UCI/ACM-UCI-Website
6092db56b50f5c6d26a6e9ad65adb553f44ccb5f
[ "MIT" ]
47
2019-02-01T08:50:24.000Z
2022-03-01T18:35:05.000Z
src/data/long_distance_social_distancing_ii.cpp
ACM-UCI/ACM-UCI-Website
6092db56b50f5c6d26a6e9ad65adb553f44ccb5f
[ "MIT" ]
5
2018-11-30T03:10:08.000Z
2020-09-22T06:37:50.000Z
#include <string> #include <iterator> #include <iostream> #include <algorithm> #include <array> using namespace std; #define LL long long #define UL unsigned long #define matrix array<array<LL, 5>, 5> #define vector array<LL, 5> LL mod = 1000000007; matrix matmul(matrix a, matrix b) { matrix c; for (unsigned long i = 0; i < a.size(); i++) { for (unsigned long j = 0; j < b.size(); j++) { c[i][j] = 0; for (unsigned long k = 0; k < 5; k++) { c[i][j] += (a[i][k] * b[k][j]) % mod; c[i][j] %= mod; } } } return c; } vector matmul(matrix a, vector b) { vector c; for (int i = 0; i < 5; i++) { c[i] = 0; for (int j = 0; j < 5; j++) { c[i] += (a[i][j] * b[i]) % mod; c[i] %= mod; } } return c; } matrix pow(matrix mat, long p) { if (p == 0) return matrix{{{1, 0, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 0}, {0, 0, 0, 0, 1}}}; matrix temp = pow(mat, p / 2); if (p % 2 == 0) return matmul(temp, temp); return matmul(matmul(temp, temp), mat); } LL solve(LL t) { if (t == 0) return 1; matrix init = matrix{{{1, 1, 1, 1, 1}, {1, 0, 1, 1, 0}, {1, 1, 0, 1, 1}, {1, 1, 1, 0, 0}, {1, 0, 1, 0, 0}}}; matrix result = pow(init, t - 1); vector lastRow = matmul(result, vector{1, 1, 1, 1, 1}); LL s = 0; for (int i = 0; i < 5; i++) { s += lastRow[i]; s %= mod; } return (s * s) % mod; } int main() { int t; LL c; cin >> t; for (int i = 0; i < t; i++) { cin >> c; cout << solve(c) << endl; } }
20.840909
109
0.401309
ACM-UCI
cfaead4da4e3c588cab43e9c6f64acff48fbb9dd
4,198
hpp
C++
includes/zab/strong_types.hpp
HungMingWu/zab
9e9fd78d192b4d037a6edbbd4c1474bd6e01feaf
[ "MIT" ]
null
null
null
includes/zab/strong_types.hpp
HungMingWu/zab
9e9fd78d192b4d037a6edbbd4c1474bd6e01feaf
[ "MIT" ]
null
null
null
includes/zab/strong_types.hpp
HungMingWu/zab
9e9fd78d192b4d037a6edbbd4c1474bd6e01feaf
[ "MIT" ]
null
null
null
/* * MMM"""AMV db `7MM"""Yp, * M' AMV ;MM: MM Yb * ' AMV ,V^MM. MM dP * AMV ,M `MM MM"""bg. * AMV , AbmmmqMA MM `Y * AMV ,M A' VML MM ,9 * AMVmmmmMM .AMA. .AMMA..JMMmmmd9 * * * MIT License * * Copyright (c) 2021 Donald-Rupin * * 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. * * @file strong_types.hpp * */ #ifndef ZAB_STRONG_TYPES_HPP_ #define ZAB_STRONG_TYPES_HPP_ #include <chrono> #include <concepts> #include <cstdint> #include <limits> #include <ostream> namespace zab { /** * @brief A struct for providing strict typing of thread ids'. */ struct thread_t { std::uint16_t thread_ = std::numeric_limits<std::uint16_t>::max(); constexpr auto operator<=>(const thread_t& _other) const = default; template <std::integral Intergral> constexpr auto operator<=>(const Intergral _number) const { return thread_ <=> _number; } }; namespace thread { constexpr auto in(std::uint16_t _thread) noexcept { return thread_t{_thread}; } constexpr auto any() noexcept { return thread_t{}; } } inline std::ostream& operator<<(std::ostream& os, const thread_t _thread) { os << "thread[" << _thread.thread_ << "]"; return os; } /** * @brief A struct for providing strict typing for ordering. */ struct order_t { int64_t order_ = std::chrono::high_resolution_clock::now().time_since_epoch().count(); constexpr auto operator<=>(const order_t& _other) const = default; template <std::integral Intergral> constexpr auto operator<=>(const Intergral _number) const { return order_ <=> _number; } friend constexpr auto operator +(order_t _lhs, order_t _rhs) noexcept { return order_t{_lhs.order_ + _rhs.order_}; } friend constexpr auto operator -(order_t _lhs, order_t _rhs) noexcept { return order_t{_lhs.order_ - _rhs.order_}; } }; namespace order { inline constexpr order_t seconds(int64_t _number) noexcept { return order_t{_number * 1000000000}; } inline constexpr order_t milli(int64_t _number) noexcept { return order_t{_number * 1000000}; } inline order_t now() noexcept { return order_t{}; } inline order_t in_seconds(int64_t _number) noexcept { return now() + order_t{_number * 1000000000}; } inline order_t in_milli(int64_t _number) noexcept { return now() + order_t{_number * 1000000000}; } } // namespace order } // namespace zab #endif /* ZAB_STRONG_TYPES_HPP_ */
27.25974
98
0.579085
HungMingWu
cfb01a5642f0ac3348c7fb8eeea86a80aecac072
1,503
hpp
C++
server/common/log.hpp
egor-tensin/math-server
25f810714ea8249da0a5e30fb0297e9055b70d50
[ "MIT" ]
null
null
null
server/common/log.hpp
egor-tensin/math-server
25f810714ea8249da0a5e30fb0297e9055b70d50
[ "MIT" ]
null
null
null
server/common/log.hpp
egor-tensin/math-server
25f810714ea8249da0a5e30fb0297e9055b70d50
[ "MIT" ]
null
null
null
// Copyright (c) 2019 Egor Tensin <Egor.Tensin@gmail.com> // This file is part of the "math-server" project. // For details, see https://github.com/egor-tensin/math-server. // Distributed under the MIT License. #pragma once #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/format.hpp> #include <boost/system/error_code.hpp> #include <ctime> #include <iomanip> #include <iostream> #include <sstream> #include <string> #include <string_view> #include <thread> #include <utility> namespace math::server::log { namespace details { inline std::thread::id get_tid() { return std::this_thread::get_id(); } inline std::string get_timestamp() { const auto now = boost::posix_time::second_clock::universal_time(); const auto tm = boost::posix_time::to_tm(now); std::ostringstream oss; oss << std::put_time(&tm, "%Y-%m-%d %H:%M:%S"); return oss.str(); } inline void log(const std::string& msg) { std::clog << get_timestamp() << " | " << get_tid() << " | " << msg << '\n'; } } // namespace details template <typename... Args> inline void log(const std::string_view& fmt, Args&&... args) { details::log(boost::str((boost::format(fmt.data()) % ... % args))); } template <typename... Args> inline void error(const std::string_view& fmt, Args&&... args) { details::log(boost::str((boost::format(fmt.data()) % ... % args))); } inline void error(const boost::system::error_code& ec) { details::log(ec.message()); } } // namespace math::server::log
25.913793
79
0.664005
egor-tensin
cfb1b1b6dd2452a008e0f423dac3da12302fee92
509
cc
C++
stl/list.cc
Becavalier/playground-cpp
0fce453f769111698f813852238f933e326ed441
[ "MIT" ]
1
2018-02-23T11:12:17.000Z
2018-02-23T11:12:17.000Z
stl/list.cc
Becavalier/playground-cpp
0fce453f769111698f813852238f933e326ed441
[ "MIT" ]
null
null
null
stl/list.cc
Becavalier/playground-cpp
0fce453f769111698f813852238f933e326ed441
[ "MIT" ]
null
null
null
#include <iostream> #include <list> #include <iterator> using namespace std; int main (int argc, char *argv[]) { list<int> lint; // List is a kind of "linked list"; for (int i = 0; i < 5; i++) { lint.push_back(i * i); } list<int>::iterator it; for (it = lint.begin(); it != lint.end(); it++) { cout << *it << endl; } lint.reverse(); for (list<int>::reverse_iterator it = lint.rbegin(); it != lint.rend(); it++) { cout << *it << endl; } }
18.851852
83
0.516699
Becavalier
cfb505f74f6d71b58ea0b4f34dc4e99796049a70
574
cpp
C++
_site/Competitive Programming/Hackerearth/Bishu and Soldiers.cpp
anujkyadav07/anuj-k-yadav.github.io
ac5cccc8cdada000ba559538cd84921437b3c5e6
[ "MIT" ]
1
2019-06-10T04:39:49.000Z
2019-06-10T04:39:49.000Z
_site/Competitive Programming/Hackerearth/Bishu and Soldiers.cpp
anujkyadav07/anuj-k-yadav.github.io
ac5cccc8cdada000ba559538cd84921437b3c5e6
[ "MIT" ]
2
2021-09-27T23:34:07.000Z
2022-02-26T05:54:27.000Z
_site/Competitive Programming/Hackerearth/Bishu and Soldiers.cpp
anujkyadav07/anuj-k-yadav.github.io
ac5cccc8cdada000ba559538cd84921437b3c5e6
[ "MIT" ]
3
2019-06-23T14:15:08.000Z
2019-07-09T20:40:58.000Z
#include <bits/stdc++.h> using namespace std; int main(){ int n, q, a; cin>>n; vector<int> arr; for (int i = 0; i < n; ++i) { cin>>a; arr.push_back(a); } cin>>q; int p[q]; /*for (int i = 0; i < q; ++i) { cin>>p[i]; }*/ sort(arr.begin(),arr.end()); for (int i = 0; i < q; ++i) { cin>>a; vector<int>::iterator lower; lower = upper_bound(arr.begin(),arr.end(),a); int idx = lower - arr.begin(); int sum = 0, cnt = 0; for (int i = 0; i < idx; ++i) { if(arr[i] <= a){ sum += arr[i]; cnt++; } } cout<<cnt<<" "<<sum<<"\n"; } }
15.513514
47
0.473868
anujkyadav07
cfb59658a0181e11c6c4d87befc61cfff554f507
1,697
cpp
C++
Level3/Level3/Level 3/Section 2.2/Exercise 2.2.1/TestProgram.cpp
chunyuyuan/My-Solution-for-C-Programming-for-Financial-Engineering
478b414714edbea1ebdc2f565baad6f04f54bc70
[ "MIT" ]
1
2021-09-12T08:15:57.000Z
2021-09-12T08:15:57.000Z
Level3/Level3/Level 3/Section 2.2/Exercise 2.2.1/TestProgram.cpp
chunyuyuan/My-Solution-for-C-Programming-for-Financial-Engineering
478b414714edbea1ebdc2f565baad6f04f54bc70
[ "MIT" ]
null
null
null
Level3/Level3/Level 3/Section 2.2/Exercise 2.2.1/TestProgram.cpp
chunyuyuan/My-Solution-for-C-Programming-for-Financial-Engineering
478b414714edbea1ebdc2f565baad6f04f54bc70
[ "MIT" ]
null
null
null
/* * Level_3 Exercise 2.2.1: * Test program for point class * * @file TestProgram.cpp * @author Chunyu Yuan * @version 1.0 02/08/2021 * */ #include "Point.hpp" // Header file for point class #include <iostream> // Standard Input / Output Streams Library /* * Controls operation of the program * Return type of main() expects an int * * @function main() * @param none * @return 0 */ int main() { double x, y; // declare two double value x and y for X coordinate and Y coordinate std::cout << "Please input point x coordinate:" << std::endl; // remind user to input X coordinate std::cin >> x; //promote user input value and assign value to x std::cout << "Please input point y coordinate:" << std::endl;// remind user to input Y coordinate std::cin >> y;//promote user input value and assign value to y Point point; //create a Point object using the default constructor point.SetX(x); //Set the X coordinate entered by the user using the X setter function point.SetY(y); //Set the Y coordinate entered by the user using the Y setter function std::cout << "\nCall ToString()" << std::endl; //remind user calling ToString function std::cout << point.ToString() << std::endl; // print the point information std::cout << "\nCall GetX() function" << std::endl; //remind user calling GetX() function std::cout <<"Point's x coordinate: "<< point.GetX() << std::endl; //Print the point X coordinate using the get x function std::cout << "\nCall GetY() function" << std::endl; // remind user calling GetY() function std::cout << "Point's y coordinate: " << point.GetY() << std::endl;//Print the point X coordinate using the get y function return 0;// return 0 to end program }
34.632653
123
0.690631
chunyuyuan
cfbbcc6c25f6bde73a20fbe38b313f5b067b00b5
1,474
cpp
C++
book/basics/names/Puzzle.cpp
luanics/cpp-illustrated
6049de2119a53d656a63b65d9441e680355ef196
[ "MIT" ]
null
null
null
book/basics/names/Puzzle.cpp
luanics/cpp-illustrated
6049de2119a53d656a63b65d9441e680355ef196
[ "MIT" ]
null
null
null
book/basics/names/Puzzle.cpp
luanics/cpp-illustrated
6049de2119a53d656a63b65d9441e680355ef196
[ "MIT" ]
null
null
null
#include <iostream> int x; namespace Y { int a; void f(float) {} void h(int) {} } namespace Z { void h(double) {} } namespace A { using namespace Y; void f(int) {} void g(int) {} void g() {} int i; } namespace B { using namespace Z; void f(char) {} int i; } namespace AB { using namespace A; using namespace B; void g() {A::i = 2;} void A() {g();} } void h() { int AB; // OK - this won't interfere with names below as nested name specifiers don't match variables AB::g(); // AB is searched, AB::g found by lookup and is chosen AB::g(void) // (A and B are not searched) AB::f(1); // First, AB is searched, there is no f // Then, A, B are searched // A::f, B::f found by lookup (but Y is not searched so Y::f is not considered) // overload resolution picks A::f(int) // AB::x++; // First, AB is searched, there is no x // Then A, B are searched. There is no x // Then Y and Z are searched. There is still no x: this is an error // AB::i++; // AB is searched, there is no i // Then A, B are searched. A::i and B::i found by lookup: this is an error AB::h(16.8); // First, AB is searched: there is no h // Then A, B are searched. There is no h // Then Y and Z are searched. // lookup finds Y::h and Z::h. Overload resolution picks Z::h(double) } int main(int argc, char ** argv) { return 0; }
27.296296
102
0.565129
luanics
cfbc761c900f7fd17d6e2b0b00ef46aaeb0c8117
6,161
hpp
C++
src/vtu11/vtu11/impl/writer_impl.hpp
gtsc/HPC-divers-license
fa1493e217ff76a407feea9b80623eca4691e044
[ "BSD-3-Clause" ]
7
2020-01-07T16:38:31.000Z
2022-01-26T19:23:26.000Z
src/vtu11/vtu11/impl/writer_impl.hpp
gtsc/HPC-divers-license
fa1493e217ff76a407feea9b80623eca4691e044
[ "BSD-3-Clause" ]
25
2020-01-13T17:38:43.000Z
2021-12-09T11:58:15.000Z
vtu11/impl/writer_impl.hpp
phmkopp/vtu11
7afb9e33d076536af3ac333211a7a78576d582bf
[ "BSD-3-Clause" ]
3
2020-04-08T10:46:23.000Z
2020-04-15T18:34:41.000Z
// __ ____ ____ // ___ ___/ |_ __ _/_ /_ | // \ \/ /\ __\ | \ || | // \ / | | | | / || | // \_/ |__| |____/|___||___| // // License: BSD License ; see LICENSE // #ifndef VTU11_WRITER_IMPL_HPP #define VTU11_WRITER_IMPL_HPP #include "vtu11/inc/utilities.hpp" #include <fstream> namespace vtu11 { namespace detail { template<typename T> inline void writeNumber( char (&buffer)[64], T value ) { VTU11_THROW( "Invalid data type." ); } #define __VTU11_WRITE_NUMBER_SPECIALIZATION( string, type ) \ template<> inline \ void writeNumber<type>( char (&buffer)[64], type value ) \ { \ std::snprintf( buffer, sizeof( buffer ), string, value ); \ } __VTU11_WRITE_NUMBER_SPECIALIZATION( VTU11_ASCII_FLOATING_POINT_FORMAT, double ) __VTU11_WRITE_NUMBER_SPECIALIZATION( "%lld", long long int ) __VTU11_WRITE_NUMBER_SPECIALIZATION( "%ld" , long int ) __VTU11_WRITE_NUMBER_SPECIALIZATION( "%d" , int ) __VTU11_WRITE_NUMBER_SPECIALIZATION( "%hd" , short ) __VTU11_WRITE_NUMBER_SPECIALIZATION( "%hhd", char ) __VTU11_WRITE_NUMBER_SPECIALIZATION( "%llu", unsigned long long int ) __VTU11_WRITE_NUMBER_SPECIALIZATION( "%ld" , unsigned long int ) __VTU11_WRITE_NUMBER_SPECIALIZATION( "%d" , unsigned int ) __VTU11_WRITE_NUMBER_SPECIALIZATION( "%hd" , unsigned short ) __VTU11_WRITE_NUMBER_SPECIALIZATION( "%hhd", unsigned char ) } // namespace detail template<typename T> inline void AsciiWriter::writeData( std::ostream& output, const std::vector<T>& data ) { char buffer[64]; for( auto value : data ) { detail::writeNumber( buffer, value ); output << buffer << " "; } output << "\n"; } template<> inline void AsciiWriter::writeData( std::ostream& output, const std::vector<std::int8_t>& data ) { for( auto value : data ) { // will otherwise interpret uint8 as char and output nonsense instead // changed the datatype from unsigned to int output << static_cast<int>( value ) << " "; } output << "\n"; } inline void AsciiWriter::writeAppended( std::ostream& ) { } inline void AsciiWriter::addHeaderAttributes( StringStringMap& ) { } inline void AsciiWriter::addDataAttributes( StringStringMap& attributes ) { attributes["format"] = "ascii"; } inline StringStringMap AsciiWriter::appendedAttributes( ) { return { }; } // ---------------------------------------------------------------- template<typename T> inline void Base64BinaryWriter::writeData( std::ostream& output, const std::vector<T>& data ) { HeaderType numberOfBytes = data.size( ) * sizeof( T ); output << base64Encode( &numberOfBytes, &numberOfBytes + 1 ); output << base64Encode( data.begin( ), data.end( ) ); output << "\n"; } inline void Base64BinaryWriter::writeAppended( std::ostream& ) { } inline void Base64BinaryWriter::addHeaderAttributes( StringStringMap& attributes ) { attributes["header_type"] = dataTypeString<HeaderType>( ); } inline void Base64BinaryWriter::addDataAttributes( StringStringMap& attributes ) { attributes["format"] = "binary"; } inline StringStringMap Base64BinaryWriter::appendedAttributes( ) { return { }; } // ---------------------------------------------------------------- template<typename T> inline void Base64BinaryAppendedWriter::writeData( std::ostream&, const std::vector<T>& data ) { HeaderType rawBytes = data.size( ) * sizeof( T ); appendedData.emplace_back( reinterpret_cast<const char*>( &data[0] ), rawBytes ); offset += encodedNumberOfBytes( rawBytes + sizeof( HeaderType ) ); } inline void Base64BinaryAppendedWriter::writeAppended( std::ostream& output ) { for( auto dataSet : appendedData ) { // looks like header and data has to be encoded at once std::vector<char> data( dataSet.second + sizeof( HeaderType ) ); *reinterpret_cast<HeaderType*>( &data[0] ) = dataSet.second; std::copy( dataSet.first, dataSet.first + dataSet.second, &data[ sizeof( HeaderType ) ] ); output << base64Encode( data.begin( ), data.end( ) ); } output << "\n"; } inline void Base64BinaryAppendedWriter::addHeaderAttributes( StringStringMap& attributes ) { attributes["header_type"] = dataTypeString<HeaderType>( ); } inline void Base64BinaryAppendedWriter::addDataAttributes( StringStringMap& attributes ) { attributes["format"] = "appended"; attributes["offset"] = std::to_string( offset ); } inline StringStringMap Base64BinaryAppendedWriter::appendedAttributes( ) { return { { "encoding", "base64" } }; } // ---------------------------------------------------------------- template<typename T> inline void RawBinaryAppendedWriter::writeData( std::ostream&, const std::vector<T>& data ) { HeaderType rawBytes = data.size( ) * sizeof( T ); appendedData.emplace_back( reinterpret_cast<const char*>( &data[0] ), rawBytes ); offset += sizeof( HeaderType ) + rawBytes; } inline void RawBinaryAppendedWriter::writeAppended( std::ostream& output ) { for( auto dataSet : appendedData ) { const char* headerBegin = reinterpret_cast<const char*>( &dataSet.second ); for( const char* ptr = headerBegin; ptr < headerBegin + sizeof( HeaderType ); ++ptr ) { output << *ptr; } for( const char* ptr = dataSet.first; ptr < dataSet.first + dataSet.second; ++ptr ) { output << *ptr; } } output << "\n"; } inline void RawBinaryAppendedWriter::addHeaderAttributes( StringStringMap& attributes ) { attributes["header_type"] = dataTypeString<HeaderType>( ); } inline void RawBinaryAppendedWriter::addDataAttributes( StringStringMap& attributes ) { attributes["format"] = "appended"; attributes["offset"] = std::to_string( offset ); } inline StringStringMap RawBinaryAppendedWriter::appendedAttributes( ) { return { { "encoding", "raw" } }; } } // namespace vtu11 #endif // VTU11_WRITER_IMPL_HPP
26.786957
94
0.635286
gtsc
cfbd1ca55702ca6b33927dc7831b66f08acc1cc9
6,009
cpp
C++
test/invalid_encoding.cpp
TyRoXx/warpcoil
e0454a7880fa644dfb6e77968a37f8547590c15f
[ "MIT" ]
2
2018-06-04T06:44:00.000Z
2018-09-14T09:45:12.000Z
test/invalid_encoding.cpp
TyRoXx/warpcoil
e0454a7880fa644dfb6e77968a37f8547590c15f
[ "MIT" ]
40
2016-05-01T12:51:47.000Z
2016-09-04T14:21:51.000Z
test/invalid_encoding.cpp
TyRoXx/warpcoil
e0454a7880fa644dfb6e77968a37f8547590c15f
[ "MIT" ]
2
2018-06-04T06:44:06.000Z
2018-09-14T09:45:19.000Z
#include "test_streams.hpp" #include "checkpoint.hpp" #include "generated.hpp" #include "boost_print_log_value.hpp" #include "failing_test_interface.hpp" #include <silicium/exchange.hpp> #include <silicium/error_or.hpp> namespace { void test_invalid_server_request(std::vector<std::uint8_t> expected_request) { warpcoil::failing_test_interface server_impl; warpcoil::async_read_dummy_stream server_requests; warpcoil::async_write_dummy_stream server_responses; warpcoil::cpp::message_splitter<decltype(server_requests)> splitter(server_requests); warpcoil::cpp::buffered_writer<decltype(server_responses)> writer(server_responses); async_test_interface_server<decltype(server_impl), warpcoil::async_read_dummy_stream, warpcoil::async_write_dummy_stream> server(server_impl, splitter, writer); BOOST_REQUIRE(!server_requests.respond); BOOST_REQUIRE(!server_responses.handle_result); warpcoil::checkpoint request_served; server.serve_one_request([&request_served](boost::system::error_code ec) { request_served.enter(); BOOST_CHECK_EQUAL(warpcoil::cpp::make_invalid_input_error(), ec); }); BOOST_REQUIRE(server_requests.respond); BOOST_REQUIRE(!server_responses.handle_result); BOOST_REQUIRE(server_responses.written.empty()); request_served.enable(); Si::exchange(server_requests.respond, nullptr)(Si::make_memory_range(expected_request)); request_served.require_crossed(); BOOST_REQUIRE(!server_requests.respond); BOOST_REQUIRE(!server_responses.handle_result); } } BOOST_AUTO_TEST_CASE(async_server_invalid_utf8_request) { test_invalid_server_request( {0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 'u', 't', 'f', '8', 5, 'N', 'a', 'm', 'e', 0xff}); } BOOST_AUTO_TEST_CASE(async_server_invalid_variant_request_a) { test_invalid_server_request( {0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 'v', 'a', 'r', 'i', 'a', 'n', 't', 2, 0, 0, 0, 0}); } BOOST_AUTO_TEST_CASE(async_server_invalid_variant_request_b) { test_invalid_server_request( {0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 'v', 'a', 'r', 'i', 'a', 'n', 't', 255, 0, 0, 0, 0}); } BOOST_AUTO_TEST_CASE(async_server_invalid_message_type) { test_invalid_server_request( {1, 0, 0, 0, 0, 0, 0, 0, 0, 4, 'u', 't', 'f', '8', 4, 'N', 'a', 'm', 'e'}); } namespace { template <class Result> void test_invalid_client_request( std::function<void(async_test_interface &, std::function<void(Si::error_or<Result>)>)> begin_request) { warpcoil::async_write_dummy_stream client_requests; warpcoil::async_read_dummy_stream client_responses; warpcoil::cpp::message_splitter<decltype(client_responses)> splitter(client_responses); warpcoil::cpp::buffered_writer<decltype(client_requests)> writer(client_requests); async_test_interface_client<warpcoil::async_write_dummy_stream, warpcoil::async_read_dummy_stream> client(writer, splitter); BOOST_REQUIRE(!client_responses.respond); BOOST_REQUIRE(!client_requests.handle_result); async_type_erased_test_interface<decltype(client)> type_erased_client{client}; warpcoil::checkpoint request_rejected; request_rejected.enable(); begin_request(type_erased_client, [&request_rejected](Si::error_or<Result> result) { BOOST_REQUIRE_EQUAL(warpcoil::cpp::make_invalid_input_error(), result.error()); request_rejected.enter(); }); request_rejected.require_crossed(); BOOST_REQUIRE(!client_responses.respond); BOOST_REQUIRE(!client_requests.handle_result); } } BOOST_AUTO_TEST_CASE(async_client_invalid_utf8_request) { test_invalid_client_request<std::string>( [](async_test_interface &client, std::function<void(Si::error_or<std::string>)> on_result) { client.utf8("Name\xff", on_result); }); } BOOST_AUTO_TEST_CASE(async_client_invalid_utf8_length_request) { test_invalid_client_request<std::string>( [](async_test_interface &client, std::function<void(Si::error_or<std::string>)> on_result) { client.utf8(std::string(256, 'a'), on_result); }); } BOOST_AUTO_TEST_CASE(async_client_invalid_vector_length_request) { test_invalid_client_request<std::vector<std::uint64_t>>( [](async_test_interface &client, std::function<void(Si::error_or<std::vector<std::uint64_t>>)> on_result) { client.vectors_256(std::vector<std::uint64_t>(256), on_result); }); } BOOST_AUTO_TEST_CASE(async_client_invalid_int_request_too_small) { test_invalid_client_request<std::uint16_t>( [](async_test_interface &client, std::function<void(Si::error_or<std::uint16_t>)> on_result) { client.atypical_int(0, on_result); }); } BOOST_AUTO_TEST_CASE(async_client_invalid_int_request_too_large) { test_invalid_client_request<std::uint16_t>( [](async_test_interface &client, std::function<void(Si::error_or<std::uint16_t>)> on_result) { client.atypical_int(1001, on_result); }); } BOOST_AUTO_TEST_CASE(async_client_invalid_variant_element_request) { test_invalid_client_request<Si::variant<std::uint16_t, std::string>>( [](async_test_interface &client, std::function<void(Si::error_or<Si::variant<std::uint16_t, std::string>>)> on_result) { client.variant(std::string("Name\xff"), on_result); }); }
40.06
100
0.643868
TyRoXx
cfbf4201b3f86c93d0709acd6e844cd5f6665646
4,168
cpp
C++
tests/test_configd/fetch/UnittestLayerTypeCommand.cpp
webOS-ports/configd
707f158782b82417b197c00845d3fdf44dd5bcfd
[ "Apache-2.0" ]
2
2018-03-22T19:07:50.000Z
2019-05-06T05:20:31.000Z
tests/test_configd/fetch/UnittestLayerTypeCommand.cpp
webOS-ports/configd
707f158782b82417b197c00845d3fdf44dd5bcfd
[ "Apache-2.0" ]
null
null
null
tests/test_configd/fetch/UnittestLayerTypeCommand.cpp
webOS-ports/configd
707f158782b82417b197c00845d3fdf44dd5bcfd
[ "Apache-2.0" ]
3
2018-03-22T19:07:52.000Z
2022-02-26T04:28:53.000Z
// Copyright (c) 2016-2018 LG Electronics, 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. // // SPDX-License-Identifier: Apache-2.0 #include <config/MockLayer.h> #include <gtest/gtest.h> #include <pbnjson.hpp> #include "config/Layer.h" #include "util/Platform.h" #include "Environment.h" #include "UnittestLayerType.hpp" using namespace pbnjson; using namespace std; using ::testing::SetArgReferee; using ::testing::_; class UnittestLayerTypeCommand : public UnittestLayerType, public testing::Test { protected: UnittestLayerTypeCommand() : UnittestLayerType(TEST_DATA_PATH, "command") { m_info = pbnjson::Object(); } virtual void givenCMDOneLayer() { givenInfo(COMMAND_ONE_NAME, COMMAND_ONE_VALUE); givenLayer(); } virtual void givenCMDTwoLayer() { givenInfo(COMMAND_TWO_NAME, COMMAND_TWO_VALUE); givenLayer(); } const string COMMAND_ONE_NAME = "CommandOneLayer"; const string COMMAND_ONE_VALUE = "echo 'selection1'"; const string COMMAND_ONE_RESULT = "selection1"; const string COMMAND_TWO_NAME = "CommandTwoLayer"; const string COMMAND_TWO_VALUE = "echo 'selection2'"; const string COMMAND_TWO_RESULT = "selection2"; }; TEST_F(UnittestLayerTypeCommand, gettingWithoutSelectionOfCMDOneLayer) { givenCMDOneLayer(); thenTypeAndName(SelectorType_Command, COMMAND_ONE_NAME); thenUnselectedStatus(TEST_DATA_PATH); EXPECT_FALSE(m_layer->isReadOnlyType()); } TEST_F(UnittestLayerTypeCommand, gettingWithSelectionOfCMDOneLayer) { givenCMDOneLayer(); EXPECT_TRUE(m_layer->select()); thenSelectedStatus(TEST_DATA_PATH, COMMAND_ONE_RESULT); } TEST_F(UnittestLayerTypeCommand, checkListenerWithSelectionOfCMDOneLayer) { givenCMDOneLayer(); EXPECT_CALL(m_listener, onSelectionChanged(_, _, _)); EXPECT_TRUE(m_layer->select()); } TEST_F(UnittestLayerTypeCommand, gettingWithoutSelectionOfCMDTwoLayer) { givenCMDTwoLayer(); thenTypeAndName(SelectorType_Command, COMMAND_TWO_NAME); thenUnselectedStatus(TEST_DATA_PATH); EXPECT_FALSE(m_layer->isReadOnlyType()); } TEST_F(UnittestLayerTypeCommand, gettingWithSelectionOfCMDTwoLayer) { givenCMDTwoLayer(); EXPECT_TRUE(m_layer->select()); thenSelectedStatus(TEST_DATA_PATH, COMMAND_TWO_RESULT); } TEST_F(UnittestLayerTypeCommand, fetchConfigs) { givenCMDTwoLayer(); m_layer->select(); string path = m_layer->getFullDirPath(true); thenFetchConfigs(path); } TEST_F(UnittestLayerTypeCommand, fetchFullConfigs) { givenCMDOneLayer(); m_layer->select(); string path = m_layer->getFullDirPath(true); thenFetchFullConfigs(path); } TEST_F(UnittestLayerTypeCommand, clearSelectAndSelectAgain) { givenCMDOneLayer(); EXPECT_TRUE(m_layer->select()); EXPECT_TRUE(m_layer->isSelected()); m_layer->clearSelection(); EXPECT_FALSE(m_layer->isSelected()); EXPECT_TRUE(m_layer->setSelection(COMMAND_TWO_RESULT)); thenSelectedStatus(TEST_DATA_PATH, COMMAND_TWO_RESULT); EXPECT_TRUE(m_layer->select()); thenSelectedStatus(TEST_DATA_PATH, COMMAND_ONE_RESULT); } TEST_F(UnittestLayerTypeCommand, invalidCallOperation) { givenCMDOneLayer(); EXPECT_EQ(false, m_layer->call()); } TEST_F(UnittestLayerTypeCommand, fetchFilesWithInvaildPath) { givenCMDOneLayer(); string path = "invalidPath"; JsonDB A; EXPECT_FALSE(Layer::parseFiles(path, NULL, &A)); } TEST_F(UnittestLayerTypeCommand, fetchFilesNotExistJsonInDir) { givenCMDOneLayer(); string path = TEST_DATA_PATH; JsonDB A; EXPECT_TRUE(Layer::parseFiles(path, NULL, &A)); }
24.662722
81
0.740883
webOS-ports
cfc3ef51422183c772cf5f2b8423034dffe1725b
13,588
cc
C++
DataFormats/L1GlobalTrigger/src/L1GtPsbWord.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
DataFormats/L1GlobalTrigger/src/L1GtPsbWord.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
DataFormats/L1GlobalTrigger/src/L1GtPsbWord.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
/** * \class L1GtPsbWord * * * Description: PSB block in the L1 GT readout record. * * Implementation: * <TODO: enter implementation details> * * \author: Vasile Mihai Ghete - HEPHY Vienna * * */ // this class header #include "DataFormats/L1GlobalTrigger/interface/L1GtPsbWord.h" // system include files #include <iomanip> // user include files #include "FWCore/Utilities/interface/EDMException.h" // constructors // empty constructor, all members set to zero; L1GtPsbWord::L1GtPsbWord() { m_boardId = 0; m_bxInEvent = 0; m_bxNr = 0; m_eventNr = 0; for (int iA = 0; iA < NumberAData; ++iA) { m_aData[iA] = 0; } for (int iB = 0; iB < NumberBData; ++iB) { m_bData[iB] = 0; } m_localBxNr = 0; } // constructor from unpacked values; L1GtPsbWord::L1GtPsbWord(cms_uint16_t boardIdValue, int bxInEventValue, cms_uint16_t bxNrValue, cms_uint32_t eventNrValue, cms_uint16_t aDataValue[NumberAData], cms_uint16_t bDataValue[NumberBData], cms_uint16_t localBxNrValue) { m_boardId = boardIdValue; m_bxInEvent = bxInEventValue; m_bxNr = bxNrValue; m_eventNr = eventNrValue; for (int iA = 0; iA < NumberAData; ++iA) { m_aData[iA] = aDataValue[iA]; } for (int iB = 0; iB < NumberBData; ++iB) { m_bData[iB] = bDataValue[iB]; } m_localBxNr = localBxNrValue; } // destructor L1GtPsbWord::~L1GtPsbWord() { // empty now } // equal operator bool L1GtPsbWord::operator==(const L1GtPsbWord& result) const { if (m_boardId != result.m_boardId) { return false; } if (m_bxInEvent != result.m_bxInEvent) { return false; } if (m_bxNr != result.m_bxNr) { return false; } if (m_eventNr != result.m_eventNr) { return false; } for (int iA = 0; iA < NumberAData; ++iA) { if (m_aData[iA] != result.m_aData[iA]) { return false; } } for (int iB = 0; iB < NumberBData; ++iB) { if (m_bData[iB] != result.m_bData[iB]) { return false; } } if (m_localBxNr != result.m_localBxNr) { return false; } // all members identical return true; } // unequal operator bool L1GtPsbWord::operator!=(const L1GtPsbWord& result) const { return !(result == *this); } // methods // set the BoardId value from a 64-bits word, having the index iWord // in the GTFE raw record void L1GtPsbWord::setBoardId(const cms_uint64_t& word64, int iWord) { if (iWord == BoardIdWord) { m_boardId = (word64 & BoardIdMask) >> BoardIdShift; } } // set the BoardId value in a 64-bits word, having the index iWord // in the GTFE raw record void L1GtPsbWord::setBoardIdWord64(cms_uint64_t& word64, int iWord) { if (iWord == BoardIdWord) { word64 = word64 | (static_cast<cms_uint64_t>(m_boardId) << BoardIdShift); } } // set the BxInEvent value from a 64-bits word, having the index iWord // in the GTFE raw record void L1GtPsbWord::setBxInEvent(const cms_uint64_t& word64, int iWord) { if (iWord == BxInEventWord) { int baseValue = 16; // using hexadecimal values; int hexBxInEvent = (word64 & BxInEventMask) >> BxInEventShift; m_bxInEvent = (hexBxInEvent + baseValue / 2) % baseValue - baseValue / 2; } } // set the BxInEvent value in a 64-bits word, having the index iWord // in the GTFE raw record void L1GtPsbWord::setBxInEventWord64(cms_uint64_t& word64, int iWord) { if (iWord == BxInEventWord) { int baseValue = 16; // using hexadecimal values; int hexBxInEvent = (m_bxInEvent + baseValue) % baseValue; word64 = word64 | (static_cast<cms_uint64_t>(hexBxInEvent) << BxInEventShift); } } // set the BxNr value from a 64-bits word, having the index iWord in the GTFE raw record void L1GtPsbWord::setBxNr(const cms_uint64_t& word64, int iWord) { if (iWord == BxNrWord) { m_bxNr = (word64 & BxNrMask) >> BxNrShift; } } // set the BxNr value in a 64-bits word, having the index iWord // in the GTFE raw record void L1GtPsbWord::setBxNrWord64(cms_uint64_t& word64, int iWord) { if (iWord == BxNrWord) { word64 = word64 | (static_cast<cms_uint64_t>(m_bxNr) << BxNrShift); } } // set the EventNr value from a 64-bits word, having the index iWord in the GTFE raw record void L1GtPsbWord::setEventNr(const cms_uint64_t& word64, int iWord) { if (iWord == EventNrWord) { m_eventNr = (word64 & EventNrMask) >> EventNrShift; } } // set the EventNr value in a 64-bits word, having the index iWord // in the GTFE raw record void L1GtPsbWord::setEventNrWord64(cms_uint64_t& word64, int iWord) { if (iWord == EventNrWord) { word64 = word64 | (static_cast<cms_uint64_t>(m_eventNr) << EventNrShift); } } // get/set A_DATA_CH_IA const cms_uint16_t L1GtPsbWord::aData(int iA) const { if (iA < 0 || iA > NumberAData) { throw cms::Exception("aDataIndexError") << "\nError: index for A_DATA array out of range. Allowed range: [0, " << NumberAData << ") " << std::endl; } else { return m_aData[iA]; } } void L1GtPsbWord::setAData(cms_uint16_t aDataVal, int iA) { if (iA < 0 || iA > NumberAData) { throw cms::Exception("aDataIndexError") << "\nError: index for A_DATA array out of range. Allowed range: [0, " << NumberAData << ") " << std::endl; } else { m_aData[iA] = aDataVal; } } // set the AData value from a 64-bits word, having the index iWord // in the GTFE raw record void L1GtPsbWord::setAData(const cms_uint64_t& word64, int iWord) { int sizeW64 = sizeof(word64) * 8; int nSubWords = sizeW64 / DataCHSize; if (iWord == ADataCH0Word) { for (int i = 0; i < nSubWords; ++i) { int dataShift = i * DataCHSize; m_aData[i] = (word64 & (DataCHMask << dataShift)) >> dataShift; // LogTrace("L1GtPsbWord") // << "\n A_Data_CH" << i << " = " // << m_aData[i] // << std::endl; } } else if (iWord == ADataCH4Word) { for (int i = 0; i < nSubWords; ++i) { int dataShift = i * DataCHSize; m_aData[i + nSubWords] = (word64 & (DataCHMask << dataShift)) >> dataShift; // LogTrace("L1GtPsbWord") // << "\n A_Data_CH" << i + nSubWords << " = " // << m_aData[i] // << std::endl; } } } // set the AData value in a 64-bits word, having the index iWord // in the GTFE raw record void L1GtPsbWord::setADataWord64(cms_uint64_t& word64, int iWord) { int sizeW64 = sizeof(word64) * 8; int nSubWords = sizeW64 / DataCHSize; if (iWord == ADataCH0Word) { for (int i = 0; i < nSubWords; ++i) { int dataShift = i * DataCHSize; word64 = word64 | (static_cast<cms_uint64_t>(m_aData[i]) << dataShift); } } else if (iWord == ADataCH4Word) { for (int i = 0; i < nSubWords; ++i) { int dataShift = i * DataCHSize; word64 = word64 | (static_cast<cms_uint64_t>(m_aData[i + nSubWords]) << dataShift); } } } // get/set B_DATA_CH_IB const cms_uint16_t L1GtPsbWord::bData(int iB) const { if (iB < 0 || iB > NumberBData) { throw cms::Exception("bDataIndexError") << "\nError: index for B_DATA array out of range. Allowed range: [0, " << NumberBData << ") " << std::endl; } else { return m_bData[iB]; } } void L1GtPsbWord::setBData(cms_uint16_t bDataVal, int iB) { if (iB < 0 || iB > NumberBData) { throw cms::Exception("bDataIndexError") << "\nError: index for B_DATA array out of range. Allowed range: [0, " << NumberBData << ") " << std::endl; } else { m_bData[iB] = bDataVal; } } // set the BData value from a 64-bits word, having the index iWord // in the GTFE raw record void L1GtPsbWord::setBData(const cms_uint64_t& word64, int iWord) { int sizeW64 = sizeof(word64) * 8; int nSubWords = sizeW64 / DataCHSize; if (iWord == BDataCH0Word) { for (int i = 0; i < nSubWords; ++i) { int dataShift = i * DataCHSize; m_bData[i] = (word64 & (DataCHMask << dataShift)) >> dataShift; } } else if (iWord == BDataCH4Word) { for (int i = 0; i < nSubWords; ++i) { int dataShift = i * DataCHSize; m_bData[i + nSubWords] = (word64 & (DataCHMask << dataShift)) >> dataShift; } } } // set the BData value in a 64-bits word, having the index iWord // in the GTFE raw record void L1GtPsbWord::setBDataWord64(cms_uint64_t& word64, int iWord) { int sizeW64 = sizeof(word64) * 8; int nSubWords = sizeW64 / DataCHSize; if (iWord == BDataCH0Word) { for (int i = 0; i < nSubWords; ++i) { int dataShift = i * DataCHSize; word64 = word64 | (static_cast<cms_uint64_t>(m_bData[i]) << dataShift); } } else if (iWord == BDataCH4Word) { for (int i = 0; i < nSubWords; ++i) { int dataShift = i * DataCHSize; word64 = word64 | (static_cast<cms_uint64_t>(m_bData[i + nSubWords]) << dataShift); } } } // set the LocalBxNr value from a 64-bits word, // having the index iWord in the GTFE raw record void L1GtPsbWord::setLocalBxNr(const cms_uint64_t& word64, int iWord) { if (iWord == LocalBxNrWord) { m_localBxNr = (word64 & LocalBxNrMask) >> LocalBxNrShift; } } // set the LocalBxNr value in a 64-bits word, having the index iWord // in the GTFE raw record void L1GtPsbWord::setLocalBxNrWord64(cms_uint64_t& word64, int iWord) { if (iWord == LocalBxNrWord) { word64 = word64 | (static_cast<cms_uint64_t>(m_localBxNr) << LocalBxNrShift); } } // reset the content of a L1GtPsbWord void L1GtPsbWord::reset() { m_boardId = 0; m_bxInEvent = 0; m_bxNr = 0; m_eventNr = 0; for (int iA = 0; iA < NumberAData; ++iA) { m_aData[iA] = 0; } for (int iB = 0; iB < NumberBData; ++iB) { m_bData[iB] = 0; } m_localBxNr = 0; } // pretty print void L1GtPsbWord::print(std::ostream& myCout) const { myCout << "\n L1GtPsbWord::print \n" << std::endl; myCout << " Board Id: " << std::hex << " hex: " << std::setw(4) << std::setfill('0') << m_boardId << std::setfill(' ') << std::dec << " dec: " << m_boardId << std::endl; int baseValue = 16; // using hexadecimal values; int hexBxInEvent = (m_bxInEvent + baseValue) % baseValue; myCout << " BxInEvent: " << std::hex << " hex: " << " " << std::setw(1) << hexBxInEvent << std::dec << " dec: " << m_bxInEvent << std::endl; myCout << " BxNr: " << std::hex << " hex: " << " " << std::setw(3) << std::setfill('0') << m_bxNr << std::setfill(' ') << std::dec << " dec: " << m_bxNr << std::endl; myCout << " EventNr: " << std::hex << " hex: " << " " << std::setw(6) << std::setfill('0') << m_eventNr << std::setfill(' ') << std::dec << " dec: " << m_eventNr << std::endl; int sizeW64 = 64; int dataBlocksPerLine = sizeW64 / DataCHSize; // 4x16 bits per line myCout << "\n " << "A_Data_CH3 " << "A_Data_CH2 " << "A_Data_CH1 " << "A_Data_CH0 " << "\n" << std::hex << " hex: " << std::setfill('0'); for (int i = 0; i < dataBlocksPerLine; ++i) { int iCh = dataBlocksPerLine - (i + 1); // reverse myCout << std::setw(4) << m_aData[iCh] << " "; } myCout << "\n" << std::dec << " dec: "; for (int i = 0; i < dataBlocksPerLine; ++i) { int iCh = dataBlocksPerLine - (i + 1); // reverse myCout << std::setw(5) << m_aData[iCh] << " "; } myCout << "\n\n " << "A_Data_CH7 " << "A_Data_CH6 " << "A_Data_CH5 " << "A_Data_CH4 " << "\n" << std::hex << " hex: " << std::setfill('0'); for (int i = 0; i < dataBlocksPerLine; ++i) { int iCh = dataBlocksPerLine - (i + 1); // reverse myCout << std::setw(4) << m_aData[iCh + dataBlocksPerLine] << " "; } myCout << "\n" << std::dec << " dec: "; for (int i = 0; i < dataBlocksPerLine; ++i) { int iCh = dataBlocksPerLine - (i + 1); // reverse myCout << std::setw(5) << m_aData[iCh + dataBlocksPerLine] << " "; } myCout << std::endl; myCout << "\n " << "B_Data_CH3 " << "B_Data_CH2 " << "B_Data_CH1 " << "B_Data_CH0 " << "\n" << std::hex << " hex: " << std::setfill('0'); for (int i = 0; i < dataBlocksPerLine; ++i) { int iCh = dataBlocksPerLine - (i + 1); // reverse myCout << std::setw(4) << m_bData[iCh] << " "; } myCout << "\n" << std::dec << " dec: "; for (int i = 0; i < dataBlocksPerLine; ++i) { int iCh = dataBlocksPerLine - (i + 1); // reverse myCout << std::setw(5) << m_bData[iCh] << " "; } myCout << "\n\n " << "B_Data_CH7 " << "B_Data_CH6 " << "B_Data_CH5 " << "B_Data_CH4 " << "\n" << std::hex << " hex: " << std::setfill('0'); for (int i = 0; i < dataBlocksPerLine; ++i) { int iCh = dataBlocksPerLine - (i + 1); // reverse myCout << std::setw(4) << m_bData[iCh + dataBlocksPerLine] << " "; } myCout << "\n" << std::dec << " dec: "; for (int i = 0; i < dataBlocksPerLine; ++i) { int iCh = dataBlocksPerLine - (i + 1); // reverse myCout << std::setw(5) << m_bData[iCh + dataBlocksPerLine] << " "; } myCout << "\n" << std::endl; myCout << " LocalBxNr: " << std::hex << " hex: " << " " << std::setw(3) << std::setfill('0') << m_localBxNr << std::setfill(' ') << std::dec << " dec: " << m_localBxNr << std::endl; } // static class members const int L1GtPsbWord::NumberAData; const int L1GtPsbWord::NumberBData;
29.347732
117
0.586989
ckamtsikis
cfcfd604e2d1961439c9fd3966618be859214bf6
6,724
cpp
C++
validation_tests/faodel/examples/opbox/basic/rdma_ping/OpRdmaPing.cpp
brugger1/testsuite
9b504db668cdeaf7c561f15b76c95d05bfdd1517
[ "MIT" ]
12
2019-02-12T18:20:29.000Z
2021-12-09T19:46:19.000Z
validation_tests/faodel/examples/opbox/basic/rdma_ping/OpRdmaPing.cpp
brugger1/testsuite
9b504db668cdeaf7c561f15b76c95d05bfdd1517
[ "MIT" ]
24
2020-08-31T22:05:07.000Z
2022-02-21T18:30:03.000Z
validation_tests/faodel/examples/opbox/basic/rdma_ping/OpRdmaPing.cpp
brugger1/testsuite
9b504db668cdeaf7c561f15b76c95d05bfdd1517
[ "MIT" ]
19
2020-08-31T21:59:10.000Z
2022-02-23T22:06:46.000Z
// Copyright 2018 National Technology & Engineering Solutions of Sandia, // LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. #include <assert.h> #include <string.h> //for memcpy #include "opbox/ops/OpHelpers.hh" #include "OpRdmaPing.hh" using namespace std; const unsigned int OpRdmaPing::op_id = const_hash("OpRdmaPing"); const string OpRdmaPing::op_name = "OpRdmaPing"; OpRdmaPing::OpRdmaPing(opbox::net::peer_ptr_t dst, lunasa::DataObject msg) : state(State::start), ldo_msg(), Op(true) { peer = dst; ping_ldo = msg; createOutgoingMessage(opbox::net::ConvertPeerToNodeID(dst), GetAssignedMailbox(), 0, ping_ldo); //Work picks up again in origin's state machine } OpRdmaPing::OpRdmaPing(op_create_as_target_t t) : state(State::start), ldo_msg(), Op(t) { //No work to do - done in target's state machine } OpRdmaPing::~OpRdmaPing(){ } future<std::string> OpRdmaPing::GetFuture(){ return ping_promise.get_future(); } /* * Create a message to initiate the communication with the target. * This message starts with a message_t that carries basic * information about the origin (us) and the target (them). Following * the message_t is the body of the message. The body of this * message is a NetBufferRemote that describes the RDMA window of the * ping message. */ void OpRdmaPing::createOutgoingMessage(faodel::nodeid_t dst, const mailbox_t &src_mailbox, const mailbox_t &dst_mailbox, lunasa::DataObject ping_ldo){ ldo_msg = opbox::net::NewMessage(sizeof(message_t)+sizeof(struct opbox::net::NetBufferRemote)); message_t *msg = ldo_msg.GetDataPtr<message_t *>(); msg->src = opbox::net::GetMyID(); msg->dst = dst; msg->src_mailbox = src_mailbox; msg->dst_mailbox = dst_mailbox; msg->op_id = OpRdmaPing::op_id; msg->body_len = sizeof(struct opbox::net::NetBufferRemote); opbox::net::NetBufferLocal *nbl = nullptr; opbox::net::NetBufferRemote nbr; opbox::net::GetRdmaPtr(&ping_ldo, &nbl, &nbr); memcpy(&msg->body[0], &nbr, sizeof(opbox::net::NetBufferRemote)); } /* * Create a message to terminate communication with the origin. This * message is just a message_t that tells the origin (them) which * operation is complete. */ void OpRdmaPing::createAckMessage(faodel::nodeid_t dst, const mailbox_t &src_mailbox, const mailbox_t &dst_mailbox){ ldo_msg = opbox::net::NewMessage(sizeof(message_t)); message_t *msg = ldo_msg.GetDataPtr<message_t *>(); msg->src = opbox::net::GetMyID(); msg->dst = dst; msg->src_mailbox = src_mailbox; msg->dst_mailbox = dst_mailbox; msg->op_id = OpRdmaPing::op_id; msg->body_len = 0; } /* * This is the origin state machine. */ WaitingType OpRdmaPing::UpdateOrigin(OpArgs *args) { string user_data; switch(state){ case State::start: // send a message to the target process to begin the ping. opbox::net::SendMsg(peer, std::move(ldo_msg)); state=State::snd_wait_for_ack; return WaitingType::waiting_on_cq; case State::snd_wait_for_ack: // the ACK message has arrived args->ExpectMessageOrDie<message_t *>(); //TODO ack/nack check // extract the transformed ping message from the LDO and create a string from it user_data = string(ping_ldo.GetDataPtr<char *>(), ping_ldo.GetDataSize()); // set the the value of the promise which will wake up the main // thread which is waiting on the associated future ping_promise.set_value(user_data); state=State::done; return WaitingType::done_and_destroy; case State::done: return WaitingType::done_and_destroy; } //Shouldn't be here KFAIL(); return WaitingType::error; } /* * This is the target state machine. */ WaitingType OpRdmaPing::UpdateTarget(OpArgs *args) { switch(state){ case State::start: { auto incoming_msg = args->ExpectMessageOrDie<message_t *>(&peer); // save a copy of the NBR for later use memcpy(&nbr, &incoming_msg->body[0], sizeof(opbox::net::NetBufferRemote)); // this is the initiator buffer for the get and the put shout_ldo = lunasa::DataObject(0, nbr.GetLength(), lunasa::DataObject::AllocatorType::eager); // we create the ACK message now be cause we need the sender's // node ID and the mailbox ID from the incoming message. // instead of saving the message, just use what we need. createAckMessage(incoming_msg->src, 0, //Not expecting a reply incoming_msg->src_mailbox); // get the ping message from the origin process. // AllEventsCallback() is a convenience class that will redirect // all events generated by the get to this operation's Update() // method. opbox::net::Get(peer, &nbr, shout_ldo, AllEventsCallback(this)); state=State::get_wait_complete; return WaitingType::waiting_on_cq; } case State::get_wait_complete: // the get is complete, so transform the ping message in-place. //for(int i=0; i<shout_ldo.dataSize(); i++) { // (shout_ldo.dataPtr<char *>())[i] = toupper(shout_ldo.dataPtr<char *>())[i]); //} { auto *data = shout_ldo.GetDataPtr<char *>(); for(int i=0; i<shout_ldo.GetDataSize(); i++) data[i] = toupper(data[i]); } // put the transformed ping message back to the origin process. // AllEventsCallback() is a convenience class that will redirect // all events generated by the put to this operation's Update() // method. opbox::net::Put(peer, shout_ldo, &nbr, AllEventsCallback(this)); state=State::put_wait_complete; return WaitingType::waiting_on_cq; case State::put_wait_complete: // the put is complete, so send the ACK to the origin process. opbox::net::SendMsg(peer, std::move(ldo_msg)); state=State::done; return WaitingType::done_and_destroy; case State::done: return WaitingType::done_and_destroy; } KHALT("Missing state"); return WaitingType::done_and_destroy; } string OpRdmaPing::GetStateName() const { switch(state){ case State::start: return "Start"; case State::snd_wait_for_ack: return "Sender-WaitForAck"; case State::get_wait_complete: return "GetWaitComplete"; case State::put_wait_complete: return "PutWaitComplete"; case State::done: return "Done"; } KFAIL(); }
32.960784
99
0.659875
brugger1
cfd37fdb986966a61e6f2ded1901961f412619b0
877
cpp
C++
qt_tstfrm/test_main_loop.cpp
bowlofstew/omim
8045157c95244aa8f862d47324df42a19b87e335
[ "Apache-2.0" ]
2
2019-01-24T15:36:20.000Z
2019-12-26T10:03:48.000Z
qt_tstfrm/test_main_loop.cpp
bowlofstew/omim
8045157c95244aa8f862d47324df42a19b87e335
[ "Apache-2.0" ]
13
2015-09-28T13:59:23.000Z
2015-10-08T20:12:45.000Z
qt_tstfrm/test_main_loop.cpp
bowlofstew/omim
8045157c95244aa8f862d47324df42a19b87e335
[ "Apache-2.0" ]
1
2019-08-09T21:31:29.000Z
2019-08-09T21:31:29.000Z
#include "qt_tstfrm/test_main_loop.hpp" #include <QtCore/QTimer> #include <QtWidgets/QApplication> #include <QtWidgets/QWidget> #include "base/scope_guard.hpp" #include "std/cstring.hpp" namespace { class MyWidget : public QWidget { public: MyWidget(TRednerFn const & fn) : m_fn(fn) { } protected: void paintEvent(QPaintEvent * e) { m_fn(this); } private: TRednerFn m_fn; }; } // namespace void RunTestLoop(char const * testName, TRednerFn const & fn, bool autoExit) { char * buf = (char *)malloc(strlen(testName) + 1); MY_SCOPE_GUARD(argvFreeFun, [&buf](){ free(buf); }); strcpy(buf, testName); int argc = 1; QApplication app(argc, &buf); if (autoExit) QTimer::singleShot(3000, &app, SLOT(quit())); MyWidget * widget = new MyWidget(fn); widget->setWindowTitle(testName); widget->show(); app.exec(); delete widget; }
16.865385
76
0.672748
bowlofstew
cfd5914eb8b72dfc901dc7a0666625c8023983d4
1,505
cpp
C++
src/prod/src/ServiceModel/management/FaultAnalysisService/RestartDeployedCodePackageStatus.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/ServiceModel/management/FaultAnalysisService/RestartDeployedCodePackageStatus.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/ServiceModel/management/FaultAnalysisService/RestartDeployedCodePackageStatus.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace Common; using namespace ServiceModel; using namespace std; using namespace Management::FaultAnalysisService; StringLiteral const TraceComponent("RestartDeployedCodePackageStatus"); RestartDeployedCodePackageStatus::RestartDeployedCodePackageStatus() : deployedCodePackageResultSPtr_() { } RestartDeployedCodePackageStatus::RestartDeployedCodePackageStatus( shared_ptr<Management::FaultAnalysisService::DeployedCodePackageResult> && deployedCodePackageResultSPtr) : deployedCodePackageResultSPtr_(std::move(deployedCodePackageResultSPtr)) { } RestartDeployedCodePackageStatus::RestartDeployedCodePackageStatus(RestartDeployedCodePackageStatus && other) : deployedCodePackageResultSPtr_(move(other.deployedCodePackageResultSPtr_)) { } RestartDeployedCodePackageStatus & RestartDeployedCodePackageStatus::operator=(RestartDeployedCodePackageStatus && other) { if (this != &other) { deployedCodePackageResultSPtr_ = move(other.deployedCodePackageResultSPtr_); } return *this; } shared_ptr<DeployedCodePackageResult> const & RestartDeployedCodePackageStatus::GetRestartDeployedCodePackageResult() { return deployedCodePackageResultSPtr_; }
33.444444
121
0.756146
AnthonyM
cfdb15f2ec287001e85829552f57bd9597ff90b1
213
cpp
C++
UE4_Project_Hunt/Source/UE4_Project_Hunt/UE4_Project_Hunt.cpp
AhmedEhabAmer/project-hunt
21d881ea9243101603d5b8d402fe7f3c46d29ecf
[ "MIT" ]
1
2020-06-25T13:09:29.000Z
2020-06-25T13:09:29.000Z
UE4_Project_Hunt/Source/UE4_Project_Hunt/UE4_Project_Hunt.cpp
AhmedEhabAmer/project-hunt
21d881ea9243101603d5b8d402fe7f3c46d29ecf
[ "MIT" ]
null
null
null
UE4_Project_Hunt/Source/UE4_Project_Hunt/UE4_Project_Hunt.cpp
AhmedEhabAmer/project-hunt
21d881ea9243101603d5b8d402fe7f3c46d29ecf
[ "MIT" ]
null
null
null
// Copyright Epic Games, Inc. All Rights Reserved. #include "UE4_Project_Hunt.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, UE4_Project_Hunt, "UE4_Project_Hunt" );
30.428571
94
0.812207
AhmedEhabAmer
cfdc370a63f2cb5d9590aa746bdc53be830fa883
599
cpp
C++
src/data/dmc_octree_node.cpp
Svennny/isomesh
be7ed638079a81b1ca468833aa2972656277aaaf
[ "MIT" ]
4
2019-04-08T17:36:53.000Z
2020-04-11T18:53:29.000Z
src/data/dmc_octree_node.cpp
Svennny/isomesh
be7ed638079a81b1ca468833aa2972656277aaaf
[ "MIT" ]
null
null
null
src/data/dmc_octree_node.cpp
Svennny/isomesh
be7ed638079a81b1ca468833aa2972656277aaaf
[ "MIT" ]
2
2020-01-26T18:55:41.000Z
2020-09-30T20:10:11.000Z
/* This file is part of Isomesh library, released under MIT license. Copyright (c) 2018-2019 Pavel Asyutchenko (sventeam@yandex.ru) */ #include <isomesh/data/dmc_octree_node.hpp> #include <stdexcept> namespace isomesh { DMC_OctreeNode::DMC_OctreeNode () noexcept : children (nullptr) {} DMC_OctreeNode::~DMC_OctreeNode () noexcept { collapse (); } void DMC_OctreeNode::subdivide () { if (children) throw std::logic_error ("Octree node is already subdivided"); children = new DMC_OctreeNode[8]; } void DMC_OctreeNode::collapse () noexcept { delete[] children; children = nullptr; } }
20.655172
68
0.734558
Svennny
cfdd63392854982e1a705b102dac59599023d4ff
1,298
cpp
C++
Breakout/src/Ball.cpp
Ebsidia/Mana
ebecc2a02ab65d634438e2c207b4bb0b8af01505
[ "Apache-2.0" ]
null
null
null
Breakout/src/Ball.cpp
Ebsidia/Mana
ebecc2a02ab65d634438e2c207b4bb0b8af01505
[ "Apache-2.0" ]
null
null
null
Breakout/src/Ball.cpp
Ebsidia/Mana
ebecc2a02ab65d634438e2c207b4bb0b8af01505
[ "Apache-2.0" ]
null
null
null
#include "Ball.h" Ball::Ball() { } Ball::~Ball() { } void Ball::loadAssets() { m_ballTexture = Mana::Texture2D::Create("assets/Breakout/textures/pongball.png"); } void Ball::onUpdate(Mana::TimeStep dt) { if (Mana::Input::isKeyPressed(MA_KEY_SPACE)) m_isStuck = false; if (!m_isStuck) { glm::vec2 velocity = { m_velocity.x * dt, m_velocity.y * dt }; m_position += velocity; //setPosition({ m_velocity.x * dt, m_velocity.y * dt }); // Then check if outside window bounds and if so, reverse velocity and restore at correct position if (getPosition().x <= 0.0f) { m_velocity.x = -m_velocity.x; setPosition({0, getPosition().y }); } else if (getPosition().x + m_size.x >= 1600) { m_velocity.x = -m_velocity.x; setPosition({ 1600 - m_size.x, getPosition().y }); } if (getPosition().y <= 0.0f) { m_velocity.y = -this->m_velocity.y; setPosition({getPosition().x, 0}); } } } void Ball::onRender() { Mana::Renderer2D::drawQuad({m_position.x, m_position.y, 0.1f}, m_size, m_ballTexture, 1.0f, glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)); } void Ball::onImGuiRender() { } void Ball::reset() { }
19.969231
131
0.561633
Ebsidia
cfe175d1ce78274fc1e0d662a21e312fe10b45cc
99
cc
C++
src/Foundational/iwmisc/_copy_vector_double.cc
michaelweiss092/LillyMol
a2b7d1d8a07ef338c754a0a2e3b2624aac694cc9
[ "Apache-2.0" ]
53
2018-06-01T13:16:15.000Z
2022-02-23T21:04:28.000Z
src/Foundational/iwmisc/_copy_vector_double.cc
IanAWatson/LillyMol-4.0-Bazel
f38f23a919c622c31280222f8a90e6ab7d871b93
[ "Apache-2.0" ]
19
2018-08-14T13:43:18.000Z
2021-09-24T12:53:11.000Z
src/Foundational/iwmisc/_copy_vector_double.cc
IanAWatson/LillyMol-4.0-Bazel
f38f23a919c622c31280222f8a90e6ab7d871b93
[ "Apache-2.0" ]
19
2018-10-23T19:41:01.000Z
2022-02-17T08:14:00.000Z
#include <stdlib.h> #include "misc.h" template void copy_vector (double *, const double *, int);
16.5
58
0.69697
michaelweiss092
cfe24e0ddfc191105daa49549d0ef38d39e802f3
3,904
cpp
C++
FryEngine/tests/FryEngine/ECS/UT_ECS_System.cpp
Schtekt/FryEngine
eb36df4d0b42ca5a0549a130709c567e88b6a826
[ "MIT" ]
null
null
null
FryEngine/tests/FryEngine/ECS/UT_ECS_System.cpp
Schtekt/FryEngine
eb36df4d0b42ca5a0549a130709c567e88b6a826
[ "MIT" ]
null
null
null
FryEngine/tests/FryEngine/ECS/UT_ECS_System.cpp
Schtekt/FryEngine
eb36df4d0b42ca5a0549a130709c567e88b6a826
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <iostream> #include "helperClasses.h" TEST(ECS, CustomSystemSingleComponent) { ECS* ecs = new ECS(); DeleteIntClassSystem sys; Entity* ent = ecs->CreateEntity(); int myNumber = 5; ent->AddComponent<DeleteIntClass>(&myNumber); ASSERT_EQ(myNumber, 5); std::vector<BaseSystem*> systems; systems.push_back(&sys); ecs->UpdateSystems(0, systems); ASSERT_EQ(myNumber, 4); delete ecs; ASSERT_EQ(myNumber, 5); } TEST(ECS, CustomSystemSingleComponentType) { ECS* ecs = new ECS(); DeleteIntClassSystem sys; std::vector<int> myNumbers; std::vector<int> origNumbers; std::vector<Entity*> entities; for(int i = 0; i < 20; i++) { myNumbers.push_back(i); origNumbers.push_back(i); entities.push_back(ecs->CreateEntity()); } for(int i = 0; i < 20; i++) { entities[i]->AddComponent<DeleteIntClass>(&myNumbers[i]); ASSERT_EQ(myNumbers[i], origNumbers[i]); } std::vector<BaseSystem*> systems; systems.push_back(&sys); ecs->UpdateSystems(0, systems); for(size_t i = 0; i < 20; i++) { ASSERT_EQ(myNumbers[i], origNumbers[i] - 1); } delete ecs; for(size_t i = 0; i < 20; i++) { ASSERT_EQ(myNumbers[i], origNumbers[i]); } } TEST(ECS, CustomSystemMultipleComponentTypes) { ECS* ecs = new ECS(); CreateDeleteIntClassSystem sys; std::vector<int> myNumbers; std::vector<int> origNumbers; std::vector<Entity*> entities; for(int i = 0; i < 20; i++) { myNumbers.push_back(i); origNumbers.push_back(i); entities.push_back(ecs->CreateEntity()); } for(int i = 0; i < 20; i++) { entities[i]->AddComponent<DeleteIntClass>(&myNumbers[i]); entities[i]->AddComponent<CreateIntClass>(i); ASSERT_EQ(myNumbers[i], origNumbers[i]); ASSERT_EQ(*entities[i]->GetComponent<CreateIntClass>()->GetNumber(), i); } std::vector<BaseSystem*> systems; systems.push_back(&sys); ecs->UpdateSystems(0, systems); for(size_t i = 0; i < 20; i++) { ASSERT_EQ(*entities[i]->GetComponent<CreateIntClass>()->GetNumber() - myNumbers[i], 2); } delete ecs; for(size_t i = 0; i < 20; i++) { ASSERT_EQ(myNumbers[i], origNumbers[i]); } } TEST(ECS, CustomSystemMultipleComponentTypesOptional) { ECS ecs; SubtractionSystem sys; std::vector<BaseSystem*> systems; systems.push_back(&sys); std::vector<Entity*> entities; for(int i = 0; i < 20; i++) { entities.push_back(ecs.CreateEntity()); } for(int i = 0; i < 20; i++) { entities[i]->AddComponent<int>(i); ASSERT_EQ(*entities[i]->GetComponent<int>(), i); if(i % 2 == 0) { entities[i]->AddComponent<unsigned int>(i); ASSERT_EQ(*entities[i]->GetComponent<unsigned int>(), i); } } ecs.UpdateSystems(0, systems); for(int i = 0; i < 20; i++) { if(i % 2 == 0) { ASSERT_EQ(*entities[i]->GetComponent<int>(), 0); } else { ASSERT_EQ(*entities[i]->GetComponent<int>(), i); } } } TEST(ECS, MultipleCustomSystems) { ECS ecs; SubtractionSystem subSys; MultiplicationSystem mulSys; std::vector<Entity*> entities; for(int i = 0; i < 20; i++) { entities.push_back(ecs.CreateEntity()); entities[i]->AddComponent<int>(i); entities[i]->AddComponent<unsigned int>(i); } // Order matters! std::vector<BaseSystem*> systems; systems.push_back(&mulSys); systems.push_back(&subSys); ecs.UpdateSystems(0, systems); for(int i = 0; i < 20; i++) { ASSERT_EQ(*entities[i]->GetComponent<int>(), i * i - i); } }
20.765957
95
0.573258
Schtekt
cfe7e8be38d0795cbd9830610e49d419ae073f94
1,416
hpp
C++
src/Engine.hpp
Galhad/firestorm
3c1584b1e5b95f21d963b9cf226f6ec1a469d7af
[ "MIT" ]
null
null
null
src/Engine.hpp
Galhad/firestorm
3c1584b1e5b95f21d963b9cf226f6ec1a469d7af
[ "MIT" ]
null
null
null
src/Engine.hpp
Galhad/firestorm
3c1584b1e5b95f21d963b9cf226f6ec1a469d7af
[ "MIT" ]
null
null
null
#ifndef FIRESTORM_ENGINE_HPP #define FIRESTORM_ENGINE_HPP #include "EngineCreationParams.hpp" #include "graphics/GraphicsManager.hpp" #include "scene/SceneManager.hpp" #include "physics/PhysicsManager.hpp" #include "io/InputManager.hpp" #include "io/FileProvider.hpp" #include "utils/Logger.hpp" #include <memory> #include <functional> namespace fs { class Engine { public: Engine(); virtual ~Engine(); void create(const EngineCreationParams& creationParams); virtual void destroy(); void run(); virtual void update(float deltaTime); graphics::GraphicsManager& getGraphicsManager() const; scene::SceneManager& getSceneManager() const; io::InputManager& getInputManager() const; io::FileProvider& getFileProvider() const; const utils::LoggerPtr& getLogger() const; protected: virtual void render(const VkCommandBuffer& commandBuffer, const VkPipelineLayout& pipelineLayout, const VkDescriptorSet& uniformDescriptorSet); protected: graphics::GraphicsManagerPtr graphicsManager; io::InputManagerPtr inputManager; io::FileProviderPtr fileProvider; scene::SceneManagerPtr sceneManager; physics::PhysicsManagerPtr physicsManager; utils::LoggerPtr logger = spdlog::stdout_color_mt(utils::CONSOLE_LOGGER_NAME); }; typedef std::unique_ptr<Engine> EnginePtr; } #endif //FIRESTORM_ENGINE_HPP
24.413793
82
0.737994
Galhad
cfe80dd1d50da4993f3e77635a4006f700c358ea
63,477
cpp
C++
app/ValidateIABStream.cpp
DTSProAudio/iab-validator
694b3782672aece877a3d5f79996f379e74299e9
[ "MIT" ]
3
2020-03-17T17:46:30.000Z
2020-10-01T09:09:00.000Z
app/ValidateIABStream.cpp
DTSProAudio/iab-validator
694b3782672aece877a3d5f79996f379e74299e9
[ "MIT" ]
1
2020-04-14T15:59:00.000Z
2020-04-14T15:59:00.000Z
app/ValidateIABStream.cpp
DTSProAudio/iab-validator
694b3782672aece877a3d5f79996f379e74299e9
[ "MIT" ]
3
2020-04-01T16:10:49.000Z
2020-04-16T06:47:37.000Z
/* Copyright (c) 2020 Xperi Corporation (and its subsidiaries). All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <iomanip> #include <fstream> #include <iostream> #include <sstream> #include "ValidateIABStream.h" #include "libjson.h" #ifdef _LOG #define LOG_ERR(x) (std::cerr << (x)) #define LOG_OUT(x) (std::cout << (x)) #else #define LOG_ERR(x) #define LOG_OUT(x) #endif std::string intToString(int32_t value) { char ch[32]; sprintf(ch, "%d", value); return std::string(ch); } // Constructor ValidateIABStream::ValidateIABStream() { iabParser_ = nullptr; iabValidator_ = nullptr; inputFile_ = nullptr; hasInvalidSets_ = false; hasValidationIssues_ = false; inputFrameCount_ = 0; numIssuesToReport_ = 0; reportAllIssues_ = true; jsonTree_ = json_new(JSON_NODE); validationResultSummaryInJson_ = nullptr; validationIssuesSummaryInJson_ = nullptr; parserResultInJson_ = nullptr; status_code_ = kIABValidatorSuccessful; error_warnings_list_ = nullptr; // Create an IAB Validator instance to validate bitstream iabValidator_ = IABValidatorInterface::Create(); } // Destructor ValidateIABStream::~ValidateIABStream() { if (iabParser_) { IABParserInterface::Delete(iabParser_); } if (iabValidator_) { IABValidatorInterface::Delete(iabValidator_); } if (jsonTree_) { json_delete(jsonTree_); } // Delete error and warnings list. struct ErrorList *current = error_warnings_list_; struct ErrorList *next; while (current != nullptr) { next = current->next_; delete(current); current = next; } CloseInputOutputFiles(); } // ValidateIABStream::AreSettingsValid() implementation bool ValidateIABStream::AreSettingsValid(ValidationSettings& iSettings) { if (iSettings.inputFileStem_.empty() || iSettings.inputFileExt_.empty() || iSettings.validationConstraintSets_.empty()) { return false; } // Save settings to class internal members inputFileStem_ = iSettings.inputFileStem_; inputFileExt_ = iSettings.inputFileExt_; outputPath_ = iSettings.outputPath_; multiFilesInput_ = iSettings.multiFilesInput_; validationConstraintSets_ = iSettings.validationConstraintSets_; reportAllIssues_ = iSettings.reportAllIssues_; numIssuesToReport_ = iSettings.numIssuesToReport_; return true; } // ValidateIABStream::OpenInputFile() implementation iabError ValidateIABStream::OpenInputFile(std::string iInputFileName) { inputFile_ = new std::ifstream(iInputFileName.c_str(), std::ifstream::in | std::ifstream::binary); if (!inputFile_->good()) { return kIABGeneralError; } return kIABNoError; } // ValidateIABStream::CloseInputOutputFiles() implementation iabError ValidateIABStream::CloseInputOutputFiles() { // Close files if (inputFile_) { inputFile_->close(); delete inputFile_; inputFile_ = nullptr; } return kIABNoError; } // ValidateIABStream::Validate() implementation ExitStatusCode ValidateIABStream::Validate(ValidationSettings& iSettings) { // Check settings and save if valid if (!AreSettingsValid(iSettings)) { // Invalid, return error return kIABValidatorSetupFailed; } if (!iabValidator_) { // Error : Validator not instantiated return kIABValidatorInstanceCannotBeCreated; } bool noProcessingError = true; iabError returnCode = kIABNoError; if (multiFilesInput_) { LOG_ERR("Processing bitstream frame sequence. This could take several minutes for complex or long bitstreams ........\n"); while (1) { // Construct next input file name std::stringstream ss; ss << inputFileStem_.c_str() << std::setfill('0') << std::setw(6) << inputFrameCount_ << inputFileExt_; // open input file for processing. Break loop if there is no more input. if (kIABNoError != OpenInputFile(ss.str())) { if (inputFrameCount_ == 0) { LOG_ERR("!Error in opening file : " + ss.str() + ". Input file name error or missing input file).\n"); noProcessingError = false; status_code_ = kIABValidatorCannotOpenInputFile; } break; } // Use a new IABParser instance for each new file. If one exists, delete it if (iabParser_) { IABParserInterface::Delete(iabParser_); iabParser_ = nullptr; } // Create an IAB Parser instance to process current file iabParser_ = IABParserInterface::Create(inputFile_); // Parse the bitstream into IAB frame returnCode = iabParser_->ParseIABFrame(); if (kIABNoError != returnCode) { if ((inputFrameCount_ == 0) || (returnCode != kIABParserEndOfStreamReached)) { LOG_ERR("The application has encountered an error when parsing a frame from the bitstream.\n"); LOG_ERR("Error code: " + intToString(returnCode) + GetParserErrorString(returnCode)); parserResultInJson_ = json_new(JSON_NODE); json_set_name(parserResultInJson_, "ParserState"); json_push_back(parserResultInJson_, json_new_a("Error", GetParserErrorString(returnCode).c_str())); json_push_back(parserResultInJson_, json_new_i("FrameIndex", inputFrameCount_ + 1)); noProcessingError = false; status_code_ = kIABValidatorParsingIABFrameFromBitStreamFailed; } break; } if (inputFile_) { // For multi-files input, finish with current input file, close it inputFile_->close(); delete inputFile_; inputFile_ = nullptr; } const IABFrameInterface *frameInterface = nullptr; // Get the parsed IAB frame from IABParser if (kIABNoError != iabParser_->GetIABFrame(frameInterface) || frameInterface == nullptr) { LOG_ERR("The application is unable to get the parsed IAB frame from the parser.\n"); noProcessingError = false; status_code_ = kIABValidatorParsedIABFrameFromParserFailed; break; } if (inputFrameCount_ > 0) { // Check and update maxRendered if necessary IABMaxRenderedRangeType maxRendered = 0; frameInterface->GetMaxRendered(maxRendered); if (maxRendered > bitstreamMaxRendered_) { bitstreamMaxRendered_ = maxRendered; } } else { // First frame, record bitstream summary for reporting // Note that these items should be static for a valid bitstream and leave it to the validator to pick up any issues. RecordBitstreamSummary(frameInterface); } // Validate the parsed frame. The validator will keep tracks of validation state, warnings and errors // These will be checked when validation completes or aborted returnCode = iabValidator_->ValidateIABFrame(frameInterface, inputFrameCount_); if (kIABNoError != returnCode) { // Temporary reporting, parser error reporting will be finalised in PACL-669 LOG_ERR("The application has encountered an error when validating a parsed IAB frame.\n"); LOG_ERR("Error code: " + intToString(returnCode)); noProcessingError = false; status_code_ = kIABValidatorIABParsedFrameValidationFailed; break; } inputFrameCount_++; if ((reportAllIssues_ == false) && (DoesNumOfIssuesExceed() == true)) { status_code_ = kIABValidatorIssuesExceeded; noProcessingError = false; break; } // Display progress every 50 frames if ((inputFrameCount_ % 50) == 0) { std::cout << "Frames processed: " << inputFrameCount_ << std::endl << std::flush; } } } else // single-file input { LOG_OUT("Processing input file : " + inputFileStem_ + inputFileExt_ + ". This could take several minutes for complex or long bitstreams ........\n" ); while (1) { if (inputFrameCount_ > 0) { if (inputFile_->eof()) { // Finished processing inputFile_->close(); delete inputFile_; inputFile_ = nullptr; break; } } else { // First frame, open the input file for the Parser to use std::string inputFile = inputFileStem_ + inputFileExt_; if (kIABNoError != OpenInputFile(inputFile)) { LOG_ERR( "!Error in opening file : " +inputFile + ". Input file name error or missing input file.\n"); noProcessingError = false; status_code_ = kIABValidatorCannotOpenInputFile; break; } } if (inputFrameCount_ == 0) { if (iabParser_) { IABParserInterface::Delete(iabParser_); iabParser_ = nullptr; } // Create an IAB Parser instance to process current file iabParser_ = IABParserInterface::Create(inputFile_); } // Parse the bitstream into IAB frame returnCode = iabParser_->ParseIABFrame(); // TODO Process error code to provide more info if (kIABNoError != returnCode) { if ((inputFrameCount_ == 0) || (returnCode != kIABParserEndOfStreamReached)) { // Temporary reporting, parser error reporting will be finalised in PACL-669 LOG_ERR("The application has encountered an error when parsing a frame from the bitstream.\n"); LOG_ERR("Error code: " + intToString(returnCode) + GetParserErrorString(returnCode) + "\n"); parserResultInJson_ = json_new(JSON_NODE); json_set_name(parserResultInJson_, "ParserState"); json_push_back(parserResultInJson_, json_new_a("Error", GetParserErrorString(returnCode).c_str())); json_push_back(parserResultInJson_, json_new_i("FrameIndex", inputFrameCount_ + 1)); noProcessingError = false; status_code_ = kIABValidatorParsingIABFrameFromBitStreamFailed; } break; } const IABFrameInterface *frameInterface = nullptr; if (kIABNoError != iabParser_->GetIABFrame(frameInterface) || frameInterface == nullptr) { LOG_ERR("The application is unable to get the parsed IAB frame from the parser.\n"); noProcessingError = false; status_code_ = kIABValidatorParsedIABFrameFromParserFailed; break; } if (inputFrameCount_ > 0) { // Check and update maxRendered if necessary IABMaxRenderedRangeType maxRendered = 0; frameInterface->GetMaxRendered(maxRendered); if (maxRendered > bitstreamMaxRendered_) { bitstreamMaxRendered_ = maxRendered; } } else { // First frame, record bitstream summary for reporting RecordBitstreamSummary(frameInterface); } // Validate the parsed frame. The validator will keep tracks of validation state, warnings and errors // These will be checked when validation completes or aborted returnCode = iabValidator_->ValidateIABFrame(frameInterface, inputFrameCount_); if (kIABNoError != returnCode) { // Temporary reporting, parser error reporting will be finalised in PACL-669 LOG_ERR("The application has encountered an error when validating a parsed IAB frame.\n"); LOG_ERR("Error code: " + intToString(returnCode) + "\n"); noProcessingError = false; status_code_ = kIABValidatorIABParsedFrameValidationFailed; break; } inputFrameCount_++; if ((reportAllIssues_ == false) && (DoesNumOfIssuesExceed() == true)) { status_code_ = kIABValidatorIssuesExceeded; noProcessingError = false; break; } // Display progress every 50 frames if ((inputFrameCount_ % 50) == 0) { LOG_OUT("Frames processed: " + intToString(inputFrameCount_) + "\n"); } } } LOG_OUT ( "Total frames processed: " + intToString(inputFrameCount_) + "\n\n"); if (noProcessingError) { return kIABValidatorSuccessful; } else { return status_code_; } } // ValidateIABStream::RecordBitstreamSummary() implementation void ValidateIABStream::RecordBitstreamSummary(const IABFrameInterface *iFrameInterface) { iFrameInterface->GetSampleRate(bitstreamSampleRate_); iFrameInterface->GetFrameRate(bitstreamFrameRate_); iFrameInterface->GetBitDepth(bitstreamBitDepth_); iFrameInterface->GetMaxRendered(bitstreamMaxRendered_); } // Display the validation report on the console void ValidateIABStream::DisplayValidationSummary() { std::cout << "Bitstream Summary Information:" << std::endl; std::cout << "\tSampleRate: " << GetSampleRateString(bitstreamSampleRate_) << std::endl; std::cout << "\tFrameRate: " << GetFrameRateString(bitstreamFrameRate_) << std::endl; std::cout << "\tBitDepth: " << GetBitDepthString(bitstreamBitDepth_) << std::endl; std::cout << "\tFrameCount: " << inputFrameCount_ << std::endl; std::cout << "\tMaxRenderedInStream: " << bitstreamMaxRendered_ << std::endl << std::endl; if (validationResultSummaryInJson_) { std::cout << "Validation Summary Information:\n" << json_write_formatted(validationResultSummaryInJson_) << std::endl << std::endl; } if (validationIssuesSummaryInJson_) { std::cout << "Issues Summary Information:\n" << json_write_formatted(validationIssuesSummaryInJson_) << std::endl << std::endl; } } // Display parser fail state on console. void ValidateIABStream::DisplayParserFailState() { if (parserResultInJson_) { std::cout << json_write_formatted(parserResultInJson_) << std::endl; std::cout << "\n====================\n\n"; } } void ValidateIABStream::ReportBitstreamSummary() { JSONNODE * summaryNode = json_new(JSON_NODE); json_set_name(summaryNode, "BitStreamSummary"); json_push_back(summaryNode, json_new_a("SampleRate", GetSampleRateString(bitstreamSampleRate_).c_str())); json_push_back(summaryNode, json_new_a("FrameRate", GetFrameRateString(bitstreamFrameRate_).c_str())); json_push_back(summaryNode, json_new_a("BitDepth", GetBitDepthString(bitstreamBitDepth_).c_str())); // validation stopped, hence total number of frames yet to be known if (status_code_ == kIABValidatorIssuesExceeded) { json_push_back(summaryNode, json_new_a("FrameCount", "?")); json_push_back(summaryNode, json_new_a("MaxRendered", "?")); } else { json_push_back(summaryNode, json_new_a("FrameCount", intToString(inputFrameCount_).c_str())); json_push_back(summaryNode, json_new_a("MaxRendered", intToString(bitstreamMaxRendered_).c_str())); } json_push_back(jsonTree_, summaryNode); } // Returns the json report void ValidateIABStream::GetValidatedResultInJson(JSONNODE** oNode) { *oNode = jsonTree_; } // Check for number of issues found so far bool ValidateIABStream::DoesNumOfIssuesExceed() { // if number of issues are said to be displayed restricted, after each frame validation check for number of issues // captured so far. if (reportAllIssues_ == false) { std::set<SupportedConstraintsSet>::iterator iterCS; for (iterCS = validationConstraintSets_.begin(); iterCS != validationConstraintSets_.end(); iterCS++) { std::vector<ValidationIssue> validationIssues; std::vector<ValidationIssue>::iterator iterIssues; validationIssues = iabValidator_->GetValidationIssues(*iterCS); if (validationIssues.size() >= numIssuesToReport_) { return true; } } } return false; } // ValidateIABStream::WriteValidationReport() implementation void ValidateIABStream::GenerateValidationReport(ReportLevel iReportLevel) { // No parser error. if (status_code_ != kIABValidatorParsingIABFrameFromBitStreamFailed) { // Report Summary ReportBitstreamSummary(); LOG_OUT("Validation result:\n\n"); JSONNODE * validationResultsInJson = json_new(JSON_ARRAY); json_set_name(validationResultsInJson, "ValidationResult"); validationResultSummaryInJson_ = json_new(JSON_ARRAY); json_set_name(validationResultSummaryInJson_, "ValidationResultSummary"); validationIssuesSummaryInJson_ = json_new(JSON_ARRAY); json_set_name(validationIssuesSummaryInJson_, "IssueOccurrenceSummary"); // Generate report for each constraint set specified in validation settings std::set<SupportedConstraintsSet>::iterator iterCS; for (iterCS = validationConstraintSets_.begin(); iterCS != validationConstraintSets_.end(); iterCS++) { JSONNODE * validationResultInJson = json_new(JSON_NODE); WriteReportForConstrainSet(*iterCS, validationResultInJson, validationResultSummaryInJson_); json_push_back(validationResultsInJson, validationResultInJson); // Get the constriant set string for reporting std::string constraintString; constraintString = GetConstraintSetString(*iterCS); AddErrorSummaryToReport(*iterCS, validationIssuesSummaryInJson_); } if (hasValidationIssues_) { LOG_OUT( "\nNote that due to the validation constraint hierrarchy design, issues from the base set(s) will be reported\n"); LOG_OUT( "before the requested constraint set. For example since ST-429-18-2019 is a super set of ST-2098-2, a bitstream\n"); LOG_OUT( "item could be reported as a warning issue for ST-2098-2 and additionally reported as an error issue for ST-429-18-2019.\n\n"); } json_push_back(jsonTree_, validationResultSummaryInJson_); json_push_back(jsonTree_, validationIssuesSummaryInJson_); if (kIABValidatorReportFull == iReportLevel) { json_push_back(jsonTree_, validationResultsInJson); } } else { json_push_back(jsonTree_, parserResultInJson_); } } // WriteReportForConstrainSet functionality summary // 1. Gets the issueList for the constraintSet // 2. Generates the issues summary in Json structure (i.e indicates the valid, invalid or warning) // 3. Generates Issue summary Linked list (Group the errors and warnings together for constraint set // 4. Stores the issue in the JSON structure. // ValidateIABStream::WriteReportForConstrainSet() implementation bool ValidateIABStream::WriteReportForConstrainSet(SupportedConstraintsSet iValidationConstraintSet, JSONNODE* validationResultInJson, JSONNODE* iSummaryNode) { std::string constraintString; ValidationResult validationResult; // Get the constriant set string for reporting constraintString = GetConstraintSetString(iValidationConstraintSet); // Get validation result validationResult = iabValidator_->GetValidationResult(iValidationConstraintSet); json_push_back(validationResultInJson, json_new_a("Constraint", constraintString.c_str())); JSONNODE * validationResultSummary = json_new(JSON_NODE); json_push_back(validationResultSummary, json_new_a("Constraint", constraintString.c_str())); // 1. Gets the issueList for the constraintSet // combined issues list is needed to find out the origin of the issue. std::vector<ValidationIssue> combinedIssuesList = iabValidator_->GetValidationIssues(iValidationConstraintSet); std::string issueOrigin = ""; if (combinedIssuesList.size()) { std::vector<ValidationIssue>::iterator iter = combinedIssuesList.begin(); issueOrigin = GetConstraintSetString(iter->isBeingValidated_); } std::vector<ValidationIssue> validationIssues; std::vector<ValidationIssue>::iterator iterIssues; // Get only constraint set interested in. For all constraints validaiton (-cA), we dont want to report the errors repeatedly. // For single constraint validation, we shall report all errors in the hierarchy. if (validationConstraintSets_.size() > 1) { validationIssues = iabValidator_->GetValidationIssuesSingleSetOnly(iValidationConstraintSet); } else { validationIssues = combinedIssuesList; } // 2. Generates the issues summary in Json structure (i.e indicates the valid, invalid or warning) // 3. Generates Issue summary Linked list (Group the errors and warnings together for constraint set if (validationResult == kValid) { json_push_back(validationResultInJson, json_new_a("ValidationState", "Valid")); json_push_back(validationResultSummary, json_new_a("ValidationState", "Valid")); // Bitstream is valid against this constraint set, no additional information to report LOG_OUT( "Input stream complies with " + constraintString +"\n\n"); json_push_back(validationResultSummary, json_new_i("NumIssues", combinedIssuesList.size())); } else { std::string issueType = ""; if (validationResult == kValidWithWarning) { issueType = "ValidWithWarning"; LOG_OUT( "Input stream complies with " + constraintString + " but with warnings, see additional information below:\n" ); } else { hasInvalidSets_ = true; issueType = "Invalid"; LOG_OUT( "Input stream does not comply with " + constraintString + ", see additional information below:\n"); } json_push_back(validationResultInJson, json_new_a("ValidationState", issueType.c_str())); // added to validation results // added to summary json_push_back(validationResultSummary, json_new_a("ValidationState", issueType.c_str())); json_push_back(validationResultSummary, json_new_a("IssueRootConstraintSet", issueOrigin.c_str())); // The below logic is for classifying the NumIssues for each constraint set. if (iValidationConstraintSet == kConstraints_set_Cinema_ST2098_2_2018) { json_push_back(validationResultSummary, json_new_i("NumIssues", validationIssues.size())); } else if (iValidationConstraintSet == kConstraints_set_Cinema_ST429_18_2019) { std::string classification = ""; const std::vector<ValidationIssue> set_1 = iabValidator_->GetValidationIssuesSingleSetOnly(kConstraints_set_Cinema_ST2098_2_2018); const std::vector<ValidationIssue> set_2 = iabValidator_->GetValidationIssuesSingleSetOnly(kConstraints_set_Cinema_ST429_18_2019); if (set_1.size()) { classification = "ST2098-2-2018(" + intToString(set_1.size()) + ") + "; } if (classification.length()) { classification += "ST429-18-2019(" + intToString(set_2.size()) + ")"; classification = intToString(combinedIssuesList.size()) + " (= " + classification + ")"; json_push_back(validationResultSummary, json_new_a("NumIssues", classification.c_str())); } else { json_push_back(validationResultSummary, json_new_i("NumIssues", set_2.size())); } } else if (iValidationConstraintSet == kConstraints_set_DbyCinema) { std::string classification = ""; const std::vector<ValidationIssue> set_1 = iabValidator_->GetValidationIssuesSingleSetOnly(kConstraints_set_Cinema_ST2098_2_2018); const std::vector<ValidationIssue> set_2 = iabValidator_->GetValidationIssuesSingleSetOnly(kConstraints_set_Cinema_ST429_18_2019); const std::vector<ValidationIssue> set_3 = iabValidator_->GetValidationIssuesSingleSetOnly(kConstraints_set_DbyCinema); if (set_1.size()) { classification = "ST2098-2-2018(" + intToString(set_1.size()) + ") + "; } if (set_2.size()) { classification += "ST429-18-2019(" + intToString(set_2.size()) + ") + "; } if (classification.length()) { classification += "DbyCinema(" + intToString(set_3.size()) + ")"; classification = intToString(combinedIssuesList.size()) + " (= " + classification + ")"; json_push_back(validationResultSummary, json_new_a("NumIssues", classification.c_str())); } else { json_push_back(validationResultSummary, json_new_i("NumIssues", set_3.size())); } } /// IMF Constraint sets // The following logic will group together errors and warnings depending upon the constraint set. if (iValidationConstraintSet == kConstraints_set_IMF_ST2098_2_2019) { json_push_back(validationResultSummary, json_new_i("NumIssues", validationIssues.size())); } else if (iValidationConstraintSet == kConstraints_set_IMF_ST2067_201_2019) { std::string classification = ""; const std::vector<ValidationIssue> set_1 = iabValidator_->GetValidationIssuesSingleSetOnly(kConstraints_set_IMF_ST2098_2_2019); const std::vector<ValidationIssue> set_2 = iabValidator_->GetValidationIssuesSingleSetOnly(kConstraints_set_IMF_ST2067_201_2019); if (set_1.size()) { classification = "IMF ST2098-2-2019(" + intToString(set_1.size()) + ") + "; } if (classification.length()) { classification += "IMF ST2067-201-2019(" + intToString(set_2.size()) + ")"; classification = intToString(combinedIssuesList.size()) + " (= " + classification + ")"; json_push_back(validationResultSummary, json_new_a("NumIssues", classification.c_str())); } else { json_push_back(validationResultSummary, json_new_i("NumIssues", set_2.size())); } } else if (iValidationConstraintSet == kConstraints_set_DbyIMF) { std::string classification = ""; const std::vector<ValidationIssue> set_1 = iabValidator_->GetValidationIssuesSingleSetOnly(kConstraints_set_IMF_ST2098_2_2019); const std::vector<ValidationIssue> set_2 = iabValidator_->GetValidationIssuesSingleSetOnly(kConstraints_set_IMF_ST2067_201_2019); const std::vector<ValidationIssue> set_3 = iabValidator_->GetValidationIssuesSingleSetOnly(kConstraints_set_DbyIMF); if (set_1.size()) { classification = "IMF ST2098-2-2019(" + intToString(set_1.size()) + ") + "; } if (set_2.size()) { classification += "IMF ST2067-201-2019(" + intToString(set_2.size()) + ") + "; } if (classification.length()) { classification += "DbyIMF(" + intToString(set_3.size()) + ")"; classification = intToString(combinedIssuesList.size()) + " (= " + classification + ")"; json_push_back(validationResultSummary, json_new_a("NumIssues", classification.c_str())); } else { json_push_back(validationResultSummary, json_new_i("NumIssues", set_3.size())); } } // 4. Stores the issues in the JSON structure. SupportedConstraintsSet lastReportingConstraintSet = iValidationConstraintSet; std::string errorString; if (validationIssues.size() > 0) { hasValidationIssues_ = true; json_push_back(validationResultInJson, json_new_i("IssuesReported", validationIssues.size())); JSONNODE * IssuesJson = json_new(JSON_ARRAY); json_set_name(IssuesJson, "ReportedIssues"); for (iterIssues = validationIssues.begin(); iterIssues != validationIssues.end(); iterIssues++) { JSONNODE * IssueJson = json_new(JSON_NODE); json_push_back(IssueJson, json_new_i("IssueNum", iterIssues - validationIssues.begin()+1)); // Check the reporting constraint set and display once per group if ((iterIssues == validationIssues.begin()) || (lastReportingConstraintSet != iterIssues->isBeingValidated_)) { lastReportingConstraintSet = iterIssues->isBeingValidated_; constraintString = GetConstraintSetString(lastReportingConstraintSet); LOG_ERR("\n\tIssues found when validating against " + constraintString + ":\n" ); } switch(iterIssues->event_) { case ErrorEvent: LOG_ERR( "\t\t- Error event found at frame #" + intToString(iterIssues->frameIndex_) + ", ID=" + intToString(iterIssues->id_)); if (kIABNoError != iterIssues->errorCode_) { LOG_ERR( ", ErrorCode=" + intToString(iterIssues->errorCode_) + GetValidationErrorString(iterIssues->errorCode_) +"\n"); json_push_back(IssueJson, json_new_a("EventType", "Error")); } else { LOG_OUT("\n"); } break; case WarningEvent: LOG_ERR( "\t\t- Warning event found at frame #" + intToString(iterIssues->frameIndex_) + ", ID=" + intToString(iterIssues->id_)); if (kIABNoError != iterIssues->errorCode_) { LOG_ERR( ", ErrorCode=" + intToString(iterIssues->errorCode_) + GetValidationErrorString(iterIssues->errorCode_) + "\n"); json_push_back(IssueJson, json_new_a("EventType", "Warning")); } else { LOG_OUT("\n"); } break; default: break; } json_push_back(IssueJson, json_new_i("FrameIndex", iterIssues->frameIndex_)); json_push_back(IssueJson, json_new_a("MetaID", GetIssueIDString(iterIssues->id_).c_str())); json_push_back(IssueJson, json_new_a("ErrorText", GetValidationErrorString(iterIssues->errorCode_).c_str())); json_push_back(IssueJson, json_new_a("Constraint", GetConstraintSetString(iterIssues->isBeingValidated_).c_str())); AddEventToList(lastReportingConstraintSet, iterIssues->event_, iterIssues->errorCode_); json_push_back(IssuesJson, IssueJson); } json_push_back(validationResultInJson, IssuesJson); LOG_OUT("\n"); } } json_push_back(iSummaryNode, validationResultSummary); return true; } // ValidateIABStream::GetIssueIDString() implementation std::string ValidateIABStream::GetIssueIDString(int32_t issueId) { switch(issueId) { case kIssueID_IAFrame: return "IABFrame"; case kIssueID_AuthoringToolInfo: return "AuthoringTool Info"; case kIssueID_UserData: return "UserData"; case kIssueID_ObjectZoneDefinition19: return "ObjectZoneDefinition19"; default: return intToString(issueId); } } // ValidateIABStream::GetConstraintSetString() implementation std::string ValidateIABStream::GetConstraintSetString(SupportedConstraintsSet iValidationConstraintSet) { switch(iValidationConstraintSet) { case kConstraints_set_Cinema_ST2098_2_2018: return "Cinema 2098-2-2018 constraint"; case kConstraints_set_Cinema_ST429_18_2019: return "Cinema ST429-18-2019 constraint"; case kConstraints_set_DbyCinema: return "DbyCinema constraint"; case kConstraints_set_IMF_ST2098_2_2019: return "IMF ST2098-2-2019 constraint"; case kConstraints_set_IMF_ST2067_201_2019: return "IMF ST2067-201-2019 constraint"; case kConstraints_set_DbyIMF: return "DbyIMF constraint"; default: return ""; } } // ValidateIABStream::GetSampleRateString() implementation std::string ValidateIABStream::GetSampleRateString(IABSampleRateType iSampleRateCode) { if (iSampleRateCode == kIABSampleRate_48000Hz) { return "48kHz"; } else if (iSampleRateCode == kIABSampleRate_96000Hz) { return "96kHz"; } else { return "unknown"; } } // ValidateIABStream::GetFrameRateString() implementation std::string ValidateIABStream::GetFrameRateString(IABFrameRateType iFrameRateCode) { switch(iFrameRateCode) { case kIABFrameRate_24FPS: return "24 fps"; case kIABFrameRate_25FPS: return "25 fps"; case kIABFrameRate_30FPS: return "30 fps"; case kIABFrameRate_48FPS: return "48 fps"; case kIABFrameRate_50FPS: return "50 fps"; case kIABFrameRate_60FPS: return "60 fps"; case kIABFrameRate_96FPS: return "96 fps"; case kIABFrameRate_100FPS: return "100 fps"; case kIABFrameRate_120FPS: return "120 fps"; case kIABFrameRate_23_976FPS: return "23.976 fps"; default: return "unknown"; } } // ValidateIABStream::GetBitDepthString() implementation std::string ValidateIABStream::GetBitDepthString(IABBitDepthType iBitDepthCode) { if (iBitDepthCode == kIABBitDepth_24Bit) { return "24-bit"; } else if (iBitDepthCode == kIABBitDepth_16Bit) { return "16-bit"; } else { return "unknown"; } } // ValidateIABStream::GetValidationErrorString() implementation std::string ValidateIABStream::GetParserErrorString(iabError iErrorCode) { std::string errorString = "!Parsing terminated: "; // Not expecting any non-validation error code but just for completeness if (iErrorCode < kValidateGeneralError) { switch (iErrorCode) { case kIABParserInvalidVersionNumberError: errorString += "Invalid IAB Version number"; break; case kIABParserInvalidSampleRateError: errorString += "Invalid IAB Sample Rate"; break; case kIABParserInvalidFrameRateError: errorString += "Invalid IAB Frame Rate"; break; case kIABParserInvalidBitDepthError: errorString += "Invalid IAB Bit Depth"; break; case kIABParserMissingPreambleError: errorString += "IAB Preamble sub-frame is missing from bitstream"; break; default: errorString += "Input stream contains possible data corruption. Unable to continue parsing."; break; } } return errorString; } // ValidateIABStream::GetValidationErrorString() implementation std::string ValidateIABStream::GetValidationErrorString(iabError iErrorCode) { std::string errorString; // Map validation error code to error string switch (iErrorCode) { case kValidateGeneralError: errorString = "General validation error"; break; case kValidateErrorIAFrameIllegalBitstreamVersion: errorString = "Illegal version number"; break; case kValidateErrorIAFrameUnsupportedSampleRate: errorString = "Unsupported sample rate"; break; case kValidateErrorIAFrameUnsupportedBitDepth: errorString = "Unsupported bit depth"; break; case kValidateErrorIAFrameUnsupportedFrameRate: errorString = "Unsupported frame rate"; break; case kValidateErrorIAFrameMaxRenderedExceeded: errorString = "IAFrame MaxRendered limit exceeded"; break; case kValidateWarningIAFrameMaxRenderedNotMatchObjectNumbers: errorString = "IAFrame MaxRendered not matching number of bed channels and objects"; break; case kValidateErrorIAFrameSubElementCountConflict: errorString = "Frame sub-element count in conflict with sub-element list"; break; case kValidateErrorIAFrameBitstreamVersionNotPersistent: errorString = "Bitstream version number not persistent"; break; case kValidateErrorIAFrameSampleRateNotPersistent: errorString = "Sample rate not persistent"; break; case kValidateErrorIAFrameBitDepthNotPersistent: errorString = "Bit depth not persistent"; break; case kValidateErrorIAFrameFrameRateNotPersistent: errorString = "Frame rate not persistent"; break; case kValidateErrorIAFrameUndefinedElementType: errorString = "Undefined element found in IABFrame"; break; case kValidateErrorIAFrameSizeLimitExceeded: errorString = "IABFrame size limit exceeded"; break; case kValidateErrorBedDefinitionDuplicateMetaID: errorString = "Duplicate BedDefinition meta ID in frame"; break; case kValidateErrorBedDefinitionMultiActiveSubElements: errorString = "BedDefinition has multiple active sub-elements"; break; case kValidateErrorBedDefinitionHierarchyLevelExceeded: errorString = "BedDefinition hierarchy level exceeded"; break; case kValidateErrorBedDefinitionChannelCountConflict: errorString = "BedDefinition channel count in conflict with channel list"; break; case kValidateErrorBedDefinitionDuplicateChannelID: errorString = "BedDefinition contains duplicate channel ID"; break; case kValidateErrorBedDefinitionUnsupportedGainPrefix: errorString = "BedDefinition contains unsupported gain prefix"; break; case kValidateErrorBedDefinitionUnsupportedDecorPrefix: errorString = "BedDefinition contains unsupported decorrelation prefix"; break; case kValidateErrorBedDefinitionAudioDescriptionTextExceeded: errorString = "BedDefinition audio description text exceeded length limit"; break; case kValidateErrorBedDefinitionSubElementCountConflict: errorString = "BedDefinition sub-element count in conflict with sub-element list"; break; case kValidateErrorBedDefinitionInvalidChannelID: errorString = "BedDefinition contains invalid or reserved channel ID"; break; case kValidateErrorBedDefinitionInvalidUseCase: errorString = "BedDefinition contains invalid or reserved use case"; break; case kValidateErrorBedDefinitionSubElementsNotAllowed: errorString = "BedDefinition cannot have sub-element"; break; case kValidateErrorBedDefinitionCountNotPersistent: errorString = "BedDefinition count changes over program frames"; break; case kValidateErrorBedDefinitionChannelCountNotPersistent: errorString = "BedDefinition channel count changes over program frames"; break; case kValidateErrorBedDefinitionMetaIDNotPersistent: errorString = "BedDefinition meta ID changes over program frames"; break; case kValidateErrorBedDefinitionChannelIDsNotPersistent: errorString = "BedDefinition channel IDs change over program frames"; break; case kValidateErrorBedDefinitionConditionalStateNotPersistent: errorString = "BedDefinition conditional flag or use case changes over program frames"; break; case kValidateErrorBedRemapDuplicateMetaID: errorString = "Duplicate BedRemap meta ID"; break; case kValidateErrorBedRemapSourceChannelCountNotEqualToBed: errorString = "BedRemap source channel count not equal to parent bed"; break; case kValidateErrorBedRemapSubblockCountConflict: errorString = "BedRemap subblock count conflict"; break; case kValidateErrorBedRemapSourceChannelCountConflict: errorString = "BedRemap source channel count conflict"; break; case kValidateErrorBedRemapDestinationChannelCountConflict: errorString = "BedRemap destination channel count conflict"; break; case kValidateErrorBedRemapInvalidDestChannelID: errorString = "BedRemap contains invalid or reserved destination channel ID"; break; case kValidateErrorBedRemapInvalidUseCase: errorString = "BedRemap contains invalid or reserved use case"; break; case kValidateErrorBedRemapNotAnAllowedSubElement: errorString = "BedRemap is not an allowed sub-element"; break; case kValidateErrorObjectDefinitionDuplicateMetaID: errorString = "Duplicate ObjectDefinition meta ID in frame"; break; case kValidateErrorObjectDefinitionMultiActiveSubElements: errorString = "ObjectDefinition has multiple active sub-elements"; break; case kValidateErrorObjectDefinitionHierarchyLevelExceeded: errorString = "ObjectDefinition hierarchy level exceeded"; break; case kValidateErrorObjectDefinitionPanSubblockCountConflict: errorString = "ObjectDefinition panblock count conflict"; break; case kValidateErrorObjectDefinitionUnsupportedGainPrefix: errorString = "ObjectDefinition contains unsupported gain prefix"; break; case kValidateErrorObjectDefinitionUnsupportedZoneGainPrefix: errorString = "ObjectDefinition contains unsupported zone gain prefix"; break; case kValidateErrorObjectDefinitionUnsupportedSpreadMode: errorString = "ObjectDefinition contains unsupported spread mode"; break; case kValidateErrorObjectDefinitionUnsupportedDecorPrefix: errorString = "ObjectDefinition contains unsupported decorrelation prefix"; break; case kValidateErrorObjectDefinitionAudioDescriptionTextExceeded: errorString = "ObjectDefinition audio description text exceeded length limit"; break; case kValidateErrorObjectDefinitionSubElementCountConflict: errorString = "ObjectDefinition sub-element count in conflict with sub-element list"; break; case kValidateErrorObjectDefinitionInvalidUseCase: errorString = "ObjectDefinition contains invalid or reserved use case"; break; case kValidateErrorObjectDefinitionInvalidSubElementType: errorString = "ObjectDefinition contains invalid sub-element type"; break; case kValidateErrorObjectDefinitionConditionalStateNotPersistent: errorString = "ObjectDefinition conditional flag or use case changes over program frames"; break; case kValidateErrorObjectZoneDefinition19SubblockCountConflict: errorString = "Object zone19 subblock count conflict"; break; case kValidateErrorObjectZoneDefinition19UnsupportedZoneGainPrefix: errorString = "Object zone19 contains unsupported zone gain prefix"; break; case kValidateErrorAudioDataDLCAudioDataIDZero: errorString = "AudioDataDLC AudioDataID cannot be zero"; break; case kValidateErrorAudioDataDLCDuplicateAudioDataID: errorString = "Duplicate AudioDataDLC duplicate ID"; break; case kValidateErrorAudioDataDLCUnsupportedSampleRate: errorString = "AudioDataDLC has unsupported sample rate"; break; case kValidateErrorAudioDataDLCSampleRateConflict: errorString = "AudioDataDLC sample rate in conflict with frame sample rate"; break; case kValidateErrorAudioDataDLCNotAnAllowedSubElement: errorString = "AudioDataDLC is not allowed"; break; case kValidateErrorAudioDataPCMAudioDataIDZero: errorString = "AudioDataPCM AudioDataID cannot be zero"; break; case kValidateErrorAudioDataPCMDuplicateAudioDataID: errorString = "Duplicate AudioDataDPCM duplicate ID"; break; case kValidateErrorAudioDataPCMNotAnAllowedSubElement: errorString = "AudioDataPCM is not allowed"; break; case kValidateErrorMissingAudioDataEssenceElement: errorString = "A referenced audio essence element (DLC or PCM) is missing"; break; case kValidateErrorUserDataNotAnAllowedSubElement: errorString = "UserData is not allowed"; break; case kValidateErrorDLCUsedWithIncompatibleFrameRate: errorString = "AudioDataDLC cannot be used with the current frame rate"; break; case kValidateErrorDolCinIAFrameUnsupportedSampleRate: errorString = "Sample rate not valid for DbyCinema"; break; case kValidateErrorDolCinBedDefinitionSubElementsNotAllowed: errorString = "BedDefinition cannot have sub-element for DbyCinema"; break; case kValidateErrorDolCinBedDefinitionInvalidChannelID: errorString = "BedDefinition contains invalid channel ID for DbyCinema"; break; case kValidateErrorDolCinBedDefinitionInvalidUseCase: errorString = "BedDefinition contains invalid use case for DbyCinema"; break; case kValidateErrorDolCinBedDefinitionMultipleBedsNotAllowed: errorString = "Multiple BedDefinitions are not allowed for DbyCinema"; break; case kValidateErrorDolCinBedDefinitionInvalidGainPrefix: errorString = "BedDefinition contains invalid gain prefix for DbyCinema"; break; case kValidateErrorDolCinBedDefinitionChannelDecorInfoExistNotZero: errorString = "BedDefinition channel DecorInfoExist must = 0 for DbyCinema"; break; case kValidateErrorDolCinBedDefinitionMaxChannelCountExceeded: errorString = "BedDefinition channel count limit exceeded for DbyCinema"; break; case kValidateErrorDolCinBedDefinitionCountNotPersistent: errorString = "BedDefinition count must be persistent for DbyCinema"; break; case kValidateErrorDolCinBedDefinitionMetaIDNotPersistent: errorString = "BedDefinition meta ID must be persistent for DbyCinema"; break; case kValidateErrorDolCinBedDefinitionChannelListNotPersistent: errorString = "BedDefinition channel list must be persistent for DbyCinema"; break; case kValidateErrorDolCinBedRemapUnsupportedGainPrefix: errorString = "BedRemap contains unsupported gain prefix for DbyCinema"; break; case kValidateErrorDolCinBedRemapNotAnAllowedSubElement: errorString = "BedRemap is not allowed for DbyCinema"; break; case kValidateErrorDolCinObjectDefinitionSubElementsNotAllowed: errorString = "ObjectDefinition cannot have sub-element for DbyCinema"; break; case kValidateErrorDolCinObjectDefinitionInvalidUseCase: errorString = "ObjectDefinition contains invalid use case for DbyCinema"; break; case kValidateErrorDolCinObjectDefinitionInvalidGainPrefix: errorString = "ObjectDefinition contains invalid gain prefix for DbyCinema"; break; case kValidateErrorDolCinObjectDefinitionInvalidZoneGainPrefix: errorString = "ObjectDefinition contains invalid zone gain prefix for DbyCinema"; break; case kValidateErrorDolCinObjectDefinitionInvalidSpreadMode: errorString = "ObjectDefinition contains invalid spread mode for DbyCinema"; break; case kValidateErrorDolCinObjectDefinitionInvalidDecorPrefix: errorString = "ObjectDefinition contains invalid decorrelation prefix for DbyCinema"; break; case kValidateErrorDolCinObjectDefinitionSnapTolExistsNotZero: errorString = "ObjectDefinition SnapTolExist must = 0 for DbyCinema"; break; case kValidateErrorDolCinObjectDefinitionMaxObjectCountExceeded: errorString = "ObjectDefinition count limit exceeded for DbyCinema"; break; case kValidateErrorDolCinObjectDefinitionNonSequenctialMetaID: errorString = "ObjectDefinition meta ID must be sequential for DbyCinema"; break; case kValidateErrorDolCinObjectZoneDefinition19NotAnAllowedSubElement: errorString = "Object zone19 is not allowed for DbyCinema"; break; case kValidateErrorDolCinAuthoringToolInfoNotAnAllowedSubElement: errorString = "AuthoringToolInfo is not allowed for DbyCinema"; break; case kValidateGeneralWarning: errorString = "Validation general warning"; break; case kValidateWarningFrameContainFrame: errorString = "IABFrame contains an IABFrame as sub-element"; break; case kValidateWarningFrameContainBedRemap: errorString = "IABFrame contains an BedRemap as sub-element"; break; case kValidateWarningFrameContainObjectZoneDefinition19: errorString = "IABFrame contains an Object zone19 as sub-element"; break; case kValidateWarningFrameContainUndefinedSubElement: errorString = "IABFrame contains an undefined sub-element"; break; case kValidateWarningAuthoringToolInfoMultipleElements: errorString = "IABFrame contains multiple AuthoringToolInfo sub-elements"; break; case kValidateWarningBedDefinitionUndefinedUseCase: errorString = "BedDefinition contains undefined or reserved use case"; break; case kValidateWarningBedDefinitionUndefinedChannelID: errorString = "BedDefinition contains undefined or reserved channel ID"; break; case kValidateWarningBedDefinitionUndefinedAudioDescription: errorString = "BedDefinition contains undefined audio description"; break; case kValidateWarningBedDefinitionContainUnsupportedSubElement: errorString = "BedDefinition contains unsupported sub-element"; break; case kValidateWarningBedDefinitionAlwaysActiveSubElement: errorString = "BedDefinition contains unsupported sub-element"; break; case kValidateWarningBedRemapUndefinedUseCase: errorString = "BedRemap contains undefined or reserved use case"; break; case kValidateWarningBedRemapUndefinedChannelID: errorString = "BedRemap contains undefined or reserved channel ID"; break; case kValidateWarningObjectDefinitionUndefinedUseCase: errorString = "ObjectDefinition contains undefined or reserved use case"; break; case kValidateWarningObjectDefinitionUndefinedAudioDescription: errorString = "ObjectDefinition contains undefined audio description"; break; case kValidateWarningObjectDefinitionMultipleZone19SubElements: errorString = "ObjectDefinition contains multiple zone19 sub-elements"; break; case kValidateWarningObjectDefinitionContainUnsupportedSubElement: errorString = "ObjectDefinition contains unsupported sub-elements"; break; case kValidateWarningObjectDefinitionAlwaysActiveSubElement: errorString = "ObjectDefinition contains an always active sub-element"; break; case kValidateWarningUnreferencedAudioDataDLCElement: errorString = "AudioDataDLC element not referenced by any BedDefinition or ObjectDefinition"; break; case kValidateWarningUnreferencedAudioDataPCMElement: errorString = "AudioDataPCM element not referenced by any BedDefinition or ObjectDefinition"; break; case kValidateErrorDolCinObjectDefinitionZoneGainsNotAPreset: errorString = "ObjectDefinition zone gain is not a DbyCinema preset"; break; case kValidateErrorDolIMFBedDefinitionInvalidChannelID: errorString = "BedDefinition contains invalid channel ID for DbyIMF"; break; case kValidateErrorDolIMFBedDefinitionInvalidGainPrefix: errorString = "BedDefinition contains invalid gain prefix for DbyIMF"; break; case kValidateErrorDolIMFBedDefinitionChannelDecorInfoExistNotZero: errorString = "BedDefinition channel DecorInfoExist must = 0 for DbyIMF"; break; case kValidateErrorDolIMFObjectDefinitionInvalidGainPrefix: errorString = "ObjectDefinition contains invalid gain prefix for DbyIMF"; break; case kValidateErrorDolIMFObjectDefinitionInvalidZoneGainPrefix: errorString = "ObjectDefinition contains invalid zone gain prefix for DbyIMF"; break; case kValidateErrorDolIMFObjectDefinitionInvalidSpreadMode: errorString = "ObjectDefinition contains invalid spread mode for DbyIMF"; break; case kValidateErrorDolIMFObjectDefinitionInvalidDecorPrefix: errorString = "ObjectDefinition contains invalid decorrelation prefix for DbyIMF"; break; case kValidateErrorDolIMFObjectDefinitionSnapTolExistsNotZero: errorString = "ObjectDefinition SnapTolExist must = 0 for DbyIMF"; break; case kValidateErrorDolIMFNotMeetingContinuousAudioSequence: errorString = "Frame sub-element order not meeting continuous audio sequence for DbyIMF"; break; case kValidateErrorDolIMFContinuousAudioSequenceNotPersistent: errorString = "Frame sub-element continuous audio sequence not persistent for DbyIMF"; break; case kValidateWarningDolIMFObjectDefinitionZoneGainsNotAPreset: errorString = "ObjectDefinition zone gain is not a DbyIMF preset"; break; default: errorString = "Unknown err"; } return errorString; } // Error code Map and List functions // returns the item from the list ErrorList* ValidateIABStream::FindListItem(std::string iConstraint, iabError iErrorCode, ErrorList** oLastNode) { ErrorList *element = error_warnings_list_; while (element != nullptr) { *oLastNode = element; if (element->node_.constraint_ == iConstraint && element->node_.errorCode_ == iErrorCode) { return element; } else { element = element->next_; } } return element; } // Adds the summary to json void ValidateIABStream::AddErrorSummaryToReport(SupportedConstraintsSet iConstraintSetId, JSONNODE* iSummaryNode) { ErrorList *element = error_warnings_list_; std::string constraintName = GetConstraintSetString(iConstraintSetId); JSONNODE * errorSummary = json_new(JSON_NODE); json_push_back(errorSummary, json_new_a("Constraint", constraintName.c_str())); JSONNODE * errors = json_new(JSON_NODE); json_set_name(errors, "Errors"); JSONNODE * warnings = json_new(JSON_NODE); json_set_name(warnings, "Warnings"); while (element != nullptr) { // For single constraint validation, group all the errors and warnings. // For all constraints validation, display errors and warnings on its own constraint. if ((element->node_.constraintId_ == iConstraintSetId) || (validationConstraintSets_.size() == 1)) { if (element->node_.errorOccurrences_) { json_push_back(errors, json_new_i(GetValidationErrorString(element->node_.errorCode_).c_str(), element->node_.errorOccurrences_)); } if (element->node_.warningOccurrences_) { json_push_back(warnings, json_new_i(GetValidationErrorString(element->node_.errorCode_).c_str(), element->node_.warningOccurrences_)); } } element = element->next_; } if (json_size(errors)) { json_push_back(errorSummary, errors); } else { json_delete(errors); json_push_back(errorSummary, json_new_i("Errors", 0)); } if (json_size(warnings)) { json_push_back(errorSummary, warnings); } else { json_delete(warnings); json_push_back(errorSummary, json_new_i("Warnings", 0)); } json_push_back(iSummaryNode, errorSummary); } // Increments the error code occurance. void ValidateIABStream::AddEventToList(SupportedConstraintsSet iConstraintSetId, ValidatorEventKind iEventKind, iabError iErrorCode) { ErrorList *lastNode = nullptr; std::string constraintString = GetConstraintSetString(iConstraintSetId); ErrorList *element = FindListItem(constraintString, iErrorCode, &lastNode); if (!element) { element = new ErrorList(); element->node_.constraint_ = constraintString; element->node_.constraintId_ = iConstraintSetId; element->node_.errorCode_ = iErrorCode; element->next_ = nullptr; if (error_warnings_list_ == nullptr) { error_warnings_list_ = element; } if (lastNode) { lastNode->next_ = element; } } if (iEventKind == WarningEvent) { element->node_.warningOccurrences_++; } else if (iEventKind == ErrorEvent) { element->node_.errorOccurrences_++; } }
39.135018
158
0.626054
DTSProAudio
cfeb2bd73d4acbde2b977f44ced847f1ec2305fa
14,039
cpp
C++
Libraries/RobsJuceModules/rosic/filters/rosic_MultiModeFilter.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Libraries/RobsJuceModules/rosic/filters/rosic_MultiModeFilter.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Libraries/RobsJuceModules/rosic/filters/rosic_MultiModeFilter.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
//#include "rosic_MultiModeFilter.h" //using namespace rosic; //------------------------------------------------------------------------------------------------- // construction/destruction: MultiModeFilter::MultiModeFilter() { parameters = new MultiModeFilterParameters; isMaster = true; freqWithKeyAndVel = 1000.0; freqInstantaneous = 1000.0; currentKey = 64.0; currentVel = 64.0; //glideMode = false; //glideTime = 0.1; resetBuffers(); //mode = MultiModeFilterParameters::BYPASS //twoStageBiquad.setMode(FourPoleFilter::LOWPASS_RBJ); //twoStageBiquad.setMode(FourPoleFilter::MORPH_LP_RES_HP); //setMode(MultiModeFilterParameters::BYPASS); //calculateCoefficients(); //markPresetAsClean(); } MultiModeFilter::~MultiModeFilter() { if( isMaster && parameters != NULL ) delete parameters; } //------------------------------------------------------------------------------------------------- // parameter settings: void MultiModeFilter::setSampleRate(double newSampleRate) { ladderFilter.setSampleRate(newSampleRate); twoStageBiquad.setSampleRate(newSampleRate); } void MultiModeFilter::setMode(int newMode) { if( newMode >= MultiModeFilterParameters::BYPASS && newMode < MultiModeFilterParameters::NUM_FILTER_MODES ) { parameters->mode = newMode; if( parameters->mode == MultiModeFilterParameters::BYPASS ) parameters->filterClass = MultiModeFilterParameters::NO_FILTER; else if( parameters->mode == MultiModeFilterParameters::MOOGISH_LOWPASS ) parameters->filterClass = MultiModeFilterParameters::LADDER_FILTER; else { parameters->filterClass = MultiModeFilterParameters::TWO_STAGE_BIQUAD; switch( parameters->mode ) { case MultiModeFilterParameters::LOWPASS_6: twoStageBiquad.setMode(FourPoleFilterParameters::LOWPASS_6); break; case MultiModeFilterParameters::LOWPASS_RBJ: twoStageBiquad.setMode(FourPoleFilterParameters::LOWPASS_12); break; case MultiModeFilterParameters::HIGHPASS_6: twoStageBiquad.setMode(FourPoleFilterParameters::HIGHPASS_6); break; case MultiModeFilterParameters::HIGHPASS_RBJ: twoStageBiquad.setMode(FourPoleFilterParameters::HIGHPASS_12); break; case MultiModeFilterParameters::BANDPASS_RBJ: twoStageBiquad.setMode(FourPoleFilterParameters::BANDPASS_RBJ); break; case MultiModeFilterParameters::BANDREJECT_RBJ: twoStageBiquad.setMode(FourPoleFilterParameters::BANDREJECT_RBJ); break; case MultiModeFilterParameters::PEAK_OR_DIP_RBJ: twoStageBiquad.setMode(FourPoleFilterParameters::PEAK_OR_DIP_RBJ ); break; case MultiModeFilterParameters::LOW_SHELV_1ST: twoStageBiquad.setMode(FourPoleFilterParameters::LOW_SHELV_1ST ); break; case MultiModeFilterParameters::LOW_SHELV_RBJ: twoStageBiquad.setMode(FourPoleFilterParameters::LOW_SHELV_RBJ ); break; case MultiModeFilterParameters::HIGH_SHELV_1ST: twoStageBiquad.setMode(FourPoleFilterParameters::HIGH_SHELV_1ST ); break; case MultiModeFilterParameters::HIGH_SHELV_RBJ: twoStageBiquad.setMode(FourPoleFilterParameters::HIGH_SHELV_RBJ ); break; case MultiModeFilterParameters::ALLPASS_1ST: twoStageBiquad.setMode(FourPoleFilterParameters::ALLPASS_1ST ); break; case MultiModeFilterParameters::ALLPASS_RBJ: twoStageBiquad.setMode(FourPoleFilterParameters::ALLPASS_RBJ ); break; case MultiModeFilterParameters::MORPH_LP_BP_HP: twoStageBiquad.setMode(FourPoleFilterParameters::MORPH_LP_BP_HP); break; case MultiModeFilterParameters::MORPH_LP_PK_HP: twoStageBiquad.setMode(FourPoleFilterParameters::MORPH_LP_PK_HP); break; } } calculateCoefficients(); for(unsigned int s = 0; s < slaves.size(); s++) slaves[s]->setMode(newMode); //markPresetAsDirty(); } else DEBUG_BREAK; // invalid filter mode index } void MultiModeFilter::setFrequencyNominal(double newFrequency) { parameters->freqNominal = newFrequency; updateFreqWithKeyAndVel(); if( isMaster == true ) { setFrequencyInstantaneous(newFrequency, true); for(unsigned int s = 0; s < slaves.size(); s++) slaves[s]->updateFreqWithKeyAndVel(); } //markPresetAsDirty(); /* if( updateCoefficients == true ) { calculateCoefficients(); for(int s=0; s<slaves.size(); s++) slaves[s]->calculateCoefficients(); } */ } void MultiModeFilter::setFrequencyByKey(double newFrequencyByKey) { parameters->freqByKey = newFrequencyByKey; updateFreqWithKeyAndVel(); for(unsigned int s = 0; s < slaves.size(); s++) slaves[s]->updateFreqWithKeyAndVel(); //markPresetAsDirty(); } void MultiModeFilter::setFrequencyByVel(double newFrequencyByVel) { parameters->freqByVel = newFrequencyByVel; updateFreqWithKeyAndVel(); for(unsigned int s = 0; s < slaves.size(); s++) slaves[s]->updateFreqWithKeyAndVel(); //markPresetAsDirty(); } void MultiModeFilter::setKey(double newKey) { currentKey = newKey; updateFreqWithKeyAndVel(); for(unsigned int s = 0; s < slaves.size(); s++) slaves[s]->updateFreqWithKeyAndVel(); } void MultiModeFilter::setKeyAndVel(double newKey, double newVel) { currentKey = newKey; currentVel = newVel; updateFreqWithKeyAndVel(); for(unsigned int s = 0; s < slaves.size(); s++) slaves[s]->updateFreqWithKeyAndVel(); } void MultiModeFilter::setResonance(double newResonance, bool updateCoefficients) { parameters->resonance = newResonance; ladderFilter.setResonance(0.01*parameters->resonance, updateCoefficients); /* twoStageBiquad.setResonance(0.01*parameters->resonance); if( updateCoefficients == true ) twoStageBiquad.updateFilterCoefficients(); */ //markPresetAsDirty(); } void MultiModeFilter::setQ(double newQ, bool updateCoefficients) { twoStageBiquad.setQ(newQ); if( updateCoefficients == true ) twoStageBiquad.updateFilterCoefficients(); //markPresetAsDirty(); } void MultiModeFilter::setGain(double newGain) { twoStageBiquad.setGain(newGain); //markPresetAsDirty(); } void MultiModeFilter::setDrive(double newDrive) { ladderFilter.setDrive(newDrive); //twoStageBiquad.setDrive(newDrive); //markPresetAsDirty(); } void MultiModeFilter::setOrder(int newOrder) { parameters->order = newOrder; //twoStageBiquad.setOrder(newOrder); ladderFilter.setOutputStage(newOrder); //markPresetAsDirty(); } void MultiModeFilter::useTwoStages(bool shouldUseTwoStages) { twoStageBiquad.useTwoStages(shouldUseTwoStages); //markPresetAsDirty(); } void MultiModeFilter::setAllpassFreq(double newAllpassFreq) { ladderFilter.setAllpassFreq(newAllpassFreq); //markPresetAsDirty(); } void MultiModeFilter::setMakeUp(double newMakeUp) { ladderFilter.setMakeUp(newMakeUp, true); //markPresetAsDirty(); } //------------------------------------------------------------------------------------------------- // inquiry: Complex MultiModeFilter::getTransferFunctionAt(Complex z) { ///< \todo switch or ifs return ladderFilter.getTransferFunctionAt(z, true, true, true, ladderFilter.getOutputStage()); } double MultiModeFilter::getMagnitudeAt(double frequency) { switch( parameters->filterClass ) { case MultiModeFilterParameters::LADDER_FILTER: return ladderFilter.getMagnitudeAt(frequency, true, true, true, ladderFilter.getOutputStage()); case MultiModeFilterParameters::TWO_STAGE_BIQUAD: return twoStageBiquad.getMagnitudeAt(frequency); default: return 1.0; } /* if( parameters->mode == BYPASS ) return 1.0; else if( parameters->mode == MOOGISH_LOWPASS ) return ladderFilter.getMagnitudeAt(frequency, true, true, true, ladderFilter.getOutputStage()); else return twoStageBiquad.getMagnitudeAt(frequency); */ } void MultiModeFilter::getMagnitudeResponse(double *frequencies, double *magnitudes, int numBins, bool inDecibels, bool accumulate) { if( parameters->filterClass == MultiModeFilterParameters::NO_FILTER ) { // fill magnitude-array with bypass-rspeonse: int k; if( accumulate == false && inDecibels == true ) { for(k=0; k<numBins; k++) magnitudes[k] = 0.0; } else if( accumulate == false && inDecibels == false ) { for(k=0; k<numBins; k++) magnitudes[k] = 1.0; } return; } /* else if( parameters->mode == MOOGISH_LOWPASS ) ladderFilter.getMagnitudeResponse(frequencies, magnitudes, numBins, inDecibels, accumulate); else twoStageBiquad.getMagnitudeResponse(frequencies, magnitudes, numBins, inDecibels, accumulate); */ switch( parameters->filterClass ) { case MultiModeFilterParameters::LADDER_FILTER: ladderFilter.getMagnitudeResponse(frequencies, magnitudes, numBins, inDecibels, accumulate); break; case MultiModeFilterParameters::TWO_STAGE_BIQUAD: twoStageBiquad.getMagnitudeResponse(frequencies, magnitudes, numBins, inDecibels, accumulate); break; } } int MultiModeFilter::getMode() { return parameters->mode; } double MultiModeFilter::getFrequencyNominal() { return parameters->freqNominal; } double MultiModeFilter::getFrequencyByKey() { return parameters->freqByKey; } double MultiModeFilter::getFrequencyByVel() { return parameters->freqByVel; } double MultiModeFilter::getFrequencyWithKeyAndVel() { return freqWithKeyAndVel; } double MultiModeFilter::getResonance() { return parameters->resonance; } double MultiModeFilter::getQ() { return twoStageBiquad.getQ();; } double MultiModeFilter::getGain() { return twoStageBiquad.getGain(); } double MultiModeFilter::getDrive() { return ladderFilter.getDrive(); } int MultiModeFilter::getOrder() { return parameters->order; } bool MultiModeFilter::usesTwoStages() { return twoStageBiquad.usesTwoStages(); } double MultiModeFilter::getMorph() { return twoStageBiquad.getMorph(); } double MultiModeFilter::getAllpassFreq() { return ladderFilter.getAllpassFreq(); } double MultiModeFilter::getMakeUp() { return ladderFilter.getMakeUp(); } bool MultiModeFilter::currentModeSupportsQ() { if( parameters->mode == MultiModeFilterParameters::LOWPASS_RBJ || parameters->mode == MultiModeFilterParameters::HIGHPASS_RBJ || parameters->mode == MultiModeFilterParameters::BANDPASS_RBJ || parameters->mode == MultiModeFilterParameters::BANDREJECT_RBJ || parameters->mode == MultiModeFilterParameters::ALLPASS_RBJ || parameters->mode == MultiModeFilterParameters::PEAK_OR_DIP_RBJ || parameters->mode == MultiModeFilterParameters::LOW_SHELV_RBJ || parameters->mode == MultiModeFilterParameters::HIGH_SHELV_RBJ || parameters->mode == MultiModeFilterParameters::MORPH_LP_PK_HP ) { return true; } else return false; } bool MultiModeFilter::currentModeSupportsGain() { if( parameters->mode == MultiModeFilterParameters::PEAK_OR_DIP_RBJ || parameters->mode == MultiModeFilterParameters::LOW_SHELV_1ST || parameters->mode == MultiModeFilterParameters::LOW_SHELV_RBJ || parameters->mode == MultiModeFilterParameters::HIGH_SHELV_1ST || parameters->mode == MultiModeFilterParameters::HIGH_SHELV_RBJ ) { return true; } else return false; } bool MultiModeFilter::currentModeSupportsTwoStages() { if( parameters->filterClass == MultiModeFilterParameters::TWO_STAGE_BIQUAD ) return true; else return false; /* if( parameters->mode == MultiModeFilterParameters::LOWPASS_6 || parameters->mode == MultiModeFilterParameters::LOWPASS_RBJ || parameters->mode == MultiModeFilterParameters::HIGHPASS_6 || parameters->mode == MultiModeFilterParameters::HIGHPASS_RBJ || parameters->mode == MultiModeFilterParameters::BANDPASS_RBJ || parameters->mode == MultiModeFilterParameters::BANDREJECT_RBJ || parameters->mode == MultiModeFilterParameters::ALLPASS_1ST || parameters->mode == MultiModeFilterParameters::ALLPASS_RBJ || parameters->mode == MultiModeFilterParameters::MORPH_LP_PK_HP ) { return true; } else return false; */ } //------------------------------------------------------------------------------------------------- // master/slave config: void MultiModeFilter::addSlave(MultiModeFilter* newSlave) { // add the new slave to the vector of slaves: slaves.push_back(newSlave); // delete the original parameter-set of the new slave and redirect it to ours (with some safety // checks): if( newSlave->parameters != NULL && newSlave->parameters != this->parameters ) { delete newSlave->parameters; newSlave->parameters = this->parameters; } else { DEBUG_BREAK; // the object to be added as slave did not contain a valid parameter-pointer - maybe it has // been already added as slave to another master? } // add the embedded filters in the newSlave as slaves to the respective embedded filter here in // this instance: ladderFilter.addSlave( &(newSlave->ladderFilter) ); twoStageBiquad.addSlave( &(newSlave->twoStageBiquad) ); // set the isMaster-flag of the new slave to false: newSlave->isMaster = false; // this flag will prevent the destructor of the slave from trying to delete the parameter-set // which is now shared - only masters delete their parameter-set on destruction } //------------------------------------------------------------------------------------------------- // others: void MultiModeFilter::updateFreqWithKeyAndVel() { freqWithKeyAndVel = parameters->freqNominal; freqWithKeyAndVel *= pow(2.0, (0.01*parameters->freqByKey/12.0) * (currentKey-64.0) ); freqWithKeyAndVel *= pow(2.0, (0.01*parameters->freqByVel/63.0) * (currentVel-64.0) ); } void MultiModeFilter::resetBuffers() { ladderFilter.reset(); twoStageBiquad.reset(); }
29.247917
99
0.697557
RobinSchmidt
cfed7ff24ed2cca2f5564f91eadf82b54ff46306
3,577
cpp
C++
Classes/Scenes/LogoScene.cpp
irfanf/Galvighas3D
b180b18f840efbeac9c5b84b9901f30d7889e123
[ "MIT" ]
null
null
null
Classes/Scenes/LogoScene.cpp
irfanf/Galvighas3D
b180b18f840efbeac9c5b84b9901f30d7889e123
[ "MIT" ]
null
null
null
Classes/Scenes/LogoScene.cpp
irfanf/Galvighas3D
b180b18f840efbeac9c5b84b9901f30d7889e123
[ "MIT" ]
null
null
null
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ //! //! IRFAN FAHMI RAMADHAN //! //! 2016/5/24 //! //! LogoScene.cpp //! //! Copyright ©2016 IrGame All Right Reserved //_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ //--------------------------------------------------------------------- #include "LogoScene.h" #include "ui/CocosGUI.h" #include "TitleScene.h" //--------------------------------------------------------------------- USING_NS_CC; //--------------------------------------------------------------------- //------------------------------------ //@! クラス作成 //------------------------------------ Scene* LogoScene::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = LogoScene::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } //------------------------------------ //@! クラスの初期化 //------------------------------------ bool LogoScene::init() { ////////////////////////////// // 1. super init first if (!Layer::init()) { return false; } //タッチしたら移動 auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = CC_CALLBACK_2(LogoScene::onTouchBegan, this); this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this); Size visibleSize = Director::getInstance()->getVisibleSize(); //----------------------------------------------------------------- //ロゴを出す auto logo_bg = Sprite::create("Logo/Logo_bg.png"); logo_bg->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2)); logo_bg->setScale(0.0001); this->addChild(logo_bg); //ロゴ名を出す auto logo_tag = Sprite::create("Logo/Logo_name.png"); logo_tag->setPosition(Vec2(-1000.0f, visibleSize.width / 2)); this->addChild(logo_tag); //ロゴのパーティクル CCParticleSystemQuad* logo_particle = CCParticleSystemQuad::create("Logo/particleLogo2.plist"); logo_particle->resetSystem(); logo_particle->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2)); logo_particle->setScale(1.5); this->addChild(logo_particle); //ロゴのアクション DelayTime* delay = DelayTime::create(1.5f); RotateBy* rot = RotateBy::create(1.5f, 360); ScaleTo* scale = ScaleTo::create(1.0f,1); Spawn* spawn = Spawn::create(rot, scale, nullptr); Sequence* seq = Sequence::create(delay, spawn, nullptr); logo_bg->runAction(seq); //ロゴ名のアクション MoveTo* move = MoveTo::create(2.0f, Vec2(visibleSize.width / 2, visibleSize.height / 2)); Sequence* seq2 = Sequence::create(delay, move, nullptr); logo_tag->runAction(seq2); //----------------------------------------------------------------- //シーン生成されてから4秒後に"ChangeScene"が呼ばれる this->scheduleOnce(schedule_selector(LogoScene::changeScene), 5.0f); //----------------------------------------------------------------- return true; } //------------------------------------ //@! 時間たったら,シーン移動する //@! 時間 //------------------------------------ void LogoScene::changeScene(float dt) { //移動先シーンの作成 auto scene = TitleScene::createScene(); scene = TitleScene::createScene(); auto transition = TransitionFade::create(3.0f, scene); Director::getInstance()->replaceScene(transition); } //------------------------------------ //@! 時間たったら,シーン移動する //@! 時間 //------------------------------------ bool LogoScene::onTouchBegan(Touch* touch, Event* unused_event) { //移動先シーンの作成 auto scene = TitleScene::createScene(); auto transition = TransitionFade::create(1.0f, scene); Director::getInstance()->replaceScene(transition); this->unscheduleAllSelectors(); return false; }
27.945313
96
0.55745
irfanf
cff5ef77e14bec558baaf5c6901fa4a20001e9ef
785
hpp
C++
server/memory_resource_manager.hpp
photonmaster/scymnus
bcbf580091a730c63e15b67b6331705a281ba20b
[ "MIT" ]
7
2021-08-19T01:11:21.000Z
2021-08-31T15:25:51.000Z
server/memory_resource_manager.hpp
photonmaster/scymnus
bcbf580091a730c63e15b67b6331705a281ba20b
[ "MIT" ]
null
null
null
server/memory_resource_manager.hpp
photonmaster/scymnus
bcbf580091a730c63e15b67b6331705a281ba20b
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> #include <cassert> #include <cstddef> #include <iostream> #include <list> #include <memory_resource> #include <thread> namespace scymnus { class memory_resource_manager { public: static memory_resource_manager &instance() { thread_local memory_resource_manager manager; return manager; } auto pool() { // return std::pmr::new_delete_resource(); return &pool_; } private: std::pmr::unsynchronized_pool_resource pool_{}; //{std::data(buffer_), std::size(buffer_)}; memory_resource_manager() = default; memory_resource_manager(const memory_resource_manager &) = delete; memory_resource_manager &operator=(const memory_resource_manager &) = delete; }; } // namespace scymnus
21.805556
81
0.699363
photonmaster
cff603a933870fbf2c96e5292f1ec7e006175709
326
cpp
C++
1183/1681782_AC_15MS_124K.cpp
vandreas19/POJ_sol
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
18
2017-08-14T07:34:42.000Z
2022-01-29T14:20:29.000Z
1183/1681782_AC_15MS_124K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
null
null
null
1183/1681782_AC_15MS_124K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
14
2016-12-21T23:37:22.000Z
2021-07-24T09:38:57.000Z
#include<iostream> using namespace std; void main() { unsigned long iA,iB,iSum=0; cin>>iA; for(iB=iA+1;iB<=iA*2;iB+=1) if(!((iA*iB+1)%(iB-iA)) && (iB+((iA*iB+1)/(iB-iA))<iSum || !iSum)) { iSum=iB+((iA*iB+1)/(iB-iA)); //cout<<iB<<"+"<<((iA*iB+1)/(iB-iA))<<"="<<iSum<<endl; } cout<<iSum<<endl; }
20.375
69
0.496933
vandreas19
cff6b61bd9a794f33363be172a9586b242d71d6e
8,432
hpp
C++
include/g6/http/message.hpp
Garcia6l20/g6-web
6e9a1f9d85f26a977407d4c895f357e5f045efb9
[ "MIT" ]
3
2021-05-16T11:37:59.000Z
2022-01-30T13:52:59.000Z
include/g6/http/message.hpp
Garcia6l20/g6-web
6e9a1f9d85f26a977407d4c895f357e5f045efb9
[ "MIT" ]
null
null
null
include/g6/http/message.hpp
Garcia6l20/g6-web
6e9a1f9d85f26a977407d4c895f357e5f045efb9
[ "MIT" ]
1
2021-11-06T12:36:37.000Z
2021-11-06T12:36:37.000Z
/** * @file cppcoro/http/htt_message.hpp * @author Garcia Sylvain <garcia.6l20@gmail.com> */ #pragma once #include <cppcoro/http/details/static_parser_handler.hpp> #include <cppcoro/detail/is_specialization.hpp> #include <fmt/format.h> #include <span> namespace cppcoro::http { namespace detail { enum { max_body_size = 1024 }; struct base_message { base_message() = default; explicit base_message(http::headers&& headers) : headers{ std::forward<http::headers>(headers) } { } base_message(base_message const& other) = delete; base_message& operator=(base_message const& other) = delete; base_message(base_message&& other) = default; base_message& operator=(base_message&& other) = default; std::optional<std::reference_wrapper<std::string>> header(const std::string& key) noexcept { if (auto it = headers.find(key); it != headers.end()) { return it->second; } return {}; } http::headers headers; byte_span body; // virtual bool is_chunked() = 0; // virtual std::string build_header() = 0; // virtual task<std::span<std::byte, std::dynamic_extent>> read_body(size_t //max_size = max_body_size) = 0; virtual task<size_t> write_body(std::span<std::byte, //std::dynamic_extent> data) = 0; }; struct base_request : base_message { static constexpr bool is_request = true; static constexpr bool is_response = false; using base_message::base_message; base_request(base_request&& other) = default; base_request& operator=(base_request&& other) = default; base_request(http::method method, std::string&& path, http::headers&& headers = {}) : base_message{ std::forward<http::headers>(headers) } , method{ method } , path{ std::forward<std::string>(path) } { } http::method method; std::string path; [[nodiscard]] auto method_str() const { return http_method_str(static_cast<detail::http_method>(method)); } std::string to_string() const { return fmt::format("{} {}", method_str(), path); } }; struct base_response : base_message { static constexpr bool is_response = true; static constexpr bool is_request = false; using base_message::base_message; base_response(base_response&& other) = default; base_response& operator=(base_response&& other) = default; base_response(http::status status, http::headers&& headers = {}) : base_message{ std::forward<http::headers>(headers) } , status{ status } { } http::status status; [[nodiscard]] auto status_str() const { return http_status_str(static_cast<detail::http_status>(status)); } std::string to_string() const { return status_str(); } }; template<bool _is_response, is_body BodyT> struct abstract_message : std::conditional_t<_is_response, base_response, base_request> { using base_type = std::conditional_t<_is_response, base_response, base_request>; static constexpr bool is_response = _is_response; static constexpr bool is_request = !_is_response; using parser_type = http::detail::static_parser_handler<is_request>; using base_type::base_type; std::optional<async_generator<std::string_view>> chunk_generator_; std::optional<async_generator<std::string_view>::iterator> chunk_generator_it_; abstract_message(abstract_message::parser_type& parser) : base_response{ parser.template status_code_or_method<is_request>(), std::move(parser.headers_), std::move(parser.url()), std::move(parser.header_) } { } abstract_message( auto status_or_method, http::headers&& headers = {}) : base_response{ status_or_method, std::forward<http::headers>(headers) } { } abstract_message( http::method method, std::string&& path, http::headers&& headers = {}) requires(is_request) : base_request{ method, std::forward<std::string>(path), std::forward<http::headers>(headers) } { } auto& operator=(parser_type& parser) noexcept requires(is_request) { this->method = parser.method(); this->path = std::move(parser.url()); this->headers = std::move(parser.headers_); return *this; } // explicit abstract_message(base_type &&base) noexcept : // base_type(std::move(base)) {} abstract_message& operator=(base_type // &&base) noexcept { // static_cast<base_type>(*this) = std::move(base); // } // // bool is_chunked() final // { // if constexpr (ro_chunked_body<body_type> or wo_chunked_body<body_type>) // { // return true; // } // else // { // return false; // } // } // task<std::span<std::byte, std::dynamic_extent>> read_body(size_t max_size = //max_body_size) final // { // if constexpr (ro_basic_body<BodyT>) // { // co_return std::span{ body_access }; // } // else if constexpr (ro_chunked_body<BodyT>) // { // if (not chunk_generator_) // { // chunk_generator_ = body_access.read(max_size); // chunk_generator_it_ = co_await chunk_generator_->begin(); // if (*chunk_generator_it_ != chunk_generator_->end()) // { // co_return** chunk_generator_it_; // } // } // else if ( // chunk_generator_it_ and // co_await ++*chunk_generator_it_ != chunk_generator_->end()) // { // co_return** chunk_generator_it_; // } // co_return {}; // } // } // task<size_t> write_body(std::span<std::byte, std::dynamic_extent> data) //final // { // if constexpr (wo_basic_body<BodyT>) // { // auto size = // std::min(data.size(), //std::as_writable_bytes(this->body_access).size()); std::memmove( // std::as_writable_bytes(this->body_access).data(), data.data(), //size); co_return size; // } // else if constexpr (wo_chunked_body<BodyT>) // { // co_return co_await this->body_access.write(data); // } // } inline std::string build_header() { for (auto& [k, v] : this->headers) { spdlog::debug("- {}: {}", k, v); } std::string output = _header_base(); auto write_header = [&output](const std::string& field, const std::string& value) { output += fmt::format("{}: {}\r\n", field, value); }; if constexpr (ro_basic_body<BodyT>) { auto sz = this->body.size(); if (auto node = this->headers.extract("Content-Length"); !node.empty()) { node.mapped() = std::to_string(sz); this->headers.insert(std::move(node)); } else { this->headers.emplace("Content-Length", std::to_string(sz)); } } else if constexpr (ro_chunked_body<BodyT>) { this->headers.emplace("Transfer-Encoding", "chunked"); } for (auto& [field, value] : this->headers) { write_header(field, value); } output += "\r\n"; return output; } private: inline auto _header_base() { if constexpr (is_response) { return fmt::format( "HTTP/1.1 {} {}\r\n" "UserAgent: cppcoro-http/0.0\r\n", int(this->status), http_status_str(this->status)); } else { return fmt::format( "{} {} HTTP/1.1\r\n" "UserAgent: cppcoro-http/0.0\r\n", this->method_str(), this->path); } } }; template<bool response, typename T> struct abstract_span_message : detail::abstract_message<response, T> { abstract_span_message(auto status_or_method, T span, http::headers &&headers = {}) noexcept : detail::abstract_message<response, T>{status_or_method} { this->body = std::as_writable_bytes(span); } }; } // namespace detail template<detail::is_body BodyT> using abstract_request = detail::abstract_message<false, BodyT>; template<detail::is_body BodyT> using abstract_response = detail::abstract_message<true, BodyT>; template<detail::is_body BodyT> using abstract_request = detail::abstract_message<false, BodyT>; struct request_parser : detail::static_parser_handler<true> { using detail::static_parser_handler<true>::static_parser_handler; }; struct response_parser : detail::static_parser_handler<false> { using detail::static_parser_handler<false>::static_parser_handler; }; } // namespace cppcoro::http
27.736842
103
0.631641
Garcia6l20
cfff77bf78c067378423efa49bf841301e9bf67d
1,587
hpp
C++
include/termox/widget/detail/pipe_utility.hpp
a-n-t-h-o-n-y/MCurses
c9184a0fefbdc4eb9a044f815ee2270e6b8f202c
[ "MIT" ]
284
2017-11-07T10:06:48.000Z
2021-01-12T15:32:51.000Z
include/termox/widget/detail/pipe_utility.hpp
a-n-t-h-o-n-y/MCurses
c9184a0fefbdc4eb9a044f815ee2270e6b8f202c
[ "MIT" ]
38
2018-01-14T12:34:54.000Z
2020-09-26T15:32:43.000Z
include/termox/widget/detail/pipe_utility.hpp
a-n-t-h-o-n-y/MCurses
c9184a0fefbdc4eb9a044f815ee2270e6b8f202c
[ "MIT" ]
31
2017-11-30T11:22:21.000Z
2020-11-03T05:27:47.000Z
#ifndef TERMOX_WIDGET_DETAIL_PIPE_UTILITY_HPP #define TERMOX_WIDGET_DETAIL_PIPE_UTILITY_HPP #include <memory> #include <type_traits> #include <termox/widget/widget.hpp> namespace ox::pipe::detail { /// Used to call operator| overload to create a new Range from filter predicate template <typename Predicate> class Filter_predicate { public: explicit Filter_predicate(Predicate p) : predicate{p} {} public: Predicate predicate; }; /// Used to call operator| overload to create a new Range from filter predicate template <typename W> class Dynamic_filter_predicate { public: using Widget_t = W; }; template <typename T> struct is_widget_ptr : std::false_type {}; template <typename X> struct is_widget_ptr<std::unique_ptr<X>> : std::is_base_of<ox::Widget, X> {}; /// True if T is a std::unique_ptr<> to a ox::Widget type. template <typename T> constexpr bool is_widget_ptr_v = is_widget_ptr<T>::value; /// True if T is a Widget type. template <typename T> constexpr bool is_widget_v = std::is_base_of_v<Widget, std::decay_t<T>>; /// True if T is a Widget type or a Widget pointer. template <typename T> constexpr bool is_widget_or_wptr = is_widget_v<T> || is_widget_ptr_v<std::decay_t<T>>; } // namespace ox::pipe::detail namespace ox { /// Return *x if x is a unique_ptr to a Widget type, otherwise x. template <typename T> [[nodiscard]] constexpr auto get(T& x) -> auto& { if constexpr (::ox::pipe::detail::is_widget_ptr_v<T>) return *x; else return x; } } // namespace ox #endif // TERMOX_WIDGET_DETAIL_PIPE_UTILITY_HPP
25.596774
79
0.724008
a-n-t-h-o-n-y
3205b4dd8cffd38079a04954c2bd51830e0387cb
1,325
hpp
C++
src/endpoint.hpp
pcdangio/ros-driver_tcpip
7e2aa0d727cd3a86ec5ddc7f3495a6f461e55702
[ "MIT" ]
2
2021-03-23T19:15:55.000Z
2021-04-04T13:55:53.000Z
src/endpoint.hpp
pcdangio/ros-driver_tcpip
7e2aa0d727cd3a86ec5ddc7f3495a6f461e55702
[ "MIT" ]
1
2019-07-30T01:36:43.000Z
2019-07-31T23:52:49.000Z
src/endpoint.hpp
pcdangio/ros-driver_modem
7e2aa0d727cd3a86ec5ddc7f3495a6f461e55702
[ "MIT" ]
1
2022-03-16T03:46:55.000Z
2022-03-16T03:46:55.000Z
/// \file endpoint.hpp /// \brief Defines endpoint conversion functions. #ifndef DRIVER_TCPIP___ENDPOINT_H #define DRIVER_TCPIP___ENDPOINT_H #include <driver_tcpip_msgs/endpoint.h> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/ip/udp.hpp> namespace driver_tcpip { namespace endpoint { // TCP /// \brief Converts a ROS endpoint to an ASIO TCP endpoint. /// \param endpoint_ros The ROS endpoint to convert. /// \returns The converted ASIO TCP endpoint. boost::asio::ip::tcp::endpoint to_asio_tcp(const driver_tcpip_msgs::endpoint& endpoint_ros); /// \brief Converts an ASIO TCP endpoint to a ROS endpoint. /// \param endpoint_asio The ASIO TCP endpoint to convert. /// \returns The converted ROS endpoint. driver_tcpip_msgs::endpoint to_ros(const boost::asio::ip::tcp::endpoint& endpoint_asio); // UDP /// \brief Converts a ROS endpoint to an ASIO UDP endpoint. /// \param endpoint_ros The ROS endpoint to convert. /// \returns The converted ASIO UDP endpoint. boost::asio::ip::udp::endpoint to_asio_udp(const driver_tcpip_msgs::endpoint& endpoint_ros); /// \brief Converts an ASIO UDP endpoint to a ROS endpoint. /// \param endpoint_asio The ASIO UDP endpoint to convert. /// \returns The converted ROS endpoint. driver_tcpip_msgs::endpoint to_ros(const boost::asio::ip::udp::endpoint& endpoint_asio); }} #endif
36.805556
92
0.763774
pcdangio
3206be9b81b9a1116c7abb34a145fd6196ca4b28
6,678
cpp
C++
dev/Code/Tools/AssetBundler/tests/UtilsTests.cpp
brianherrera/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Code/Tools/AssetBundler/tests/UtilsTests.cpp
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Code/Tools/AssetBundler/tests/UtilsTests.cpp
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <AzFramework/API/ApplicationAPI.h> #include <source/utils/utils.h> #include <AzCore/UnitTest/TestTypes.h> #include <AzFramework/StringFunc/StringFunc.h> #include <Tests/Utils/Utils.h> #include <AzFramework/IO/LocalFileIO.h> namespace AssetBundler { class MockUtilsTest : public UnitTest::ScopedAllocatorSetupFixture , public AzFramework::ApplicationRequests::Bus::Handler { public: void SetUp() override { ScopedAllocatorSetupFixture::SetUp(); AzFramework::ApplicationRequests::Bus::Handler::BusConnect(); m_localFileIO = aznew AZ::IO::LocalFileIO(); m_priorFileIO = AZ::IO::FileIOBase::GetInstance(); // we need to set it to nullptr first because otherwise the // underneath code assumes that we might be leaking the previous instance AZ::IO::FileIOBase::SetInstance(nullptr); AZ::IO::FileIOBase::SetInstance(m_localFileIO); m_tempDir = new UnitTest::ScopedTemporaryDirectory(); } void TearDown() override { delete m_tempDir; AZ::IO::FileIOBase::SetInstance(nullptr); delete m_localFileIO; AZ::IO::FileIOBase::SetInstance(m_priorFileIO); AzFramework::ApplicationRequests::Bus::Handler::BusDisconnect(); ScopedAllocatorSetupFixture::TearDown(); } // AzFramework::ApplicationRequests::Bus::Handler interface void NormalizePath(AZStd::string& /*path*/) override {} void NormalizePathKeepCase(AZStd::string& /*path*/) override {} void CalculateBranchTokenForAppRoot(AZStd::string& /*token*/) const override {} void QueryApplicationType(AzFramework::ApplicationTypeQuery& /*appType*/) const override {} const char* GetAppRoot() const override { return m_tempDir->GetDirectory(); } AZ::IO::FileIOBase* m_priorFileIO = nullptr; AZ::IO::FileIOBase* m_localFileIO = nullptr; UnitTest::ScopedTemporaryDirectory* m_tempDir = nullptr; }; TEST_F(MockUtilsTest, TestFilePath_StartsWithAFileSeparator_Valid) { AZStd::string relFilePath = "Foo/foo.xml"; AzFramework::StringFunc::Prepend(relFilePath, AZ_CORRECT_FILESYSTEM_SEPARATOR); AZStd::string absoluteFilePath; #if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS AZStd::string driveString; AzFramework::StringFunc::Path::GetDrive(GetAppRoot(), driveString); AzFramework::StringFunc::Path::ConstructFull(driveString.c_str(), relFilePath.c_str(), absoluteFilePath, true); #else absoluteFilePath = relFilePath; #endif FilePath filePath(relFilePath); EXPECT_STREQ(filePath.AbsolutePath().c_str(), absoluteFilePath.c_str()); } TEST_F(MockUtilsTest, TestFilePath_RelativePath_Valid) { AZStd::string relFilePath = "Foo\\foo.xml"; AZStd::string absoluteFilePath; AzFramework::StringFunc::Path::ConstructFull(GetAppRoot(), relFilePath.c_str(), absoluteFilePath, true); FilePath filePath(relFilePath); EXPECT_EQ(filePath.AbsolutePath(), absoluteFilePath); } TEST_F(MockUtilsTest, TestFilePath_CasingMismatch_Error_valid) { AZStd::string relFilePath = "Foo\\Foo.xml"; AZStd::string wrongCaseRelFilePath = "Foo\\foo.xml"; AZStd::string correctAbsoluteFilePath; AZStd::string wrongCaseAbsoluteFilePath; AzFramework::StringFunc::Path::ConstructFull(GetAppRoot(), relFilePath.c_str(), correctAbsoluteFilePath, true); AzFramework::StringFunc::Path::ConstructFull(GetAppRoot(), wrongCaseRelFilePath.c_str(), wrongCaseAbsoluteFilePath, true); AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; AZ::IO::FileIOBase::GetInstance()->Open(correctAbsoluteFilePath.c_str(), AZ::IO::OpenMode::ModeWrite | AZ::IO::OpenMode::ModeCreatePath, fileHandle); FilePath filePath(wrongCaseAbsoluteFilePath, true, false); EXPECT_FALSE(filePath.IsValid()); EXPECT_TRUE(filePath.ErrorString().find("File case mismatch") != AZStd::string::npos); } TEST_F(MockUtilsTest, TestFilePath_NoFileExists_NoError_valid) { AZStd::string relFilePath = "Foo\\Foo.xml"; AZStd::string absoluteFilePath; AzFramework::StringFunc::Path::ConstructFull(GetAppRoot(), relFilePath.c_str(), absoluteFilePath, true); FilePath filePath(absoluteFilePath, true, false); EXPECT_TRUE(filePath.IsValid()); EXPECT_TRUE(filePath.ErrorString().empty()); } TEST_F(MockUtilsTest, TestFilePath_CasingMismatch_Ignore_Filecase_valid) { AZStd::string relFilePath = "Foo\\Foo.xml"; AZStd::string wrongCaseRelFilePath = "Foo\\foo.xml"; AZStd::string correctAbsoluteFilePath; AZStd::string wrongCaseAbsoluteFilePath; AzFramework::StringFunc::Path::ConstructFull(GetAppRoot(), relFilePath.c_str(), correctAbsoluteFilePath, true); AzFramework::StringFunc::Path::ConstructFull(GetAppRoot(), wrongCaseRelFilePath.c_str(), wrongCaseAbsoluteFilePath, true); AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; AZ::IO::FileIOBase::GetInstance()->Open(correctAbsoluteFilePath.c_str(), AZ::IO::OpenMode::ModeWrite | AZ::IO::OpenMode::ModeCreatePath, fileHandle); FilePath filePath(wrongCaseAbsoluteFilePath, true, true); EXPECT_TRUE(filePath.IsValid()); EXPECT_STREQ(filePath.AbsolutePath().c_str(), correctAbsoluteFilePath.c_str()); } TEST_F(MockUtilsTest, LooksLikeWildcardPattern_IsWildcardPattern_ExpectTrue) { EXPECT_TRUE(LooksLikeWildcardPattern("*")); EXPECT_TRUE(LooksLikeWildcardPattern("?")); EXPECT_TRUE(LooksLikeWildcardPattern("*/*")); EXPECT_TRUE(LooksLikeWildcardPattern("*/test?/*.xml")); } TEST_F(MockUtilsTest, LooksLikeWildcardPattern_IsNotWildcardPattern_ExpectFalse) { EXPECT_FALSE(LooksLikeWildcardPattern("")); EXPECT_FALSE(LooksLikeWildcardPattern("test")); EXPECT_FALSE(LooksLikeWildcardPattern("test/path.xml")); } }
44.818792
157
0.696316
brianherrera
3209541adc64390d9604cb4e1c314447a6d9c68d
60
hh
C++
RAVL2/MSVC/include/Ravl/HEMeshBaseEdge.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/MSVC/include/Ravl/HEMeshBaseEdge.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/MSVC/include/Ravl/HEMeshBaseEdge.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
#include "../.././Core/Container/Graph/HEMeshBaseEdge.hh"
15
57
0.683333
isuhao
32127331669f0d118c8f3c2d68bfffd83c3d9cff
13,169
cpp
C++
src/dogfood/output/text_modifier_test.cpp
lsilvest/crpcut
e9d694fb04599b72ebdcf6fea7d6ad598807ff41
[ "BSD-2-Clause" ]
1
2019-04-09T12:48:41.000Z
2019-04-09T12:48:41.000Z
src/dogfood/output/text_modifier_test.cpp
lsilvest/crpcut
e9d694fb04599b72ebdcf6fea7d6ad598807ff41
[ "BSD-2-Clause" ]
2
2020-05-06T16:22:07.000Z
2020-05-07T04:02:41.000Z
src/dogfood/output/text_modifier_test.cpp
lsilvest/crpcut
e9d694fb04599b72ebdcf6fea7d6ad598807ff41
[ "BSD-2-Clause" ]
1
2019-04-10T12:47:11.000Z
2019-04-10T12:47:11.000Z
/* * Copyright 2012 Bjorn Fahller <bjorn@fahller.se> * All rights reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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 <trompeloeil.hpp> #include <crpcut.hpp> #include "../../output/writer.hpp" #include "../../output/buffer.hpp" #include "../../output/text_modifier.hpp" #include <sstream> TESTSUITE(output) { using trompeloeil::_; TESTSUITE(text_modifier) { class test_buffer : public crpcut::output::buffer { public: typedef std::pair<const char*, std::size_t> buff; MAKE_CONST_MOCK0(get_buffer, buff()); MAKE_MOCK0(advance, void()); MAKE_MOCK2(write, ssize_t(const char*, std::size_t)); MAKE_CONST_MOCK0(is_empty, bool()); }; using crpcut::output::text_modifier; TEST(nullstring_does_nothing) { text_modifier obj(0); std::ostringstream os; obj.write_to(os, text_modifier::NORMAL); ASSERT_TRUE(os.str() == ""); obj.write_to(os, text_modifier::PASSED); ASSERT_TRUE(os.str() == ""); obj.write_to(os, text_modifier::FAILED); ASSERT_TRUE(os.str() == ""); obj.write_to(os, text_modifier::NCFAILED); ASSERT_TRUE(os.str() == ""); obj.write_to(os, text_modifier::NCPASSED); ASSERT_TRUE(os.str() == ""); obj.write_to(os, text_modifier::BLOCKED); ASSERT_TRUE(os.str() == ""); obj.write_to(os, text_modifier::PASSED_SUM); ASSERT_TRUE(os.str() == ""); obj.write_to(os, text_modifier::FAILED_SUM); ASSERT_TRUE(os.str() == ""); obj.write_to(os, text_modifier::NCPASSED_SUM); ASSERT_TRUE(os.str() == ""); obj.write_to(os, text_modifier::NCFAILED_SUM); ASSERT_TRUE(os.str() == ""); obj.write_to(os, text_modifier::BLOCKED_SUM); ASSERT_TRUE(os.str() == ""); test_buffer buff; FORBID_CALL(buff, write(_,_)); crpcut::output::writer w(buff, "UTF-8", "--illegal--"); obj.write_to(w, text_modifier::NORMAL); obj.write_to(w, text_modifier::PASSED); obj.write_to(w, text_modifier::FAILED); obj.write_to(w, text_modifier::NCFAILED); obj.write_to(w, text_modifier::NCPASSED); obj.write_to(w, text_modifier::BLOCKED); obj.write_to(w, text_modifier::PASSED_SUM); obj.write_to(w, text_modifier::FAILED_SUM); obj.write_to(w, text_modifier::NCPASSED_SUM); obj.write_to(w, text_modifier::NCFAILED_SUM); obj.write_to(w, text_modifier::BLOCKED_SUM); } class fix { protected: fix() : writer(buff, "UTF-8", "--illegal--") {} test_buffer buff; crpcut::output::writer writer; trompeloeil::sequence seq; }; TEST(set_values_are_honoured, fix) { static const char config[] = " 0" " PASSED=1" " FAILED=2" " NCFAILED=3" " NCPASSED=4" " BLOCKED=5" " PASSED_SUM=6" " FAILED_SUM=7" " NCPASSED_SUM=8" " NCFAILED_SUM=9" " BLOCKED_SUM=10" " "; text_modifier modifier(config); REQUIRE_CALL(buff, write(_,1U)).WITH(*_1=='0').IN_SEQUENCE(seq).RETURN(ssize_t(_2)); REQUIRE_CALL(buff, write(_,1U)).WITH(*_1=='1').IN_SEQUENCE(seq).RETURN(ssize_t(_2)); REQUIRE_CALL(buff, write(_,1U)).WITH(*_1=='2').IN_SEQUENCE(seq).RETURN(ssize_t(_2)); REQUIRE_CALL(buff, write(_,1U)).WITH(*_1=='3').IN_SEQUENCE(seq).RETURN(ssize_t(_2)); REQUIRE_CALL(buff, write(_,1U)).WITH(*_1=='4').IN_SEQUENCE(seq).RETURN(ssize_t(_2)); REQUIRE_CALL(buff, write(_,1U)).WITH(*_1=='5').IN_SEQUENCE(seq).RETURN(ssize_t(_2)); REQUIRE_CALL(buff, write(_,1U)).WITH(*_1=='6').IN_SEQUENCE(seq).RETURN(ssize_t(_2)); REQUIRE_CALL(buff, write(_,1U)).WITH(*_1=='7').IN_SEQUENCE(seq).RETURN(ssize_t(_2)); REQUIRE_CALL(buff, write(_,1U)).WITH(*_1=='8').IN_SEQUENCE(seq).RETURN(ssize_t(_2)); REQUIRE_CALL(buff, write(_,1U)).WITH(*_1=='9').IN_SEQUENCE(seq).RETURN(ssize_t(_2)); REQUIRE_CALL(buff, write(_,2U)) .WITH(std::string(_1,_2) == "10") .IN_SEQUENCE(seq) .RETURN(ssize_t(_2)); modifier.write_to(writer, text_modifier::NORMAL); modifier.write_to(writer, text_modifier::PASSED); modifier.write_to(writer, text_modifier::FAILED); modifier.write_to(writer, text_modifier::NCFAILED); modifier.write_to(writer, text_modifier::NCPASSED); modifier.write_to(writer, text_modifier::BLOCKED); modifier.write_to(writer, text_modifier::PASSED_SUM); modifier.write_to(writer, text_modifier::FAILED_SUM); modifier.write_to(writer, text_modifier::NCPASSED_SUM); modifier.write_to(writer, text_modifier::NCFAILED_SUM); modifier.write_to(writer, text_modifier::BLOCKED_SUM); } TEST(failed_propagates, fix) { static const char config[] = " 0" " FAILED=F" " "; text_modifier modifier(config); { REQUIRE_CALL(buff, write(_,_)) .WITH(std::string(_1,_2) == "F") .TIMES(4) .RETURN(ssize_t(_2)); modifier.write_to(writer, text_modifier::FAILED); modifier.write_to(writer, text_modifier::NCFAILED); modifier.write_to(writer, text_modifier::FAILED_SUM); modifier.write_to(writer, text_modifier::NCFAILED_SUM); } { REQUIRE_CALL(buff, write(_,_)) .WITH(std::string(_1,_2) == "0") .RETURN(ssize_t(_2)); modifier.write_to(writer, text_modifier::NORMAL); modifier.write_to(writer, text_modifier::PASSED); modifier.write_to(writer, text_modifier::NCPASSED); modifier.write_to(writer, text_modifier::BLOCKED); modifier.write_to(writer, text_modifier::PASSED_SUM); modifier.write_to(writer, text_modifier::NCPASSED_SUM); modifier.write_to(writer, text_modifier::BLOCKED_SUM); } } TEST(ncfailed_propagates, fix) { static const char config[] = " 0" " NCFAILED=F" " "; text_modifier modifier(config); { REQUIRE_CALL(buff, write(_,_)) .WITH(std::string(_1,_2) == "F") .TIMES(2) .RETURN(ssize_t(_2)); modifier.write_to(writer, text_modifier::NCFAILED); modifier.write_to(writer, text_modifier::NCFAILED_SUM); } { REQUIRE_CALL(buff, write(_,_)) .WITH(std::string(_1,_2) == "0") .RETURN(ssize_t(_2)); modifier.write_to(writer, text_modifier::NORMAL); } modifier.write_to(writer, text_modifier::FAILED_SUM); modifier.write_to(writer, text_modifier::FAILED); modifier.write_to(writer, text_modifier::PASSED); modifier.write_to(writer, text_modifier::NCPASSED); modifier.write_to(writer, text_modifier::BLOCKED); modifier.write_to(writer, text_modifier::PASSED_SUM); modifier.write_to(writer, text_modifier::NCPASSED_SUM); modifier.write_to(writer, text_modifier::BLOCKED_SUM); } TEST(ncpassed_propagates, fix) { static const char config[] = " 0" " NCPASSED=P" " "; text_modifier modifier(config); { REQUIRE_CALL(buff, write(_,_)) .WITH(std::string(_1,_2) == "P") .TIMES(2) .RETURN(ssize_t(_2)); modifier.write_to(writer, text_modifier::NCPASSED); modifier.write_to(writer, text_modifier::NCPASSED_SUM); } { REQUIRE_CALL(buff, write(_,_)) .WITH(std::string(_1,_2) == "0") .RETURN(ssize_t(_2)); modifier.write_to(writer, text_modifier::NORMAL); } FORBID_CALL(buff, write(_,_)); modifier.write_to(writer, text_modifier::NCFAILED); modifier.write_to(writer, text_modifier::NCFAILED_SUM); modifier.write_to(writer, text_modifier::FAILED_SUM); modifier.write_to(writer, text_modifier::FAILED); modifier.write_to(writer, text_modifier::PASSED); modifier.write_to(writer, text_modifier::BLOCKED); modifier.write_to(writer, text_modifier::PASSED_SUM); modifier.write_to(writer, text_modifier::BLOCKED_SUM); } TEST(blocked_propagates, fix) { static const char config[] = " 0" " BLOCKED=B" " "; text_modifier modifier(config); { REQUIRE_CALL(buff, write(_,_)) .WITH(std::string(_1,_2) == "B") .TIMES(2) .RETURN(ssize_t(_2)); modifier.write_to(writer, text_modifier::BLOCKED); modifier.write_to(writer, text_modifier::BLOCKED_SUM); } { REQUIRE_CALL(buff, write(_,_)) .WITH(std::string(_1,_2) == "0") .RETURN(ssize_t(_2)); modifier.write_to(writer, text_modifier::NORMAL); } FORBID_CALL(buff, write(_,_)); modifier.write_to(writer, text_modifier::NCPASSED); modifier.write_to(writer, text_modifier::NCPASSED_SUM); modifier.write_to(writer, text_modifier::NCFAILED); modifier.write_to(writer, text_modifier::NCFAILED_SUM); modifier.write_to(writer, text_modifier::FAILED_SUM); modifier.write_to(writer, text_modifier::FAILED); modifier.write_to(writer, text_modifier::PASSED); modifier.write_to(writer, text_modifier::PASSED_SUM); } TEST(terminals_do_not_propagate, fix) { static const char config[] = " 0" " PASSED_SUM=PS" " FAILED_SUM=FS" " NCFAILED_SUM=NFS" " NCPASSED_SUM=NPS" " BLOCKED_SUM=BS" " "; text_modifier modifier(config); { REQUIRE_CALL(buff, write(_, _)) .WITH(std::string(_1,_2) == "PS") .RETURN(ssize_t(_2)); modifier.write_to(writer, text_modifier::PASSED_SUM); } { REQUIRE_CALL(buff, write(_, _)) .WITH(std::string(_1,_2) == "FS") .RETURN(2); modifier.write_to(writer, text_modifier::FAILED_SUM); } { REQUIRE_CALL(buff, write(_, _)) .WITH(std::string(_1, _2) == "BS") .RETURN(2); modifier.write_to(writer, text_modifier::BLOCKED_SUM); } { REQUIRE_CALL(buff, write(_, _)) .WITH(std::string(_1,_2) == "NFS") .RETURN(ssize_t(_2)); modifier.write_to(writer, text_modifier::NCFAILED_SUM); } { REQUIRE_CALL(buff, write(_, _)) .WITH(std::string(_1, _2) == "NPS") .RETURN(ssize_t(_2)); modifier.write_to(writer, text_modifier::NCPASSED_SUM); } { REQUIRE_CALL(buff, write(_, _)) .WITH(std::string(_1, _2) == "0") .RETURN(ssize_t(_2)); modifier.write_to(writer, text_modifier::NORMAL); } FORBID_CALL(buff, write(_,_)); modifier.write_to(writer, text_modifier::PASSED); modifier.write_to(writer, text_modifier::FAILED); modifier.write_to(writer, text_modifier::NCFAILED); modifier.write_to(writer, text_modifier::NCPASSED); modifier.write_to(writer, text_modifier::BLOCKED); } TEST(variable_subset_length_throws) { ASSERT_THROW(text_modifier(" 0 BLOCKED_SU=apa "), text_modifier::illegal_decoration_format, "BLOCKED_SU is not a decorator"); } TEST(variable_superset_length_throws) { ASSERT_THROW(text_modifier(" 0 BLOCKED_SUMM=apa "), text_modifier::illegal_decoration_format, "BLOCKED_SUMM is not a decorator"); } TEST(lacking_assign_throws) { ASSERT_THROW(text_modifier(" 0 BLOCKED_SUM "), text_modifier::illegal_decoration_format, "Missing = after name"); } TEST(lacking_terminator_throws) { ASSERT_THROW(text_modifier(" 0 BLOCKED_SUM=apa"), text_modifier::illegal_decoration_format, "Missing separator after value for BLOCKED_SUM"); } } }
35.980874
90
0.62594
lsilvest
3212a591afacd990ed550c13bbdfa5b4c1bb3425
42
cpp
C++
testStateMachine/IWaveFile.cpp
wp4398151/TestApp
7dffb4ca275801043f9e911f4f699dfaa1e906ae
[ "Apache-2.0" ]
null
null
null
testStateMachine/IWaveFile.cpp
wp4398151/TestApp
7dffb4ca275801043f9e911f4f699dfaa1e906ae
[ "Apache-2.0" ]
null
null
null
testStateMachine/IWaveFile.cpp
wp4398151/TestApp
7dffb4ca275801043f9e911f4f699dfaa1e906ae
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #include "IWaveFile.h"
21
22
0.738095
wp4398151
3215df03438b6a784c0dd3c350199cccc67cc4b6
2,674
cpp
C++
file-commander-core/src/diskenumerator/cvolumeenumerator_impl_win.cpp
treehugging-green-wolf/file-commander
5e6f5372e70de68981d0001035a6d2a110293ebb
[ "Apache-2.0" ]
null
null
null
file-commander-core/src/diskenumerator/cvolumeenumerator_impl_win.cpp
treehugging-green-wolf/file-commander
5e6f5372e70de68981d0001035a6d2a110293ebb
[ "Apache-2.0" ]
null
null
null
file-commander-core/src/diskenumerator/cvolumeenumerator_impl_win.cpp
treehugging-green-wolf/file-commander
5e6f5372e70de68981d0001035a6d2a110293ebb
[ "Apache-2.0" ]
null
null
null
#include "cvolumeenumerator.h" #include "../filesystemhelpers/filesystemhelpers.hpp" #include "windows/windowsutils.h" #include "utility/on_scope_exit.hpp" #include "system/ctimeelapsed.h" #include <Windows.h> DISABLE_COMPILER_WARNINGS #include <QDebug> RESTORE_COMPILER_WARNINGS inline QString parseVolumePathFromPathsList(WCHAR* paths) { QString qstring; for (auto string = paths; string[0] != L'\0'; string += wcslen(string) + 1) { qstring = QString::fromWCharArray(string); if (qstring.contains(':')) return qstring; } return qstring; } static VolumeInfo volumeInfoForDriveLetter(const QString& driveLetter) { if (!FileSystemHelpers::pathIsAccessible(driveLetter)) return {}; WCHAR volumeName[256], filesystemName[256]; const DWORD error = GetVolumeInformationW((WCHAR*)driveLetter.utf16(), volumeName, 256, nullptr, nullptr, nullptr, filesystemName, 256) != 0 ? 0 : GetLastError(); if (error != 0 && error != ERROR_NOT_READY) { const auto text = ErrorStringFromLastError(); qInfo() << "GetVolumeInformationW() returned error for" << driveLetter << text; return {}; } VolumeInfo info; info.isReady = error != ERROR_NOT_READY; info.rootObjectInfo = driveLetter; if (info.isReady) { ULARGE_INTEGER totalSpace, freeSpace; if (GetDiskFreeSpaceExW((WCHAR*)driveLetter.utf16(), &freeSpace, &totalSpace, nullptr) != 0) { info.volumeSize = totalSpace.QuadPart; info.freeSize = freeSpace.QuadPart; } else qInfo() << "GetDiskFreeSpaceExW() returned error:" << ErrorStringFromLastError(); } info.volumeLabel = QString::fromWCharArray(volumeName); info.fileSystemName = QString::fromWCharArray(filesystemName); return info; } const std::vector<VolumeInfo> CVolumeEnumerator::enumerateVolumesImpl() { std::vector<VolumeInfo> volumes; const auto oldErrorMode = ::SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); EXEC_ON_SCOPE_EXIT([oldErrorMode]() {::SetErrorMode(oldErrorMode);}); DWORD drives = ::GetLogicalDrives(); if (drives == 0) { qInfo() << "GetLogicalDrives() returned an error:" << ErrorStringFromLastError(); return volumes; } for (char driveLetter = 'A'; drives != 0 && driveLetter <= 'Z'; ++driveLetter, drives >>= 1) { if ((drives & 0x1) == 0) continue; CTimeElapsed timer{ true }; auto volumeInfo = volumeInfoForDriveLetter(QString(driveLetter) + QStringLiteral(":\\")); const auto elapsedMs = timer.elapsed(); if (elapsedMs > 100) qInfo() << "volumeInfoForDriveLetter for" << QString(driveLetter) + QStringLiteral(":\\") << "took" << elapsedMs << "ms"; if (!volumeInfo.isEmpty()) volumes.emplace_back(std::move(volumeInfo)); } return volumes; }
28.147368
163
0.720269
treehugging-green-wolf
32178875fc21b22adee573655bbad49a88e00cb7
1,125
cpp
C++
LCM of n nos.cpp
Kunal-Attri/Maths-Codes-Cpp
1aec8a9a9a30b50c09c9dbaebb0008687b51a386
[ "Apache-2.0" ]
null
null
null
LCM of n nos.cpp
Kunal-Attri/Maths-Codes-Cpp
1aec8a9a9a30b50c09c9dbaebb0008687b51a386
[ "Apache-2.0" ]
null
null
null
LCM of n nos.cpp
Kunal-Attri/Maths-Codes-Cpp
1aec8a9a9a30b50c09c9dbaebb0008687b51a386
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include "Basic_Functions.h" using namespace std; int main() { int t; cout << "Numbers of numbers: "; cin >> t; int x[t]; cout << "Numbers: "; for (int i = 0; i < t; i++) { cin >> x[i]; } // LCM function int larger = x[0]; for (int i = 0; i < t; i++) { if (x[i] > larger) { larger = x[i]; } } int divisors[larger]; int divQuan[larger]; for (int i = 0; i < larger; i++) { divisors[i] = 0; divQuan[i] = 0; } for (int a = 0; a < t; a++) { int i = 2; while (x[a] > 1) { int quantity = 0; while (x[a] % i == 0) { if (isprime(i)) { divisors[i] = i; quantity++; x[a] /= i; } } if (quantity > divQuan[i]) { divQuan[i] = quantity; } i++; } } int lcm = 1; for (int i = 0; i < larger; i++) { lcm *= pow(divisors[i], divQuan[i]); } cout << "LCM is " << lcm; }
20.833333
44
0.364444
Kunal-Attri
321916c75aa69ce94b9c77f9fd3c81404f44abb9
3,076
cpp
C++
engine/generators/fortresses/source/MotteBaileyCastleGeneratorStrategy.cpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
engine/generators/fortresses/source/MotteBaileyCastleGeneratorStrategy.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
engine/generators/fortresses/source/MotteBaileyCastleGeneratorStrategy.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#include "MotteBaileyCastleGeneratorStrategy.hpp" #include "CoordUtils.hpp" #include "DirectionUtils.hpp" #include "GeneratorUtils.hpp" #include "TileGenerator.hpp" #include "RNG.hpp" using namespace std; const int MotteBaileyCastleGeneratorStrategy::MIN_MOTTE_WIDTH = 8; const int MotteBaileyCastleGeneratorStrategy::MIN_MOTTE_HEIGHT = 6; // The motte is the keep, bailey is the courtyard. void MotteBaileyCastleGeneratorStrategy::generate(MapPtr castle_map) { Dimensions d; int start_y = RNG::range(2, d.get_y() / 4); int start_x = RNG::range(5, d.get_x() / 4); int end_y = d.get_y() - start_y; int end_x = d.get_x() - start_x; int motte_width = RNG::range(MIN_MOTTE_WIDTH, end_x - start_x - 4); int motte_height = RNG::range(MIN_MOTTE_HEIGHT, end_y - start_y - 4); generate_moat(castle_map, start_y, start_x, end_y, end_x); generate_motte(castle_map, motte_height, motte_width); generate_bridge(castle_map, start_y, start_x, end_y, end_x); } // Generate the moat around the castle structure, generated on the // centre of the map. void MotteBaileyCastleGeneratorStrategy::generate_moat(MapPtr castle_map, const int start_y, const int start_x, int end_y, int end_x) { TileGenerator tg; Dimensions dim = castle_map->size(); vector<Coordinate> coords = CoordUtils::get_perimeter_coordinates(make_pair(start_y, start_x), make_pair(end_y, end_x)); for (const Coordinate& c : coords) { TilePtr river_tile = tg.generate(TileType::TILE_TYPE_RIVER); castle_map->insert(c.first, c.second, river_tile); } } // Generate the motte (the keep). void MotteBaileyCastleGeneratorStrategy::generate_motte(MapPtr castle_map, const int motte_height, const int motte_width) { Dimensions dim = castle_map->size(); int start_row = (dim.get_y() / 2) - (motte_height / 2); int start_col = (dim.get_x() / 2) - (motte_width / 2); Coordinate top_left = make_pair(start_row, start_col); Coordinate bottom_right = make_pair(start_row + motte_height, start_col + motte_width); GeneratorUtils::generate_building(castle_map, start_row, start_col, motte_height+1, motte_width+1); map<CardinalDirection, Coordinate> midway_points = CoordUtils::get_midway_coordinates(top_left, bottom_right); for (const auto& c : midway_points) { GeneratorUtils::generate_door(castle_map, c.second.first, c.second.second); } } // Generate a land bridge over the moat. void MotteBaileyCastleGeneratorStrategy::generate_bridge(MapPtr castle_map, const int start_y, const int start_x, const int end_y, const int end_x) { Coordinate a = make_pair(start_y, start_x); Coordinate b = make_pair(end_y, end_x); map<CardinalDirection, Coordinate> bridge_coords = CoordUtils::get_midway_coordinates(a, b); auto b_it = bridge_coords.begin(); std::advance(b_it, RNG::range(0, bridge_coords.size() - 1)); Coordinate c = b_it->second; TilePtr bridge_tile = castle_map->at(c); TileGenerator tg; if (bridge_tile != nullptr) { bridge_tile = tg.generate(TileType::TILE_TYPE_ROAD); castle_map->insert(c.first, c.second, bridge_tile); } }
37.060241
147
0.75
sidav
321f220edd4592091688930651afe19b4974173b
3,113
cpp
C++
agent/messages/messages.cpp
vs49688/nimrodg-agent
9afdb6f84c2fa4f588f73cd4dd0ef9065fbc8931
[ "Apache-2.0" ]
1
2020-07-21T18:17:28.000Z
2020-07-21T18:17:28.000Z
agent/messages/messages.cpp
vs49688/nimrodg-agent
9afdb6f84c2fa4f588f73cd4dd0ef9065fbc8931
[ "Apache-2.0" ]
4
2019-05-23T05:39:14.000Z
2019-06-17T08:07:35.000Z
agent/messages/messages.cpp
vs49688/nimrodg-agent
9afdb6f84c2fa4f588f73cd4dd0ef9065fbc8931
[ "Apache-2.0" ]
null
null
null
/* * Nimrod/G Agent * https://github.com/UQ-RCC/nimrodg-agent * * SPDX-License-Identifier: Apache-2.0 * Copyright (c) 2019 The University of Queensland * * 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 "messages/messages.hpp" #include "agent_common.hpp" using namespace nimrod; using namespace nimrod::net; hello_message::hello_message(nimrod::uuid uuid, nim1::nanotime_t time, std::string_view queue) : message_base_type(uuid, time), m_queue(queue) {} std::string_view hello_message::queue() const noexcept { return m_queue; } init_message::init_message() noexcept : init_message(nimrod::uuid(), nim1::nanotime_t{0}) {} init_message::init_message(nimrod::uuid uuid, nim1::nanotime_t time) noexcept : message_base_type(uuid, time) {} lifecontrol_message::lifecontrol_message(nimrod::uuid uuid, nim1::nanotime_t time, operation_t op) : message_base_type(uuid, time), m_operation(op) {} lifecontrol_message::operation_t lifecontrol_message::operation() const noexcept { return m_operation; } shutdown_message::shutdown_message(nimrod::uuid uuid, nim1::nanotime_t time, reason_t reason, int signal) noexcept : message_base_type(uuid, time), m_reason(reason), m_signal(signal) {} shutdown_message::reason_t shutdown_message::reason() const noexcept { return m_reason; } int shutdown_message::signal() const noexcept { return m_signal; } submit_message::submit_message(nimrod::uuid uuid, nim1::nanotime_t time, const job_definition& job) : message_base_type(uuid, time), m_job(job) {} submit_message::submit_message(nimrod::uuid uuid, nim1::nanotime_t time, job_definition&& job) : message_base_type(uuid, time), m_job(std::move(job)) {} const job_definition& submit_message::job() const noexcept { return m_job; } update_message::update_message(nimrod::uuid uuid, nim1::nanotime_t time, nimrod::uuid job_uuid, const command_result& result, action_t action) : message_base_type(uuid, time), m_job_uuid(job_uuid), m_result(result), m_action(action) {} nimrod::uuid update_message::job_uuid() const noexcept { return m_job_uuid; } const command_result& update_message::result() const noexcept { return m_result; } update_message::action_t update_message::action() const noexcept { return m_action; } ping_message::ping_message(nimrod::uuid uuid, nim1::nanotime_t time) noexcept : message_base_type(uuid, time) {} pong_message::pong_message( nimrod::uuid uuid, nim1::nanotime_t time, agent_state_t state ) noexcept : message_base_type(uuid, time), m_state(state) {} agent_state_t pong_message::state() const noexcept { return m_state; }
23.946154
144
0.761323
vs49688
32200a137c740c636e320e64d84e85856db410c3
4,090
hpp
C++
VSDataReduction/VBFHiLoCalc.hpp
sfegan/ChiLA
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
[ "BSD-3-Clause" ]
1
2018-04-17T14:03:36.000Z
2018-04-17T14:03:36.000Z
VSDataReduction/VBFHiLoCalc.hpp
sfegan/ChiLA
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
[ "BSD-3-Clause" ]
null
null
null
VSDataReduction/VBFHiLoCalc.hpp
sfegan/ChiLA
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
[ "BSD-3-Clause" ]
null
null
null
//-*-mode:c++; mode:font-lock;-*- /*! \file VBFHiLoCalc.hpp Class designed for use with logain.cpp... \author Timothy C. Arlen \n UCLA \n arlen@astro.ucla.edu \n \author Stephen Fegan \n UCLA \n sfegan@astro.ucla.edu \n \version 1.0 \date 05/18/2005 $Id: VBFHiLoCalc.hpp,v 3.1 2009/12/22 19:43:30 matthew Exp $ */ #ifndef VBFHILOCALC_HPP #define VBFHILOCALC_HPP #include<vector> // Not sure if all these are needed?? #include "VBFSimplePeds.hpp" #include "VSSimpleHist.hpp" #include "VBFLaserCalc.hpp" #include "VSHiLoData.hpp" #include "VSFileUtility.hpp" #include "VSChannelMap.hpp" // ============================================================================ // VBFHiLoCalc // ============================================================================ // (Every new ChiLA class goes into the VERITAS namespace) namespace VERITAS { class VBFHiLoCalc: public VSSimpleVBFVisitor { public: struct ChanData { ChanData(): ped_stat(), nevent() { } // Statistics counters ------------------------------------------------- VSSimpleStat1<double> ped_stat; // Amplitude unsigned nevent; }; struct ScopeData { ScopeData(unsigned nchan=0): chan(nchan,ChanData()), nevent() { } // Channel data std::vector<ChanData> chan; // Statistics counters -------------------------------------------------- unsigned nevent; }; typedef std::vector<ScopeData*> ArrayData; VBFHiLoCalc(int sample_0, unsigned sample_N); virtual ~VBFHiLoCalc(); virtual void visitArrayTrigger(bool& veto_array_event, void* user_data, uint32_t event_num, const VEventType& event_type, uint32_t trigger_mask, uint32_t flags, const VSTime& raw_time, uint32_t at_flags, uint32_t config_mask, uint32_t num_telescopes, uint32_t num_trigger_telescopes, uint32_t run_number, const uint32_t* ten_mhz_clocks, const uint32_t* cal_count, const uint32_t* ped_count, const VArrayTrigger* trigger); virtual void visitScopeEvent(bool& veto_scope_event, void* user_data, uint32_t event_num, uint32_t telescope_num, const VEventType& event_type, uint32_t trigger_mask, uint32_t flags, const VSTime& raw_time, uint32_t num_samples, uint32_t num_channels_saved, uint32_t num_channels_total, uint32_t num_clock_trigger, const VEvent* event); virtual void visitChannel(bool& veto_channel, void* user_data, uint32_t channel_num, bool hit, bool trigger); virtual void visitHitChannel(void* user_data, uint32_t channel_num, uint32_t charge, uint32_t pedestal, bool lo_gain, unsigned nsample, const uint32_t* samples, const uint32_t* integrated); virtual void leaveScopeEvent(bool veto_scope_event, void* user_data); virtual void leaveArrayEvent(bool veto_array_event, void* user_data); void getData(VSHiLoData& data, unsigned nevent_min = 10) const; ArrayData scope; private: VBFHiLoCalc(VBFLaserCalc&); VBFHiLoCalc& operator= (const VBFLaserCalc&); // Settings int m_sample_0; unsigned m_sample_N; // State unsigned m_runno; unsigned m_scope_id; }; } #endif // VBFHILOCALC_HPP
30.073529
79
0.513447
sfegan
322698c34888563a503d92cc8ff04842291fad3f
16,685
cpp
C++
src/Algorithm/DataStructure/CoresetTree.cpp
intellistream/Sesame
efbd40084c591059af851f71bdafd96ab021f524
[ "MIT" ]
null
null
null
src/Algorithm/DataStructure/CoresetTree.cpp
intellistream/Sesame
efbd40084c591059af851f71bdafd96ab021f524
[ "MIT" ]
48
2022-03-14T09:33:09.000Z
2022-03-31T08:41:46.000Z
src/Algorithm/DataStructure/CoresetTree.cpp
intellistream/Sesame
efbd40084c591059af851f71bdafd96ab021f524
[ "MIT" ]
null
null
null
// Copyright (C) 2021 by the IntelliStream team (https://github.com/intellistream) // // Created by Shuhao Zhang on 19/07/2021. // #include <Algorithm/DataStructure/CoresetTree.hpp> #include <Utils/Logger.hpp> #include <Utils/UtilityFunctions.hpp> #include <Algorithm/DataStructure/DataStructureFactory.hpp> // TODO: convert it as general tree model void SESAME::CoresetTree::unionTreeCoreset(int k, int n_1, int n_2, std::vector<PointPtr> &setA, std::vector<PointPtr> &setB, std::vector<PointPtr> &centres) { // SESAME_DEBUG("Computing coreset..."); //total number of points int n = n_1 + n_2; //choose the first centre (each point has the same probability of being choosen) //stores, how many centres have been choosen yet int choosenPoints = 0; //only choose from the n-i points not already choosen int j = UtilityFunctions::genrand_int31() % (n - choosenPoints); //copy the choosen point if (j < n_1) { centres[choosenPoints] = setA[j]->copy();//TODO: ???? why re-set setA[j]? } else { j = j - n_1; centres[choosenPoints] = setB[j]->copy();//TODO: ???? why re-set setB[j]? } // struct treeNode *root = (struct treeNode *) malloc(sizeof(struct treeNode)); TreeNodePtr root = DataStructureFactory::createTreeNode(); constructRoot(root, setA, setB, n_1, n_2, centres[choosenPoints], choosenPoints); choosenPoints = 1; //choose the remaining points while (choosenPoints < k) { if (root->cost > 0.0) { TreeNodePtr leaf = selectNode(root); PointPtr centre = chooseCentre(leaf); split(leaf, centre, choosenPoints); centres[choosenPoints] = centre->copy(); } else { //create a dummy point centres[choosenPoints] = root->centre->copy(); int l; for (l = 0; l < centres[choosenPoints]->getDimension(); l++) { centres[choosenPoints]->setFeatureItem(-1 * 1000000, l); } centres[choosenPoints]->setIndex(-1); centres[choosenPoints]->setWeight(0.0); } choosenPoints++; } //free the tree freeTree(root); //recalculate clustering features int i; for (i = 0; i < n; i++) { if (i < n_1) { int index = setA[i]->getClusteringCenter(); if (centres[index]->getIndex() != setA[i]->getIndex()) { centres[index]->setWeight(centres[index]->getWeight() + setA[i]->getWeight()); int l; for (l = 0; l < setA[i]->getDimension(); l++) { if (setA[i]->getWeight() != 0.0) { centres[index]->setFeatureItem(setA[i]->getFeatureItem(l) + centres[index]->getFeatureItem(l), l); } } } } else { int index = setB[i - n_1]->getClusteringCenter(); if (centres[index]->getIndex() != setB[i - n_1]->getIndex()) { centres[index]->setWeight(centres[index]->getWeight() + setB[i - n_1]->getWeight()); int l; for (l = 0; l < setB[i - n_1]->getDimension(); l++) { if (setB[i - n_1]->getWeight() != 0.0) { centres[index]->setFeatureItem( setB[i - n_1]->getFeatureItem(l) + centres[index]->getFeatureItem(l), l); } } } } } } void SESAME::CoresetTree::freeTree(TreeNodePtr root) { while (!treeFinished(root)) { if (root->lc == NULL && root->rc == NULL) { root = root->parent; } else if (root->lc == NULL && root->rc != NULL) { //Schau ob rc ein Blatt ist if (isLeaf(root->rc)) { //Gebe rechtes Kind frei root->rc->points.clear(); DataStructureFactory::clearTreeNode(root->rc); root->rc = NULL; } else { //Fahre mit rechtem Kind fort root = root->rc; } } else if (root->lc != NULL) { if (isLeaf(root->lc)) { root->lc->points.clear(); DataStructureFactory::clearTreeNode(root->lc); root->lc = NULL; } else { root = root->lc; } } } root->points.clear(); root.reset(); } bool SESAME::CoresetTree::treeFinished(TreeNodePtr root) { if (root->parent == NULL && root->lc == NULL && root->rc == NULL) { return 1; } else { return 0; } } bool SESAME::CoresetTree::isLeaf(TreeNodePtr node) { if (node->lc == NULL && node->rc == NULL) { return 1; } else { return 0; } } void SESAME::CoresetTree::constructRoot(TreeNodePtr root, std::vector<PointPtr> &setA, std::vector<PointPtr> &setB, int n_1, int n_2, PointPtr centre, int centreIndex) { //loop counter variable int i; //the root has no parent and no child nodes in the beginning root->parent = NULL; root->lc = NULL; root->rc = NULL; //array with points to the points //root->points= new Point[n_1 + n_2]; root->n = n_1 + n_2; for (i = 0; i < root->n; i++) { if (i < n_1) { root->points.push_back(setA[i]); // root->points[i] = setA[i]; root->points[i]->setClusteringCenter(centreIndex); } else { root->points.push_back(setB[i - n_1]); root->points[i]->setClusteringCenter(centreIndex); } } //set the centre root->centre = centre; //calculate costs treeNodeTargetFunctionValue(root); } void SESAME::CoresetTree::treeNodeTargetFunctionValue(TreeNodePtr node) { //loop counter variable int i; //stores the cost double sum = 0.0; for (i = 0; i < node->n; i++) { //stores the distance double distance = 0.0; //loop counter variable int l; for (l = 0; l < node->points[i]->getDimension(); l++) { //centroid coordinate of the point double centroidCoordinatePoint; if (node->points[i]->getWeight() != 0.0) { centroidCoordinatePoint = node->points[i]->getFeatureItem(l) / node->points[i]->getWeight(); } else { centroidCoordinatePoint = node->points[i]->getFeatureItem(l); } //centroid coordinate of the centre double centroidCoordinateCentre; if (node->centre->getWeight() != 0.0) { centroidCoordinateCentre = node->centre->getFeatureItem(l) / node->centre->getWeight(); } else { centroidCoordinateCentre = node->centre->getFeatureItem(l); } distance += (centroidCoordinatePoint - centroidCoordinateCentre) * (centroidCoordinatePoint - centroidCoordinateCentre); } sum += distance * node->points[i]->getWeight(); } node->cost = sum; } SESAME::TreeNodePtr SESAME::CoresetTree::selectNode(TreeNodePtr root) { //random number between 0 and 1 double random = UtilityFunctions::genrand_real3(); while (!isLeaf(root)) { if (root->lc->cost == 0 && root->rc->cost == 0) { if (root->lc->n == 0) { root = root->rc; } else if (root->rc->n == 0) { root = root->lc; } else if (random < 0.5) { random = UtilityFunctions::genrand_real3(); root = root->lc; } else { random = UtilityFunctions::genrand_real3(); root = root->rc; } } else { if (random < root->lc->cost / root->cost) { root = root->lc; } else { root = root->rc; } } } return root; } /** * selects a new centre from the treenode (using the kMeans++ distribution) * TODO: Why hard-code?? */ SESAME::PointPtr SESAME::CoresetTree::chooseCentre(TreeNodePtr node) { //TODO: How many times should we try to choose a centre ?? int times = 3; //stores the nodecost if node is split with the best centre double minCost = node->cost; PointPtr bestCentre = DataStructureFactory::createPoint(); //loop counter variable int i; int j; for (j = 0; j < times; j++) { //sum of the relativ cost of the points double sum = 0.0; //random number between 0 and 1 double random = UtilityFunctions::genrand_real3(); for (i = 0; i < node->n; i++) { sum += treeNodeCostOfPoint(node, node->points[i]) / node->cost; if (sum >= random) { if (node->points[i]->getWeight() == 0.0) { SESAME_INFO("ERROR: CHOOSEN DUMMY NODE THOUGH OTHER AVAILABLE \n"); return bestCentre; } double curCost = treeNodeSplitCost(node, node->centre, node->points[i]); if (curCost < minCost) { bestCentre = node->points[i]; minCost = curCost; } break; } } } if (bestCentre->getIndex() == -1) { return node->points[0]; } else { return bestCentre; } } double SESAME::CoresetTree::treeNodeCostOfPoint(TreeNodePtr node, PointPtr p) { if (p->getWeight() == 0.0) { return 0.0; } //stores the distance between centre and p double distance = 0.0; //loop counter variable int l; for (l = 0; l < p->getDimension(); l++) { //centroid coor->inate of the point double centroidCoordinatePoint; if (p->getWeight() != 0.0) { centroidCoordinatePoint = p->getFeatureItem(l) / p->getWeight(); } else { centroidCoordinatePoint = p->getFeatureItem(l); } //centroid coordinate of the centre double centroidCoordinateCentre; if (node->centre->getWeight() != 0.0) { centroidCoordinateCentre = node->centre->getFeatureItem(l) / node->centre->getWeight(); } else { centroidCoordinateCentre = node->centre->getFeatureItem(l); } distance += (centroidCoordinatePoint - centroidCoordinateCentre) * (centroidCoordinatePoint - centroidCoordinateCentre); } return distance * p->getWeight(); } /** * computes the hypothetical cost if the node would be split with new centers centreA, centreB * @param node * @param centreA * @param centreB * @return */ double SESAME::CoresetTree::treeNodeSplitCost(TreeNodePtr node, PointPtr centreA, PointPtr centreB) { //loop counter variable int i; //stores the cost double sum = 0.0; for (i = 0; i < node->n; i++) { //loop counter variable int l; //stores the distance between p and centreA double distanceA = 0.0; for (l = 0; l < node->points[i]->getDimension(); l++) { //centroid coordinate of the point double centroidCoordinatePoint; if (node->points[i]->getWeight() != 0.0) { centroidCoordinatePoint = node->points[i]->getFeatureItem(l) / node->points[i]->getWeight(); } else { centroidCoordinatePoint = node->points[i]->getFeatureItem(l); } //centroid coordinate of the centre double centroidCoordinateCentre; if (centreA->getWeight() != 0.0) { centroidCoordinateCentre = centreA->getFeatureItem(l) / centreA->getWeight(); } else { centroidCoordinateCentre = centreA->getFeatureItem(l); } distanceA += (centroidCoordinatePoint - centroidCoordinateCentre) * (centroidCoordinatePoint - centroidCoordinateCentre); } //stores the distance between p and centreB double distanceB = 0.0; for (l = 0; l < node->points[i]->getDimension(); l++) { //centroid coordinate of the point double centroidCoordinatePoint; if (node->points[i]->getWeight() != 0.0) { centroidCoordinatePoint = node->points[i]->getFeatureItem(l) / node->points[i]->getWeight(); } else { centroidCoordinatePoint = node->points[i]->getFeatureItem(l); } //centroid coordinate of the centre double centroidCoordinateCentre; if (centreB->getWeight() != 0.0) { centroidCoordinateCentre = centreB->getFeatureItem(l) / centreB->getWeight(); } else { centroidCoordinateCentre = centreB->getFeatureItem(l); } distanceB += (centroidCoordinatePoint - centroidCoordinateCentre) * (centroidCoordinatePoint - centroidCoordinateCentre); } //add the cost of the closest centre to the sum if (distanceA < distanceB) { sum += distanceA * node->points[i]->getWeight(); } else { sum += distanceB * node->points[i]->getWeight(); } } //return the total cost return sum; } /** splits the parent node and creates two child nodes (one with the old centre and one with the new one) **/ void SESAME::CoresetTree::split(TreeNodePtr parent, PointPtr newCentre, int newCentreIndex) { //loop counter variable int i = 0; //1. Counts how many points belong to the new and how many points belong to the old centre int nOld = 0; int nNew = 0; for (i = 0; i < parent->n; i++) { PointPtr centre = determineClosestCentre(parent->points[i], parent->centre, newCentre); if (centre->getIndex() == newCentre->getIndex()) { nNew++; } else { nOld++; } } //2. initalizes the arrays for the pointer //array for pointer on the points belonging to the old centre std::vector<PointPtr> oldPoints;// = new Point[nOld]; // for(i = 0; i < nOld; i++) { // // } //array for pointer on the points belonging to the new centre std::vector<PointPtr> newPoints; //= new Point[nNew]; int indexOld = 0; int indexNew = 0; for (i = 0; i < parent->n; i++) { PointPtr centre = determineClosestCentre(parent->points[i], parent->centre, newCentre); if (centre->getIndex() == newCentre->getIndex()) { newPoints.push_back(parent->points[i]); newPoints[indexNew]->setClusteringCenter(newCentreIndex); indexNew++; } else if (centre->getIndex() == parent->centre->getIndex()) { oldPoints.push_back(parent->points[i]); indexOld++; } else { SESAME_INFO("ERROR !!! NO CENTER NEAREST !! \n"); } } //left child: old centre // struct TreeNode *lc = (struct TreeNode *) malloc(sizeof(struct TreeNode)); TreeNodePtr lc = DataStructureFactory::createTreeNode(); lc->centre = parent->centre; lc->points = oldPoints; lc->n = nOld; lc->lc = NULL; lc->rc = NULL; lc->parent = parent; treeNodeTargetFunctionValue(lc); //right child: new centre // struct TreeNode *rc = (struct TreeNode *) malloc(sizeof(struct TreeNode)); TreeNodePtr rc = DataStructureFactory::createTreeNode(); rc->centre = newCentre; rc->points = newPoints; rc->n = nNew; rc->lc = NULL; rc->rc = NULL; rc->parent = parent; treeNodeTargetFunctionValue(rc); //set childs of the parent node parent->lc = lc; parent->rc = rc; //propagate the cost changes to the parent nodes while (parent != NULL) { parent->cost = parent->lc->cost + parent->rc->cost; parent = parent->parent; } } /** * returns the next centre from A or B. * @param point * @param centreA * @param centreB * @return */ SESAME::PointPtr SESAME::CoresetTree::determineClosestCentre(PointPtr point, PointPtr centreA, PointPtr centreB) { //loop counter variable int l; //stores the distance between p and centreA double distanceA = 0.0; for (l = 0; l < point->getDimension(); l++) { //centroid coordinate of the point double centroidCoordinatePoint; if (point->getWeight() != 0.0) { centroidCoordinatePoint = point->getFeatureItem(l) / point->getWeight(); } else { centroidCoordinatePoint = point->getFeatureItem(l); } //centroid coordinate of the centre double centroidCoordinateCentre; if (centreA->getWeight() != 0.0) { centroidCoordinateCentre = centreA->getFeatureItem(l) / centreA->getWeight(); } else { centroidCoordinateCentre = centreA->getFeatureItem(l); } distanceA += (centroidCoordinatePoint - centroidCoordinateCentre) * (centroidCoordinatePoint - centroidCoordinateCentre); } //stores the distance between p and centreB double distanceB = 0.0; for (l = 0; l < point->getDimension(); l++) { //centroid coordinate of the point double centroidCoordinatePoint; if (point->getWeight() != 0.0) { centroidCoordinatePoint = point->getFeatureItem(l) / point->getWeight(); } else { centroidCoordinatePoint = point->getFeatureItem(l); } //centroid coordinate of the centre double centroidCoordinateCentre; if (centreB->getWeight() != 0.0) { centroidCoordinateCentre = centreB->getFeatureItem(l) / centreB->getWeight(); } else { centroidCoordinateCentre = centreB->getFeatureItem(l); } distanceB += (centroidCoordinatePoint - centroidCoordinateCentre) * (centroidCoordinatePoint - centroidCoordinateCentre); } //return the nearest centre if (distanceA < distanceB) { return centreA; } else { return centreB; } }
30.670956
114
0.60875
intellistream
322713e384e250dd9e0f0a2f5d169e98dca4a2dc
1,301
hpp
C++
include/armadillo_bits/fn_chol.hpp
jshahbazi/mnist-cpp
d757d07c03b2c24df94af4c0762b99db21c21538
[ "MIT" ]
80
2015-06-23T04:51:27.000Z
2022-03-09T08:15:36.000Z
include/armadillo_bits/fn_chol.hpp
jshahbazi/mnist-cpp
d757d07c03b2c24df94af4c0762b99db21c21538
[ "MIT" ]
4
2017-06-18T03:40:48.000Z
2018-10-31T09:55:32.000Z
include/armadillo_bits/fn_chol.hpp
jshahbazi/mnist-cpp
d757d07c03b2c24df94af4c0762b99db21c21538
[ "MIT" ]
37
2015-08-20T03:26:28.000Z
2022-03-08T10:54:49.000Z
// Copyright (C) 2009-2014 Conrad Sanderson // Copyright (C) 2009-2014 NICTA (www.nicta.com.au) // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! \addtogroup fn_chol //! @{ template<typename T1> inline const Op<T1, op_chol> chol ( const Base<typename T1::elem_type,T1>& X, const char* layout = "upper", const typename arma_blas_type_only<typename T1::elem_type>::result* junk = 0 ) { arma_extra_debug_sigprint(); arma_ignore(junk); const char sig = (layout != NULL) ? layout[0] : char(0); arma_debug_check( ((sig != 'u') && (sig != 'l')), "chol(): layout must be \"upper\" or \"lower\"" ); return Op<T1, op_chol>(X.get_ref(), ((sig == 'u') ? 0 : 1), 0 ); } template<typename T1> inline bool chol ( Mat<typename T1::elem_type>& out, const Base<typename T1::elem_type,T1>& X, const char* layout = "upper", const typename arma_blas_type_only<typename T1::elem_type>::result* junk = 0 ) { arma_extra_debug_sigprint(); arma_ignore(junk); try { out = chol(X, layout); } catch(std::runtime_error&) { return false; } return true; } //! @}
20.015385
102
0.626441
jshahbazi
32294654fc73d538f1c8b788abe1a0c0766a6f1e
6,599
cc
C++
services/resource_coordinator/coordination_unit/system_coordination_unit_impl.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
services/resource_coordinator/coordination_unit/system_coordination_unit_impl.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
services/resource_coordinator/coordination_unit/system_coordination_unit_impl.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2018 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 "services/resource_coordinator/coordination_unit/system_coordination_unit_impl.h" #include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" #include "services/resource_coordinator/coordination_unit/page_coordination_unit_impl.h" #include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" #include "base/macros.h" #include "base/process/process_handle.h" namespace resource_coordinator { SystemCoordinationUnitImpl::SystemCoordinationUnitImpl( const CoordinationUnitID& id, std::unique_ptr<service_manager::ServiceContextRef> service_ref) : CoordinationUnitInterface(id, std::move(service_ref)) {} SystemCoordinationUnitImpl::~SystemCoordinationUnitImpl() = default; void SystemCoordinationUnitImpl::OnProcessCPUUsageReady() { SendEvent(mojom::Event::kProcessCPUUsageReady); } void SystemCoordinationUnitImpl::DistributeMeasurementBatch( mojom::ProcessResourceMeasurementBatchPtr measurement_batch) { // Grab all the processes. std::vector<ProcessCoordinationUnitImpl*> processes = ProcessCoordinationUnitImpl::GetAllProcessCoordinationUnits(); base::TimeDelta time_since_last_measurement; if (!last_measurement_batch_time_.is_null()) { // Use the end of the measurement batch as a proxy for when every // measurement was acquired. For the purpose of estimating CPU usage // over the duration from last measurement, it'll be near enough. The error // will average out, and there's an inherent race in knowing when a // measurement was actually acquired in any case. time_since_last_measurement = measurement_batch->batch_ended_time - last_measurement_batch_time_; DCHECK_LE(base::TimeDelta(), time_since_last_measurement); } last_measurement_batch_time_ = measurement_batch->batch_ended_time; // Keep track of the pages updated with CPU cost for the second pass, // where their memory usage is updated. std::set<PageCoordinationUnitImpl*> pages; for (const auto& measurement : measurement_batch->measurements) { for (auto it = processes.begin(); it != processes.end(); ++it) { ProcessCoordinationUnitImpl* process = *it; int64_t process_pid; // TODO(siggi): This seems pretty silly - we're going O(N^2) in processes // here, and going through a relatively expensive accessor for the // PID. if (process->GetProperty(mojom::PropertyType::kPID, &process_pid) && static_cast<base::ProcessId>(process_pid) == measurement->pid) { base::TimeDelta cumulative_cpu_delta = measurement->cpu_usage - process->cumulative_cpu_usage(); DCHECK_LE(base::TimeDelta(), cumulative_cpu_delta); // Distribute the CPU delta to the pages that own the frames in this // process. std::set<FrameCoordinationUnitImpl*> frames = process->GetFrameCoordinationUnits(); if (!frames.empty()) { // To make sure we don't systemically truncate the remainder of the // delta, simply subtract the remainder and "hold it back" from the // measurement. Since our measurement is cumulative, we'll see that // CPU time again in the next measurement. cumulative_cpu_delta -= cumulative_cpu_delta % base::TimeDelta::FromMicroseconds(frames.size()); for (FrameCoordinationUnitImpl* frame : frames) { PageCoordinationUnitImpl* page = frame->GetPageCoordinationUnit(); if (page) { page->set_usage_estimate_time(last_measurement_batch_time_); page->set_cumulative_cpu_usage_estimate( page->cumulative_cpu_usage_estimate() + cumulative_cpu_delta / frames.size()); pages.insert(page); } } } else { // TODO(siggi): The process has zero frames, maybe this is a newly // started renderer and if so, this might be a good place to // estimate the process overhead. Alternatively perhaps the first // measurement for each process, or a lower bound thereof will // converge to a decent estimate. } if (process->cumulative_cpu_usage().is_zero() || time_since_last_measurement.is_zero()) { // Imitate the behavior of GetPlatformIndependentCPUUsage, which // yields zero for the initial measurement of each process. process->SetCPUUsage(0.0); } else { double cpu_usage = 100.0 * cumulative_cpu_delta.InMicrosecondsF() / time_since_last_measurement.InMicrosecondsF(); process->SetCPUUsage(cpu_usage); } process->set_cumulative_cpu_usage(process->cumulative_cpu_usage() + cumulative_cpu_delta); process->set_private_footprint_kb(measurement->private_footprint_kb); // Remove found processes. processes.erase(it); break; } } } // Clear processes we didn't get data for. for (ProcessCoordinationUnitImpl* process : processes) { process->SetCPUUsage(0.0); process->set_private_footprint_kb(0); } // Iterate through the pages involved to distribute the memory to them. for (PageCoordinationUnitImpl* page : pages) { uint64_t private_footprint_kb_sum = 0; const auto& frames = page->GetFrameCoordinationUnits(); for (FrameCoordinationUnitImpl* frame : frames) { ProcessCoordinationUnitImpl* process = frame->GetProcessCoordinationUnit(); if (process) { private_footprint_kb_sum += process->private_footprint_kb() / process->GetFrameCoordinationUnits().size(); } } page->set_private_footprint_kb_estimate(private_footprint_kb_sum); DCHECK_EQ(last_measurement_batch_time_, page->usage_estimate_time()); } // Fire the end update signal. OnProcessCPUUsageReady(); } void SystemCoordinationUnitImpl::OnEventReceived(mojom::Event event) { for (auto& observer : observers()) observer.OnSystemEventReceived(this, event); } void SystemCoordinationUnitImpl::OnPropertyChanged( mojom::PropertyType property_type, int64_t value) { for (auto& observer : observers()) observer.OnSystemPropertyChanged(this, property_type, value); } } // namespace resource_coordinator
42.301282
91
0.69753
zipated
322bb019718b72e28848ecc4d12693e62deb593b
2,995
cpp
C++
Uncategorized/nccc6s3.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
Uncategorized/nccc6s3.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
Uncategorized/nccc6s3.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; const short MM = 104, SS = 52; int X, Y, N; int mx[] = {0, 1, -1, 0, 0}, my[] = {0, 0, 0, 1, -1}; struct st{ short x, y, vx, vy; } start, ed; queue<st> q; unsigned short dis[MM][MM][MM][MM]; bool no[MM][MM]; int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a); } int main(){ memset(dis, 0x7e, sizeof dis); memset(no, 0, sizeof no); unsigned short inf = dis[0][0][0][0]; //print(inf); scanf("%d%d%d",&X,&Y,&N); scanf("%d%d",&start.x,&start.y); scanf("%d%d",&ed.x,&ed.y); for(int i = 0,a,b; i < N; i++){ scanf("%d%d",&a,&b); no[a][b] = 1; } start.vx = start.vy = ed.vx = ed.vy = SS; //zero dis[start.x][start.y][SS][SS] = 0; q.push(start); while(!q.empty()){ st cur = q.front(); q.pop(); short curd = dis[cur.x][cur.y][cur.vx][cur.vy]; for(int k = 0; k < 5; k++){ st nx; nx.vx = cur.vx + mx[k] - SS; nx.vy = cur.vy + my[k] - SS; nx.x = cur.x + nx.vx; nx.y = cur.y + nx.vy; if(nx.x < 0 || nx.x > X || nx.y < 0 || nx.y > Y) continue; //make sure no wind in between int slope = abs(gcd(nx.vx, nx.vy)); if(slope == 0) slope = 1; int ax = nx.vx / slope; int ay = nx.vy / slope; bool flag = 0; for(int i = cur.x, j = cur.y; i != nx.x || j != nx.y; i += ax, j += ay){ /* if(i < 0 || i >= MM || j < 0 || j >= MM){ puts("why"); break; } */ if(no[i][j]){ flag = 1; break; } } if(flag) continue; nx.vx += SS; nx.vy += SS; if(nx.vx < 0 || nx.vx >= MM || nx.vy < 0 || nx.vy >= MM) continue; /* if(nx.x < 0 || nx.x >= MM || nx.y < 0 || nx.y >= MM || nx.vx < 0 || nx.vx >= MM || nx.vy < 0 || nx.vy >= MM ){ puts("nope"); continue; } */ if(!no[nx.x][nx.y] && (curd+1 < dis[nx.x][nx.y][nx.vx][nx.vy])){ dis[nx.x][nx.y][nx.vx][nx.vy] = curd+1; q.push(nx); } } } int ans = dis[ed.x][ed.y][SS][SS]; if(ans == inf) ans = -1; printf("%d\n", ans); /* for(int i = 0; i <= X; i++){ for(int j = 0; j <= Y; j++){ printf("%d ", dis[i][j][SS][SS]); } printf("\n"); } */ return 0; }
25.168067
123
0.323539
crackersamdjam
7a86da3dfbdcfcb9422bed08230b16c861a22c7e
3,154
hpp
C++
headers/fun/instances/eq.hpp
BlackMATov/fun.hpp
11b208996c3c3784d31afb6463b34d5b68b47bd4
[ "MIT" ]
12
2019-01-07T05:55:35.000Z
2020-04-21T08:37:25.000Z
headers/fun/instances/eq.hpp
BlackMATov/fun.hpp
11b208996c3c3784d31afb6463b34d5b68b47bd4
[ "MIT" ]
1
2019-01-07T08:53:56.000Z
2019-01-07T08:53:56.000Z
headers/fun/instances/eq.hpp
BlackMATov/fun.hpp
11b208996c3c3784d31afb6463b34d5b68b47bd4
[ "MIT" ]
1
2019-01-08T07:51:30.000Z
2019-01-08T07:51:30.000Z
/******************************************************************************* * This file is part of the "https://github.com/blackmatov/fun.hpp" * For conditions of distribution and use, see copyright notice in LICENSE.md * Copyright (C) 2019-2020, by Matvey Cherevko (blackmatov@gmail.com) ******************************************************************************/ #pragma once #include "_instances.hpp" #include "../types/all.hpp" #include "../types/any.hpp" #include "../types/sum.hpp" #include "../types/product.hpp" #include "../types/box.hpp" #include "../types/maybe.hpp" #include "../classes/eq.hpp" namespace fun { // // arithmetic types // template < typename A > struct eq_inst_t<A, std::enable_if_t< std::is_arithmetic<A>::value, A> > : eq_inst_t<A> { static constexpr bool instance = true; static bool equals(A l, A r) { return l == r; } }; // // all_t // template <> struct eq_inst_t<all_t, all_t> : eq_inst_t<all_t> { static constexpr bool instance = true; static bool equals(const all_t& l, const all_t& r) { return l.get_all() == r.get_all(); } }; // // any_t // template <> struct eq_inst_t<any_t, any_t> : eq_inst_t<any_t> { static constexpr bool instance = true; static bool equals(const any_t& l, const any_t& r) { return l.get_any() == r.get_any(); } }; // // sum_t // template < typename A > struct eq_inst_t<sum_t<A>, std::enable_if_t< eq_t::instance<A>, sum_t<A>> > : eq_inst_t<sum_t<A>> { static constexpr bool instance = true; static bool equals(const sum_t<A>& l, const sum_t<A>& r) { return eq_f::equals(l.get_sum(), r.get_sum()); } }; // // product_t // template < typename A > struct eq_inst_t<product_t<A>, std::enable_if_t< eq_t::instance<A>, product_t<A>> > : eq_inst_t<product_t<A>> { static constexpr bool instance = true; static bool equals(const product_t<A>& l, const product_t<A>& r) { return eq_f::equals(l.get_product(), r.get_product()); } }; // // box_t // template < typename A > struct eq_inst_t<box_t<A>, std::enable_if_t< eq_t::instance<A>, box_t<A>> > : eq_inst_t<box_t<A>> { static constexpr bool instance = true; static bool equals(const box_t<A>& l, const box_t<A>& r) { return eq_f::equals(*l, *r); } }; // // maybe_t // template < typename A > struct eq_inst_t<maybe_t<A>, std::enable_if_t< eq_t::instance<A>, maybe_t<A>> > : eq_inst_t<maybe_t<A>> { static constexpr bool instance = true; static bool equals(const maybe_t<A>& l, const maybe_t<A>& r) { return (l.is_nothing() && r.is_nothing()) || (l.is_just() && r.is_just() && eq_f::equals(*l, *r)); } }; }
24.640625
80
0.509829
BlackMATov
7a8ed42e228158fb6a61f9bbf487114a4167aad2
1,201
cpp
C++
coast/modules/CacheHandler/Test/CallLdapCacheAction.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/modules/CacheHandler/Test/CallLdapCacheAction.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/modules/CacheHandler/Test/CallLdapCacheAction.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ #include "CallLdapCacheAction.h" #include "Tracer.h" #include "Context.h" #include "LDAPCachePolicyModule.h" //---- CallLdapCacheAction --------------------------------------------------------------- RegisterAction(CallLdapCacheAction); bool CallLdapCacheAction::DoExecAction(String &action, Context &ctx, const ROAnything &config) { // this is the new method that also gets a config ( similar to Renderer::RenderAll ) // write the action code here - you don't have to override DoAction anymore StartTrace(CallLdapCacheAction.DoExecAction); TraceAny(config, "config"); ROAnything result; String key(config["Key"].AsString()); String daName(config["Da"].AsString()); bool ret = true; if (key == "*") { result = LdapCacheGetter::GetAll(daName); } else { ret = LdapCacheGetter::Get(result, daName, key); } ctx.GetTmpStore() = result.DeepClone(); return ret; }
36.393939
102
0.701082
zer0infinity
7a935b1361d3d8d8fc90d329a480a73e9668aab2
2,056
cpp
C++
lib/widgets/TWizard.cpp
Tarsnap/tarsnap-gui
60a1d7816747ac71a4573673df8ee1b81ef1cb99
[ "BSD-2-Clause" ]
270
2015-06-11T05:08:56.000Z
2022-03-26T08:48:00.000Z
lib/widgets/TWizard.cpp
Tarsnap/tarsnap-gui
60a1d7816747ac71a4573673df8ee1b81ef1cb99
[ "BSD-2-Clause" ]
154
2015-06-10T21:28:54.000Z
2021-11-10T19:08:08.000Z
lib/widgets/TWizard.cpp
Tarsnap/tarsnap-gui
60a1d7816747ac71a4573673df8ee1b81ef1cb99
[ "BSD-2-Clause" ]
28
2015-06-11T00:09:26.000Z
2021-12-19T04:43:26.000Z
#include "TWizard.h" WARNINGS_DISABLE #include <QDialog> #include <QLabel> #include <QStackedWidget> #include <QWidget> #include "ui_TWizard.h" WARNINGS_ENABLE #include "TWizardPage.h" TWizard::TWizard(QWidget *parent) : QDialog(parent), _ui(new Ui::TWizard), _maxPageInitialized(-1) { _ui->setupUi(this); } TWizard::~TWizard() { delete _ui; } TWizardPage *TWizard::currentPage() const { QWidget *page = _ui->pageWidget->currentWidget(); return qobject_cast<TWizardPage *>(page); } void TWizard::setLogo(const QPixmap &pixmap) { _ui->logoLabel->setPixmap(pixmap); } QString TWizard::pageTitle() const { return _ui->titleLabel->text(); } void TWizard::addPages(QList<TWizardPage *> pages) { for(TWizardPage *page : pages) addPage(page); setupCurrentPage(); } void TWizard::addPage(TWizardPage *page) { _ui->pageWidget->addWidget(page); // Navigation connect(page, &TWizardPage::skipWizard, this, &TWizard::skipWizard); connect(page, &TWizardPage::backPage, this, &TWizard::backPage); connect(page, &TWizardPage::nextPage, this, &TWizard::nextPage); connect(page, &TWizardPage::finishWizard, this, &TWizard::finishWizard); } void TWizard::skipWizard() { accept(); } void TWizard::backPage() { const int pos = _ui->pageWidget->currentIndex(); Q_ASSERT(pos > 0); _ui->pageWidget->setCurrentIndex(pos - 1); setupCurrentPage(); } void TWizard::nextPage() { const int pos = _ui->pageWidget->currentIndex(); Q_ASSERT(pos < _ui->pageWidget->count() - 1); _ui->pageWidget->setCurrentIndex(pos + 1); setupCurrentPage(); } void TWizard::finishWizard() { accept(); } void TWizard::setupCurrentPage() { TWizardPage *page = currentPage(); Q_ASSERT(page != nullptr); // Set title _ui->titleLabel->setText(page->title()); // Initialize the page (if required) const int pos = _ui->pageWidget->currentIndex(); if(pos > _maxPageInitialized) { page->initializePage(); _maxPageInitialized = pos; } }
20.356436
76
0.672179
Tarsnap
7a93f7d3ed34d0333accea20df6d917d3a67ccb9
918
hpp
C++
src/Game.hpp
ingmarinho/wappie-jump
b869825222997c4ff068e03fe02e2b94ecd5e450
[ "BSL-1.0" ]
null
null
null
src/Game.hpp
ingmarinho/wappie-jump
b869825222997c4ff068e03fe02e2b94ecd5e450
[ "BSL-1.0" ]
null
null
null
src/Game.hpp
ingmarinho/wappie-jump
b869825222997c4ff068e03fe02e2b94ecd5e450
[ "BSL-1.0" ]
null
null
null
#pragma once #include <memory> #include <string> #include <SFML/Graphics.hpp> #include "StateMachine.hpp" #include "AssetManager.hpp" #include "InputManager.hpp" /// @file namespace WappieJump { /// saves all the data about the game's current state, /// and contains important information for the game to be able to run struct GameData { StateMachine machine; sf::RenderWindow window; AssetManager assets; InputManager input; bool isRunning = true; long long int score = 0; long long int highScore = 0; sf::Sprite characterSprite; int difficultyLevel = 100; int soundVolume = 50; }; typedef std::shared_ptr<GameData> GameDataRef; class Game { public: /// Declares the window (width/height) and sets the window title Game(int width, int height, std::string title); private: GameDataRef _data = std::make_shared<GameData>(); /// Start the main game loop void Run(); }; }
20.863636
70
0.712418
ingmarinho
7a9539d0481a613147586be0fbedf98b16a449fe
2,942
cpp
C++
submods/amrex/Tests/Amr/Advection_AmrCore/Source/DefineVelocity.cpp
ndevelder/amr-wind-channel-les
51b048ba30a5ed3ac1bd055e807f4d59a64a45ea
[ "BSD-3-Clause" ]
null
null
null
submods/amrex/Tests/Amr/Advection_AmrCore/Source/DefineVelocity.cpp
ndevelder/amr-wind-channel-les
51b048ba30a5ed3ac1bd055e807f4d59a64a45ea
[ "BSD-3-Clause" ]
null
null
null
submods/amrex/Tests/Amr/Advection_AmrCore/Source/DefineVelocity.cpp
ndevelder/amr-wind-channel-les
51b048ba30a5ed3ac1bd055e807f4d59a64a45ea
[ "BSD-3-Clause" ]
null
null
null
#include <AmrCoreAdv.H> #include <Kernels.H> #include <AMReX_MultiFabUtil.H> using namespace amrex; void AmrCoreAdv::DefineVelocityAllLevels (Real time) { for (int lev = 0; lev <= finest_level; ++lev) DefineVelocityAtLevel(lev,time); } void AmrCoreAdv::DefineVelocityAtLevel (int lev, Real time) { const auto dx = geom[lev].CellSizeArray(); #ifdef AMREX_USE_OMP #pragma omp parallel if (Gpu::notInLaunchRegion()) #endif { for (MFIter mfi(phi_new[lev],TilingIfNotGPU()); mfi.isValid(); ++mfi) { // ======== GET FACE VELOCITY ========= GpuArray<Box, AMREX_SPACEDIM> nbx; AMREX_D_TERM(nbx[0] = mfi.nodaltilebox(0);, nbx[1] = mfi.nodaltilebox(1);, nbx[2] = mfi.nodaltilebox(2);); AMREX_D_TERM(const Box& ngbxx = amrex::grow(mfi.nodaltilebox(0),1);, const Box& ngbxy = amrex::grow(mfi.nodaltilebox(1),1);, const Box& ngbxz = amrex::grow(mfi.nodaltilebox(2),1);); GpuArray<Array4<Real>, AMREX_SPACEDIM> vel{ AMREX_D_DECL( facevel[lev][0].array(mfi), facevel[lev][1].array(mfi), facevel[lev][2].array(mfi)) }; const Box& psibox = Box(IntVect(AMREX_D_DECL(std::min(ngbxx.smallEnd(0)-1, ngbxy.smallEnd(0)-1), std::min(ngbxx.smallEnd(1)-1, ngbxy.smallEnd(0)-1), 0)), IntVect(AMREX_D_DECL(std::max(ngbxx.bigEnd(0), ngbxy.bigEnd(0)+1), std::max(ngbxx.bigEnd(1)+1, ngbxy.bigEnd(1)), 0))); FArrayBox psifab(psibox, 1); Elixir psieli = psifab.elixir(); Array4<Real> psi = psifab.array(); GeometryData geomdata = geom[lev].data(); amrex::launch(psibox, [=] AMREX_GPU_DEVICE (const Box& tbx) { get_face_velocity_psi(tbx, time, psi, geomdata); }); amrex::ParallelFor (AMREX_D_DECL(ngbxx,ngbxy,ngbxz), AMREX_D_DECL( [=] AMREX_GPU_DEVICE (int i, int j, int k) { get_face_velocity_x(i, j, k, vel[0], psi, dx[1]); }, [=] AMREX_GPU_DEVICE (int i, int j, int k) { get_face_velocity_y(i, j, k, vel[1], psi, dx[0]); }, [=] AMREX_GPU_DEVICE (int i, int j, int k) { get_face_velocity_z(i, j, k, vel[2]); })); } } }
38.207792
108
0.449354
ndevelder
7a9a6c5dadbb470f402bcfc0801010684154f711
28,521
cpp
C++
enduser/netmeeting/av/nac/sendaudio.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
enduser/netmeeting/av/nac/sendaudio.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
enduser/netmeeting/av/nac/sendaudio.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "precomp.h" #include "dtmf.h" HRESULT SendAudioStream::Initialize( DataPump *pDP) { HRESULT hr = DPR_OUT_OF_MEMORY; DWORD dwFlags = DP_FLAG_FULL_DUPLEX | DP_FLAG_AUTO_SWITCH ; MEDIACTRLINIT mcInit; FX_ENTRY ("SendAudioStream::Initialize") dwFlags |= DP_FLAG_ACM | DP_FLAG_MMSYSTEM | DP_FLAG_AUTO_SILENCE_DETECT; // store the platform flags // enable Send and Recv by default m_DPFlags = (dwFlags & DP_MASK_PLATFORM) | DPFLAG_ENABLE_SEND; // store a back pointer to the datapump container m_pDP = pDP; m_Net = NULL; // this object (RTPSession) no longer used; m_pRTPSend = NULL; // replaced with this object (RTPSend) // Initialize data (should be in constructor) m_CaptureDevice = (UINT) -1; // use VIDEO_MAPPER // Create and Transmit audio streams DBG_SAVE_FILE_LINE m_SendStream = new TxStream(); if ( !m_SendStream) { DEBUGMSG (ZONE_DP, ("%s: TxStream new failed\r\n", _fx_)); goto StreamAllocError; } // Create Input and Output audio filters DBG_SAVE_FILE_LINE m_pAudioFilter = new AcmFilter(); // audio filter will replace m_SendFilter if (!m_pAudioFilter) { DEBUGMSG (ZONE_DP, ("%s: FilterManager new failed\r\n", _fx_)); goto FilterAllocError; } //Create MultiMedia device control objects DBG_SAVE_FILE_LINE m_InMedia = new WaveInControl(); if (!m_InMedia ) { DEBUGMSG (ZONE_DP, ("%s: MediaControl new failed\r\n", _fx_)); goto MediaAllocError; } // Initialize the send-stream media control object mcInit.dwFlags = dwFlags | DP_FLAG_SEND; hr = m_InMedia->Initialize(&mcInit); if (hr != DPR_SUCCESS) { DEBUGMSG (ZONE_DP, ("%s: IMedia->Init failed, hr=0x%lX\r\n", _fx_, hr)); goto MediaAllocError; } DBG_SAVE_FILE_LINE m_pDTMF = new DTMFQueue; if (!m_pDTMF) { return DPR_OUT_OF_MEMORY; } // determine if the wave devices are available if (waveInGetNumDevs()) m_DPFlags |= DP_FLAG_RECORD_CAP; // set media to half duplex mode by default m_InMedia->SetProp(MC_PROP_DUPLEX_TYPE, DP_FLAG_HALF_DUPLEX); m_SavedTickCount = timeGetTime(); //so we start with low timestamps m_DPFlags |= DPFLAG_INITIALIZED; m_bAutoMix = FALSE; // where else do you initialize this ? return DPR_SUCCESS; MediaAllocError: if (m_InMedia) delete m_InMedia; FilterAllocError: if (m_pAudioFilter) delete m_pAudioFilter; StreamAllocError: if (m_SendStream) delete m_SendStream; ERRORMESSAGE( ("%s: exit, hr=0x%lX\r\n", _fx_, hr)); return hr; } SendAudioStream::~SendAudioStream() { if (m_DPFlags & DPFLAG_INITIALIZED) { m_DPFlags &= ~DPFLAG_INITIALIZED; if (m_DPFlags & DPFLAG_CONFIGURED_SEND ) UnConfigure(); if (m_pRTPSend) { m_pRTPSend->Release(); m_pRTPSend = NULL; } if (m_pDTMF) { delete m_pDTMF; m_pDTMF = NULL; } // Close the receive and transmit streams if (m_SendStream) delete m_SendStream; // Close the wave devices if (m_InMedia) { delete m_InMedia;} if (m_pAudioFilter) delete m_pAudioFilter; m_pDP->RemoveMediaChannel(MCF_SEND|MCF_AUDIO, (IMediaChannel*)(SendMediaStream*)this); } } HRESULT STDMETHODCALLTYPE SendAudioStream::QueryInterface(REFIID iid, void **ppVoid) { // resolve duplicate inheritance to the SendMediaStream; extern IID IID_IProperty; if (iid == IID_IUnknown) { *ppVoid = (IUnknown*)((SendMediaStream*)this); } else if (iid == IID_IMediaChannel) { *ppVoid = (IMediaChannel*)((SendMediaStream *)this); } else if (iid == IID_IAudioChannel) { *ppVoid = (IAudioChannel*)this; } else if (iid == IID_IDTMFSend) { *ppVoid = (IDTMFSend*)this; } else if (iid == IID_IProperty) { *ppVoid = NULL; ERROR_OUT(("Don't QueryInterface for IID_IProperty, use IMediaChannel")); return E_NOINTERFACE; } else { *ppVoid = NULL; return E_NOINTERFACE; } AddRef(); return S_OK; } ULONG STDMETHODCALLTYPE SendAudioStream::AddRef(void) { return InterlockedIncrement(&m_lRefCount); } ULONG STDMETHODCALLTYPE SendAudioStream::Release(void) { LONG lRet; lRet = InterlockedDecrement(&m_lRefCount); if (lRet == 0) { delete this; return 0; } else return lRet; } HRESULT STDMETHODCALLTYPE SendAudioStream::Configure( BYTE *pFormat, UINT cbFormat, BYTE *pChannelParams, UINT cbParams, IUnknown *pUnknown) { HRESULT hr; BOOL fRet; MEDIAPACKETINIT apInit; MEDIACTRLCONFIG mcConfig; MediaPacket **ppAudPckt; ULONG cAudPckt; DWORD_PTR dwPropVal; DWORD dwSourceSize, dwDestSize; UINT ringSize = MAX_RXRING_SIZE; WAVEFORMATEX *pwfSend; DWORD dwPacketDuration, dwPacketSize; AUDIO_CHANNEL_PARAMETERS audChannelParams; audChannelParams.RTP_Payload = 0; MMRESULT mmr; int nIndex; FX_ENTRY ("SendAudioStream::Configure") // basic parameter checking if (! (m_DPFlags & DPFLAG_INITIALIZED)) return DPR_OUT_OF_MEMORY; //BUGBUG: return proper error; // Not a good idea to change anything while in mid-stream if (m_DPFlags & DPFLAG_STARTED_SEND) { return DPR_IO_PENDING; // anything better to return } if (m_DPFlags & DPFLAG_CONFIGURED_SEND) { DEBUGMSG(ZONE_DP, ("Stream Re-Configuration - calling UnConfigure")); UnConfigure(); } if ((NULL == pFormat) || (NULL == pChannelParams) || (cbParams < sizeof(AUDIO_CHANNEL_PARAMETERS)) || (cbFormat < sizeof(WAVEFORMATEX))) { return DPR_INVALID_PARAMETER; } audChannelParams = *(AUDIO_CHANNEL_PARAMETERS *)pChannelParams; pwfSend = (WAVEFORMATEX *)pFormat; m_wfCompressed = *pwfSend; m_wfCompressed.cbSize = 0; mmr = AcmFilter::SuggestDecodeFormat(pwfSend, &m_fDevSend); UPDATE_REPORT_ENTRY(g_prptCallParameters, pwfSend->wFormatTag, REP_SEND_AUDIO_FORMAT); UPDATE_REPORT_ENTRY(g_prptCallParameters, pwfSend->nSamplesPerSec, REP_SEND_AUDIO_SAMPLING); UPDATE_REPORT_ENTRY(g_prptCallParameters, pwfSend->nAvgBytesPerSec * 8, REP_SEND_AUDIO_BITRATE); RETAILMSG(("NAC: Audio Send Format: %s", (pwfSend->wFormatTag == 66) ? "G723.1" : (pwfSend->wFormatTag == 112) ? "LHCELP" : (pwfSend->wFormatTag == 113) ? "LHSB08" : (pwfSend->wFormatTag == 114) ? "LHSB12" : (pwfSend->wFormatTag == 115) ? "LHSB16" : (pwfSend->wFormatTag == 6) ? "MSALAW" : (pwfSend->wFormatTag == 7) ? "MSULAW" : (pwfSend->wFormatTag == 130) ? "MSRT24" : "??????")); RETAILMSG(("NAC: Audio Send Sampling Rate (Hz): %ld", pwfSend->nSamplesPerSec)); RETAILMSG(("NAC: Audio Send Bitrate (w/o network overhead - bps): %ld", pwfSend->nAvgBytesPerSec*8)); // Initialize the send-stream media control object mcConfig.uDuration = MC_USING_DEFAULT; // set duration by samples per pkt mcConfig.pDevFmt = &m_fDevSend; mcConfig.hStrm = (DPHANDLE) m_SendStream; mcConfig.uDevId = m_CaptureDevice; mcConfig.cbSamplesPerPkt = audChannelParams.ns_params.wFrameSize *audChannelParams.ns_params.wFramesPerPkt; UPDATE_REPORT_ENTRY(g_prptCallParameters, mcConfig.cbSamplesPerPkt, REP_SEND_AUDIO_PACKET); RETAILMSG(("NAC: Audio Send Packetization (ms/packet): %ld", pwfSend->nSamplesPerSec ? mcConfig.cbSamplesPerPkt * 1000UL / pwfSend->nSamplesPerSec : 0)); INIT_COUNTER_MAX(g_pctrAudioSendBytes, (pwfSend->nAvgBytesPerSec + pwfSend->nSamplesPerSec * (sizeof(RTP_HDR) + IP_HEADER_SIZE + UDP_HEADER_SIZE) / mcConfig.cbSamplesPerPkt) << 3); hr = m_InMedia->Configure(&mcConfig); if (hr != DPR_SUCCESS) { DEBUGMSG (ZONE_DP, ("%s: IMedia->Config failed, hr=0x%lX\r\n", _fx_, hr)); goto IMediaInitError; } // initialize the ACM filter mmr = m_pAudioFilter->Open(&m_fDevSend, pwfSend); if (mmr != 0) { DEBUGMSG (ZONE_DP, ("%s: AcmFilter->Open failed, mmr=%d\r\n", _fx_, mmr)); hr = DPR_CANT_OPEN_CODEC; goto SendFilterInitError; } // Initialize the send stream and the packets ZeroMemory (&apInit, sizeof (apInit)); apInit.dwFlags = DP_FLAG_SEND | DP_FLAG_ACM | DP_FLAG_MMSYSTEM; m_InMedia->FillMediaPacketInit (&apInit); m_InMedia->GetProp (MC_PROP_SIZE, &dwPropVal); dwSourceSize = (DWORD)dwPropVal; m_pAudioFilter->SuggestDstSize(dwSourceSize, &dwDestSize); apInit.cbSizeRawData = dwSourceSize; apInit.cbOffsetRawData = 0; apInit.cbSizeNetData = dwDestSize; dwPacketSize = dwDestSize; apInit.pStrmConvSrcFmt = &m_fDevSend; apInit.pStrmConvDstFmt = &m_wfCompressed; m_InMedia->GetProp (MC_PROP_DURATION, &dwPropVal); dwPacketDuration = (DWORD)dwPropVal; apInit.cbOffsetNetData = sizeof (RTP_HDR); apInit.payload = audChannelParams.RTP_Payload; fRet = m_SendStream->Initialize (DP_FLAG_MMSYSTEM, MAX_TXRING_SIZE, m_pDP, &apInit); if (! fRet) { DEBUGMSG (ZONE_DP, ("%s: TxStream->Init failed, fRet=0%u\r\n", _fx_, fRet)); hr = DPR_CANT_INIT_TX_STREAM; goto TxStreamInitError; } // prepare headers for TxStream m_SendStream->GetRing (&ppAudPckt, &cAudPckt); m_InMedia->RegisterData (ppAudPckt, cAudPckt); m_InMedia->PrepareHeaders (); m_pAudioFilter->PrepareAudioPackets((AudioPacket**)ppAudPckt, cAudPckt, AP_ENCODE); // Open the play from wav file OpenSrcFile(); // Initialize DTMF support m_pDTMF->Initialize(&m_fDevSend); m_pDTMF->ClearQueue(); // WS2Qos will be called in Start to communicate stream reservations to the // remote endpoint using a RESV message // // We use a peak-rate allocation approach based on our target bitrates // Note that for the token bucket size and the maximum SDU size, we now // account for IP header overhead, and use the max frame fragment size // instead of the maximum compressed image size returned by the codec // // Some of the parameters are left unspecified because they are set // in the sender Tspec. InitAudioFlowspec(&m_flowspec, pwfSend, dwPacketSize); if (m_pDP->m_pIQoS) { // Initialize our requests. One for CPU usage, one for bandwidth usage. m_aRRq.cResourceRequests = 2; m_aRRq.aResourceRequest[0].resourceID = RESOURCE_OUTGOING_BANDWIDTH; if (dwPacketDuration) m_aRRq.aResourceRequest[0].nUnitsMin = (DWORD)(dwPacketSize + sizeof(RTP_HDR) + IP_HEADER_SIZE + UDP_HEADER_SIZE) * 8000 / dwPacketDuration; else m_aRRq.aResourceRequest[0].nUnitsMin = 0; m_aRRq.aResourceRequest[1].resourceID = RESOURCE_CPU_CYCLES; m_aRRq.aResourceRequest[1].nUnitsMin = 800; /* BUGBUG. This is, in theory the correct calculation, but until we do more investigation, go with a known value m_aRRq.aResourceRequest[1].nUnitsMin = (audDetails.wCPUUtilizationEncode+audDetails.wCPUUtilizationDecode)*10; */ // Initialize QoS structure ZeroMemory(&m_Stats, sizeof(m_Stats)); // Initialize oldest QoS callback timestamp // Register with the QoS module. Even if this call fails, that's Ok, we'll do without the QoS support m_pDP->m_pIQoS->RequestResources((GUID *)&MEDIA_TYPE_H323AUDIO, (LPRESOURCEREQUESTLIST)&m_aRRq, QosNotifyAudioCB, (DWORD_PTR)this); } m_DPFlags |= DPFLAG_CONFIGURED_SEND; return DPR_SUCCESS; TxStreamInitError: SendFilterInitError: m_InMedia->Close(); m_pAudioFilter->Close(); IMediaInitError: ERRORMESSAGE(("%s: failed, hr=0%u\r\n", _fx_, hr)); return hr; } void SendAudioStream::UnConfigure() { AudioPacket **ppAudPckt; ULONG uPackets; if ((m_DPFlags & DPFLAG_CONFIGURED_SEND)) { if (m_hCapturingThread) { Stop(); } // Close the wave devices m_InMedia->Reset(); m_InMedia->UnprepareHeaders(); m_InMedia->Close(); // Close the play from wav file CloseSrcFile(); // Close the filters m_SendStream->GetRing ((MediaPacket***)&ppAudPckt, &uPackets); m_pAudioFilter->UnPrepareAudioPackets(ppAudPckt, uPackets, AP_ENCODE); m_pAudioFilter->Close(); // Close the transmit streams m_SendStream->Destroy(); m_DPFlags &= ~DPFLAG_CONFIGURED_SEND; m_ThreadFlags = 0; // invalidate previous call to SetMaxBitrate // Release the QoS Resources // If the associated RequestResources had failed, the ReleaseResources can be // still called... it will just come back without having freed anything. if (m_pDP->m_pIQoS) { m_pDP->m_pIQoS->ReleaseResources((GUID *)&MEDIA_TYPE_H323AUDIO, (LPRESOURCEREQUESTLIST)&m_aRRq); } } } DWORD CALLBACK SendAudioStream::StartRecordingThread (LPVOID pVoid) { SendAudioStream *pThisStream = (SendAudioStream*)pVoid; return pThisStream->RecordingThread(); } // LOOK: identical to SendVideoStream version. HRESULT SendAudioStream::Start() { FX_ENTRY ("SendAudioStream::Start") if (m_DPFlags & DPFLAG_STARTED_SEND) return DPR_SUCCESS; // TODO: remove this check once audio UI calls the IComChan PAUSE_ prop if (!(m_DPFlags & DPFLAG_ENABLE_SEND)) return DPR_SUCCESS; if ((!(m_DPFlags & DPFLAG_CONFIGURED_SEND)) || (m_pRTPSend==NULL)) return DPR_NOT_CONFIGURED; ASSERT(!m_hCapturingThread); m_ThreadFlags &= ~(DPTFLAG_STOP_RECORD|DPTFLAG_STOP_SEND); SetFlowSpec(); // Start recording thread if (!(m_ThreadFlags & DPTFLAG_STOP_RECORD)) m_hCapturingThread = CreateThread(NULL,0, SendAudioStream::StartRecordingThread,(LPVOID)this,0,&m_CaptureThId); m_DPFlags |= DPFLAG_STARTED_SEND; DEBUGMSG (ZONE_DP, ("%s: Record threadid=%x,\r\n", _fx_, m_CaptureThId)); return DPR_SUCCESS; } // LOOK: identical to SendVideoStream version. HRESULT SendAudioStream::Stop() { DWORD dwWait; if(!(m_DPFlags & DPFLAG_STARTED_SEND)) { return DPR_SUCCESS; } m_ThreadFlags = m_ThreadFlags | DPTFLAG_STOP_SEND | DPTFLAG_STOP_RECORD ; if(m_SendStream) m_SendStream->Stop(); DEBUGMSG (ZONE_VERBOSE, ("STOP1: Waiting for record thread to exit\r\n")); /* * we want to wait for all the threads to exit, but we need to handle windows * messages (mostly from winsock) while waiting. */ if(m_hCapturingThread) { dwWait = WaitForSingleObject (m_hCapturingThread, INFINITE); DEBUGMSG (ZONE_VERBOSE, ("STOP2: Recording thread exited\r\n")); ASSERT(dwWait != WAIT_FAILED); CloseHandle(m_hCapturingThread); m_hCapturingThread = NULL; } m_DPFlags &= ~DPFLAG_STARTED_SEND; return DPR_SUCCESS; } // low order word is the signal strength // high order work contains bits to indicate status // (0x01 - transmitting) // (0x02 - audio device is jammed) STDMETHODIMP SendAudioStream::GetSignalLevel(UINT *pSignalStrength) { UINT uLevel; DWORD dwJammed; DWORD_PTR dwPropVal; if(!(m_DPFlags & DPFLAG_STARTED_SEND)) { uLevel = 0; } else { uLevel = m_AudioMonitor.GetSignalStrength(); m_InMedia->GetProp(MC_PROP_AUDIO_JAMMED, &dwPropVal); dwJammed = (DWORD)dwPropVal; if (dwJammed) { uLevel = (2 << 16); // 0x0200 } else if (m_fSending) { uLevel |= (1 << 16); // 0x0100 + uLevel } } *pSignalStrength = uLevel; return S_OK; }; // this interface method is primarily for H.245 flow control messages // it will pause the stream if uMaxBitrate is less than the codec // output bitrate. Only valid on a Configure'd stream. HRESULT STDMETHODCALLTYPE SendAudioStream::SetMaxBitrate(UINT uMaxBitrate) { UINT uMinBitrate; if (!(m_DPFlags & DPFLAG_CONFIGURED_SEND)) { return DPR_NOT_CONFIGURED; } uMinBitrate = 8 * m_wfCompressed.nAvgBytesPerSec; if (uMaxBitrate < uMinBitrate) { DEBUGMSG(1, ("SendAudioStream::SetMaxBitrate - PAUSING")); m_ThreadFlags |= DPTFLAG_PAUSE_SEND; } else { DEBUGMSG(1, ("SendAudioStream::SetMaxBitrate - UnPausing")); m_ThreadFlags = m_ThreadFlags & ~(DPTFLAG_PAUSE_SEND); } return S_OK; } // IProperty::GetProperty / SetProperty // (DataPump::MediaChannel::GetProperty) // Properties of the MediaChannel. Supports properties for both audio // and video channels. STDMETHODIMP SendAudioStream::GetProperty( DWORD prop, PVOID pBuf, LPUINT pcbBuf ) { HRESULT hr = DPR_SUCCESS; RTP_STATS RTPStats; DWORD_PTR dwPropVal; UINT len = sizeof(DWORD); // most props are DWORDs if (!pBuf || *pcbBuf < len) { *pcbBuf = len; return DPR_INVALID_PARAMETER; } switch (prop) { case PROP_AUDIO_STRENGTH: return GetSignalLevel((UINT *)pBuf); case PROP_AUDIO_JAMMED: hr = m_InMedia->GetProp(MC_PROP_AUDIO_JAMMED, &dwPropVal); *(DWORD *)pBuf = (DWORD)dwPropVal; break; #ifdef OLDSTUFF case PROP_NET_SEND_STATS: if (m_Net && *pcbBuf >= sizeof(RTP_STATS)) { m_Net->GetSendStats((RTP_STATS *)pBuf); *pcbBuf = sizeof(RTP_STATS); } else hr = DPR_INVALID_PROP_VAL; break; #endif case PROP_DURATION: hr = m_InMedia->GetProp(MC_PROP_DURATION, &dwPropVal); *(DWORD *)pBuf = (DWORD)dwPropVal; break; case PROP_SILENCE_LEVEL: *(DWORD *)pBuf = m_AudioMonitor.GetSilenceLevel(); break; case PROP_SILENCE_DURATION: hr = m_InMedia->GetProp(MC_PROP_SILENCE_DURATION, &dwPropVal); *(DWORD *)pBuf = (DWORD)dwPropVal; break; case PROP_DUPLEX_TYPE: hr = m_InMedia->GetProp(MC_PROP_DUPLEX_TYPE, &dwPropVal); if(HR_SUCCEEDED(hr)) { if(dwPropVal & DP_FLAG_FULL_DUPLEX) *(DWORD *)pBuf = DUPLEX_TYPE_FULL; else *(DWORD *)pBuf = DUPLEX_TYPE_HALF; } break; case PROP_AUDIO_SPP: hr = m_InMedia->GetProp(MC_PROP_SPP, &dwPropVal); *(DWORD *)pBuf = (DWORD)dwPropVal; break; case PROP_AUDIO_SPS: hr = m_InMedia->GetProp(MC_PROP_SPS, &dwPropVal); *(DWORD *)pBuf = (DWORD)dwPropVal; break; case PROP_WAVE_DEVICE_TYPE: *(DWORD *)pBuf = m_DPFlags & DP_MASK_WAVE_DEVICE; break; case PROP_RECORD_ON: *(DWORD *)pBuf = (m_DPFlags & DPFLAG_ENABLE_SEND) !=0; break; case PROP_AUDIO_AUTOMIX: *(DWORD *)pBuf = m_bAutoMix; break; case PROP_RECORD_DEVICE: *(DWORD *)pBuf = m_CaptureDevice; break; default: hr = DPR_INVALID_PROP_ID; break; } return hr; } STDMETHODIMP SendAudioStream::SetProperty( DWORD prop, PVOID pBuf, UINT cbBuf ) { DWORD dw; HRESULT hr = S_OK; if (cbBuf < sizeof (DWORD)) return DPR_INVALID_PARAMETER; switch (prop) { case PROP_SILENCE_LEVEL: m_AudioMonitor.SetSilenceLevel(*(DWORD *)pBuf); RETAILMSG(("NAC: Silence Level set to %d / 1000",*(DWORD*)pBuf)); break; case PROP_DUPLEX_TYPE: ASSERT(0); break; case DP_PROP_DUPLEX_TYPE: dw = *(DWORD*)pBuf; if (dw) { dw = DP_FLAG_FULL_DUPLEX; } else { dw = DP_FLAG_HALF_DUPLEX; } m_InMedia->SetProp(MC_PROP_DUPLEX_TYPE, dw); break; case PROP_VOICE_SWITCH: // set duplex type of both input and output dw = *(DWORD*)pBuf; switch(dw) { case VOICE_SWITCH_MIC_ON: dw = DP_FLAG_MIC_ON; break; case VOICE_SWITCH_MIC_OFF: dw = DP_FLAG_MIC_OFF; break; default: case VOICE_SWITCH_AUTO: dw = DP_FLAG_AUTO_SWITCH; break; } hr = m_InMedia->SetProp(MC_PROP_VOICE_SWITCH, dw); RETAILMSG(("NAC: Setting voice switch to %s", (DP_FLAG_AUTO_SWITCH & dw) ? "Auto" : ((DP_FLAG_MIC_ON & dw)? "MicOn":"MicOff"))); break; case PROP_SILENCE_DURATION: hr = m_InMedia->SetProp(MC_PROP_SILENCE_DURATION, *(DWORD*)pBuf); RETAILMSG(("NAC: setting silence duration to %d ms",*(DWORD*)pBuf)); break; // TODO: remove this property once UI calls IComChan version case PROP_RECORD_ON: { DWORD flag = DPFLAG_ENABLE_SEND ; if (*(DWORD *)pBuf) { m_DPFlags |= flag; // set the flag Start(); } else { m_DPFlags &= ~flag; // clear the flag Stop(); } RETAILMSG(("NAC: %s", *(DWORD*)pBuf ? "Enabling":"Disabling")); break; } case PROP_AUDIO_AUTOMIX: m_bAutoMix = *(DWORD*)pBuf; break; case PROP_RECORD_DEVICE: m_CaptureDevice = *(DWORD*)pBuf; RETAILMSG(("NAC: Setting default record device to %d", m_CaptureDevice)); break; default: return DPR_INVALID_PROP_ID; break; } return hr; } void SendAudioStream::EndSend() { } /************************************************************************* Function: SendAudioStream::OpenSrcFile(void) Purpose : Opens wav file to read audio data from. Returns : HRESULT. Params : None Comments: * Registry keys: \\HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Audio\PlayFromFile\fPlayFromFile If set to zero, data will not be read from wav file. If set to a non null value <= INT_MAX, data will be read from wav file. \\HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Audio\PlayFromFile\szInputFileName Name of the wav file to read audio data from. \\HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Audio\PlayFromFile\fLoop If set to zero, the file will only be read once. If set to a non null value <= INT_MAX, the file will be read circularly. \\HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Audio\PlayFromFile\cchIOBuffer If set to zero, size of the MM IO buffer is set to its default value (8Kbytes). If set to one, size of the MM IO buffer is set to match maximum size of the wav file. If set a non null value between 2 and INT_MAX, size of the MM IO buffer is set to cchIOBuffer bytes. History : Date Reason 06/02/96 Created - PhilF *************************************************************************/ HRESULT SendAudioStream::OpenSrcFile (void) { return AudioFile::OpenSourceFile(&m_mmioSrc, &m_fDevSend); } /************************************************************************* Function: DataPump::CloseSrcFile(void) Purpose : Close wav file used to read audio data from. Returns : HRESULT. Params : None Comments: History : Date Reason 06/02/96 Created - PhilF *************************************************************************/ HRESULT SendAudioStream::CloseSrcFile (void) { return AudioFile::CloseSourceFile(&m_mmioSrc); } HRESULT CALLBACK SendAudioStream::QosNotifyAudioCB(LPRESOURCEREQUESTLIST lpResourceRequestList, DWORD_PTR dwThis) { HRESULT hr=NOERROR; LPRESOURCEREQUESTLIST prrl=lpResourceRequestList; int i; #ifdef LOGSTATISTICS_ON int iMaxBWUsage, iMaxCPUUsage; char szDebug[256]; #endif DWORD dwCPUUsage, dwBWUsage; int iCPUUsageId, iBWUsageId; UINT dwSize = sizeof(int); SendMediaStream *pThis = (SendMediaStream *)dwThis; // Enter critical section to allow QoS thread to read the statistics while recording EnterCriticalSection(&(pThis->m_crsQos)); // Record the time of this callback call pThis->m_Stats.dwNewestTs = timeGetTime(); // Only do anything if we have at least captured a frame in the previous epoch if ((pThis->m_Stats.dwCount) && (pThis->m_Stats.dwNewestTs > pThis->m_Stats.dwOldestTs)) { #ifdef LOGSTATISTICS_ON wsprintf(szDebug, " Epoch = %ld\r\n", pThis->m_Stats.dwNewestTs - pThis->m_Stats.dwOldestTs); OutputDebugString(szDebug); #endif // Read the stats dwCPUUsage = pThis->m_Stats.dwMsComp * 1000UL / (pThis->m_Stats.dwNewestTs - pThis->m_Stats.dwOldestTs); dwBWUsage = pThis->m_Stats.dwBits * 1000UL / (pThis->m_Stats.dwNewestTs - pThis->m_Stats.dwOldestTs); // Initialize QoS structure. Only the four first fields should be zeroed. ZeroMemory(&(pThis->m_Stats), 4UL * sizeof(DWORD)); // Record the time of this call for the next callback call pThis->m_Stats.dwOldestTs = pThis->m_Stats.dwNewestTs; } else dwBWUsage = dwCPUUsage = 0UL; // Get the latest RTCP stats and update the counters. // we do this here because it is called periodically. if (pThis->m_pRTPSend) { UINT lastPacketsLost = pThis->m_RTPStats.packetsLost; if (g_pctrAudioSendLost && SUCCEEDED(pThis->m_pRTPSend->GetSendStats(&pThis->m_RTPStats))) UPDATE_COUNTER(g_pctrAudioSendLost, pThis->m_RTPStats.packetsLost-lastPacketsLost); } // Leave critical section LeaveCriticalSection(&(pThis->m_crsQos)); // Get the max for the resources. #ifdef LOGSTATISTICS_ON iMaxCPUUsage = -1L; iMaxBWUsage = -1L; #endif for (i=0, iCPUUsageId = -1L, iBWUsageId = -1L; i<(int)lpResourceRequestList->cRequests; i++) if (lpResourceRequestList->aRequests[i].resourceID == RESOURCE_OUTGOING_BANDWIDTH) iBWUsageId = i; else if (lpResourceRequestList->aRequests[i].resourceID == RESOURCE_CPU_CYCLES) iCPUUsageId = i; #ifdef LOGSTATISTICS_ON if (iBWUsageId != -1L) iMaxBWUsage = lpResourceRequestList->aRequests[iBWUsageId].nUnitsMin; if (iCPUUsageId != -1L) iMaxCPUUsage = lpResourceRequestList->aRequests[iCPUUsageId].nUnitsMin; #endif // Update the QoS resources (only if you need less than what's available) if (iCPUUsageId != -1L) { if ((int)dwCPUUsage < lpResourceRequestList->aRequests[iCPUUsageId].nUnitsMin) lpResourceRequestList->aRequests[iCPUUsageId].nUnitsMin = dwCPUUsage; } if (iBWUsageId != -1L) { if ((int)dwBWUsage < lpResourceRequestList->aRequests[iBWUsageId].nUnitsMin) lpResourceRequestList->aRequests[iBWUsageId].nUnitsMin = dwBWUsage; } #ifdef LOGSTATISTICS_ON // How are we doing? if (iCPUUsageId != -1L) { wsprintf(szDebug, " A: Max CPU Usage: %ld, Current CPU Usage: %ld\r\n", iMaxCPUUsage, dwCPUUsage); OutputDebugString(szDebug); } if (iBWUsageId != -1L) { wsprintf(szDebug, " A: Max BW Usage: %ld, Current BW Usage: %ld\r\n", iMaxBWUsage, dwBWUsage); OutputDebugString(szDebug); } #endif return hr; } HRESULT __stdcall SendAudioStream::AddDigit(int nDigit) { IMediaChannel *pIMC = NULL; RecvMediaStream *pRecv = NULL; BOOL bIsStarted; if ((!(m_DPFlags & DPFLAG_CONFIGURED_SEND)) || (m_pRTPSend==NULL)) { return DPR_NOT_CONFIGURED; } bIsStarted = (m_DPFlags & DPFLAG_STARTED_SEND); if (bIsStarted) { Stop(); } m_pDTMF->AddDigitToQueue(nDigit); SendDTMF(); m_pDP->GetMediaChannelInterface(MCF_RECV | MCF_AUDIO, &pIMC); if (pIMC) { pRecv = static_cast<RecvMediaStream *> (pIMC); pRecv->DTMFBeep(); pIMC->Release(); } if (bIsStarted) { Start(); } return S_OK; } HRESULT __stdcall SendAudioStream::SendDTMF() { HRESULT hr; MediaPacket **ppAudPckt, *pPacket; ULONG uCount; UINT uBufferSize, uBytesSent; void *pBuffer; bool bMark = true; DWORD dwSamplesPerPkt; MMRESULT mmr; DWORD dwSamplesPerSec; DWORD dwPacketTimeMS; DWORD_PTR dwPropVal; UINT uTimerID; HANDLE hEvent = m_pDTMF->GetEvent(); m_InMedia->GetProp (MC_PROP_SPP, &dwPropVal); dwSamplesPerPkt = (DWORD)dwPropVal; m_InMedia->GetProp (MC_PROP_SPS, &dwPropVal); dwSamplesPerSec = (DWORD)dwPropVal; dwPacketTimeMS = (dwSamplesPerPkt * 1000) / dwSamplesPerSec; timeBeginPeriod(5); ResetEvent(hEvent); uTimerID = timeSetEvent(dwPacketTimeMS-1, 5, (LPTIMECALLBACK)hEvent, 0, TIME_CALLBACK_EVENT_SET|TIME_PERIODIC); // since the stream is stopped, just grab any packet // from the TxStream m_SendStream->GetRing(&ppAudPckt, &uCount); pPacket = ppAudPckt[0]; pPacket->GetDevData(&pBuffer, &uBufferSize); hr = m_pDTMF->ReadFromQueue((BYTE*)pBuffer, uBufferSize); while (SUCCEEDED(hr)) { // there should be only 1 tone in the queue (it can handle more) // so assume we only need to set the mark bit on the first packet pPacket->m_fMark = bMark; bMark = false; pPacket->SetProp(MP_PROP_TIMESTAMP, m_SendTimestamp); m_SendTimestamp += dwSamplesPerPkt; pPacket->SetState (MP_STATE_RECORDED); // compress mmr = m_pAudioFilter->Convert((AudioPacket*)pPacket, AP_ENCODE); if (mmr == MMSYSERR_NOERROR) { pPacket->SetState(MP_STATE_ENCODED); SendPacket((AudioPacket*)pPacket, &uBytesSent); pPacket->m_fMark=false; pPacket->SetState(MP_STATE_RESET); } hr = m_pDTMF->ReadFromQueue((BYTE*)pBuffer, uBufferSize); // so that we don't overload the receive jitter buffer on the remote // side, sleep a few milliseconds between sending packets if (SUCCEEDED(hr)) { WaitForSingleObject(hEvent, dwPacketTimeMS); ResetEvent(hEvent); } } timeKillEvent(uTimerID); timeEndPeriod(5); return S_OK; } HRESULT __stdcall SendAudioStream::ResetDTMF() { if(!(m_DPFlags & DPFLAG_STARTED_SEND)) { return S_OK; } return m_pDTMF->ClearQueue(); } 
26.214154
385
0.685775
npocmaka
7a9c337d7c6432a75726145264e75e582727722c
7,103
cpp
C++
qtsvg/src/plugins/imageformats/svg/qsvgiohandler.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
qtsvg/src/plugins/imageformats/svg/qsvgiohandler.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
qtsvg/src/plugins/imageformats/svg/qsvgiohandler.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsvgiohandler.h" #ifndef QT_NO_SVGRENDERER #include "qsvgrenderer.h" #include "qimage.h" #include "qpixmap.h" #include "qpainter.h" #include "qvariant.h" #include "qbuffer.h" #include "qdebug.h" QT_BEGIN_NAMESPACE class QSvgIOHandlerPrivate { public: QSvgIOHandlerPrivate(QSvgIOHandler *qq) : q(qq), loaded(false), readDone(false), backColor(Qt::transparent) {} bool load(QIODevice *device); QSvgIOHandler *q; QSvgRenderer r; QXmlStreamReader xmlReader; QSize defaultSize; QRect clipRect; QSize scaledSize; QRect scaledClipRect; bool loaded; bool readDone; QColor backColor; }; bool QSvgIOHandlerPrivate::load(QIODevice *device) { if (loaded) return true; if (q->format().isEmpty()) q->canRead(); // # The SVG renderer doesn't handle trailing, unrelated data, so we must // assume that all available data in the device is to be read. bool res = false; QBuffer *buf = qobject_cast<QBuffer *>(device); if (buf) { const QByteArray &ba = buf->data(); res = r.load(QByteArray::fromRawData(ba.constData() + buf->pos(), ba.size() - buf->pos())); buf->seek(ba.size()); #ifndef QT_NO_COMPRESS } else if (q->format() == "svgz") { res = r.load(device->readAll()); #endif } else { xmlReader.setDevice(device); res = r.load(&xmlReader); } if (res) { defaultSize = QSize(r.viewBox().width(), r.viewBox().height()); loaded = true; } return loaded; } QSvgIOHandler::QSvgIOHandler() : d(new QSvgIOHandlerPrivate(this)) { } QSvgIOHandler::~QSvgIOHandler() { delete d; } bool QSvgIOHandler::canRead() const { if (!device()) return false; if (d->loaded && !d->readDone) return true; // Will happen if we have been asked for the size QByteArray buf = device()->peek(8); #ifndef QT_NO_COMPRESS if (buf.startsWith("\x1f\x8b")) { setFormat("svgz"); return true; } else #endif if (buf.contains("<?xml") || buf.contains("<svg") || buf.contains("<!--")) { setFormat("svg"); return true; } return false; } QByteArray QSvgIOHandler::name() const { return "svg"; } bool QSvgIOHandler::read(QImage *image) { if (!d->readDone && d->load(device())) { bool xform = (d->clipRect.isValid() || d->scaledSize.isValid() || d->scaledClipRect.isValid()); QSize finalSize = d->defaultSize; QRectF bounds; if (xform && !d->defaultSize.isEmpty()) { bounds = QRectF(QPointF(0,0), QSizeF(d->defaultSize)); QPoint tr1, tr2; QSizeF sc(1, 1); if (d->clipRect.isValid()) { tr1 = -d->clipRect.topLeft(); finalSize = d->clipRect.size(); } if (d->scaledSize.isValid()) { sc = QSizeF(qreal(d->scaledSize.width()) / finalSize.width(), qreal(d->scaledSize.height()) / finalSize.height()); finalSize = d->scaledSize; } if (d->scaledClipRect.isValid()) { tr2 = -d->scaledClipRect.topLeft(); finalSize = d->scaledClipRect.size(); } QTransform t; t.translate(tr2.x(), tr2.y()); t.scale(sc.width(), sc.height()); t.translate(tr1.x(), tr1.y()); bounds = t.mapRect(bounds); } *image = QImage(finalSize, QImage::Format_ARGB32_Premultiplied); if (!finalSize.isEmpty()) { image->fill(d->backColor.rgba()); QPainter p(image); d->r.render(&p, bounds); p.end(); } d->readDone = true; return true; } return false; } QVariant QSvgIOHandler::option(ImageOption option) const { switch(option) { case ImageFormat: return QImage::Format_ARGB32_Premultiplied; break; case Size: d->load(device()); return d->defaultSize; break; case ClipRect: return d->clipRect; break; case ScaledSize: return d->scaledSize; break; case ScaledClipRect: return d->scaledClipRect; break; case BackgroundColor: return d->backColor; break; default: break; } return QVariant(); } void QSvgIOHandler::setOption(ImageOption option, const QVariant & value) { switch(option) { case ClipRect: d->clipRect = value.toRect(); break; case ScaledSize: d->scaledSize = value.toSize(); break; case ScaledClipRect: d->scaledClipRect = value.toRect(); break; case BackgroundColor: d->backColor = value.value<QColor>(); break; default: break; } } bool QSvgIOHandler::supportsOption(ImageOption option) const { switch(option) { case ImageFormat: case Size: case ClipRect: case ScaledSize: case ScaledClipRect: case BackgroundColor: return true; default: break; } return false; } bool QSvgIOHandler::canRead(QIODevice *device) { QByteArray buf = device->peek(8); return #ifndef QT_NO_COMPRESS buf.startsWith("\x1f\x8b") || #endif buf.contains("<?xml") || buf.contains("<svg") || buf.contains("<!--"); } QT_END_NAMESPACE #endif // QT_NO_SVGRENDERER
26.405204
103
0.589751
wgnet
7aa351f30a9379d173bb62c5ceef359d6f042d73
1,053
cpp
C++
src/MCMC.cpp
Chrom3D/Chrom3D
e6b78e679d788d9822a3258c7a9c06ca4edcafc6
[ "MIT" ]
25
2018-02-13T03:55:06.000Z
2021-12-13T06:47:53.000Z
src/MCMC.cpp
Chrom3D/Chrom3D
e6b78e679d788d9822a3258c7a9c06ca4edcafc6
[ "MIT" ]
31
2017-11-27T14:40:17.000Z
2022-03-28T10:38:38.000Z
src/MCMC.cpp
Chrom3D/Chrom3D
e6b78e679d788d9822a3258c7a9c06ca4edcafc6
[ "MIT" ]
11
2018-04-19T14:43:40.000Z
2022-03-29T08:37:44.000Z
#include "MCMC.h" MCMC::MCMC(Model& mod): model(mod) { } bool MCMC::doMetropolisHastingsStep(double T /*=1*/, uint maxAttempts /*=10000*/) { uint i=0; bool success = false; while(i < maxAttempts and !success) { try { Move proposedMove = model.proposeMove(); // Idea: if this fails (no move proposed), we could set the proposed Move to the same (identity) move. double before = model.getPartialLossScore(proposedMove.chr, proposedMove.start, proposedMove.stop); // score before move Move oldCoords = model.accept(proposedMove); //, true); double after = model.getPartialLossScore(proposedMove.chr, proposedMove.start, proposedMove.stop); // score after move if(after > before) { double pAccept = exp((before-after)/T); bool accept = util::unif_real(0,1, model.randEngine) < pAccept; if(not accept) { Move tmp = model.accept(oldCoords); //, true); // roll back to previous coordinates. } } success = true; } catch(util::MoveException& e){ i++; } } return success; }
33.967742
149
0.662868
Chrom3D
7aa39c5b08b4cd2ad8ed6d56af327167a3f4f511
2,499
hpp
C++
include/hfn/fnv1a.hpp
obhi-d/hfn
692203a25a13214ba8a0e2feddb8d6e78275c860
[ "MIT" ]
null
null
null
include/hfn/fnv1a.hpp
obhi-d/hfn
692203a25a13214ba8a0e2feddb8d6e78275c860
[ "MIT" ]
null
null
null
include/hfn/fnv1a.hpp
obhi-d/hfn
692203a25a13214ba8a0e2feddb8d6e78275c860
[ "MIT" ]
null
null
null
#pragma once #include "config.hpp" #include "detail/fnv1a.hpp" #include <type_traits> namespace hfn::fnv1a { template <typename fnvt> inline auto seed(fnvt initial = 0) noexcept { using type = std::remove_cv_t<std::remove_reference_t<fnvt>>; return (initial) ? (detail::fnv1a<sizeof(type)>::offset ^ initial) * detail::fnv1a<sizeof(type)>::prime : detail::fnv1a<sizeof(type)>::offset; } template <typename fnvt> inline auto update(fnvt& last, void const* source, std::size_t len) { const std::uint8_t* values = reinterpret_cast<const std::uint8_t*>(source); for (std::size_t i = 0; i < len; ++i) { last ^= values[i]; last *= detail::fnv1a<sizeof(fnvt)>::prime; } return last; } template <typename fnvt, typename T> inline auto update(fnvt& last, T const& mem) { return update(last, &mem, sizeof(mem)); } template <typename fnvt> inline fnvt compute(void const* source, std::size_t len) { constexpr fnvt initial = 0; auto result = seed(initial); return update(result, source, len); } template <typename fnvt, typename T> inline auto compute(T const& mem) { return compute<fnvt>(&mem, sizeof(T)); } inline std::uint64_t compute64(void const* source, std::size_t len) { constexpr std::uint64_t initial = 0; auto result = seed(initial); return update(result, source, len); } template <typename T> inline auto compute64(T const& mem) { return compute<std::uint64_t>(&mem, sizeof(T)); } inline std::uint32_t compute32(void const* source, std::size_t len) { constexpr std::uint32_t initial = 0; auto result = seed(initial); return update(result, source, len); } template <typename T> inline auto compute32(T const& mem) { return compute<std::uint32_t>(&mem, sizeof(T)); } template <typename base> class hash { public: HFN_FORCE_INLINE hash() noexcept : value(seed<base>()) {} HFN_FORCE_INLINE hash(base initial) noexcept : value(seed(initial)) {} HFN_FORCE_INLINE base operator()() const noexcept { return value; } HFN_FORCE_INLINE auto operator()(void const* key, std::size_t len) noexcept { return update(value, key, len); } template <typename T> HFN_FORCE_INLINE auto operator()(T const& key) noexcept { return update(value, &key, sizeof(T)); } private: base value; }; } // namespace hfn::fnv1a namespace hfn { using fnv1a_32 = hfn::fnv1a::hash<std::uint32_t>; using fnv1a_64 = hfn::fnv1a::hash<std::uint64_t>; } // namespace hfn
22.926606
105
0.67547
obhi-d
7aa7479d9938d0220c832e76c78fbb5b43de539e
7,268
cpp
C++
filters/ffmpeg/ffmpegSwScale.cpp
InfiniteInteractive/LimitlessSDK
cb71dde14d8c59cbf8a1ece765989c5787fffefa
[ "MIT" ]
3
2017-05-13T20:36:03.000Z
2021-07-16T17:23:01.000Z
filters/ffmpeg/ffmpegSwScale.cpp
InfiniteInteractive/LimitlessSDK
cb71dde14d8c59cbf8a1ece765989c5787fffefa
[ "MIT" ]
null
null
null
filters/ffmpeg/ffmpegSwScale.cpp
InfiniteInteractive/LimitlessSDK
cb71dde14d8c59cbf8a1ece765989c5787fffefa
[ "MIT" ]
2
2016-08-04T00:16:50.000Z
2017-09-07T14:50:03.000Z
#include "FfmpegSwScale.h" #include "QtComponents/QtPluginView.h" #include "Media/MediaPad.h" #include "Media/MediaSampleFactory.h" #include "Media/ImageSample.h" #include "ffmpegResources.h" #include "ffmpegControls.h" #include "ffmpegPacketSample.h" #include <boost/foreach.hpp> #include <boost/tokenizer.hpp> extern "C" { #include <libavutil/avutil.h> #include <libavutil/opt.h> #include <libavutil/imgutils.h> } //#include "Utilities\utilitiesImage.h" using namespace Limitless; FfmpegSwScale::FfmpegSwScale(std::string name, SharedMediaFilter parent): MediaAutoRegister(name, parent), m_swsContext(NULL), m_widthChanged(false), m_heightChanged(false), m_formatChanged(false) { addAttribute("width", 0); addAttribute("height", 0); addAttribute("format", "RGB24"); } FfmpegSwScale::~FfmpegSwScale() { } bool FfmpegSwScale::initialize(const Attributes &attributes) { FfmpegResources::instance().registerAll(); m_ffmpegFrameSampleId=MediaSampleFactory::getTypeId("FfmpegFrameSample"); m_imageInterfaceSampleId=MediaSampleFactory::getTypeId("IImageSample"); m_imageSampleId=MediaSampleFactory::getTypeId("ImageSample"); addSinkPad("Sink", "{\"mime\":\"video/raw\"}"); return true; } SharedPluginView FfmpegSwScale::getView() { return SharedPluginView(); // if(m_view == SharedPluginView()) // { // } // return m_view; } bool FfmpegSwScale::processSample(SharedMediaPad sinkPad, SharedMediaSample sample) { if(m_convert) { if(sample->isType(m_ffmpegFrameSampleId)) { SharedFfmpegFrameSample frameSample=boost::dynamic_pointer_cast<FfmpegFrameSample>(sample); if(frameSample == SharedFfmpegFrameSample()) return false; AVFrame *avFrame=frameSample->getFrame(); SharedMediaSample mediaSample=newSample(m_imageSampleId); SharedImageSample imageSample=boost::dynamic_pointer_cast<ImageSample>(mediaSample); FfmpegFormat format=FfmpegResources::getFormat(m_outputInfo.format); imageSample->resize(m_outputInfo.width, m_outputInfo.height, format.channels); uint8_t *rgbaPlane[]={imageSample->buffer()}; int rgbaPitch[]={imageSample->width()*format.channels}; // Limitless::savePGM("swScaleInputImage.pgm", Limitless::GREY, avFrame->data[0], avFrame->linesize[0], avFrame->height); // Log::write((boost::format("SwScale %08x,%08x: %08x -> %08x")%GetCurrentThreadId()%this%(void *)avFrame->data[0]%(void *)imageSample->buffer()).str()); sws_scale(m_swsContext, avFrame->data, avFrame->linesize, 0, avFrame->height, rgbaPlane, rgbaPitch); imageSample->copyHeader(sample, instance()); pushSample(imageSample); } else if(sample->isType(m_imageInterfaceSampleId)) { SharedIImageSample imageSample=boost::dynamic_pointer_cast<IImageSample>(sample); if(!imageSample) return false; SharedImageSample mediaSample=newSampleType<ImageSample>(m_imageSampleId); FfmpegFormat format=FfmpegResources::getFormat(m_outputInfo.format); mediaSample->resize(m_outputInfo.width, m_outputInfo.height, format.channels); uint8_t *srcPlane[]={imageSample->buffer()}; int srcPitch[]={imageSample->width()*format.channels}; uint8_t *dstPlane[]={mediaSample->buffer()}; int dstPitch[]={mediaSample->width()*format.channels}; sws_scale(m_swsContext, srcPlane, srcPitch, 0, m_outputInfo.height, dstPlane, dstPitch); imageSample->copyHeader(sample, instance()); pushSample(imageSample); } else pushSample(sample); } else pushSample(sample); return true; } IMediaFilter::StateChange FfmpegSwScale::onReady() { SharedMediaPads sinkMediaPads=getSinkPads(); if(sinkMediaPads.size() <= 0) return FAILED; return SUCCESS; } IMediaFilter::StateChange FfmpegSwScale::onPaused() { return SUCCESS; } IMediaFilter::StateChange FfmpegSwScale::onPlaying() { return SUCCESS; } bool FfmpegSwScale::onAcceptMediaFormat(SharedMediaPad pad, SharedMediaFormat format) { if(pad->type() == MediaPad::SINK) { if(!format->exists("mime")) return false; MimeDetail mimeDetail=parseMimeDetail(format->attribute("mime")->toString()); if((mimeDetail.type != "video") && (mimeDetail.type != "image")) return false; if((mimeDetail.codec != "raw") && (mimeDetail.codec != "")) return false; return true; } else if(pad->type() == MediaPad::SOURCE) return true; return false; } void FfmpegSwScale::onLinkFormatChanged(SharedMediaPad pad, SharedMediaFormat format) { if(pad->type() == MediaPad::SINK) { if(!format->exists("mime")) return; std::string mime=format->attribute("mime")->toString(); MimeDetail mimeDetail=parseMimeDetail(format->attribute("mime")->toString()); if((mimeDetail.type != "video") && (mimeDetail.type != "image")) return; if((mimeDetail.codec != "raw") && (mimeDetail.codec != "")) return; if(format->exists("width")) m_inputInfo.width=format->attribute("width")->toInt(); if(format->exists("height")) m_inputInfo.height=format->attribute("height")->toInt(); if(format->exists("format")) m_inputInfo.format=format->attribute("format")->toString(); //set output values if not set by user if(!m_widthChanged) setAttribute("width", (int)m_inputInfo.width); // m_outputInfo.width=m_inputInfo.width; if(!m_heightChanged) setAttribute("height", (int)m_inputInfo.height); // m_outputInfo.height=m_inputInfo.height; if(!m_formatChanged) setAttribute("format", m_inputInfo.format); // m_outputInfo.format=m_inputInfo.format; updateScaler(false); } } void FfmpegSwScale::onAttributeChanged(std::string name, SharedAttribute attribute) { bool update=false; if(name == "width") { m_outputInfo.width=attribute->toInt(); if(m_outputInfo.width > 0) m_widthChanged=true; update=true; } if(name == "height") { m_outputInfo.height=attribute->toInt(); if(m_outputInfo.height > 0) m_heightChanged=true; update=true; } if(name == "format") { m_outputInfo.format=attribute->toString(); m_formatChanged=true; update=true; } if(update) updateScaler(); } void FfmpegSwScale::updateScaler(bool checkLink) { m_convert=false; SharedMediaPads sourcePads=getSourcePads(); if(checkLink) { if(sourcePads.empty()) return; bool linked=false; for(SharedMediaPad &sourcePad:sourcePads) { if(sourcePad->linked()) { linked=true; break; } } if(!linked) return; } bool update=false; if(m_outputInfo != m_inputInfo) { AVPixelFormat inputFormat=FfmpegResources::getAvPixelFormat(m_inputInfo.format); AVPixelFormat outputFormat=FfmpegResources::getAvPixelFormat(m_outputInfo.format); m_swsContext=sws_getCachedContext(m_swsContext, m_inputInfo.width, m_inputInfo.height, inputFormat, m_outputInfo.width, m_outputInfo.height, outputFormat, SWS_LANCZOS|SWS_ACCURATE_RND, NULL, NULL, NULL); m_convert=true; } SharedMediaFormat sourceFormat(new MediaFormat()); sourceFormat->addAttribute("mime", "video/raw"); sourceFormat->addAttribute("width", m_outputInfo.width); sourceFormat->addAttribute("height", m_outputInfo.height); sourceFormat->addAttribute("format", m_outputInfo.format); if(sourcePads.empty()) addSourcePad("Source", sourceFormat); else { for(SharedMediaPad &sourcePad:sourcePads) { sourcePad->setFormat(*sourceFormat.get()); } } }
25.324042
155
0.7306
InfiniteInteractive
7aa7e44a7449c151f76a354bcbdd4b68d6780cf8
1,663
hh
C++
src/search.hh
grencez/protocon
0ca25d832f7222f4154507d974bf9213e0cf26d3
[ "0BSD" ]
7
2015-10-16T18:56:01.000Z
2022-01-17T21:19:08.000Z
src/search.hh
czlynn/protocon
aa520f9edf3be7ff458f96e88cd2dab1eec4c505
[ "0BSD" ]
19
2015-09-27T17:37:21.000Z
2021-07-26T06:50:12.000Z
src/search.hh
czlynn/protocon
aa520f9edf3be7ff458f96e88cd2dab1eec4c505
[ "0BSD" ]
1
2020-09-02T22:29:01.000Z
2020-09-02T22:29:01.000Z
#ifndef SEARCH_HH_ #define SEARCH_HH_ #include "cx/synhax.hh" #include "cx/alphatab.hh" #include "cx/table.hh" #include "namespace.hh" class AddConvergenceOpt; class ConflictFamily; class PartialSynthesis; class ProtoconFileOpt; class ProtoconOpt; class SynthesisCtx; bool AddStabilization(vector<uint>& ret_actions, PartialSynthesis& base_inst, const AddConvergenceOpt& opt); bool AddStabilization(Xn::Sys& sys, const AddConvergenceOpt& opt); bool try_order_synthesis(vector<uint>& ret_actions, PartialSynthesis& tape); bool rank_actions (Table< Table<uint> >& act_layers, const Xn::Net& topo, const vector<uint>& candidates, const X::Fmla& xn, const P::Fmla& legit); void oput_conflicts (const ConflictFamily& conflicts, const String& ofilename); void oput_conflicts (const ConflictFamily& conflicts, String ofilename, uint pcidx); bool initialize_conflicts(ConflictFamily& conflicts, Table< FlatSet<uint> >& flat_conflicts, const ProtoconOpt& exec_opt, const AddConvergenceOpt& global_opt, bool do_output); void multi_verify_stabilization (uint i, SynthesisCtx& synctx, vector<uint>& ret_actions, bool& solution_found, const ProtoconFileOpt& infile_opt, const ProtoconOpt& exec_opt, AddConvergenceOpt& opt); bool stabilization_search(vector<uint>& ret_actions, const ProtoconFileOpt& infile_opt, const ProtoconOpt& exec_opt, const AddConvergenceOpt& global_opt); END_NAMESPACE #endif
27.716667
79
0.678292
grencez
7aa89788f5fe20d8ab4751443f22855dbe48aab7
130
cpp
C++
src/drivers/distance_sensor/ll40ls/LidarLiteI2C.cpp
Diksha-agg/Firmware_val
1efc1ba06997d19df3ed9bd927cfb24401b0fe03
[ "BSD-3-Clause" ]
null
null
null
src/drivers/distance_sensor/ll40ls/LidarLiteI2C.cpp
Diksha-agg/Firmware_val
1efc1ba06997d19df3ed9bd927cfb24401b0fe03
[ "BSD-3-Clause" ]
null
null
null
src/drivers/distance_sensor/ll40ls/LidarLiteI2C.cpp
Diksha-agg/Firmware_val
1efc1ba06997d19df3ed9bd927cfb24401b0fe03
[ "BSD-3-Clause" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:d962303659f52f13ea58ddbae625bd8a310a0dc6ef83cc5dfa45ca99a34ed6d4 size 13664
32.5
75
0.884615
Diksha-agg
7aaa233b81c179178b199f72c83c2d66ef249e8a
13,009
cpp
C++
src/core/vl53l1_wait.cpp
rneurink/VL53L1X_FULL_API
ee8097ce27937bdf3b8f08d28fdee7658b4d9039
[ "BSD-3-Clause" ]
2
2020-07-25T20:56:23.000Z
2020-08-25T23:54:21.000Z
src/core/vl53l1_wait.cpp
rneurink/VL53L1X_FULL_API
ee8097ce27937bdf3b8f08d28fdee7658b4d9039
[ "BSD-3-Clause" ]
null
null
null
src/core/vl53l1_wait.cpp
rneurink/VL53L1X_FULL_API
ee8097ce27937bdf3b8f08d28fdee7658b4d9039
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2017, STMicroelectronics - All Rights Reserved * * This file is part of VL53L1 Core and is dual licensed, * either 'STMicroelectronics * Proprietary license' * or 'BSD 3-clause "New" or "Revised" License' , at your option. * ******************************************************************************** * * 'STMicroelectronics Proprietary license' * ******************************************************************************** * * License terms: STMicroelectronics Proprietary in accordance with licensing * terms at www.st.com/sla0081 * * STMicroelectronics confidential * Reproduction and Communication of this document is strictly prohibited unless * specifically authorized in writing by STMicroelectronics. * * ******************************************************************************** * * Alternatively, VL53L1 Core may be distributed under the terms of * 'BSD 3-clause "New" or "Revised" License', in which case the following * provisions apply instead of the ones mentioned above : * ******************************************************************************** * * License terms: BSD 3-clause "New" or "Revised" License. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder 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. * * ******************************************************************************** * */ /** * @file vl53l1_wait.c * * @brief EwokPlus25 low level Driver wait function definition */ #include "vl53l1_ll_def.h" #include "vl53l1_ll_device.h" #include "../platform/vl53l1_platform.h" #include "vl53l1_core.h" #include "vl53l1_silicon_core.h" #include "vl53l1_wait.h" #include "vl53l1_register_settings.h" #define LOG_FUNCTION_START(fmt, ...) \ _LOG_FUNCTION_START(VL53L1_TRACE_MODULE_CORE, fmt, ##__VA_ARGS__) #define LOG_FUNCTION_END(status, ...) \ _LOG_FUNCTION_END(VL53L1_TRACE_MODULE_CORE, status, ##__VA_ARGS__) #define LOG_FUNCTION_END_FMT(status, fmt, ...) \ _LOG_FUNCTION_END_FMT(VL53L1_TRACE_MODULE_CORE, status, \ fmt, ##__VA_ARGS__) VL53L1_Error VL53L1_wait_for_boot_completion( VL53L1_DEV Dev) { /* Waits for firmware boot to finish */ VL53L1_Error status = VL53L1_ERROR_NONE; VL53L1_LLDriverData_t *pdev = VL53L1DevStructGetLLDriverHandle(Dev); uint8_t fw_ready = 0; LOG_FUNCTION_START(""); if (pdev->wait_method == VL53L1_WAIT_METHOD_BLOCKING) { /* blocking version */ status = VL53L1_poll_for_boot_completion( Dev, VL53L1_BOOT_COMPLETION_POLLING_TIMEOUT_MS); } else { /* implement non blocking version below */ fw_ready = 0; while (fw_ready == 0x00 && status == VL53L1_ERROR_NONE) { status = VL53L1_is_boot_complete( Dev, &fw_ready); if (status == VL53L1_ERROR_NONE) { status = VL53L1_WaitMs( Dev, VL53L1_POLLING_DELAY_MS); } } } LOG_FUNCTION_END(status); return status; } VL53L1_Error VL53L1_wait_for_firmware_ready( VL53L1_DEV Dev) { /* If in timed mode or single shot then check firmware is ready * before sending handshake */ VL53L1_Error status = VL53L1_ERROR_NONE; VL53L1_LLDriverData_t *pdev = VL53L1DevStructGetLLDriverHandle(Dev); uint8_t fw_ready = 0; uint8_t mode_start = 0; LOG_FUNCTION_START(""); /* Filter out tje measure mode part of the mode * start register */ mode_start = pdev->sys_ctrl.system__mode_start & VL53L1_DEVICEMEASUREMENTMODE_MODE_MASK; /* * conditional wait for firmware ready * only waits for timed and single shot modes */ if ((mode_start == VL53L1_DEVICEMEASUREMENTMODE_TIMED) || (mode_start == VL53L1_DEVICEMEASUREMENTMODE_SINGLESHOT)) { if (pdev->wait_method == VL53L1_WAIT_METHOD_BLOCKING) { /* blocking version */ status = VL53L1_poll_for_firmware_ready( Dev, VL53L1_RANGE_COMPLETION_POLLING_TIMEOUT_MS); } else { /* implement non blocking version below */ fw_ready = 0; while (fw_ready == 0x00 && status == VL53L1_ERROR_NONE) { status = VL53L1_is_firmware_ready( Dev, &fw_ready); if (status == VL53L1_ERROR_NONE) { status = VL53L1_WaitMs( Dev, VL53L1_POLLING_DELAY_MS); } } } } LOG_FUNCTION_END(status); return status; } VL53L1_Error VL53L1_wait_for_range_completion( VL53L1_DEV Dev) { /* Wrapper function for waiting for range completion */ VL53L1_Error status = VL53L1_ERROR_NONE; VL53L1_LLDriverData_t *pdev = VL53L1DevStructGetLLDriverHandle(Dev); uint8_t data_ready = 0; LOG_FUNCTION_START(""); if (pdev->wait_method == VL53L1_WAIT_METHOD_BLOCKING) { /* blocking version */ status = VL53L1_poll_for_range_completion( Dev, VL53L1_RANGE_COMPLETION_POLLING_TIMEOUT_MS); } else { /* implement non blocking version below */ data_ready = 0; while (data_ready == 0x00 && status == VL53L1_ERROR_NONE) { status = VL53L1_is_new_data_ready( Dev, &data_ready); if (status == VL53L1_ERROR_NONE) { status = VL53L1_WaitMs( Dev, VL53L1_POLLING_DELAY_MS); } } } LOG_FUNCTION_END(status); return status; } VL53L1_Error VL53L1_wait_for_test_completion( VL53L1_DEV Dev) { /* Wrapper function for waiting for test mode completion */ VL53L1_Error status = VL53L1_ERROR_NONE; VL53L1_LLDriverData_t *pdev = VL53L1DevStructGetLLDriverHandle(Dev); uint8_t data_ready = 0; LOG_FUNCTION_START(""); if (pdev->wait_method == VL53L1_WAIT_METHOD_BLOCKING) { /* blocking version */ status = VL53L1_poll_for_range_completion( Dev, VL53L1_TEST_COMPLETION_POLLING_TIMEOUT_MS); } else { /* implement non blocking version below */ data_ready = 0; while (data_ready == 0x00 && status == VL53L1_ERROR_NONE) { status = VL53L1_is_new_data_ready( Dev, &data_ready); if (status == VL53L1_ERROR_NONE) { status = VL53L1_WaitMs( Dev, VL53L1_POLLING_DELAY_MS); } } } LOG_FUNCTION_END(status); return status; } VL53L1_Error VL53L1_is_boot_complete( VL53L1_DEV Dev, uint8_t *pready) { /** * Determines if the firmware finished booting by reading * bit 0 of firmware__system_status register */ VL53L1_Error status = VL53L1_ERROR_NONE; uint8_t firmware__system_status = 0; LOG_FUNCTION_START(""); /* read current range interrupt state */ status = VL53L1_RdByte( Dev, VL53L1_FIRMWARE__SYSTEM_STATUS, &firmware__system_status); /* set *pready = 1 if new range data ready complete * zero otherwise */ if ((firmware__system_status & 0x01) == 0x01) { *pready = 0x01; VL53L1_init_ll_driver_state( Dev, VL53L1_DEVICESTATE_SW_STANDBY); } else { *pready = 0x00; VL53L1_init_ll_driver_state( Dev, VL53L1_DEVICESTATE_FW_COLDBOOT); } LOG_FUNCTION_END(status); return status; } VL53L1_Error VL53L1_is_firmware_ready( VL53L1_DEV Dev, uint8_t *pready) { /** * Determines if the firmware is ready to range */ VL53L1_Error status = VL53L1_ERROR_NONE; VL53L1_LLDriverData_t *pdev = VL53L1DevStructGetLLDriverHandle(Dev); LOG_FUNCTION_START(""); status = VL53L1_is_firmware_ready_silicon( Dev, pready); pdev->fw_ready = *pready; LOG_FUNCTION_END(status); return status; } VL53L1_Error VL53L1_is_new_data_ready( VL53L1_DEV Dev, uint8_t *pready) { /** * Determines if new range data is ready by reading bit 0 of * VL53L1_GPIO__TIO_HV_STATUS to determine the current state * of output interrupt pin */ VL53L1_Error status = VL53L1_ERROR_NONE; VL53L1_LLDriverData_t *pdev = VL53L1DevStructGetLLDriverHandle(Dev); uint8_t gpio__mux_active_high_hv = 0; uint8_t gpio__tio_hv_status = 0; uint8_t interrupt_ready = 0; LOG_FUNCTION_START(""); gpio__mux_active_high_hv = pdev->stat_cfg.gpio_hv_mux__ctrl & VL53L1_DEVICEINTERRUPTLEVEL_ACTIVE_MASK; if (gpio__mux_active_high_hv == VL53L1_DEVICEINTERRUPTLEVEL_ACTIVE_HIGH) interrupt_ready = 0x01; else interrupt_ready = 0x00; /* read current range interrupt state */ status = VL53L1_RdByte( Dev, VL53L1_GPIO__TIO_HV_STATUS, &gpio__tio_hv_status); /* set *pready = 1 if new range data ready complete zero otherwise */ if ((gpio__tio_hv_status & 0x01) == interrupt_ready) *pready = 0x01; else *pready = 0x00; LOG_FUNCTION_END(status); return status; } VL53L1_Error VL53L1_poll_for_boot_completion( VL53L1_DEV Dev, uint32_t timeout_ms) { /** * Polls the bit 0 of the FIRMWARE__SYSTEM_STATUS register to see if * the firmware is ready. */ VL53L1_Error status = VL53L1_ERROR_NONE; LOG_FUNCTION_START(""); /* after reset for the firmware blocks I2C access while * it copies the NVM data into the G02 host register banks * The host must wait the required time to allow the copy * to complete before attempting to read the firmware status */ status = VL53L1_WaitUs( Dev, VL53L1_FIRMWARE_BOOT_TIME_US); if (status == VL53L1_ERROR_NONE) status = VL53L1_WaitValueMaskEx( Dev, timeout_ms, VL53L1_FIRMWARE__SYSTEM_STATUS, 0x01, 0x01, VL53L1_POLLING_DELAY_MS); if (status == VL53L1_ERROR_NONE) VL53L1_init_ll_driver_state(Dev, VL53L1_DEVICESTATE_SW_STANDBY); LOG_FUNCTION_END(status); return status; } VL53L1_Error VL53L1_poll_for_firmware_ready( VL53L1_DEV Dev, uint32_t timeout_ms) { /** * Polls the bit 0 of the FIRMWARE__SYSTEM_STATUS register to see if * the firmware is ready. */ VL53L1_Error status = VL53L1_ERROR_NONE; VL53L1_LLDriverData_t *pdev = VL53L1DevStructGetLLDriverHandle(Dev); uint32_t start_time_ms = 0; uint32_t current_time_ms = 0; int32_t poll_delay_ms = VL53L1_POLLING_DELAY_MS; uint8_t fw_ready = 0; /* calculate time limit in absolute time */ VL53L1_GetTickCount(&start_time_ms); /*lint !e534 ignoring return*/ pdev->fw_ready_poll_duration_ms = 0; /* wait until firmware is ready, timeout reached on error occurred */ while ((status == VL53L1_ERROR_NONE) && (pdev->fw_ready_poll_duration_ms < timeout_ms) && (fw_ready == 0)) { status = VL53L1_is_firmware_ready( Dev, &fw_ready); if (status == VL53L1_ERROR_NONE && fw_ready == 0 && poll_delay_ms > 0) { status = VL53L1_WaitMs( Dev, poll_delay_ms); } /* * Update polling time (Compare difference rather than * absolute to negate 32bit wrap around issue) */ VL53L1_GetTickCount(&current_time_ms); /*lint !e534 ignoring return*/ pdev->fw_ready_poll_duration_ms = current_time_ms - start_time_ms; } if (fw_ready == 0 && status == VL53L1_ERROR_NONE) status = VL53L1_ERROR_TIME_OUT; LOG_FUNCTION_END(status); return status; } VL53L1_Error VL53L1_poll_for_range_completion( VL53L1_DEV Dev, uint32_t timeout_ms) { /** * Polls bit 0 of VL53L1_GPIO__TIO_HV_STATUS to determine * the state of output interrupt pin * * Interrupt may be either active high or active low. Use active_high to * select the required level check */ VL53L1_Error status = VL53L1_ERROR_NONE; VL53L1_LLDriverData_t *pdev = VL53L1DevStructGetLLDriverHandle(Dev); uint8_t gpio__mux_active_high_hv = 0; uint8_t interrupt_ready = 0; LOG_FUNCTION_START(""); gpio__mux_active_high_hv = pdev->stat_cfg.gpio_hv_mux__ctrl & VL53L1_DEVICEINTERRUPTLEVEL_ACTIVE_MASK; if (gpio__mux_active_high_hv == VL53L1_DEVICEINTERRUPTLEVEL_ACTIVE_HIGH) interrupt_ready = 0x01; else interrupt_ready = 0x00; status = VL53L1_WaitValueMaskEx( Dev, timeout_ms, VL53L1_GPIO__TIO_HV_STATUS, interrupt_ready, 0x01, VL53L1_POLLING_DELAY_MS); LOG_FUNCTION_END(status); return status; }
23.271914
80
0.707433
rneurink
7aba39f17e6717500f0cfe709c147d6d13e017dd
29,063
cpp
C++
medusa_control/outer_loops_controllers/path_following/src/ros/PathFollowingServices.cpp
gshubham96/medusa_base
1f6e8776ac115951eea13d227ce8c370abd2ea0e
[ "MIT" ]
null
null
null
medusa_control/outer_loops_controllers/path_following/src/ros/PathFollowingServices.cpp
gshubham96/medusa_base
1f6e8776ac115951eea13d227ce8c370abd2ea0e
[ "MIT" ]
1
2022-02-21T16:50:47.000Z
2022-02-21T16:50:47.000Z
medusa_control/outer_loops_controllers/path_following/src/ros/PathFollowingServices.cpp
gshubham96/medusa_base
1f6e8776ac115951eea13d227ce8c370abd2ea0e
[ "MIT" ]
2
2022-02-02T11:00:14.000Z
2022-03-01T08:42:05.000Z
#include "PathFollowingNode.h" /** * @brief A method for initializing all the services. This method is called by * the constructor of the PathNode class upon creation */ void PathFollowingNode::initializeServices() { ROS_INFO("Initializing Services for PathFollowingNode"); /* Get the service names for starting and stoping the path following */ std::string start_pf_name = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/services/start_pf", "/start_pf"); std::string stop_pf_name = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/services/stop_pf", "/stop_pf"); std::string update_gains_name = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/services/updates_gains_pf", "/update_gains_pf"); /* Get the service names for switching the path following algorithm to use */ std::string set_marcelo_name = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/services/marcelo_pf", "/set_marcelo_pf"); std::string set_aguiar_name = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/services/aguiar_pf", "/set_aguiar_pf"); std::string set_brevik_name = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/services/brevik_pf", "/set_brevik_pf"); std::string set_fossen_name = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/services/fossen_pf", "/set_fossen_pf"); std::string set_romulo_name = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/services/romulo_pf", "/set_romulo_pf"); std::string set_lapierre_name = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/services/lapierre_pf", "/set_lapierre_pf"); std::string set_pramod_name = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/services/pramod_pf", "/set_pramod_pf"); std::string set_samson_name = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/services/samson_pf", "/set_samson_pf"); std::string set_relative_heading_name = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/services/relative_heading_pf", "/set_relative_heading_pf"); /* Get the service name for reseting the virtual target in the path following */ std::string reset_virtual_taget_name = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/services/reset_vt_pf", "/resetVT_pf"); /* Get the service name for waypoint*/ std::string wp_service_name = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/services/wp_standard", "/controls/send_wp_standard"); /* Get the service name for reset_dr*/ std::string reset_dr_service_name = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/services/reset_dr", "/nav/reset_filter_dr"); /* Get the name to reset and set the mode of operation of the path */ std::string reset_path_name = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/services/reset_path"); std::string set_path_mode_name = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/services/set_path_mode"); /* Advertise the services with these names */ this->pf_start_srv_ = this->nh_.advertiseService( start_pf_name, &PathFollowingNode::StartPFService, this); this->pf_stop_srv_ = this->nh_.advertiseService( stop_pf_name, &PathFollowingNode::StopPFService, this); this->pf_update_gains_srv_ = this->nh_.advertiseService( update_gains_name, &PathFollowingNode::UpdateGainsPFService, this); this->pf_relative_heading_srv_ = this->nh_.advertiseService( set_relative_heading_name, &PathFollowingNode::SetRelativeHeadingService, this); this->pf_marcelo_srv_ = this->nh_.advertiseService( set_marcelo_name, &PathFollowingNode::SetMarceloService, this); this->pf_aguiar_srv_ = this->nh_.advertiseService( set_aguiar_name, &PathFollowingNode::SetAguiarService, this); this->pf_brevik_srv_ = this->nh_.advertiseService( set_brevik_name, &PathFollowingNode::SetBrevikService, this); this->pf_fossen_srv_ = this->nh_.advertiseService( set_fossen_name, &PathFollowingNode::SetFossenService, this); this->pf_romulo_srv_ = this->nh_.advertiseService( set_romulo_name, &PathFollowingNode::SetRomuloService, this); this->pf_lapierre_srv_ = this->nh_.advertiseService( set_lapierre_name, &PathFollowingNode::SetLapierreService, this); this->pf_pramod_srv_ = this->nh_.advertiseService( set_pramod_name, &PathFollowingNode::SetPramodService, this); this->pf_samson_srv_ = this->nh_.advertiseService( set_samson_name, &PathFollowingNode::SetSamsonService, this); this->pf_reset_vt_srv_ = this->nh_.advertiseService( reset_virtual_taget_name, &PathFollowingNode::ResetVirtualTargetService, this); /* Setup the waypoint client needed when mission finishes */ this->wp_standard_client_ = nh_.serviceClient<waypoint::sendWpType1>(wp_service_name); /* Setup the reset DeadReckoning client needed when mission finishes */ this->dr_reset_client_ = nh_.serviceClient<std_srvs::Trigger>(reset_dr_service_name); /* Reset the path we are following and set the mode of operation */ this->reset_path_client_ = nh_.serviceClient<dsor_paths::ResetPath>(reset_path_name); this->set_path_mode_client_ = nh_.serviceClient<dsor_paths::SetMode>(set_path_mode_name); } /* Service to start running the path following algorithm that was chosen * previously */ bool PathFollowingNode::StartPFService(path_following::StartPF::Request &req, path_following::StartPF::Response &res) { /* Check if we have a path following algorithm allocated. If so, start the * timer callbacks */ if (this->pf_algorithm_ != nullptr) { /* Update the last time the iteration of the path following run */ this->prev_time_ = ros::Time::now(); this->timer_.start(); res.success = true; /* Publish the code that simbolizes that path following has started */ MedusaGimmicks::publishValue<std_msgs::Int8, const int>(this->flag_pub_, FLAG_PF); /* Run the first iteration of the algorithm */ this->pf_algorithm_->start(); /* Inform the user the path following algorithm will start */ ROS_INFO("Path Following is starting."); return true; } /* If there is not object for path following allocated, then print message to * console */ ROS_WARN("There is not path following method allocated. Please restart the " "node or set the PF to use."); res.success = false; return true; } /* Service to stop the path following algorithm that was running */ bool PathFollowingNode::StopPFService(path_following::StopPF::Request &req, path_following::StopPF::Response &res) { /* Stop the path following only if it was already running */ if (this->timer_.hasStarted()) { /* Publish the code that simbolizes idle mode */ MedusaGimmicks::publishValue<std_msgs::Int8, const int>(this->flag_pub_, FLAG_IDLE); } /* Return success */ res.success = true; return true; } /* Service to reset the virtual target value */ bool PathFollowingNode::ResetVirtualTargetService(path_following::ResetVT::Request &req, path_following::ResetVT::Response &res) { /* Check if we have a path following algorithm instantiated */ if(this->pf_algorithm_ == nullptr) { res.success = false; return true; } /* Reset the virtual target */ res.success = this->pf_algorithm_->resetVirtualTarget((float) req.value); return true; } /* Servce to update the gains of the path following algorithms live */ bool PathFollowingNode::UpdateGainsPFService( path_following::UpdateGainsPF::Request &req, path_following::UpdateGainsPF::Response &res) { /* Get the new gains */ std::vector<double> new_gains = req.gains; /* Pass the new gains for the controller */ if (this->pf_algorithm_ != nullptr) { /* Try to update the gains */ bool result = this->pf_algorithm_->setPFGains(new_gains); /* Inform the user if the new gains were accepted or not */ if (result == true) { ROS_INFO("Gains updated successfully!"); } else { ROS_INFO("Gains not accepted!"); } /* Update the response message */ res.success = result; return true; } /* If the path following algorithm object is not allocated, some error ocurred * and we need to restart this node */ ROS_WARN("There is not path following method allocated. Please restart the " "node or set the PF to use."); res.success = false; return true; } /* Service to switch to the RelativeHeading Path Following method */ bool PathFollowingNode::SetRelativeHeadingService(path_following::SetPF::Request &req, path_following::SetPF::Response &res) { /* Don't change if the algorithm is running */ if (this->timer_.hasStarted()) { ROS_INFO("Can't change algorithm when PF is running."); res.success = false; return true; } /* Clear the memory used by the previous controller */ this->deleteCurrentController(); /* Get the topic names for the publishers */ std::string surge_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/surge"); std::string sway_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/sway"); std::string yaw_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/yaw"); std::string rabbit_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/rabbit"); std::string pfollowing_debug_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/pfollowing_debug"); /* Create the publishers for the node */ this->publishers_.push_back(nh_.advertise<std_msgs::Float64>(surge_topic, 1)); this->publishers_.push_back(nh_.advertise<std_msgs::Float64>(sway_topic, 1)); this->publishers_.push_back(nh_.advertise<std_msgs::Float64>(yaw_topic, 1)); this->publishers_.push_back(nh_.advertise<std_msgs::Float64>(rabbit_topic, 1)); /* Read the control gains from the parameter server */ double kx, ky, kz, yaw_offset; std::vector<double> p_sat; try { /* Read the gains for the controller */ nh_p_.getParam("controller_gains/relative_heading/kx", kx); nh_p_.getParam("controller_gains/relative_heading/ky", ky); nh_p_.getParam("controller_gains/relative_heading/kz", kz); nh_p_.getParam("controller_gains/relative_heading/yaw_offset", yaw_offset); nh_p_.getParam("controller_gains/relative_heading/p_sat", p_sat); /* Assign the new controller */ this->pf_algorithm_ = new RelativeHeading(kx, ky, kz, Eigen::Vector2d(p_sat.data()), yaw_offset, this->publishers_[0], this->publishers_[1], this->publishers_[2], this->publishers_[3]); /* Path the debug variables publisher to the class*/ pf_algorithm_->setPFollowingDebugPublisher(nh_p_.advertise<medusa_msgs::mPFollowingDebug>(pfollowing_debug_topic,1)); /* Return success */ res.success = true; } catch (...) { ROS_WARN("Some error occured. Please reset the PF node for safety"); res.success = false; return false; } /* Return success */ ROS_INFO("PF controller switched to RelativeHeading"); return true; } /* Service to switch to the Marcelo Path Following method */ bool PathFollowingNode::SetMarceloService(path_following::SetPF::Request &req, path_following::SetPF::Response &res) { /* Don't change if the algorithm is running */ if (this->timer_.hasStarted()) { ROS_INFO("Can't change algorithm when PF is running."); res.success = false; return true; } /* Clear the memory used by the previous controller */ this->deleteCurrentController(); /* Get the topic names for the publishers */ std::string surge_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/surge"); std::string yaw_rate_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/yaw_rate"); std::string rabbit_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/rabbit"); std::string pfollowing_debug_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/pfollowing_debug"); std::string observer_x_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/observer/x"); std::string observer_y_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/observer/y"); /* Create the publishers for the node */ this->publishers_.push_back(nh_.advertise<std_msgs::Float64>(surge_topic, 1)); this->publishers_.push_back( nh_.advertise<std_msgs::Float64>(yaw_rate_topic, 1)); this->publishers_.push_back( nh_.advertise<std_msgs::Float64>(rabbit_topic, 1)); this->publishers_.push_back( nh_.advertise<std_msgs::Float64>(observer_x_topic, 1)); this->publishers_.push_back( nh_.advertise<std_msgs::Float64>(observer_y_topic, 1)); double delta, kz; double kk[2]; double k_pos; double k_currents; std::vector<double> rd; std::vector<double> d; try { /* Read the gains for the controller */ nh_p_.getParam("controller_gains/marcelo/delta", delta); nh_p_.getParam("controller_gains/marcelo/kx", kk[0]); nh_p_.getParam("controller_gains/marcelo/ky", kk[1]); nh_p_.getParam("controller_gains/marcelo/kz", kz); nh_p_.getParam("controller_gains/marcelo/k_pos", k_pos); nh_p_.getParam("controller_gains/marcelo/k_currents", k_currents); nh_p_.getParam("controller_gains/marcelo/rd", rd); nh_p_.getParam("controller_gains/marcelo/d", d); /* Assign the new controller */ this->pf_algorithm_ = new Marcelo(delta, kk, kz, k_pos, k_currents, rd.data(), d.data(), this->publishers_[0], this->publishers_[1], this->publishers_[2], this->publishers_[3], this->publishers_[4]); pf_algorithm_->setPFollowingDebugPublisher(nh_p_.advertise<medusa_msgs::mPFollowingDebug>(pfollowing_debug_topic,1)); res.success = true; } catch (...) { ROS_WARN("Some error occured. Please reset the PF node for safety"); res.success = false; return false; } /* Return success */ ROS_INFO("PF controller switched to Marcelo"); return true; } /* Service to switch to the Aguiar Path Following method */ bool PathFollowingNode::SetAguiarService(path_following::SetPF::Request &req, path_following::SetPF::Response &res) { /* Don't change if the algorithm is running */ if (this->timer_.hasStarted()) { ROS_INFO("Can't change algorithm when PF is running."); res.success = false; return true; } /* Clear the memory used by the previous controller */ this->deleteCurrentController(); /* Get the topic names for the publishers */ std::string surge_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/surge"); std::string yaw_rate_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/yaw_rate"); std::string rabbit_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/rabbit"); std::string pfollowing_debug_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/pfollowing_debug"); /* Create the publishers for the node */ this->publishers_.push_back(nh_.advertise<std_msgs::Float64>(surge_topic, 1)); this->publishers_.push_back( nh_.advertise<std_msgs::Float64>(yaw_rate_topic, 1)); this->publishers_.push_back( nh_.advertise<std_msgs::Float64>(rabbit_topic, 1)); double delta, kz; double kk[2]; double k_pos; double k_currents; try { /* Read the gains for the controller */ nh_p_.getParam("controller_gains/aguiar/delta", delta); nh_p_.getParam("controller_gains/aguiar/kx", kk[0]); nh_p_.getParam("controller_gains/aguiar/ky", kk[1]); nh_p_.getParam("controller_gains/aguiar/kz", kz); nh_p_.getParam("controller_gains/aguiar/k_pos", k_pos); nh_p_.getParam("controller_gains/aguiar/k_currents", k_currents); /* Assign the new controller */ this->pf_algorithm_ = new Aguiar(delta, kk, kz, k_pos, k_currents, this->publishers_[0], this->publishers_[1], this->publishers_[2]); pf_algorithm_->setPFollowingDebugPublisher(nh_p_.advertise<medusa_msgs::mPFollowingDebug>(pfollowing_debug_topic,1)); res.success = true; } catch (...) { ROS_WARN("Some error occured. Please reset the PF node for safety"); res.success = false; return false; } /* Return success */ ROS_INFO("PF controller switched to Aguiar"); return true; } /* Service to switch to the Brevik Path Following method */ bool PathFollowingNode::SetBrevikService(path_following::SetPF::Request &req, path_following::SetPF::Response &res) { /* Don't change if the algorithm is running */ if (this->timer_.hasStarted()) { ROS_INFO("Can't change algorithm when PF is running."); res.success = false; return true; } /* Clear the memory used by the previous controller */ this->deleteCurrentController(); /* Get the topic names for the publishers */ std::string surge_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/surge"); std::string yaw_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/yaw"); std::string rabbit_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/rabbit"); std::string pfollowing_debug_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/pfollowing_debug"); /* Create the publishers for the node */ this->publishers_.push_back(nh_.advertise<std_msgs::Float64>(surge_topic, 1)); this->publishers_.push_back( nh_.advertise<std_msgs::Float64>(yaw_topic, 1)); this->publishers_.push_back( nh_.advertise<std_msgs::Float64>(rabbit_topic, 1)); try { /* Assign the new controller */ this->pf_algorithm_ = new Brevik(this->publishers_[0], this->publishers_[1], this->publishers_[2]); res.success = true; pf_algorithm_->setPFollowingDebugPublisher(nh_p_.advertise<medusa_msgs::mPFollowingDebug>(pfollowing_debug_topic,1)); } catch (...) { ROS_WARN("Some error occured. Please reset the PF node for safety"); res.success = false; return false; } /* Return success */ ROS_INFO("PF controller switched to Brevik"); return true; } /* Service to switch to the Fossen Path Following method */ bool PathFollowingNode::SetFossenService(path_following::SetPF::Request &req, path_following::SetPF::Response &res) { /* Don't change if the algorithm is running */ if (this->timer_.hasStarted()) { ROS_INFO("Can't change algorithm when PF is running."); res.success = false; return true; } /* Clear the memory used by the previous controller */ this->deleteCurrentController(); /* Get the topic names for the publishers */ std::string surge_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/surge"); std::string yaw_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/yaw"); std::string pfollowing_debug_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/pfollowing_debug"); /* Create the publishers for the node */ this->publishers_.push_back(nh_.advertise<std_msgs::Float64>(surge_topic, 1)); this->publishers_.push_back(nh_.advertise<std_msgs::Float64>(yaw_topic, 1)); try { /* Assign the new controller */ this->pf_algorithm_ = new Fossen(this->publishers_[0], this->publishers_[1], this->set_path_mode_client_); res.success = true; pf_algorithm_->setPFollowingDebugPublisher(nh_p_.advertise<medusa_msgs::mPFollowingDebug>(pfollowing_debug_topic,1)); } catch (...) { ROS_WARN("Some error occured. Please reset the PF node for safety"); res.success = false; return false; } /* Return success */ ROS_INFO("PF controller switched to Fossen. This algorithm uses the path closest point to make the computations"); return true; } /* Service to switch to the Romulo Path Following method */ bool PathFollowingNode::SetRomuloService( path_following::SetPF::Request &req, path_following::SetPF::Response &res) { /* Don't change if the algorithm is running */ if (this->timer_.hasStarted()) { ROS_INFO("Can't change algorithm when PF is running."); res.success = false; return true; } /* Clear the memory used by the previous controller */ this->deleteCurrentController(); /* Get the topic names for the publishers */ std::string surge_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/surge"); std::string sway_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/sway"); std::string rabbit_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/rabbit"); std::string pfollowing_debug_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/pfollowing_debug"); /* Create the publishers for the node */ this->publishers_.push_back(nh_.advertise<std_msgs::Float64>(surge_topic, 1)); this->publishers_.push_back(nh_.advertise<std_msgs::Float64>(sway_topic, 1)); this->publishers_.push_back( nh_.advertise<std_msgs::Float64>(rabbit_topic, 1)); /* Variables to store the gains of the controller */ std::vector<double> controller_gains; double kz; try { /* Read the gains for the controller */ nh_p_.getParam("controller_gains/romulo/ke", controller_gains); nh_p_.getParam("controller_gains/romulo/kz", kz); controller_gains.push_back(kz); /* Assign the new controller */ this->pf_algorithm_ = new Romulo(controller_gains, this->publishers_[0], this->publishers_[1], this->publishers_[2]); res.success = true; pf_algorithm_->setPFollowingDebugPublisher(nh_p_.advertise<medusa_msgs::mPFollowingDebug>(pfollowing_debug_topic,1)); } catch (...) { ROS_WARN("Some error occured. Please reset the PF node for safety"); res.success = false; return false; } /* Return success */ ROS_INFO("PF controller switched to Romulo"); return true; } /* Service to switch to the Lapierre Path Following method */ bool PathFollowingNode::SetLapierreService( path_following::SetPF::Request &req, path_following::SetPF::Response &res) { /* Don't change if the algorithm is running */ if (this->timer_.hasStarted()) { ROS_INFO("Can't change algorithm when PF is running."); res.success = false; return true; } /* Clear the memory used by the previous controller */ this->deleteCurrentController(); /* Get the topic names for the publishers */ std::string surge_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/surge"); std::string yaw_rate_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/yaw_rate"); std::string rabbit_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/rabbit"); std::string pfollowing_debug_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/pfollowing_debug"); /* Create the publishers for the node */ this->publishers_.push_back(nh_.advertise<std_msgs::Float64>(surge_topic, 1)); this->publishers_.push_back( nh_.advertise<std_msgs::Float64>(yaw_rate_topic, 1)); this->publishers_.push_back( nh_.advertise<std_msgs::Float64>(rabbit_topic, 1)); /* Variables to store the gains of the controller */ double k1, k2, k3, theta, k_delta; try { /* Read the gains for the controller */ nh_p_.getParam("controller_gains/lapierre/k1", k1); nh_p_.getParam("controller_gains/lapierre/k2", k2); nh_p_.getParam("controller_gains/lapierre/k3", k3); nh_p_.getParam("controller_gains/lapierre/theta", theta); nh_p_.getParam("controller_gains/lapierre/k_delta", k_delta); /* Assign the new controller */ this->pf_algorithm_ = new Lapierre(k1, k2, k3, theta, k_delta, this->publishers_[0], this->publishers_[1], this->publishers_[2]); pf_algorithm_->setPFollowingDebugPublisher(nh_p_.advertise<medusa_msgs::mPFollowingDebug>(pfollowing_debug_topic,1)); res.success = true; } catch (...) { ROS_WARN("Some error occured. Please reset the PF node for safety"); res.success = false; return false; } /* Return success */ ROS_INFO("PF controller switched to Lapierre"); return true; } /* Service to switch to the Pramod Path Following method */ bool PathFollowingNode::SetPramodService(path_following::SetPF::Request &req, path_following::SetPF::Response &res) { /* Don't change if the algorithm is running */ if (this->timer_.hasStarted()) { ROS_INFO("Can't change algorithm when PF is running."); res.success = false; return true; } /* Clear the memory used by the previous controller */ this->deleteCurrentController(); std::string surge_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/surge"); std::string yaw_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/yaw"); std::string pfollowing_debug_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/pfollowing_debug"); /* Create the publishers for the node */ this->publishers_.push_back(nh_.advertise<std_msgs::Float64>(surge_topic, 1)); this->publishers_.push_back(nh_.advertise<std_msgs::Float64>(yaw_topic, 1)); /* Variables to store the gains of the controller */ double kp, kd; std::vector<double> controller_gains; try { /* Read the gains for the controller */ nh_p_.getParam("controller_gains/pramod/kp", kp); nh_p_.getParam("controller_gains/pramod/kd", kd); controller_gains.push_back(kp); controller_gains.push_back(kd); /* Assign the new controller */ this->pf_algorithm_ = new Pramod(controller_gains, this->publishers_[0], this->publishers_[1], this->set_path_mode_client_); pf_algorithm_->setPFollowingDebugPublisher(nh_p_.advertise<medusa_msgs::mPFollowingDebug>(pfollowing_debug_topic,1)); res.success = true; } catch (...) { ROS_WARN("Some error occured. Please reset the PF node for safety"); res.success = false; return false; } /* Return success */ ROS_INFO("PF controller switched to Pramod. This algorithm uses the path closest point to make the computations"); return true; } /* Service to switch to the Samson Path Following method */ bool PathFollowingNode::SetSamsonService(path_following::SetPF::Request &req, path_following::SetPF::Response &res) { /* Don't change if the algorithm is running */ if (this->timer_.hasStarted()) { ROS_INFO("Can't change algorithm when PF is running."); res.success = false; return true; } /* Clear the memory used by the previous controller */ this->deleteCurrentController(); std::string surge_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/surge"); std::string yaw_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/yaw_rate"); std::string pfollowing_debug_topic = MedusaGimmicks::getParameters<std::string>( this->nh_p_, "topics/publishers/pfollowing_debug"); /* Create the publishers for the node */ this->publishers_.push_back(nh_.advertise<std_msgs::Float64>(surge_topic, 1)); this->publishers_.push_back(nh_.advertise<std_msgs::Float64>(yaw_topic, 1)); /* Variables to store the gains of the controller */ double k1, k2, k3, theta, k_delta; try { /* Read the gains for the controller */ nh_p_.getParam("controller_gains/samson/k1", k1); nh_p_.getParam("controller_gains/samson/k2", k2); nh_p_.getParam("controller_gains/samson/k3", k3); nh_p_.getParam("controller_gains/samson/theta", theta); nh_p_.getParam("controller_gains/samson/k_delta", k_delta); /* Assign the new controller */ this->pf_algorithm_ = new Samson(k1, k2, k3, theta, k_delta, this->publishers_[0], this->publishers_[1], this->set_path_mode_client_); pf_algorithm_->setPFollowingDebugPublisher(nh_p_.advertise<medusa_msgs::mPFollowingDebug>(pfollowing_debug_topic,1)); res.success = true; } catch (...) { ROS_WARN("Some error occured. Please reset the PF node for safety"); res.success = false; return false; } /* Return success */ ROS_INFO("PF controller switched to Samson. This algorithm uses the path closest point to make the computations"); return true; }
40.03168
193
0.714861
gshubham96
7abbbfc26107ee06e39ebdfdbf50df1d2c5338e6
10,495
cpp
C++
src/server.cpp
xiangp126/p2p_communication
8ec3eb546fa4ba36876ba1e3158d98ffb9b1891f
[ "MIT" ]
null
null
null
src/server.cpp
xiangp126/p2p_communication
8ec3eb546fa4ba36876ba1e3158d98ffb9b1891f
[ "MIT" ]
null
null
null
src/server.cpp
xiangp126/p2p_communication
8ec3eb546fa4ba36876ba1e3158d98ffb9b1891f
[ "MIT" ]
null
null
null
#include <iostream> #include "common.h" #include "server.h" pthread_mutex_t ticksLock; pthread_mutexattr_t tickLockAttr; using namespace std; static ofstream logFile(LOGNAME, ofstream::app); ostream & operator<<(ostream &out, PEERTICKTYPE &clientMap) { out << "----------->>> List" << endl; auto iter = clientMap.begin(); for (; iter != clientMap.end(); ++iter) { out << " " << iter->first.ip << ":" << iter->first.port; out << endl; } out << "<<< ---------------" << endl; return out; } ostream & operator<<(ostream &out, PEERPUNCHEDTYPE &hashMap) { out << "----------->>> List" << endl; auto iter = hashMap.begin(); for (; iter != hashMap.end(); ++iter) { } out << "<<< ---------------" << endl; return out; } /* unordered_map remove duplicate items */ void addClient(PEERTICKTYPE &clientMap, const PeerInfo &peer) { pthread_mutex_lock(&ticksLock); clientMap[peer].tick = TICKS_INI; pthread_mutex_unlock(&ticksLock); return; } void delClient(PEERTICKTYPE &clientMap, const PeerInfo &peer) { pthread_mutex_lock(&ticksLock); auto iterFind = clientMap.find(peer); if (iterFind != clientMap.end()) { clientMap.erase(iterFind); } else { write2Log(logFile, "delete peer error: did not found."); } pthread_mutex_unlock(&ticksLock); return; } /* till now, did not use this function. */ void setReentrant(pthread_mutex_t &lock, pthread_mutexattr_t &attr) { pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&lock, &attr); return; } void listInfo2Str(PEERTICKTYPE &clientMap, PEERPUNCHEDTYPE &punchMap, char *msg) { ostringstream oss; ostringstream pOss; string ip, port; oss << "\n-------------------------- *** Login Info\n" << std::left << std::setfill(' ') << " " << setw(21) << "PEERINFO-IP-PORT" << " " << setw(3) << "TTL" << " " << setw(8) << "HOSTNAME\n"; pthread_mutex_lock(&ticksLock); auto iter1 = clientMap.begin(); for (; iter1 != clientMap.end(); ++iter1) { /* reformat port ip layout: 127.0.0.1 13000. */ ip = iter1->first.ip; ip.push_back(' '); /* clear str of pOss, notice that function pOss.clear() * only reset the iostat. */ pOss.str(""); pOss.clear(); pOss << iter1->first.port; port = pOss.str(); ip += port; oss << " " << setw(21) << ip << " " << setw(3) << iter1->second.tick << " " << iter1->second.hostname << "\n"; } oss << "*** --------------------------------------" << "\n"; oss << "\n-------------------------- *** Punch Info\n"; auto iter2 = punchMap.begin(); for (; iter2 != punchMap.end(); ++iter2) { oss << " " << iter2->first.ip << " " << iter2->first.port << " " << " ===>> " << " " << iter2->second.ip << " " << iter2->second.port << "\n"; } pthread_mutex_unlock(&ticksLock); oss << "*** --------------------------------------" << endl; memset(msg, 0, IBUFSIZ); strcpy(msg, oss.str().c_str()); return; } void *handleTicks(void *arg) { PEERTICKTYPE *hashMap = (PEERTICKTYPE *)arg; while (1) { pthread_mutex_lock(&ticksLock); /* Erasing an element of a map invalidates iterators pointing * to that element (after all that element has been deleted). * You shouldn't reuse that iterator, instead, advance the * iterator to the next element before the deletion takes place. */ auto iter = hashMap->begin(); #if 0 cout << "########## Enter --iter->second" << endl; #endif while (iter != hashMap->end()) { --(iter->second).tick; if ((iter->second).tick < 0) { PeerInfo peer = iter->first; hashMap->erase(iter++); #if 1 /* check if punchMap still has this timeout info. */ cout << "############################### Delete It" << endl; auto iterFind = punchMap.find(peer); if (iterFind != punchMap.end()) { cout << "Found Timeout Peer: " << peer << endl; cout << "#######################################" << endl; punchMap.erase(iterFind); } #endif } else { ++iter; } } pthread_mutex_unlock(&ticksLock); /* sleep 1 s before next lock action. sleep some time is must.*/ sleep(1); } return NULL; } void onCalled(int sockFd, PEERTICKTYPE &clientMap, PktInfo &packet, PeerInfo &peer) { char message[IBUFSIZ]; memset(message, 0, IBUFSIZ); ssize_t recvSize = udpRecvPkt(sockFd, peer, packet); PKTTYPE type = packet.getHead().type; switch (type) { case PKTTYPE::MESSAGE: { /* check if peer has punched pair. */ cout << "Message From " << peer << ". " << endl; pthread_mutex_lock(&ticksLock); auto iterFind = punchMap.find(peer); if (iterFind != punchMap.end()) { /* TYPE SYN inform peer to fetch getHead().peer info * from NET packet in addition with peer info. */ packet.getHead().type = PKTTYPE::SYN; packet.getHead().peer = peer; udpSendPkt(sockFd, punchMap[peer], packet); } pthread_mutex_unlock(&ticksLock); break; } case PKTTYPE::HEARTBEAT: { pthread_mutex_lock(&ticksLock); clientMap[peer].tick = TICKS_INI; /* fix bug: under some uncertein circumstance handleTicks() * will stop minus 'tick', so use upper code replacing below, * seems work good. */ #if 0 auto iterFind = clientMap.find(peer); if (iterFind != clientMap.end()) { (iterFind->second).tick = TICKS_INI; } else { /* reentrant lock. */ addClient(clientMap, peer); } #endif pthread_mutex_unlock(&ticksLock); cout << "Heart Beat Received From " << peer << endl; break; } case PKTTYPE::LOGIN: { addClient(clientMap, peer); cout << peer << " login." << endl; break; } case PKTTYPE::LOGOUT: { delClient(clientMap, peer); #if 1 /* check if punchMap still has this timeout info. */ pthread_mutex_lock(&ticksLock); cout << "############################### Delete It" << endl; auto iterFind = punchMap.find(peer); if (iterFind != punchMap.end()) { cout << "Found To Delete Peer: " << peer << endl; cout << "#######################################" << endl; punchMap.erase(iterFind); } pthread_mutex_unlock(&ticksLock); #endif cout << peer << " logout." << endl; break; } case PKTTYPE::LIST: { listInfo2Str(clientMap, punchMap, message); makePacket(message, packet, PKTTYPE::MESSAGE); udpSendPkt(sockFd, peer, packet); break; } case PKTTYPE::PUNCH: { PeerInfo tPeer = packet.getHead().peer; cout << "From " << peer << " To " << tPeer << endl; /* check if both peer and tPeer has logined. */ pthread_mutex_lock(&ticksLock); auto iterFind = clientMap.find(peer); auto pFind = clientMap.find(tPeer); if ((iterFind == clientMap.end()) || (pFind == clientMap.end())) { strcpy(message, "First, You Two Must All Be Logined.\ \nJust Type 'list' to See Info."); makePacket(message, packet, PKTTYPE::ERROR); udpSendPkt(sockFd, peer, packet); break; } packet.getHead().peer = peer; /* add to punchMap */ punchMap[peer] = tPeer; punchMap[tPeer] = peer; cout << punchMap << endl; pthread_mutex_unlock(&ticksLock); /* notice the punched peer. */ udpSendPkt(sockFd, tPeer, packet); break; } case PKTTYPE::SYN: { cout << "From " << peer << endl; break; } case PKTTYPE::ACK: { break; } case PKTTYPE::WHOAMI: { makePacket(message, packet, PKTTYPE::WHOAMI); packet.getHead().peer = peer; udpSendPkt(sockFd, peer, packet); break; } case PKTTYPE::SETNAME: { /* get hostname sent by client and set it to TickInfo. */ getSetHostName(clientMap, peer, packet.getPayload()); break; } default: break; } #if 1 cout << packet << "\n" << endl; #endif return; } void getSetHostName(PEERTICKTYPE &clientMap, PeerInfo &peer, char *payload) { char fWord[MAXHOSTLEN]; #if 0 cout << "####### payload ****" << payload << endl; #endif int cnt = 0; char *pTmp = payload; char *pSet = fWord; /* skip first command word till encountere a blank space. */ while ((*pTmp != ' ') && (cnt < MAXHOSTLEN - 1)) { ++pTmp; ++cnt; } /* while (*pTmp++ == ' '); * will omit the first character of hostname. BUG * */ while (*pTmp == ' ') { ++pTmp; } cnt = 0; while ((*pTmp != '\0') && (cnt < MAXHOSTLEN - 1)) { *pSet = *pTmp; ++pSet; ++pTmp; ++cnt; } fWord[cnt] = '\0'; strncpy(clientMap[peer].hostname, fWord, MAXHOSTLEN - 1); return; }
32.391975
78
0.471558
xiangp126
7ac01e8914174a0a35459daf870a7b216cc715e8
261
hpp
C++
src/Arrays.hpp
jaimedelacruz/depthOptimizer
4845cc2d2c81c98c5d905da3fcb057c4e76ee8e9
[ "MIT" ]
1
2019-01-27T14:54:10.000Z
2019-01-27T14:54:10.000Z
Arrays.hpp
jaimedelacruz/Arrays
83175d8a412962a0321cb58a74707c43b11ff5b3
[ "MIT" ]
null
null
null
Arrays.hpp
jaimedelacruz/Arrays
83175d8a412962a0321cb58a74707c43b11ff5b3
[ "MIT" ]
null
null
null
#ifndef ARRAYS_H #define ARRAYS_H #include "Arrays/Arrays_macros.hpp" #include "Arrays/Arrays_mem.hpp" #include "Arrays/Arrays_traits.hpp" #include "Arrays/Arrays_internal.hpp" #include "Arrays/Arrays_dense.hpp" #include "Arrays/Arrays_expression.hpp" #endif
21.75
39
0.800766
jaimedelacruz
7ac37c027b3b35973dbda5db8a45838a67b61889
876
cc
C++
Functions/reading-ifstream.cc
ULL-ESIT-IB-2021-2022/IB-class-code-examples
c17bad34c66bdc4f73862fc92ee929de9a207486
[ "MIT" ]
6
2021-11-01T19:35:17.000Z
2022-01-14T18:13:53.000Z
Functions/reading-ifstream.cc
ULL-ESIT-IB-2021-2022/IB-class-code-examples
c17bad34c66bdc4f73862fc92ee929de9a207486
[ "MIT" ]
null
null
null
Functions/reading-ifstream.cc
ULL-ESIT-IB-2021-2022/IB-class-code-examples
c17bad34c66bdc4f73862fc92ee929de9a207486
[ "MIT" ]
6
2021-10-30T19:04:31.000Z
2022-03-11T19:29:32.000Z
/** * Universidad de La Laguna * Escuela Superior de Ingeniería y Tecnología * Grado en Ingeniería Informática * Informática Básica * * @author F. de Sande * @date 23 Jun 2020 * @brief I/O Reading from ifstream * * @see https://en.cppreference.com/w/cpp/io/manip */ #include <fstream> // For the file streams #include <iostream> #include <string> using namespace std; // Saving space int main() { int my_var1; double my_var2, my_var3; string my_string; // Create an input file stream ifstream input_file{"test_cols.txt", ios_base::in}; // Read data, until it is there while (input_file >> my_var1 >> my_var2 >> my_string >> my_var3) { cout << my_var1 << ", " << my_var2 << ", " << my_string << ", " << my_var3 << endl; } return (0); } // Content of the test_cols.txt file // 1 2.34 One 0.21 // 2 2.004 two 0.23 // 3 -2.34 string 0.22
22.461538
87
0.649543
ULL-ESIT-IB-2021-2022
7ac3d3fdfacd6041fe03c97acf4e8cb79441e28c
3,541
cpp
C++
Vandevoorde/Rozdzial 06/6.16-atoi.cpp
antonitomaszewski/Jezyk-C-
596b5f3add6698ffee3a485a727db3b6e3cf5b0a
[ "MIT" ]
null
null
null
Vandevoorde/Rozdzial 06/6.16-atoi.cpp
antonitomaszewski/Jezyk-C-
596b5f3add6698ffee3a485a727db3b6e3cf5b0a
[ "MIT" ]
null
null
null
Vandevoorde/Rozdzial 06/6.16-atoi.cpp
antonitomaszewski/Jezyk-C-
596b5f3add6698ffee3a485a727db3b6e3cf5b0a
[ "MIT" ]
null
null
null
/* NIEROZUMIEM */ #include <iostream> #include <stdexcept> #include <string> #include <limits> using std::domain_error; using std::range_error; using std::string; namespace { /* NIEROZUMIEM */ inline int cyfra (char c, int podstawa) { int wartosc; switch (c) { case '0': wartosc = 0; break; case '1': wartosc = 1; break; case '2': wartosc = 2; break; case '3': wartosc = 3; break; case '4': wartosc = 4; break; case '5': wartosc = 5; break; case '6': wartosc = 6; break; case '7': wartosc = 7; break; case '8': wartosc = 8; break; case '9': wartosc = 9; break; case 'a': case 'A': wartosc = 10; break; case 'b': case 'B': wartosc = 11; break; case 'c': case 'C': wartosc = 12; break; case 'd': case 'D': wartosc = 13; break; case 'e': case 'E': wartosc = 14; break; case 'f': case 'F': wartosc = 15; break; default: throw domain_error(string("niepoprawna cyfra")); } if (wartosc >= podstawa) throw domain_error(string("niepoprawna cyfra")); return wartosc; } /* NIEROZUMIEM */ inline char nastepny_znak(const char *&p) { if (*p != '\\') // \ ma specjalne znaczenie; więc '\\' return *(p++); else { // 3 cyfry ósemkowe: int wartosc_znaku = cyfra(p[1], 8) * 64 + cyfra(p[2], 8) * 8 + cyfra(p[3], 8); if (wartosc_znaku > std::numeric_limits<char>::max() or wartosc_znaku < std::numeric_limits<char>::min()) throw domain_error (string ("nie znak")); p += 4; // odwrtotny ukośnik i 3 cyfry ósemkowe return wartosc_znaku; } } void pobierz_pierwsza_cyfre(const char *&s, int &wartosc, bool &jest_ujemne, int &podstawa) { char c1 = nastepny_znak(s); jest_ujemne = (c1 == '-'); if (c1 == '-' || c1 == '+') c1 = nastepny_znak(s); if (c1 == '\0') { // "", "-" i "+" są niepoprawne throw domain_error(string("niepoprawne wejście")); } else if (c1 != '0') { podstawa = 10; } else { const char *p = s; char c2 = nastepny_znak(p); if (c2 == 'x' || c2 == 'X') { // "0x..."? podstawa = 16; s = p; c1 = nastepny_znak(s); } else { // c2 != 'x' && c2 != 'X' podstawa = 8; // Nawet "0" jest traktowane jako ósemkowe } } wartosc = cyfra(c1, podstawa); } } // Koniec nienazwanej przestrzeni nazw (funkcje pomocnicze) int atoi(const char *s) { int wartosc, podstawa; bool jest_ujemne; pobierz_pierwsza_cyfre(s, wartosc, jest_ujemne, podstawa); while (char c = nastepny_znak(s)) { if (wartosc > std::numeric_limits<int>::max()/podstawa) throw range_error(string("poza zakresem")); wartosc *= podstawa; int d = cyfra(c, podstawa); if (wartosc > std::numeric_limits<int>::max()-d) throw range_error(string("poza zakresem")); wartosc += d; } return jest_ujemne ? -wartosc : wartosc; } int main() { const char *napis = "123"; int liczba = atoi(napis); std::cout << napis + 1 << std::endl; std::cout << liczba + 1 << std::endl; }
34.715686
121
0.493081
antonitomaszewski
7ac6262f1b39ea358b994bff0c1cea9c74a13af9
3,472
cpp
C++
Convert/src/M2/file_loader.cpp
blackdragonx61/M2-JSON-CONVERTER
9e125586b698daaf32ad1e96c0bc38b6bdd2aca3
[ "MIT" ]
4
2021-09-22T21:34:04.000Z
2022-03-04T15:47:37.000Z
Convert/src/M2/file_loader.cpp
blackdragonx61/M2-JSON-CONVERTER
9e125586b698daaf32ad1e96c0bc38b6bdd2aca3
[ "MIT" ]
null
null
null
Convert/src/M2/file_loader.cpp
blackdragonx61/M2-JSON-CONVERTER
9e125586b698daaf32ad1e96c0bc38b6bdd2aca3
[ "MIT" ]
null
null
null
#include "file_loader.h" #include <assert.h> CMemoryTextFileLoader::CMemoryTextFileLoader() { } CMemoryTextFileLoader::~CMemoryTextFileLoader() { } bool CMemoryTextFileLoader::SplitLineByTab(DWORD dwLine, TTokenVector* pstTokenVector) { pstTokenVector->reserve(10); pstTokenVector->clear(); const std::string& c_rstLine = GetLineString(dwLine); const int c_iLineLength = c_rstLine.length(); if (0 == c_iLineLength) return false; int basePos = 0; do { int beginPos = c_rstLine.find_first_of("\t", basePos); pstTokenVector->push_back(c_rstLine.substr(basePos, beginPos - basePos)); basePos = beginPos + 1; } while (basePos < c_iLineLength && basePos > 0); return true; } bool CMemoryTextFileLoader::SplitLine(DWORD dwLine, std::vector<std::string>* pstTokenVector, const char * c_szDelimeter) { pstTokenVector->clear(); std::string stToken; const std::string & c_rstLine = GetLineString(dwLine); DWORD basePos = 0; do { int beginPos = c_rstLine.find_first_not_of(c_szDelimeter, basePos); if (beginPos < 0) return false; int endPos; if (c_rstLine[beginPos] == '#' && c_rstLine.compare(beginPos, 4, "#--#") != 0) { return false; } else if (c_rstLine[beginPos] == '"') { ++beginPos; endPos = c_rstLine.find_first_of("\"", beginPos); if (endPos < 0) return false; basePos = endPos + 1; } else { endPos = c_rstLine.find_first_of(c_szDelimeter, beginPos); basePos = endPos; } pstTokenVector->push_back(c_rstLine.substr(beginPos, endPos - beginPos)); if (int(c_rstLine.find_first_not_of(c_szDelimeter, basePos)) < 0) break; } while (basePos < c_rstLine.length()); return true; } int CMemoryTextFileLoader::SplitLine2(DWORD dwLine, TTokenVector* pstTokenVector, const char* c_szDelimeter) { pstTokenVector->reserve(10); pstTokenVector->clear(); std::string stToken; const std::string& c_rstLine = GetLineString(dwLine); DWORD basePos = 0; do { int beginPos = c_rstLine.find_first_not_of(c_szDelimeter, basePos); if (beginPos < 0) return -1; int endPos; if (c_rstLine[beginPos] == '"') { ++beginPos; endPos = c_rstLine.find_first_of("\"", beginPos); if (endPos < 0) return -2; basePos = endPos + 1; } else { endPos = c_rstLine.find_first_of(c_szDelimeter, beginPos); basePos = endPos; } pstTokenVector->push_back(c_rstLine.substr(beginPos, endPos - beginPos)); if (int(c_rstLine.find_first_not_of(c_szDelimeter, basePos)) < 0) break; } while (basePos < c_rstLine.length()); return 0; } DWORD CMemoryTextFileLoader::GetLineCount() { return m_stLineVector.size(); } bool CMemoryTextFileLoader::CheckLineIndex(DWORD dwLine) { if (dwLine >= m_stLineVector.size()) return false; return true; } const std::string & CMemoryTextFileLoader::GetLineString(DWORD dwLine) { assert(CheckLineIndex(dwLine)); return m_stLineVector[dwLine]; } void CMemoryTextFileLoader::Bind(int bufSize, const void* c_pvBuf) { m_stLineVector.clear(); const char * c_pcBuf = (const char *)c_pvBuf; std::string stLine; int pos = 0; while (pos < bufSize) { const char c = c_pcBuf[pos++]; if ('\n' == c || '\r' == c) { if (pos < bufSize) if ('\n' == c_pcBuf[pos] || '\r' == c_pcBuf[pos]) ++pos; m_stLineVector.push_back(stLine); stLine = ""; } else if (c < 0) { stLine.append(c_pcBuf + (pos-1), 2); ++pos; } else { stLine += c; } } m_stLineVector.push_back(stLine); }
19.18232
121
0.679435
blackdragonx61