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
4818553a9e987f2d528ff7da296a7cdbac63890c
1,235
cpp
C++
BAC_2nd/ch6/UVa11853.cpp
Anyrainel/aoapc-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
3
2017-08-15T06:00:01.000Z
2018-12-10T09:05:53.000Z
BAC_2nd/ch6/UVa11853.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
null
null
null
BAC_2nd/ch6/UVa11853.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
2
2017-09-16T18:46:27.000Z
2018-05-22T05:42:03.000Z
// UVa11853 Paintball // Rujia Liu #include<cstdio> #include<cstdlib> #include<cmath> #include<cstring> #include<algorithm> using namespace std; const int maxn = 1000 + 5; const double W = 1000.0; int n, vis[maxn]; double x[maxn], y[maxn], r[maxn], left, right; bool ok; bool intersect(int c1, int c2) { return sqrt((x[c1]-x[c2])*(x[c1]-x[c2]) + (y[c1]-y[c2])*(y[c1]-y[c2])) < r[c1] + r[c2]; } void check_circle(int u) { if(x[u] - r[u] < 0) left = min(left, y[u] - sqrt(r[u]*r[u] - x[u]*x[u])); if(x[u] + r[u] > W) right = min(right, y[u] - sqrt(r[u]*r[u] - (W-x[u])*(W-x[u]))); } // 能达到底部则返回true bool dfs(int u) { if(vis[u]) return false; vis[u] = 1; if(y[u] - r[u] < 0) return true; for(int v = 0; v < n; v++) if(intersect(u, v) && dfs(v)) return true; check_circle(u); return false; } int main() { while(scanf("%d", &n) == 1) { ok = true; left = right = W; memset(vis, 0, sizeof(vis)); for(int i = 0; i < n; i++) scanf("%lf%lf%lf", &x[i], &y[i], &r[i]); for(int i = 0; i < n; i++) if(y[i] + r[i] >= W && dfs(i)) { ok = false; break; } // 从上往下dfs if(ok) printf("0.00 %.2lf %.2lf %.2lf\n", left, W, right); else printf("IMPOSSIBLE\n"); } return 0; }
22.87037
89
0.527935
Anyrainel
48235ef8d9d9e5b17a6c6f7d587e163f308ae52c
698
cpp
C++
src/CSMGameProject/CSMGameProject/EmoticonHandler.cpp
mastrayer/CSM
4ea656584dec4fe60771fbf13dc3d6bca00675fd
[ "MIT" ]
5
2016-06-02T09:50:31.000Z
2018-06-20T04:52:54.000Z
src/CSMGameProject/CSMGameProject/EmoticonHandler.cpp
mastrayer/CSM
4ea656584dec4fe60771fbf13dc3d6bca00675fd
[ "MIT" ]
null
null
null
src/CSMGameProject/CSMGameProject/EmoticonHandler.cpp
mastrayer/CSM
4ea656584dec4fe60771fbf13dc3d6bca00675fd
[ "MIT" ]
null
null
null
#include <stdio.h> #include "PacketHandler.h" #include "PlayerManager.h" #include "GameManager.h" #include "EffectManager.h" #include "EmoticonEffect.h" EmoticonHandler::EmoticonHandler() { } EmoticonHandler::~EmoticonHandler() { } void EmoticonHandler::HandlingPacket( short packetType, NNCircularBuffer* circularBuffer, NNPacketHeader* header ) { switch ( packetType ) { case PKT_SC_EMOTICON: { if ( circularBuffer->Read((char*)&mEmoticonResult, header->mSize) ) { EffectManager::GetInstance()->AddEffect(new CEmoticonEffect(mEmoticonResult.mPlayerId, (EmoticonType)mEmoticonResult.mEmoticonNumber)); } else { } } break; } }
19.942857
140
0.696275
mastrayer
4823be4f463910cd08208685aee8a37cc52df35c
1,433
cpp
C++
Highwaycam/program.cpp
42yeah/Highwaycam
02d06c3e30eef741e252b9f518ab24b3c7ac7e64
[ "MIT" ]
1
2020-06-16T10:29:25.000Z
2020-06-16T10:29:25.000Z
Highwaycam/program.cpp
42yeah/Highwaycam
02d06c3e30eef741e252b9f518ab24b3c7ac7e64
[ "MIT" ]
null
null
null
Highwaycam/program.cpp
42yeah/Highwaycam
02d06c3e30eef741e252b9f518ab24b3c7ac7e64
[ "MIT" ]
null
null
null
// // program.cpp // Highwaycam // // Created by Hao Zhou on 28/05/2020. // Copyright © 2020 John Boiles . All rights reserved. // #include "program.hpp" #include "app.hpp" #include <sstream> GLuint compile(App *app, GLuint type, std::string path) { std::string reason = "Failed to compile shader: " + path; GLuint shader = glCreateShader(type); std::fstream reader(path); if (!reader.good()) { app->warnings.push_back(reason + " (shader path not found)"); return 0; } std::stringstream ss; ss << reader.rdbuf(); std::string src = ss.str(); const char *raw = src.c_str(); glShaderSource(shader, 1, &raw, nullptr); glCompileShader(shader); char log[512] = { 0 }; glGetShaderInfoLog(shader, sizeof(log), nullptr, log); if (std::string(log).length() > 0 && log[0] != '\n') { app->warnings.push_back(reason + " (" + log + ")"); } return shader; } GLuint link(App *app, std::string vpath, std::string fpath) { std::string reason = "Failed to link program"; GLuint program = glCreateProgram(); glAttachShader(program, compile(app, GL_VERTEX_SHADER, vpath)); glAttachShader(program, compile(app, GL_FRAGMENT_SHADER, fpath)); glLinkProgram(program); char log[512] = { 0 }; if (std::string(log).length() > 0 && log[0] != '\n') { app->warnings.push_back(reason + " (" + log + ")"); } return program; }
29.244898
69
0.611305
42yeah
482647dae603244f1d36e1ec2e8736a4e65cceca
3,657
cpp
C++
ljrServer/tcp_server.cpp
lijianran/ljrServer
d5087447b92ac4eaffe35dec0c0661cf72a3dad7
[ "Apache-2.0" ]
1
2021-05-15T14:40:36.000Z
2021-05-15T14:40:36.000Z
ljrServer/tcp_server.cpp
lijianran/ljrServer
d5087447b92ac4eaffe35dec0c0661cf72a3dad7
[ "Apache-2.0" ]
null
null
null
ljrServer/tcp_server.cpp
lijianran/ljrServer
d5087447b92ac4eaffe35dec0c0661cf72a3dad7
[ "Apache-2.0" ]
null
null
null
#include "tcp_server.h" #include "config.h" #include "log.h" namespace ljrserver { static ljrserver::ConfigVar<uint64_t>::ptr g_tcp_server_read_timeout = ljrserver::Config::Lookup("tcp_server.read_timeout", (uint64_t)(60 * 1000 * 2), "tcp server read timeout"); static ljrserver::Logger::ptr g_logger = LJRSERVER_LOG_NAME("system"); TcpServer::TcpServer(ljrserver::IOManager *worker, ljrserver::IOManager *acceptworker) : m_worker(worker), m_acceptWorker(acceptworker), m_recvTimeout(g_tcp_server_read_timeout->getValue()), m_name("ljrserver/1.0.0"), m_isStop(true) { } TcpServer::~TcpServer() { for (auto &sock : m_socks) { sock->close(); } m_socks.clear(); } bool TcpServer::bind(ljrserver::Address::ptr addr) { std::vector<Address::ptr> addrs; std::vector<Address::ptr> fails; addrs.push_back(addr); return bind(addrs, fails); } bool TcpServer::bind(const std::vector<Address::ptr> &addrs, std::vector<Address::ptr> &fails) { for (auto &addr : addrs) { Socket::ptr sock = Socket::CreateTCP(addr); if (!sock->bind(addr)) { LJRSERVER_LOG_ERROR(g_logger) << "bind fail errno = " << errno << " errno-string = " << strerror(errno) << " addr = [" << addr->toString() << "]"; fails.push_back(addr); continue; } if (!sock->listen()) { LJRSERVER_LOG_ERROR(g_logger) << "listen fail errno = " << errno << " errno-string = " << strerror(errno) << " addr = [" << addr->toString() << "]"; fails.push_back(addr); continue; } m_socks.push_back(sock); } if (!fails.empty()) { m_socks.clear(); return false; } for (auto &sock : m_socks) { LJRSERVER_LOG_INFO(g_logger) << "server bind success: " << *sock; } return true; } bool TcpServer::start() { if (!m_isStop) { return true; } m_isStop = false; for (auto &sock : m_socks) { m_acceptWorker->schedule(std::bind(&TcpServer::startAccept, shared_from_this(), sock)); } return true; } void TcpServer::stop() { m_isStop = true; auto self = shared_from_this(); m_acceptWorker->schedule([this, self]() { for (auto &sock : m_socks) { sock->cancelAll(); sock->close(); } m_socks.clear(); }); } void TcpServer::handleClient(Socket::ptr client) { LJRSERVER_LOG_INFO(g_logger) << "handleClient: " << *client; } void TcpServer::startAccept(Socket::ptr sock) { while (!m_isStop) { Socket::ptr client = sock->accept(); if (client) { client->setRecvTimeout(m_recvTimeout); m_worker->schedule(std::bind(&TcpServer::handleClient, shared_from_this(), client)); } else { LJRSERVER_LOG_ERROR(g_logger) << "accept errno = " << errno << " errno-string = " << strerror(errno); } } } } // namespace ljrserver
28.130769
115
0.481816
lijianran
4826b6fb5f83ec6bb737444d63af60e9f165bff6
1,736
cc
C++
compiler/verify/function_type_test.cc
perimosocordiae/Icarus
183098eff886a0503562e5571e7009dd22719367
[ "Apache-2.0" ]
10
2015-10-28T18:54:41.000Z
2021-12-29T16:48:31.000Z
compiler/verify/function_type_test.cc
perimosocordiae/Icarus
183098eff886a0503562e5571e7009dd22719367
[ "Apache-2.0" ]
95
2020-02-27T22:34:02.000Z
2022-03-06T19:45:24.000Z
compiler/verify/function_type_test.cc
perimosocordiae/Icarus
183098eff886a0503562e5571e7009dd22719367
[ "Apache-2.0" ]
2
2019-02-01T23:16:04.000Z
2020-02-27T16:06:02.000Z
#include "compiler/compiler.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "test/module.h" #include "type/overload_set.h" namespace compiler { namespace { using ::testing::IsEmpty; using ::testing::Pair; using ::testing::UnorderedElementsAre; TEST(FunctionType, Empty) { test::TestModule mod; auto const *f = mod.Append<ast::FunctionType>("() -> ()"); auto qts = mod.context().qual_types(f); EXPECT_THAT(qts, UnorderedElementsAre(type::QualType::Constant(type::Type_))); EXPECT_THAT(mod.consumer.diagnostics(), IsEmpty()); } TEST(FunctionType, SuccessWithoutDeclaration) { test::TestModule mod; auto const *f = mod.Append<ast::FunctionType>("(i64, bool) -> (f32, f64)"); auto qts = mod.context().qual_types(f); EXPECT_THAT(qts, UnorderedElementsAre(type::QualType::Constant(type::Type_))); EXPECT_THAT(mod.consumer.diagnostics(), IsEmpty()); } TEST(FunctionType, SuccessWithDeclaration) { test::TestModule mod; auto const *f = mod.Append<ast::FunctionType>("(n: i64, b: bool) -> (f32, f64)"); auto qts = mod.context().qual_types(f); EXPECT_THAT(qts, UnorderedElementsAre(type::QualType::Constant(type::Type_))); EXPECT_THAT(mod.consumer.diagnostics(), IsEmpty()); } TEST(FunctionType, NonType) { test::TestModule mod; auto const *f = mod.Append<ast::FunctionType>("(3, b: bool) -> (f32, 4)"); auto qts = mod.context().qual_types(f); EXPECT_THAT(qts, UnorderedElementsAre(type::QualType::Constant(type::Type_))); EXPECT_THAT( mod.consumer.diagnostics(), UnorderedElementsAre(Pair("type-error", "non-type-function-input"), Pair("type-error", "non-type-function-output"))); } } // namespace } // namespace compiler
33.384615
80
0.685484
perimosocordiae
48274f205b1f63788b25f6e88be3fad4cfc1e0af
128
cpp
C++
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/SelfAdjointEigenSolver_operatorSqrt.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/SelfAdjointEigenSolver_operatorSqrt.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/SelfAdjointEigenSolver_operatorSqrt.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:eb2d0741391080bf616202edba473e05dcf8d96886d2d80f3f78df48f9dbe6f9 size 363
32
75
0.882813
initialz
48287ef19fb1ed0ec68f9a36e5be0cc193faf01a
414
cpp
C++
src/core/subsystem/utility/SSStartupScript.cpp
Robograde/Robograde
2c9a7d0b8250ec240102d504127f5c54532cb2b0
[ "Zlib" ]
5
2015-10-11T10:22:39.000Z
2019-07-24T10:09:13.000Z
src/core/subsystem/utility/SSStartupScript.cpp
Robograde/Robograde
2c9a7d0b8250ec240102d504127f5c54532cb2b0
[ "Zlib" ]
null
null
null
src/core/subsystem/utility/SSStartupScript.cpp
Robograde/Robograde
2c9a7d0b8250ec240102d504127f5c54532cb2b0
[ "Zlib" ]
null
null
null
/************************************************** Copyright 2015 Ola Enberg ***************************************************/ #include "SSStartupScript.h" #include <script/ScriptEngine.h> SSStartupScript& SSStartupScript::GetInstance( ) { static SSStartupScript instance; return instance; } void SSStartupScript::Startup( ) { g_Script.Perform( "dofile( SRC_DIR .. \"personal/Startup.lua\" )" ); }
23
69
0.548309
Robograde
4829ec577feb811cf4ebd802de912d5f9820dc8e
8,442
cpp
C++
src/src/Share/ShareLib/LinuxPublic/ACE_wrappers/tests/Token_Strategy_Test.cpp
549654033/RDHelp
0f5f9c7d098635c7216713d7137c845c0d999226
[ "MIT" ]
2
2020-05-20T05:16:34.000Z
2020-05-20T05:19:19.000Z
src/src/Share/ShareLib/LinuxPublic/ACE_wrappers/tests/Token_Strategy_Test.cpp
jimxie2012/RDHelp
0f5f9c7d098635c7216713d7137c845c0d999226
[ "MIT" ]
null
null
null
src/src/Share/ShareLib/LinuxPublic/ACE_wrappers/tests/Token_Strategy_Test.cpp
jimxie2012/RDHelp
0f5f9c7d098635c7216713d7137c845c0d999226
[ "MIT" ]
4
2020-05-20T01:50:16.000Z
2021-08-29T13:48:25.000Z
// $Id: Token_Strategy_Test.cpp 90163 2010-05-18 21:42:20Z mitza $ // ============================================================================ // // = LIBRARY // tests // // = DESCRIPTION // This program tests the behavior of ACE_Token under a variety of scenarios // in order verify whether or not tokens are returned, and threads run, in // a LIFO or FIFO manner. // // = AUTHOR // Don Hinton <dhinton@ieee.org> // // ============================================================================ #include "test_config.h" #include "ace/Token.h" #include "ace/Task.h" #include "ace/Atomic_Op.h" #include "ace/Auto_IncDec_T.h" #include "ace/Vector_T.h" #include "ace/Stats.h" #include "ace/ACE.h" #include "ace/Barrier.h" ACE_RCSID(tests, Token_Strategy_Test, "$Id: Token_Strategy_Test.cpp 90163 2010-05-18 21:42:20Z mitza $") #if defined (ACE_HAS_THREADS) class Token_Strategy_Test : public ACE_Task<ACE_MT_SYNCH> { public: Token_Strategy_Test (ACE_Token::QUEUEING_STRATEGY strategy = ACE_Token::FIFO, int threads = 5, int invocations = 10); ~Token_Strategy_Test (void); //FUZZ: disable check_for_lack_ACE_OS int open (void *a = 0); //FUZZ: enable check_for_lack_ACE_OS int svc (void); private: // Number of threads for the test, must be 5 or more. int threads_; // Barrier used to try to synchronize the for loop in the svc() method. ACE_Barrier barrier_; // Token used to synchonize for loop. ACE_Token token_; // Token strategy to use, LIFO/FIFO. ACE_Token::QUEUEING_STRATEGY strategy_; // Number of loops. int invocations_; // Vector of token counts, one per thread. ACE_Vector<ACE_INT32> vec_token_count_; // This keeps a count of the number of threads who have the token--should always // be 0 or 1; ACE_Atomic_Op<ACE_Thread_Mutex, int> counter_; // Number of active threads in svc() method. ACE_Atomic_Op<ACE_Thread_Mutex, int> active_; // Errors count, set in svc() and returned from open(). ACE_Atomic_Op<ACE_Thread_Mutex, int> errors_; ACE_UNIMPLEMENTED_FUNC (Token_Strategy_Test (const Token_Strategy_Test &)) ACE_UNIMPLEMENTED_FUNC (Token_Strategy_Test &operator= (const Token_Strategy_Test &)) }; Token_Strategy_Test::Token_Strategy_Test (ACE_Token::QUEUEING_STRATEGY strategy, int threads, int invocations) : threads_ (threads < 5 ? 5 : threads), // need at least 5 threads to satisfy test conditions. barrier_ (threads_), strategy_ (strategy), invocations_ (invocations < 10 ? 10 : invocations), // insure we loop at least a few times. vec_token_count_ (threads_) { this->counter_ = 0; this->active_ = 0; this->errors_ = 0; // Initialize the per thread counters used for generating stats. for (int i = 0; i < this->threads_; ++i) { const ACE_UINT32 sample = 0; this->vec_token_count_.push_back (sample); } this->token_.queueing_strategy (this->strategy_); ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" (tid = %t) Token_Test::Token_Test (\n") ACE_TEXT (" token_type = %s\n") ACE_TEXT (" thread = %d\n") ACE_TEXT (" invocations = %d\n"), this->strategy_ == ACE_Token::FIFO ? ACE_TEXT ("FIFO") : ACE_TEXT ("LIFO"), this->threads_, this->invocations_)); } Token_Strategy_Test::~Token_Strategy_Test (void) {} int Token_Strategy_Test::open (void *) { // spawn threads in ace task... // Make this Task into an Active Object. this->activate (THR_BOUND | THR_DETACHED, this->threads_); // Wait for all the threads to exit. this->thr_mgr ()->wait (); return this->errors_.value (); } int Token_Strategy_Test::svc (void) { int current = this->active_.value (); ACE_Auto_IncDec<ACE_Atomic_Op<ACE_Thread_Mutex, int> > active_counter (this->active_); this->barrier_.wait (); //ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" (tid = %t) starting loop\n"))); for (int i = 0; i < this->invocations_; i++) { ACE_GUARD_RETURN (ACE_Token, lock, this->token_, -1); this->vec_token_count_[current]++; ACE_Auto_IncDec<ACE_Atomic_Op<ACE_Thread_Mutex, int> > token_count_counter (this->counter_); // Turn this on to watch each thread grab the token. LIFO has the interesting // behavior that two thread seem to take turns while all the other threads wait. if (0) ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" (tid = %t) token count = %d, ") ACE_TEXT ("waiters = %d, loop: %d/%d\n"), this->counter_.value (), this->token_.waiters (), i + 1, this->invocations_)); // Yield, then simulate some work in order to give the other threads a chance to queue up. ACE_Thread::yield (); for (int k = 0; k != 100; ++k) { ACE::is_prime (k, 2, k/2); } // If we are the first thread to finish, compute the stats. if (i + 1 == this->invocations_) { if (this->active_ == this->threads_) { ACE_Stats stats; ACE_Stats_Value std_dev (2); ACE_Stats_Value mean (2); for (int i = 0; i < this->threads_; ++i) { stats.sample (this->vec_token_count_[i]); } //stats.print_summary (2); stats.std_dev (std_dev); stats.mean (mean); ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" (tid = %t) mean = %d.%d, std_dev = %d.%d, max = %d, min = %d\n"), mean.whole (), mean.fractional (), std_dev.whole (), std_dev.fractional (), stats.max_value (), stats.min_value ())); // These are pretty simplistic tests, so let me know if you have a better idea. // The assumption is that the standard deviation will be small when using the // FIFO strategy since all threads will share the token more or less evenly. // In contrast, the LIFO strategy will allow the two threads to alternate, thus // several threads will have a low, or zero, token count and create a low mean and // high standard deviation. If the the thread count is over say 4 or 5, the // standard deviation will actually excide the mean, hence the test. if (this->strategy_ == ACE_Token::LIFO && (mean.whole () > std_dev.whole () && mean.fractional () > std_dev.fractional ())) { ACE_DEBUG ((LM_ERROR, ACE_TEXT (" (tid = %t) LIFO: mean greater than std_dev.\n"))); this->errors_++; } if (this->strategy_ == ACE_Token::FIFO && (mean.whole () < std_dev.whole () && mean.fractional () < std_dev.fractional ())) { ACE_DEBUG ((LM_ERROR, ACE_TEXT (" (tid = %t) FIFO: mean less than std_dev.\n"))); this->errors_++; } } } } return 0; } int run_test (ACE_Token::QUEUEING_STRATEGY strategy, int threads = 5, int invocations = 10) { Token_Strategy_Test test (strategy, threads, invocations); return test.open () == 0 ? 0 : 1; } int run_main (int argc, ACE_TCHAR *argv[]) { ACE_START_TEST (ACE_TEXT ("Token_Strategy_Test")); int retval = 0; if (argc > 3) { // print usage retval = 1; } else { int threads = 5; int invocations = 100; if (argc > 1) threads = ACE_OS::atoi (argv[1]); if (argc > 2) invocations = ACE_OS::atoi (argv[2]); // New test using ACE_Token::queueing_strategy () retval += run_test (ACE_Token::FIFO, threads, invocations); retval += run_test (ACE_Token::LIFO, threads, invocations); } ACE_END_TEST; return retval; } #else /* ACE_HAS_THREADS */ int run_main (int, ACE_TCHAR *[]) { ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("Token_Strategy_Test: your platform doesn't support threads\n")), 1); } #endif /* ACE_HAS_THREADS */
33.903614
111
0.572732
549654033
482b528a90ccb709b175ed12a6a65b210056216c
6,691
cpp
C++
painelSingle.cpp
lsfcin/anikillerscin
8bbd1024fdf0d0b0bd815b2615faed02e1d07fe4
[ "MIT" ]
null
null
null
painelSingle.cpp
lsfcin/anikillerscin
8bbd1024fdf0d0b0bd815b2615faed02e1d07fe4
[ "MIT" ]
null
null
null
painelSingle.cpp
lsfcin/anikillerscin
8bbd1024fdf0d0b0bd815b2615faed02e1d07fe4
[ "MIT" ]
null
null
null
#include "painelSingle.h" Textura PainelSingle :: tSingleFundo("Texturas/Menu/menuSinglePlayerPreto.bmp",false); Textura PainelSingle :: tStartS("Texturas/Menu/Botoes/botaostartS.bmp",false); Textura PainelSingle :: tStart("Texturas/Menu/Botoes/botaostartN.bmp",false); Textura PainelSingle :: tBack("Texturas/Menu/Botoes/botaobackN.bmp",false); Textura PainelSingle :: tBackS("Texturas/Menu/Botoes/botaobackS.bmp",false); Textura PainelSingle :: tSeta("Texturas/Menu/setaN.bmp",false); Textura PainelSingle :: tSetaAmarela("Texturas/Menu/setaAmarela.bmp",false); Textura PainelSingle :: tSetaS("Texturas/Menu/setaS.bmp",false); Textura PainelSingle :: tSetaVermelha("Texturas/Menu/setaVermelha.bmp",false); Textura PainelSingle :: tSetaVerde("Texturas/Menu/setaVerde.bmp",false); Textura PainelSingle :: tSetaRosa("Texturas/Menu/setaRosa.bmp",false); Textura PainelSingle :: tSetaBranca("Texturas/Menu/setaBranca.bmp",false); Textura PainelSingle :: tSetaPreta("Texturas/Menu/setaPreta.bmp",false); PainelSingle :: PainelSingle():Painel(){ this->tSingleFundo.carregarBMP(); this->tStartS.carregarBMP(); this->tStart.carregarBMP(); this->tSeta.carregarBMP(); this->tSetaAmarela.carregarBMP(); this->tSetaS.carregarBMP(); this->tSetaVermelha.carregarBMP(); this->tSetaVerde.carregarBMP(); this->tSetaRosa.carregarBMP(); this->tSetaBranca.carregarBMP(); this->tSetaPreta.carregarBMP(); this->tBack.carregarBMP(); this->tBackS.carregarBMP(); this->camera = new Camera(); this->camera->setPosicaoCamera((new Ponto(0.f, 2.f, -5.f)), PI/2, -PI/8); this->carros[Carro::CHEVETTE] = new Chevette(); this->carros[Carro::CHEVETTE_ESCOLIOSE] = new ChevetteEscoliose(); this->carros[Carro::PICAPE] = new Picape(); this->carros[Carro::CORNOCAR] = new CornoCar(); this->carros[Carro::DIABLO] = new Diablo(); this->setCarroEscolhido(Carro::CHEVETTE); this->setCor(Carro::PRETO); this->anguloRotacao = 269.85; } PainelSingle :: ~PainelSingle(){ delete this->camera; delete this->carros[0]; delete this->carros[1]; } void PainelSingle::draw(){ this->camera->fotografar(); glPushMatrix(); glTranslatef(carros[this->carroEscolhido]->centro->x, 0,carros[this->carroEscolhido]->centro->z); glPushMatrix(); glRotated(anguloRotacao, 0, 1.f, 0); anguloRotacao += 0.15; carros[this->carroEscolhido]->draw(); glPopMatrix(); glEnable(GL_TEXTURE_2D); glScalef(0.02, 0.02, 0.02); glBindTexture(GL_TEXTURE_2D, tSingleFundo.ID); glBegin(GL_QUADS); glTexCoord2i(0, 1); glVertex3f(-200, -120, 50.f); glTexCoord2i(1, 1); glVertex3f( 200, -120, 50.f); glTexCoord2i(1, 0); glVertex3f( 200, 80, 50.f); glTexCoord2i(0, 0); glVertex3f(-200, 80, 50.f); glEnd(); glDisable(GL_TEXTURE_2D); glPopMatrix(); } void PainelSingle::drawOrtho(){ // botao voltar glEnable(GL_TEXTURE_2D); if (escolha == 2){ glBindTexture(GL_TEXTURE_2D, tBackS.ID); }else{ glBindTexture(GL_TEXTURE_2D, tBack.ID); } glBegin(GL_QUADS); glTexCoord2i(0, 1);glVertex2i(WIDTH * 0.1f, HEIGHT * 0.9f); glTexCoord2i(1, 1);glVertex2i(WIDTH * 0.1f + 160.f, HEIGHT * 0.9f); glTexCoord2i(1, 0);glVertex2i(WIDTH * 0.1f + 160.f, HEIGHT * 0.9f + 13.f); glTexCoord2i(0, 0);glVertex2i(WIDTH * 0.1f, HEIGHT * 0.9f + 13.f); glEnd(); // botao start game if (escolha == 3){ glBindTexture(GL_TEXTURE_2D, tStartS.ID); }else{ glBindTexture(GL_TEXTURE_2D, tStart.ID); } glBegin(GL_QUADS); glTexCoord2i(0, 1);glVertex2i(WIDTH * 0.9f - 160.f, HEIGHT * 0.9f); glTexCoord2i(1, 1);glVertex2i(WIDTH * 0.9f, HEIGHT * 0.9f); glTexCoord2i(1, 0);glVertex2i(WIDTH * 0.9f, HEIGHT * 0.9f + 13.f); glTexCoord2i(0, 0);glVertex2i(WIDTH * 0.9f - 160.f, HEIGHT * 0.9f + 13.f); glEnd(); //seta esquerda if (escolha == 0){ if(IsKeyPressed(LEFT)) glBindTexture(GL_TEXTURE_2D, tSetaAmarela.ID); else glBindTexture(GL_TEXTURE_2D, tSetaS.ID); }else{ glBindTexture(GL_TEXTURE_2D, tSeta.ID); } glBegin(GL_QUADS); glTexCoord2i(0, 1);glVertex2i(WIDTH * 0.15f - tSeta.imageWidth*0.75f, HEIGHT * 0.45f - tSeta.imageHeight*0.75f); glTexCoord2i(1, 1);glVertex2i(WIDTH * 0.15f + tSeta.imageWidth*0.75f, HEIGHT * 0.45f - tSeta.imageHeight*0.75f); glTexCoord2i(1, 0);glVertex2i(WIDTH * 0.15f + tSeta.imageWidth*0.75f, HEIGHT * 0.45f + tSeta.imageHeight*0.75f); glTexCoord2i(0, 0);glVertex2i(WIDTH * 0.15f - tSeta.imageWidth*0.75f, HEIGHT * 0.45f + tSeta.imageHeight*0.75f); glEnd(); //seta direita if (escolha == 1){ if(IsKeyPressed(RIGHT)) glBindTexture(GL_TEXTURE_2D, tSetaAmarela.ID); else glBindTexture(GL_TEXTURE_2D, tSetaS.ID); }else{ glBindTexture(GL_TEXTURE_2D, tSeta.ID); } glBegin(GL_QUADS); glTexCoord2i(0, 1);glVertex2i(WIDTH * 0.85f + tSeta.imageWidth*0.75f, HEIGHT * 0.45f - tSeta.imageHeight*0.75f); glTexCoord2i(1, 1);glVertex2i(WIDTH * 0.85f - tSeta.imageWidth*0.75f, HEIGHT * 0.45f - tSeta.imageHeight*0.75f); glTexCoord2i(1, 0);glVertex2i(WIDTH * 0.85f - tSeta.imageWidth*0.75f, HEIGHT * 0.45f + tSeta.imageHeight*0.75f); glTexCoord2i(0, 0);glVertex2i(WIDTH * 0.85f + tSeta.imageWidth*0.75f, HEIGHT * 0.45f + tSeta.imageHeight*0.75f); glEnd(); //seta UP glBindTexture(GL_TEXTURE_2D, setaUp->ID); glBegin(GL_QUADS); glTexCoord2i(0, 0);glVertex2i(WIDTH * 0.5f - tSeta.imageWidth*0.75f, HEIGHT * 0.25f - tSeta.imageHeight*0.75f); glTexCoord2i(0, 1);glVertex2i(WIDTH * 0.5f + tSeta.imageWidth*0.75f, HEIGHT * 0.25f - tSeta.imageHeight*0.75f); glTexCoord2i(1, 1);glVertex2i(WIDTH * 0.5f + tSeta.imageWidth*0.75f, HEIGHT * 0.25f + tSeta.imageHeight*0.75f); glTexCoord2i(1, 0);glVertex2i(WIDTH * 0.5f - tSeta.imageWidth*0.75f, HEIGHT * 0.25f + tSeta.imageHeight*0.75f); glEnd(); glDisable(GL_TEXTURE_2D); } void PainelSingle::setCarroEscolhido(int carroEscolhido){ this->carroEscolhido = carroEscolhido; } void PainelSingle::setCor(int cor){ this->carros[this->carroEscolhido]->setCor(cor); if(this->escolha == 4){ int corUp = (cor +1) % Carro::NUM_CORES; switch(corUp){ case Carro::PRETO: this->setaUp = &this->tSetaPreta; break; case Carro::VERMELHO: this->setaUp = &this->tSetaVermelha; break; case Carro::AMARELO: this->setaUp = &this->tSetaAmarela; break; case Carro::VERDE: this->setaUp = &this->tSetaVerde; break; case Carro::ROSA: this->setaUp = &this->tSetaRosa; break; case Carro::BRANCO: this->setaUp = &this->tSetaBranca; break; default: this->setaUp = &this->tSetaPreta; break; } }else{ this->setaUp = &this->tSeta; } } void PainelSingle::zerarAnguloRotacao(){ this->anguloRotacao = 269.85; } Carro & PainelSingle::getCarroEscolhido(){ return *this->carros[this->carroEscolhido]; }
33.455
114
0.702586
lsfcin
482e3172c7f9f08fe6de9fecba0eabf372aad77f
6,633
cpp
C++
plugins/tapjoy/common/src/cpp/LuaLibTapjoy.cpp
mikolajgucki/ae-engine
c4953feb74853b01b39b45b3bce23c10f6f74db0
[ "MIT" ]
1
2021-02-23T09:36:42.000Z
2021-02-23T09:36:42.000Z
plugins/tapjoy/common/src/cpp/LuaLibTapjoy.cpp
mikolajgucki/ae-engine
c4953feb74853b01b39b45b3bce23c10f6f74db0
[ "MIT" ]
null
null
null
plugins/tapjoy/common/src/cpp/LuaLibTapjoy.cpp
mikolajgucki/ae-engine
c4953feb74853b01b39b45b3bce23c10f6f74db0
[ "MIT" ]
null
null
null
#include "Log.h" #include "ae_lock.h" #include "LuaLibTapjoy.h" using namespace std; namespace ae { namespace tapjoy { /** */ class TapjoyEvent:public Runnable { protected: /** */ LuaLibTapjoy *luaLibTapjoy; public: /** */ TapjoyEvent(LuaLibTapjoy *lib_):Runnable(), luaLibTapjoy(lib_) { } /** */ virtual ~TapjoyEvent() { } }; /** */ class ConnectionSucceeded:public TapjoyEvent { public: /** */ ConnectionSucceeded(LuaLibTapjoy *lib_):TapjoyEvent(lib_) { } /** */ virtual bool run() { luaLibTapjoy->connectionSucceeded(); return true; } }; /** */ class ConnectionFailed:public TapjoyEvent { public: /** */ ConnectionFailed(LuaLibTapjoy *lib_):TapjoyEvent(lib_) { } /** */ virtual bool run() { luaLibTapjoy->connectionFailed(); return true; } }; /** */ class RequestSucceeded:public TapjoyEvent { /** */ const string placement; public: /** */ RequestSucceeded(LuaLibTapjoy *lib_,const string &placement_): TapjoyEvent(lib_),placement(placement_) { } /** */ virtual bool run() { luaLibTapjoy->requestSucceeded(placement); return true; } }; /** */ class RequestFailed:public TapjoyEvent { /** */ const string placement; /** */ const string error; public: /** */ RequestFailed(LuaLibTapjoy *lib_,const string &placement_, const string &error_):TapjoyEvent(lib_),placement(placement_), error(error_) { } /** */ virtual bool run() { luaLibTapjoy->requestFailed(placement,error); return true; } }; /** */ class ContentIsReady:public TapjoyEvent { /** */ const string placement; public: /** */ ContentIsReady(LuaLibTapjoy *lib_,const string &placement_): TapjoyEvent(lib_),placement(placement_) { } /** */ virtual bool run() { luaLibTapjoy->contentIsReady(placement); return true; } }; /** */ class ContentShown:public TapjoyEvent { /** */ const string placement; public: /** */ ContentShown(LuaLibTapjoy *lib_,const string &placement_): TapjoyEvent(lib_),placement(placement_) { } /** */ virtual bool run() { luaLibTapjoy->contentShown(placement); return true; } }; /** */ class ContentDismissed:public TapjoyEvent { /** */ const string placement; public: /** */ ContentDismissed(LuaLibTapjoy *lib_,const string &placement_): TapjoyEvent(lib_),placement(placement_) { } /** */ virtual bool run() { luaLibTapjoy->contentDismissed(placement); return true; } }; /// The log tag. static const char *logTag = "AE/Tapjoy"; /** */ void LuaLibTapjoy::trace(const char *msg) { if (dlog != (DLog *)0) { dlog->trace(logTag,msg); } else { Log::trace(logTag,msg); } } /** */ void LuaLibTapjoy::setCallback(TapjoyCallback *callback_) { aeGlobalLock(); if (callback != (TapjoyCallback *)0) { delete callback; } callback = callback_; if (callback != (TapjoyCallback *)0) { if (runnableQueue.run() == false) { trace(runnableQueue.getError().c_str()); } } aeGlobalUnlock(); } /** */ void LuaLibTapjoy::connectionSucceeded() { aeGlobalLock(); // log trace("connectionSucceeded()"); // callback if (getCallback() != (TapjoyCallback *)0) { getCallback()->connectionSucceeded(); } else { trace("connectionSucceeded() called with null callback"); runnableQueue.add(new ConnectionSucceeded(this)); } aeGlobalUnlock(); } /** */ void LuaLibTapjoy::connectionFailed() { aeGlobalLock(); // log trace("connectionFailed()"); // callback if (getCallback() != (TapjoyCallback *)0) { getCallback()->connectionFailed(); } else { trace("connectionFailed() called with null callback"); runnableQueue.add(new ConnectionFailed(this)); } aeGlobalUnlock(); } /** */ void LuaLibTapjoy::requestSucceeded(const string& placement) { aeGlobalLock(); // log trace("requestSucceeded()"); // callback if (getCallback() != (TapjoyCallback *)0) { getCallback()->requestSucceeded(placement); } else { trace("requestSucceeded() called with null callback"); runnableQueue.add(new RequestSucceeded(this,placement)); } aeGlobalUnlock(); } /** */ void LuaLibTapjoy::requestFailed(const string& placement,const string& error) { aeGlobalLock(); // log trace("requestFailed()"); // callback if (getCallback() != (TapjoyCallback *)0) { getCallback()->requestFailed(placement,error); } else { trace("requestFailed() called with null callback"); runnableQueue.add(new RequestFailed(this,placement,error)); } aeGlobalUnlock(); } /** */ void LuaLibTapjoy::contentIsReady(const string& placement) { aeGlobalLock(); // log trace("contentIsReady()"); // callback if (getCallback() != (TapjoyCallback *)0) { getCallback()->contentIsReady(placement); } else { trace("contentIsReady() called with null callback"); runnableQueue.add(new ContentIsReady(this,placement)); } aeGlobalUnlock(); } /** */ void LuaLibTapjoy::contentShown(const string& placement) { aeGlobalLock(); // log trace("contentShown()"); // callback if (getCallback() != (TapjoyCallback *)0) { getCallback()->contentShown(placement); } else { trace("contentShown() called with null callback"); runnableQueue.add(new ContentShown(this,placement)); } aeGlobalUnlock(); } /** */ void LuaLibTapjoy::contentDismissed(const string& placement) { aeGlobalLock(); // log trace("contentDismissed()"); // callback if (getCallback() != (TapjoyCallback *)0) { getCallback()->contentDismissed(placement); } else { trace("contentDismissed() called with null callback"); runnableQueue.add(new ContentDismissed(this,placement)); } aeGlobalUnlock(); } } // namespace } // namespace
22.11
80
0.56641
mikolajgucki
482ec84b9153a0c8d412c008e2197b91e8194cff
15,556
hpp
C++
polympc/src/nmpc.hpp
alexandreguerradeoliveira/rocket_gnc
164e96daca01d9edbc45bfaac0f6b55fe7324f24
[ "MIT" ]
null
null
null
polympc/src/nmpc.hpp
alexandreguerradeoliveira/rocket_gnc
164e96daca01d9edbc45bfaac0f6b55fe7324f24
[ "MIT" ]
null
null
null
polympc/src/nmpc.hpp
alexandreguerradeoliveira/rocket_gnc
164e96daca01d9edbc45bfaac0f6b55fe7324f24
[ "MIT" ]
null
null
null
// This file is part of PolyMPC, a lightweight C++ template library // for real-time nonlinear optimization and optimal control. // // Copyright (C) 2020 Listov Petr <petr.listov@epfl.ch> // // 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/. #ifndef NMPC_HPP #define NMPC_HPP #include <memory> #include "chebyshev.hpp" #define POLYMPC_USE_CONSTRAINTS namespace polympc { /** std::set<std::string> available_options = {"spectral.number_segments", "spectral.poly_order", "spectral.tf"}; template<typename ParamType> ParamType get_param(const std::string &key, const casadi::Dict dict, const ParamType &default_val) { if((available_options.find(key) != available_options.end()) && (dict.find(key) != dict.end())) return dict.find(key)->second; else if((available_options.find(key) == available_options.end()) && (dict.find(key) != dict.end())) { std::cout << "Unknown parameter: " << key << "\n"; // << "Available parameters: " << available_options << "\n"; return default_val; } else return default_val; } */ template <typename System, int NX, int NU, int NumSegments = 2, int PolyOrder = 5> class nmpc { public: nmpc(const casadi::DM &_reference, const double &tf = 1.0, const casadi::DMDict &mpc_options = casadi::DMDict(), const casadi::Dict &solver_options = casadi::Dict()); ~nmpc(){} /** contsraints setters */ void setLBX(const casadi::DM &_lbx) { ARG["lbx"](casadi::Slice(0, NX * (PolyOrder * NumSegments + 1 ))) = casadi::SX::repmat(casadi::SX::mtimes(Scale_X, _lbx), PolyOrder * NumSegments + 1, 1); } void setUBX(const casadi::DM &_ubx) { ARG["ubx"](casadi::Slice(0, NX * (PolyOrder * NumSegments + 1 ))) = casadi::SX::repmat(casadi::SX::mtimes(Scale_X, _ubx), PolyOrder * NumSegments + 1, 1); } void setLBU(const casadi::DM &_lbu) { int start = NX * (PolyOrder * NumSegments + 1 ); int finish = start + NU * (PolyOrder * NumSegments + 1 ); ARG["lbx"](casadi::Slice(start, finish)) = casadi::SX::repmat(casadi::SX::mtimes(Scale_U, _lbu), PolyOrder * NumSegments + 1, 1); } void setUBU(const casadi::DM &_ubu) { int start = NX * (PolyOrder * NumSegments + 1 ); int finish = start + NU * (PolyOrder * NumSegments + 1 ); ARG["ubx"](casadi::Slice(start, finish)) = casadi::SX::repmat(casadi::SX::mtimes(Scale_U, _ubu), PolyOrder * NumSegments + 1, 1); } void setStateScaling(const casadi::DM &Scaling){Scale_X = Scaling; invSX = casadi::DM::solve(Scale_X, casadi::DM::eye(Scale_X.size1()));} void setControlScaling(const casadi::DM &Scaling){Scale_U = Scaling; invSU = casadi::DM::solve(Scale_U, casadi::DM::eye(Scale_U.size1()));} void createNLP(const casadi::Dict &solver_options); void updateParams(const casadi::Dict &params); void enableWarmStart(){WARM_START = true;} void disableWarmStart(){WARM_START = false;} void computeControl(const casadi::DM &_X0); casadi::DM getOptimalControl() const {return OptimalControl;} casadi::DM getOptimalTrajetory() const {return OptimalTrajectory;} casadi::Dict getStats() const {return stats;} bool initialized() const {return _initialized;} double getPathError(); private: System system; casadi::SX Reference; uint nx, nu, ny, np; double Tf; casadi::SX Contraints; casadi::Function ContraintsFunc; /** state box constraints */ casadi::DM LBX, UBX; /** nonlinear inequality constraints */ casadi::DM LBG, UBG; /** control box constraints */ casadi::DM LBU, UBU; /** state and control scaling matrixces */ casadi::DM Scale_X, invSX; casadi::DM Scale_U, invSU; /** cost function weight matrices */ casadi::SX Q, R, P; casadi::DM NLP_X, NLP_LAM_G, NLP_LAM_X; casadi::Function NLP_Solver; casadi::SXDict NLP; casadi::Dict OPTS; casadi::DMDict ARG; casadi::Dict stats; casadi::DM OptimalControl; casadi::DM OptimalTrajectory; unsigned NUM_COLLOCATION_POINTS; bool WARM_START; bool _initialized; bool scale; /** TRACE FUNCTIONS */ casadi::Function DynamicsFunc; casadi::Function DynamicConstraints; casadi::Function PerformanceIndex; casadi::Function CostFunction; casadi::Function PathError; casadi::Function m_Jacobian; casadi::Function m_Dynamics; }; template<typename System, int NX, int NU, int NumSegments, int PolyOrder> nmpc<System, NX, NU, NumSegments, PolyOrder>::nmpc(const casadi::DM &_reference, const double &tf, const casadi::DMDict &mpc_options, const casadi::Dict &solver_options) { /** set up default */ casadi::Function dynamics = system.getDynamics(); nx = dynamics.nnz_out(); nu = dynamics.nnz_in() - nx; Tf = tf; assert(NX == nx); assert(NU == nu); casadi::Function output = system.getOutputMapping(); ny = output.nnz_out(); Reference = _reference; assert(ny == Reference.size1()); Q = casadi::SX::eye(ny); P = casadi::SX::eye(ny); R = casadi::SX::eye(NU); Scale_X = casadi::DM::eye(ny); invSX = Scale_X; Scale_U = casadi::DM::eye(NU); invSU = Scale_U; if(mpc_options.find("mpc.Q") != mpc_options.end()) { Q = mpc_options.find("mpc.Q")->second; assert(ny == Q.size1()); assert(ny == Q.size2()); } if(mpc_options.find("mpc.R") != mpc_options.end()) { R = mpc_options.find("mpc.R")->second; assert(NU == R.size1()); assert(NU == R.size2()); } if(mpc_options.find("mpc.P") != mpc_options.end()) { P = mpc_options.find("mpc.P")->second; assert(ny == P.size1()); assert(ny == P.size2()); } /** problem scaling */ scale = false; if(mpc_options.find("mpc.scaling") != mpc_options.end()) scale = static_cast<bool>(mpc_options.find("mpc.scaling")->second.nonzeros()[0]); if(mpc_options.find("mpc.scale_x") != mpc_options.end() && scale) { Scale_X = mpc_options.find("mpc.scale_x")->second; assert(NX == Scale_X.size1()); assert(NX == Scale_X.size2()); invSX = casadi::DM::solve(Scale_X, casadi::DM::eye(Scale_X.size1())); } if(mpc_options.find("mpc.scale_u") != mpc_options.end() && scale) { Scale_U = mpc_options.find("mpc.scale_u")->second; assert(NU == Scale_U.size1()); assert(NU == Scale_U.size2()); invSU = casadi::DM::solve(Scale_U, casadi::DM::eye(Scale_U.size1())); } /** assume unconstrained problem */ LBX = -casadi::DM::inf(nx); UBX = casadi::DM::inf(nx); LBU = -casadi::DM::inf(nu); UBU = casadi::DM::inf(nu); WARM_START = false; _initialized = false; /** create NLP */ createNLP(solver_options); } /** update solver paramters */ template<typename System, int NX, int NU, int NumSegments, int PolyOrder> void nmpc<System, NX, NU, NumSegments, PolyOrder>::updateParams(const casadi::Dict &params) { for (casadi::Dict::const_iterator it = params.begin(); it != params.end(); ++it) { OPTS[it->first] = it->second; } } template<typename System, int NX, int NU, int NumSegments, int PolyOrder> void nmpc<System, NX, NU, NumSegments, PolyOrder>::createNLP(const casadi::Dict &solver_options) { /** get dynamics function and state Jacobian */ casadi::Function dynamics = system.getDynamics(); casadi::Function output = system.getOutputMapping(); casadi::SX x = casadi::SX::sym("x", nx); casadi::SX u = casadi::SX::sym("u", nu); DynamicsFunc = dynamics; if(scale) { assert(Scale_X.size1() != 0); assert(Scale_U.size1() != 0); } /** ----------------------------------------------------------------------------------*/ /** set default properties of approximation */ const int num_segments = NumSegments; //get_param<int>("spectral.number_segments", spectral_props.props, 2); const int poly_order = PolyOrder; //get_param<int>("spectral.poly_order", spectral_props.props, 5); const int dimx = NX; const int dimu = NU; const int dimp = 0; const double tf = Tf; //get_param<double>("spectral.tf", spectral_props.props, 1.0); NUM_COLLOCATION_POINTS = num_segments * poly_order; /** Order of polynomial interpolation */ Chebyshev<casadi::SX, poly_order, num_segments, dimx, dimu, dimp> spectral; casadi::SX diff_constr; if(scale) { casadi::SX SODE = dynamics(casadi::SXVector{casadi::SX::mtimes(invSX, x), casadi::SX::mtimes(invSU, u)})[0]; SODE = casadi::SX::mtimes(Scale_X, SODE); casadi::Function FunSODE = casadi::Function("scaled_ode", {x, u}, {SODE}); diff_constr = spectral.CollocateDynamics(FunSODE, 0, tf); } else { diff_constr = spectral.CollocateDynamics(DynamicsFunc, 0, tf); } diff_constr = diff_constr(casadi::Slice(0, diff_constr.size1() - dimx)); /** define an integral cost */ casadi::SX lagrange, residual; if(scale) { casadi::SX _invSX = invSX(casadi::Slice(0, NX), casadi::Slice(0, NX)); residual = Reference - output({casadi::SX::mtimes(_invSX, x)})[0]; lagrange = casadi::SX::sum1( casadi::SX::mtimes(Q, pow(residual, 2)) ); lagrange = lagrange + casadi::SX::sum1( casadi::SX::mtimes(R, pow(u, 2)) ); } else { residual = Reference - output({x})[0]; lagrange = casadi::SX::sum1( casadi::SX::mtimes(Q, pow(residual, 2)) ); lagrange = lagrange + casadi::SX::sum1( casadi::SX::mtimes(R, pow(u, 2)) ); } casadi::Function LagrangeTerm = casadi::Function("Lagrange", {x, u}, {lagrange}); /** trace functions */ PathError = casadi::Function("PathError", {x}, {residual}); casadi::SX mayer = casadi::SX::sum1( casadi::SX::mtimes(P, pow(residual, 2)) ); casadi::Function MayerTerm = casadi::Function("Mayer",{x}, {mayer}); casadi::SX performance_idx = spectral.CollocateCost(MayerTerm, LagrangeTerm, 0.0, tf); casadi::SX varx = spectral.VarX(); casadi::SX varu = spectral.VarU(); casadi::SX opt_var = casadi::SX::vertcat(casadi::SXVector{varx, varu}); /** debugging output */ DynamicConstraints = casadi::Function("constraint_func", {opt_var}, {diff_constr}); PerformanceIndex = casadi::Function("performance_idx", {opt_var}, {performance_idx}); casadi::SX lbg = casadi::SX::zeros(diff_constr.size()); casadi::SX ubg = casadi::SX::zeros(diff_constr.size()); /** set inequality (box) constraints */ /** state */ casadi::SX lbx = casadi::SX::repmat(casadi::SX::mtimes(Scale_X, LBX), poly_order * num_segments + 1, 1); casadi::SX ubx = casadi::SX::repmat(casadi::SX::mtimes(Scale_X, UBX), poly_order * num_segments + 1, 1); /** control */ lbx = casadi::SX::vertcat( {lbx, casadi::SX::repmat(casadi::SX::mtimes(Scale_U, LBU), poly_order * num_segments + 1, 1)} ); ubx = casadi::SX::vertcat( {ubx, casadi::SX::repmat(casadi::SX::mtimes(Scale_U, UBU), poly_order * num_segments + 1, 1)} ); casadi::SX diff_constr_jacobian = casadi::SX::jacobian(diff_constr, opt_var); /** Augmented Jacobian */ m_Jacobian = casadi::Function("aug_jacobian",{opt_var}, {diff_constr_jacobian}); /** formulate NLP */ NLP["x"] = opt_var; NLP["f"] = performance_idx; // 1e-3 * casadi::SX::dot(diff_constr, diff_constr); NLP["g"] = diff_constr; /** default solver options */ OPTS["ipopt.linear_solver"] = "mumps"; OPTS["ipopt.print_level"] = 1; OPTS["ipopt.tol"] = 1e-4; OPTS["ipopt.acceptable_tol"] = 1e-4; OPTS["ipopt.max_iter"] = 150; OPTS["ipopt.warm_start_init_point"] = "yes"; //OPTS["ipopt.hessian_approximation"] = "limited-memory"; /** set user defined options */ if(!solver_options.empty()) updateParams(solver_options); NLP_Solver = casadi::nlpsol("solver", "ipopt", NLP, OPTS); /** set default args */ ARG["lbx"] = lbx; ARG["ubx"] = ubx; ARG["lbg"] = lbg; ARG["ubg"] = ubg; casadi::DM feasible_state = casadi::DM::zeros(UBX.size()); casadi::DM feasible_control = casadi::DM::zeros(UBU.size()); ARG["x0"] = casadi::DM::vertcat(casadi::DMVector{casadi::DM::repmat(feasible_state, poly_order * num_segments + 1, 1), casadi::DM::repmat(feasible_control, poly_order * num_segments + 1, 1)}); } template<typename System, int NX, int NU, int NumSegments, int PolyOrder> void nmpc<System, NX, NU, NumSegments, PolyOrder>::computeControl(const casadi::DM &_X0) { int N = NUM_COLLOCATION_POINTS; /** scale input */ casadi::DM X0 = casadi::DM::mtimes(Scale_X, _X0); std::cout << "Compute control at: " << X0 << "\n"; if(WARM_START) { int idx_in = N * NX; int idx_out = idx_in + NX; ARG["lbx"](casadi::Slice(idx_in, idx_out), 0) = X0; ARG["ubx"](casadi::Slice(idx_in, idx_out), 0) = X0; ARG["x0"] = NLP_X; ARG["lam_g0"] = NLP_LAM_G; ARG["lam_x0"] = NLP_LAM_X; } else { ARG["x0"](casadi::Slice(0, (N + 1) * NX), 0) = casadi::DM::repmat(X0, (N + 1), 1); int idx_in = N * NX; int idx_out = idx_in + NX; ARG["lbx"](casadi::Slice(idx_in, idx_out), 0) = X0; ARG["ubx"](casadi::Slice(idx_in, idx_out), 0) = X0; } /** store optimal solution */ casadi::DMDict res = NLP_Solver(ARG); NLP_X = res.at("x"); NLP_LAM_X = res.at("lam_x"); NLP_LAM_G = res.at("lam_g"); casadi::DM opt_x = NLP_X(casadi::Slice(0, (N + 1) * NX)); //DM invSX = DM::solve(Scale_X, DM::eye(15)); OptimalTrajectory = casadi::DM::mtimes(invSX, casadi::DM::reshape(opt_x, NX, N + 1)); //casadi::DM opt_u = NLP_X( casadi::Slice((N + 1) * NX, NLP_X.size1()) ); casadi::DM opt_u = NLP_X( casadi::Slice((N + 1) * NX, (N + 1) * NX + (N + 1) * NU ) ); //DM invSU = DM::solve(Scale_U, DM::eye(4)); OptimalControl = casadi::DM::mtimes(invSU, casadi::DM::reshape(opt_u, NU, N + 1)); stats = NLP_Solver.stats(); std::cout << stats << "\n"; std::string solve_status = static_cast<std::string>(stats["return_status"]); if(solve_status.compare("Invalid_Number_Detected") == 0) { std::cout << "X0 : " << ARG["x0"] << "\n"; //assert(false); } if(solve_status.compare("Infeasible_Problem_Detected") == 0) { std::cout << "X0 : " << ARG["x0"] << "\n"; //assert(false); } enableWarmStart(); } /** get path error */ template<typename System, int NX, int NU, int NumSegments, int PolyOrder> double nmpc<System, NX, NU, NumSegments, PolyOrder>::getPathError() { double error = 0; if(!OptimalTrajectory.is_empty()) { casadi::DM state = OptimalTrajectory(casadi::Slice(0, OptimalTrajectory.size1()), OptimalTrajectory.size2() - 1); state = casadi::DM::mtimes(Scale_X, state); casadi::DMVector tmp = PathError(casadi::DMVector{state}); error = casadi::DM::norm_2( tmp[0] ).nonzeros()[0]; } return error; } } //polympc namespace #endif // NMPC_HPP
34.800895
170
0.607547
alexandreguerradeoliveira
482f0c351449b350b65187e77b7a0bfc69803464
4,073
cpp
C++
mlir/lib/Dialect/ArmSVE/IR/ArmSVEDialect.cpp
jinge90/llvm
1f3f9b9b1181feb559e85970155678c18a436711
[ "Apache-2.0" ]
null
null
null
mlir/lib/Dialect/ArmSVE/IR/ArmSVEDialect.cpp
jinge90/llvm
1f3f9b9b1181feb559e85970155678c18a436711
[ "Apache-2.0" ]
null
null
null
mlir/lib/Dialect/ArmSVE/IR/ArmSVEDialect.cpp
jinge90/llvm
1f3f9b9b1181feb559e85970155678c18a436711
[ "Apache-2.0" ]
null
null
null
//===- ArmSVEDialect.cpp - MLIR ArmSVE dialect implementation -------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the ArmSVE dialect and its operations. // //===----------------------------------------------------------------------===// #include "mlir/Dialect/ArmSVE/ArmSVEDialect.h" #include "mlir/Dialect/LLVMIR/LLVMTypes.h" #include "mlir/Dialect/Vector/VectorOps.h" #include "mlir/IR/Builders.h" #include "mlir/IR/DialectImplementation.h" #include "mlir/IR/OpImplementation.h" #include "mlir/IR/TypeUtilities.h" #include "llvm/ADT/TypeSwitch.h" using namespace mlir; using namespace arm_sve; #include "mlir/Dialect/ArmSVE/ArmSVEDialect.cpp.inc" static Type getI1SameShape(Type type); static void buildScalableCmpIOp(OpBuilder &build, OperationState &result, arith::CmpIPredicate predicate, Value lhs, Value rhs); static void buildScalableCmpFOp(OpBuilder &build, OperationState &result, arith::CmpFPredicate predicate, Value lhs, Value rhs); #define GET_OP_CLASSES #include "mlir/Dialect/ArmSVE/ArmSVE.cpp.inc" #define GET_TYPEDEF_CLASSES #include "mlir/Dialect/ArmSVE/ArmSVETypes.cpp.inc" void ArmSVEDialect::initialize() { addOperations< #define GET_OP_LIST #include "mlir/Dialect/ArmSVE/ArmSVE.cpp.inc" >(); addTypes< #define GET_TYPEDEF_LIST #include "mlir/Dialect/ArmSVE/ArmSVETypes.cpp.inc" >(); } //===----------------------------------------------------------------------===// // ScalableVectorType //===----------------------------------------------------------------------===// void ScalableVectorType::print(AsmPrinter &printer) const { printer << "<"; for (int64_t dim : getShape()) printer << dim << 'x'; printer << getElementType() << '>'; } Type ScalableVectorType::parse(AsmParser &parser) { SmallVector<int64_t> dims; Type eltType; if (parser.parseLess() || parser.parseDimensionList(dims, /*allowDynamic=*/false) || parser.parseType(eltType) || parser.parseGreater()) return {}; return ScalableVectorType::get(eltType.getContext(), dims, eltType); } //===----------------------------------------------------------------------===// // ScalableVector versions of general helpers for comparison ops //===----------------------------------------------------------------------===// // Return the scalable vector of the same shape and containing i1. static Type getI1SameShape(Type type) { auto i1Type = IntegerType::get(type.getContext(), 1); if (auto sVectorType = type.dyn_cast<ScalableVectorType>()) return ScalableVectorType::get(type.getContext(), sVectorType.getShape(), i1Type); return nullptr; } //===----------------------------------------------------------------------===// // CmpFOp //===----------------------------------------------------------------------===// static void buildScalableCmpFOp(OpBuilder &build, OperationState &result, arith::CmpFPredicate predicate, Value lhs, Value rhs) { result.addOperands({lhs, rhs}); result.types.push_back(getI1SameShape(lhs.getType())); result.addAttribute(ScalableCmpFOp::getPredicateAttrName(), build.getI64IntegerAttr(static_cast<int64_t>(predicate))); } static void buildScalableCmpIOp(OpBuilder &build, OperationState &result, arith::CmpIPredicate predicate, Value lhs, Value rhs) { result.addOperands({lhs, rhs}); result.types.push_back(getI1SameShape(lhs.getType())); result.addAttribute(ScalableCmpIOp::getPredicateAttrName(), build.getI64IntegerAttr(static_cast<int64_t>(predicate))); }
38.065421
80
0.57206
jinge90
482fa342f6894b7348fd53358f2a5855d85cd4f5
74,542
cpp
C++
gazebo_lwr4_simulator/src/gazebo_kuka_lwr/src/kuka_lwr_plugin.cpp
mfigat/public_rshpn_tool
3555cb8f1eb35ef12441b9aef63dae8f578c2aa7
[ "BSD-3-Clause" ]
null
null
null
gazebo_lwr4_simulator/src/gazebo_kuka_lwr/src/kuka_lwr_plugin.cpp
mfigat/public_rshpn_tool
3555cb8f1eb35ef12441b9aef63dae8f578c2aa7
[ "BSD-3-Clause" ]
null
null
null
gazebo_lwr4_simulator/src/gazebo_kuka_lwr/src/kuka_lwr_plugin.cpp
mfigat/public_rshpn_tool
3555cb8f1eb35ef12441b9aef63dae8f578c2aa7
[ "BSD-3-Clause" ]
null
null
null
// ################################################################################################### /* Choose either GAZEBO_CALCULATIONS or EXTERNAL_CALCULATIONS */ //#define GAZEBO_CALCULATIONS /* calculation done in gazebo, no shared memory utilised */ #define EXTERNAL_CALCULATIONS /* calculation done in external process, data sent through share memory */ // ################################################################################################### // ############################################## #define CALCULATE_SAMPLING_PERIOD /* An information whether the sampling period has to be calculated - leave it if you want to calculate sampling period otherwise comment it */ // ############################################## //#define PRINT_DEBUG_INFO /* if defined all cout will be printed otherwise all information will not be printed to the console */ // ########################################## #include <iostream> #include <fstream> // ################ #include <chrono> // needed to get the current time #include <ctime> // ################ #include <functional> #include <gazebo/gazebo.hh> #include <gazebo/physics/physics.hh> #include <gazebo/common/common.hh> #include <ignition/math/Vector3.hh> // Communication #include <gazebo/transport/transport.hh> #include <gazebo/msgs/msgs.hh> // Kuka communication messages - my own //#include "msgs/kuka_joints.pb.h" #include "kuka_joints.pb.h" // lwr4_kinematics_dynamics - moja biblioteka #include "../../../../my_libs/lwr4_kinematics_dynamics/lwr4_kinematics_dynamics.h" // shared memory - moja biblioteka #include "../../../../my_libs/shared_memory/shared_memory.h" //#define gravity_constant 9.80665 // gravity acceleration - from General Conference on Weights and Measures - 1901 year #define gravity_constant 9.81 // gravity acceleration - option 2 #define L1 0.2 // według gazebo 0.2005 // 0.2 // l1=0.2m #define L2 0.2 // l2=0.2m #define L3 0.2 // l3=0.2m #define L4 0.195 // l4=0.195m #define L5 0.195 // według gazebo 0.2 //0.195 // l5=0.195m #define D1 0.31 // d1=0.31m #define D3 0.4 // d3=0.4m #define D5 0.39 // d5=0.39m #define D7 0.078 // d7=0.078m #define OPTION_1 //#define OPTION_2 #ifdef GAZEBO_CALCULATIONS // for GAZEBO_CALCULATIONS #define MAX_ITERATIONS 360 #define ITERATIONS_IN_ONE_CYCLE 50 #endif // GAZEBO_CALCULATIONS #ifdef EXTERNAL_CALCULATIONS // for EXTERNAL_CALCULATIONS #define MAX_ITERATIONS 360 #define ITERATIONS_IN_ONE_CYCLE 50 #endif // EXTERNAL_CALCULATIONS //std::array<double,7> equilibrium_global={0.04, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4}; namespace gazebo { class ModelKukaLwr : public ModelPlugin { // pointer to Int message typedef const boost::shared_ptr<const gazebo::msgs::Any> AnyPtr; typedef const boost::shared_ptr<const kuka_joints_msgs::KukaJoints> KukaJointsPtr; // Load function public: void Load(physics::ModelPtr _parent, sdf::ElementPtr /*_sdf*/) { // Stores the pointer to the model this->model_ = _parent; // Listen to the update event. This event is broadcast every simulation iteration. // connects OnUpadate method to the world update start signal this->updateConnection = event::Events::ConnectWorldUpdateBegin( std::bind(&ModelKukaLwr::OnUpdate, this)); #ifdef PRINT_DEBUG_INFO std::cout << "plugin loaded" << std::endl; #endif // #################################################### // test // set equilibrium to base position //equilibrium= {0.04, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4}; // equilibrium joint position equilibrium= {0, 0, 0, 1.57, 0, 0, 0}; // equilibrium joint position equilibrium_x=0.56; equilibrium_y=0.17; equilibrium_z=0.8; equilibrium_roll=0; equilibrium_pitch=0; equilibrium_yaw=0; eq_0_step=0.001; // eq_3_step=0.001; kinematic_chain_index=0; // #################################################### const std::string name = "lwr"; for (int i = 0; i < 7; ++i) { std::string joint_name = std::string("lwr::") + name + "_arm_" + std::to_string(i) + "_joint"; joints_.push_back(model_->GetJoint(joint_name)); // add joint to joints_ vector (added joint is found from the model based on its name) } for (int i = 0; i < 7; ++i) { std::string link_name = std::string("lwr::") + name + "_arm_" + std::to_string(i+1) + "_link"; links_.push_back(model_->GetLink(link_name)); // analogously like in joints } // ############################################ // subscribe to specific topic, e.g. ~/test/maxym // create node for communication gazebo::transport::NodePtr node(new gazebo::transport::Node); node->Init(); // listen to gazebo ~/test/maxym topic sub=node->Subscribe("~/test/maxym", &ModelKukaLwr::subscribe_callback_function, this); // ############################################### // subscribe to kuka_joints topic gazebo::transport::NodePtr node_kuka_joints(new gazebo::transport::Node); node_kuka_joints->Init(); sub_kuka_joints=node_kuka_joints->Subscribe("~/kuka_joints", &ModelKukaLwr::subscribe_callback_function_kuka_joints, this); _iterations=0; _iterations2=0; _flag=true; // add to vector the base position saveBasePoseToFile(); // tests // shared memory test #ifdef EXTERNAL_CALCULATIONS /* if data are calculated in external process and transfered through shared memory */ std::cout<<"SetUpSharedMemory"<<std::endl; setUpSharedMemory(); #endif // ########################### #ifdef CALCULATE_SAMPLING_PERIOD start_time=std::chrono::system_clock::now(); #endif // CALCULATE_SAMPLING_PERIOD // ############################# // ############################################ } // end of function Load #ifdef EXTERNAL_CALCULATIONS /* Set up shared memory */ void setUpSharedMemory(){ //#ifdef PRINT_DEBUG_INFO std::cout<<"[EXTERNAL_CALCULATIONS] - setUpSharedMemory"<<std::endl; //#endif //shm_producer= new SharedMemory<float>("shared_memory_float", SharedMemoryType::Producer); /* shared memory - test */ shm_torque_consumer= new SharedMemory<struct lwr4_joints>("shared_memory_torque", SharedMemoryType::Consumer); /* Consumer of torque data received from shared memory */ shm_parameters_producer= new SharedMemory<struct lwr4_kinematics_params>("shared_memory_lwr4_kinematics_params", SharedMemoryType::Producer); /* Consumer of torque data received from shared memory */ } #endif // set forces to joints based on given torques void setForces(const std::array<double, 7 > &t) { for (int i=0; i<joints_.size(); i++) { joints_[i]->SetForce(0, t[i]); // axis 0 jest default //std::cout<<"Torque["<<i<<"]="<<t[i]<<std::endl; } } // end of function setForces double gravity_compensation_joint_7(){ double tau=0; return tau; } double gravity_compensation_joint_6(){ double g=gravity_constant; double m6 = links_[5]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double m7 = links_[6]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double d7= D7, d5 = D5, d3=D3, d1=D1; double theta1=joints_[0]->Position(0); double theta2=joints_[1]->Position(0); double theta3=joints_[2]->Position(0); double theta4=joints_[3]->Position(0); double theta5=joints_[4]->Position(0); double theta6=joints_[5]->Position(0); double theta7=joints_[6]->Position(0); double c1=cos(theta1), c2=cos(theta2), c3=cos(theta3), c4=cos(theta4), c5=cos(theta5), c6=cos(theta6), c7=cos(theta7); double s1=sin(theta1), s2=sin(theta2), s3=sin(theta3), s4=sin(theta4), s5=sin(theta5), s6=sin(theta6), s7=sin(theta7); double tau=0; #ifdef OPTION_1 // wersja nr 1 /* tau=-d7*(c7*m7*(s7*(s5*(c2*g*s4 - c3*c4*g*s2) - c5*g*s2*s3) + c7*(s6*(c2*c4*g + c3*g*s2*s4) - c6*(c5*(c2*g*s4 - c3*c4*g*s2) + g*s2*s3*s5))) + m7*s7*(s7*(s6*(c2*c4*g + c3*g*s2*s4) - c6*(c5*(c2*g*s4 - c3*c4*g*s2) + g*s2*s3*s5)) - c7*(s5*(c2*g*s4 - c3*c4*g*s2) - c5*g*s2*s3))); */ //tau=-(m6*(s6*(c2*c4*g + c3*g*s2*s4) - c6*(c5*(c2*g*s4 - c3*c4*g*s2) + g*s2*s3*s5)))/16.0; tau=-(m6*(s6*(c2*c4*g + c3*g*s2*s4) - c6*(c5*(c2*g*s4 - c3*c4*g*s2) + g*s2*s3*s5)))/16.0; #endif return tau; } ///////////////////////////////////////////// double gravity_compensation_joint_5(){ //std::cout<<"sin="<<sin(1.57)<<std::endl; double g=gravity_constant; double m5 = links_[4]->GetInertial()->Mass(); // because 4-th link in links_ is in fact 5-th link of the lwr4+ manipulator double m6 = links_[5]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double m7 = links_[6]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double d7= D7, d5 = D5, d3=D3, d1=D1; double l5= L5; double theta1=joints_[0]->Position(0); double theta2=joints_[1]->Position(0); double theta3=joints_[2]->Position(0); double theta4=joints_[3]->Position(0); double theta5=joints_[4]->Position(0); double theta6=joints_[5]->Position(0); double theta7=joints_[6]->Position(0); double c1=cos(theta1), c2=cos(theta2), c3=cos(theta3), c4=cos(theta4), c5=cos(theta5), c6=cos(theta6), c7=cos(theta7); double s1=sin(theta1), s2=sin(theta2), s3=sin(theta3), s4=sin(theta4), s5=sin(theta5), s6=sin(theta6), s7=sin(theta7); double tau=0; #ifdef OPTION_1 // wersja nr 1 /* */ //tau=(g*m6*s6*(c5*s2*s3 - c2*s4*s5 + c3*c4*s2*s5))/16.0; tau=(g*m6*s6*(c5*s2*s3 - c2*s4*s5 + c3*c4*s2*s5))/16.0; #ifdef PRINT_DEBUG_INFO std::cout<<"tau5="<<tau<<std::endl; #endif #endif return tau; } double gravity_compensation_joint_4(){ //std::cout<<"sin="<<sin(1.57)<<std::endl; double g=gravity_constant; double m4 = links_[3]->GetInertial()->Mass(); // because 3-th link in links_ is in fact 4-th link of the lwr4+ manipulator double m5 = links_[4]->GetInertial()->Mass(); // because 4-th link in links_ is in fact 5-th link of the lwr4+ manipulator double m6 = links_[5]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double m7 = links_[6]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double d7= D7, d5 = D5, d3=D3, d1=D1; double l5= L5, l4=L4; double theta1=joints_[0]->Position(0); double theta2=joints_[1]->Position(0); double theta3=joints_[2]->Position(0); double theta4=joints_[3]->Position(0); double theta5=joints_[4]->Position(0); double theta6=joints_[5]->Position(0); double theta7=joints_[6]->Position(0); double c1=cos(theta1), c2=cos(theta2), c3=cos(theta3), c4=cos(theta4), c5=cos(theta5), c6=cos(theta6), c7=cos(theta7); double s1=sin(theta1), s2=sin(theta2), s3=sin(theta3), s4=sin(theta4), s5=sin(theta5), s6=sin(theta6), s7=sin(theta7); double tau=0; #ifdef OPTION_1 // wersja nr 1 /* */ // tau=(g*(140*c3*c4*m4*s2 - 140*c2*m4*s4 + 152*c2*c5*c5*m5*s4 + 152*c2*m5*s4*s5*s5 + 125*c2*c4*c5*m6*s6 - 152*c3*c4*c5*c5*m5*s2 - 125*c2*c5*c5*c6*m6*s4 - 2000*c2*c5*c5*d5*m5*s4 - 152*c3*c4*m5*s2*s5*s5 - 125*c2*c6*m6*s4*s5*s5 - 2000*c2*d5*m5*s4*s5*s5 - 2000*c2*d5*m6*s4*s5*s5 + 125*c3*c4*c5*c5*c6*m6*s2 + 2000*c3*c4*c5*c5*d5*m5*s2 + 125*c3*c4*c6*m6*s2*s5*s5 + 2000*c3*c4*d5*m5*s2*s5*s5 + 2000*c3*c4*d5*m6*s2*s5*s5 - 2000*c2*c5*c5*c6*c6*d5*m6*s4 - 2000*c2*c5*c5*d5*m6*s4*s6*s6 + 125*c3*c5*m6*s2*s4*s6 + 2000*c5*d5*m6*s2*s3*s5 - 2000*c5*c6*c6*d5*m6*s2*s3*s5 - 2000*c5*d5*m6*s2*s3*s5*s6*s6 + 2000*c3*c4*c5*c5*c6*c6*d5*m6*s2 + 2000*c3*c4*c5*c5*d5*m6*s2*s6*s6))/2000.0; //tau=(g*(180*c3*c4*m4*s2 - 180*c2*m4*s4 + 152*c2*c5*c5*m5*s4 + 152*c2*m5*s4*s5*s5 + 125*c2*c4*c5*m6*s6 - 152*c3*c4*c5*c5*m5*s2 - 125*c2*c5*c5*c6*m6*s4 - 2000*c2*c5*c5*d5*m5*s4 - 152*c3*c4*m5*s2*s5*s5 - 125*c2*c6*m6*s4*s5*s5 - 2000*c2*d5*m5*s4*s5*s5 - 2000*c2*d5*m6*s4*s5*s5 + 125*c3*c4*c5*c5*c6*m6*s2 + 2000*c3*c4*c5*c5*d5*m5*s2 + 125*c3*c4*c6*m6*s2*s5*s5 + 2000*c3*c4*d5*m5*s2*s5*s5 + 2000*c3*c4*d5*m6*s2*s5*s5 - 2000*c2*c5*c5*c6*c6*d5*m6*s4 - 2000*c2*c5*c5*d5*m6*s4*s6*s6 + 125*c3*c5*m6*s2*s4*s6 + 2000*c5*d5*m6*s2*s3*s5 - 2000*c5*c6*c6*d5*m6*s2*s3*s5 - 2000*c5*d5*m6*s2*s3*s5*s6*s6 + 2000*c3*c4*c5*c5*c6*c6*d5*m6*s2 + 2000*c3*c4*c5*c5*d5*m6*s2*s6*s6))/2000.0; tau=(g*(160*c3*c4*m4*s2 - 160*c2*m4*s4 + 152*c2*c5*c5*m5*s4 + 152*c2*m5*s4*s5*s5 + 125*c2*c4*c5*m6*s6 - 152*c3*c4*c5*c5*m5*s2 - 125*c2*c5*c5*c6*m6*s4 - 2000*c2*c5*c5*d5*m5*s4 - 152*c3*c4*m5*s2*s5*s5 - 125*c2*c6*m6*s4*s5*s5 - 2000*c2*d5*m5*s4*s5*s5 - 2000*c2*d5*m6*s4*s5*s5 + 125*c3*c4*c5*c5*c6*m6*s2 + 2000*c3*c4*c5*c5*d5*m5*s2 + 125*c3*c4*c6*m6*s2*s5*s5 + 2000*c3*c4*d5*m5*s2*s5*s5 + 2000*c3*c4*d5*m6*s2*s5*s5 - 2000*c2*c5*c5*c6*c6*d5*m6*s4 - 2000*c2*c5*c5*d5*m6*s4*s6*s6 + 125*c3*c5*m6*s2*s4*s6 + 2000*c5*d5*m6*s2*s3*s5 - 2000*c5*c6*c6*d5*m6*s2*s3*s5 - 2000*c5*d5*m6*s2*s3*s5*s6*s6 + 2000*c3*c4*c5*c5*c6*c6*d5*m6*s2 + 2000*c3*c4*c5*c5*d5*m6*s2*s6*s6))/2000.0; #endif return tau; } double gravity_compensation_joint_3(){ //std::cout<<"sin="<<sin(1.57)<<std::endl; double g=gravity_constant; double m3 = links_[2]->GetInertial()->Mass(); // because 3-th link in links_ is in fact 4-th link of the lwr4+ manipulator double m4 = links_[3]->GetInertial()->Mass(); // because 3-th link in links_ is in fact 4-th link of the lwr4+ manipulator double m5 = links_[4]->GetInertial()->Mass(); // because 4-th link in links_ is in fact 5-th link of the lwr4+ manipulator double m6 = links_[5]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double m7 = links_[6]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double d7= D7, d5 = D5, d3=D3, d1=D1; double l5= L5, l4=L4, l3=L3; double theta1=joints_[0]->Position(0); double theta2=joints_[1]->Position(0); double theta3=joints_[2]->Position(0); double theta4=joints_[3]->Position(0); double theta5=joints_[4]->Position(0); double theta6=joints_[5]->Position(0); double theta7=joints_[6]->Position(0); double c1=cos(theta1), c2=cos(theta2), c3=cos(theta3), c4=cos(theta4), c5=cos(theta5), c6=cos(theta6), c7=cos(theta7); double s1=sin(theta1), s2=sin(theta2), s3=sin(theta3), s4=sin(theta4), s5=sin(theta5), s6=sin(theta6), s7=sin(theta7); double tau=0; #ifdef OPTION_1 // wersja nr 1 /* */ //tau=-(g*(140*m4*s2*s3*s4 - 120*c3*m3*s2 + 120*c3*c4*c4*m4*s2 + 120*c3*m4*s2*s4*s4 - 152*c5*c5*m5*s2*s3*s4 - 152*m5*s2*s3*s4*s5*s5 - 2000*c2*c5*d5*m6*s4*s4*s5 - 125*c3*c4*c4*m6*s2*s5*s6 + 125*c5*c5*c6*m6*s2*s3*s4 + 2000*c5*c5*d5*m5*s2*s3*s4 + 2000*c5*c5*d5*m6*s2*s3*s4 - 125*c3*m6*s2*s4*s4*s5*s6 + 125*c6*m6*s2*s3*s4*s5*s5 + 2000*d5*m5*s2*s3*s4*s5*s5 - 125*c4*c5*m6*s2*s3*s6 + 2000*c2*c5*d5*m6*s4*s4*s5*s6*s6 + 2000*c6*c6*d5*m6*s2*s3*s4*s5*s5 + 2000*d5*m6*s2*s3*s4*s5*s5*s6*s6 + 2000*c2*c5*c6*c6*d5*m6*s4*s4*s5 + 2000*c3*c4*c5*d5*m6*s2*s4*s5 - 2000*c3*c4*c5*c6*c6*d5*m6*s2*s4*s5 - 2000*c3*c4*c5*d5*m6*s2*s4*s5*s6*s6))/2000.0; tau=-(g*(160*m4*s2*s3*s4 - 120*c3*m3*s2 + 120*c3*c4*c4*m4*s2 + 120*c3*m4*s2*s4*s4 - 152*c5*c5*m5*s2*s3*s4 - 152*m5*s2*s3*s4*s5*s5 - 2000*c2*c5*d5*m6*s4*s4*s5 - 125*c3*c4*c4*m6*s2*s5*s6 + 125*c5*c5*c6*m6*s2*s3*s4 + 2000*c5*c5*d5*m5*s2*s3*s4 + 2000*c5*c5*d5*m6*s2*s3*s4 - 125*c3*m6*s2*s4*s4*s5*s6 + 125*c6*m6*s2*s3*s4*s5*s5 + 2000*d5*m5*s2*s3*s4*s5*s5 - 125*c4*c5*m6*s2*s3*s6 + 2000*c2*c5*d5*m6*s4*s4*s5*s6*s6 + 2000*c6*c6*d5*m6*s2*s3*s4*s5*s5 + 2000*d5*m6*s2*s3*s4*s5*s5*s6*s6 + 2000*c2*c5*c6*c6*d5*m6*s4*s4*s5 + 2000*c3*c4*c5*d5*m6*s2*s4*s5 - 2000*c3*c4*c5*c6*c6*d5*m6*s2*s4*s5 - 2000*c3*c4*c5*d5*m6*s2*s4*s5*s6*s6))/2000.0; #endif return tau; } double gravity_compensation_joint_2(){ double g=gravity_constant; double m2 = links_[1]->GetInertial()->Mass(); // because 1-th link in links_ is in fact 2-th link of the lwr4+ manipulator double m3 = links_[2]->GetInertial()->Mass(); // because 2-th link in links_ is in fact 3-th link of the lwr4+ manipulator double m4 = links_[3]->GetInertial()->Mass(); // because 3-th link in links_ is in fact 4-th link of the lwr4+ manipulator double m5 = links_[4]->GetInertial()->Mass(); // because 4-th link in links_ is in fact 5-th link of the lwr4+ manipulator double m6 = links_[5]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double m7 = links_[6]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double d7= D7, d5 = D5, d3=D3, d1=D1; double l5= L5, l4=L4, l3=L3, l2=L2; double theta1=joints_[0]->Position(0); double theta2=joints_[1]->Position(0); double theta3=joints_[2]->Position(0); double theta4=joints_[3]->Position(0); double theta5=joints_[4]->Position(0); double theta6=joints_[5]->Position(0); double theta7=joints_[6]->Position(0); double c1=cos(theta1), c2=cos(theta2), c3=cos(theta3), c4=cos(theta4), c5=cos(theta5), c6=cos(theta6), c7=cos(theta7); double s1=sin(theta1), s2=sin(theta2), s3=sin(theta3), s4=sin(theta4), s5=sin(theta5), s6=sin(theta6), s7=sin(theta7); double tau=0; #ifdef OPTION_1 // wersja nr 1 /* */ /* tau=-(g*(140*m2*s2 - 140*c3*c3*m3*s2 - 140*m3*s2*s3*s3 - 120*c2*m3*s3 - 140*c2*c3*m4*s4 + 120*c2*c4*c4*m4*s3 + 140*c3*c3*c4*m4*s2 + 2000*c3*c3*d3*m3*s2 + 120*c2*m4*s3*s4*s4 + 140*c4*m4*s2*s3*s3 + 2000*d3*m3*s2*s3*s3 + 2000*d3*m4*s2*s3*s3 - 152*c3*c3*c4*c5*c5*m5*s2 + 2000*c3*c3*c4*c4*d3*m4*s2 - 152*c4*c5*c5*m5*s2*s3*s3 - 152*c3*c3*c4*m5*s2*s5*s5 + 2000*c3*c3*d3*m4*s2*s4*s4 + 2000*c3*c3*d3*m5*s2*s4*s4 + 2000*c5*c5*d3*m5*s2*s3*s3 + 2000*c5*c5*d3*m6*s2*s3*s3 - 152*c4*m5*s2*s3*s3*s5*s5 + 2000*d3*m5*s2*s3*s3*s5*s5 + 152*c2*c3*c5*c5*m5*s4 + 152*c2*c3*m5*s4*s5*s5 + 2000*c3*c3*d3*m6*s2*s4*s4*s6*s6 + 2000*c6*c6*d3*m6*s2*s3*s3*s5*s5 + 2000*d3*m6*s2*s3*s3*s5*s5*s6*s6 - 125*c2*c3*c5*c5*c6*m6*s4 - 2000*c2*c3*c5*c5*d5*m5*s4 - 125*c2*c3*c6*m6*s4*s5*s5 - 2000*c2*c3*d5*m5*s4*s5*s5 - 2000*c2*c3*d5*m6*s4*s5*s5 - 125*c2*c4*c4*m6*s3*s5*s6 + 125*c3*c3*c5*m6*s2*s4*s6 - 125*c2*m6*s3*s4*s4*s5*s6 + 125*c5*m6*s2*s3*s3*s4*s6 + 125*c3*c3*c4*c5*c5*c6*m6*s2 + 2000*c3*c3*c4*c5*c5*d5*m5*s2 + 125*c4*c5*c5*c6*m6*s2*s3*s3 + 125*c3*c3*c4*c6*m6*s2*s5*s5 + 2000*c4*c5*c5*d5*m5*s2*s3*s3 + 2000*c3*c3*c4*d5*m5*s2*s5*s5 + 2000*c4*c5*c5*d5*m6*s2*s3*s3 + 2000*c3*c3*c4*d5*m6*s2*s5*s5 + 125*c4*c6*m6*s2*s3*s3*s5*s5 + 2000*c4*d5*m5*s2*s3*s3*s5*s5 + 125*c2*c3*c4*c5*m6*s6 + 2000*c2*c3*c4*d3*m5*s4 + 2000*c3*c3*c4*c4*c5*c5*d3*m5*s2 + 2000*c3*c3*c4*c4*d3*m5*s2*s5*s5 + 2000*c3*c3*c4*c4*d3*m6*s2*s5*s5 + 2000*c3*c3*c6*c6*d3*m6*s2*s4*s4 + 2000*c3*c3*c4*c5*c5*c6*c6*d5*m6*s2 - 2000*c2*c5*d3*m6*s3*s4*s5 + 2000*c3*c5*d5*m6*s2*s3*s5 + 2000*c3*c3*c4*c5*c5*d5*m6*s2*s6*s6 + 2000*c4*c6*c6*d5*m6*s2*s3*s3*s5*s5 + 2000*c4*d5*m6*s2*s3*s3*s5*s5*s6*s6 - 2000*c2*c3*c4*c5*c5*d3*m5*s4 + 2000*c2*c3*c4*c6*c6*d3*m6*s4 - 2000*c2*c3*c4*d3*m5*s4*s5*s5 - 2000*c2*c3*c4*d3*m6*s4*s5*s5 + 2000*c2*c3*c4*d3*m6*s4*s6*s6 + 2000*c3*c3*c4*c4*c5*c5*c6*c6*d3*m6*s2 + 2000*c3*c3*c4*c4*c5*c5*d3*m6*s2*s6*s6 - 2000*c2*c3*c5*c5*c6*c6*d5*m6*s4 - 2000*c2*c3*c5*c5*d5*m6*s4*s6*s6 + 2000*c3*c4*c4*c5*d5*m6*s2*s3*s5 + 2000*c2*c5*c6*c6*d3*m6*s3*s4*s5 - 2000*c3*c5*c6*c6*d5*m6*s2*s3*s5 + 2000*c2*c5*d3*m6*s3*s4*s5*s6*s6 - 2000*c3*c5*d5*m6*s2*s3*s5*s6*s6 - 2000*c2*c3*c4*c5*c5*c6*c6*d3*m6*s4 - 2000*c2*c3*c4*c5*c5*d3*m6*s4*s6*s6 + 4000*c3*c4*c5*d3*m6*s2*s3*s5 - 2000*c2*c4*c5*d5*m6*s3*s4*s5 - 4000*c3*c4*c5*c6*c6*d3*m6*s2*s3*s5 + 2000*c2*c4*c5*c6*c6*d5*m6*s3*s4*s5 - 4000*c3*c4*c5*d3*m6*s2*s3*s5*s6*s6 + 2000*c2*c4*c5*d5*m6*s3*s4*s5*s6*s6 - 2000*c3*c4*c4*c5*c6*c6*d5*m6*s2*s3*s5 - 2000*c3*c4*c4*c5*d5*m6*s2*s3*s5*s6*s6))/2000.0; */ tau=-(g*(140*m2*s2 - 140*c3*c3*m3*s2 - 140*m3*s2*s3*s3 - 120*c2*m3*s3 - 160*c2*c3*m4*s4 + 120*c2*c4*c4*m4*s3 + 160*c3*c3*c4*m4*s2 + 2000*c3*c3*d3*m3*s2 + 120*c2*m4*s3*s4*s4 + 160*c4*m4*s2*s3*s3 + 2000*d3*m3*s2*s3*s3 + 2000*d3*m4*s2*s3*s3 - 152*c3*c3*c4*c5*c5*m5*s2 + 2000*c3*c3*c4*c4*d3*m4*s2 - 152*c4*c5*c5*m5*s2*s3*s3 - 152*c3*c3*c4*m5*s2*s5*s5 + 2000*c3*c3*d3*m4*s2*s4*s4 + 2000*c3*c3*d3*m5*s2*s4*s4 + 2000*c5*c5*d3*m5*s2*s3*s3 + 2000*c5*c5*d3*m6*s2*s3*s3 - 152*c4*m5*s2*s3*s3*s5*s5 + 2000*d3*m5*s2*s3*s3*s5*s5 + 152*c2*c3*c5*c5*m5*s4 + 152*c2*c3*m5*s4*s5*s5 + 2000*c3*c3*d3*m6*s2*s4*s4*s6*s6 + 2000*c6*c6*d3*m6*s2*s3*s3*s5*s5 + 2000*d3*m6*s2*s3*s3*s5*s5*s6*s6 - 125*c2*c3*c5*c5*c6*m6*s4 - 2000*c2*c3*c5*c5*d5*m5*s4 - 125*c2*c3*c6*m6*s4*s5*s5 - 2000*c2*c3*d5*m5*s4*s5*s5 - 2000*c2*c3*d5*m6*s4*s5*s5 - 125*c2*c4*c4*m6*s3*s5*s6 + 125*c3*c3*c5*m6*s2*s4*s6 - 125*c2*m6*s3*s4*s4*s5*s6 + 125*c5*m6*s2*s3*s3*s4*s6 + 125*c3*c3*c4*c5*c5*c6*m6*s2 + 2000*c3*c3*c4*c5*c5*d5*m5*s2 + 125*c4*c5*c5*c6*m6*s2*s3*s3 + 125*c3*c3*c4*c6*m6*s2*s5*s5 + 2000*c4*c5*c5*d5*m5*s2*s3*s3 + 2000*c3*c3*c4*d5*m5*s2*s5*s5 + 2000*c4*c5*c5*d5*m6*s2*s3*s3 + 2000*c3*c3*c4*d5*m6*s2*s5*s5 + 125*c4*c6*m6*s2*s3*s3*s5*s5 + 2000*c4*d5*m5*s2*s3*s3*s5*s5 + 125*c2*c3*c4*c5*m6*s6 + 2000*c2*c3*c4*d3*m5*s4 + 2000*c3*c3*c4*c4*c5*c5*d3*m5*s2 + 2000*c3*c3*c4*c4*d3*m5*s2*s5*s5 + 2000*c3*c3*c4*c4*d3*m6*s2*s5*s5 + 2000*c3*c3*c6*c6*d3*m6*s2*s4*s4 + 2000*c3*c3*c4*c5*c5*c6*c6*d5*m6*s2 - 2000*c2*c5*d3*m6*s3*s4*s5 + 2000*c3*c5*d5*m6*s2*s3*s5 + 2000*c3*c3*c4*c5*c5*d5*m6*s2*s6*s6 + 2000*c4*c6*c6*d5*m6*s2*s3*s3*s5*s5 + 2000*c4*d5*m6*s2*s3*s3*s5*s5*s6*s6 - 2000*c2*c3*c4*c5*c5*d3*m5*s4 + 2000*c2*c3*c4*c6*c6*d3*m6*s4 - 2000*c2*c3*c4*d3*m5*s4*s5*s5 - 2000*c2*c3*c4*d3*m6*s4*s5*s5 + 2000*c2*c3*c4*d3*m6*s4*s6*s6 + 2000*c3*c3*c4*c4*c5*c5*c6*c6*d3*m6*s2 + 2000*c3*c3*c4*c4*c5*c5*d3*m6*s2*s6*s6 - 2000*c2*c3*c5*c5*c6*c6*d5*m6*s4 - 2000*c2*c3*c5*c5*d5*m6*s4*s6*s6 + 2000*c3*c4*c4*c5*d5*m6*s2*s3*s5 + 2000*c2*c5*c6*c6*d3*m6*s3*s4*s5 - 2000*c3*c5*c6*c6*d5*m6*s2*s3*s5 + 2000*c2*c5*d3*m6*s3*s4*s5*s6*s6 - 2000*c3*c5*d5*m6*s2*s3*s5*s6*s6 - 2000*c2*c3*c4*c5*c5*c6*c6*d3*m6*s4 - 2000*c2*c3*c4*c5*c5*d3*m6*s4*s6*s6 + 4000*c3*c4*c5*d3*m6*s2*s3*s5 - 2000*c2*c4*c5*d5*m6*s3*s4*s5 - 4000*c3*c4*c5*c6*c6*d3*m6*s2*s3*s5 + 2000*c2*c4*c5*c6*c6*d5*m6*s3*s4*s5 - 4000*c3*c4*c5*d3*m6*s2*s3*s5*s6*s6 + 2000*c2*c4*c5*d5*m6*s3*s4*s5*s6*s6 - 2000*c3*c4*c4*c5*c6*c6*d5*m6*s2*s3*s5 - 2000*c3*c4*c4*c5*d5*m6*s2*s3*s5*s6*s6))/2000.0; #endif return tau; } double gravity_compensation_joint_1(){ double g=gravity_constant; double m1 = links_[0]->GetInertial()->Mass(); // because 0-th link in links_ is in fact 1-th link of the lwr4+ manipulator double m2 = links_[1]->GetInertial()->Mass(); // because 1-th link in links_ is in fact 2-th link of the lwr4+ manipulator double m3 = links_[2]->GetInertial()->Mass(); // because 2-th link in links_ is in fact 3-th link of the lwr4+ manipulator double m4 = links_[3]->GetInertial()->Mass(); // because 3-th link in links_ is in fact 4-th link of the lwr4+ manipulator double m5 = links_[4]->GetInertial()->Mass(); // because 4-th link in links_ is in fact 5-th link of the lwr4+ manipulator double m6 = links_[5]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double m7 = links_[6]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator #ifdef PRINT_DEBUG_INFO std::cout<<"M1="<<m1<<std::endl; std::cout<<"M2="<<m2<<std::endl; std::cout<<"M3="<<m3<<std::endl; std::cout<<"M4="<<m4<<std::endl; std::cout<<"M5="<<m5<<std::endl; std::cout<<"M6="<<m6<<std::endl; std::cout<<"M7="<<m7<<std::endl; #endif double d7= D7, d5 = D5, d3=D3, d1=D1; double l5= L5, l4=L4, l3=L3, l2=L2, l1=L1; double theta1=joints_[0]->Position(0); double theta2=joints_[1]->Position(0); double theta3=joints_[2]->Position(0); double theta4=joints_[3]->Position(0); double theta5=joints_[4]->Position(0); double theta6=joints_[5]->Position(0); double theta7=joints_[6]->Position(0); double c1=cos(theta1), c2=cos(theta2), c3=cos(theta3), c4=cos(theta4), c5=cos(theta5), c6=cos(theta6), c7=cos(theta7); double s1=sin(theta1), s2=sin(theta2), s3=sin(theta3), s4=sin(theta4), s5=sin(theta5), s6=sin(theta6), s7=sin(theta7); double tau=0; #ifdef OPTION_1 // wersja nr 1 /* tau=-g*(c3*c4*c4*d3*m4*s2*s2*s3 - c3*d3*m4*s2*s2*s3 - c3*c5*c5*d3*m5*s2*s2*s3 - c3*c5*c5*d3*m6*s2*s2*s3 - c2*c2*c5*d5*m6*s4*s4*s5 + c3*d3*m4*s2*s2*s3*s4*s4 + c3*d3*m5*s2*s2*s3*s4*s4 - c3*d3*m5*s2*s2*s3*s5*s5 + c5*d5*m6*s2*s2*s3*s3*s5 + c3*c4*d5*m6*s2*s2*s3*s5*s5 + c4*c5*d3*m6*s2*s2*s3*s3*s5 + c2*c4*d3*m5*s2*s3*s4 + c3*c4*c4*c5*c5*d3*m5*s2*s2*s3 - c3*c3*c4*c4*c5*d5*m6*s2*s2*s5 + c2*c2*c5*c6*c6*d5*m6*s4*s4*s5 + c3*c4*c4*d3*m5*s2*s2*s3*s5*s5 + c3*c4*c4*d3*m6*s2*s2*s3*s5*s5 + c3*c6*c6*d3*m6*s2*s2*s3*s4*s4 - c3*c6*c6*d3*m6*s2*s2*s3*s5*s5 - c5*c6*c6*d5*m6*s2*s2*s3*s3*s5 + c2*c2*c5*d5*m6*s4*s4*s5*s6*s6 + c3*d3*m6*s2*s2*s3*s4*s4*s6*s6 - c3*d3*m6*s2*s2*s3*s5*s5*s6*s6 - c5*d5*m6*s2*s2*s3*s3*s5*s6*s6 + c2*c5*c5*d5*m6*s2*s3*s4 - c2*d5*m6*s2*s3*s4*s5*s5 - c3*c4*c5*c5*d5*m6*s2*s2*s3 - c3*c3*c4*c5*d3*m6*s2*s2*s5 - c2*c4*c5*c5*d3*m5*s2*s3*s4 + c2*c4*c6*c6*d3*m6*s2*s3*s4 + c3*c4*c4*c5*c5*c6*c6*d3*m6*s2*s2*s3 + c3*c3*c4*c4*c5*c6*c6*d5*m6*s2*s2*s5 - c2*c4*d3*m5*s2*s3*s4*s5*s5 - c2*c4*d3*m6*s2*s3*s4*s5*s5 + c2*c4*d3*m6*s2*s3*s4*s6*s6 + c3*c4*c4*c5*c5*d3*m6*s2*s2*s3*s6*s6 + c3*c3*c4*c4*c5*d5*m6*s2*s2*s5*s6*s6 - c2*c5*c5*c6*c6*d5*m6*s2*s3*s4 - c2*c5*c5*d5*m6*s2*s3*s4*s6*s6 + c2*c6*c6*d5*m6*s2*s3*s4*s5*s5 + c2*d5*m6*s2*s3*s4*s5*s5*s6*s6 + c2*c3*c5*d3*m6*s2*s4*s5 + c3*c4*c5*c5*c6*c6*d5*m6*s2*s2*s3 + c3*c3*c4*c5*c6*c6*d3*m6*s2*s2*s5 + c3*c4*c5*c5*d5*m6*s2*s2*s3*s6*s6 - c3*c4*c6*c6*d5*m6*s2*s2*s3*s5*s5 - c4*c5*c6*c6*d3*m6*s2*s2*s3*s3*s5 + c3*c3*c4*c5*d3*m6*s2*s2*s5*s6*s6 - c3*c4*d5*m6*s2*s2*s3*s5*s5*s6*s6 - c4*c5*d3*m6*s2*s2*s3*s3*s5*s6*s6 + 2*c2*c3*c4*c5*d5*m6*s2*s4*s5 - c2*c3*c5*c6*c6*d3*m6*s2*s4*s5 - c2*c3*c5*d3*m6*s2*s4*s5*s6*s6 - c2*c4*c5*c5*c6*c6*d3*m6*s2*s3*s4 - c2*c4*c5*c5*d3*m6*s2*s3*s4*s6*s6 - 2*c2*c3*c4*c5*c6*c6*d5*m6*s2*s4*s5 - 2*c2*c3*c4*c5*d5*m6*s2*s4*s5*s6*s6); */ tau=-g*(c3*c4*c4*d3*m4*s2*s2*s3 - c3*d3*m4*s2*s2*s3 - c3*c5*c5*d3*m5*s2*s2*s3 - c3*c5*c5*d3*m6*s2*s2*s3 - c2*c2*c5*d5*m6*s4*s4*s5 + c3*d3*m4*s2*s2*s3*s4*s4 + c3*d3*m5*s2*s2*s3*s4*s4 - c3*d3*m5*s2*s2*s3*s5*s5 + c5*d5*m6*s2*s2*s3*s3*s5 + c3*c4*d5*m6*s2*s2*s3*s5*s5 + c4*c5*d3*m6*s2*s2*s3*s3*s5 + c2*c4*d3*m5*s2*s3*s4 + c3*c4*c4*c5*c5*d3*m5*s2*s2*s3 - c3*c3*c4*c4*c5*d5*m6*s2*s2*s5 + c2*c2*c5*c6*c6*d5*m6*s4*s4*s5 + c3*c4*c4*d3*m5*s2*s2*s3*s5*s5 + c3*c4*c4*d3*m6*s2*s2*s3*s5*s5 + c3*c6*c6*d3*m6*s2*s2*s3*s4*s4 - c3*c6*c6*d3*m6*s2*s2*s3*s5*s5 - c5*c6*c6*d5*m6*s2*s2*s3*s3*s5 + c2*c2*c5*d5*m6*s4*s4*s5*s6*s6 + c3*d3*m6*s2*s2*s3*s4*s4*s6*s6 - c3*d3*m6*s2*s2*s3*s5*s5*s6*s6 - c5*d5*m6*s2*s2*s3*s3*s5*s6*s6 + c2*c5*c5*d5*m6*s2*s3*s4 - c2*d5*m6*s2*s3*s4*s5*s5 - c3*c4*c5*c5*d5*m6*s2*s2*s3 - c3*c3*c4*c5*d3*m6*s2*s2*s5 - c2*c4*c5*c5*d3*m5*s2*s3*s4 + c2*c4*c6*c6*d3*m6*s2*s3*s4 + c3*c4*c4*c5*c5*c6*c6*d3*m6*s2*s2*s3 + c3*c3*c4*c4*c5*c6*c6*d5*m6*s2*s2*s5 - c2*c4*d3*m5*s2*s3*s4*s5*s5 - c2*c4*d3*m6*s2*s3*s4*s5*s5 + c2*c4*d3*m6*s2*s3*s4*s6*s6 + c3*c4*c4*c5*c5*d3*m6*s2*s2*s3*s6*s6 + c3*c3*c4*c4*c5*d5*m6*s2*s2*s5*s6*s6 - c2*c5*c5*c6*c6*d5*m6*s2*s3*s4 - c2*c5*c5*d5*m6*s2*s3*s4*s6*s6 + c2*c6*c6*d5*m6*s2*s3*s4*s5*s5 + c2*d5*m6*s2*s3*s4*s5*s5*s6*s6 + c2*c3*c5*d3*m6*s2*s4*s5 + c3*c4*c5*c5*c6*c6*d5*m6*s2*s2*s3 + c3*c3*c4*c5*c6*c6*d3*m6*s2*s2*s5 + c3*c4*c5*c5*d5*m6*s2*s2*s3*s6*s6 - c3*c4*c6*c6*d5*m6*s2*s2*s3*s5*s5 - c4*c5*c6*c6*d3*m6*s2*s2*s3*s3*s5 + c3*c3*c4*c5*d3*m6*s2*s2*s5*s6*s6 - c3*c4*d5*m6*s2*s2*s3*s5*s5*s6*s6 - c4*c5*d3*m6*s2*s2*s3*s3*s5*s6*s6 + 2*c2*c3*c4*c5*d5*m6*s2*s4*s5 - c2*c3*c5*c6*c6*d3*m6*s2*s4*s5 - c2*c3*c5*d3*m6*s2*s4*s5*s6*s6 - c2*c4*c5*c5*c6*c6*d3*m6*s2*s3*s4 - c2*c4*c5*c5*d3*m6*s2*s3*s4*s6*s6 - 2*c2*c3*c4*c5*c6*c6*d5*m6*s2*s4*s5 - 2*c2*c3*c4*c5*d5*m6*s2*s4*s5*s6*s6); #endif return tau; } /* Gravity compensation - algorithm nr 2 */ void getGravComp2(std::array<double, 7> &t) { // #ifdef PRINT_DEBUG_INFO std::cout<<"Gravitation compensation based on Newton-Euler dynamics equations"<<std::endl; #endif // // t[6]=gravity_compensation_joint_7(); // t[5]=gravity_compensation_joint_6(); //t[5]=0; // t[4]=gravity_compensation_joint_5(); //t[4]=0; // t[3]=gravity_compensation_joint_4(); //t[3]*=1.2; // t[2]=gravity_compensation_joint_3(); t[2]=0; // t[1]=gravity_compensation_joint_2(); //t[1]=t[1]*1.2; // t[0]=gravity_compensation_joint_1(); //t[0]=0; // eksperyment t[6]=gravity_compensation_joint_7(); t[5]=gravity_compensation_joint_6(); //t[5]=0; t[4]=gravity_compensation_joint_5(); //t[4]=0; t[3]=gravity_compensation_joint_4(); //t[3]*=1.2; t[2]=gravity_compensation_joint_3(); // t[2]=0; t[1]=gravity_compensation_joint_2(); //t[1]=t[1]*1.2; t[0]=gravity_compensation_joint_1(); //t[0]=0; // change the sign of the torque #ifdef PRINT_DEBUG_INFO std::cout<<std::endl; for (int i = 0; i < 7; ++i) { std::cout<<"[Optional] t["<<i<<"]="<<t[i]<<std::endl; } std::cout<<std::endl; #endif } /* gravity compensation - basic algorithm */ void getGravComp(std::array<double, 7 > &t) { // gravity vector ignition::math::Vector3d gr = gazebo::physics::get_world()->Gravity(); ignition::math::Vector3d tool_com; #ifdef PRINT_DEBUG_INFO std::cout<<"tool_com="<<tool_com<<std::endl; #endif // tool mass double tool_mass = 0; // pointer to the last link from the links_ vector - i.e. end effector gazebo::physics::LinkPtr link = links_[6]; // pointer to the last joint from the joints_ vector gazebo::physics::JointPtr joint = joints_[6]; // get the world pose of the link ignition::math::Pose3d T_W_L7 = link->WorldPose(); // get the global position of the last link, i.e. in simulation the last link is 6-th link #ifdef PRINT_DEBUG_INFO std::cout<<"T_W_L7="<<T_W_L7<<std::endl; #endif // add to T_W_L7 pose vector tool_com (is it empty?) ignition::math::Vector3d cog = T_W_L7.CoordPositionAdd( tool_com ); // calculate the center of gravity of link nr 6 (in fact we number all link from 0 to 6, so in fact here the last link is 6-th but in reality we say it is the 7-th link) #ifdef PRINT_DEBUG_INFO std::cout<<"tool_com for link 6 => tool_com="<<tool_com<<std::endl; std::cout<<"cog for link 6 => cog="<<cog<<std::endl; #endif // calculate new vector which is vector cog - position of last joint ignition::math::Vector3d r = cog - joint->WorldPose().Pos(); // calculate the distance between the global joint position and the center of gravity (i.e. it's a center of mass) #ifdef PRINT_DEBUG_INFO std::cout<<"r for link 6 => r="<<r<<std::endl; #endif // set a mass to tool_mass - i.e. it equals zero double mass = tool_mass; // tool mass we assume equals zero #ifdef PRINT_DEBUG_INFO std::cout<<"mass="<<mass<<std::endl; #endif // calculate torque as a cross product of two vectors r and gravity vector multiplied by mass (which is still zero) ignition::math::Vector3d torque = r.Cross(mass * gr); // we calculate the torque exerting on the last joint as a cross product of r and (mass * gr) [arm x mass * gravity constant], pay attention that the mass of the last link is zero // calculate axis ignition::math::Vector3d axis = joint->GlobalAxis(0); // rotation axis of joint nr 6 in global position t[6] = axis.Dot(torque); // dot product of axis and torque is a torque compansating the gravity for the last link #ifdef PRINT_DEBUG_INFO std::cout<<"#####################################"<<std::endl; std::cout<<"Joint position for i=6-th joint: "<<joint->WorldPose().Pos()<<std::endl; std::cout<<"Axis for i=6-th joint: "<<axis<<std::endl; std::cout<<"Torque for i=6-th joint: "<<t[6]<<std::endl; #endif // for each link within links_ - except the 6-th link for (int i = 6; i > 0; i--) { link = links_[i-1]; // get the (i-1)th link joint = joints_[i-1]; // get the (i-1)th joint // WorldCoGPose - get the pose of the body's center of gravity in the world coordinate frame // now we calculate the center of gravity for all links already visited, i.e. (i-1) to 6, we are using weighted mean cog = (cog * mass + link->WorldCoGPose().Pos() * link->GetInertial()->Mass()) / (mass+link->GetInertial()->Mass()); // we calculate here the weighted mean, based on this we calculate the center of gravity of the links (from i-1-th link do 6-th link) #ifdef PRINT_DEBUG_INFO std::cout<<"cog="<<cog<<std::endl; #endif // update the total mass of already visited links, i.e. (i-1) to 6 mass += link->GetInertial()->Mass(); // here we calculate the total sum of the manipulator (iteratively adding masses of links starting from end-effector, which has zero mass) #ifdef PRINT_DEBUG_INFO std::cout<<"mass["<<i-1<<"]="<<mass<<std::endl; #endif // caluclate the distance between the joint position and the center of gravity of all already visited joints r = cog - joint->WorldPose().Pos(); // calculate the torque excerting on joint, as a cross product of arm and the gravitation force acting on the arm torque = r.Cross(mass * gr); // global axis of joint (i-1) - i.e. rotation axis of joint, in other words the z-th vector from transformation matrix ^0_(i-1)T axis = joint->GlobalAxis(0); // torque exerting on joint (i-1) along, why dot product? because we calculate torque along z-th axis from transformation matrix (rotation axis of joint i-1 from poiint of view of base frame) t[i-1] = axis.Dot(torque); #ifdef PRINT_DEBUG_INFO std::cout<<"#####################################"<<std::endl; std::cout<<"Joint position for i="<<i-1<<"-th joint "<<joint->WorldPose().Pos()<<std::endl; std::cout<<"Axis for i="<<i-1<<"-th joint "<<axis<<std::endl; std::cout<<"Torque for i="<<i-1<<"-th joint "<<t[i-1]<<std::endl; #endif } #ifdef PRINT_DEBUG_INFO std::cout<<"#####################################"<<std::endl; std::cout<<""<<std::endl; std::cout<<""<<std::endl; std::cout<<"#####################################"<<std::endl; #endif // change the sign of the torque for (int i = 0; i < 7; ++i) { t[i] = -t[i]; #ifdef PRINT_DEBUG_INFO std::cout<<"[Original] t["<<i<<"]="<<t[i]<<std::endl; #endif } } // end of function getGravComp // just get center of gravity of each links void getCenterOfGravityJustForTests(){ #ifdef PRINT_DEBUG_INFO std::cout<<"Get center of gravity of links"<<std::endl; for(int i=0; i<7; i++){ std::cout<<"CoG of link "<<i+1<<"="<<links_[i]->WorldCoGPose().Pos()<<std::endl; } for(int i=0; i<7; i++){ std::cout<<"Joint position "<<i+1<<"="<<joints_[i]->WorldPose().Pos()<<std::endl; } for(int i=0; i<7; i++){ std::cout<<"Link position "<<i+1<<"="<<links_[i]->WorldPose().Pos()<<std::endl; } for(int i=0; i<7; i++){ std::cout<<"Delta "<<i+1<<"="<<links_[i]->WorldPose().Pos()-links_[i]->WorldCoGPose().Pos()<<std::endl; } #endif } #ifdef EXTERNAL_CALCULATIONS /* Set torque based on received data */ void setTorqueBasedOnReceiveDataFromSharedMemory(){ /* Read torques from shared memory */ struct lwr4_joints received_torque; //received_torque=shm_torque_consumer->readSynchronously(); // or received_torque=shm_torque_consumer->readAsynchronously(); // get table of joints for(int i=0;i<7;i++){ torque[i]=received_torque._joints[i]; //std::cout<<"Received data - torque["<<i+1<<"]="<<received_torque._joints[i]<<std::endl; } } /* Send current position and velocity of the last frame, i.e. end-effector frame */ void sendCurrentLWRManipulatorParameters(){ #ifdef PRINT_DEBUG_INFO std::cout<<"[sendCurrentLWRManipulatorParameters] -- Start "<<std::endl; #endif struct lwr4_kinematics_params current_lwr_params; current_lwr_params.theta1=joints_[0]->Position(0); //std::cout<<"sets theta1="<<joints_[0]->Position(0)<<std::endl; current_lwr_params.theta2=joints_[1]->Position(0); //std::cout<<"sets theta2="<<joints_[1]->Position(0)<<std::endl; current_lwr_params.theta3=joints_[2]->Position(0); //std::cout<<"sets theta3="<<joints_[2]->Position(0)<<std::endl; current_lwr_params.theta4=joints_[3]->Position(0); //std::cout<<"sets theta4="<<joints_[3]->Position(0)<<std::endl; current_lwr_params.theta5=joints_[4]->Position(0); //std::cout<<"sets theta5="<<joints_[4]->Position(0)<<std::endl; current_lwr_params.theta6=joints_[5]->Position(0); //std::cout<<"sets theta6="<<joints_[5]->Position(0)<<std::endl; current_lwr_params.theta7=joints_[6]->Position(0); //std::cout<<"sets theta7="<<joints_[6]->Position(0)<<std::endl; current_lwr_params.x_current=links_[6]->WorldPose().Pos().X()-links_[0]->WorldPose().Pos().X(); current_lwr_params.y_current=links_[6]->WorldPose().Pos().Y()-links_[0]->WorldPose().Pos().Y(); current_lwr_params.z_current=links_[6]->WorldPose().Pos().Z();//-links_[0]->WorldPose().Pos().Z(); //######################################## current_lwr_params.roll_current=equilibrium_roll; current_lwr_params.pitch_current=equilibrium_pitch; current_lwr_params.yaw_current=equilibrium_yaw; current_lwr_params.v_x=links_[6]->WorldLinearVel().X(); current_lwr_params.v_y=links_[6]->WorldLinearVel().Y(); current_lwr_params.v_z=links_[6]->WorldLinearVel().Z(); current_lwr_params.w_roll=0; current_lwr_params.w_pitch=0; current_lwr_params.w_yaw=0; /* Writes asynchronously - or in other way, e.g. Synchornously */ shm_parameters_producer->writeAsynchronously(current_lwr_params); } #endif // Called by the world update start event public: void OnUpdate() { torque.fill(0); // initialize all torques to 0 #ifdef EXTERNAL_CALCULATIONS /* calculation done in external process, data sent through share memory */ /* Shared memory - test */ //float msg_tmp = rand() % 360; //std::cout<<"Writes message: "<<msg_tmp<<std::endl; //shm_producer->writeSynchronously(msg_tmp); /* Update torque from shared memory */ setTorqueBasedOnReceiveDataFromSharedMemory(); #endif // END of EXTERNAL_CALCULATIONS #ifdef GAZEBO_CALCULATIONS // WORKS //LWR4KinematicsDynamics lwr=LWR4KinematicsDynamics(0, 30, 0, 10); //int i = lwr.function(4); // get gravity compensation torques - our function //getGravComp(t); //t.fill(0); // initialize all torques to 0 /* SUCCESS !!! - my version of gravity compensation based on Euler-Newton equations !!! - it works! */ // GRAVITY COMPENSATION!!! getGravComp2(torque); // gravity compensation version based on Euler-Newton equations (my version) //getCenterOfGravityJustForTests(); // ########################### // update equilibrium // equilibrium=equilibrium_global; // UpdateEquilibirum(); // ########################### // ############################################## // impedance control in joints //impedanceControlInJointSpace(t); // <<< ================================================================= // ############################################## // ############################################## // impedance control in joints impedanceControlInCartesianSpace(torque); // <<< ================================================================= // ############################################## // just to test impedance control in cartesian space updateCartesianImpedance(); #endif // END of GAZEBO_CALCULATIONS // ### - just for tests #ifdef CALCULATE_SAMPLING_PERIOD { std::cout<<"CALCULATE SAMPLING PERIOD"<<std::endl; std::chrono::duration<double> elapsed_time_between_iterations = std::chrono::system_clock::now()-end_time; std::cout<< "Elapsed between iterations: "<<elapsed_time_between_iterations.count()<<std::endl; end_time=std::chrono::system_clock::now(); } #endif // CALCULATE_SAMPLING_PERIOD // apply torques setForces(torque); saveEndEffectorPoseToFile(); // save to file current position of end-effector #ifdef EXTERNAL_CALCULATIONS /* SEND current position of end-effector frame */ sendCurrentLWRManipulatorParameters(); #endif } // end of function OnUpdate void updateCartesianImpedance(){ double radius=0.3; double origin_x=0; double origin_y=0; double origin_z=0.5; // ############# JUST TO print time - i.e. calculate the sampling period ######################## _iterations2++; // how many iterations are within a single cycle (waiting a whole cycle to change the desired cartesian position) if(_iterations2>ITERATIONS_IN_ONE_CYCLE){ _iterations2=0; // if number of iterations is greater then ITERATIONS_IN_ONE_CYCLE (the waiting time has been ended, set zero and calculate new cartesian position for end-effector) } else{ return; } //saveEndEffectorPoseToFile(); // save to file current position of end-effector if(_flag) // one direction of movement of manipulator's end-effector _iterations++; else // another direction of movement of manipulator's end-effector _iterations--; if(_iterations>MAX_ITERATIONS){ // check whether the whole movement in a desired direction has ended _iterations--; _flag=false; // change direction of movement } if(_iterations<0){ // check whether the whole movement in a desired direction has ended _iterations++; _flag=true; // change direction of movement } // ########################################################################################################################### // ######## Calculate desired position in cartesian space, i.e. equilibrium point ############################# // ########################################################################################################################### // in X-Y plane // double theta=(_iterations/MAX_ITERATIONS) * 360 * 3.14/180.0; // std::cout<<"!!!!!ITERATIONS="<<_iterations<<" theta="<<theta<<std::endl; // equilibrium_x= origin_x + radius * cos(theta); // equilibrium_y= origin_y + radius * sin(theta); // in Z-Y plane double theta=(_iterations/MAX_ITERATIONS) * 360 * 3.14/180.0; #ifdef PRINT_DEBUG_INFO std::cout<<"!!!!!ITERATIONS="<<_iterations<<" theta="<<theta<<" EQUILIBRIUM=("<<equilibrium_x<<","<<equilibrium_y<<","<<equilibrium_z<<")"<<std::endl; #endif equilibrium_z= origin_z + radius * sin(theta); equilibrium_y= origin_y + radius * cos(theta); // equilibrium in X coordinate is always the same - i.e. as defined at the beginning of this file: equilibrium_x=0.56; // ########################################################################################################################### // ########################################################################################################################### // ############# JUST TO print time - i.e. calculate the sampling period ######################## #ifdef CALCULATE_SAMPLING_PERIOD { end_time=std::chrono::system_clock::now(); std::cout<<"CALCULATE SAMPLING PERIOD"<<std::endl; std::chrono::duration<double> elapsed_seconds = end_time-start_time; std::cout<< "Elapsed time for a single iteration, i.e. time between calculating a new cartesian position: "<<elapsed_seconds.count()<<std::endl; start_time=end_time; } #endif // CALCULATE_SAMPLING_PERIOD // ######################################################### } // impedance control in joints void impedanceControlInJointSpace(std::array<double, 7> &t) { #ifdef PRINT_DEBUG_INFO std::cout<<"Impedance Control In Joint Space"<<std::endl; #endif // declare equilibrium point - set the desired position of the kinematic chain //std::array<double, 7 > eq({0.04, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4}); // almost vertical //std::array<double, 7 > eq ({0.04, 0, 0, 0, 0, 0, 0}); // joint angles in radians std::array<double, 7> eq = equilibrium; // calculate spring forces - becasue we utilise the impedance control - in joint space! // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! double k = 10; // stiffness constant for (int i = 0; i < t.size(); ++i) { double diff = eq[i] - joints_[i]->Position(0); // the difference between the equilibrium point and the current joint positions (Position(0) returns the current position of the axis nr 0) t[i] += k * diff; // add to torque additional force ? } } // # end of impedanceControlInJointSpace void saveInFile(std::string fileName, std::string what){ std::ofstream myfile; myfile.open (fileName, std::ios::app); myfile << what; myfile.close(); } void saveBasePoseToFile(){ std::ostringstream strs; strs << links_[0]->WorldPose().Pos().X()<<" "<<links_[0]->WorldPose().Pos().Y()<<" "<<0<<" "; strs<<0<<" "<<0<<" "<<0<<" "<<0<<" "<<0<<" "<<0<<" "<<0<<"\n"; std::string what = strs.str(); saveInFile("pozycje.txt", what); } void saveEndEffectorPoseToFile(){ double theta1=joints_[0]->Position(0); double theta2=joints_[1]->Position(0); double theta3=joints_[2]->Position(0); double theta4=joints_[3]->Position(0); double theta5=joints_[4]->Position(0); double theta6=joints_[5]->Position(0); double theta7=joints_[6]->Position(0); std::ostringstream strs; strs << links_[6]->WorldPose().Pos().X()<<" "<<links_[6]->WorldPose().Pos().Y()<<" "<<links_[6]->WorldPose().Pos().Z()<<" "; strs<<theta1<<" "<<theta2<<" "<<theta3<<" "<<theta4<<" "<<theta5<<" "<<theta6<<" "<<theta7<<"\n"; std::string what = strs.str(); saveInFile("pozycje.txt", what); } // impedance control in joints void impedanceControlInCartesianSpace(std::array<double, 7> &t) { #ifdef PRINT_DEBUG_INFO std::cout<<"Impedance Control In Cartesian Space"<<std::endl; #endif //ignition::math::Pose3d pos=ignition::math::Pose3d(links_[6]->WorldPose().Pos().X(), links_[6]->WorldPose().Pos().Y(), links_[6]->WorldPose().Pos().Z()); //_end_effector_position_vector.push_back(pos); // ################################################################################################## double d7= D7, d5 = D5, d3=D3, d1=D1; double l5= L5, l4=L4, l3=L3, l2=L2, l1=L1; double theta1=joints_[0]->Position(0); double theta2=joints_[1]->Position(0); double theta3=joints_[2]->Position(0); double theta4=joints_[3]->Position(0); double theta5=joints_[4]->Position(0); double theta6=joints_[5]->Position(0); double theta7=joints_[6]->Position(0); double c1=cos(theta1), c2=cos(theta2), c3=cos(theta3), c4=cos(theta4), c5=cos(theta5), c6=cos(theta6), c7=cos(theta7); double s1=sin(theta1), s2=sin(theta2), s3=sin(theta3), s4=sin(theta4), s5=sin(theta5), s6=sin(theta6), s7=sin(theta7); // ################################################################################################## // ################################################################################################## // declare equilibrium point - set the desired position of the kinematic chain // equilibrium point (x,y,z) double x_desired= equilibrium_x; double y_desired= equilibrium_y; double z_desired= equilibrium_z; double roll_desired = equilibrium_roll; double pitch_desired = equilibrium_pitch; double yaw_desired = equilibrium_yaw; // ################################################################################################## // ################################################################################################## // calculate spring forces - becasue we utilise the impedance control - in cartesian space! // ################################################################################################## // ################################################################################################## // double x_current=links_[6]->WorldPose().Pos().X()-links_[0]->WorldPose().Pos().X(); // double y_current=links_[6]->WorldPose().Pos().Y()-links_[0]->WorldPose().Pos().Y(); // double z_current=links_[6]->WorldPose().Pos().Z(); // double roll_current=links_[6]->WorldPose().Rot().Yaw(); // double pitch_current=links_[6]->WorldPose().Rot().Pitch(); // double yaw_current=links_[6]->WorldPose().Rot().Roll(); // ################################################################################### // in XY AXIS // double x_current=links_[6]->WorldPose().Pos().X()-links_[0]->WorldPose().Pos().X(); // double y_current=links_[6]->WorldPose().Pos().Y()-links_[0]->WorldPose().Pos().Y(); // double z_current=z_desired;//links_[6]->WorldPose().Pos().Z()-links_[0]->WorldPose().Pos().Z(); //######################################## // ################################################################################### // in XZ AXIS double x_current=links_[6]->WorldPose().Pos().X()-links_[0]->WorldPose().Pos().X(); double y_current=links_[6]->WorldPose().Pos().Y()-links_[0]->WorldPose().Pos().Y(); double z_current=links_[6]->WorldPose().Pos().Z();//-links_[0]->WorldPose().Pos().Z(); //######################################## double roll_current=roll_desired; double pitch_current=pitch_desired; double yaw_current=yaw_desired; // ################################################################################################## // ################################################################################################## // linear and angular velocities of the end-effector of LWR4+ manipulator // double v_x=links_[6]->WorldLinearVel().X(); // double v_y=links_[6]->WorldLinearVel().Y(); // double v_z=links_[6]->WorldLinearVel().Z(); //double w_roll=links_[6]->WorldAngularVel().X(); //double w_pitch=links_[6]->WorldAngularVel().Y(); //double w_yaw=links_[6]->WorldAngularVel().Z(); // ################# in XY AXIS // double v_x=links_[6]->WorldLinearVel().X(); // double v_y=links_[6]->WorldLinearVel().Y(); // double v_z=0;//links_[6]->WorldLinearVel().Z(); // ################# in ZY AXIS double v_x=links_[6]->WorldLinearVel().X(); double v_y=links_[6]->WorldLinearVel().Y(); double v_z=links_[6]->WorldLinearVel().Z(); double w_roll=0; double w_pitch=0; double w_yaw=0; // ################################################################################################## #ifdef PRINT_DEBUG_INFO std::cout<<"Current position of end-effector (X,Y,Z)=("<<x_current<<","<<y_current<<","<<z_current<<") angles (ROLL,PITCH,YAW)="<<roll_current<<","<<pitch_current<<","<<yaw_current<<")"<<std::endl; #endif // difference_k means the distance between k_desired and k_current along k-axis //double difference_x=x_desired-x_current; //double difference_y=y_desired-y_current; //double difference_z=z_desired-z_current; //double difference_roll=roll_desired-roll_current; //double difference_pitch=pitch_desired-pitch_current; //double difference_yaw=yaw_desired-yaw_current; double difference_x=x_desired-x_current; double difference_y=y_desired-y_current; double difference_z=z_desired-z_current; double difference_roll=0; double difference_pitch=0; double difference_yaw=0; #ifdef PRINT_DEBUG_INFO std::cout<<"Difference between desired and current position of end-effector (X,Y,Z)=("<<difference_x<<","<<difference_y<<","<<difference_z<<") angles (ROLL,PITCH,YAW)="<<roll_current<<","<<pitch_current<<","<<yaw_current<<")"<<std::endl; #endif // delta time - time between two iterations //double delta_t =0.0001; // stiffness constant double k=0; // stiffness matrix components double k11=k, k12=k, k13=k, k14=k, k15=k, k16=k, k21=k, k22=k, k23=k, k24=k, k25=k, k26=k, k31=k, k32=k, k33=k, k34=k, k35=k, k36=k, k41=k, k42=k, k43=k, k44=k, k45=k, k46=k, k51=k, k52=k, k53=k, k54=k, k55=k, k56=k, k61=k, k62=k, k63=k, k64=k, k65=k, k66=k; double k_diag=30; // 40 ok // set up diagonal parameters of stiffness matrix k11=k_diag; k22=k_diag; k33=k_diag; k44=k_diag; k55=k_diag; k66=k_diag; //damping constant double d=0; // damping matrix components double d11=d, d12=d, d13=d, d14=d, d15=d, d16=d, d21=d, d22=d, d23=d, d24=d, d25=d, d26=d, d31=d, d32=d, d33=d, d34=d, d35=d, d36=d, d41=d, d42=d, d43=d, d44=d, d45=d, d46=d, d51=d, d52=d, d53=d, d54=d, d55=d, d56=d, d61=d, d62=d, d63=d, d64=d, d65=d, d66=d; double d_diag=10; d11=d_diag; d22=d_diag; d33=d_diag; d44=d_diag; d55=d_diag; d66=d_diag; // torque for joint 1 double t1=k65*(pitch_desired - pitch_current) - d62*v_y - d63*v_z - d65*w_pitch - d64*w_roll - d66*w_yaw - (d5*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) + d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3))) + c1*d3*s2)*(d21*v_x + d22*v_y + d23*v_z + d25*w_pitch + d24*w_roll + d26*w_yaw - k25*(pitch_desired - pitch_current) - k24*(roll_desired - roll_current) + k21*(x_current - x_desired) + k22*(y_current - y_desired) - k26*(yaw_desired - yaw_current) + k23*(z_current - z_desired)) - d61*v_x + k64*(roll_desired - roll_current) - k61*(x_current - x_desired) - k62*(y_current - y_desired) + k66*(yaw_desired - yaw_current) - k63*(z_current - z_desired) - (d5*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) + d7*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3))) - d3*s1*s2)*(d11*v_x + d12*v_y + d13*v_z + d15*w_pitch + d14*w_roll + d16*w_yaw - k15*(pitch_desired - pitch_current) - k14*(roll_desired - roll_current) + k11*(x_current - x_desired) + k12*(y_current - y_desired) - k16*(yaw_desired - yaw_current) + k13*(z_current - z_desired)); // torque for joint nr 2 double t2=(c1*(d5*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) + d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3))) + c1*d3*s2) - s1*(d5*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) + d7*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3))) - d3*s1*s2))*(d31*v_x + d32*v_y + d33*v_z + d35*w_pitch + d34*w_roll + d36*w_yaw - k35*(pitch_desired - pitch_current) - k34*(roll_desired - roll_current) + k31*(x_current - x_desired) + k32*(y_current - y_desired) - k36*(yaw_desired - yaw_current) + k33*(z_current - z_desired)) - c1*(d51*v_x + d52*v_y + d53*v_z + d55*w_pitch + d54*w_roll + d56*w_yaw - k55*(pitch_desired - pitch_current) - k54*(roll_desired - roll_current) + k51*(x_current - x_desired) + k52*(y_current - y_desired) - k56*(yaw_desired - yaw_current) + k53*(z_current - z_desired)) + s1*(d41*v_x + d42*v_y + d43*v_z + d45*w_pitch + d44*w_roll + d46*w_yaw - k45*(pitch_desired - pitch_current) - k44*(roll_desired - roll_current) + k41*(x_current - x_desired) + k42*(y_current - y_desired) - k46*(yaw_desired - yaw_current) + k43*(z_current - z_desired)) - c1*(c2*d3 + d7*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4)) + d5*(c2*c4 + c3*s2*s4))*(d11*v_x + d12*v_y + d13*v_z + d15*w_pitch + d14*w_roll + d16*w_yaw - k15*(pitch_desired - pitch_current) - k14*(roll_desired - roll_current) + k11*(x_current - x_desired) + k12*(y_current - y_desired) - k16*(yaw_desired - yaw_current) + k13*(z_current - z_desired)) - s1*(c2*d3 + d7*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4)) + d5*(c2*c4 + c3*s2*s4))*(d21*v_x + d22*v_y + d23*v_z + d25*w_pitch + d24*w_roll + d26*w_yaw - k25*(pitch_desired - pitch_current) - k24*(roll_desired - roll_current) + k21*(x_current - x_desired) + k22*(y_current - y_desired) - k26*(yaw_desired - yaw_current) + k23*(z_current - z_desired)); // torque for joint nr 3 double t3=(s1*s2*(d5*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) + d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3)))) + c1*s2*(d5*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) + d7*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3)))))*(d31*v_x + d32*v_y + d33*v_z + d35*w_pitch + d34*w_roll + d36*w_yaw - k35*(pitch_desired - pitch_current) - k34*(roll_desired - roll_current) + k31*(x_current - x_desired) + k32*(y_current - y_desired) - k36*(yaw_desired - yaw_current) + k33*(z_current - z_desired)) - (c2*(d5*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) + d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3)))) - c1*s2*(d7*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4)) + d5*(c2*c4 + c3*s2*s4)))*(d21*v_x + d22*v_y + d23*v_z + d25*w_pitch + d24*w_roll + d26*w_yaw - k25*(pitch_desired - pitch_current) - k24*(roll_desired - roll_current) + k21*(x_current - x_desired) + k22*(y_current - y_desired) - k26*(yaw_desired - yaw_current) + k23*(z_current - z_desired)) - (c2*(d5*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) + d7*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3)))) + s1*s2*(d7*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4)) + d5*(c2*c4 + c3*s2*s4)))*(d11*v_x + d12*v_y + d13*v_z + d15*w_pitch + d14*w_roll + d16*w_yaw - k15*(pitch_desired - pitch_current) - k14*(roll_desired - roll_current) + k11*(x_current - x_desired) + k12*(y_current - y_desired) - k16*(yaw_desired - yaw_current) + k13*(z_current - z_desired)) - c2*(d61*v_x + d62*v_y + d63*v_z + d65*w_pitch + d64*w_roll + d66*w_yaw - k65*(pitch_desired - pitch_current) - k64*(roll_desired - roll_current) + k61*(x_current - x_desired) + k62*(y_current - y_desired) - k66*(yaw_desired - yaw_current) + k63*(z_current - z_desired)) - c1*s2*(d41*v_x + d42*v_y + d43*v_z + d45*w_pitch + d44*w_roll + d46*w_yaw - k45*(pitch_desired - pitch_current) - k44*(roll_desired - roll_current) + k41*(x_current - x_desired) + k42*(y_current - y_desired) - k46*(yaw_desired - yaw_current) + k43*(z_current - z_desired)) - s1*s2*(d51*v_x + d52*v_y + d53*v_z + d55*w_pitch + d54*w_roll + d56*w_yaw - k55*(pitch_desired - pitch_current) - k54*(roll_desired - roll_current) + k51*(x_current - x_desired) + k52*(y_current - y_desired) - k56*(yaw_desired - yaw_current) + k53*(z_current - z_desired)); // torque for joint nr 4 double t4=(c1*c3 - c2*s1*s3)*(d51*v_x + d52*v_y + d53*v_z + d55*w_pitch + d54*w_roll + d56*w_yaw - k55*(pitch_desired - pitch_current) - k54*(roll_desired - roll_current) + k51*(x_current - x_desired) + k52*(y_current - y_desired) - k56*(yaw_desired - yaw_current) + k53*(z_current - z_desired)) - (c3*s1 + c1*c2*s3)*(d41*v_x + d42*v_y + d43*v_z + d45*w_pitch + d44*w_roll + d46*w_yaw - k45*(pitch_desired - pitch_current) - k44*(roll_desired - roll_current) + k41*(x_current - x_desired) + k42*(y_current - y_desired) - k46*(yaw_desired - yaw_current) + k43*(z_current - z_desired)) + ((c3*s1 + c1*c2*s3)*(d7*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4)) + d5*(c2*c4 + c3*s2*s4)) + s2*s3*(d5*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) + d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3)))))*(d21*v_x + d22*v_y + d23*v_z + d25*w_pitch + d24*w_roll + d26*w_yaw - k25*(pitch_desired - pitch_current) - k24*(roll_desired - roll_current) + k21*(x_current - x_desired) + k22*(y_current - y_desired) - k26*(yaw_desired - yaw_current) + k23*(z_current - z_desired)) - ((c1*c3 - c2*s1*s3)*(d5*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) + d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3)))) - (d5*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) + d7*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3))))*(c3*s1 + c1*c2*s3))*(d31*v_x + d32*v_y + d33*v_z + d35*w_pitch + d34*w_roll + d36*w_yaw - k35*(pitch_desired - pitch_current) - k34*(roll_desired - roll_current) + k31*(x_current - x_desired) + k32*(y_current - y_desired) - k36*(yaw_desired - yaw_current) + k33*(z_current - z_desired)) + ((c1*c3 - c2*s1*s3)*(d7*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4)) + d5*(c2*c4 + c3*s2*s4)) + s2*s3*(d5*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) + d7*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3)))))*(d11*v_x + d12*v_y + d13*v_z + d15*w_pitch + d14*w_roll + d16*w_yaw - k15*(pitch_desired - pitch_current) - k14*(roll_desired - roll_current) + k11*(x_current - x_desired) + k12*(y_current - y_desired) - k16*(yaw_desired - yaw_current) + k13*(z_current - z_desired)) + s2*s3*(d61*v_x + d62*v_y + d63*v_z + d65*w_pitch + d64*w_roll + d66*w_yaw - k65*(pitch_desired - pitch_current) - k64*(roll_desired - roll_current) + k61*(x_current - x_desired) + k62*(y_current - y_desired) - k66*(yaw_desired - yaw_current) + k63*(z_current - z_desired)); // torque for joint nr 5 double t5=(d7*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4))*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3)))*(c2*c4 + c3*s2*s4))*(d21*v_x + d22*v_y + d23*v_z + d25*w_pitch + d24*w_roll + d26*w_yaw - k25*(pitch_desired - pitch_current) - k24*(roll_desired - roll_current) + k21*(x_current - x_desired) + k22*(y_current - y_desired) - k26*(yaw_desired - yaw_current) + k23*(z_current - z_desired)) - (c2*c4 + c3*s2*s4)*(d61*v_x + d62*v_y + d63*v_z + d65*w_pitch + d64*w_roll + d66*w_yaw - k65*(pitch_desired - pitch_current) - k64*(roll_desired - roll_current) + k61*(x_current - x_desired) + k62*(y_current - y_desired) - k66*(yaw_desired - yaw_current) + k63*(z_current - z_desired)) - (d7*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3)))*(c2*c4 + c3*s2*s4) - d7*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2)*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4)))*(d11*v_x + d12*v_y + d13*v_z + d15*w_pitch + d14*w_roll + d16*w_yaw - k15*(pitch_desired - pitch_current) - k14*(roll_desired - roll_current) + k11*(x_current - x_desired) + k12*(y_current - y_desired) - k16*(yaw_desired - yaw_current) + k13*(z_current - z_desired)) - (s4*(s1*s3 - c1*c2*c3) + c1*c4*s2)*(d41*v_x + d42*v_y + d43*v_z + d45*w_pitch + d44*w_roll + d46*w_yaw - k45*(pitch_desired - pitch_current) - k44*(roll_desired - roll_current) + k41*(x_current - x_desired) + k42*(y_current - y_desired) - k46*(yaw_desired - yaw_current) + k43*(z_current - z_desired)) + (s4*(c1*s3 + c2*c3*s1) - c4*s1*s2)*(d51*v_x + d52*v_y + d53*v_z + d55*w_pitch + d54*w_roll + d56*w_yaw - k55*(pitch_desired - pitch_current) - k54*(roll_desired - roll_current) + k51*(x_current - x_desired) + k52*(y_current - y_desired) - k56*(yaw_desired - yaw_current) + k53*(z_current - z_desired)) - (d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3)))*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - d7*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3)))*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2))*(d31*v_x + d32*v_y + d33*v_z + d35*w_pitch + d34*w_roll + d36*w_yaw - k35*(pitch_desired - pitch_current) - k34*(roll_desired - roll_current) + k31*(x_current - x_desired) + k32*(y_current - y_desired) - k36*(yaw_desired - yaw_current) + k33*(z_current - z_desired)); // torque for joint nr 6 double t6=(s5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) - c5*(c1*c3 - c2*s1*s3))*(d51*v_x + d52*v_y + d53*v_z + d55*w_pitch + d54*w_roll + d56*w_yaw - k55*(pitch_desired - pitch_current) - k54*(roll_desired - roll_current) + k51*(x_current - x_desired) + k52*(y_current - y_desired) - k56*(yaw_desired - yaw_current) + k53*(z_current - z_desired)) + (d7*(s5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) - c5*(c3*s1 + c1*c2*s3))*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4)) + d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3)))*(s5*(c2*s4 - c3*c4*s2) - c5*s2*s3))*(d21*v_x + d22*v_y + d23*v_z + d25*w_pitch + d24*w_roll + d26*w_yaw - k25*(pitch_desired - pitch_current) - k24*(roll_desired - roll_current) + k21*(x_current - x_desired) + k22*(y_current - y_desired) - k26*(yaw_desired - yaw_current) + k23*(z_current - z_desired)) + (d7*(s5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) - c5*(c3*s1 + c1*c2*s3))*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3))) - d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3)))*(s5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) - c5*(c1*c3 - c2*s1*s3)))*(d31*v_x + d32*v_y + d33*v_z + d35*w_pitch + d34*w_roll + d36*w_yaw - k35*(pitch_desired - pitch_current) - k34*(roll_desired - roll_current) + k31*(x_current - x_desired) + k32*(y_current - y_desired) - k36*(yaw_desired - yaw_current) + k33*(z_current - z_desired)) + (d7*(s5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) - c5*(c1*c3 - c2*s1*s3))*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4)) + d7*(s5*(c2*s4 - c3*c4*s2) - c5*s2*s3)*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3))))*(d11*v_x + d12*v_y + d13*v_z + d15*w_pitch + d14*w_roll + d16*w_yaw - k15*(pitch_desired - pitch_current) - k14*(roll_desired - roll_current) + k11*(x_current - x_desired) + k12*(y_current - y_desired) - k16*(yaw_desired - yaw_current) + k13*(z_current - z_desired)) + (s5*(c2*s4 - c3*c4*s2) - c5*s2*s3)*(d61*v_x + d62*v_y + d63*v_z + d65*w_pitch + d64*w_roll + d66*w_yaw - k65*(pitch_desired - pitch_current) - k64*(roll_desired - roll_current) + k61*(x_current - x_desired) + k62*(y_current - y_desired) - k66*(yaw_desired - yaw_current) + k63*(z_current - z_desired)) - (s5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) - c5*(c3*s1 + c1*c2*s3))*(d41*v_x + d42*v_y + d43*v_z + d45*w_pitch + d44*w_roll + d46*w_yaw - k45*(pitch_desired - pitch_current) - k44*(roll_desired - roll_current) + k41*(x_current - x_desired) + k42*(y_current - y_desired) - k46*(yaw_desired - yaw_current) + k43*(z_current - z_desired)); // torque for joint nr 7 double t7=(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3)))*(d51*v_x + d52*v_y + d53*v_z + d55*w_pitch + d54*w_roll + d56*w_yaw - k55*(pitch_desired - pitch_current) - k54*(roll_desired - roll_current) + k51*(x_current - x_desired) + k52*(y_current - y_desired) - k56*(yaw_desired - yaw_current) + k53*(z_current - z_desired)) - (s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4))*(d61*v_x + d62*v_y + d63*v_z + d65*w_pitch + d64*w_roll + d66*w_yaw - k65*(pitch_desired - pitch_current) - k64*(roll_desired - roll_current) + k61*(x_current - x_desired) + k62*(y_current - y_desired) - k66*(yaw_desired - yaw_current) + k63*(z_current - z_desired)) - (c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3)))*(d41*v_x + d42*v_y + d43*v_z + d45*w_pitch + d44*w_roll + d46*w_yaw - k45*(pitch_desired - pitch_current) - k44*(roll_desired - roll_current) + k41*(x_current - x_desired) + k42*(y_current - y_desired) - k46*(yaw_desired - yaw_current) + k43*(z_current - z_desired)); #ifdef PRINT_DEBUG_INFO std::cout<<"Calculated torques - impedance control in Cartesian space: "<<std::endl; std::cout<<"[Torque] t1 = "<<t1<<std::endl; std::cout<<"[Torque] t2 = "<<t2<<std::endl; std::cout<<"[Torque] t3 = "<<t3<<std::endl; std::cout<<"[Torque] t4 = "<<t4<<std::endl; std::cout<<"[Torque] t5 = "<<t5<<std::endl; std::cout<<"[Torque] t6 = "<<t6<<std::endl; std::cout<<"[Torque] t7 = "<<t7<<std::endl; #endif t[0]+=t1; t[1]+=t2; t[2]+=t3; t[3]+=t4; t[4]+=t5; t[5]+=t6; t[6]+=t7; // for (int i = 0; i < t.size(); ++i) { // double diff = eq[i] - joints_[i]->Position(0); // the difference between the equilibrium point and the current joint positions (Position(0) returns the current position of the axis nr 0) // t[i] += k * diff; // add to torque additional force ? // } } // # end of impedanceControlInCartesianSpace // ################################# // update equilibrium public: void UpdateEquilibirum(){ equilibrium[0]+=eq_0_step; equilibrium[3]+=eq_3_step; if(equilibrium[0]>3.14) { equilibrium[0]=3.14; eq_0_step*=-1; } else if(equilibrium[0]<-3.14){ equilibrium[0]=-3.14; eq_0_step*=-1; } if(equilibrium[3]>1.14) { equilibrium[3]=1.14; eq_3_step*=-1; } else if(equilibrium[3]<-1.14){ equilibrium[3]=-1.14; eq_3_step*=-1; } } private: void subscribe_callback_function(AnyPtr & _msg){ int i; #ifdef PRINT_DEBUG_INFO std::cout << "Message received:\nMessage type="<<_msg->type()<<std::endl; #endif if(_msg->type()==2){ // double -> angle #ifdef PRINT_DEBUG_INFO std::cout << "Double="<<_msg->double_value()<<std::endl; #endif // equilibrium_global[0]=_msg->double_value(); equilibrium[kinematic_chain_index]=_msg->double_value(); } else if(_msg->type()==3){ // int -> index of kinematic chain i=_msg->int_value(); #ifdef PRINT_DEBUG_INFO std::cout << "Int="<<i<<std::endl; #endif if(i>=0 && i<=6){ kinematic_chain_index=i; } } } private: void subscribe_callback_function_kuka_joints(KukaJointsPtr & _msg){ int i; equilibrium[0]=_msg->joint_0(); equilibrium[1]=_msg->joint_1(); equilibrium[2]=_msg->joint_2(); equilibrium[3]=_msg->joint_3(); equilibrium[4]=_msg->joint_4(); equilibrium[5]=_msg->joint_5(); equilibrium[6]=_msg->joint_6(); #ifdef PRINT_DEBUG_INFO std::cout << "Message received:\n\ Joint_0="<<_msg->joint_0()<< "\nJoint_1="<<_msg->joint_1()<< "\nJoint_2="<<_msg->joint_2()<< "\nJoint_3="<<_msg->joint_3()<< "\nJoint_4="<<_msg->joint_4()<< "\nJoint_5="<<_msg->joint_5()<< "\nJoint_6="<<_msg->joint_6()<<std::endl; #endif } private: double eq_0_step, eq_3_step; public: std::array<double,7> equilibrium; public: double equilibrium_x; public: double equilibrium_y; public: double equilibrium_z; public: double equilibrium_roll; public: double equilibrium_pitch; public: double equilibrium_yaw; public: double x_last; public: double y_last; public: double z_last; public: double roll_last; public: double pitch_last; public: double yaw_last; public: double _iterations; // for impedance control test public: double _iterations2; // for impedance control test public: double _flag; // for impedance control test public: std::vector<ignition::math::Pose3d> _end_effector_position_vector; private: int kinematic_chain_index; // ################################# // Pointer to the model private: physics::ModelPtr model_; // Pointer to the update event connection private: event::ConnectionPtr updateConnection; // Pointer to the subscriber private: transport::SubscriberPtr sub, sub_kuka_joints; private: // vector of joint pointers std::vector<gazebo::physics::JointPtr > joints_; // vector of link pointers std::vector<gazebo::physics::LinkPtr > links_; /* For communication - shared memory */ //SharedMemory<float> *shm_producer; /* Shared memory - torque calculated for gazebo simulation */ SharedMemory<struct lwr4_joints> *shm_torque_consumer; /* Shared memory - manipulator parameters, such as angles in joint space (theta) and velocities */ SharedMemory<struct lwr4_kinematics_params> *shm_parameters_producer; /* Manipulator torque */ std::array<double, 7 > torque; /* Measuring the iteration time */ std::chrono::time_point<std::chrono::system_clock> start_time; std::chrono::time_point<std::chrono::system_clock> end_time; }; // Register this plugin with the simulator GZ_REGISTER_MODEL_PLUGIN(ModelKukaLwr) }
63.224767
2,711
0.599192
mfigat
483116ba7daa8eed90262193e27e4f97eb2872bc
9,344
cpp
C++
libs/vgc/ui/lineedit.cpp
PixelRick/vgc
154cc275449a51327a36cb6386a17bbcf1149686
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
libs/vgc/ui/lineedit.cpp
PixelRick/vgc
154cc275449a51327a36cb6386a17bbcf1149686
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
libs/vgc/ui/lineedit.cpp
PixelRick/vgc
154cc275449a51327a36cb6386a17bbcf1149686
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// Copyright 2021 The VGC Developers // See the COPYRIGHT file at the top-level directory of this distribution // and at https://github.com/vgc/vgc/blob/master/COPYRIGHT // // 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 <vgc/ui/lineedit.h> #include <QKeyEvent> #include <vgc/core/array.h> #include <vgc/core/colors.h> #include <vgc/core/performancelog.h> #include <vgc/ui/cursor.h> #include <vgc/ui/strings.h> #include <vgc/ui/style.h> #include <vgc/ui/internal/paintutil.h> namespace vgc { namespace ui { LineEdit::LineEdit(std::string_view text) : Widget(), text_(""), shapedText_(graphics::fontLibrary()->defaultFace(), text_), textCursor_(false, 0), scrollLeft_(0.0f), reload_(true), isHovered_(false), isMousePressed_(false) { addClass(strings::LineEdit); setText(text); } LineEditPtr LineEdit::create() { return LineEditPtr(new LineEdit("")); } LineEditPtr LineEdit::create(std::string_view text) { return LineEditPtr(new LineEdit(text)); } void LineEdit::setText(std::string_view text) { if (text_ != text) { text_ = text; shapedText_.setText(text); reload_ = true; repaint(); } } void LineEdit::onResize() { reload_ = true; } void LineEdit::onPaintCreate(graphics::Engine* engine) { triangles_ = engine->createTriangles(); } void LineEdit::onPaintDraw(graphics::Engine*) { if (reload_) { reload_ = false; core::FloatArray a; core::Color backgroundColor = internal::getColor(this, isHovered_ ? strings::background_color_on_hover : strings::background_color); #ifdef VGC_QOPENGL_EXPERIMENT static core::Stopwatch sw = {}; auto t = sw.elapsed() * 50.f; backgroundColor = core::Color::hsl(t, 0.6f, 0.3f); #endif core::Color textColor = internal::getColor(this, strings::text_color); float borderRadius = internal::getLength(this, strings::border_radius); float paddingLeft = internal::getLength(this, strings::padding_left); float paddingRight = internal::getLength(this, strings::padding_right); float textWidth = width() - paddingLeft - paddingRight; graphics::TextProperties textProperties( graphics::TextHorizontalAlign::Left, graphics::TextVerticalAlign::Middle); if (hasFocus()) { textCursor_.setVisible(true); } else { textCursor_.setVisible(false); } updateScroll_(textWidth); bool hinting = style(strings::pixel_hinting) == strings::normal; internal::insertRect(a, backgroundColor, 0, 0, width(), height(), borderRadius); internal::insertText(a, textColor, 0, 0, width(), height(), paddingLeft, paddingRight, 0, 0, shapedText_, textProperties, textCursor_, hinting, scrollLeft_); triangles_->load(a.data(), a.length()); } triangles_->draw(); } void LineEdit::onPaintDestroy(graphics::Engine*) { triangles_.reset(); } bool LineEdit::onMouseMove(MouseEvent* event) { if (isMousePressed_) { updateBytePosition_(event->pos()); } return true; } bool LineEdit::onMousePress(MouseEvent* event) { isMousePressed_ = true; setFocus(); updateBytePosition_(event->pos()); return true; } bool LineEdit::onMouseRelease(MouseEvent* /*event*/) { isMousePressed_ = false; return true; } bool LineEdit::onMouseEnter() { pushCursor(Qt::IBeamCursor); return true; } bool LineEdit::onMouseLeave() { popCursor(); return true; } bool LineEdit::onFocusIn() { reload_ = true; repaint(); return true; } bool LineEdit::onFocusOut() { reload_ = true; repaint(); return true; } bool LineEdit::onKeyPress(QKeyEvent* event) { int key = event->key(); if (key == Qt::Key_Delete || key == Qt::Key_Backspace) { Int p1_ = textCursor_.bytePosition(); Int p2_ = -1; graphics::TextBoundaryType boundaryType = (event->modifiers().testFlag(Qt::ControlModifier)) ? graphics::TextBoundaryType::Word : graphics::TextBoundaryType::Grapheme; graphics::TextBoundaryIterator it(boundaryType, text()); it.setPosition(p1_); if (key == Qt::Key_Delete) { p2_ = it.toNextBoundary(); } else { // Backspace p2_ = p1_; p1_ = it.toPreviousBoundary(); } if (p1_ != -1 && p2_ != -1) { size_t p1 = core::int_cast<size_t>(p1_); size_t p2 = core::int_cast<size_t>(p2_); std::string newText; newText.reserve(text().size() - (p2 - p1)); newText.append(text(), 0, p1); newText.append(text(), p2); textCursor_.setBytePosition(p1_); setText(newText); } return true; } else if (key == Qt::Key_Home) { Int p1 = textCursor_.bytePosition(); Int home = 0; if (p1 != home) { textCursor_.setBytePosition(home); reload_ = true; repaint(); } return true; } else if (key == Qt::Key_End) { Int p1 = textCursor_.bytePosition(); Int end = core::int_cast<Int>(text().size()); if (p1 != end) { textCursor_.setBytePosition(end); reload_ = true; repaint(); } return true; } else if (key == Qt::Key_Left || key == Qt::Key_Right) { Int p1 = textCursor_.bytePosition(); Int p2 = -1; graphics::TextBoundaryType boundaryType = (event->modifiers().testFlag(Qt::ControlModifier)) ? graphics::TextBoundaryType::Word : graphics::TextBoundaryType::Grapheme; graphics::TextBoundaryIterator it(boundaryType, text()); it.setPosition(p1); if (key == Qt::Key_Left) { p2 = it.toPreviousBoundary(); } else { // Right p2 = it.toNextBoundary(); } if (p2 != -1 && p1 != p2) { textCursor_.setBytePosition(it.position()); reload_ = true; repaint(); } return true; } else { std::string t = event->text().toStdString(); if (!t.empty()) { size_t p = core::int_cast<size_t>(textCursor_.bytePosition()); std::string newText; newText.reserve(text().size() + t.size()); newText.append(text(), 0, p); newText.append(t); newText.append(text(), p); textCursor_.setBytePosition(p + t.size()); setText(newText); return true; } else { return false; } } } geometry::Vec2f LineEdit::computePreferredSize() const { PreferredSizeType auto_ = PreferredSizeType::Auto; PreferredSize w = preferredWidth(); PreferredSize h = preferredHeight(); geometry::Vec2f res(0, 0); if (w.type() == auto_) { res[0] = 100; // TODO: compute appropriate width based on text length } else { res[0] = w.value(); } if (h.type() == auto_) { res[1] = 26; // TODO: compute appropriate height based on font size? } else { res[1] = h.value(); } return res; } void LineEdit::updateBytePosition_(const geometry::Vec2f& mousePosition) { Int bytePosition = bytePosition_(mousePosition); if (bytePosition != textCursor_.bytePosition()) { textCursor_.setBytePosition(bytePosition); reload_ = true; repaint(); } } Int LineEdit::bytePosition_(const geometry::Vec2f& mousePosition) { float paddingLeft = internal::getLength(this, strings::padding_left); float x = mousePosition[0] - paddingLeft; float y = mousePosition[1]; return shapedText_.bytePosition( geometry::Vec2d(static_cast<double>(x + scrollLeft_), static_cast<double>(y))); } void LineEdit::updateScroll_(float textWidth) { float textEndAdvance = shapedText_.advance()[0]; float currentTextEndPos = textEndAdvance - scrollLeft_; if (currentTextEndPos < textWidth && scrollLeft_ > 0) { if (textEndAdvance < textWidth) { scrollLeft_ = 0; } else { scrollLeft_ = textEndAdvance - textWidth; } } if (textCursor_.isVisible()) { float cursorAdvance = shapedText_.advance(textCursor_.bytePosition())[0]; float currentCursorPos = cursorAdvance - scrollLeft_; if (currentCursorPos < 0) { scrollLeft_ = cursorAdvance; } else if (currentCursorPos > textWidth) { scrollLeft_ = cursorAdvance - textWidth; } } } } // namespace ui } // namespace vgc
28.487805
165
0.600171
PixelRick
4832732563378140d97279676de4ee377bdd1418
65
cpp
C++
src/runtime/io.cpp
slak44/Xylene
acc5b0d6f3ae0098ab4cc1692dbcbe4d17556647
[ "MIT" ]
2
2019-07-18T00:34:15.000Z
2019-08-09T13:05:26.000Z
src/runtime/io.cpp
slak44/Xylene
acc5b0d6f3ae0098ab4cc1692dbcbe4d17556647
[ "MIT" ]
null
null
null
src/runtime/io.cpp
slak44/Xylene
acc5b0d6f3ae0098ab4cc1692dbcbe4d17556647
[ "MIT" ]
null
null
null
#include "runtime/io.hpp" void printC(char c) { putchar(c); }
10.833333
25
0.646154
slak44
4834cf71f04bd80152ab8157b8e743a86618080f
10,483
cpp
C++
AvxBlas/PixelShuffle3D/pixelshuffle3d_spacetochannel.cpp
tk-yoshimura/AvxBlas
37ae77f05e35aa3e97109785276afba3835585ec
[ "MIT" ]
null
null
null
AvxBlas/PixelShuffle3D/pixelshuffle3d_spacetochannel.cpp
tk-yoshimura/AvxBlas
37ae77f05e35aa3e97109785276afba3835585ec
[ "MIT" ]
null
null
null
AvxBlas/PixelShuffle3D/pixelshuffle3d_spacetochannel.cpp
tk-yoshimura/AvxBlas
37ae77f05e35aa3e97109785276afba3835585ec
[ "MIT" ]
null
null
null
#include "../avxblas.h" #include "../constants.h" #include "../utils.h" #include "../Inline/inline_copy_s.hpp" #pragma unmanaged int pixelshuffle3d_spacetochannel_aligned( const uint n, const uint ic, const uint oc, const uint iw, const uint ow, const uint ih, const uint oh, const uint id, const uint od, const uint s, infloats x_ptr, outfloats y_ptr) { const uint cs = ic * s; #ifdef _DEBUG if ((cs & AVX2_FLOAT_REMAIN_MASK) != 0 || ((size_t)x_ptr % AVX2_ALIGNMENT) != 0 || ((size_t)y_ptr % AVX2_ALIGNMENT) != 0) { return FAILURE_BADPARAM; } #endif // _DEBUG for (uint i = 0; i < n; i++) { for (uint oz = 0; oz < od; oz++) { for (uint cz = 0; cz < s; cz++) { for (uint oy = 0; oy < oh; oy++) { for (uint cy = 0; cy < s; cy++) { float* yc_ptr = y_ptr + cs * (cy + s * cz) + oc * ow * (oy + oh * oz); for (uint ox = 0; ox < ow; ox++) { copy_aligned_s(cs, x_ptr, yc_ptr); x_ptr += cs; yc_ptr += oc; } } } } } y_ptr += oc * ow * oh * od; } return SUCCESS; } int pixelshuffle3d_spacetochannel_unaligned( const uint n, const uint ic, const uint oc, const uint iw, const uint ow, const uint ih, const uint oh, const uint id, const uint od, const uint s, infloats x_ptr, outfloats y_ptr) { const uint cs = ic * s; #ifdef _DEBUG if ((cs & AVX2_FLOAT_REMAIN_MASK) == 0) { return FAILURE_BADPARAM; } #endif // _DEBUG const __m256i mask = _mm256_setmask_ps(cs & AVX2_FLOAT_REMAIN_MASK); for (uint i = 0; i < n; i++) { for (uint oz = 0; oz < od; oz++) { for (uint cz = 0; cz < s; cz++) { for (uint oy = 0; oy < oh; oy++) { for (uint cy = 0; cy < s; cy++) { float* yc_ptr = y_ptr + cs * (cy + s * cz) + oc * ow * (oy + oh * oz); for (uint ox = 0; ox < ow; ox++) { copy_unaligned_s(cs, x_ptr, yc_ptr, mask); x_ptr += cs; yc_ptr += oc; } } } } } y_ptr += oc * ow * oh * od; } return SUCCESS; } int pixelshuffle3d_spacetochannel_cs2to3( const uint n, const uint ic, const uint oc, const uint iw, const uint ow, const uint ih, const uint oh, const uint id, const uint od, const uint s, infloats x_ptr, outfloats y_ptr) { const uint cs = ic * s; #ifdef _DEBUG if (cs != 2 && cs != 3) { return FAILURE_BADPARAM; } #endif // _DEBUG __m128 x; const __m128i mask = _mm_setmask_ps(cs); for (uint i = 0; i < n; i++) { for (uint oz = 0; oz < od; oz++) { for (uint cz = 0; cz < s; cz++) { for (uint oy = 0; oy < oh; oy++) { for (uint cy = 0; cy < s; cy++) { float* yc_ptr = y_ptr + cs * (cy + s * cz) + oc * ow * (oy + oh * oz); for (uint ox = 0; ox < ow; ox++) { x = _mm_loadu_ps(x_ptr); _mm_maskstore_ps(yc_ptr, mask, x); x_ptr += cs; yc_ptr += oc; } } } } } y_ptr += oc * ow * oh * od; } return SUCCESS; } int pixelshuffle3d_spacetochannel_cs4( const uint n, const uint ic, const uint oc, const uint iw, const uint ow, const uint ih, const uint oh, const uint id, const uint od, const uint s, infloats x_ptr, outfloats y_ptr) { const uint cs = ic * s; #ifdef _DEBUG if (cs != AVX1_FLOAT_STRIDE || ((size_t)x_ptr % AVX1_ALIGNMENT) != 0 || ((size_t)y_ptr % AVX1_ALIGNMENT) != 0) { return FAILURE_BADPARAM; } #endif // _DEBUG __m128 x; for (uint i = 0; i < n; i++) { for (uint oz = 0; oz < od; oz++) { for (uint cz = 0; cz < s; cz++) { for (uint oy = 0; oy < oh; oy++) { for (uint cy = 0; cy < s; cy++) { float* yc_ptr = y_ptr + cs * (cy + s * cz) + oc * ow * (oy + oh * oz); for (uint ox = 0; ox < ow; ox++) { x = _mm_load_ps(x_ptr); _mm_stream_ps(yc_ptr, x); x_ptr += cs; yc_ptr += oc; } } } } } y_ptr += oc * ow * oh * od; } return SUCCESS; } int pixelshuffle3d_spacetochannel_cs5to7( const uint n, const uint ic, const uint oc, const uint iw, const uint ow, const uint ih, const uint oh, const uint id, const uint od, const uint s, infloats x_ptr, outfloats y_ptr) { const uint cs = ic * s; #ifdef _DEBUG if (cs <= AVX1_FLOAT_STRIDE || cs >= AVX2_FLOAT_STRIDE) { return FAILURE_BADPARAM; } #endif // _DEBUG const __m256i mask = _mm256_setmask_ps(cs & AVX2_FLOAT_REMAIN_MASK); __m256 x; for (uint i = 0; i < n; i++) { for (uint oz = 0; oz < od; oz++) { for (uint cz = 0; cz < s; cz++) { for (uint oy = 0; oy < oh; oy++) { for (uint cy = 0; cy < s; cy++) { float* yc_ptr = y_ptr + cs * (cy + s * cz) + oc * ow * (oy + oh * oz); for (uint ox = 0; ox < ow; ox++) { _mm256_loadu_x1_ps(x_ptr, x); _mm256_maskstore_x1_ps(yc_ptr, x, mask); x_ptr += cs; yc_ptr += oc; } } } } } y_ptr += oc * ow * oh * od; } return SUCCESS; } int pixelshuffle3d_spacetochannel_cs8( const uint n, const uint ic, const uint oc, const uint iw, const uint ow, const uint ih, const uint oh, const uint id, const uint od, const uint s, infloats x_ptr, outfloats y_ptr) { const uint cs = ic * s; #ifdef _DEBUG if (cs != AVX2_FLOAT_STRIDE || ((size_t)x_ptr % AVX2_ALIGNMENT) != 0 || ((size_t)y_ptr % AVX2_ALIGNMENT) != 0) { return FAILURE_BADPARAM; } #endif // _DEBUG __m256 x; for (uint i = 0; i < n; i++) { for (uint oz = 0; oz < od; oz++) { for (uint cz = 0; cz < s; cz++) { for (uint oy = 0; oy < oh; oy++) { for (uint cy = 0; cy < s; cy++) { float* yc_ptr = y_ptr + cs * (cy + s * cz) + oc * ow * (oy + oh * oz); for (uint ox = 0; ox < ow; ox++) { _mm256_load_x1_ps(x_ptr, x); _mm256_stream_x1_ps(yc_ptr, x); x_ptr += cs; yc_ptr += oc; } } } } } y_ptr += oc * ow * oh * od; } return SUCCESS; } int pixelshuffle3d_spacetochannel_csleq8( const uint n, const uint ic, const uint oc, const uint iw, const uint ow, const uint ih, const uint oh, const uint id, const uint od, const uint s, infloats x_ptr, outfloats y_ptr) { const uint cs = ic * s; if (cs <= 1) { return FAILURE_BADPARAM; } if (cs < AVX1_FLOAT_STRIDE) { return pixelshuffle3d_spacetochannel_cs2to3(n, ic, oc, iw, ow, ih, oh, id, od, s, x_ptr, y_ptr); } if (cs == AVX1_FLOAT_STRIDE) { return pixelshuffle3d_spacetochannel_cs4(n, ic, oc, iw, ow, ih, oh, id, od, s, x_ptr, y_ptr); } if (cs < AVX2_FLOAT_STRIDE) { return pixelshuffle3d_spacetochannel_cs5to7(n, ic, oc, iw, ow, ih, oh, id, od, s, x_ptr, y_ptr); } if (cs == AVX2_FLOAT_STRIDE) { return pixelshuffle3d_spacetochannel_cs8(n, ic, oc, iw, ow, ih, oh, id, od, s, x_ptr, y_ptr); } return FAILURE_BADPARAM; } #pragma managed void AvxBlas::PixelShuffle3D::SpaceToChannel( UInt32 n, UInt32 ic, UInt32 iw, UInt32 ih, UInt32 id, UInt32 s, Array<float>^ xs, Array<float>^ yc) { if (n > MAX_BATCHES) { throw gcnew System::ArgumentOutOfRangeException(ErrorMessage::InvalidBatches); } if (s <= 0 || s > MAX_PIXELSHUFFLE_STRIDE) { throw gcnew System::ArgumentOutOfRangeException(ErrorMessage::InvalidStride); } if (ic > MAX_CHANNELS || ic * s * s * s > MAX_CHANNELS) { throw gcnew System::ArgumentOutOfRangeException(ErrorMessage::InvalidChannels); } if (n <= 0 || ic <= 0 || iw <= 0 || ih <= 0 || id <= 0) { return; } if ((iw % s) != 0 || iw > MAX_MAP_SIZE || (ih % s) != 0 || ih > MAX_MAP_SIZE || (id % s) != 0 || id > MAX_MAP_SIZE) { throw gcnew System::ArgumentOutOfRangeException(ErrorMessage::InvalidDataSize); } Util::CheckProdOverflow(ic, s, s, s); UInt32 ow = iw / s, oh = ih / s, od = id / s, oc = ic * s * s * s; Util::CheckProdOverflow(n, ic, iw, ih, id); Util::CheckProdOverflow(n, oc, ow, oh, od); Util::CheckLength(n * ic * iw * ih * id, xs); Util::CheckLength(n * oc * ow * oh * od, yc); Util::CheckDuplicateArray(xs, yc); if (s == 1) { Elementwise::Copy(n * ic * iw * ih * id, xs, yc); return; } const float* x_ptr = (const float*)(xs->Ptr.ToPointer()); float* y_ptr = (float*)(yc->Ptr.ToPointer()); int ret = UNEXECUTED; const uint cs = ic * s; if (cs <= AVX2_FLOAT_STRIDE) { #ifdef _DEBUG Console::WriteLine("type leq8"); #endif // _DEBUG ret = pixelshuffle3d_spacetochannel_csleq8(n, ic, oc, iw, ow, ih, oh, id, od, s, x_ptr, y_ptr); } else if ((cs & AVX2_FLOAT_REMAIN_MASK) == 0) { #ifdef _DEBUG Console::WriteLine("type aligned"); #endif // _DEBUG ret = pixelshuffle3d_spacetochannel_aligned(n, ic, oc, iw, ow, ih, oh, id, od, s, x_ptr, y_ptr); } else { #ifdef _DEBUG Console::WriteLine("type unaligned"); #endif // _DEBUG ret = pixelshuffle3d_spacetochannel_unaligned(n, ic, oc, iw, ow, ih, oh, id, od, s, x_ptr, y_ptr); } Util::AssertReturnCode(ret); }
28.958564
127
0.485643
tk-yoshimura
4834e76c2b2db11047bb1b7ff52fd89c538a8fdb
491
hpp
C++
src/process.hpp
Leomotors/Terminal-Video-Player
0f01efb600479d8d3bb562473a871eaa85a71519
[ "MIT" ]
1
2021-12-12T03:55:09.000Z
2021-12-12T03:55:09.000Z
src/process.hpp
Leomotors/Terminal-Video-Player
0f01efb600479d8d3bb562473a871eaa85a71519
[ "MIT" ]
null
null
null
src/process.hpp
Leomotors/Terminal-Video-Player
0f01efb600479d8d3bb562473a871eaa85a71519
[ "MIT" ]
null
null
null
#pragma once #include <opencv2/opencv.hpp> #include "colors.hpp" namespace tplay::process { extern char *ascii_array; extern int ascii_arrlen; void setup(int options1, int options2); void setupColor(int options2); void processFrame(cv::Mat Frame, int width, int height, std::string header); std::string getClosestColorLinear(colors::Color target); void processFrameColor(cv::Mat Frame, int width, int height, std::string header); } // namespace tplay::process
23.380952
76
0.727088
Leomotors
4835242860ac2aaf3c74f023f0f6d81329fd7e9e
933
hpp
C++
include/jln/mp/smp/algorithm/is_sorted.hpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
9
2020-07-04T16:46:13.000Z
2022-01-09T21:59:31.000Z
include/jln/mp/smp/algorithm/is_sorted.hpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
null
null
null
include/jln/mp/smp/algorithm/is_sorted.hpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
1
2021-05-23T13:37:40.000Z
2021-05-23T13:37:40.000Z
#pragma once #include <jln/mp/smp/functional/identity.hpp> #include <jln/mp/smp/utility/always.hpp> #include <jln/mp/smp/number/operators.hpp> #include <jln/mp/functional/tee.hpp> #include <jln/mp/functional/if.hpp> #include <jln/mp/list/size.hpp> #include <jln/mp/algorithm/is_sorted.hpp> namespace jln::mp::smp { template<class Cmp = less<>, class C = identity> using is_sorted = contract< mp::if_< mp::size<mp::less_than_c<2>>, always<mp::number<1>, C>, mp::tee< mp::pop_front<>, mp::rotate_c<-1, mp::pop_front<>>, mp::zip_with< try_assume_binary<Cmp>, mp::try_<mp::or_<mp::not_<try_assume_unary<C>>>> > > > >; } /// \cond namespace jln::mp::detail { template<template<class> class sfinae, class Cmp, class C> struct _sfinae<sfinae, is_sorted<Cmp, C>> { using type = smp::is_sorted<sfinae<Cmp>, sfinae<C>>; }; } /// \endcond
23.325
60
0.624866
jonathanpoelen
483acf982086365972c20530d88987b51d3e746a
20,901
hpp
C++
src/c4/dump.hpp
kasper93/c4core
170509d06aceefda8980c98a2785e838bb19e578
[ "BSL-1.0", "MIT" ]
null
null
null
src/c4/dump.hpp
kasper93/c4core
170509d06aceefda8980c98a2785e838bb19e578
[ "BSL-1.0", "MIT" ]
null
null
null
src/c4/dump.hpp
kasper93/c4core
170509d06aceefda8980c98a2785e838bb19e578
[ "BSL-1.0", "MIT" ]
null
null
null
#ifndef C4_DUMP_HPP_ #define C4_DUMP_HPP_ #include <c4/substr.hpp> namespace c4 { //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** type of the function to dump characters */ using DumperPfn = void (*)(csubstr buf); //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- template<DumperPfn dumpfn, class Arg> inline size_t dump(substr buf, Arg const& a) { size_t sz = to_chars(buf, a); // need to serialize to the buffer if(C4_LIKELY(sz <= buf.len)) dumpfn(buf.first(sz)); return sz; } template<class DumperFn, class Arg> inline size_t dump(DumperFn &&dumpfn, substr buf, Arg const& a) { size_t sz = to_chars(buf, a); // need to serialize to the buffer if(C4_LIKELY(sz <= buf.len)) dumpfn(buf.first(sz)); return sz; } template<DumperPfn dumpfn> inline size_t dump(substr buf, csubstr a) { if(buf.len) dumpfn(a); // dump directly, no need to serialize to the buffer return 0; // no space was used in the buffer } template<class DumperFn> inline size_t dump(DumperFn &&dumpfn, substr buf, csubstr a) { if(buf.len) dumpfn(a); // dump directly, no need to serialize to the buffer return 0; // no space was used in the buffer } template<DumperPfn dumpfn, size_t N> inline size_t dump(substr buf, const char (&a)[N]) { if(buf.len) dumpfn(csubstr(a)); // dump directly, no need to serialize to the buffer return 0; // no space was used in the buffer } template<class DumperFn, size_t N> inline size_t dump(DumperFn &&dumpfn, substr buf, const char (&a)[N]) { if(buf.len) dumpfn(csubstr(a)); // dump directly, no need to serialize to the buffer return 0; // no space was used in the buffer } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** */ struct DumpResults { enum : size_t { noarg = (size_t)-1 }; size_t bufsize = 0; size_t lastok = noarg; bool success_until(size_t expected) const { return lastok == noarg ? false : lastok >= expected; } bool write_arg(size_t arg) const { return lastok == noarg || arg > lastok; } size_t argfail() const { return lastok + 1; } }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /// @cond dev // terminates the variadic recursion template<class DumperFn> size_t cat_dump(DumperFn &&, substr) { return 0; } // terminates the variadic recursion template<DumperPfn dumpfn> size_t cat_dump(substr) { return 0; } /// @endcond /** take the function pointer as a function argument */ template<class DumperFn, class Arg, class... Args> size_t cat_dump(DumperFn &&dumpfn, substr buf, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { size_t size_for_a = dump(dumpfn, buf, a); if(C4_UNLIKELY(size_for_a > buf.len)) buf = buf.first(0); // ensure no more calls size_t size_for_more = cat_dump(dumpfn, buf, more...); return size_for_more > size_for_a ? size_for_more : size_for_a; } /** take the function pointer as a template argument */ template<DumperPfn dumpfn,class Arg, class... Args> size_t cat_dump(substr buf, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { size_t size_for_a = dump<dumpfn>(buf, a); if(C4_LIKELY(size_for_a > buf.len)) buf = buf.first(0); // ensure no more calls size_t size_for_more = cat_dump<dumpfn>(buf, more...); return size_for_more > size_for_a ? size_for_more : size_for_a; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /// @cond dev namespace detail { // terminates the variadic recursion template<DumperPfn dumpfn, class Arg> DumpResults cat_dump_resume(size_t currarg, DumpResults results, substr buf, Arg const& C4_RESTRICT a) { if(C4_LIKELY(results.write_arg(currarg))) { size_t sz = dump<dumpfn>(buf, a); // yield to the specialized function if(currarg == results.lastok + 1 && sz <= buf.len) results.lastok = currarg; results.bufsize = sz > results.bufsize ? sz : results.bufsize; } return results; } // terminates the variadic recursion template<class DumperFn, class Arg> DumpResults cat_dump_resume(size_t currarg, DumperFn &&dumpfn, DumpResults results, substr buf, Arg const& C4_RESTRICT a) { if(C4_LIKELY(results.write_arg(currarg))) { size_t sz = dump(dumpfn, buf, a); // yield to the specialized function if(currarg == results.lastok + 1 && sz <= buf.len) results.lastok = currarg; results.bufsize = sz > results.bufsize ? sz : results.bufsize; } return results; } template<DumperPfn dumpfn, class Arg, class... Args> DumpResults cat_dump_resume(size_t currarg, DumpResults results, substr buf, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { results = detail::cat_dump_resume<dumpfn>(currarg, results, buf, a); return detail::cat_dump_resume<dumpfn>(currarg + 1u, results, buf, more...); } template<class DumperFn, class Arg, class... Args> DumpResults cat_dump_resume(size_t currarg, DumperFn &&dumpfn, DumpResults results, substr buf, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { results = detail::cat_dump_resume(currarg, dumpfn, results, buf, a); return detail::cat_dump_resume(currarg + 1u, dumpfn, results, buf, more...); } } // namespace detail /// @endcond template<DumperPfn dumpfn, class Arg, class... Args> C4_ALWAYS_INLINE DumpResults cat_dump_resume(DumpResults results, substr buf, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { if(results.bufsize > buf.len) return results; return detail::cat_dump_resume<dumpfn>(0u, results, buf, a, more...); } template<class DumperFn, class Arg, class... Args> C4_ALWAYS_INLINE DumpResults cat_dump_resume(DumperFn &&dumpfn, DumpResults results, substr buf, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { if(results.bufsize > buf.len) return results; return detail::cat_dump_resume(0u, dumpfn, results, buf, a, more...); } template<DumperPfn dumpfn, class Arg, class... Args> C4_ALWAYS_INLINE DumpResults cat_dump_resume(substr buf, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { return detail::cat_dump_resume<dumpfn>(0u, DumpResults{}, buf, a, more...); } template<class DumperFn, class Arg, class... Args> C4_ALWAYS_INLINE DumpResults cat_dump_resume(DumperFn &&dumpfn, substr buf, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { return detail::cat_dump_resume(0u, dumpfn, DumpResults{}, buf, a, more...); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /// @cond dev // terminate the recursion template<class DumperFn, class Sep> size_t catsep_dump(DumperFn &&, substr, Sep const& C4_RESTRICT) { return 0; } // terminate the recursion template<DumperPfn dumpfn, class Sep> size_t catsep_dump(substr, Sep const& C4_RESTRICT) { return 0; } /// @endcond /** take the function pointer as a function argument */ template<class DumperFn, class Sep, class Arg, class... Args> size_t catsep_dump(DumperFn &&dumpfn, substr buf, Sep const& C4_RESTRICT sep, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { size_t sz = dump(dumpfn, buf, a); if(C4_UNLIKELY(sz > buf.len)) buf = buf.first(0); // ensure no more calls if C4_IF_CONSTEXPR (sizeof...(more) > 0) { size_t szsep = dump(dumpfn, buf, sep); if(C4_UNLIKELY(szsep > buf.len)) buf = buf.first(0); // ensure no more calls sz = sz > szsep ? sz : szsep; } size_t size_for_more = catsep_dump(dumpfn, buf, sep, more...); return size_for_more > sz ? size_for_more : sz; } /** take the function pointer as a template argument */ template<DumperPfn dumpfn, class Sep, class Arg, class... Args> size_t catsep_dump(substr buf, Sep const& C4_RESTRICT sep, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { size_t sz = dump<dumpfn>(buf, a); if(C4_UNLIKELY(sz > buf.len)) buf = buf.first(0); // ensure no more calls if C4_IF_CONSTEXPR (sizeof...(more) > 0) { size_t szsep = dump<dumpfn>(buf, sep); if(C4_UNLIKELY(szsep > buf.len)) buf = buf.first(0); // ensure no more calls sz = sz > szsep ? sz : szsep; } size_t size_for_more = catsep_dump<dumpfn>(buf, sep, more...); return size_for_more > sz ? size_for_more : sz; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /// @cond dev namespace detail { template<DumperPfn dumpfn, class Arg> void catsep_dump_resume_(size_t currarg, DumpResults *C4_RESTRICT results, substr *C4_RESTRICT buf, Arg const& C4_RESTRICT a) { if(C4_LIKELY(results->write_arg(currarg))) { size_t sz = dump<dumpfn>(*buf, a); results->bufsize = sz > results->bufsize ? sz : results->bufsize; if(C4_LIKELY(sz <= buf->len)) results->lastok = currarg; else buf->len = 0; } } template<class DumperFn, class Arg> void catsep_dump_resume_(size_t currarg, DumperFn &&dumpfn, DumpResults *C4_RESTRICT results, substr *C4_RESTRICT buf, Arg const& C4_RESTRICT a) { if(C4_LIKELY(results->write_arg(currarg))) { size_t sz = dump(dumpfn, *buf, a); results->bufsize = sz > results->bufsize ? sz : results->bufsize; if(C4_LIKELY(sz <= buf->len)) results->lastok = currarg; else buf->len = 0; } } template<DumperPfn dumpfn, class Sep, class Arg> C4_ALWAYS_INLINE void catsep_dump_resume(size_t currarg, DumpResults *C4_RESTRICT results, substr *C4_RESTRICT buf, Sep const& C4_RESTRICT, Arg const& C4_RESTRICT a) { detail::catsep_dump_resume_<dumpfn>(currarg, results, buf, a); } template<class DumperFn, class Sep, class Arg> C4_ALWAYS_INLINE void catsep_dump_resume(size_t currarg, DumperFn &&dumpfn, DumpResults *C4_RESTRICT results, substr *C4_RESTRICT buf, Sep const& C4_RESTRICT, Arg const& C4_RESTRICT a) { detail::catsep_dump_resume_(currarg, dumpfn, results, buf, a); } template<DumperPfn dumpfn, class Sep, class Arg, class... Args> C4_ALWAYS_INLINE void catsep_dump_resume(size_t currarg, DumpResults *C4_RESTRICT results, substr *C4_RESTRICT buf, Sep const& C4_RESTRICT sep, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { detail::catsep_dump_resume_<dumpfn>(currarg , results, buf, a); detail::catsep_dump_resume_<dumpfn>(currarg + 1u, results, buf, sep); detail::catsep_dump_resume <dumpfn>(currarg + 2u, results, buf, sep, more...); } template<class DumperFn, class Sep, class Arg, class... Args> C4_ALWAYS_INLINE void catsep_dump_resume(size_t currarg, DumperFn &&dumpfn, DumpResults *C4_RESTRICT results, substr *C4_RESTRICT buf, Sep const& C4_RESTRICT sep, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { detail::catsep_dump_resume_(currarg , dumpfn, results, buf, a); detail::catsep_dump_resume_(currarg + 1u, dumpfn, results, buf, sep); detail::catsep_dump_resume (currarg + 2u, dumpfn, results, buf, sep, more...); } } // namespace detail /// @endcond template<DumperPfn dumpfn, class Sep, class... Args> C4_ALWAYS_INLINE DumpResults catsep_dump_resume(DumpResults results, substr buf, Sep const& C4_RESTRICT sep, Args const& C4_RESTRICT ...more) { detail::catsep_dump_resume<dumpfn>(0u, &results, &buf, sep, more...); return results; } template<class DumperFn, class Sep, class... Args> C4_ALWAYS_INLINE DumpResults catsep_dump_resume(DumperFn &&dumpfn, DumpResults results, substr buf, Sep const& C4_RESTRICT sep, Args const& C4_RESTRICT ...more) { detail::catsep_dump_resume(0u, dumpfn, &results, &buf, sep, more...); return results; } template<DumperPfn dumpfn, class Sep, class... Args> C4_ALWAYS_INLINE DumpResults catsep_dump_resume(substr buf, Sep const& C4_RESTRICT sep, Args const& C4_RESTRICT ...more) { DumpResults results; detail::catsep_dump_resume<dumpfn>(0u, &results, &buf, sep, more...); return results; } template<class DumperFn, class Sep, class... Args> C4_ALWAYS_INLINE DumpResults catsep_dump_resume(DumperFn &&dumpfn, substr buf, Sep const& C4_RESTRICT sep, Args const& C4_RESTRICT ...more) { DumpResults results; detail::catsep_dump_resume(0u, dumpfn, &results, &buf, sep, more...); return results; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** take the function pointer as a function argument */ template<class DumperFn> C4_ALWAYS_INLINE size_t format_dump(DumperFn &&dumpfn, substr buf, csubstr fmt) { // we can dump without using buf // but we'll only dump if the buffer is ok if(C4_LIKELY(buf.len > 0 && fmt.len)) dumpfn(fmt); return 0u; } /** take the function pointer as a function argument */ template<DumperPfn dumpfn> C4_ALWAYS_INLINE size_t format_dump(substr buf, csubstr fmt) { // we can dump without using buf // but we'll only dump if the buffer is ok if(C4_LIKELY(buf.len > 0 && fmt.len > 0)) dumpfn(fmt); return 0u; } /** take the function pointer as a function argument */ template<class DumperFn, class Arg, class... Args> size_t format_dump(DumperFn &&dumpfn, substr buf, csubstr fmt, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { // we can dump without using buf // but we'll only dump if the buffer is ok size_t pos = fmt.find("{}"); // @todo use _find_fmt() if(C4_UNLIKELY(pos == csubstr::npos)) { if(C4_LIKELY(buf.len > 0 && fmt.len > 0)) dumpfn(fmt); return 0u; } if(C4_LIKELY(buf.len > 0 && pos > 0)) dumpfn(fmt.first(pos)); // we can dump without using buf fmt = fmt.sub(pos + 2); // skip {} do this before assigning to pos again pos = dump(dumpfn, buf, a); if(C4_UNLIKELY(pos > buf.len)) buf.len = 0; // ensure no more calls to dump size_t size_for_more = format_dump(dumpfn, buf, fmt, more...); return size_for_more > pos ? size_for_more : pos; } /** take the function pointer as a template argument */ template<DumperPfn dumpfn, class Arg, class... Args> size_t format_dump(substr buf, csubstr fmt, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { // we can dump without using buf // but we'll only dump if the buffer is ok size_t pos = fmt.find("{}"); // @todo use _find_fmt() if(C4_UNLIKELY(pos == csubstr::npos)) { if(C4_LIKELY(buf.len > 0 && fmt.len > 0)) dumpfn(fmt); return 0u; } if(C4_LIKELY(buf.len > 0 && pos > 0)) dumpfn(fmt.first(pos)); // we can dump without using buf fmt = fmt.sub(pos + 2); // skip {} do this before assigning to pos again pos = dump<dumpfn>(buf, a); if(C4_UNLIKELY(pos > buf.len)) buf.len = 0; // ensure no more calls to dump size_t size_for_more = format_dump<dumpfn>(buf, fmt, more...); return size_for_more > pos ? size_for_more : pos; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /// @cond dev namespace detail { template<DumperPfn dumpfn> DumpResults format_dump_resume(size_t currarg, DumpResults results, substr buf, csubstr fmt) { // we can dump without using buf // but we'll only dump if the buffer is ok if(C4_LIKELY(buf.len > 0)) { dumpfn(fmt); results.lastok = currarg; } return results; } template<class DumperFn> DumpResults format_dump_resume(size_t currarg, DumperFn &&dumpfn, DumpResults results, substr buf, csubstr fmt) { // we can dump without using buf // but we'll only dump if the buffer is ok if(C4_LIKELY(buf.len > 0)) { dumpfn(fmt); results.lastok = currarg; } return results; } template<DumperPfn dumpfn, class Arg, class... Args> DumpResults format_dump_resume(size_t currarg, DumpResults results, substr buf, csubstr fmt, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { // we need to process the format even if we're not // going to print the first arguments because we're resuming size_t pos = fmt.find("{}"); // @todo use _find_fmt() // we can dump without using buf // but we'll only dump if the buffer is ok if(C4_LIKELY(results.write_arg(currarg))) { if(C4_UNLIKELY(pos == csubstr::npos)) { if(C4_LIKELY(buf.len > 0)) { results.lastok = currarg; dumpfn(fmt); } return results; } if(C4_LIKELY(buf.len > 0)) { results.lastok = currarg; dumpfn(fmt.first(pos)); } } fmt = fmt.sub(pos + 2); if(C4_LIKELY(results.write_arg(currarg + 1))) { pos = dump<dumpfn>(buf, a); results.bufsize = pos > results.bufsize ? pos : results.bufsize; if(C4_LIKELY(pos <= buf.len)) results.lastok = currarg + 1; else buf.len = 0; } return detail::format_dump_resume<dumpfn>(currarg + 2u, results, buf, fmt, more...); } /// @endcond template<class DumperFn, class Arg, class... Args> DumpResults format_dump_resume(size_t currarg, DumperFn &&dumpfn, DumpResults results, substr buf, csubstr fmt, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { // we need to process the format even if we're not // going to print the first arguments because we're resuming size_t pos = fmt.find("{}"); // @todo use _find_fmt() // we can dump without using buf // but we'll only dump if the buffer is ok if(C4_LIKELY(results.write_arg(currarg))) { if(C4_UNLIKELY(pos == csubstr::npos)) { if(C4_LIKELY(buf.len > 0)) { results.lastok = currarg; dumpfn(fmt); } return results; } if(C4_LIKELY(buf.len > 0)) { results.lastok = currarg; dumpfn(fmt.first(pos)); } } fmt = fmt.sub(pos + 2); if(C4_LIKELY(results.write_arg(currarg + 1))) { pos = dump(dumpfn, buf, a); results.bufsize = pos > results.bufsize ? pos : results.bufsize; if(C4_LIKELY(pos <= buf.len)) results.lastok = currarg + 1; else buf.len = 0; } return detail::format_dump_resume(currarg + 2u, dumpfn, results, buf, fmt, more...); } } // namespace detail template<DumperPfn dumpfn, class... Args> C4_ALWAYS_INLINE DumpResults format_dump_resume(DumpResults results, substr buf, csubstr fmt, Args const& C4_RESTRICT ...more) { return detail::format_dump_resume<dumpfn>(0u, results, buf, fmt, more...); } template<class DumperFn, class... Args> C4_ALWAYS_INLINE DumpResults format_dump_resume(DumperFn &&dumpfn, DumpResults results, substr buf, csubstr fmt, Args const& C4_RESTRICT ...more) { return detail::format_dump_resume(0u, dumpfn, results, buf, fmt, more...); } template<DumperPfn dumpfn, class... Args> C4_ALWAYS_INLINE DumpResults format_dump_resume(substr buf, csubstr fmt, Args const& C4_RESTRICT ...more) { return detail::format_dump_resume<dumpfn>(0u, DumpResults{}, buf, fmt, more...); } template<class DumperFn, class... Args> C4_ALWAYS_INLINE DumpResults format_dump_resume(DumperFn &&dumpfn, substr buf, csubstr fmt, Args const& C4_RESTRICT ...more) { return detail::format_dump_resume(0u, dumpfn, DumpResults{}, buf, fmt, more...); } } // namespace c4 #endif /* C4_DUMP_HPP_ */
36.036207
221
0.601933
kasper93
483ae437a02f74fadf782d2e3e83a8cec9d68bf9
326
cpp
C++
dialog/dialogsectorsetup.cpp
ignmiz/ATC_Console
549dd67a007cf54b976e33fed1581f30beb08b06
[ "Intel", "MIT" ]
5
2018-01-08T22:20:07.000Z
2021-06-19T17:42:29.000Z
dialog/dialogsectorsetup.cpp
ignmiz/ATC_Console
549dd67a007cf54b976e33fed1581f30beb08b06
[ "Intel", "MIT" ]
null
null
null
dialog/dialogsectorsetup.cpp
ignmiz/ATC_Console
549dd67a007cf54b976e33fed1581f30beb08b06
[ "Intel", "MIT" ]
2
2017-08-07T23:07:42.000Z
2021-05-09T13:02:39.000Z
#include "dialogsectorsetup.h" #include "ui_dialogsectorsetup.h" DialogSectorSetup::DialogSectorSetup(QWidget *parent) : ATCDialog(parent, "Sector Setup", 600, 800), uiInner(new Ui::DialogSectorSetup) { uiInner->setupUi(this); windowSetup(); } DialogSectorSetup::~DialogSectorSetup() { delete uiInner; }
20.375
55
0.726994
ignmiz
483bfb24316d505c6c6086f0ec1f70a61c2e2baf
1,773
cpp
C++
mmcv/ops/csrc/parrots/furthest_point_sample_parrots.cpp
raoshenglong/mmcv
e22740b1d6953d75a0acecce4455d23800b1f018
[ "Apache-2.0" ]
1
2021-08-22T14:47:13.000Z
2021-08-22T14:47:13.000Z
mmcv/ops/csrc/parrots/furthest_point_sample_parrots.cpp
raoshenglong/mmcv
e22740b1d6953d75a0acecce4455d23800b1f018
[ "Apache-2.0" ]
2
2021-04-26T08:32:50.000Z
2021-05-10T06:42:57.000Z
mmcv/ops/csrc/parrots/furthest_point_sample_parrots.cpp
raoshenglong/mmcv
e22740b1d6953d75a0acecce4455d23800b1f018
[ "Apache-2.0" ]
1
2020-12-10T08:35:35.000Z
2020-12-10T08:35:35.000Z
// Copyright (c) OpenMMLab. All rights reserved #include <parrots/compute/aten.hpp> #include <parrots/extension.hpp> #include <parrots/foundation/ssattrs.hpp> #include "furthest_point_sample_pytorch.h" using namespace parrots; #ifdef MMCV_WITH_CUDA void furthest_point_sample_forward_cuda_parrots( CudaContext& ctx, const SSElement& attr, const OperatorBase::in_list_t& ins, OperatorBase::out_list_t& outs) { int b, n, m; SSAttrs(attr).get<int>("b", b).get<int>("n", n).get<int>("m", m).done(); auto points_tensor = buildATensor(ctx, ins[0]); auto temp_tensor = buildATensor(ctx, ins[1]); auto idx_tensor = buildATensor(ctx, outs[0]); furthest_point_sampling_forward(points_tensor, temp_tensor, idx_tensor, b, n, m); } void furthest_point_sampling_with_dist_forward_cuda_parrots( CudaContext& ctx, const SSElement& attr, const OperatorBase::in_list_t& ins, OperatorBase::out_list_t& outs) { int b, n, m; SSAttrs(attr).get<int>("b", b).get<int>("n", n).get<int>("m", m).done(); auto points_tensor = buildATensor(ctx, ins[0]); auto temp_tensor = buildATensor(ctx, ins[1]); auto idx_tensor = buildATensor(ctx, outs[0]); furthest_point_sampling_with_dist_forward(points_tensor, temp_tensor, idx_tensor, b, n, m); } PARROTS_EXTENSION_REGISTER(furthest_point_sampling_forward) .attr("b") .attr("n") .attr("m") .input(2) .output(1) .apply(furthest_point_sample_forward_cuda_parrots) .done(); PARROTS_EXTENSION_REGISTER(furthest_point_sampling_with_dist_forward) .attr("b") .attr("n") .attr("m") .input(2) .output(1) .apply(furthest_point_sampling_with_dist_forward_cuda_parrots) .done(); #endif
30.568966
80
0.689227
raoshenglong
483d7027df3d118eb493eae1022c11bd5809680b
1,888
cpp
C++
leetcode-algorithms/048. Rotate Image/48.rotate-image.cpp
cnyy7/LeetCode_EY
44e92f102b61f5e931e66081ed6636d7ecbdefd4
[ "MIT" ]
null
null
null
leetcode-algorithms/048. Rotate Image/48.rotate-image.cpp
cnyy7/LeetCode_EY
44e92f102b61f5e931e66081ed6636d7ecbdefd4
[ "MIT" ]
null
null
null
leetcode-algorithms/048. Rotate Image/48.rotate-image.cpp
cnyy7/LeetCode_EY
44e92f102b61f5e931e66081ed6636d7ecbdefd4
[ "MIT" ]
null
null
null
/* * @lc app=leetcode id=48 lang=cpp * * [48] Rotate Image * * https://leetcode.com/problems/rotate-image/description/ * * algorithms * Medium (51.26%) * Likes: 2258 * Dislikes: 187 * Total Accepted: 330K * Total Submissions: 626.2K * Testcase Example: '[[1,2,3],[4,5,6],[7,8,9]]' * * You are given an n x n 2D matrix representing an image. * * Rotate the image by 90 degrees (clockwise). * * Note: * * You have to rotate the image in-place, which means you have to modify the * input 2D matrix directly. DO NOT allocate another 2D matrix and do the * rotation. * * Example 1: * * * Given input matrix = * [ * ⁠ [1,2,3], * ⁠ [4,5,6], * ⁠ [7,8,9] * ], * * rotate the input matrix in-place such that it becomes: * [ * ⁠ [7,4,1], * ⁠ [8,5,2], * ⁠ [9,6,3] * ] * * * Example 2: * * * Given input matrix = * [ * ⁠ [ 5, 1, 9,11], * ⁠ [ 2, 4, 8,10], * ⁠ [13, 3, 6, 7], * ⁠ [15,14,12,16] * ], * * rotate the input matrix in-place such that it becomes: * [ * ⁠ [15,13, 2, 5], * ⁠ [14, 3, 4, 1], * ⁠ [12, 6, 8, 9], * ⁠ [16, 7,10,11] * ] * * */ // @lc code=start class Solution { public: void rotate(vector<vector<int>> &matrix) { if (matrix.size() == 0) { return; } int n = matrix.size(), mid = (matrix.size() - 1) / 2, temp = 0; for (int i = 0; i <= mid; i++) { for (int j = 0; j < n; j++) { temp = matrix[i][j]; matrix[i][j] = matrix[n - i - 1][j]; matrix[n - i - 1][j] = temp; } } for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } } }; // @lc code=end
19.265306
76
0.445975
cnyy7
c61aaf2dedae025a1e16c33697b9a53407dd32c2
5,447
cpp
C++
main/src/deps/gpusurf/gpusurf/src/detector.cpp
utiasASRL/vtr3
b4edca56a19484666d3cdb25a032c424bdc6f19d
[ "Apache-2.0" ]
32
2021-09-15T03:42:42.000Z
2022-03-26T10:40:01.000Z
main/src/deps/gpusurf/gpusurf/src/detector.cpp
shimp-t/vtr3
bdcad784ffe26fabfa737d0e195bcb3bacb930c3
[ "Apache-2.0" ]
7
2021-09-18T19:18:15.000Z
2022-02-02T11:15:40.000Z
main/src/deps/gpusurf/gpusurf/src/detector.cpp
shimp-t/vtr3
bdcad784ffe26fabfa737d0e195bcb3bacb930c3
[ "Apache-2.0" ]
7
2021-09-18T01:31:28.000Z
2022-03-14T05:09:37.000Z
/* Copyright (c) 2010, Paul Furgale and Chi Hay Tong All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "detector.h" #include "timing.h" #include "fasthessian.h" #include "non_max_suppression.h" #include "keypoint_interpolation.h" #include "GpuSurfFeatures.hpp" #include "GpuSurfOctave.hpp" #include <fstream> #include "adaptive_threshold.h" namespace asrl { void run_surf_detector(float * d_hessianBuffer, GpuSurfOctave & octave, int octaveIdx, GpuSurfFeatures & features, float basic_threshold, int fh_x_threads, int fh_y_threads, int nonmax_x_threads, int nonmax_y_threads, CudaSynchronizedMemory<unsigned int> & histograms, CudaSynchronizedMemory<float> & thresholds, int regions_horizontal, int regions_vertical) { ///////////////// // FASTHESSIAN // ///////////////// // GlobalTimer.start("compute interest operator"); dim3 threads; threads.x = fh_x_threads; threads.y = fh_y_threads; threads.z = octave.intervals(); dim3 grid; grid.x = ( (octave.width() + threads.x - 1) / threads.x); grid.y = ( (octave.height() + threads.y - 1) / threads.y); grid.z = 1; if(octave.valid()) { run_fasthessian_kernel(grid, threads, d_hessianBuffer, octaveIdx); ASRL_CHECK_CUDA_ERROR("Finding fasthessian"); } // GlobalTimer.stop("compute interest operator"); //////////// // NONMAX // //////////// // GlobalTimer.start("nonmax suppression"); // Reset the candidate count. cudaMemset(features.featureCounterMem().d_get() + 1,0,sizeof(int)); // clear the adaptive threshold histograms. histograms.memsetDevice(0); threads.x = nonmax_x_threads; threads.y = nonmax_y_threads; threads.z = 1;//octave.intervals(); grid.x = ( (octave.width() + (threads.x) - 1) / (threads.x)); grid.y = ( (octave.height() + (threads.y-2) - 1) / (threads.y-2)); grid.z = 1; size_t sharedBytes = (threads.x + 2) * threads.y * octave.intervals() * sizeof(float); run_surf_nonmaxonly_kernel(grid, threads, sharedBytes, d_hessianBuffer, octaveIdx, features.rawFeatureMem().d_get(), features.featureCounterMem().d_get() + 1, basic_threshold, histograms.d_get()); ASRL_CHECK_CUDA_ERROR("Running Nonmax, octave " << octaveIdx); // GlobalTimer.stop("nonmax suppression"); //////////////////////// // ADAPTIVE THRESHOLD // //////////////////////// // GlobalTimer.start("find thresholds"); run_find_adaptive_thresholds_kernel(histograms.d_get(), thresholds.d_get(), regions_horizontal, regions_vertical, octaveIdx, basic_threshold); ASRL_CHECK_CUDA_ERROR("Running adaptive threhsold kernel, octave " << octaveIdx); // GlobalTimer.stop("find thresholds"); /* #if 0 histograms.pullFromDevice(); std::stringstream fname; fname << "hist-" << octaveIdx << ".txt"; std::ofstream fout(fname.str().c_str()); for(int r = 0; r < ASRL_SURF_MAX_REGIONS*ASRL_SURF_MAX_REGIONS; r++) { for(int i = 0; i < ASRL_SURF_HISTOGRAM_BUCKETS; i++) { fout << histograms[r*ASRL_SURF_HISTOGRAM_BUCKETS + i] << '\t'; } fout << std::endl; } thresholds.pullFromDevice(); std::stringstream fnameb; fnameb << "threshold-" << octaveIdx << ".txt"; std::ofstream foutb(fnameb.str().c_str()); for(int r = 0; r < ASRL_SURF_MAX_REGIONS*ASRL_SURF_MAX_REGIONS; r++) { foutb << thresholds[r] << '\t'; } #endif */ /////////////////// // INTERPOLATION // /////////////////// // GlobalTimer.start("keypoint interpolation"); run_fh_interp_extremum(d_hessianBuffer, features.deviceFeatures(), features.rawFeatureMem().d_get(), features.featureCounterMem().d_get(), features.featureCounterMem().d_get() + 1, thresholds.d_get()); ASRL_CHECK_CUDA_ERROR("Running subpixel interpolation"); features.featureCounterMem().pullFromDevice(); features.setDirty(); // GlobalTimer.stop("keypoint interpolation"); } // run_surf_detector() } // namespace asrl
35.601307
146
0.684597
utiasASRL
c61c1689a56d922465da5c25fd6b6d9ad8e5aec0
5,971
cpp
C++
dblib/src/EDatabase.cpp
cxxjava/CxxDBC
01bee98aa407c9e762cf75f63a2c21942968cf0a
[ "Apache-2.0" ]
20
2017-09-01T08:56:25.000Z
2021-03-18T11:07:38.000Z
dblib/src/EDatabase.cpp
foolishantcat/CxxDBC
f0f9e95baad72318e7fe53231aeca2ffa4a8b574
[ "Apache-2.0" ]
null
null
null
dblib/src/EDatabase.cpp
foolishantcat/CxxDBC
f0f9e95baad72318e7fe53231aeca2ffa4a8b574
[ "Apache-2.0" ]
14
2017-09-01T12:23:36.000Z
2021-09-02T01:06:27.000Z
/* * EDatabase.cpp * * Created on: 2017-6-12 * Author: cxxjava@163.com */ #include "../inc/EDatabase.hh" #include "../../interface/EDBInterface.h" namespace efc { namespace edb { EDatabase::~EDatabase() { // } EDatabase::EDatabase(EDBProxyInf* proxy) : m_DBProxy(proxy), m_AutoCommit(true), m_ErrorCode(0), m_CursorID(0) { } sp<EBson> EDatabase::processSQL(EBson *req, void *arg) { #ifdef DEBUG showMessage(req); #endif sp<EBson> rep; int ope = req->getInt(EDB_KEY_MSGTYPE); switch (ope) { case DB_SQL_DBOPEN: rep = onOpen(req); break; case DB_SQL_DBCLOSE: rep = onClose(req); break; case DB_SQL_EXECUTE: { EIterable<EInputStream*>* itb = (EIterable<EInputStream*>*)arg; rep = onExecute(req, itb); break; } case DB_SQL_UPDATE: { EIterable<EInputStream*>* itb = (EIterable<EInputStream*>*)arg; rep = onUpdate(req, itb); break; } case DB_SQL_MORE_RESULT: rep = onMoreResult(req); break; case DB_SQL_RESULT_FETCH: rep = onResultFetch(req); break; case DB_SQL_RESULT_CLOSE: rep = onResultClose(req); break; case DB_SQL_SET_AUTOCOMMIT: { boolean flag = req->getByte(EDB_KEY_AUTOCOMMIT) ? true : false; rep = setAutoCommit(flag); break; } case DB_SQL_COMMIT: rep = onCommit(); break; case DB_SQL_ROLLBACK: rep = onRollback(); break; case DB_SQL_SETSAVEPOINT: rep = setSavepoint(req); break; case DB_SQL_BACKSAVEPOINT: rep = rollbackSavepoint(req); break; case DB_SQL_RELESAVEPOINT: rep = releaseSavepoint(req); break; case DB_SQL_LOB_CREATE: rep = onLOBCreate(); break; case DB_SQL_LOB_WRITE: { EInputStream *is = (EInputStream*)arg; llong oid = req->getLLong(EDB_KEY_OID); rep = onLOBWrite(oid, is); break; } case DB_SQL_LOB_READ: { EOutputStream *os = (EOutputStream*)arg; llong oid = req->getLLong(EDB_KEY_OID); rep = onLOBRead(oid, os); break; } default: { m_ErrorCode = -1; m_ErrorMessage = EString::formatOf("No #%d message.", ope); break; } } if (!rep) { rep = genRspCommFailure(); } #ifdef DEBUG showMessage(rep.get()); #endif return rep; } sp<EBson> EDatabase::onOpen(EBson *req) { char* database = req->get(EDB_KEY_DATABASE); char* host = req->get(EDB_KEY_HOST); int port = req->getInt(EDB_KEY_PORT); char* username = req->get(EDB_KEY_USERNAME); char* password = req->get(EDB_KEY_PASSWORD); char* charset = req->get(EDB_KEY_CHARSET); int timeout = req->getInt(EDB_KEY_TIMEOUT, 60); //默认60秒 boolean ret = open(database, host, port, username, password, charset, timeout); if (!ret) { return null; } sp<EBson> rep = new EBson(); rep->addInt(EDB_KEY_ERRCODE, ES_SUCCESS); rep->add(EDB_KEY_VERSION, m_DBProxy ? m_DBProxy->getProxyVersion().c_str(): null); rep->add(EDB_KEY_DBTYPE, dbtype().c_str()); rep->add(EDB_KEY_DBVERSION, dbversion().c_str()); return rep; } sp<EBson> EDatabase::onClose(EBson *req) { boolean ret = close(); if (!ret) { return null; } sp<EBson> rep = new EBson(); rep->addInt(EDB_KEY_ERRCODE, ES_SUCCESS); return rep; } sp<EBson> EDatabase::doSavepoint(EBson *req, EString& sql) { //转换请求为onUpdate(req) req->setInt(EDB_KEY_MSGTYPE, DB_SQL_UPDATE); req->add(EDB_KEY_SQLS "/" EDB_KEY_SQL, sql.c_str()); return onUpdate(req, null); } sp<EBson> EDatabase::setSavepoint(EBson *req) { EString name = req->getString(EDB_KEY_NAME); EString sql = EString::formatOf("SAVEPOINT %s", name.c_str()); return doSavepoint(req, sql); } sp<EBson> EDatabase::rollbackSavepoint(EBson *req) { EString name = req->getString(EDB_KEY_NAME); EString sql = EString::formatOf("ROLLBACK TO SAVEPOINT %s", name.c_str()); return doSavepoint(req, sql); } sp<EBson> EDatabase::releaseSavepoint(EBson *req) { EString name = req->getString(EDB_KEY_NAME); EString sql = EString::formatOf("RELEASE SAVEPOINT %s", name.c_str()); return doSavepoint(req, sql); } boolean EDatabase::getAutoCommit() { return m_AutoCommit; } llong EDatabase::newCursorID() { return ++m_CursorID; } llong EDatabase::currCursorID() { return m_CursorID; } sp<EBson> EDatabase::genRspCommSuccess() { sp<EBson> rep = new EBson(); rep->addInt(EDB_KEY_ERRCODE, ES_SUCCESS); return rep; } sp<EBson> EDatabase::genRspCommFailure() { sp<EBson> rep = new EBson(); rep->addInt(EDB_KEY_ERRCODE, ES_FAILURE); rep->add(EDB_KEY_ERRMSG, m_ErrorMessage.c_str()); return rep; } void EDatabase::dumpSQL(const char *oldSql, const char *newSql) { if (m_DBProxy != null && (oldSql || newSql)) { m_DBProxy->dumpSQL(oldSql, newSql); } } void EDatabase::setErrorCode(int errcode) { m_ErrorCode = errcode; } int EDatabase::getErrorCode() { return m_ErrorCode; } void EDatabase::setErrorMessage(const char* message) { m_ErrorMessage = message; } EString EDatabase::getErrorMessage() { return m_ErrorMessage; } EString EDatabase::getDBType() { return dbtype(); } #ifdef DEBUG void EDatabase::showMessage(EBson* bson) { EByteArrayOutputStream baos; bson->Export(&baos, NULL); EByteArrayInputStream bais(baos.data(), baos.size()); class BsonParser : public EBsonParser { public: BsonParser(EInputStream *is) : EBsonParser(is) { } void parsing(es_bson_node_t* node) { if (!node) return; for (int i=1; i<_bson->levelOf(node); i++) { printf("\t"); } printf(node->name); printf("-->"); if (eso_strcmp(node->name, "param") == 0) { printf("?"); } else if (eso_strcmp(node->name, "record") == 0) { es_size_t size = 0; void *value = EBson::nodeGet(node, &size); EByteArrayInputStream bais(value, size); EDataInputStream dis(&bais); int len; try { while ((len = dis.readInt()) != -1) { EA<byte> buf(len + 1); dis.read(buf.address(), len); printf(" %s |", buf.address()); } } catch (...) { } } else { printf(EBson::nodeGetString(node).c_str()); } printf("\n"); } }; BsonParser ep(&bais); EBson bson_; while (ep.nextBson(&bson_)) { // } } #endif } /* namespace edb */ } /* namespace efc */
21.555957
83
0.676269
cxxjava
c61cd1991f720bd75987be76adaf0f5cca6e7768
4,409
cc
C++
bigtable/client/table_admin.cc
cschuet/google-cloud-cpp
e6397ac48571202ee9a7adef298aad9c7c6facde
[ "Apache-2.0" ]
null
null
null
bigtable/client/table_admin.cc
cschuet/google-cloud-cpp
e6397ac48571202ee9a7adef298aad9c7c6facde
[ "Apache-2.0" ]
null
null
null
bigtable/client/table_admin.cc
cschuet/google-cloud-cpp
e6397ac48571202ee9a7adef298aad9c7c6facde
[ "Apache-2.0" ]
null
null
null
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "bigtable/client/table_admin.h" #include "bigtable/client/internal/throw_delegate.h" #include <sstream> namespace btproto = ::google::bigtable::admin::v2; namespace bigtable { inline namespace BIGTABLE_CLIENT_NS { ::google::bigtable::admin::v2::Table TableAdmin::CreateTable( std::string table_id, TableConfig config) { grpc::Status status; auto result = impl_.CreateTable(std::move(table_id), std::move(config), status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } return result; } std::vector<::google::bigtable::admin::v2::Table> TableAdmin::ListTables( ::google::bigtable::admin::v2::Table::View view) { grpc::Status status; auto result = impl_.ListTables(std::move(view), status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } return result; } ::google::bigtable::admin::v2::Table TableAdmin::GetTable( std::string table_id, ::google::bigtable::admin::v2::Table::View view) { grpc::Status status; auto result = impl_.GetTable(std::move(table_id), status, std::move(view)); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } return result; } void TableAdmin::DeleteTable(std::string table_id) { grpc::Status status; impl_.DeleteTable(std::move(table_id), status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } } ::google::bigtable::admin::v2::Table TableAdmin::ModifyColumnFamilies( std::string table_id, std::vector<ColumnFamilyModification> modifications) { grpc::Status status; auto result = impl_.ModifyColumnFamilies(std::move(table_id), std::move(modifications), status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } return result; } void TableAdmin::DropRowsByPrefix(std::string table_id, std::string row_key_prefix) { grpc::Status status; impl_.DropRowsByPrefix(std::move(table_id), std::move(row_key_prefix), status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } } void TableAdmin::DropAllRows(std::string table_id) { grpc::Status status; impl_.DropAllRows(std::move(table_id), status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } } ::google::bigtable::admin::v2::Snapshot TableAdmin::GetSnapshot( bigtable::ClusterId const& cluster_id, bigtable::SnapshotId const& snapshot_id) { grpc::Status status; auto result = impl_.GetSnapshot(cluster_id, snapshot_id, status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } return result; } std::string TableAdmin::GenerateConsistencyToken(std::string const& table_id) { grpc::Status status; std::string token = impl_.GenerateConsistencyToken(std::move(table_id), status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } return token; } bool TableAdmin::CheckConsistency( bigtable::TableId const& table_id, bigtable::ConsistencyToken const& consistency_token) { grpc::Status status; bool consistent = impl_.CheckConsistency(table_id, consistency_token, status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } return consistent; } void TableAdmin::DeleteSnapshot(bigtable::ClusterId const& cluster_id, bigtable::SnapshotId const& snapshot_id) { grpc::Status status; impl_.DeleteSnapshot(cluster_id, snapshot_id, status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } } } // namespace BIGTABLE_CLIENT_NS } // namespace bigtable
32.902985
80
0.700386
cschuet
c62329643d5be4cf2d8ec26240941a38e72c1964
225
cpp
C++
Resources/Example Code/03 Loops/While Loop Countdown/countdown.cpp
tdfairch2/CS200-Concepts-of-Progamming-Algorithms
050510da8eea06aff3519097cc5f22831036b7cf
[ "MIT" ]
null
null
null
Resources/Example Code/03 Loops/While Loop Countdown/countdown.cpp
tdfairch2/CS200-Concepts-of-Progamming-Algorithms
050510da8eea06aff3519097cc5f22831036b7cf
[ "MIT" ]
null
null
null
Resources/Example Code/03 Loops/While Loop Countdown/countdown.cpp
tdfairch2/CS200-Concepts-of-Progamming-Algorithms
050510da8eea06aff3519097cc5f22831036b7cf
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int counter = 100; while ( counter > 0 ) { // the \t is a tab character. cout << counter << "\t"; counter--; } return 0; }
12.5
37
0.488889
tdfairch2
c62335a7a24ee968a1db12ff3eb2771af010d9c5
8,847
cpp
C++
source/Irrlicht/CGUIProfiler.cpp
vell001/Irrlicht-vell
23d4f03dbcd35dd93681dc0751f327f584516709
[ "IJG" ]
null
null
null
source/Irrlicht/CGUIProfiler.cpp
vell001/Irrlicht-vell
23d4f03dbcd35dd93681dc0751f327f584516709
[ "IJG" ]
null
null
null
source/Irrlicht/CGUIProfiler.cpp
vell001/Irrlicht-vell
23d4f03dbcd35dd93681dc0751f327f584516709
[ "IJG" ]
null
null
null
// This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h // Written by Michael Zeilfelder #include "CGUIProfiler.h" #ifdef _IRR_COMPILE_WITH_GUI_ #include "IGUITable.h" #include "IGUIScrollBar.h" #include "IGUIEnvironment.h" #include "CProfiler.h" namespace irr { namespace gui { //! constructor CGUIProfiler::CGUIProfiler(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect<s32> rectangle, IProfiler* profiler) : IGUIProfiler(environment, parent, id, rectangle, profiler) , Profiler(profiler) , DisplayTable(0), CurrentGroupIdx(0), CurrentGroupPage(0), NumGroupPages(1) , DrawBackground(false), Frozen(false), UnfreezeOnce(false), ShowGroupsTogether(false) , MinCalls(0), MinTimeSum(0), MinTimeAverage(0.f), MinTimeMax(0) { if ( !Profiler ) Profiler = &getProfiler(); core::recti r(0, 0, rectangle.getWidth(), rectangle.getHeight()); // Really just too lazy to code a complete new element for this. // If anyone can do this nicer he's welcome. DisplayTable = Environment->addTable(r, this, -1, DrawBackground); DisplayTable->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT); DisplayTable->setSubElement(true); rebuildColumns(); } void CGUIProfiler::fillRow(u32 rowIndex, const SProfileData& data, bool overviewTitle, bool groupTitle) { DisplayTable->setCellText(rowIndex, 0, data.getName()); if ( !overviewTitle ) DisplayTable->setCellText(rowIndex, 1, core::stringw(data.getCallsCounter())); if ( data.getCallsCounter() > 0 ) { DisplayTable->setCellText(rowIndex, 2, core::stringw(data.getTimeSum())); DisplayTable->setCellText(rowIndex, 3, core::stringw((u32)((f32)data.getTimeSum()/(f32)data.getCallsCounter()))); DisplayTable->setCellText(rowIndex, 4, core::stringw(data.getLongestTime())); } if ( overviewTitle || groupTitle ) { const video::SColor titleColor(255, 0, 0, 255); DisplayTable->setCellColor(rowIndex, 0, titleColor); } } void CGUIProfiler::rebuildColumns() { if ( DisplayTable ) { DisplayTable->clear(); DisplayTable->addColumn(L"name "); DisplayTable->addColumn(L"count calls"); DisplayTable->addColumn(L"time(sum)"); DisplayTable->addColumn(L"time(avg)"); DisplayTable->addColumn(L"time(max) "); DisplayTable->setActiveColumn(-1); } } u32 CGUIProfiler::addDataToTable(u32 rowIndex, u32 dataIndex, u32 groupIndex) { const SProfileData& data = Profiler->getProfileDataByIndex(dataIndex); if ( data.getGroupIndex() == groupIndex && data.getCallsCounter() >= MinCalls && ( data.getCallsCounter() == 0 || (data.getTimeSum() >= MinTimeSum && (f32)data.getTimeSum()/(f32)data.getCallsCounter() >= MinTimeAverage && data.getLongestTime() >= MinTimeMax)) ) { rowIndex = DisplayTable->addRow(rowIndex); fillRow(rowIndex, data, false, false); ++rowIndex; } return rowIndex; } void CGUIProfiler::updateDisplay() { if ( DisplayTable ) { DisplayTable->clearRows(); if ( CurrentGroupIdx < Profiler->getGroupCount() ) { bool overview = CurrentGroupIdx == 0; u32 rowIndex = 0; // show description row (overview or name of the following group) const SProfileData& groupData = Profiler->getGroupData(CurrentGroupIdx); if ( !ShowGroupsTogether && (overview || groupData.getCallsCounter() >= MinCalls) ) { rowIndex = DisplayTable->addRow(rowIndex); fillRow(rowIndex, groupData, overview, true); ++rowIndex; } // show overview over all groups? if ( overview ) { for ( u32 i=1; i<Profiler->getGroupCount(); ++i ) { const SProfileData& groupData = Profiler->getGroupData(i); if ( groupData.getCallsCounter() >= MinCalls ) { rowIndex = DisplayTable->addRow(rowIndex); fillRow(rowIndex, groupData, false, false); ++rowIndex; } } } // show data for all elements in current group else { for ( u32 i=0; i < Profiler->getProfileDataCount(); ++i ) { rowIndex = addDataToTable(rowIndex, i, CurrentGroupIdx); } } // Show the rest of the groups if (ShowGroupsTogether) { for ( u32 groupIdx = CurrentGroupIdx+1; groupIdx < Profiler->getGroupCount(); ++groupIdx) { for ( u32 i=0; i < Profiler->getProfileDataCount(); ++i ) { rowIndex = addDataToTable(rowIndex, i, groupIdx); } } } } // IGUITable has no page-wise scrolling yet. The following code can be replaced when we add that. // For now we use some CGUITable implementation info to figure this out. // (If you wonder why I didn't code page-scrolling directly in CGUITable ... because then it needs to be a // public interface and I don't have enough time currently to design & implement that well) s32 itemsTotalHeight = DisplayTable->getRowCount() * DisplayTable->getItemHeight(); s32 tableHeight = DisplayTable->getAbsolutePosition().getHeight(); s32 heightTitleRow = DisplayTable->getItemHeight()+1; if ( itemsTotalHeight+heightTitleRow < tableHeight ) { NumGroupPages = 1; } else { s32 heightHScrollBar = DisplayTable->getHorizontalScrollBar() ? DisplayTable->getHorizontalScrollBar()->getAbsolutePosition().getHeight() : 0; s32 pageHeight = tableHeight - (heightTitleRow+heightHScrollBar); if ( pageHeight > 0 ) { NumGroupPages = (itemsTotalHeight/pageHeight); if ( itemsTotalHeight % pageHeight ) ++NumGroupPages; } else // won't see anything, but that's up to the user { NumGroupPages = DisplayTable->getRowCount(); } if ( NumGroupPages < 1 ) NumGroupPages = 1; } if ( CurrentGroupPage < 0 ) CurrentGroupPage = (s32)NumGroupPages-1; IGUIScrollBar* vScrollBar = DisplayTable->getVerticalScrollBar(); if ( vScrollBar ) { if ( NumGroupPages < 2 ) vScrollBar->setPos(0); else { f32 factor = (f32)CurrentGroupPage/(f32)(NumGroupPages-1); vScrollBar->setPos( s32(factor * (f32)vScrollBar->getMax()) ); } } } } void CGUIProfiler::draw() { if ( isVisible() ) { if (!Frozen || UnfreezeOnce) { UnfreezeOnce = false; updateDisplay(); } } IGUIElement::draw(); } void CGUIProfiler::nextPage(bool includeOverview) { UnfreezeOnce = true; if ( CurrentGroupPage < NumGroupPages-1 ) ++CurrentGroupPage; else { CurrentGroupPage = 0; if ( ++CurrentGroupIdx >= Profiler->getGroupCount() ) { if ( includeOverview ) CurrentGroupIdx = 0; else CurrentGroupIdx = 1; // can be invalid } } } void CGUIProfiler::previousPage(bool includeOverview) { UnfreezeOnce = true; if ( CurrentGroupPage > 0 ) { --CurrentGroupPage; } else { CurrentGroupPage = -1; // unknown because NumGroupPages has to be re-calculated first if ( CurrentGroupIdx > 0 ) --CurrentGroupIdx; else CurrentGroupIdx = Profiler->getGroupCount()-1; if ( CurrentGroupIdx == 0 && !includeOverview ) { if ( Profiler->getGroupCount() ) CurrentGroupIdx = Profiler->getGroupCount()-1; if ( CurrentGroupIdx == 0 ) CurrentGroupIdx = 1; // invalid to avoid showing the overview } } } void CGUIProfiler::setShowGroupsTogether(bool groupsTogether) { ShowGroupsTogether = groupsTogether; } bool CGUIProfiler::getShowGroupsTogether() const { return ShowGroupsTogether; } void CGUIProfiler::firstPage(bool includeOverview) { UnfreezeOnce = true; if ( includeOverview ) CurrentGroupIdx = 0; else CurrentGroupIdx = 1; // can be invalid CurrentGroupPage = 0; } //! Sets another skin independent font. void CGUIProfiler::setOverrideFont(IGUIFont* font) { if ( DisplayTable ) { DisplayTable->setOverrideFont(font); rebuildColumns(); } } //! Gets the override font (if any) IGUIFont * CGUIProfiler::getOverrideFont() const { if ( DisplayTable ) return DisplayTable->getOverrideFont(); return 0; } //! Get the font which is used right now for drawing IGUIFont* CGUIProfiler::getActiveFont() const { if ( DisplayTable ) return DisplayTable->getActiveFont(); return 0; } //! Sets whether to draw the background. By default disabled, void CGUIProfiler::setDrawBackground(bool draw) { DrawBackground = draw; if ( DisplayTable ) DisplayTable->setDrawBackground(draw); } //! Checks if background drawing is enabled bool CGUIProfiler::isDrawBackgroundEnabled() const { return DrawBackground; } //! Allows to freeze updates which makes it easier to read the numbers void CGUIProfiler::setFrozen(bool freeze) { Frozen = freeze; } //! Are updates currently frozen bool CGUIProfiler::getFrozen() const { return Frozen; } void CGUIProfiler::setFilters(irr::u32 minCalls, irr::u32 minTimeSum, irr::f32 minTimeAverage, irr::u32 minTimeMax) { MinCalls = minCalls; MinTimeSum = minTimeSum; MinTimeAverage = minTimeAverage; MinTimeMax = minTimeMax; } } // end namespace gui } // end namespace irr #endif // _IRR_COMPILE_WITH_GUI_
26.64759
145
0.703628
vell001
c623b218f302af9881bc54f3567fe19fa1deaaaa
1,384
cpp
C++
src/Nazara/Graphics/AbstractRenderQueue.cpp
AntoineJT/NazaraEngine
e0b05a7e7a2779e20a593b4083b4a881cc57ce14
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
src/Nazara/Graphics/AbstractRenderQueue.cpp
AntoineJT/NazaraEngine
e0b05a7e7a2779e20a593b4083b4a881cc57ce14
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
src/Nazara/Graphics/AbstractRenderQueue.cpp
AntoineJT/NazaraEngine
e0b05a7e7a2779e20a593b4083b4a881cc57ce14
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Graphics/AbstractRenderQueue.hpp> #include <Nazara/Graphics/Debug.hpp> namespace Nz { /*! * \ingroup graphics * \class Nz::AbstractRenderQueue * \brief Graphics class that represents the rendering queue for our scene * * \remark This class is abstract */ AbstractRenderQueue::~AbstractRenderQueue() = default; /*! * \brief Adds a directional light to the rendering queue * * \param light Directional light */ void AbstractRenderQueue::AddDirectionalLight(const DirectionalLight& light) { directionalLights.push_back(light); } /*! * \brief Adds a point light to the rendering queue * * \param light Point light */ void AbstractRenderQueue::AddPointLight(const PointLight& light) { pointLights.push_back(light); } /*! * \brief Adds a spot light to the rendering queue * * \param light Spot light */ void AbstractRenderQueue::AddSpotLight(const SpotLight& light) { spotLights.push_back(light); } /*! * \brief Clears the rendering queue * * \param fully Should everything be cleared ? */ void AbstractRenderQueue::Clear(bool fully) { NazaraUnused(fully); directionalLights.clear(); pointLights.clear(); spotLights.clear(); } }
20.352941
77
0.725434
AntoineJT
c623e28ad67a964099a008365d871a39ceb7eb6f
6,161
hpp
C++
foedus_code/foedus-core/include/foedus/log/log_type.hpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/foedus-core/include/foedus/log/log_type.hpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/foedus-core/include/foedus/log/log_type.hpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2014-2015, Hewlett-Packard Development Company, LP. * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * HP designates this particular file as subject to the "Classpath" exception * as provided by HP in the LICENSE.txt file that accompanied this code. */ #ifndef FOEDUS_LOG_LOG_TYPE_HPP_ #define FOEDUS_LOG_LOG_TYPE_HPP_ #include "foedus/cxx11.hpp" // include all header files that forward-declare log types defined in the xmacro. // don't include headers that really declare them. we just need foward-declarations here. #include "foedus/log/fwd.hpp" #include "foedus/storage/fwd.hpp" #include "foedus/storage/array/fwd.hpp" #include "foedus/storage/hash/fwd.hpp" #include "foedus/storage/masstree/fwd.hpp" #include "foedus/storage/sequential/fwd.hpp" namespace foedus { namespace log { /** * @defgroup LOGTYPE Log Types * @ingroup LOG * @brief Defines the content and \e apply logic of transactional operatrions. * @details * Each loggable operation defines a struct XxxLogType that has the following methods: * * \li "populate" method to populate all properties, but the method is not overridden and its * signature varies. This is just to have a uniform method name for readability. * \li One of the 3 apply methods as follows. These also populate xct_order in log if applicable * (remember, XctId or xct_order is finalized only at commit time, so populate() can't do it). * \li void apply_engine(Thread*) : For engine-wide operation. * \li void apply_storage(Engine*, StorageId) : For storage-wide operation. * \li void apply_record(Thread*, StorageId, RwLockableXctId*, char*) : For record-wise operation. * \li void assert_valid() : For debugging (should have no cost in NDEBUG). * \li is_engine_log()/is_storage_log()/is_record_log() * \li ostream operator, preferably in xml format. * * For non-applicable apply-type, the implmentation class should abort. * Remember that these are all non-virtual methods. See the next section for more details. * * @par No polymorphism * There is no polymorphism guaranteed for log types. * Because we read/write just a bunch of bytes and do reinterpret_cast, there is no dynamic * type information. We of course can't afford instantiating objects for each log entry, either. * Do not use any override in log type classes. You should even delete \b all constructors to avoid * misuse (see LOG_TYPE_NO_CONSTRUCT(clazz) ). * We do have base classes (EngineLogType, StorageLogType, and RecordLogType), but this is only * to reduce typing. No virtual methods. * * @par Current List of LogType * See foedus::log::LogCode * * @par log_type.hpp and log_type_invoke.hpp * This file defines only log codes and names, so quite compact even after preprocessing. * On the other hand, log_type_invoke.hpp defines more methods that need to include a few * more headers, so its size is quite big after proprocessing. Most places should need only * log_type.hpp. Include log_type_invoke.hpp only where we invoke apply/ostream etc. */ /** * @var LogCode * @brief A unique identifier of all log types. * @ingroup LOGTYPE * @details * Log code values must follow the convention. * Most significant 4 bits are used to denote the kind of the log: * \li 0x0000: record targetted logs * \li 0x1000: storage targetted logs * \li 0x2000: engine targetted logs * \li 0x3000: markers/fillers * \li ~0xF000 (reserved for future use) */ #define X(a, b, c) /** b: c. @copydoc c */ a = b, enum LogCode { /** 0 is reserved as a non-existing log type. */ kLogCodeInvalid = 0, #include "foedus/log/log_type.xmacro" // NOLINT }; #undef X /** * @var LogCodeKind * @brief Represents the kind of log types. * @ingroup LOGTYPE * @details * This is the most significant 4 bits of LogCode. */ enum LogCodeKind { /** record targetted logs */ kRecordLogs = 0, /** storage targetted logs */ kStorageLogs = 1, /** engine targetted logs */ kEngineLogs = 2, /** markers/fillers */ kMarkerLogs = 3, }; /** * @brief Returns the kind of the given log code. * @ingroup LOGTYPE * @details * This is inlined here because it's called frequently. */ inline LogCodeKind get_log_code_kind(LogCode code) { return static_cast<LogCodeKind>(code >> 12); } /** * @brief Returns if the LogCode value exists. * @ingroup LOGTYPE * @details * This is inlined here because it's called frequently. */ inline bool is_valid_log_type(LogCode code) { switch (code) { #define X(a, b, c) case a: return true; #include "foedus/log/log_type.xmacro" // NOLINT #undef X default: return false; } } /** * @brief Returns the names of LogCode enum defined in log_type.xmacro. * @ingroup LOGTYPE * @details * This is NOT inlined because this is used only in debugging situation. */ const char* get_log_type_name(LogCode code); /** * @brief Returns LogCode for the log type defined in log_type.xmacro. * @ingroup LOGTYPE * @details * This is inlined below because it's called VERY frequently. * This method is declared as constexpr if C++11 is enabled, in which case there should * be really no overheads to call this method. */ template <typename LOG_TYPE> CXX11_CONSTEXPR LogCode get_log_code(); // give a template specialization for each log type class #define X(a, b, c) template <> inline CXX11_CONSTEXPR LogCode get_log_code< c >() { return a ; } #include "foedus/log/log_type.xmacro" // NOLINT #undef X } // namespace log } // namespace foedus #endif // FOEDUS_LOG_LOG_TYPE_HPP_
37.339394
100
0.735108
sam1016yu
c6266ab319663c6f8892dc11f413a75e87b5a237
1,021
hpp
C++
soccer/src/soccer/planning/planner/pivot_path_planner.hpp
xiaoqingyu0113/robocup-software
6127d25fc455051ef47610d0e421b2ca7330b4fa
[ "Apache-2.0" ]
200
2015-01-26T01:45:34.000Z
2022-03-19T13:05:31.000Z
soccer/src/soccer/planning/planner/pivot_path_planner.hpp
xiaoqingyu0113/robocup-software
6127d25fc455051ef47610d0e421b2ca7330b4fa
[ "Apache-2.0" ]
1,254
2015-01-03T01:57:35.000Z
2022-03-16T06:32:21.000Z
soccer/src/soccer/planning/planner/pivot_path_planner.hpp
xiaoqingyu0113/robocup-software
6127d25fc455051ef47610d0e421b2ca7330b4fa
[ "Apache-2.0" ]
206
2015-01-21T02:03:18.000Z
2022-02-01T17:57:46.000Z
#pragma once #include "planner.hpp" namespace planning { class PivotPathPlanner : public PlannerForCommandType<PivotCommand> { public: PivotPathPlanner() : PlannerForCommandType<PivotCommand>("PivotPathPlanner") {} ~PivotPathPlanner() override = default; PivotPathPlanner(PivotPathPlanner&&) noexcept = default; PivotPathPlanner& operator=(PivotPathPlanner&&) noexcept = default; PivotPathPlanner(const PivotPathPlanner&) = default; PivotPathPlanner& operator=(const PivotPathPlanner&) = default; Trajectory plan(const PlanRequest& request) override; void reset() override { previous_ = Trajectory{}; cached_pivot_target_ = std::nullopt; cached_pivot_point_ = std::nullopt; } private: Trajectory previous_; // Cache the pivot point and target so we don't just push the ball across the field. std::optional<rj_geometry::Point> cached_pivot_point_; std::optional<rj_geometry::Point> cached_pivot_target_; }; } // namespace planning
31.90625
88
0.728697
xiaoqingyu0113
c626a868fd2d71e50fd03c69ba5e5795e54b5462
626
cpp
C++
src/realsense_demo.cpp
ivision-ufba/depth-face-detection
f70441eb9e72fa3f509458ffc202648c2f3e27d1
[ "MIT" ]
15
2017-11-01T11:39:32.000Z
2021-04-02T02:42:59.000Z
src/realsense_demo.cpp
ivision-ufba/depth-face-detection
f70441eb9e72fa3f509458ffc202648c2f3e27d1
[ "MIT" ]
6
2017-07-26T17:55:27.000Z
2020-11-15T22:04:35.000Z
src/realsense_demo.cpp
ivision-ufba/depth-face-detection
f70441eb9e72fa3f509458ffc202648c2f3e27d1
[ "MIT" ]
5
2018-05-09T13:42:17.000Z
2020-01-17T06:22:59.000Z
#include <opencv2/highgui.hpp> #include "face_detector.hpp" #include "realsense.hpp" /* RealSense demonstration for faces in angles from 0 to 30 degrees in the * x-axis, -20 to 20 in the y-xis and no rotation in the z-axis */ int main() { RealSense rs; FaceDetector detector; while (true) { rs.get_images(); auto dets = detector.range_detect(rs.depth, rs.calibration, 0, -20, 0, 30, 20, 0); cvtColor(rs.depth, rs.depth, CV_GRAY2RGB); for (auto det : dets) cv::rectangle(rs.depth, det, cv::Scalar((1 << 16) - 1, 0, 0), 1); cv::imshow("depth", rs.depth); cv::waitKey(10); } }
25.04
78
0.635783
ivision-ufba
c628548dee59482174d11be3a487ed1748817b0d
5,817
cpp
C++
c86ctl/src/vis/vis_c86sub.cpp
honet/c86ctl
c1e454d4e0652c55dacb9435dfac218dfad89e7f
[ "BSD-3-Clause" ]
10
2015-04-04T17:05:04.000Z
2021-12-31T02:51:43.000Z
c86ctl/src/vis/vis_c86sub.cpp
honet/c86ctl
c1e454d4e0652c55dacb9435dfac218dfad89e7f
[ "BSD-3-Clause" ]
null
null
null
c86ctl/src/vis/vis_c86sub.cpp
honet/c86ctl
c1e454d4e0652c55dacb9435dfac218dfad89e7f
[ "BSD-3-Clause" ]
2
2015-04-09T14:16:29.000Z
2020-12-16T02:00:50.000Z
/*** c86ctl Copyright (c) 2009-2012, honet. All rights reserved. This software is licensed under the BSD license. honet.kk(at)gmail.com */ #include "stdafx.h" #include <stdlib.h> #include <stdio.h> #include <math.h> #include "resource.h" #include "vis_c86sub.h" #include "vis_c86skin.h" #ifdef _DEBUG #define new new(_NORMAL_BLOCK,__FILE__,__LINE__) #endif // -------------------------------------------------------------------------------------- void c86ctl::vis::blt( IVisBitmap *dst, int dst_x, int dst_y, int w, int h, IVisBitmap *src, int src_x, int src_y ) { if( dst_x<0 || dst_y<0 || src_x<0 || src_y<0 ) return; if( src_x+w > src->getWidth() || src_y+h > src->getHeight() || dst_x+w > dst->getWidth() || dst_y+h > dst->getHeight() ) return; for( int y=0; y<h; y++ ){ UINT *ps = ((UINT*)src->getRow0( src_y+y )) + src_x; UINT *pd = ((UINT*)dst->getRow0( dst_y+y )) + dst_x; for( int x=0; x<w; x++ ){ *pd++ = (*ps++|0xff000000); } } } void c86ctl::vis::alphablt( IVisBitmap *dst, int dst_x, int dst_y, int w, int h, IVisBitmap *src, int src_x, int src_y ) { if( dst_x<0 || dst_y<0 || src_x<0 || src_y<0 ) return; if( src_x+w > src->getWidth() || src_y+h > src->getHeight() || dst_x+w > dst->getWidth() || dst_y+h > dst->getHeight() ) return; for( int y=0; y<h; y++ ){ UINT *ps = ((UINT*)src->getRow0( src_y+y )) + src_x; UINT *pd = ((UINT*)dst->getRow0( dst_y+y )) + dst_x; for( int x=0; x<w; x++ ){ UINT a = *ps >> 24; UINT na = a^0xff; // 255-a UINT s = *ps; UINT d = *pd; UINT t; // (s*a) + (d*(1-a)) t = (((((s&0x00ff00ff) * ( a+1)) >> 8) & 0x00ff00ff) | ((((s&0x0000ff00) * ( a+1)) >> 8) & 0x0000ff00)) + + (((((d&0x00ff00ff) * (na+1)) >> 8) & 0x00ff00ff) | ((((d&0x0000ff00) * (na+1)) >> 8) & 0x0000ff00)); *pd = t; ps++; pd++; } } } void c86ctl::vis::transblt( IVisBitmap *dst, int dst_x, int dst_y, int w, int h, IVisBitmap *src1, int src1_x, int src1_y, IVisBitmap *src2, int src2_x, int src2_y, IVisBitmap *trans, int trans_x, int trans_y, int t ) { if( dst_x<0 || dst_y<0 || trans_x<0 || trans_y<0 ) return; if( src1_x<0 || src1_y<0 || src2_x<0 || src2_y<0 ) return; if( dst_x+w > dst->getWidth() || dst_y+h > dst->getHeight() || src1_x+w > src1->getWidth() || src1_y+h > src1->getHeight() || src2_x+w > src2->getWidth() || src2_y+h > src2->getHeight() || trans_x+w > trans->getWidth() || trans_y+h > trans->getHeight() ) return; for( int y=0; y<h; y++ ){ UINT *pd = (UINT*)dst->getRow0( dst_y+y ) + dst_x; UINT *ps1 = (UINT*)src1->getRow0( src1_y+y ) + src1_x; UINT *ps2 = (UINT*)src2->getRow0( src2_y+y ) + src2_x; UINT *ts = (UINT*)trans->getRow0( trans_y+y ) + trans_x; for( int x=0; x<w; x++ ){ int a = *ts&0xff; *pd = ( (t<=a) ? *ps1 : *ps2 ) | 0xff000000; pd++; ps1++; ps2++; ts++; } } } // [tmin, tmax) void c86ctl::vis::transblt2( IVisBitmap *dst, int dst_x, int dst_y, int w, int h, IVisBitmap *src1, int src1_x, int src1_y, IVisBitmap *src2, int src2_x, int src2_y, IVisBitmap *trans, int trans_x, int trans_y, int tmin, int tmax ) { if( dst_x<0 || dst_y<0 || trans_x<0 || trans_y<0 ) return; if( src1_x<0 || src1_y<0 || src2_x<0 || src2_y<0 ) return; if( dst_x+w > dst->getWidth() || dst_y+h > dst->getHeight() || src1_x+w > src1->getWidth() || src1_y+h > src1->getHeight() || src2_x+w > src2->getWidth() || src2_y+h > src2->getHeight() || trans_x+w > trans->getWidth() || trans_y+h > trans->getHeight() ) return; for( int y=0; y<h; y++ ){ UINT *pd = (UINT*)dst->getRow0( dst_y+y ) + dst_x; UINT *ps1 = (UINT*)src1->getRow0( src1_y+y ) + src1_x; UINT *ps2 = (UINT*)src2->getRow0( src2_y+y ) + src2_x; UINT *ts = (UINT*)trans->getRow0( trans_y+y ) + trans_x; for( int x=0; x<w; x++ ){ int a = *ts&0xff; *pd = ( (tmin<=a && a<tmax) ? *ps2 : *ps1 ) | 0xff000000; pd++; ps1++; ps2++; ts++; } } } void c86ctl::vis::visDrawLine( IVisBitmap *bmp, int xs, int ys, int xe, int ye, COLORREF col ) { // note: めんどくさがって bpp==4専用コードで書いてるので注意 if( !bmp ) return; if( xs<0 || ys<0 || bmp->getWidth()<=xs || bmp->getHeight()<=ys ) return; if( xe<0 || ye<0 || bmp->getWidth()<=xe || bmp->getHeight()<=ye ) return; int step = bmp->getStep()>>2; if( xs == xe ){ // 垂直線 if( ye<ys ) SWAP(ys,ye); UINT *p = ((UINT*)bmp->getRow0(ys)) + xs; for( int y=ys; y<=ye; y++ ){ *p = col; p += step; } }else if( ys == ye ){ //水平線 if( xe<xs ) SWAP(xs,xe); UINT *p = ((UINT*)bmp->getRow0(ys)) + xs; for( int x=xs; x<=xe; x++ ){ *p++ = col; } }else{ // 斜め // TODO : デバッグしてないの。 int dx = abs(xe-xs); int dy = abs(ye-ys); int dx2=dx*2; int dy2=dy*2; if( dx > dy ){ if( xe<xs ){ SWAP(xs,xe); SWAP(ys,ye); } UINT *p = ((UINT*)bmp->getRow0(ys)) + xs; int dstep = ys<ye ? step : -step; for( int e=dy, x=xs; x<=xe; x++, p+=1 ){ *p = col; e+=dy2; if( e>=dx2 ){ e-=dx2; p+=dstep; } } }else{ if( ye<ys ){ SWAP(xs,xe); SWAP(ys,ye); } UINT *p = ((UINT*)bmp->getRow0(ys)) + xs; int dstep = xs<xe ? 1 : -1; for( int e=dx, y=ys; y<=ye; y++, p+=step ){ *p = col; e+=dx2; if( e>=dy2 ){ e-=dy2; p+=dstep; } } } } } void c86ctl::vis::visFillRect( IVisBitmap *bmp, int xs, int ys, int w, int h, COLORREF col ) { if( !bmp ) return; if( xs<0 || ys<0 || bmp->getWidth()<(xs+w) || bmp->getHeight()<(ys+h) ) return; for( int y=0; y<h; y++ ){ UINT *p = ((UINT*)bmp->getRow0(ys+y)) + xs; for( int x=0; x<w; x++ ){ *p++ = col; } } }
26.440909
90
0.517105
honet
c6318ce193499b2925946ca964effcaef39c3f7b
6,842
cpp
C++
dotnet/native/sealnet/galoiskeys_wrapper.cpp
MasterMann/SEAL
791ae130de895e6323d36a12515cf2d59071e414
[ "MIT" ]
5
2019-04-29T01:46:05.000Z
2021-10-10T10:28:02.000Z
dotnet/native/sealnet/galoiskeys_wrapper.cpp
MasterMann/SEAL
791ae130de895e6323d36a12515cf2d59071e414
[ "MIT" ]
null
null
null
dotnet/native/sealnet/galoiskeys_wrapper.cpp
MasterMann/SEAL
791ae130de895e6323d36a12515cf2d59071e414
[ "MIT" ]
4
2019-04-18T11:28:13.000Z
2020-11-01T14:25:35.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. // SEALNet #include "sealnet/stdafx.h" #include "sealnet/galoiskeys_wrapper.h" #include "sealnet/utilities.h" // SEAL #include "seal/galoiskeys.h" using namespace std; using namespace seal; using namespace sealnet; namespace seal { struct GaloisKeys::GaloisKeysPrivateHelper { static void set_decomposition_bit_count(GaloisKeys &keys, int value) { keys.decomposition_bit_count_ = value; } }; } namespace { HRESULT GetKeyFromVector(const vector<Ciphertext> &key, uint64_t *count, void **ciphers) { *count = key.size(); if (nullptr == ciphers) { // We only wanted the count return S_OK; } auto ciphertexts = reinterpret_cast<Ciphertext**>(ciphers); for (size_t i = 0; i < key.size(); i++) { ciphertexts[i] = new Ciphertext(key[i]); } return S_OK; } } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_Create1(void **galois_keys) { IfNullRet(galois_keys, E_POINTER); GaloisKeys *keys = new GaloisKeys(); *galois_keys = keys; return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_Create2(void *copy, void **galois_keys) { GaloisKeys *copyptr = FromVoid<GaloisKeys>(copy); IfNullRet(copyptr, E_POINTER); IfNullRet(galois_keys, E_POINTER); GaloisKeys *keys = new GaloisKeys(*copyptr); *galois_keys = keys; return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_Destroy(void *thisptr) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); delete keys; return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_Set(void *thisptr, void *assign) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); GaloisKeys *assignptr = FromVoid<GaloisKeys>(assign); IfNullRet(assignptr, E_POINTER); *keys = *assignptr; return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_Size(void *thisptr, uint64_t *size) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(size, E_POINTER); *size = keys->size(); return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_DBC(void *thisptr, int *dbc) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(dbc, E_POINTER); *dbc = keys->decomposition_bit_count(); return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_SetDBC(void *thisptr, int dbc) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); GaloisKeys::GaloisKeysPrivateHelper::set_decomposition_bit_count(*keys, dbc); return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_GetKeyCount(void *thisptr, uint64_t *key_count) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(key_count, E_POINTER); *key_count = keys->data().size(); return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_GetKeyList(void *thisptr, uint64_t index, uint64_t *count, void **ciphers) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(count, E_POINTER); auto list = keys->data()[index]; return GetKeyFromVector(list, count, ciphers); } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_GetKey(void *thisptr, uint64_t galois_elt, uint64_t *count, void **ciphers) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(count, E_POINTER); if (!keys->has_key(galois_elt)) { return E_INVALIDARG; } const auto &key = keys->key(galois_elt); return GetKeyFromVector(key, count, ciphers); } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_ClearDataAndReserve(void *thisptr, uint64_t size) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); keys->data().clear(); keys->data().reserve(size); return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_AddKeyList(void *thisptr, uint64_t count, void **ciphers) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(ciphers, E_POINTER); Ciphertext **ciphertexts = reinterpret_cast<Ciphertext**>(ciphers); // Don't resize, only reserve keys->data().emplace_back(); keys->data().back().reserve(count); for (uint64_t i = 0; i < count; i++) { Ciphertext *cipher = ciphertexts[i]; Ciphertext new_key(keys->pool()); new_key = *cipher; keys->data().back().emplace_back(move(new_key)); } return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_HasKey(void *thisptr, uint64_t galois_elt, bool *has_key) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(has_key, E_POINTER); try { *has_key = keys->has_key(galois_elt); return S_OK; } catch (const invalid_argument&) { return E_INVALIDARG; } } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_GetParmsId(void *thisptr, uint64_t *parms_id) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(parms_id, E_POINTER); for (size_t i = 0; i < keys->parms_id().size(); i++) { parms_id[i] = keys->parms_id()[i]; } return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_SetParmsId(void *thisptr, uint64_t *parms_id) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(parms_id, E_POINTER); CopyParmsId(parms_id, keys->parms_id()); return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_IsValidFor(void *thisptr, void *contextptr, bool *result) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); const auto &sharedctx = SharedContextFromVoid(contextptr); IfNullRet(sharedctx.get(), E_POINTER); IfNullRet(result, E_POINTER); *result = keys->is_valid_for(sharedctx); return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_IsMetadataValidFor(void *thisptr, void *contextptr, bool *result) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); const auto &sharedctx = SharedContextFromVoid(contextptr); IfNullRet(sharedctx.get(), E_POINTER); IfNullRet(result, E_POINTER); *result = keys->is_metadata_valid_for(sharedctx); return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_Pool(void *thisptr, void **pool) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(pool, E_POINTER); MemoryPoolHandle *handleptr = new MemoryPoolHandle(keys->pool()); *pool = handleptr; return S_OK; }
26.315385
117
0.691026
MasterMann
c6326b407c937159bc6842753b2255d41c32e2b7
5,110
cpp
C++
tests/algo/test_bad_cmp.cpp
hthetran/stxxl
7f0223e52e9f10f28ed7d368cffecbbeeaa60ca7
[ "BSL-1.0" ]
null
null
null
tests/algo/test_bad_cmp.cpp
hthetran/stxxl
7f0223e52e9f10f28ed7d368cffecbbeeaa60ca7
[ "BSL-1.0" ]
null
null
null
tests/algo/test_bad_cmp.cpp
hthetran/stxxl
7f0223e52e9f10f28ed7d368cffecbbeeaa60ca7
[ "BSL-1.0" ]
null
null
null
/*************************************************************************** * tests/algo/test_bad_cmp.cpp * * Part of the STXXL. See http://stxxl.org * * Copyright (C) 2002 Roman Dementiev <dementiev@mpi-sb.mpg.de> * Copyright (C) 2011 Andreas Beckmann <beckmann@cs.uni-frankfurt.de> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ #define STXXL_DEFAULT_BLOCK_SIZE(T) 4096 //! \example algo/test_bad_cmp.cpp //! This is an example of how NOT to use \c stxxl::sort() algorithm. //! Here min_value and max_value are used as keys which is forbidden. #include <tlx/die.hpp> #include <tlx/logger.hpp> #include <foxxll/mng.hpp> #include <stxxl/bits/defines.h> #include <stxxl/sort> #include <stxxl/vector> struct my_type { using key_type = unsigned; key_type m_key; key_type m_data; my_type() { } explicit my_type(key_type k) : m_key(k), m_data(0) { } static my_type min_value() { return my_type(std::numeric_limits<key_type>::min()); } static my_type max_value() { return my_type(std::numeric_limits<key_type>::max()); } ~my_type() { } }; std::ostream& operator << (std::ostream& o, const my_type& obj) { o << obj.m_key; return o; } bool operator < (const my_type& a, const my_type& b) { return a.m_key < b.m_key; } bool operator == (const my_type& a, const my_type& b) { return a.m_key == b.m_key; } bool operator != (const my_type& a, const my_type& b) { return a.m_key != b.m_key; } struct cmp : public std::less<my_type> { my_type min_value() const { return my_type::min_value(); } my_type max_value() const { return my_type::max_value(); } }; int main(int argc, char* argv[]) { const size_t SIZE = (argc >= 2) ? strtoul(argv[1], nullptr, 0) : 16; #if STXXL_PARALLEL_MULTIWAY_MERGE LOG1 << "STXXL_PARALLEL_MULTIWAY_MERGE"; #endif size_t memory_to_use = SIZE * STXXL_DEFAULT_BLOCK_SIZE(my_type); using vector_type = stxxl::vector<my_type>; const uint64_t n_records = uint64_t(SIZE * 2 + SIZE / 2) * STXXL_DEFAULT_BLOCK_SIZE(my_type) / sizeof(my_type); vector_type v(n_records); uint64_t aliens, not_stable; size_t bs = vector_type::block_type::size; LOG1 << "Filling vector with min_value..., input size = " << v.size() << " elements (" << ((v.size() * sizeof(my_type)) >> 20) << " MiB)"; for (vector_type::size_type i = 0; i < v.size(); i++) { v[i].m_key = 0; v[i].m_data = static_cast<int>(i + 1); } LOG1 << "Checking order..."; die_unless(stxxl::is_sorted(v.cbegin(), v.cend(), cmp())); LOG1 << "Sorting (using " << (memory_to_use >> 20) << " MiB of memory)..."; stxxl::sort(v.begin(), v.end(), cmp(), memory_to_use); LOG1 << "Checking order..."; die_unless(stxxl::is_sorted(v.cbegin(), v.cend(), cmp())); aliens = not_stable = 0; for (vector_type::size_type i = 0; i < v.size(); i++) { if (v[i].m_data < 1) ++aliens; else if (v[i].m_data != i + 1) ++not_stable; v[i].m_data = static_cast<int>(i + 1); } LOG1 << "elements that were not in the input: " << aliens; LOG1 << "elements not on their expected location: " << not_stable; LOG1 << "Sorting subset (using " << (memory_to_use >> 20) << " MiB of memory)..."; stxxl::sort(v.begin() + bs - 1, v.end() - bs + 2, cmp(), memory_to_use); LOG1 << "Checking order..."; die_unless(stxxl::is_sorted(v.cbegin(), v.cend(), cmp())); aliens = not_stable = 0; for (vector_type::size_type i = 0; i < v.size(); i++) { if (v[i].m_data < 1) ++aliens; else if (v[i].m_data != i + 1) ++not_stable; v[i].m_data = static_cast<int>(i + 1); } LOG1 << "elements that were not in the input: " << aliens; LOG1 << "elements not on their expected location: " << not_stable; LOG1 << "Filling vector with max_value..., input size = " << v.size() << " elements (" << ((v.size() * sizeof(my_type)) >> 20) << " MiB)"; for (vector_type::size_type i = 0; i < v.size(); i++) { v[i].m_key = unsigned(-1); v[i].m_data = int(i + 1); } LOG1 << "Sorting subset (using " << (memory_to_use >> 20) << " MiB of memory)..."; stxxl::sort(v.begin() + bs - 1, v.end() - bs + 2, cmp(), memory_to_use); LOG1 << "Checking order..."; die_unless(stxxl::is_sorted(v.cbegin(), v.cend(), cmp())); aliens = not_stable = 0; for (vector_type::size_type i = 0; i < v.size(); i++) { if (v[i].m_data < 1) ++aliens; else if (v[i].m_data != i + 1) ++not_stable; v[i].m_data = int(i + 1); } LOG1 << "elements that were not in the input: " << aliens; LOG1 << "elements not on their expected location: " << not_stable; LOG1 << "Done, output size=" << v.size() << " block size=" << bs; return 0; }
29.883041
142
0.567906
hthetran
c63395f9b6d6e83658a4fe9f8f722cb308cec702
5,699
cpp
C++
src/cubic_bezier.cpp
pdulewic/Bezier_Curves
eb913d264337b362ed8e13b1e77c16102b7f718f
[ "MIT" ]
1
2019-10-03T14:44:52.000Z
2019-10-03T14:44:52.000Z
src/cubic_bezier.cpp
pdulewic/Bezier_Curves
eb913d264337b362ed8e13b1e77c16102b7f718f
[ "MIT" ]
null
null
null
src/cubic_bezier.cpp
pdulewic/Bezier_Curves
eb913d264337b362ed8e13b1e77c16102b7f718f
[ "MIT" ]
null
null
null
#include "inc/cubic_bezier.h" #include "inc/movable_curve.h" #include <QDebug> //===================================================================== CubicBezier::CubicBezier(QObject *parent): QObject(parent), bezierCurve(nullptr), bezierPolygon(nullptr), plot(nullptr) {} //===================================================================== void CubicBezier::swap(CubicBezier &other) { QCustomPlot* tmp1 = other.getPlot(); other.setPlot(getPlot()); setPlot(tmp1); QCPCurve* tmp2 = other.getBezierCurve(); other.setBezierCurve(getBezierCurve()); setBezierCurve(tmp2); MovableCurve* tmp3 = other.getBezierPolygon(); if(tmp3 != nullptr) { disconnect(tmp3,SIGNAL(curveChanged(int,QPointF)),&other,SLOT(updateControlPoints(int,QPointF))); connect(tmp3,SIGNAL(curveChanged(int,QPointF)),this,SLOT(updateControlPoints(int,QPointF))); } if(bezierPolygon != nullptr) { disconnect(bezierPolygon,SIGNAL(curveChanged(int,QPointF)),this,SLOT(updateControlPoints(int,QPointF))); connect(bezierPolygon,SIGNAL(curveChanged(int,QPointF)),&other,SLOT(updateControlPoints(int,QPointF))); } other.setBezierPolygon(getBezierPolygon()); setBezierPolygon(tmp3); for(int i=0; i<CUBIC_BEZIER_SIZE; ++i) { auto tmp = other[i]; other[i] = controlPoints[i]; controlPoints[i] = tmp; } } //===================================================================== CubicBezier::CubicBezier(QCustomPlot *_plot, std::initializer_list<QPointF> l, QObject *parent): QObject(parent), plot(_plot) { int i=0; for(auto x : l) controlPoints[i++] = x; bezierCurve = new QCPCurve(plot->xAxis, plot->yAxis); bezierPolygon = new MovableCurve(plot->xAxis, plot->yAxis); connect(bezierPolygon,SIGNAL(curveChanged(int,QPointF)),this,SLOT(updateControlPoints(int,QPointF))); } //===================================================================== CubicBezier::CubicBezier(const CubicBezier &cb): QObject(nullptr) { for(int i=0; i<CUBIC_BEZIER_SIZE; ++i) controlPoints[i] = cb[i]; plot = cb.getPlot(); bezierCurve = new QCPCurve(plot->xAxis, plot->yAxis); bezierPolygon = new MovableCurve(plot->xAxis, plot->yAxis); connect(bezierPolygon,SIGNAL(curveChanged(int,QPointF)),this,SLOT(updateControlPoints(int,QPointF))); } //===================================================================== CubicBezier &CubicBezier::operator=(CubicBezier cb) { // copy (or move) constructor was already used for creating cb, so we only have to swap member variables swap(cb); return *this; } //===================================================================== CubicBezier::CubicBezier(CubicBezier &&tmp) { for(int i=0; i<CUBIC_BEZIER_SIZE; ++i) controlPoints[i] = tmp[i]; plot = tmp.getPlot(); bezierCurve = tmp.getBezierCurve(); bezierPolygon = tmp.getBezierPolygon(); connect(bezierPolygon,SIGNAL(curveChanged(int,QPointF)),this,SLOT(updateControlPoints(int,QPointF))); tmp.clearCurves(); } //===================================================================== CubicBezier::~CubicBezier() { if(bezierCurve != nullptr) plot->removePlottable(bezierCurve); if(bezierPolygon != nullptr) plot->removePlottable(bezierPolygon); // memory is realesed in removePlottable() function } //===================================================================== QPointF CubicBezier::valueAt(float t) const { float u = 1.0 - t; float t2 = t * t; float u2 = u * u; float u3 = u2 * u; float t3 = t2 * t; return u3 * controlPoints[0] + (3.0 * u2 * t) * controlPoints[1] + (3.0 * u * t2) * controlPoints[2] + t3 * controlPoints[3]; } //===================================================================== void CubicBezier::clearCurves() { bezierCurve = nullptr; bezierPolygon = nullptr; } //===================================================================== void CubicBezier::translate(QPointF translationVector) { for(int i=0; i<CUBIC_BEZIER_SIZE; ++i) controlPoints[i] += translationVector; } //===================================================================== QVector<CubicBezier> CubicBezier::subdivide(float t) const { // rigid implementation of DeCasteljau algotithm QPointF p21 = controlPoints[0] + (controlPoints[1] - controlPoints[0]) * t; QPointF p22 = controlPoints[1] + (controlPoints[2] - controlPoints[1]) * t; QPointF p23 = controlPoints[2] + (controlPoints[3] - controlPoints[2]) * t; QPointF p31 = p21 + (p22 - p21) * t; QPointF p32 = p22 + (p23 - p22) * t; QPointF p4 = p31 + (p32 - p31) * t; QVector<CubicBezier> result(2); result[0] = CubicBezier(plot, {controlPoints[0], p21, p31, p4}); result[1] = CubicBezier(plot, {p4, p32, p23, controlPoints[3]}); return result; } //===================================================================== void CubicBezier::draw() const { QVector<double> x(101), y(101), t(101); for (int i=0; i<101; ++i) { float time = i/static_cast<float>(100.0); t[i] = time; auto point = valueAt(time); x[i] = point.x(); y[i] = point.y(); } bezierCurve->setData(t,x,y,true); QVector<double> x2(CUBIC_BEZIER_SIZE), y2(CUBIC_BEZIER_SIZE), t2(CUBIC_BEZIER_SIZE); for(int i=0; i<CUBIC_BEZIER_SIZE; ++i) { t2[i] = i; x2[i] = controlPoints[i].x(); y2[i] = controlPoints[i].y(); } bezierPolygon->setData(t2,x2,y2,true); bezierPolygon->setPen(QPen(Qt::red)); bezierPolygon->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, 5)); plot->replot(); } //===================================================================== void CubicBezier::updateControlPoints(int index, QPointF newValue) { controlPoints[index] = newValue; draw(); }
28.928934
108
0.576943
pdulewic
c6384197ea85f1031d58c965a8cf21977a20dc72
1,499
cpp
C++
hash/hash.cpp
kozok-dev/samples
2a33da9ba458a26bc0be373320323a63641e3582
[ "CC0-1.0" ]
null
null
null
hash/hash.cpp
kozok-dev/samples
2a33da9ba458a26bc0be373320323a63641e3582
[ "CC0-1.0" ]
null
null
null
hash/hash.cpp
kozok-dev/samples
2a33da9ba458a26bc0be373320323a63641e3582
[ "CC0-1.0" ]
null
null
null
#include "hash.h" void Hash::Str(const void *pstr, void *pdata, UINT len, const void *pkey, UINT key_len) { if (pkey == NULL) Init(); else initHMAC((BYTE *)pkey, key_len > 0 ? key_len : strlen((char *)pkey)); Update((BYTE *)pstr, len > 0 ? len : strlen((char *)pstr)); if (pkey == NULL) Final(); else finalHMAC(); getHash((BYTE *)pdata); } bool Hash::File(LPCSTR pfilename, void *pdata, const void *pkey, UINT key_len) { BYTE buf[4096]; UINT r; FILE *pfile; pfile = fopen(pfilename, "rb"); if (pfile == NULL) return false; m_stop = false; if (pkey == NULL) Init(); else initHMAC((BYTE *)pkey, key_len); for (;;) { r = fread(buf, 1, sizeof(buf), pfile); if (r == 0 || m_stop) break; Update(buf, r); } if (pkey == NULL) Final(); else finalHMAC(); getHash((BYTE *)pdata); return true; } void Hash::initHMAC(const BYTE *pkey, UINT len) { BYTE buf[128], i; if (len > getBlockSize()) { Init(); Update(pkey, len); Final(); getHash(buf); pkey = buf; len = getHashSize(); } for (i = 0; i < len; i++) { buf[i] = pkey[i] ^ 0x36; m_opad[i] = pkey[i] ^ 0x5c; } for (; i < getBlockSize(); i++) { buf[i] = 0x36; m_opad[i] = 0x5c; } Init(); Update(buf, getBlockSize()); } void Hash::finalHMAC() { BYTE buf[128]; Final(); getHash(buf); Init(); Update(m_opad, getBlockSize()); Update(buf, getHashSize()); Final(); } void Hash::Stop() { m_stop = true; }
18.280488
90
0.559039
kozok-dev
c639a907f4b9a96976bb873703332ed76932e128
25
cpp
C++
_KaramayEngine/karamay_engine_graphics_unit/karamay_engine_graphics_unit/source/graphics/variable/gl_variable.cpp
MorphingDev/karamay_engine
044aaf7af813b01dbc26185852865c8a0369efca
[ "MIT" ]
null
null
null
_KaramayEngine/karamay_engine_graphics_unit/karamay_engine_graphics_unit/source/graphics/variable/gl_variable.cpp
MorphingDev/karamay_engine
044aaf7af813b01dbc26185852865c8a0369efca
[ "MIT" ]
null
null
null
_KaramayEngine/karamay_engine_graphics_unit/karamay_engine_graphics_unit/source/graphics/variable/gl_variable.cpp
MorphingDev/karamay_engine
044aaf7af813b01dbc26185852865c8a0369efca
[ "MIT" ]
1
2022-01-29T08:34:51.000Z
2022-01-29T08:34:51.000Z
#include "gl_variable.h"
12.5
24
0.76
MorphingDev
c63a2b28c87818ae1402720a990319b4c7d06c53
2,381
cpp
C++
test/libp2p/peer/key_book/inmem_key_repository_test.cpp
Alexey-N-Chernyshov/cpp-libp2p
8b52253f9658560a4b1311b3ba327f02284a42a6
[ "Apache-2.0", "MIT" ]
135
2020-06-13T08:57:36.000Z
2022-03-27T05:26:11.000Z
test/libp2p/peer/key_book/inmem_key_repository_test.cpp
igor-egorov/cpp-libp2p
7c9d83bf0760a5f653d86ddbb00645414c61d4fc
[ "Apache-2.0", "MIT" ]
41
2020-06-12T15:45:05.000Z
2022-03-07T23:10:33.000Z
test/libp2p/peer/key_book/inmem_key_repository_test.cpp
igor-egorov/cpp-libp2p
7c9d83bf0760a5f653d86ddbb00645414c61d4fc
[ "Apache-2.0", "MIT" ]
43
2020-06-15T10:12:45.000Z
2022-03-21T03:04:50.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #include <exception> #include <gtest/gtest.h> #include <libp2p/crypto/key.hpp> #include <libp2p/peer/key_repository.hpp> #include <libp2p/peer/key_repository/inmem_key_repository.hpp> #include "testutil/outcome.hpp" using namespace libp2p::peer; using namespace libp2p::multi; using namespace libp2p::common; using namespace libp2p::crypto; struct InmemKeyRepositoryTest : ::testing::Test { static PeerId createPeerId(HashType type, Buffer b) { auto hash = Multihash::create(type, std::move(b)); if (!hash) { throw std::invalid_argument(hash.error().message()); } auto r1 = PeerId::fromHash(hash.value()); if (!r1) { throw std::invalid_argument(r1.error().message()); } return r1.value(); } PeerId p1_ = createPeerId(HashType::sha256, {1}); PeerId p2_ = createPeerId(HashType::sha256, {2}); std::unique_ptr<KeyRepository> db_ = std::make_unique<InmemKeyRepository>(); }; TEST_F(InmemKeyRepositoryTest, PubkeyStore) { EXPECT_OUTCOME_TRUE_1(db_->addPublicKey(p1_, {{Key::Type::Ed25519, {'a'}}})); EXPECT_OUTCOME_TRUE_1(db_->addPublicKey(p1_, {{Key::Type::Ed25519, {'b'}}})); // insert same pubkey. it should not be inserted EXPECT_OUTCOME_TRUE_1(db_->addPublicKey(p1_, {{Key::Type::Ed25519, {'b'}}})); // same pubkey but different type EXPECT_OUTCOME_TRUE_1(db_->addPublicKey(p1_, {{Key::Type::RSA, {'b'}}})); // put pubkey to different peer EXPECT_OUTCOME_TRUE_1(db_->addPublicKey(p2_, {{Key::Type::RSA, {'c'}}})); EXPECT_OUTCOME_TRUE(v, db_->getPublicKeys(p1_)); EXPECT_EQ(v->size(), 3); db_->clear(p1_); EXPECT_EQ(v->size(), 0); } TEST_F(InmemKeyRepositoryTest, KeyPairStore) { PublicKey pub = {{Key::Type::RSA, {'a'}}}; PrivateKey priv = {{Key::Type::RSA, {'b'}}}; KeyPair kp{pub, priv}; EXPECT_OUTCOME_TRUE_1(db_->addKeyPair({pub, priv})); EXPECT_OUTCOME_TRUE(v, db_->getKeyPairs()); EXPECT_EQ(v->size(), 1); EXPECT_EQ(*v, std::unordered_set<KeyPair>{kp}); } /** * @given 2 peers in storage * @when get peers * @then 2 peers returned */ TEST_F(InmemKeyRepositoryTest, GetPeers) { PublicKey z{}; KeyPair kp{}; EXPECT_OUTCOME_TRUE_1(db_->addPublicKey(p1_, z)); EXPECT_OUTCOME_TRUE_1(db_->addKeyPair(kp)); auto s = db_->getPeers(); EXPECT_EQ(s.size(), 1); }
28.011765
79
0.685006
Alexey-N-Chernyshov
c63c2969392e17bbec61c48820aee3f2b18bc67f
12,025
cpp
C++
co-op/UI/ProjectPropsDlg.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
67
2018-03-02T10:50:02.000Z
2022-03-23T18:20:29.000Z
co-op/UI/ProjectPropsDlg.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
null
null
null
co-op/UI/ProjectPropsDlg.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
9
2018-03-01T16:38:28.000Z
2021-03-02T16:17:09.000Z
//------------------------------------ // (c) Reliable Software, 2000 - 2008 //------------------------------------ #include "precompiled.h" #include "ProjectPropsDlg.h" #include "ProjectOptionsEx.h" #include "ProjectDb.h" #include "OutputSink.h" #include "AppInfo.h" #include "DistributorInfo.h" #include "BrowseForFolder.h" #include <Ctrl/Output.h> #include <Win/Dialog.h> #include <Com/Shell.h> #include <Sys/WinString.h> bool ProjectOptionsCtrl::OnInitDialog () throw (Win::Exception) { Win::Dow::Handle dlgWin (GetWindow ()); _autoSynch.Init (dlgWin, IDC_PROJ_OPTIONS_AUTO_SYNCH); _autoJoin.Init (dlgWin, IDC_PROJ_OPTIONS_AUTO_JOIN); _keepCheckedOut.Init (dlgWin, IDC_PROJ_OPTIONS_KEEP_CHECKED_OUT); _checkoutNotification.Init (dlgWin, IDC_START_CHECKOUT_NOTIFICATIONS); _autoInvite.Init (dlgWin, IDC_OPTIONS_AUTO_INVITE); _projectPath.Init (dlgWin, IDC_OPTIONS_PATH); _pathBrowse.Init (dlgWin, IDC_OPTIONS_BROWSE); InitializeControls (); return true; } bool ProjectOptionsCtrl::OnDlgControl (unsigned ctrlId, unsigned notifyCode) throw (Win::Exception) { if (ctrlId == IDC_OPTIONS_AUTO_INVITE && Win::SimpleControl::IsClicked (notifyCode)) { if (_autoInvite.IsChecked ()) { _projectPath.Enable (); _pathBrowse.Enable (); } else { _projectPath.Disable (); _pathBrowse.Disable (); } } else if (ctrlId == IDC_OPTIONS_BROWSE && Win::SimpleControl::IsClicked (notifyCode)) { std::string path = _projectPath.GetString (); if (BrowseForAnyFolder (path, GetWindow (), "Select folder (existing or not) where new projects will be created.", path.c_str ())) { _projectPath.SetString (path); } } return true; } void ProjectOptionsCtrl::OnSetActive (long & result) throw (Win::Exception) { result = 0; // Assume everything is OK InitializeControls (); } void ProjectOptionsCtrl::OnCancel (long & result) throw (Win::Exception) { _options.Clear (); _options.SetAutoInviteProjectPath (""); _options.SetAutoInvite (false); } void ProjectOptionsCtrl::OnApply (long & result) throw (Win::Exception) { result = 0; // Assume everything is OK _options.SetAutoSynch (_autoSynch.IsChecked ()); if (_options.IsProjectAdmin () && !_options.IsDistribution ()) _options.SetAutoJoin (_autoJoin.IsChecked ()); _options.SetKeepCheckedOut (_keepCheckedOut.IsChecked ()); _options.SetCheckoutNotification (_checkoutNotification.IsChecked ()); if (_options.IsProjectAdmin () && _options.IsAutoSynch () && !_options.IsAutoJoin ()) { Out::Answer userChoice = TheOutput.Prompt ( "You are the Admin for this project and you have selected to\n" "automatically execute all incoming synchronization changes,\n" "but not to automatically accept join requests.\n\n" "You'll have to occasionally check for join request and execute them manually\n\n" "Do you want to continue with your current settings (automatic join request\n" "processing not selected)?", Out::PromptStyle (Out::YesNo, Out::No)); if (userChoice == Out::No) result = 1; // Don't close dialog } _options.SetAutoInvite (_autoInvite.IsChecked ()); _options.SetAutoInviteProjectPath (_projectPath.GetString ()); if (!_options.ValidateAutoInvite (GetWindow ())) result = 1; // Don't close dialog } void ProjectOptionsCtrl::InitializeControls () { if (_options.IsAutoSynch ()) _autoSynch.Check (); else _autoSynch.UnCheck (); if (_options.IsProjectAdmin ()) { if (_options.IsDistribution ()) { _autoJoin.UnCheck (); _autoJoin.Disable (); } else { _autoJoin.Enable (); if (_options.IsAutoJoin ()) _autoJoin.Check (); else _autoJoin.UnCheck (); } } else { _autoJoin.UnCheck (); _autoJoin.Disable (); } if (_options.IsReceiver ()) { _keepCheckedOut.Disable (); _checkoutNotification.Disable (); } else { if (_options.IsKeepCheckedOut ()) _keepCheckedOut.Check (); else _keepCheckedOut.UnCheck (); if (_options.IsCheckoutNotification ()) _checkoutNotification.Check (); else _checkoutNotification.UnCheck (); } _projectPath.SetString (_options.GetAutoInviteProjectPath ()); if (_options.IsAutoInvite ()) { _autoInvite.Check (); } else { _autoInvite.UnCheck (); _projectPath.Disable (); _pathBrowse.Disable (); } } bool ProjectDistributorCtrl::OnInitDialog () throw (Win::Exception) { Win::Dow::Handle dlgWin (GetWindow ()); _distributor.Init (dlgWin, IDC_PROJ_OPTIONS_DISTRIBUTOR); _noBranching.Init (dlgWin, IDC_PROJ_OPTIONS_DISALLOW_BRANCHING); _frame.Init (dlgWin, IDC_DISTRIBUTOR_FRAME); _allBcc.Init (dlgWin, IDC_PROJ_OPTIONS_ALL_BCC_RECIPIENTS); _singleRecipient.Init (dlgWin, IDC_PROJ_OPTIONS_SINGLE_TO_RECIPIENT); _status.Init (dlgWin, IDC_DISTRIBUTOR_STATUS); _license.Init (dlgWin, IDC_DISTRIBUTOR_LICENSE); _buyLicense.Init (dlgWin, IDC_LICENSE_PURCHASE); if (_options.IsDistribution ()) { _status.Hide (); _distributor.Check (); if (_options.IsNoBranching ()) _noBranching.Check (); else _noBranching.UnCheck (); if (_options.UseBccRecipients ()) _allBcc.Check (); else _singleRecipient.Check (); if (!_options.MayBecomeDistributor ()) { // Distributor administrator cannot change his/her distributor status // because there are some other project members beside him/her _distributor.Disable (); _noBranching.Disable (); } } else if (_options.MayBecomeDistributor ()) { _status.Hide (); _distributor.Enable (); _noBranching.Disable (); _allBcc.Check (); _allBcc.Disable (); _singleRecipient.Disable (); } else { _distributor.Hide (); _noBranching.Hide (); _frame.Hide (); _allBcc.Hide (); _singleRecipient.Hide (); _status.SetText ("You cannot become a distributor in this project.\n" "You must be the only member of the project."); } if (_options.GetSeatTotal () != 0) { std::string license ("You have "); license += ToString (_options.GetSeatsAvailable ()); license += " distribution licenses left out of total "; license += ToString (_options.GetSeatTotal ()); license += " licenses assigned to "; license += _options.GetDistributorLicensee (); _license.SetText (license.c_str ()); } else { _license.SetText ("You may purchase a distribution license over the Internet."); } return true; } bool ProjectDistributorCtrl::OnDlgControl (unsigned ctrlId, unsigned notifyCode) throw (Win::Exception) { switch (ctrlId) { case IDC_LICENSE_PURCHASE: if (Win::SimpleControl::IsClicked (notifyCode)) { Win::Dow::Handle appWnd = TheAppInfo.GetWindow (); int errCode = ShellMan::Open (appWnd, DistributorPurchaseLink); if (errCode != -1) { std::string msg = ShellMan::HtmlOpenError (errCode, "license", DistributorPurchaseLink); TheOutput.Display (msg.c_str (), Out::Error, GetWindow ()); } else { PressButton (PropPage::Ok); } } return true; case IDC_PROJ_OPTIONS_DISTRIBUTOR: if (Win::SimpleControl::IsClicked (notifyCode)) { if (_distributor.IsChecked ()) { _options.SetDistribution (true); _noBranching.Enable (); _allBcc.Enable (); _singleRecipient.Enable (); _options.SetAutoJoin (false); } else { _options.SetDistribution (false); _noBranching.Disable (); _allBcc.Disable (); _singleRecipient.Disable (); } } return true; } return false; } void ProjectDistributorCtrl::OnCancel (long & result) throw (Win::Exception) { _options.Clear (); } void ProjectDistributorCtrl::OnApply (long & result) throw (Win::Exception) { result = 0; // Assume everything is OK if (_options.MayBecomeDistributor () || _options.IsDistribution ()) { _options.SetDistribution (_distributor.IsChecked ()); _options.SetNoBranching (_noBranching.IsChecked ()); _options.SetBccRecipients (_allBcc.IsChecked ()); } } bool ProjectEncryptionCtrl::OnInitDialog () throw (Win::Exception) { Win::Dow::Handle dlgWin (GetWindow ()); _isEncrypt.Init (dlgWin, IDC_PROJ_OPTIONS_ENCRYPT); _useCommonKey.Init (dlgWin, IDC_PROJ_OPTIONS_COMMON_PASS); _key.Init (dlgWin, IDC_PROJ_OPTIONS_ENCRYPT_PASS); _key2.Init (dlgWin, IDC_PROJ_OPTIONS_ENCRYPT_PASS2); _keyStatic.Init (dlgWin, IDC_PROJ_OPTIONS_STATIC); _key2Static.Init (dlgWin, IDC_PROJ_OPTIONS_STATIC2); InitializeControls (); return true; } bool ProjectEncryptionCtrl::OnDlgControl (unsigned ctrlId, unsigned notifyCode) throw (Win::Exception) { if (ctrlId == IDC_PROJ_OPTIONS_ENCRYPT) { if (_isEncrypt.IsChecked ()) EnableKeyControls (); else DisableKeyControls (); } else if (ctrlId == IDC_PROJ_OPTIONS_COMMON_PASS) { if (_useCommonKey.IsChecked ()) { _key.SetText (_options.GetEncryptionCommonKey ()); _key2.SetText (_options.GetEncryptionCommonKey ()); _key.Disable (); _key2.Disable (); } else { _key.Enable (); _key2.Enable (); _key.Clear (); _key2.Clear (); } } return true; } void ProjectEncryptionCtrl::OnKillActive (long & result) throw (Win::Exception) { result = 0; std::string key; std::string key2; if (_isEncrypt.IsChecked ()) { key = _key.GetString (); key2 = _key2.GetString (); if (key.empty ()) { TheOutput.Display ("Please specify the encryption key."); result = -1; return; } else if (key != key2) { TheOutput.Display ("Encryption keys do not match. Please re-enter the keys."); result = -1; return; } } std::string const originalKey = _options.GetEncryptionOriginalKey (); if (!originalKey.empty ()) { if (key.empty ()) { if (TheOutput.Prompt ("Are you sure you want to turn the encryption off?" "\nYou will not be able to receive encoded scripts.") != Out::Yes) { result = -1; return; } } else if (key != originalKey) { if (TheOutput.Prompt ("Are you sure you want to change the encryption key?" "\n(You will not be able to receive scripts encrypted" "\nwith the old key.)") != Out::Yes) { result = -1; return; } } } _options.SetEncryptionKey (key); } void ProjectEncryptionCtrl::OnCancel (long & result) throw (Win::Exception) { _options.Clear (); } void ProjectEncryptionCtrl::InitializeControls () { if (_options.GetEncryptionCommonKey ().empty ()) _useCommonKey.Disable (); std::string const key = _options.GetEncryptionKey (); if (key.empty ()) { _isEncrypt.UnCheck (); DisableKeyControls (); } else { _isEncrypt.Check (); EnableKeyControls (); _key.SetString (key); _key2.SetString (key); } } void ProjectEncryptionCtrl::DisableKeyControls () { _useCommonKey.Disable (); _keyStatic.Disable (); _key2Static.Disable (); _key.Disable (); _key2.Disable (); } void ProjectEncryptionCtrl::EnableKeyControls () { if (!_options.GetEncryptionCommonKey ().empty ()) _useCommonKey.Enable (); _keyStatic.Enable (); _key2Static.Enable (); _key.Enable (); _key2.Enable (); } ProjectOptionsHndlrSet::ProjectOptionsHndlrSet (Project::OptionsEx & options) : PropPage::HandlerSet (options.GetCaption ()), _options (options), _optionsPageHndlr (options), _distributorPageHndlr (options), _encryptionPageHndlr (options) { AddHandler (_optionsPageHndlr, "General"); AddHandler (_distributorPageHndlr, "Distributor"); // Notice: Encryption page is ready for use // AddHandler (_encryptionPageHndlr, "Encryption"); } // command line // -project_options autosynch:"on" or "off" autojoin:"on" or "off" keepcheckedout:"on" or "off" bool ProjectOptionsHndlrSet::GetDataFrom (NamedValues const & source) { std::string autoSyncValue; std::string autoJoinValue; autoSyncValue = source.GetValue ("autosynch"); std::transform (autoSyncValue.begin (), autoSyncValue.end (), autoSyncValue.begin (), tolower); autoJoinValue = source.GetValue ("autojoin"); std::transform (autoJoinValue.begin (), autoJoinValue.end (), autoJoinValue.begin (), tolower); _options.SetAutoSynch (autoSyncValue == "on"); if (_options.IsAutoSynch ()) _options.SetAutoJoin (autoJoinValue == "on"); return !autoSyncValue.empty () || !autoJoinValue.empty (); }
26.141304
103
0.701289
BartoszMilewski
c63dfdc64b825c51e66673f45c46cf593b5a5bb8
3,346
cxx
C++
Interaction/Widgets/Testing/Cxx/TestTextWidgetBackgroundInteractive.cxx
cclauss/VTK
f62a52cce9044159efb4adb7cc0cfd7ec0bc8b6d
[ "BSD-3-Clause" ]
1,755
2015-01-03T06:55:00.000Z
2022-03-29T05:23:26.000Z
Interaction/Widgets/Testing/Cxx/TestTextWidgetBackgroundInteractive.cxx
cclauss/VTK
f62a52cce9044159efb4adb7cc0cfd7ec0bc8b6d
[ "BSD-3-Clause" ]
29
2015-04-23T20:58:30.000Z
2022-03-02T16:16:42.000Z
Interaction/Widgets/Testing/Cxx/TestTextWidgetBackgroundInteractive.cxx
cclauss/VTK
f62a52cce9044159efb4adb7cc0cfd7ec0bc8b6d
[ "BSD-3-Clause" ]
1,044
2015-01-05T22:48:27.000Z
2022-03-31T02:38:26.000Z
/*========================================================================= Program: Visualization Toolkit Module: TestTextWidgetBackgroundInteractive.cxx =========================================================================*/ // // This example tests the vtkTextWidget. // First include the required header files for the VTK classes we are using. #include "vtkActor.h" #include "vtkBorderRepresentation.h" #include "vtkBorderWidget.h" #include "vtkCommand.h" #include "vtkInteractorEventRecorder.h" #include "vtkPolyDataMapper.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkSmartPointer.h" #include "vtkSphereSource.h" #include "vtkTextRepresentation.h" #include "vtkTextWidget.h" int TestTextWidgetBackgroundInteractive(int, char*[]) { // Create the RenderWindow, Renderer and both Actors // vtkNew<vtkRenderer> renderer; vtkNew<vtkRenderWindow> renderWindow; renderWindow->AddRenderer(renderer); vtkNew<vtkRenderWindowInteractor> interactor; interactor->SetRenderWindow(renderWindow); // Create a test pipeline // vtkNew<vtkSphereSource> ss; vtkNew<vtkPolyDataMapper> mapper; mapper->SetInputConnection(ss->GetOutputPort()); vtkNew<vtkActor> actor; actor->SetMapper(mapper); // Create the widget and its representation // Default Border Widget vtkNew<vtkBorderRepresentation> rep; rep->ProportionalResizeOn(); rep->SetShowBorderToOn(); rep->SetPolygonColor(0.0, 1.0, 0.0); rep->SetPolygonOpacity(0.2); vtkNew<vtkBorderWidget> widget; widget->SetInteractor(interactor); widget->SetRepresentation(rep); widget->SelectableOff(); // Top Left: Default Widget vtkNew<vtkTextRepresentation> tlRep; tlRep->ProportionalResizeOff(); tlRep->SetShowBorderToOn(); tlRep->SetPosition(0.05, 0.75); tlRep->SetPosition2(0.3, 0.2); tlRep->SetPolygonColor(1.0, 0.0, 0.0); tlRep->SetPolygonOpacity(0.5); tlRep->SetCornerRadiusStrength(0.5); vtkNew<vtkTextWidget> tlWidget; tlWidget->SetInteractor(interactor); tlWidget->SetRepresentation(tlRep); // Top Right: Always On vtkNew<vtkTextRepresentation> trRep; trRep->ProportionalResizeOff(); trRep->SetShowBorderToOn(); trRep->SetPosition(0.65, 0.75); trRep->SetPosition2(0.3, 0.2); trRep->SetPolygonColor(0.0, 1.0, 0.0); vtkNew<vtkTextWidget> trWidget; trWidget->SetInteractor(interactor); trWidget->SetRepresentation(trRep); // Bottom Right: Auto + Always Border vtkNew<vtkTextRepresentation> brRep; brRep->ProportionalResizeOff(); brRep->SetShowBorderToActive(); brRep->SetPosition(0.65, 0.05); brRep->SetPosition2(0.3, 0.2); brRep->SetPolygonColor(1.0, 0.0, 1.0); brRep->SetPolygonOpacity(0.3); brRep->EnforceNormalizedViewportBoundsOn(); brRep->SetMinimumNormalizedViewportSize(0.3, 0.2); vtkNew<vtkTextWidget> brWidget; brWidget->SetInteractor(interactor); brWidget->SetRepresentation(brRep); brWidget->SelectableOff(); // Add the actors to the renderer, set the background and size // renderer->AddActor(actor); renderer->SetBackground(0.1, 0.2, 0.4); renderWindow->SetSize(300, 300); // render the image // interactor->Initialize(); renderWindow->Render(); widget->On(); tlWidget->On(); trWidget->On(); brWidget->On(); interactor->Start(); return EXIT_SUCCESS; }
28.355932
76
0.70532
cclauss
c63e75eacc1730ae8c5b2a70530fa0053123c133
1,220
cpp
C++
Codeforces/Round-394-Div2/C.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
1
2018-01-30T13:21:30.000Z
2018-01-30T13:21:30.000Z
Codeforces/Round-394-Div2/C.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
null
null
null
Codeforces/Round-394-Div2/C.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
1
2018-08-29T13:26:50.000Z
2018-08-29T13:26:50.000Z
// Brute Force // 2 // 19-11-2020 #include <bits/stdc++.h> #define all(A) begin(A), end(A) #define rall(A) rbegin(A), rend(A) #define sz(A) int(A.size()) #define pb push_back #define mp make_pair using namespace std; typedef long long ll; typedef pair <int, int> pii; typedef pair <ll, ll> pll; typedef vector <int> vi; typedef vector <ll> vll; typedef vector <pii> vpii; typedef vector <pll> vpll; int main () { ios::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; const int INF = 1e7; vi a(n, INF); vi b(n, INF); vi c(n, INF); for (int i = 0; i < n; i++) { string s; cin >> s; for (int j = 0; j < m; j++) { if (isdigit(s[j])) { a[i] = min(a[i], min(j, m - j)); } if ('a' <= s[j] and s[j] <= 'z') { b[i] = min(b[i], min(j, m - j)); } if (s[j] == '#' or s[j] == '*' or s[j] == '&') { c[i] = min(c[i], min(j, m - j)); } } } int ans = INF; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { if (i == j or i == k or j == k) continue; ans = min(ans, a[i] + b[j] + c[k]); } } } cout << ans << '\n'; return (0); }
21.034483
54
0.456557
TISparta
c64436019d510a9593a970c4a5bf38071dc323db
10,177
cc
C++
felicia/drivers/camera/camera_frame.cc
chokobole/felicia
3b5eeb5f93c59c5364d3932bc407e054977aa1ec
[ "BSD-3-Clause" ]
17
2018-10-28T13:58:01.000Z
2022-03-22T07:54:12.000Z
felicia/drivers/camera/camera_frame.cc
chokobole/felicia
3b5eeb5f93c59c5364d3932bc407e054977aa1ec
[ "BSD-3-Clause" ]
2
2018-11-09T04:15:58.000Z
2018-11-09T06:42:57.000Z
felicia/drivers/camera/camera_frame.cc
chokobole/felicia
3b5eeb5f93c59c5364d3932bc407e054977aa1ec
[ "BSD-3-Clause" ]
5
2019-10-31T06:50:05.000Z
2022-03-22T07:54:30.000Z
// Copyright (c) 2019 The Felicia 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 "felicia/drivers/camera/camera_frame.h" #include "libyuv.h" #include "third_party/chromium/base/logging.h" #include "felicia/core/lib/unit/time_util.h" #include "felicia/drivers/camera/camera_frame_util.h" namespace felicia { namespace drivers { CameraFrame::CameraFrame() = default; CameraFrame::CameraFrame(const Data& data, const CameraFormat& camera_format, base::TimeDelta timestamp) : data_(data), camera_format_(camera_format), timestamp_(timestamp) {} CameraFrame::CameraFrame(Data&& data, const CameraFormat& camera_format, base::TimeDelta timestamp) noexcept : data_(std::move(data)), camera_format_(camera_format), timestamp_(timestamp) {} CameraFrame::CameraFrame(const Image& image, float frame_rate, base::TimeDelta timestamp) : CameraFrame(image.data(), CameraFormat{image.size(), image.pixel_format(), frame_rate}, timestamp) {} CameraFrame::CameraFrame(Image&& image, float frame_rate, base::TimeDelta timestamp) noexcept : CameraFrame(std::move(image.data()), CameraFormat{image.size(), image.pixel_format(), frame_rate}, timestamp) {} CameraFrame::CameraFrame(const CameraFrame& other) : data_(other.data_), camera_format_(other.camera_format_), timestamp_(other.timestamp_) {} CameraFrame::CameraFrame(CameraFrame&& other) noexcept : data_(std::move(other.data_)), camera_format_(other.camera_format_), timestamp_(other.timestamp_) {} CameraFrame& CameraFrame::operator=(const CameraFrame& other) = default; CameraFrame& CameraFrame::operator=(CameraFrame&& other) = default; CameraFrame::~CameraFrame() = default; const Data& CameraFrame::data() const { return data_; } Data& CameraFrame::data() { return data_; } size_t CameraFrame::length() const { return data_.size(); } const CameraFormat& CameraFrame::camera_format() const { return camera_format_; } int CameraFrame::width() const { return camera_format_.width(); } int CameraFrame::height() const { return camera_format_.height(); } float CameraFrame::frame_rate() const { return camera_format_.frame_rate(); } PixelFormat CameraFrame::pixel_format() const { return camera_format_.pixel_format(); } void CameraFrame::set_timestamp(base::TimeDelta timestamp) { timestamp_ = timestamp; } base::TimeDelta CameraFrame::timestamp() const { return timestamp_; } CameraFrameMessage CameraFrame::ToCameraFrameMessage(bool copy) { CameraFrameMessage message; if (copy) { message.set_data(data_.data()); } else { message.set_data(std::move(data_).data()); } *message.mutable_camera_format() = camera_format_.ToCameraFormatMessage(); message.set_timestamp(timestamp_.InMicroseconds()); return message; } Status CameraFrame::FromCameraFrameMessage(const CameraFrameMessage& message) { CameraFormat camera_format; Status s = camera_format.FromCameraFormatMessage(message.camera_format()); if (!s.ok()) return s; *this = CameraFrame{Data{message.data()}, camera_format, base::TimeDelta::FromMicroseconds(message.timestamp())}; return Status::OK(); } Status CameraFrame::FromCameraFrameMessage(CameraFrameMessage&& message) { CameraFormat camera_format; Status s = camera_format.FromCameraFormatMessage(message.camera_format()); if (!s.ok()) return s; std::unique_ptr<std::string> data(message.release_data()); *this = CameraFrame{Data{std::move(*data)}, camera_format, base::TimeDelta::FromMicroseconds(message.timestamp())}; return Status::OK(); } #if defined(HAS_OPENCV) bool CameraFrame::ToCvMat(cv::Mat* out, bool copy) { int type = camera_format_.ToCvType(); if (type == -1) return false; cv::Mat mat(camera_format_.height(), camera_format_.width(), type, data_.cast<void*>()); if (copy) { *out = mat.clone(); } else { *out = mat; } return true; } Status CameraFrame::FromCvMat(cv::Mat mat, const CameraFormat& camera_format, base::TimeDelta timestamp) { size_t length = mat.total() * mat.elemSize(); *this = CameraFrame{Data{mat.data, length}, camera_format, timestamp}; return Status::OK(); } #endif // defined(HAS_OPENCV) #if defined(HAS_ROS) bool CameraFrame::ToRosImage(sensor_msgs::Image* image) const { std::string ros_encoding = camera_format_.ToRosImageEncoding(); if (ros_encoding.length() == 0) return false; image->encoding = ros_encoding; image->width = camera_format_.width(); image->height = camera_format_.height(); image->step = length() / height(); image->data.resize(length()); memcpy(&(image->data[0]), data_.cast<const char*>(), length()); image->header.stamp = ToRosTime(timestamp_); return true; } Status CameraFrame::FromRosImage(const sensor_msgs::Image& image, const CameraFormat& camera_format) { size_t length = image.step * image.height; *this = CameraFrame{Data{image.data.data(), length}, camera_format, FromRosTime(image.header.stamp)}; return Status::OK(); } #endif // defined(HAS_ROS) namespace { base::Optional<CameraFrame> ConvertToBGRA(const uint8_t* data, size_t data_length, const CameraFormat& camera_format, base::TimeDelta timestamp) { PixelFormat pixel_format = camera_format.pixel_format(); libyuv::FourCC src_format; if (pixel_format == PIXEL_FORMAT_BGRA) { LOG(ERROR) << "Its format is already PIXEL_FORMAT_BGRA."; } src_format = camera_format.ToLibyuvPixelFormat(); if (src_format == libyuv::FOURCC_ANY) return base::nullopt; const int width = camera_format.width(); const int height = camera_format.height(); CameraFormat bgra_camera_format(width, height, PIXEL_FORMAT_BGRA, camera_format.frame_rate()); size_t length = bgra_camera_format.AllocationSize(); Data tmp_bgra; tmp_bgra.resize(length); uint8_t* tmp_bgra_ptr = tmp_bgra.cast<uint8_t*>(); if (libyuv::ConvertToARGB(data, data_length, tmp_bgra_ptr, width * 4, 0 /* crop_x_pos */, 0 /* crop_y_pos */, width, height, width, height, libyuv::RotationMode::kRotate0, src_format) != 0) { return base::nullopt; } return CameraFrame(std::move(tmp_bgra), bgra_camera_format, timestamp); } } // namespace base::Optional<CameraFrame> ConvertToRequestedPixelFormat( const uint8_t* data, size_t data_length, const CameraFormat& camera_format, PixelFormat requested_pixel_format, base::TimeDelta timestamp) { if (requested_pixel_format == PIXEL_FORMAT_MJPEG) { return base::nullopt; } else if (requested_pixel_format == PIXEL_FORMAT_BGRA) { return ConvertToBGRA(data, data_length, camera_format, timestamp); } else { auto bgra_camera_frame_opt = ConvertToBGRA(data, data_length, camera_format, timestamp); if (!bgra_camera_frame_opt.has_value()) return base::nullopt; CameraFrame bgra_camera_frame = std::move(bgra_camera_frame_opt.value()); const uint8_t* bgra_data = bgra_camera_frame.data().cast<const uint8_t*>(); int width = bgra_camera_frame.width(); int height = bgra_camera_frame.height(); CameraFormat camera_format = bgra_camera_frame.camera_format(); camera_format.set_pixel_format(requested_pixel_format); size_t length = camera_format.AllocationSize(); Data tmp_camera_frame; tmp_camera_frame.resize(length); uint8_t* tmp_camera_frame_ptr = tmp_camera_frame.cast<uint8_t*>(); int ret = -1; switch (requested_pixel_format) { case PIXEL_FORMAT_I420: ret = libyuv::ARGBToI420( bgra_data, width * 4, tmp_camera_frame_ptr, width, tmp_camera_frame_ptr + (width * height), width / 2, tmp_camera_frame_ptr + (width * height) * 5 / 4, width / 2, width, height); break; case PIXEL_FORMAT_YV12: // No conversion in libyuv api. break; case PIXEL_FORMAT_NV12: ret = libyuv::ARGBToNV12(bgra_data, width * 4, tmp_camera_frame_ptr, width, tmp_camera_frame_ptr + (width * height), width, width, height); break; case PIXEL_FORMAT_NV21: ret = libyuv::ARGBToNV21(bgra_data, width * 4, tmp_camera_frame_ptr, width, tmp_camera_frame_ptr + (width * height), width, width, height); break; case PIXEL_FORMAT_UYVY: ret = libyuv::ARGBToUYVY(bgra_data, width * 4, tmp_camera_frame_ptr, width * 2, width, height); break; case PIXEL_FORMAT_YUY2: ret = libyuv::ARGBToYUY2(bgra_data, width * 4, tmp_camera_frame_ptr, width * 2, width, height); break; case PIXEL_FORMAT_BGR: ret = libyuv::ARGBToRGB24(bgra_data, width * 4, tmp_camera_frame_ptr, width * 3, width, height); break; case PIXEL_FORMAT_RGBA: ret = libyuv::ARGBToABGR(bgra_data, width * 4, tmp_camera_frame_ptr, width * 4, width, height); break; case PIXEL_FORMAT_RGB: ret = libyuv::ARGBToRAW(bgra_data, width * 4, tmp_camera_frame_ptr, width * 3, width, height); break; case PIXEL_FORMAT_ARGB: ret = libyuv::ARGBToBGRA(bgra_data, width * 4, tmp_camera_frame_ptr, width * 4, width, height); break; default: break; } if (ret != 0) return base::nullopt; return CameraFrame(std::move(tmp_camera_frame), camera_format, timestamp); } } } // namespace drivers } // namespace felicia
37.278388
80
0.657168
chokobole
c645e3f9178c4968c207a235b93709d9a8e7bed8
2,944
cpp
C++
DPC++Compiler/simple-vector-inc/src/simple-vector-incr.cpp
jcarlosrm/BaseKit-code-samples
aef313f3846e6095e91ec27609fdd947056dc952
[ "MIT" ]
1
2020-02-21T06:58:51.000Z
2020-02-21T06:58:51.000Z
DPC++Compiler/simple-vector-inc/src/simple-vector-incr.cpp
jcarlosrm/BaseKit-code-samples
aef313f3846e6095e91ec27609fdd947056dc952
[ "MIT" ]
null
null
null
DPC++Compiler/simple-vector-inc/src/simple-vector-incr.cpp
jcarlosrm/BaseKit-code-samples
aef313f3846e6095e91ec27609fdd947056dc952
[ "MIT" ]
null
null
null
//============================================================== // Copyright © 2019 Intel Corporation // // SPDX-License-Identifier: MIT // ============================================================= #include <CL/sycl.hpp> #include <iostream> using namespace cl::sycl; static const size_t N = 2; // ############################################################ // work void work(queue &q) { std::cout << "Device : " << q.get_device().get_info<info::device::name>() << std::endl; // ### Step 1 - Inspect // The code presents one input buffer (vector1) for which Sycl buffer memory // is allocated. The associated with vector1_accessor set to read/write gets // the contents of the buffer. int vector1[N] = {10, 10}; std::cout << "Input : " << vector1[0] << ", " << vector1[1] << std::endl; // ### Step 2 - Add another input vector - vector2 // Uncomment the following line to add input vector2 // int vector2[N] = {20,20}; // ### Step 3 - Print out for vector2 // Uncomment the following line // std::cout << "Input : " << vector2[0] << ", " << vector2[1] << std::endl; buffer<int, 1> vector1_buffer(vector1, range<1>(N)); // ### Step 4 - Add another Sycl buffer - vector2_buffer // Uncomment the following line // buffer<int, 1> vector2_buffer(vector2, range<1>(N)); q.submit([&](handler &h) { auto vector1_accessor = vector1_buffer.get_access<access::mode::read_write>(h); // Step 5 - add an accessor for vector2_buffer // Look in the source code for the comment // auto vector2_accessor = vector2_buffer.template get_access < // access::mode::read > (my_handler); h.parallel_for<class test>(range<1>(N), [=](id<1> index) { // ### Step 6 - Replace the existing vector1_accessor to accumulate // vector2_accessor Comment the line: vector1_accessor[index] += 1; vector1_accessor[index] += 1; // Uncomment the following line // vector1_accessor[index] += vector2_accessor[index]; }); }); q.wait_and_throw(); vector1_buffer.get_access<access::mode::read>(); std::cout << "Output : " << vector1[0] << ", " << vector1[1] << std::endl; } // ############################################################ // entry point for the program int main() { auto exception_handler = [](cl::sycl::exception_list exceptionList) { for (std::exception_ptr const &e : exceptionList) { try { std::rethrow_exception(e); } catch (cl::sycl::exception const &e) { std::cout << "ASYNCHRONOUS SYCL exception:\n" << e.what() << std::endl; std::terminate(); // exit the process immediately. } } }; try { queue q(default_selector{}, exception_handler); work(q); } catch (exception e) { std::cerr << "Exception: " << e.what() << std::endl; std::terminate(); } catch (...) { std::cerr << "Unknown exception" << std::endl; std::terminate(); } }
34.635294
79
0.56284
jcarlosrm
c6515a5a74e42f4587d05da3d5dab3833a584e14
8,397
cpp
C++
server/Enclave/enclave_csk.cpp
ndokmai/sgx-genome-variants-search
dd83fb53d0a82594b9ab2c253a246a80095ca12b
[ "MIT" ]
17
2019-01-07T14:32:31.000Z
2022-03-17T00:36:05.000Z
server/Enclave/enclave_csk.cpp
ndokmai/sgx-genome-variants-search
dd83fb53d0a82594b9ab2c253a246a80095ca12b
[ "MIT" ]
2
2020-04-20T19:05:30.000Z
2021-11-23T05:58:02.000Z
server/Enclave/enclave_csk.cpp
ndokmai/sgx-genome-variants-search
dd83fb53d0a82594b9ab2c253a246a80095ca12b
[ "MIT" ]
3
2019-05-30T20:33:29.000Z
2020-07-29T19:25:17.000Z
#include <stdlib.h> #include <string.h> #include <sgx_trts.h> #include "enclave_csk.h" #include "util.h" struct csk* m_csk = NULL; static inline uint32_t calc_hash(uint64_t x, uint64_t a, uint64_t b) { uint64_t result = a * x + b; result = (result & 0x7FFFFFFF) + (result >> 31); if(result >= 0x7FFFFFFF) { return (uint32_t) (result - 0x7FFFFFFF); } return (uint32_t) result; } void csk_init_param(uint32_t width, uint32_t depth) { m_csk = (csk*) malloc(sizeof(csk)); m_csk->width = width; m_csk->depth = depth; m_csk->width_minus_one = width - 1; m_csk->seeds = NULL; m_csk->s_thres = 200; } void csk_init_seeds() { uint32_t d = m_csk->depth; m_csk->seeds = (uint64_t*) malloc(d * sizeof(uint64_t) << 2); for(size_t i = 0; i < d << 1; i++) { m_csk->seeds[(i << 1)] = my_sgx_rand(); while(m_csk->seeds[(i << 1)] == 0) { m_csk->seeds[(i << 1)] = my_sgx_rand(); } m_csk->seeds[(i << 1) + 1] = my_sgx_rand(); } } void csk_init(uint32_t width, uint32_t depth) { csk_init_param(width, depth); m_csk->sketch = (int16_t**) malloc(depth * sizeof(int16_t*)); m_csk->sketchf = NULL; for(size_t i = 0; i < depth; i++) { m_csk->sketch[i] = (int16_t*) malloc(width * sizeof(int16_t)); memset(m_csk->sketch[i], 0, width * sizeof(int16_t)); } csk_init_seeds(); } void csk_init_f(uint32_t width, uint32_t depth) { csk_init_param(width, depth); m_csk->sketch = NULL; m_csk->sketchf = (float**) malloc(depth * sizeof(float*)); for(size_t i = 0; i < depth; i++) { m_csk->sketchf[i] = (float*) malloc(width * sizeof(float)); memset(m_csk->sketchf[i], 0, width * sizeof(float)); } csk_init_seeds(); } void csk_free() { if(m_csk->seeds != NULL) { free(m_csk->seeds); } if(m_csk->sketch != NULL) { for(size_t i = 0; i < m_csk->depth; i++) { free(m_csk->sketch[i]); } free(m_csk->sketch); } if(m_csk->sketchf != NULL) { for(size_t i = 0; i < m_csk->depth; i++) { free(m_csk->sketchf[i]); } free(m_csk->sketchf); } free(m_csk); } void csk_setsth(int new_threshold) { m_csk->s_thres = new_threshold; } void csk_update_var(uint64_t item, int16_t count) { uint32_t hash; uint32_t pos; int16_t count_; for(size_t i = 0; i < m_csk->depth; i++) { hash = calc_hash(item, m_csk->seeds[i << 1], m_csk->seeds[(i << 1) + 1]); // hash = cal_hash(item, m_csk->seeds[i << 1], m_csk->seeds[(i << 1) + 1]); pos = hash & m_csk->width_minus_one; uint32_t temp = (i + m_csk->depth) << 1; hash = calc_hash(item, m_csk->seeds[temp], m_csk->seeds[temp + 1]); // hash = calc_hash(item, m_csk->seeds[(i + m_csk->depth) << 1], m_csk->seeds[((i + m_csk->depth) << 1) + 1]); // hash = cal_hash(item, m_csk->seeds[(i + m_csk->depth) << 1], m_csk->seeds[((i + m_csk->depth) << 1) + 1]); count_ = (((hash & 0x1) == 0) ? -1 : 1) * count; if(m_csk->sketch[i][pos] >= HASH_MAX_16 && count_ > 0) { continue; } if(m_csk->sketch[i][pos] <= HASH_MIN_16 && count_ < 0) { continue; } m_csk->sketch[i][pos] = m_csk->sketch[i][pos] + count_; } } void csk_update_var_f(uint64_t item, float count) { uint32_t hash; uint32_t pos; for(size_t i = 0; i < m_csk->depth; i++) { hash = cal_hash(item, m_csk->seeds[i << 1], m_csk->seeds[(i << 1) + 1]); pos = hash & m_csk->width_minus_one; hash = cal_hash(item, m_csk->seeds[(i + m_csk->depth) << 1], m_csk->seeds[((i + m_csk->depth) << 1) + 1]); if((hash & 0x1) == 0) { m_csk->sketchf[i][pos] = m_csk->sketchf[i][pos] - count; } else { m_csk->sketchf[i][pos] = m_csk->sketchf[i][pos] + count; } } } /***** Test function *****/ void csk_update_var_row(uint64_t item, int16_t count, size_t row) { uint32_t hash; hash = cal_hash(item, m_csk->seeds[row << 1], m_csk->seeds[(row << 1) + 1]); uint32_t pos = hash & m_csk->width_minus_one; hash = cal_hash(item, m_csk->seeds[(row + m_csk->depth) << 1], m_csk->seeds[((row + m_csk->depth) << 1) + 1]); int16_t count_ = (((hash & 0x1) == 0) ? -1 : 1) * count; if(m_csk->sketch[row][pos] >= HASH_MAX_16 && count_ > 0) { return; } if(m_csk->sketch[row][pos] <= HASH_MIN_16 && count_ < 0) { return; } m_csk->sketch[row][pos] = m_csk->sketch[row][pos] + count_; } void csk_update_var_row_f(uint64_t item, float count, size_t row) { uint32_t hash; hash = cal_hash(item, m_csk->seeds[row << 1], m_csk->seeds[(row << 1) + 1]); uint32_t pos = hash & m_csk->width_minus_one; hash = cal_hash(item, m_csk->seeds[(row + m_csk->depth) << 1], m_csk->seeds[((row + m_csk->depth) << 1) + 1]); if((hash & 0x1) == 0) { m_csk->sketchf[row][pos] = m_csk->sketchf[row][pos] - count; } else { m_csk->sketchf[row][pos] = m_csk->sketchf[row][pos] + count; } } /***** END: Test function *****/ int16_t csk_query_median_odd(uint64_t item) { int16_t* values; int16_t median; uint32_t hash; uint32_t pos; int32_t sign; values = (int16_t*) malloc(m_csk->depth * sizeof(int16_t)); for(size_t i = 0; i < m_csk->depth; i++) { hash = cal_hash(item, m_csk->seeds[i << 1], m_csk->seeds[(i << 1) + 1]); pos = hash & m_csk->width_minus_one; hash = cal_hash(item, m_csk->seeds[(i + m_csk->depth) << 1], m_csk->seeds[((i + m_csk->depth) << 1) + 1]); sign = ((hash & 0x1) == 0) ? -1 : 1; values[i] = m_csk->sketch[i][pos] * sign; } // Sort values qsort(values, m_csk->depth, sizeof(int16_t), cmpfunc_int16); // Get median of values median = values[m_csk->depth / 2]; // Free memory free(values); return median; } int16_t csk_query_median_even(uint64_t item) { int16_t* values; int16_t median; uint32_t hash; uint32_t pos; int32_t sign; values = (int16_t*) malloc(m_csk->depth * sizeof(int16_t)); for(size_t i = 0; i < m_csk->depth; i++) { hash = cal_hash(item, m_csk->seeds[i << 1], m_csk->seeds[(i << 1) + 1]); pos = hash & m_csk->width_minus_one; hash = cal_hash(item, m_csk->seeds[(i + m_csk->depth) << 1], m_csk->seeds[((i + m_csk->depth) << 1) + 1]); sign = ((hash & 0x1) == 0) ? -1 : 1; values[i] = m_csk->sketch[i][pos] * sign; } // Sort values qsort(values, m_csk->depth, sizeof(int16_t), cmpfunc_int16); // Get median of values if(values[m_csk->depth / 2] < -(m_csk->s_thres)) { median = values[m_csk->depth / 2 - 1]; } else if(values[m_csk->depth / 2 - 1] > m_csk->s_thres) { median = values[m_csk->depth / 2]; } else { median = (values[m_csk->depth / 2 - 1] + values[m_csk->depth / 2]) / 2; } // Free memory free(values); return median; } float csk_query_median_odd_f(uint64_t item) { float* values; float median; uint32_t hash; uint32_t pos; //int sign; values = (float*) malloc(m_csk->depth * sizeof(float)); for(size_t i = 0; i < m_csk->depth; i++) { hash = cal_hash(item, m_csk->seeds[i << 1], m_csk->seeds[(i << 1) + 1]); pos = hash & m_csk->width_minus_one; hash = cal_hash(item, m_csk->seeds[(i + m_csk->depth) << 1], m_csk->seeds[((i + m_csk->depth) << 1) + 1]); //sign = ((hash & 0x1) == 0) ? -1 : 1; if((hash & 0x1) == 0) { values[i] = -m_csk->sketchf[i][pos]; } else { values[i] = m_csk->sketchf[i][pos]; } //values[i] = m_csk->sketchf[i][pos] * sign; } // Sort values qsort(values, m_csk->depth, sizeof(float), cmpfunc_float); // Get median of values median = values[m_csk->depth / 2]; // Free memory free(values); return median; } float csk_query_median_even_f(uint64_t item) { float* values; float median; uint32_t hash; uint32_t pos; //int sign; values = (float*) malloc(m_csk->depth * sizeof(float)); for(size_t i = 0; i < m_csk->depth; i++) { hash = cal_hash(item, m_csk->seeds[i << 1], m_csk->seeds[(i << 1) + 1]); pos = hash & m_csk->width_minus_one; hash = cal_hash(item, m_csk->seeds[(i + m_csk->depth) << 1], m_csk->seeds[((i + m_csk->depth) << 1) + 1]); //sign = ((hash & 0x1) == 0) ? -1 : 1; //values[i] = m_csk->sketch32[i][pos] * sign; if((hash & 0x1) == 0) { values[i] = -m_csk->sketchf[i][pos]; } else { values[i] = m_csk->sketchf[i][pos]; } } // Sort values qsort(values, m_csk->depth, sizeof(float), cmpfunc_float); // Get median of values if(values[m_csk->depth / 2] + m_csk->s_thres < 0.0) { median = values[m_csk->depth / 2 - 1]; } else if(values[m_csk->depth / 2 - 1] - m_csk->s_thres > 0.0) { median = values[m_csk->depth / 2]; } else { median = (values[m_csk->depth / 2 - 1] + values[m_csk->depth / 2]) / 2; } // Free memory free(values); return median; }
22.942623
111
0.605097
ndokmai
c65445b0564c02430e6e98c76662a90bc47cb8c0
654
hpp
C++
framework/include/GeometryNode.hpp
GottaGoGitHub/CGLab_Almert119915_Portwich119649
027babb2018ee1ae1eb03d37ceb5777db708941c
[ "MIT" ]
null
null
null
framework/include/GeometryNode.hpp
GottaGoGitHub/CGLab_Almert119915_Portwich119649
027babb2018ee1ae1eb03d37ceb5777db708941c
[ "MIT" ]
null
null
null
framework/include/GeometryNode.hpp
GottaGoGitHub/CGLab_Almert119915_Portwich119649
027babb2018ee1ae1eb03d37ceb5777db708941c
[ "MIT" ]
null
null
null
#ifndef OPENGL_FRAMEWORK_GEOMETRYNODE_H #define OPENGL_FRAMEWORK_GEOMETRYNODE_H # include "Node.hpp" #include "model.hpp" #include "structs.hpp" class GeometryNode : public Node { public: // constructor explicit GeometryNode(std::string name); GeometryNode(const std::shared_ptr<Node> &parent, std::string name); GeometryNode(const std::shared_ptr<Node> &parent, std::string name, model geometry); // destructor ~GeometryNode(); // Getter und Setter model getGeometry() const; void setGeometry(model const &geometry); private: // Member model geometry_; }; #endif //OPENGL_FRAMEWORK_GEOMETRYNODE_H
19.235294
88
0.718654
GottaGoGitHub
c656b522b117929a0f5323359307667d0728e617
2,857
cpp
C++
Super Synthesis Engine/Source/Graphics/Texture2D.cpp
nstearns96/Super-Synthesis-Engine
64824c50557e64decc9710a5b2aa63cd93712122
[ "MIT" ]
null
null
null
Super Synthesis Engine/Source/Graphics/Texture2D.cpp
nstearns96/Super-Synthesis-Engine
64824c50557e64decc9710a5b2aa63cd93712122
[ "MIT" ]
null
null
null
Super Synthesis Engine/Source/Graphics/Texture2D.cpp
nstearns96/Super-Synthesis-Engine
64824c50557e64decc9710a5b2aa63cd93712122
[ "MIT" ]
null
null
null
#include "Graphics/Texture2D.h" #include "Logging/Logger.h" #include "Resources/Assets/TextureAssetUtils.h" #include "Vulkan/Devices/VulkanDeviceManager.h" #include "Vulkan/Memory/VulkanBuffer.h" namespace SSE { extern Logger gLogger; namespace Graphics { bool Texture2D::create(Bitmap& bitmap, VkImageTiling _tiling) { bool result = false; if (bitmap.getFormat() != VK_FORMAT_B8G8R8A8_UINT) { BitmapFormatTransitionParams params = {}; params.newFormat = VK_FORMAT_B8G8R8A8_UINT; params.channelParams[CHANNEL_GREEN].destinationChannel = CHANNEL_GREEN; params.channelParams[CHANNEL_BLUE].destinationChannel = CHANNEL_BLUE; params.channelParams[CHANNEL_ALPHA].destinationChannel = CHANNEL_ALPHA; params.channelParams[CHANNEL_ALPHA].constant = UINT_MAX; if (!bitmap.transitionFormat(params)) { GLOG_CRITICAL("Could not create texture. Failed to transition input bitmap."); return false; } } if (image.create(bitmap.getData(), bitmap.getDimensions(), VK_FORMAT_B8G8R8A8_SRGB, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT)) { if (image.transitionLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) && imageView.create(image.getImage(), VK_FORMAT_B8G8R8A8_SRGB, VK_IMAGE_ASPECT_COLOR_BIT)) { VkSamplerCreateInfo samplerInfo{}; samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; samplerInfo.magFilter = VK_FILTER_LINEAR; samplerInfo.minFilter = VK_FILTER_LINEAR; samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.anisotropyEnable = VK_TRUE; samplerInfo.maxAnisotropy = 16.0f; samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK; samplerInfo.unnormalizedCoordinates = VK_FALSE; samplerInfo.compareEnable = VK_FALSE; samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; samplerInfo.mipLodBias = 0.0f; samplerInfo.minLod = 0.0f; samplerInfo.maxLod = 0.0f; if (vkCreateSampler(LOGICAL_DEVICE_DEVICE, &samplerInfo, nullptr, &sampler) == VK_SUCCESS) { result = true; tiling = _tiling; } else { GLOG_CRITICAL("Failed to create sampler."); imageView.destroy(); image.destroy(); } } else { image.destroy(); } } return result; } void Texture2D::destroy() { image.destroy(); vkDestroyImageView(LOGICAL_DEVICE_DEVICE, imageView.getImageView(), nullptr); vkDestroySampler(LOGICAL_DEVICE_DEVICE, sampler, nullptr); } Vulkan::VulkanImageView Texture2D::getImageView() const { return imageView; } VkSampler Texture2D::getSampler() const { return sampler; } } }
29.760417
149
0.732587
nstearns96
c6588f3d9d41f0506b7ab80b6ad5cad2fff9c7f6
1,493
cpp
C++
owGameM2/M2_Part_Material.cpp
adan830/OpenWow
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
[ "Apache-2.0" ]
null
null
null
owGameM2/M2_Part_Material.cpp
adan830/OpenWow
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
[ "Apache-2.0" ]
null
null
null
owGameM2/M2_Part_Material.cpp
adan830/OpenWow
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
[ "Apache-2.0" ]
1
2020-05-11T13:32:49.000Z
2020-05-11T13:32:49.000Z
#include "stdafx.h" // General #include "M2_Part_Material.h" // M2Blend converter struct { SM2_Material::BlendModes M2Blend; uint8 EGxBLend; } M2Blend_To_EGxBlend[SM2_Material::COUNT] = { { SM2_Material::M2BLEND_OPAQUE, 0 }, { SM2_Material::M2BLEND_ALPHA_KEY, 1 }, { SM2_Material::M2BLEND_ALPHA, 2 }, { SM2_Material::M2BLEND_NO_ALPHA_ADD, 10 }, { SM2_Material::M2BLEND_ADD, 3 }, { SM2_Material::M2BLEND_MOD, 4 }, { SM2_Material::M2BLEND_MOD2X, 5 } }; CM2_Part_Material::CM2_Part_Material(const SM2_Material& _proto) { m_IsLightingDisable = _proto.flags.UNLIT; m_IsFogDisable = _proto.flags.UNFOGGED; m_IsTwoSided = _proto.flags.TWOSIDED; m_DepthTestEnabled = _proto.flags.DEPTHTEST == 0; m_DepthMaskEnabled = _proto.flags.DEPTHWRITE == 0; m_M2BlendMode = _proto.m_BlendMode; } void CM2_Part_Material::fillRenderState(RenderState* _state) const { _state->setCullMode(m_IsTwoSided ? R_CullMode::RS_CULL_NONE : R_CullMode::RS_CULL_BACK); _state->setDepthTest(m_DepthTestEnabled); _state->setDepthMask(m_DepthMaskEnabled); _Render->getRenderStorage()->SetEGxBlend(_state, M2Blend_To_EGxBlend[m_M2BlendMode].EGxBLend); } void CM2_Part_Material::Set() const { _Render->r.setCullMode(m_IsTwoSided ? R_CullMode::RS_CULL_NONE : R_CullMode::RS_CULL_BACK); _Render->r.setDepthTest(m_DepthTestEnabled); _Render->r.setDepthMask(m_DepthMaskEnabled); _Render->getRenderStorage()->SetEGxBlend(_Render->r.getState(), M2Blend_To_EGxBlend[m_M2BlendMode].EGxBLend); }
31.104167
110
0.77294
adan830
c659b80313aa4f0bd8906c83beb7ce897ddb71c6
2,429
cpp
C++
pi4home-core/src/pi4home/cover/mqtt_cover_component.cpp
khzd/pi4home
937bcdcf77bab111cca10af1fe45c63a55c29aae
[ "MIT" ]
1
2019-05-16T02:52:12.000Z
2019-05-16T02:52:12.000Z
pi4home-core/src/pi4home/cover/mqtt_cover_component.cpp
khzd/pi4home
937bcdcf77bab111cca10af1fe45c63a55c29aae
[ "MIT" ]
null
null
null
pi4home-core/src/pi4home/cover/mqtt_cover_component.cpp
khzd/pi4home
937bcdcf77bab111cca10af1fe45c63a55c29aae
[ "MIT" ]
null
null
null
#include "pi4home/defines.h" #ifdef USE_MQTT_COVER #include "pi4home/cover/mqtt_cover_component.h" #include "pi4home/log.h" PI4HOME_NAMESPACE_BEGIN namespace cover { static const char *TAG = "cover.mqtt"; MQTTCoverComponent::MQTTCoverComponent(Cover *cover) : cover_(cover) {} void MQTTCoverComponent::setup() { this->cover_->add_on_publish_state_callback([this](CoverState state) { this->publish_state(state); }); this->subscribe(this->get_command_topic_(), [this](const std::string &topic, const std::string &payload) { if (strcasecmp(payload.c_str(), "OPEN") == 0) { ESP_LOGD(TAG, "'%s': Opening cover...", this->friendly_name().c_str()); this->cover_->open(); } else if (strcasecmp(payload.c_str(), "CLOSE") == 0) { ESP_LOGD(TAG, "'%s': Closing cover...", this->friendly_name().c_str()); this->cover_->close(); } else if (strcasecmp(payload.c_str(), "STOP") == 0) { ESP_LOGD(TAG, "'%s': Stopping cover...", this->friendly_name().c_str()); this->cover_->stop(); } else { ESP_LOGW(TAG, "'%s': Received unknown payload '%s'...", this->friendly_name().c_str(), payload.c_str()); } }); } void MQTTCoverComponent::dump_config() { ESP_LOGCONFIG(TAG, "MQTT cover '%s':", this->cover_->get_name().c_str()); LOG_MQTT_COMPONENT(true, true) } void MQTTCoverComponent::send_discovery(JsonObject &root, mqtt::SendDiscoveryConfig &config) { if (this->cover_->assumed_state()) root["optimistic"] = true; } std::string MQTTCoverComponent::component_type() const { return "cover"; } std::string MQTTCoverComponent::friendly_name() const { return this->cover_->get_name(); } bool MQTTCoverComponent::send_initial_state() { if (this->cover_->has_state()) { return this->publish_state(this->cover_->state); } else { return true; } } bool MQTTCoverComponent::is_internal() { return this->cover_->is_internal(); } bool MQTTCoverComponent::publish_state(cover::CoverState state) { const char *state_s; switch (state) { case COVER_OPEN: state_s = "open"; break; case COVER_CLOSED: state_s = "closed"; break; default: { ESP_LOGW(TAG, "Unknown cover state."); return true; } } ESP_LOGD(TAG, "'%s': Sending state %s", this->friendly_name().c_str(), state_s); return this->publish(this->get_state_topic_(), state_s); } } // namespace cover PI4HOME_NAMESPACE_END #endif // USE_MQTT_COVER
32.386667
110
0.670646
khzd
c65be78a5202ef05fe8255c9f4c4ab3489a57fea
10,253
cpp
C++
OpenCP/libimq/ssim.cpp
norishigefukushima/OpenCP
63090131ec975e834f85b04e84ec29b2893845b2
[ "BSD-3-Clause" ]
137
2015-03-27T07:11:19.000Z
2022-03-30T05:58:22.000Z
OpenCP/libimq/ssim.cpp
Pandinosaurus/OpenCP
a5234ed531c610d7944fa14d42f7320442ea34a1
[ "BSD-3-Clause" ]
2
2016-05-18T06:33:16.000Z
2016-07-11T17:39:17.000Z
OpenCP/libimq/ssim.cpp
Pandinosaurus/OpenCP
a5234ed531c610d7944fa14d42f7320442ea34a1
[ "BSD-3-Clause" ]
43
2015-02-20T15:34:25.000Z
2022-01-27T14:59:37.000Z
#include <math.h> #include "imq.h" //MS_SSIMF(float *forig_img, float *fcomp_img, _INT32 PX, _INT32 PY, bool Wang, bool SSIM, _INT32 bits_per_pixel_1, bool fast, float a, float b, float g) const float aa = 0.05f; const float bb = 0.15f; const float gg = 0.10f; //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- double ABGDoSSIM(_INT32 *orig_img, _INT32 *comp_img, _INT32 PX, _INT32 PY, _INT32 BPP, bool fast, float a, float b, float g) { _INT32 size = PX * PY; double result = 0.0; float *orig_imgb = NULL; float *comp_imgb = NULL; try { orig_imgb = new float [ size ]; comp_imgb = new float [ size ]; } catch (...) { if (orig_imgb) delete orig_imgb; if (comp_imgb) delete [] comp_imgb; return result; } switch(BPP) { case 8: { for(_INT32 i = 0; i < size; ++i) { orig_imgb[i] = (float)(orig_img[i]&_MBYTE); comp_imgb[i] = (float)(comp_img[i]&_MBYTE); } result = MS_SSIMF(orig_imgb,comp_imgb,PX,PY,false,true,8,fast,a,b,g); }; break; case 16: { for(_INT32 i = 0; i < size; ++i) { orig_imgb[i] = (float)(orig_img[i]&_MINT16); comp_imgb[i] = (float)(comp_img[i]&_MINT16); } result = MS_SSIMF(orig_imgb,comp_imgb,PX,PY,false,true,16,fast,a,b,g); }; break; default: break; } delete [] orig_imgb; delete [] comp_imgb; return result; } //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- double ABGSSIM8bit(_BYTE *orig_img, _BYTE *comp_img, _INT32 PX, _INT32 PY, bool fast, float a, float b, float g) { _INT32 size = PX * PY; double result = 0.0; float *orig_imgb = NULL; float *comp_imgb = NULL; try { orig_imgb = new float [ size ]; comp_imgb = new float [ size ]; } catch (...) { if (orig_imgb) delete orig_imgb; if (comp_imgb) delete [] comp_imgb; return result; } for(_INT32 i = 0; i < size; ++i) { orig_imgb[i] = (float)(orig_img[i]&_MBYTE); comp_imgb[i] = (float)(comp_img[i]&_MBYTE); } result = MS_SSIMF(orig_imgb,comp_imgb,PX,PY,false,true,8,fast,a,b,g); delete [] orig_imgb; delete [] comp_imgb; return result; } //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- double ABGSSIM16bit(_UINT16 *orig_img, _UINT16 *comp_img, _INT32 PX, _INT32 PY, bool fast, float a, float b, float g) { _INT32 size = PX * PY; double result = 0.0; float *orig_imgb = NULL; float *comp_imgb = NULL; try { orig_imgb = new float [ size ]; comp_imgb = new float [ size ]; } catch (...) { if (orig_imgb) delete orig_imgb; if (comp_imgb) delete [] comp_imgb; return result; } for(_INT32 i = 0; i < size; ++i) { orig_imgb[i] = (float)(orig_img[i]&_MINT16); comp_imgb[i] = (float)(comp_img[i]&_MINT16); } result = MS_SSIMF(orig_imgb,comp_imgb,PX,PY,false,true,16,fast,a,b,g); delete [] orig_imgb; delete [] comp_imgb; return result; } //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- double ABGDoSSIMY(_INT32 *orig_img, _INT32 *comp_img, _INT32 PX, _INT32 PY, _INT32 BPP, bool fast, float a, float b, float g) { _INT32 size = PX * PY; double result = 0.0; switch (BPP) { case 8: case 16: result = ABGDoSSIM(orig_img, comp_img, PX,PY,BPP, fast,a,b,g); break; case 24: { float *orig_imgb = NULL; float *comp_imgb = NULL; try { orig_imgb = new float [ size ]; comp_imgb = new float [ size ]; } catch (...) { if (orig_imgb) delete orig_imgb; if (comp_imgb) delete [] comp_imgb; return result; } for(_INT32 i=0; i < size; ++i) { double Y1 = rgB * (double)((orig_img[i]>>16)&_MBYTE) + rGb * (double)((orig_img[i]>>8)&_MBYTE) + Rgb * (double)(orig_img[i]&_MBYTE) + Crgb; double Y2 = rgB * (double)((comp_img[i]>>16)&_MBYTE) + rGb * (double)((comp_img[i]>>8)&_MBYTE) + Rgb * (double)(comp_img[i]&_MBYTE) + Crgb; comp_imgb[i] = (float)Y2; orig_imgb[i] = (float)Y1; } result = MS_SSIMF(orig_imgb,comp_imgb,PX,PY,false,true,8,fast,a,b,g); delete [] orig_imgb; delete [] comp_imgb; }; break; default: break; } return result; } //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- double ABGDoSSIMY(_BYTE *orig_img, _BYTE *comp_img, _INT32 PX, _INT32 PY, _INT32 BPP, bool fast, float a, float b, float g) { _INT32 size = PX * PY; _INT32 bsize = size * 3; double result = 0.0; switch (BPP) { case 24: { float *orig_imgb = NULL; float *comp_imgb = NULL; try { orig_imgb = new float [ size ]; comp_imgb = new float [ size ]; } catch (...) { if (orig_imgb) delete orig_imgb; if (comp_imgb) delete [] comp_imgb; return result; } for(_INT32 i=0,j=0; i < bsize; i+=3,++j) { if ((i < bsize) && (i + 1 < bsize) && (i + 2 < bsize) && (j < size)) { double Y1 = rgB * (double)(orig_img[i]) + rGb * (double)(orig_img[i+1]) + Rgb * (double)(orig_img[i+2]) + Crgb; double Y2 = rgB * (double)(comp_img[i]) + rGb * (double)(comp_img[i+1]) + Rgb * (double)(comp_img[i+2]) + Crgb; comp_imgb[j] = (float)Y2; orig_imgb[j] = (float)Y1; } } result = MS_SSIMF(orig_imgb,comp_imgb,PX,PY,false,true,8,fast,a,b,g); delete [] orig_imgb; delete [] comp_imgb; }; break; default: break; } return result; } //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- double DoSSIMY(_BYTE *orig_img, _BYTE *comp_img, _INT32 PX, _INT32 PY, _INT32 BPP, bool fast) { return ABGDoSSIMY(orig_img,comp_img,PX,PY,BPP,fast,1.0f,1.0f,1.0f); } double DoSSIMY(_INT32 *orig_img, _INT32 *comp_img, _INT32 PX, _INT32 PY, _INT32 BPP, bool fast) { return ABGDoSSIMY(orig_img,comp_img,PX,PY,BPP,fast,1.0f,1.0f,1.0f); } double DoSSIM(_INT32 *orig_img, _INT32 *comp_img, _INT32 PX, _INT32 PY, _INT32 BPP, bool fast) { return ABGDoSSIM(orig_img,comp_img,PX,PY,BPP,fast, 1.0f, 1.0f, 1.0f); } double SSIM16bit(_UINT16 *orig_img, _UINT16 *comp_img, _INT32 PX, _INT32 PY, bool fast) { return ABGSSIM16bit(orig_img,comp_img,PX,PY,fast,1.0f,1.0f,1.0f); } double SSIM8bit(_BYTE *orig_img, _BYTE *comp_img, _INT32 PX, _INT32 PY, bool fast) { return ABGSSIM8bit(orig_img, comp_img, PX, PY,fast,1.0f,1.0f,1.0f); } //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- double mDoSSIMY(_BYTE *orig_img, _BYTE *comp_img, _INT32 PX, _INT32 PY, _INT32 BPP, bool fast) { return ABGDoSSIMY(orig_img,comp_img,PX,PY,BPP,fast,aa,bb,gg); } double mDoSSIMY(_INT32 *orig_img, _INT32 *comp_img, _INT32 PX, _INT32 PY, _INT32 BPP, bool fast) { return ABGDoSSIMY(orig_img,comp_img,PX,PY,BPP,fast,aa,bb,gg); } double mDoSSIM(_INT32 *orig_img, _INT32 *comp_img, _INT32 PX, _INT32 PY, _INT32 BPP, bool fast) { return ABGDoSSIM(orig_img,comp_img,PX,PY,BPP,fast,aa,bb,gg); } double mSSIM16bit(_UINT16 *orig_img, _UINT16 *comp_img, _INT32 PX, _INT32 PY, bool fast) { return ABGSSIM16bit(orig_img,comp_img,PX,PY,fast,aa,bb,gg); } double mSSIM8bit(_BYTE *orig_img, _BYTE *comp_img, _INT32 PX, _INT32 PY, bool fast) { return ABGSSIM8bit(orig_img, comp_img, PX, PY,fast,aa,bb,gg); } //---------------------------------------------------------------------------------------------------------------------------------------------- double __DoSSIM(_INT32 *orig_img,_INT32 *comp_img,_INT32 PX,_INT32 PY,_INT32 BPP, float a,float b,float g, bool fast) { return ABGDoSSIMY(orig_img,comp_img,PX,PY,BPP,fast,a,b,g); } //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------------------------------------
35.975439
153
0.424071
norishigefukushima
c65c030429c89ebdddaa12559bd3bf44cc74607a
10,761
cpp
C++
src/utils/vrad/disp_vrad.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/utils/vrad/disp_vrad.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/utils/vrad/disp_vrad.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "disp_vrad.h" #include "utllinkedlist.h" #include "utlvector.h" #include "iscratchpad3d.h" #include "scratchpadutils.h" //#define USE_SCRATCHPAD #if defined( USE_SCRATCHPAD ) static IScratchPad3D *g_pPad = 0; #endif int FindNeighborCornerVert(CCoreDispInfo *pDisp, const Vector &vTest) { CDispUtilsHelper *pDispHelper = pDisp; int iClosest = 0; float flClosest = 1e24; for (int iCorner = 0; iCorner < 4; iCorner++) { // Has it been touched? CVertIndex cornerVert = pDispHelper->GetPowerInfo()->GetCornerPointIndex(iCorner); int iCornerVert = pDispHelper->VertIndexToInt(cornerVert); const Vector &vCornerVert = pDisp->GetVert(iCornerVert); float flDist = vCornerVert.DistTo(vTest); if (flDist < flClosest) { iClosest = iCorner; flClosest = flDist; } } if (flClosest <= 0.1f) return iClosest; else return -1; } int GetAllNeighbors(const CCoreDispInfo *pDisp, int (&iNeighbors)[512]) { int nNeighbors = 0; // Check corner neighbors. for (int iCorner = 0; iCorner < 4; iCorner++) { const CDispCornerNeighbors *pCorner = pDisp->GetCornerNeighbors(iCorner); for (int i = 0; i < pCorner->m_nNeighbors; i++) { if (nNeighbors < ARRAYSIZE(iNeighbors)) iNeighbors[nNeighbors++] = pCorner->m_Neighbors[i]; } } for (int iEdge = 0; iEdge < 4; iEdge++) { const CDispNeighbor *pEdge = pDisp->GetEdgeNeighbor(iEdge); for (int i = 0; i < 2; i++) { if (pEdge->m_SubNeighbors[i].IsValid()) if (nNeighbors < 512) iNeighbors[nNeighbors++] = pEdge->m_SubNeighbors[i].GetNeighborIndex(); } } return nNeighbors; } void BlendCorners(CCoreDispInfo **ppListBase, int listSize) { CUtlVector<int> nbCornerVerts; for (int iDisp = 0; iDisp < listSize; iDisp++) { CCoreDispInfo *pDisp = ppListBase[iDisp]; int iNeighbors[512]; int nNeighbors = GetAllNeighbors(pDisp, iNeighbors); // Make sure we have room for all the neighbors. nbCornerVerts.RemoveAll(); nbCornerVerts.EnsureCapacity(nNeighbors); nbCornerVerts.AddMultipleToTail(nNeighbors); // For each corner. for (int iCorner = 0; iCorner < 4; iCorner++) { // Has it been touched? CVertIndex cornerVert = pDisp->GetCornerPointIndex(iCorner); int iCornerVert = pDisp->VertIndexToInt(cornerVert); const Vector &vCornerVert = pDisp->GetVert(iCornerVert); // For each displacement sharing this corner.. Vector vAverage = pDisp->GetNormal(iCornerVert); for (int iNeighbor = 0; iNeighbor < nNeighbors; iNeighbor++) { int iNBListIndex = iNeighbors[iNeighbor]; CCoreDispInfo *pNeighbor = ppListBase[iNBListIndex]; // Find out which vert it is on the neighbor. int iNBCorner = FindNeighborCornerVert(pNeighbor, vCornerVert); if (iNBCorner == -1) { nbCornerVerts[iNeighbor] = -1; // remove this neighbor from the list. } else { CVertIndex viNBCornerVert = pNeighbor->GetCornerPointIndex(iNBCorner); int iNBVert = pNeighbor->VertIndexToInt(viNBCornerVert); nbCornerVerts[iNeighbor] = iNBVert; vAverage += pNeighbor->GetNormal(iNBVert); } } // Blend all the neighbor normals with this one. VectorNormalize(vAverage); pDisp->SetNormal(iCornerVert, vAverage); #if defined( USE_SCRATCHPAD ) ScratchPad_DrawArrowSimple( g_pPad, pDisp->GetVert( iCornerVert ), pDisp->GetNormal( iCornerVert ), Vector( 0, 0, 1 ), 25 ); #endif for (int iNeighbor = 0; iNeighbor < nNeighbors; iNeighbor++) { int iNBListIndex = iNeighbors[iNeighbor]; if (nbCornerVerts[iNeighbor] == -1) continue; CCoreDispInfo *pNeighbor = ppListBase[iNBListIndex]; pNeighbor->SetNormal(nbCornerVerts[iNeighbor], vAverage); } } } } void BlendTJuncs(CCoreDispInfo **ppListBase, int listSize) { for (int iDisp = 0; iDisp < listSize; iDisp++) { CCoreDispInfo *pDisp = ppListBase[iDisp]; for (int iEdge = 0; iEdge < 4; iEdge++) { CDispNeighbor *pEdge = pDisp->GetEdgeNeighbor(iEdge); CVertIndex viMidPoint = pDisp->GetEdgeMidPoint(iEdge); int iMidPoint = pDisp->VertIndexToInt(viMidPoint); if (pEdge->m_SubNeighbors[0].IsValid() && pEdge->m_SubNeighbors[1].IsValid()) { const Vector &vMidPoint = pDisp->GetVert(iMidPoint); CCoreDispInfo *pNeighbor1 = ppListBase[pEdge->m_SubNeighbors[0].GetNeighborIndex()]; CCoreDispInfo *pNeighbor2 = ppListBase[pEdge->m_SubNeighbors[1].GetNeighborIndex()]; int iNBCorners[2]; iNBCorners[0] = FindNeighborCornerVert(pNeighbor1, vMidPoint); iNBCorners[1] = FindNeighborCornerVert(pNeighbor2, vMidPoint); if (iNBCorners[0] != -1 && iNBCorners[1] != -1) { CVertIndex viNBCorners[2] = { pNeighbor1->GetCornerPointIndex(iNBCorners[0]), pNeighbor2->GetCornerPointIndex(iNBCorners[1]) }; Vector vAverage = pDisp->GetNormal(iMidPoint); vAverage += pNeighbor1->GetNormal(viNBCorners[0]); vAverage += pNeighbor2->GetNormal(viNBCorners[1]); VectorNormalize(vAverage); pDisp->SetNormal(iMidPoint, vAverage); pNeighbor1->SetNormal(viNBCorners[0], vAverage); pNeighbor2->SetNormal(viNBCorners[1], vAverage); #if defined( USE_SCRATCHPAD ) ScratchPad_DrawArrowSimple( g_pPad, pDisp->GetVert( iMidPoint ), pDisp->GetNormal( iMidPoint ), Vector( 0, 1, 1 ), 25 ); #endif } } } } } void BlendEdges(CCoreDispInfo **ppListBase, int listSize) { for (int iDisp = 0; iDisp < listSize; iDisp++) { CCoreDispInfo *pDisp = ppListBase[iDisp]; for (int iEdge = 0; iEdge < 4; iEdge++) { CDispNeighbor *pEdge = pDisp->GetEdgeNeighbor(iEdge); for (int iSub = 0; iSub < 2; iSub++) { CDispSubNeighbor *pSub = &pEdge->m_SubNeighbors[iSub]; if (!pSub->IsValid()) continue; CCoreDispInfo *pNeighbor = ppListBase[pSub->GetNeighborIndex()]; int iEdgeDim = g_EdgeDims[iEdge]; CDispSubEdgeIterator it; it.Start(pDisp, iEdge, iSub, true); // Get setup on the first corner vert. it.Next(); CVertIndex viPrevPos = it.GetVertIndex(); while (it.Next()) { // Blend the two. if (!it.IsLastVert()) { Vector vAverage = pDisp->GetNormal(it.GetVertIndex()) + pNeighbor->GetNormal(it.GetNBVertIndex()); VectorNormalize(vAverage); pDisp->SetNormal(it.GetVertIndex(), vAverage); pNeighbor->SetNormal(it.GetNBVertIndex(), vAverage); #if defined( USE_SCRATCHPAD ) ScratchPad_DrawArrowSimple( g_pPad, pDisp->GetVert( it.GetVertIndex() ), pDisp->GetNormal( it.GetVertIndex() ), Vector( 1, 0, 0 ), 25 ); #endif } // Now blend the in-between verts (if this edge is high-res). int iPrevPos = viPrevPos[!iEdgeDim]; int iCurPos = it.GetVertIndex()[!iEdgeDim]; for (int iTween = iPrevPos + 1; iTween < iCurPos; iTween++) { float flPercent = RemapVal(iTween, iPrevPos, iCurPos, 0, 1); Vector vNormal; VectorLerp(pDisp->GetNormal(viPrevPos), pDisp->GetNormal(it.GetVertIndex()), flPercent, vNormal); VectorNormalize(vNormal); CVertIndex viTween; viTween[iEdgeDim] = it.GetVertIndex()[iEdgeDim]; viTween[!iEdgeDim] = iTween; pDisp->SetNormal(viTween, vNormal); #if defined( USE_SCRATCHPAD ) ScratchPad_DrawArrowSimple( g_pPad, pDisp->GetVert( viTween ), pDisp->GetNormal( viTween ), Vector( 1, 0.5, 0 ), 25 ); #endif } viPrevPos = it.GetVertIndex(); } } } } } #if defined( USE_SCRATCHPAD ) void ScratchPad_DrawOriginalNormals( const CCoreDispInfo *pListBase, int listSize ) { for ( int i=0; i < listSize; i++ ) { const CCoreDispInfo *pDisp = &pListBase[i]; const CPowerInfo *pPowerInfo = pDisp->GetPowerInfo(); // Draw the triangles. for ( int iTri=0; iTri < pPowerInfo->GetNumTriInfos(); iTri++ ) { const CTriInfo *pTriInfo = pPowerInfo->GetTriInfo( iTri ); for ( int iLine=0; iLine < 3; iLine++ ) { const Vector &v1 = pDisp->GetVert( pTriInfo->m_Indices[iLine] ); const Vector &v2 = pDisp->GetVert( pTriInfo->m_Indices[(iLine+1)%3] ); g_pPad->DrawLine( CSPVert( v1 ), CSPVert( v2 ) ); } } // Draw the normals. CDispCircumferenceIterator it( pPowerInfo->GetSideLength() ); while ( it.Next() ) { ScratchPad_DrawArrowSimple( g_pPad, pDisp->GetVert( it.GetVertIndex() ), pDisp->GetNormal( it.GetVertIndex() ), Vector( 0, 1, 0 ), 15 ); } } } #endif void SmoothNeighboringDispSurfNormals(CCoreDispInfo **ppListBase, int listSize) { //#if defined( USE_SCRATCHPAD ) // g_pPad = ScratchPad3D_Create(); // ScratchPad_DrawOriginalNormals( pListBase, listSize ); //#endif BlendTJuncs(ppListBase, listSize); BlendCorners(ppListBase, listSize); BlendEdges(ppListBase, listSize); }
35.166667
160
0.552086
cstom4994
c65d53273ae435ccfd3c072836fa7c16ebd5c802
19,973
hpp
C++
include/xframe/xaxis_variant.hpp
jeandet/xframe
b4fa0759cab381418a3d23f0d61f74d0d400a5c0
[ "BSD-3-Clause" ]
null
null
null
include/xframe/xaxis_variant.hpp
jeandet/xframe
b4fa0759cab381418a3d23f0d61f74d0d400a5c0
[ "BSD-3-Clause" ]
null
null
null
include/xframe/xaxis_variant.hpp
jeandet/xframe
b4fa0759cab381418a3d23f0d61f74d0d400a5c0
[ "BSD-3-Clause" ]
null
null
null
/*************************************************************************** * Copyright (c) 2017, Johan Mabille, Sylvain Corlay and Wolf Vollprecht * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XFRAME_XAXIS_VARIANT_HPP #define XFRAME_XAXIS_VARIANT_HPP #include <functional> #include "xtl/xclosure.hpp" #include "xtl/xmeta_utils.hpp" #include "xtl/xvariant.hpp" #include "xaxis.hpp" #include "xaxis_default.hpp" #include "xvector_variant.hpp" namespace xf { namespace detail { template <class V, class S, class... L> struct add_default_axis; template <class... A, class S> struct add_default_axis<xtl::variant<A...>, S> { using type = xtl::variant<A...>; }; template <class... A, class S, class L1, class... L> struct add_default_axis<xtl::variant<A...>, S, L1, L...> { using type = typename xtl::mpl::if_t<std::is_integral<L1>, add_default_axis<xtl::variant<A..., xaxis_default<L1, S>>, S, L...>, add_default_axis<xtl::variant<A...>, S, L...>>::type; }; template <class V, class S, class... L> using add_default_axis_t = typename add_default_axis<V, S, L...>::type; template <class V> struct get_axis_variant_iterator; template <class... A> struct get_axis_variant_iterator<xtl::variant<A...>> { using type = xtl::variant<typename A::const_iterator...>; }; template <class V> using get_axis_variant_iterator_t = typename get_axis_variant_iterator<V>::type; template <class S, class MT, class TL> struct xaxis_variant_traits; template <class S, class MT, template <class...> class TL, class... L> struct xaxis_variant_traits<S, MT, TL<L...>> { using tmp_storage_type = xtl::variant<xaxis<L, S, MT>...>; using storage_type = add_default_axis_t<tmp_storage_type, S, L...>; using label_list = xvector_variant_cref<L...>; using key_type = xtl::variant<typename xaxis<L, S, MT>::key_type...>; using key_reference = xtl::variant<xtl::xclosure_wrapper<const typename xaxis<L, S, MT>::key_type&>...>; using mapped_type = S; using value_type = std::pair<key_type, mapped_type>; using reference = std::pair<key_reference, mapped_type&>; using const_reference = std::pair<key_reference, const mapped_type&>; using pointer = xtl::xclosure_pointer<reference>; using const_pointer = xtl::xclosure_pointer<const_reference>; using size_type = typename label_list::size_type; using difference_type = typename label_list::difference_type; using subiterator = get_axis_variant_iterator_t<storage_type>; }; } template <class L, class T, class MT> class xaxis_variant_iterator; /***************** * xaxis_variant * *****************/ template <class L, class T, class MT = hash_map_tag> class xaxis_variant { public: static_assert(std::is_integral<T>::value, "index_type must be an integral type"); using self_type = xaxis_variant<L, T, MT>; using map_container_tag = MT; using traits_type = detail::xaxis_variant_traits<T, MT, L>; using storage_type = typename traits_type::storage_type; using key_type = typename traits_type::key_type; using key_reference = typename traits_type::key_reference; using mapped_type = T; using label_list = typename traits_type::label_list; using value_type = typename traits_type::value_type; using reference = typename traits_type::reference; using const_reference = typename traits_type::const_reference; using pointer = typename traits_type::pointer; using const_pointer = typename traits_type::const_pointer; using size_type = typename traits_type::size_type; using difference_type = typename traits_type::difference_type; using iterator = xaxis_variant_iterator<L, T, MT>; using const_iterator = iterator; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using subiterator = typename traits_type::subiterator; xaxis_variant() = default; template <class LB> xaxis_variant(const xaxis<LB, T, MT>& axis); template <class LB> xaxis_variant(xaxis<LB, T, MT>&& axis); template <class LB> xaxis_variant(const xaxis_default<LB, T>& axis); template <class LB> xaxis_variant(xaxis_default<LB, T>&& axis); label_list labels() const; key_type label(size_type i) const; bool empty() const; size_type size() const; bool is_sorted() const noexcept; bool contains(const key_type& key) const; mapped_type operator[](const key_type& key) const; template <class F> self_type filter(const F& f) const; template <class F> self_type filter(const F& f, size_type size) const; const_iterator find(const key_type& key) const; const_iterator begin() const; const_iterator end() const; const_iterator cbegin() const; const_iterator cend() const; const_reverse_iterator rbegin() const; const_reverse_iterator rend() const; const_reverse_iterator crbegin() const; const_reverse_iterator crend() const; template <class... Args> bool merge(const Args&... axes); template <class... Args> bool intersect(const Args&... axes); self_type as_xaxis() const; bool operator==(const self_type& rhs) const; bool operator!=(const self_type& rhs) const; private: storage_type m_data; template <class OS, class L1, class T1, class MT1> friend OS& operator<<(OS&, const xaxis_variant<L1, T1, MT1>&); }; template <class OS, class L, class T, class MT> OS& operator<<(OS& out, const xaxis_variant<L, T, MT>& axis); /************************** * xaxis_variant_iterator * **************************/ template <class L, class T, class MT> class xaxis_variant_iterator : public xtl::xrandom_access_iterator_base<xaxis_variant_iterator<L, T, MT>, typename xaxis_variant<L, T, MT>::value_type, typename xaxis_variant<L, T, MT>::difference_type, typename xaxis_variant<L, T, MT>::const_pointer, typename xaxis_variant<L, T, MT>::const_reference> { public: using self_type = xaxis_variant_iterator<L, T, MT>; using container_type = xaxis_variant<L, T, MT>; using key_reference = typename container_type::key_reference; using value_type = typename container_type::value_type; using reference = typename container_type::const_reference; using pointer = typename container_type::const_pointer; using difference_type = typename container_type::difference_type; using iterator_category = std::random_access_iterator_tag; using subiterator = typename container_type::subiterator; xaxis_variant_iterator() = default; xaxis_variant_iterator(subiterator it); self_type& operator++(); self_type& operator--(); self_type& operator+=(difference_type n); self_type& operator-=(difference_type n); difference_type operator-(const self_type& rhs) const; reference operator*() const; pointer operator->() const; bool equal(const self_type& rhs) const; bool less_than(const self_type& rhs) const; private: subiterator m_it; }; template <class L, class T, class MT> typename xaxis_variant_iterator<L, T, MT>::difference_type operator-(const xaxis_variant_iterator<L, T, MT>& lhs, const xaxis_variant_iterator<L, T, MT>& rhs); template <class L, class T, class MT> bool operator==(const xaxis_variant_iterator<L, T, MT>& lhs, const xaxis_variant_iterator<L, T, MT>& rhs); template <class L, class T, class MT> bool operator<(const xaxis_variant_iterator<L, T, MT>& lhs, const xaxis_variant_iterator<L, T, MT>& rhs); /******************************** * xaxis_variant implementation * ********************************/ template <class L, class T, class MT> template <class LB> inline xaxis_variant<L, T, MT>::xaxis_variant(const xaxis<LB, T, MT>& axis) : m_data(axis) { } template <class L, class T, class MT> template <class LB> inline xaxis_variant<L, T, MT>::xaxis_variant(xaxis<LB, T, MT>&& axis) : m_data(std::move(axis)) { } template <class L, class T, class MT> template <class LB> inline xaxis_variant<L, T, MT>::xaxis_variant(const xaxis_default<LB, T>& axis) : m_data(axis) { } template <class L, class T, class MT> template <class LB> inline xaxis_variant<L, T, MT>::xaxis_variant(xaxis_default<LB, T>&& axis) : m_data(std::move(axis)) { } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::labels() const -> label_list { return xtl::visit([](auto&& arg) -> label_list { return arg.labels(); }, m_data); }; template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::label(size_type i) const -> key_type { return xtl::visit([i](auto&& arg) -> key_type { return arg.labels()[i]; }, m_data); } template <class L, class T, class MT> inline bool xaxis_variant<L, T, MT>::empty() const { return xtl::visit([](auto&& arg) { return arg.empty(); }, m_data); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::size() const -> size_type { return xtl::visit([](auto&& arg) { return arg.size(); }, m_data); } template <class L, class T, class MT> inline bool xaxis_variant<L, T, MT>::is_sorted() const noexcept { return xtl::visit([](auto&& arg) { return arg.is_sorted(); }, m_data); } template <class L, class T, class MT> inline bool xaxis_variant<L, T, MT>::contains(const key_type& key) const { auto lambda = [&key](auto&& arg) -> bool { using type = typename std::decay_t<decltype(arg)>::key_type; return arg.contains(xtl::get<type>(key)); }; return xtl::visit(lambda, m_data); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::operator[](const key_type& key) const -> mapped_type { auto lambda = [&key](auto&& arg) -> mapped_type { using type = typename std::decay_t<decltype(arg)>::key_type; return arg[xtl::get<type>(key)]; }; return xtl::visit(lambda, m_data); } template <class L, class T, class MT> template <class F> inline auto xaxis_variant<L, T, MT>::filter(const F& f) const -> self_type { return xtl::visit([&f](const auto& arg) { return self_type(arg.filter(f)); }, m_data); } template <class L, class T, class MT> template <class F> inline auto xaxis_variant<L, T, MT>::filter(const F& f, size_type size) const -> self_type { return xtl::visit([&f, size](const auto& arg) { return self_type(arg.filter(f, size)); }, m_data); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::find(const key_type& key) const -> const_iterator { auto lambda = [&key](auto&& arg) -> const_iterator { using type = typename std::decay_t<decltype(arg)>::key_type; return subiterator(arg.find(xtl::get<type>(key))); }; return xtl::visit(lambda, m_data); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::begin() const -> const_iterator { return cbegin(); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::end() const -> const_iterator { return cend(); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::cbegin() const -> const_iterator { return xtl::visit([](auto&& arg) { return subiterator(arg.cbegin()); }, m_data); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::cend() const -> const_iterator { return xtl::visit([](auto&& arg) { return subiterator(arg.cend()); }, m_data); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::rbegin() const -> const_reverse_iterator { return crbegin(); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::rend() const -> const_reverse_iterator { return crend(); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::crbegin() const -> const_reverse_iterator { return xtl::visit([](auto&& arg) { return subiterator(arg.cend()); }, m_data); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::crend() const -> const_reverse_iterator { return xtl::visit([](auto&& arg) { return subiterator(arg.cbegin()); }, m_data); } template <class L, class T, class MT, class K> struct xaxis_variant_adaptor { using axis_variant_type = xaxis_variant<L, T, MT>; using key_type = K; using axis_type = xaxis<K, T, MT>; using label_list = typename axis_type::label_list; xaxis_variant_adaptor(const axis_variant_type& axis) : m_axis(axis) { }; inline const label_list& labels() const { return xget_vector<key_type>(m_axis.labels()); }; inline bool is_sorted() const noexcept { return m_axis.is_sorted(); }; private: const axis_variant_type& m_axis; }; template <class L, class T, class MT> template <class... Args> inline bool xaxis_variant<L, T, MT>::merge(const Args&... axes) { auto lambda = [&axes...](auto&& arg) -> bool { using key_type = typename std::decay_t<decltype(arg)>::key_type; return arg.merge(xaxis_variant_adaptor<L, T, MT, key_type>(axes)...); }; return xtl::visit(lambda, m_data); } template <class L, class T, class MT> template <class... Args> inline bool xaxis_variant<L, T, MT>::intersect(const Args&... axes) { auto lambda = [&axes...](auto&& arg) -> bool { using key_type = typename std::decay_t<decltype(arg)>::key_type; return arg.intersect(xaxis_variant_adaptor<L, T, MT, key_type>(axes)...); }; return xtl::visit(lambda, m_data); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::as_xaxis() const -> self_type { return xtl::visit([](auto&& arg) { return self_type(xaxis<typename std::decay_t<decltype(arg)>::key_type, T, MT>(arg)); }, m_data); } template <class L, class T, class MT> inline bool xaxis_variant<L, T, MT>::operator==(const self_type& rhs) const { return m_data == rhs.m_data; } template <class L, class T, class MT> inline bool xaxis_variant<L, T, MT>::operator!=(const self_type& rhs) const { return m_data != rhs.m_data; } template <class OS, class L, class T, class MT> inline OS& operator<<(OS& out, const xaxis_variant<L, T, MT>& axis) { xtl::visit([&out](auto&& arg) { out << arg; }, axis.m_data); return out; } /***************************************** * xaxis_variant_iterator implementation * *****************************************/ template<class L, class T, class MT> inline xaxis_variant_iterator<L, T, MT>::xaxis_variant_iterator(subiterator it) : m_it(it) { } template <class L, class T, class MT> inline auto xaxis_variant_iterator<L, T, MT>::operator++() -> self_type& { xtl::visit([](auto&& arg) { ++arg; }, m_it); return *this; } template <class L, class T, class MT> inline auto xaxis_variant_iterator<L, T, MT>::operator--() -> self_type& { xtl::visit([](auto&& arg) { --arg; }, m_it); return *this; } template <class L, class T, class MT> inline auto xaxis_variant_iterator<L, T, MT>::operator+=(difference_type n) -> self_type& { xtl::visit([n](auto&& arg) { arg += n; }, m_it); return *this; } template <class L, class T, class MT> inline auto xaxis_variant_iterator<L, T, MT>::operator-=(difference_type n) -> self_type& { xtl::visit([n](auto&& arg) { arg -= n; }, m_it); return *this; } template <class L, class T, class MT> inline auto xaxis_variant_iterator<L, T, MT>::operator-(const self_type& rhs) const -> difference_type { xtl::visit([&rhs](auto&& arg) { return arg - std::get<std::decay_t<decltype(arg)>>(rhs); }, m_it); return *this; } template <class L, class T, class MT> inline auto xaxis_variant_iterator<L, T, MT>::operator*() const -> reference { return xtl::visit([](auto&& arg) { return reference(key_reference(xtl::closure(arg->first)), arg->second); }, m_it); } template <class T> struct DEBUG; template <class L, class T, class MT> inline auto xaxis_variant_iterator<L, T, MT>::operator->() const -> pointer { return xtl::visit([](auto&& arg) { return pointer(reference(key_reference(xtl::closure(arg->first)), arg->second)); }, m_it); } template <class L, class T, class MT> inline bool xaxis_variant_iterator<L, T, MT>::equal(const self_type& rhs) const { return m_it == rhs.m_it; } template <class L, class T, class MT> inline bool xaxis_variant_iterator<L, T, MT>::less_than(const self_type& rhs) const { return m_it < rhs.m_it; } template <class L, class T, class MT> inline auto operator-(const xaxis_variant_iterator<L, T, MT>& lhs, const xaxis_variant_iterator<L, T, MT>& rhs) -> typename xaxis_variant_iterator<L, T, MT>::difference_type { return lhs.operator-(rhs); } template <class L, class T, class MT> inline bool operator==(const xaxis_variant_iterator<L, T, MT>& lhs, const xaxis_variant_iterator<L, T, MT>& rhs) { return lhs.equal(rhs); } template <class L, class T, class MT> inline bool operator<(const xaxis_variant_iterator<L, T, MT>& lhs, const xaxis_variant_iterator<L, T, MT>& rhs) { return lhs.less_than(rhs); } template <class LB, class L, class T, class MT> auto get_labels(const xaxis_variant<L, T, MT>& axis_variant) -> const typename xaxis<LB, T, MT>::label_list& { using label_list = typename xaxis<LB, T, MT>::label_list; return xtl::xget<const label_list&>(axis_variant.labels().storage()); } } #endif
34.856894
139
0.588945
jeandet
c65e6ac358893c7fd86fc06780c4d88f26dee4ea
490
cpp
C++
source/lab2/gradient_descent.cpp
Jovvik/methopt-lab-1
2c3acaf653c7214a925ed1292b9d1d30a33d2737
[ "Unlicense" ]
null
null
null
source/lab2/gradient_descent.cpp
Jovvik/methopt-lab-1
2c3acaf653c7214a925ed1292b9d1d30a33d2737
[ "Unlicense" ]
null
null
null
source/lab2/gradient_descent.cpp
Jovvik/methopt-lab-1
2c3acaf653c7214a925ed1292b9d1d30a33d2737
[ "Unlicense" ]
null
null
null
#include "lab2/gradient_descent.h" using namespace lab2; Vector GradientDescent::iteration(NFunction &f, double) { Vector x = points_last(); Vector f_x_grad = f.grad(x); Vector y = x - f_x_grad * a; double f_x = f(x); while (f(y) >= f_x && iteration_count <= 1000) { a /= 2; y = x - f_x_grad * a; iteration_count++; } return y; } lab2::Vector GradientDescent::points_last() const { return get_points().back(); }
23.333333
57
0.577551
Jovvik
c660fb687eac42f5a2637c516194aca94aa6edf9
4,238
cpp
C++
fileOperation/fileoperation.cpp
ycsoft/FatCat-Server
fe01d3278927437c04977f3009154537868cc354
[ "MIT" ]
30
2015-08-31T04:25:35.000Z
2022-02-19T17:39:23.000Z
fileOperation/fileoperation.cpp
Mark0518/FatCat-Server
fe01d3278927437c04977f3009154537868cc354
[ "MIT" ]
null
null
null
fileOperation/fileoperation.cpp
Mark0518/FatCat-Server
fe01d3278927437c04977f3009154537868cc354
[ "MIT" ]
35
2015-08-31T10:19:03.000Z
2021-09-18T07:37:00.000Z
#include "fileoperation.h" #include "./../Monster/monsterstruct.h" #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <cstdio> fileOperation::fileOperation() { buffMap1 = NULL; buffMap2 = NULL; buffMap3 = NULL; } fileOperation::~fileOperation() { if(buffMap1) delete buffMap1; if(buffMap2) delete buffMap2; if(buffMap3) delete buffMap3; } void fileOperation::ReadFile (hf_char* filePath, hf_uint16 MapID) { hf_int32 fd = open(filePath, O_RDONLY, 777); if(fd == -1) { printf("%s open failed\n", filePath); return; } hf_int32 fileLength = lseek (fd, 0, SEEK_END); if(fileLength == -1) { printf("lseek error\n"); close(fd); return; } printf("fileLength = %d\n", fileLength); if(fileLength != 0) { hf_char* buffMap = NULL; switch(MapID) { case MAP1: { buffMap1 = new hf_char[fileLength]; buffMap = buffMap1; break; } case MAP2: { buffMap2 = new hf_char[fileLength]; buffMap = buffMap2; break; } case MAP3: { buffMap3 = new hf_char[fileLength]; buffMap = buffMap3; break; } default: { printf("not MapFile\n"); return; } break; } memset(buffMap, 0, fileLength); lseek (fd, 0, SEEK_SET); hf_uint32 num = 0; for(hf_uint32 i = 0; i < fileLength; i++) { if(read(fd, &num, 1) == 1) { printf("%d ", num); if(num > 100) { buffMap[i] = 1; } } else { printf("%d read error\n", fileLength); return; } } printf("\n"); } close(fd); } //判断移动方向 hf_uint8 fileOperation::JudgeMoveDirect(hf_float current_x, hf_float current_z, hf_uint32 MapID, hf_float target_x, hf_float target_z) { hf_char* buffMap = NULL; switch(MapID) { case MAP1: { buffMap = buffMap1; break; } case MAP2: { buffMap = buffMap1; break; } case MAP3: { buffMap = buffMap1; break; } default: return 0; } //右1 右上2 上3 左上4 左5 左下6 下7 右下8 hf_uint8 moveDirect = 0; if(target_x - current_x >= 1) { if(target_z - current_z >= 1) moveDirect = 2; //右上 else if(target_z - current_z <= -1) moveDirect = 8; //右下 else moveDirect = 1; //右 } else if(target_x - current_x <= -1) { if(target_z - current_z >= 1) moveDirect = 4; //左上 else if(target_z - current_z <= -1) moveDirect = 6; //左下 else moveDirect = 5; //左 } else { if(target_z - current_z >= 1) moveDirect = 3; //上 else if(target_z - current_z <= -1) moveDirect = 7; //下 } return EnsureMoveDirect (current_x, current_z, buffMap, moveDirect); } hf_uint8 fileOperation::EnsureMoveDirect(hf_float current_x, hf_float current_z,hf_char* buffMap, hf_uint8 direct) { hf_int32 t_x = (hf_int32)current_x; hf_int32 t_z = (hf_int32)current_z; switch (direct) { case 1: { if(buffMap[t_z*MAP_X+t_x+1] == 0) return 1; } case 2: { if(buffMap[(t_z-1)*MAP_X+t_x+1] == 0) return 2; } case 3: { if(buffMap[(t_z-1)*MAP_X+t_x] == 0) return 3; } case 4: { if(buffMap[(t_z-1)*MAP_X+t_x-1] == 0) return 4; } case 5: { if(buffMap[(t_z)*MAP_X+t_x-1] == 0) return 5; } case 6: { if(buffMap[(t_z+1)*MAP_X+t_x-1] == 0) return 6; } case 7: { if(buffMap[(t_z+1)*MAP_X+t_x] == 0) return 7; } case 8: if(buffMap[(t_z+1)*MAP_X+t_x+1] == 0) return 8; default: return 0; } }
20.673171
134
0.475224
ycsoft
c663069e51486f921da516fb37120d1ba02b2955
3,289
cpp
C++
src/controller.cpp
hrandib/pc_fancontrol
74fd5e38a7910144bfcf5fe690ad4b22c7356c91
[ "MIT" ]
null
null
null
src/controller.cpp
hrandib/pc_fancontrol
74fd5e38a7910144bfcf5fe690ad4b22c7356c91
[ "MIT" ]
4
2020-12-22T17:48:49.000Z
2021-02-20T21:48:24.000Z
src/controller.cpp
hrandib/pc_fancontrol
74fd5e38a7910144bfcf5fe690ad4b22c7356c91
[ "MIT" ]
null
null
null
/* * Copyright (c) 2020 Dmytro Shestakov * * 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 "controller.h" std::atomic_bool Controller::breakExecution_; void Controller::handle() { while(!breakExecution_) { int temp = getHighestTemp(); samples_.add(temp); double meanValue = samples_.getMean(); double setpoint = algo_->getSetpoint(meanValue); if(temp != previousDegreeValue_ && setpoint > -1) { previousDegreeValue_ = temp; std::cout << name_ << " Peak: " << temp << " Mean: " << round(meanValue * 10) / 10 << " | " << round(setpoint * 10) / 10 << "% pwm" << std::endl; } setAllPwms(setpoint, algo_->getNormalizedTemperature(meanValue)); std::this_thread::sleep_for(ms(config_.getPollConfig().timeMsecs)); } } int32_t Controller::getHighestTemp() { auto sensors = config_.getSensors(); auto highest = std::max_element( sensors.cbegin(), sensors.cend(), [](const auto& a, const auto& b) { return a->get() < b->get(); }); return (*highest)->get(); } void Controller::setAllPwms(double value, int tempOffset) { for(auto& pwm : config_.getPwms()) { pwm->set(value, tempOffset, name_); } } Controller::Controller(const Controller::string& name, ConfigEntry& conf) : name_{name}, config_{std::move(conf)}, samples_(static_cast<size_t>(conf.getPollConfig().samplesCount)), previousDegreeValue_{} { switch(conf.getMode()) { case ConfigEntry::SETMODE_TWO_POINT: { ConfigEntry::TwoPointConfMode mode = std::get<ConfigEntry::SETMODE_TWO_POINT>(config_.getModeConfig()); algo_ = std::make_unique<AlgoTwoPoint>(mode.temp_a, mode.temp_b); } break; case ConfigEntry::SETMODE_MULTI_POINT: { ConfigEntry::MultiPointConfMode mode = std::get<ConfigEntry::SETMODE_MULTI_POINT>(config_.getModeConfig()); algo_ = std::make_unique<AlgoMultiPoint>(mode.pointVec); } break; case ConfigEntry::SETMODE_PI: { ConfigEntry::PiConfMode mode = std::get<ConfigEntry::SETMODE_PI>(config_.getModeConfig()); algo_ = std::make_unique<AlgoPI>(mode.temp, mode.kp, mode.ki, mode.max_i); } break; } }
42.166667
119
0.678322
hrandib
c66a191d6ceb80358468f251110a58e922d8cb28
837
cpp
C++
example/mallocTrim.cpp
weiboad/adbase
d37ed32b55da24f7799be286c860e280ee0c786a
[ "Apache-2.0" ]
62
2017-02-15T11:36:46.000Z
2022-03-14T09:11:10.000Z
example/mallocTrim.cpp
AraHaan/adbase
d37ed32b55da24f7799be286c860e280ee0c786a
[ "Apache-2.0" ]
5
2017-02-21T05:32:14.000Z
2017-05-21T13:15:07.000Z
example/mallocTrim.cpp
AraHaan/adbase
d37ed32b55da24f7799be286c860e280ee0c786a
[ "Apache-2.0" ]
22
2017-02-16T02:11:25.000Z
2020-02-12T18:12:44.000Z
#include <adbase/Logging.hpp> #include <unordered_map> void printMallInfo() { std::unordered_map<std::string, int> info = adbase::mallInfo(); for (auto &t : info) { LOG_INFO << t.first << ":" << t.second; } } int main(void) { std::unordered_map<std::string, std::string> data; printMallInfo(); for (int i = 0; i < 100000; i++) { std::string key = "key" + std::to_string(i); std::string value = key + std::to_string(i); data[key] = value; } printMallInfo(); for (int i = 0; i < 100000; i++) { std::string key = "key" + std::to_string(i); data.erase(key); } printMallInfo(); adbase::mallocTrim(128 * 1024); printMallInfo(); while(1) { std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } return 0; }
23.25
70
0.55675
weiboad
c670bc3965a2be20b24cb8a93e96815a144d34c2
37,190
hpp
C++
src/libtriton/includes/triton/api.hpp
thebabush/Triton
a9d4b9a88ae946d88b81b054aab375bb2cba9ef4
[ "Apache-2.0" ]
1
2019-09-26T16:57:57.000Z
2019-09-26T16:57:57.000Z
src/libtriton/includes/triton/api.hpp
thebabush/Triton
a9d4b9a88ae946d88b81b054aab375bb2cba9ef4
[ "Apache-2.0" ]
null
null
null
src/libtriton/includes/triton/api.hpp
thebabush/Triton
a9d4b9a88ae946d88b81b054aab375bb2cba9ef4
[ "Apache-2.0" ]
null
null
null
//! \file /* ** Copyright (C) - Triton ** ** This program is under the terms of the BSD License. */ #ifndef TRITON_API_H #define TRITON_API_H #include <triton/architecture.hpp> #include <triton/ast.hpp> #include <triton/astContext.hpp> #include <triton/astRepresentation.hpp> #include <triton/callbacks.hpp> #include <triton/dllexport.hpp> #include <triton/immediate.hpp> #include <triton/instruction.hpp> #include <triton/irBuilder.hpp> #include <triton/memoryAccess.hpp> #include <triton/modes.hpp> #include <triton/operandWrapper.hpp> #include <triton/register.hpp> #include <triton/registers_e.hpp> #include <triton/solverEngine.hpp> #include <triton/symbolicEngine.hpp> #include <triton/taintEngine.hpp> #include <triton/tritonTypes.hpp> #include <triton/z3Interface.hpp> //! The Triton namespace namespace triton { /*! * \addtogroup triton * @{ */ /*! \class API * \brief This is used as C++ API. */ class API { protected: //! The Callbacks interface. triton::callbacks::Callbacks callbacks; //! The architecture entry. triton::arch::Architecture arch; //! The modes. triton::modes::Modes modes; //! The taint engine. triton::engines::taint::TaintEngine* taint = nullptr; //! The symbolic engine. triton::engines::symbolic::SymbolicEngine* symbolic = nullptr; //! The solver engine. triton::engines::solver::SolverEngine* solver = nullptr; //! The AST Context interface. triton::ast::AstContext astCtxt; //! The IR builder. triton::arch::IrBuilder* irBuilder = nullptr; //! The Z3 interface between Triton and Z3. triton::ast::Z3Interface* z3Interface = nullptr; public: //! Constructor of the API. TRITON_EXPORT API(); //! Destructor of the API. TRITON_EXPORT ~API(); /* Architecture API ============================================================================== */ //! [**Architecture api**] - Returns true if the architecture is valid. TRITON_EXPORT bool isArchitectureValid(void) const; //! [**architecture api**] - Returns the architecture as triton::arch::architectures_e. TRITON_EXPORT triton::arch::architectures_e getArchitecture(void) const; //! [**architecture api**] - Raises an exception if the architecture is not initialized. TRITON_EXPORT void checkArchitecture(void) const; //! [**architecture api**] - Returns the CPU instance. TRITON_EXPORT triton::arch::CpuInterface* getCpu(void); //! [**architecture api**] - Initializes an architecture. \sa triton::arch::architectures_e. TRITON_EXPORT void setArchitecture(triton::arch::architectures_e arch); //! [**architecture api**] - Clears the architecture states (registers and memory). TRITON_EXPORT void clearArchitecture(void); //! [**architecture api**] - Returns true if the register id is a flag. \sa triton::arch::x86::registers_e. TRITON_EXPORT bool isFlag(triton::arch::registers_e regId) const; //! [**architecture api**] - Returns true if the register id is a flag. TRITON_EXPORT bool isFlag(const triton::arch::Register& reg) const; //! [**architecture api**] - Returns true if the regId is a register. \sa triton::arch::x86::registers_e. TRITON_EXPORT bool isRegister(triton::arch::registers_e regId) const; //! [**architecture api**] - Returns true if the regId is a register. TRITON_EXPORT bool isRegister(const triton::arch::Register& reg) const; //! [**architecture api**] - Returns Register from regId. TRITON_EXPORT const triton::arch::Register& getRegister(triton::arch::registers_e id) const; //! [**architecture api**] - Returns parent Register from a register. TRITON_EXPORT const triton::arch::Register& getParentRegister(const triton::arch::Register& reg) const; //! [**architecture api**] - Returns parent Register from regId. TRITON_EXPORT const triton::arch::Register& getParentRegister(triton::arch::registers_e id) const; //! [**architecture api**] - Returns true if the regId is a register or a flag. \sa triton::arch::x86::registers_e. TRITON_EXPORT bool isRegisterValid(triton::arch::registers_e regId) const; //! [**architecture api**] - Returns true if the regId is a register or a flag. TRITON_EXPORT bool isRegisterValid(const triton::arch::Register& reg) const; //! [**architecture api**] - Returns the max size (in bit) of the CPU register (GPR). TRITON_EXPORT triton::uint32 getRegisterBitSize(void) const; //! [**architecture api**] - Returns the max size (in byte) of the CPU register (GPR). TRITON_EXPORT triton::uint32 getRegisterSize(void) const; //! [**architecture api**] - Returns the number of registers according to the CPU architecture. TRITON_EXPORT triton::uint32 getNumberOfRegisters(void) const; //! [**architecture api**] - Returns all registers. \sa triton::arch::x86::registers_e. TRITON_EXPORT const std::unordered_map<triton::arch::registers_e, const triton::arch::Register>& getAllRegisters(void) const; //! [**architecture api**] - Returns all parent registers. \sa triton::arch::x86::registers_e. TRITON_EXPORT std::set<const triton::arch::Register*> getParentRegisters(void) const; //! [**architecture api**] - Returns the concrete value of a memory cell. TRITON_EXPORT triton::uint8 getConcreteMemoryValue(triton::uint64 addr, bool execCallbacks=true) const; //! [**architecture api**] - Returns the concrete value of memory cells. TRITON_EXPORT triton::uint512 getConcreteMemoryValue(const triton::arch::MemoryAccess& mem, bool execCallbacks=true) const; //! [**architecture api**] - Returns the concrete value of a memory area. TRITON_EXPORT std::vector<triton::uint8> getConcreteMemoryAreaValue(triton::uint64 baseAddr, triton::usize size, bool execCallbacks=true) const; //! [**architecture api**] - Returns the concrete value of a register. TRITON_EXPORT triton::uint512 getConcreteRegisterValue(const triton::arch::Register& reg, bool execCallbacks=true) const; /*! * \brief [**architecture api**] - Sets the concrete value of a memory cell. * * \details Note that by setting a concrete value will probably imply a desynchronization * with the symbolic state (if it exists). You should probably use the concretize functions after this. */ TRITON_EXPORT void setConcreteMemoryValue(triton::uint64 addr, triton::uint8 value); /*! * \brief [**architecture api**] - Sets the concrete value of memory cells. * * \details Note that by setting a concrete value will probably imply a desynchronization * with the symbolic state (if it exists). You should probably use the concretize functions after this. */ TRITON_EXPORT void setConcreteMemoryValue(const triton::arch::MemoryAccess& mem, const triton::uint512& value); /*! * \brief [**architecture api**] - Sets the concrete value of a memory area. * * \details Note that by setting a concrete value will probably imply a desynchronization * with the symbolic state (if it exists). You should probably use the concretize functions after this. */ TRITON_EXPORT void setConcreteMemoryAreaValue(triton::uint64 baseAddr, const std::vector<triton::uint8>& values); /*! * \brief [**architecture api**] - Sets the concrete value of a memory area. * * \details Note that by setting a concrete value will probably imply a desynchronization * with the symbolic state (if it exists). You should probably use the concretize functions after this. */ TRITON_EXPORT void setConcreteMemoryAreaValue(triton::uint64 baseAddr, const triton::uint8* area, triton::usize size); /*! * \brief [**architecture api**] - Sets the concrete value of a register. * * \details Note that by setting a concrete value will probably imply a desynchronization * with the symbolic state (if it exists). You should probably use the concretize functions after this. */ TRITON_EXPORT void setConcreteRegisterValue(const triton::arch::Register& reg, const triton::uint512& value); //! [**architecture api**] - Returns true if the range `[baseAddr:size]` is mapped into the internal memory representation. \sa getConcreteMemoryValue() and getConcreteMemoryAreaValue(). TRITON_EXPORT bool isMemoryMapped(triton::uint64 baseAddr, triton::usize size=1); //! [**architecture api**] - Removes the range `[baseAddr:size]` from the internal memory representation. \sa isMemoryMapped(). TRITON_EXPORT void unmapMemory(triton::uint64 baseAddr, triton::usize size=1); //! [**architecture api**] - Disassembles the instruction and setup operands. You must define an architecture before. \sa processing(). TRITON_EXPORT void disassembly(triton::arch::Instruction& inst) const; /* Processing API ================================================================================ */ //! [**proccesing api**] - Processes an instruction and updates engines according to the instruction semantics. Returns true if the instruction is supported. TRITON_EXPORT bool processing(triton::arch::Instruction& inst); //! [**proccesing api**] - Initializes everything. TRITON_EXPORT void initEngines(void); //! [**proccesing api**] - Removes everything. TRITON_EXPORT void removeEngines(void); //! [**proccesing api**] - Resets everything. TRITON_EXPORT void reset(void); /* IR API ======================================================================================== */ //! [**IR builder api**] - Raises an exception if the IR builder is not initialized. TRITON_EXPORT void checkIrBuilder(void) const; //! [**IR builder api**] - Builds the instruction semantics. Returns true if the instruction is supported. You must define an architecture before. \sa processing(). TRITON_EXPORT bool buildSemantics(triton::arch::Instruction& inst); //! [**IR builder api**] - Returns the AST context. Used as AST builder. TRITON_EXPORT triton::ast::AstContext& getAstContext(void); /* AST Garbage Collector API ===================================================================== */ //! [**AST garbage collector api**] - Go through every allocated nodes and free them. TRITON_EXPORT void freeAllAstNodes(void); //! [**AST garbage collector api**] - Frees a set of nodes and removes them from the global container. TRITON_EXPORT void freeAstNodes(std::set<triton::ast::AbstractNode*>& nodes); //! [**AST garbage collector api**] - Extracts all unique nodes from a partial AST into the uniqueNodes set. TRITON_EXPORT void extractUniqueAstNodes(std::set<triton::ast::AbstractNode*>& uniqueNodes, triton::ast::AbstractNode* root) const; //! [**AST garbage collector api**] - Records the allocated node or returns the same node if it already exists inside the dictionaries. TRITON_EXPORT triton::ast::AbstractNode* recordAstNode(triton::ast::AbstractNode* node); //! [**AST garbage collector api**] - Records a variable AST node. TRITON_EXPORT void recordVariableAstNode(const std::string& name, triton::ast::AbstractNode* node); //! [**AST garbage collector api**] - Returns all allocated nodes. TRITON_EXPORT const std::set<triton::ast::AbstractNode*>& getAllocatedAstNodes(void) const; //! [**AST garbage collector api**] - Returns all stats about AST Dictionaries. TRITON_EXPORT std::map<std::string, triton::usize> getAstDictionariesStats(void) const; //! [**AST garbage collector api**] - Returns all variable nodes recorded. TRITON_EXPORT const std::map<std::string, std::vector<triton::ast::AbstractNode*>>& getAstVariableNodes(void) const; //! [**AST garbage collector api**] - Returns the node of a recorded variable. TRITON_EXPORT std::vector<triton::ast::AbstractNode*> getAstVariableNode(const std::string& name) const; //! [**AST garbage collector api**] - Sets all allocated nodes. TRITON_EXPORT void setAllocatedAstNodes(const std::set<triton::ast::AbstractNode*>& nodes); //! [**AST garbage collector api**] - Sets all variable nodes recorded. TRITON_EXPORT void setAstVariableNodes(const std::map<std::string, std::vector<triton::ast::AbstractNode*>>& nodes); /* AST Representation API ======================================================================== */ //! [**AST representation api**] - Returns the AST representation mode as triton::ast::representations::mode_e. TRITON_EXPORT triton::uint32 getAstRepresentationMode(void) const; //! [**AST representation api**] - Sets the AST representation mode. TRITON_EXPORT void setAstRepresentationMode(triton::uint32 mode); /* Callbacks API ================================================================================= */ //! [**callbacks api**] - Adds a GET_CONCRETE_MEMORY_VALUE callback. TRITON_EXPORT void addCallback(triton::callbacks::getConcreteMemoryValueCallback cb); //! [**callbacks api**] - Adds a GET_CONCRETE_REGISTER_VALUE callback. TRITON_EXPORT void addCallback(triton::callbacks::getConcreteRegisterValueCallback cb); //! [**callbacks api**] - Adds a SYMBOLIC_SIMPLIFICATION callback. TRITON_EXPORT void addCallback(triton::callbacks::symbolicSimplificationCallback cb); //! [**callbacks api**] - Removes all recorded callbacks. TRITON_EXPORT void removeAllCallbacks(void); //! [**callbacks api**] - Deletes a GET_CONCRETE_MEMORY_VALUE callback. TRITON_EXPORT void removeCallback(triton::callbacks::getConcreteMemoryValueCallback cb); //! [**callbacks api**] - Deletes a GET_CONCRETE_REGISTER_VALUE callback. TRITON_EXPORT void removeCallback(triton::callbacks::getConcreteRegisterValueCallback cb); //! [**callbacks api**] - Deletes a SYMBOLIC_SIMPLIFICATION callback. TRITON_EXPORT void removeCallback(triton::callbacks::symbolicSimplificationCallback cb); //! [**callbacks api**] - Processes callbacks according to the kind and the C++ polymorphism. TRITON_EXPORT triton::ast::AbstractNode* processCallbacks(triton::callbacks::callback_e kind, triton::ast::AbstractNode* node) const; //! [**callbacks api**] - Processes callbacks according to the kind and the C++ polymorphism. TRITON_EXPORT void processCallbacks(triton::callbacks::callback_e kind, const triton::arch::MemoryAccess& mem) const; //! [**callbacks api**] - Processes callbacks according to the kind and the C++ polymorphism. TRITON_EXPORT void processCallbacks(triton::callbacks::callback_e kind, const triton::arch::Register& reg) const; /* Modes API====================================================================================== */ //! [**modes api**] - Raises an exception if modes interface is not initialized. TRITON_EXPORT void checkModes(void) const; //! [**modes api**] - Enables or disables a specific mode. TRITON_EXPORT void enableMode(enum triton::modes::mode_e mode, bool flag); //! [**modes api**] - Returns true if the mode is enabled. TRITON_EXPORT bool isModeEnabled(enum triton::modes::mode_e mode) const; /* Symbolic engine API =========================================================================== */ //! [**symbolic api**] - Raises an exception if the symbolic engine is not initialized. TRITON_EXPORT void checkSymbolic(void) const; //! [**symbolic api**] - Returns the instance of the symbolic engine. TRITON_EXPORT triton::engines::symbolic::SymbolicEngine* getSymbolicEngine(void); //! [**symbolic api**] - Returns the map of symbolic registers defined. TRITON_EXPORT std::map<triton::arch::registers_e, triton::engines::symbolic::SymbolicExpression*> getSymbolicRegisters(void) const; //! [**symbolic api**] - Returns the map (<Addr : SymExpr>) of symbolic memory defined. TRITON_EXPORT std::map<triton::uint64, triton::engines::symbolic::SymbolicExpression*> getSymbolicMemory(void) const; //! [**symbolic api**] - Returns the symbolic expression id corresponding to the memory address. TRITON_EXPORT triton::usize getSymbolicMemoryId(triton::uint64 addr) const; //! [**symbolic api**] - Returns the symbolic expression id corresponding to the register. TRITON_EXPORT triton::usize getSymbolicRegisterId(const triton::arch::Register& reg) const; //! [**symbolic api**] - Returns the symbolic memory value. TRITON_EXPORT triton::uint8 getSymbolicMemoryValue(triton::uint64 address); //! [**symbolic api**] - Returns the symbolic memory value. TRITON_EXPORT triton::uint512 getSymbolicMemoryValue(const triton::arch::MemoryAccess& mem); //! [**symbolic api**] - Returns the symbolic values of a memory area. TRITON_EXPORT std::vector<triton::uint8> getSymbolicMemoryAreaValue(triton::uint64 baseAddr, triton::usize size); //! [**symbolic api**] - Returns the symbolic register value. TRITON_EXPORT triton::uint512 getSymbolicRegisterValue(const triton::arch::Register& reg); //! [**symbolic api**] - Converts a symbolic expression to a symbolic variable. `symVarSize` must be in bits. TRITON_EXPORT triton::engines::symbolic::SymbolicVariable* convertExpressionToSymbolicVariable(triton::usize exprId, triton::uint32 symVarSize, const std::string& symVarComment=""); //! [**symbolic api**] - Converts a symbolic memory expression to a symbolic variable. TRITON_EXPORT triton::engines::symbolic::SymbolicVariable* convertMemoryToSymbolicVariable(const triton::arch::MemoryAccess& mem, const std::string& symVarComment=""); //! [**symbolic api**] - Converts a symbolic register expression to a symbolic variable. TRITON_EXPORT triton::engines::symbolic::SymbolicVariable* convertRegisterToSymbolicVariable(const triton::arch::Register& reg, const std::string& symVarComment=""); //! [**symbolic api**] - Returns a symbolic operand. TRITON_EXPORT triton::ast::AbstractNode* buildSymbolicOperand(const triton::arch::OperandWrapper& op); //! [**symbolic api**] - Returns a symbolic operand. TRITON_EXPORT triton::ast::AbstractNode* buildSymbolicOperand(triton::arch::Instruction& inst, const triton::arch::OperandWrapper& op); //! [**symbolic api**] - Returns an immediate symbolic. TRITON_EXPORT triton::ast::AbstractNode* buildSymbolicImmediate(const triton::arch::Immediate& imm); //! [**symbolic api**] - Returns an immediate symbolic and defines the immediate as input of the instruction.. TRITON_EXPORT triton::ast::AbstractNode* buildSymbolicImmediate(triton::arch::Instruction& inst, const triton::arch::Immediate& imm); //! [**symbolic api**] - Returns a symbolic memory cell. TRITON_EXPORT triton::ast::AbstractNode* buildSymbolicMemory(const triton::arch::MemoryAccess& mem); //! [**symbolic api**] - Returns a symbolic memory cell and defines the memory cell as input of the instruction. TRITON_EXPORT triton::ast::AbstractNode* buildSymbolicMemory(triton::arch::Instruction& inst, const triton::arch::MemoryAccess& mem); //! [**symbolic api**] - Returns a symbolic register. TRITON_EXPORT triton::ast::AbstractNode* buildSymbolicRegister(const triton::arch::Register& reg); //! [**symbolic api**] - Returns a symbolic register and defines the register as input of the instruction. TRITON_EXPORT triton::ast::AbstractNode* buildSymbolicRegister(triton::arch::Instruction& inst, const triton::arch::Register& reg); //! [**symbolic api**] - Returns a new symbolic expression. Note that if there are simplification passes recorded, simplification will be applied. TRITON_EXPORT triton::engines::symbolic::SymbolicExpression* newSymbolicExpression(triton::ast::AbstractNode* node, const std::string& comment=""); //! [**symbolic api**] - Returns a new symbolic variable. TRITON_EXPORT triton::engines::symbolic::SymbolicVariable* newSymbolicVariable(triton::uint32 varSize, const std::string& comment=""); //! [**symbolic api**] - Removes the symbolic expression corresponding to the id. TRITON_EXPORT void removeSymbolicExpression(triton::usize symExprId); //! [**symbolic api**] - Returns the new symbolic abstract expression and links this expression to the instruction. TRITON_EXPORT triton::engines::symbolic::SymbolicExpression* createSymbolicExpression(triton::arch::Instruction& inst, triton::ast::AbstractNode* node, const triton::arch::OperandWrapper& dst, const std::string& comment=""); //! [**symbolic api**] - Returns the new symbolic memory expression and links this expression to the instruction. TRITON_EXPORT triton::engines::symbolic::SymbolicExpression* createSymbolicMemoryExpression(triton::arch::Instruction& inst, triton::ast::AbstractNode* node, const triton::arch::MemoryAccess& mem, const std::string& comment=""); //! [**symbolic api**] - Returns the new symbolic register expression and links this expression to the instruction. TRITON_EXPORT triton::engines::symbolic::SymbolicExpression* createSymbolicRegisterExpression(triton::arch::Instruction& inst, triton::ast::AbstractNode* node, const triton::arch::Register& reg, const std::string& comment=""); //! [**symbolic api**] - Returns the new symbolic flag expression and links this expression to the instruction. TRITON_EXPORT triton::engines::symbolic::SymbolicExpression* createSymbolicFlagExpression(triton::arch::Instruction& inst, triton::ast::AbstractNode* node, const triton::arch::Register& flag, const std::string& comment=""); //! [**symbolic api**] - Returns the new symbolic volatile expression and links this expression to the instruction. TRITON_EXPORT triton::engines::symbolic::SymbolicExpression* createSymbolicVolatileExpression(triton::arch::Instruction& inst, triton::ast::AbstractNode* node, const std::string& comment=""); //! [**symbolic api**] - Assigns a symbolic expression to a memory. TRITON_EXPORT void assignSymbolicExpressionToMemory(triton::engines::symbolic::SymbolicExpression* se, const triton::arch::MemoryAccess& mem); //! [**symbolic api**] - Assigns a symbolic expression to a register. TRITON_EXPORT void assignSymbolicExpressionToRegister(triton::engines::symbolic::SymbolicExpression* se, const triton::arch::Register& reg); //! [**symbolic api**] - Processes all recorded simplifications. Returns the simplified node. TRITON_EXPORT triton::ast::AbstractNode* processSimplification(triton::ast::AbstractNode* node, bool z3=false) const; //! [**symbolic api**] - Returns the symbolic expression corresponding to an id. TRITON_EXPORT triton::engines::symbolic::SymbolicExpression* getSymbolicExpressionFromId(triton::usize symExprId) const; //! [**symbolic api**] - Returns the symbolic variable corresponding to the symbolic variable id. TRITON_EXPORT triton::engines::symbolic::SymbolicVariable* getSymbolicVariableFromId(triton::usize symVarId) const; //! [**symbolic api**] - Returns the symbolic variable corresponding to the symbolic variable name. TRITON_EXPORT triton::engines::symbolic::SymbolicVariable* getSymbolicVariableFromName(const std::string& symVarName) const; //! [**symbolic api**] - Returns the logical conjunction vector of path constraints. TRITON_EXPORT const std::vector<triton::engines::symbolic::PathConstraint>& getPathConstraints(void) const; //! [**symbolic api**] - Returns the logical conjunction AST of path constraints. TRITON_EXPORT triton::ast::AbstractNode* getPathConstraintsAst(void); //! [**symbolic api**] - Adds a path constraint. TRITON_EXPORT void addPathConstraint(const triton::arch::Instruction& inst, triton::engines::symbolic::SymbolicExpression* expr); //! [**symbolic api**] - Clears the logical conjunction vector of path constraints. TRITON_EXPORT void clearPathConstraints(void); //! [**symbolic api**] - Enables or disables the symbolic execution engine. TRITON_EXPORT void enableSymbolicEngine(bool flag); //! [**symbolic api**] - Returns true if the symbolic execution engine is enabled. TRITON_EXPORT bool isSymbolicEngineEnabled(void) const; //! [**symbolic api**] - Returns true if the symbolic expression ID exists. TRITON_EXPORT bool isSymbolicExpressionIdExists(triton::usize symExprId) const; //! [**symbolic api**] - Returns true if memory cell expressions contain symbolic variables. TRITON_EXPORT bool isMemorySymbolized(const triton::arch::MemoryAccess& mem) const; //! [**symbolic api**] - Returns true if memory cell expressions contain symbolic variables. TRITON_EXPORT bool isMemorySymbolized(triton::uint64 addr, triton::uint32 size=1) const; //! [**symbolic api**] - Returns true if the register expression contains a symbolic variable. TRITON_EXPORT bool isRegisterSymbolized(const triton::arch::Register& reg) const; //! [**symbolic api**] - Concretizes all symbolic memory references. TRITON_EXPORT void concretizeAllMemory(void); //! [**symbolic api**] - Concretizes all symbolic register references. TRITON_EXPORT void concretizeAllRegister(void); //! [**symbolic api**] - Concretizes a specific symbolic memory reference. TRITON_EXPORT void concretizeMemory(const triton::arch::MemoryAccess& mem); //! [**symbolic api**] - Concretizes a specific symbolic memory reference. TRITON_EXPORT void concretizeMemory(triton::uint64 addr); //! [**symbolic api**] - Concretizes a specific symbolic register reference. TRITON_EXPORT void concretizeRegister(const triton::arch::Register& reg); //! [**symbolic api**] - Returns the partial AST from a symbolic expression id. TRITON_EXPORT triton::ast::AbstractNode* getAstFromId(triton::usize symExprId); //! [**symbolic api**] - Unrolls the SSA form of a given AST. TRITON_EXPORT triton::ast::AbstractNode* unrollAst(triton::ast::AbstractNode* node); //! [**symbolic api**] - Unrolls the SSA form of a given symbolic expression id. TRITON_EXPORT triton::ast::AbstractNode* unrollAstFromId(triton::usize symExprId); //! [**symbolic api**] - Slices all expressions from a given one. TRITON_EXPORT std::map<triton::usize, triton::engines::symbolic::SymbolicExpression*> sliceExpressions(triton::engines::symbolic::SymbolicExpression* expr); //! [**symbolic api**] - Returns the list of the tainted symbolic expressions. TRITON_EXPORT std::list<triton::engines::symbolic::SymbolicExpression*> getTaintedSymbolicExpressions(void) const; //! [**symbolic api**] - Returns all symbolic expressions as a map of <SymExprId : SymExpr> TRITON_EXPORT const std::map<triton::usize, triton::engines::symbolic::SymbolicExpression*>& getSymbolicExpressions(void) const; //! [**symbolic api**] - Returns all symbolic variables as a map of <SymVarId : SymVar> TRITON_EXPORT const std::map<triton::usize, triton::engines::symbolic::SymbolicVariable*>& getSymbolicVariables(void) const; //! [**symbolic api**] - Gets the concrete value of a symbolic variable. TRITON_EXPORT const triton::uint512& getConcreteSymbolicVariableValue(const triton::engines::symbolic::SymbolicVariable& symVar) const; //! [**symbolic api**] - Sets the concrete value of a symbolic variable. TRITON_EXPORT void setConcreteSymbolicVariableValue(const triton::engines::symbolic::SymbolicVariable& symVar, const triton::uint512& value); /* Solver engine API ============================================================================= */ //! [**solver api**] - Raises an exception if the solver engine is not initialized. TRITON_EXPORT void checkSolver(void) const; /*! * \brief [**solver api**] - Computes and returns a model from a symbolic constraint. * * \details * **item1**: symbolic variable id<br> * **item2**: model */ TRITON_EXPORT std::map<triton::uint32, triton::engines::solver::SolverModel> getModel(triton::ast::AbstractNode* node) const; /*! * \brief [**solver api**] - Computes and returns several models from a symbolic constraint. The `limit` is the number of models returned. * * \details * **item1**: symbolic variable id<br> * **item2**: model */ TRITON_EXPORT std::list<std::map<triton::uint32, triton::engines::solver::SolverModel>> getModels(triton::ast::AbstractNode* node, triton::uint32 limit) const; /* Z3 interface API ============================================================================== */ //! [**z3 api**] - Raises an exception if the z3 interface is not initialized. TRITON_EXPORT void checkZ3Interface(void) const; //! [**z3 api**] - Evaluates a Triton's AST via Z3 and returns a concrete value. TRITON_EXPORT triton::uint512 evaluateAstViaZ3(triton::ast::AbstractNode* node) const; //! [**z3 api**] - Converts a Triton's AST to a Z3's AST, perform a Z3 simplification and returns a Triton's AST. TRITON_EXPORT triton::ast::AbstractNode* processZ3Simplification(triton::ast::AbstractNode* node) const; /* Taint engine API ============================================================================== */ //! [**taint api**] - Raises an exception if the taint engine is not initialized. TRITON_EXPORT void checkTaint(void) const; //! [**taint api**] - Returns the instance of the taint engine. TRITON_EXPORT triton::engines::taint::TaintEngine* getTaintEngine(void); //! [**taint api**] - Returns the tainted addresses. TRITON_EXPORT const std::set<triton::uint64>& getTaintedMemory(void) const; //! [**taint api**] - Returns the tainted registers. TRITON_EXPORT std::set<const triton::arch::Register*> getTaintedRegisters(void) const; //! [**taint api**] - Enables or disables the taint engine. TRITON_EXPORT void enableTaintEngine(bool flag); //! [**taint api**] - Returns true if the taint engine is enabled. TRITON_EXPORT bool isTaintEngineEnabled(void) const; //! [**taint api**] - Abstract taint verification. Returns true if the operand is tainted. TRITON_EXPORT bool isTainted(const triton::arch::OperandWrapper& op) const; //! [**taint api**] - Returns true if the address:size is tainted. TRITON_EXPORT bool isMemoryTainted(triton::uint64 addr, triton::uint32 size=1) const; //! [**taint api**] - Returns true if the memory is tainted. TRITON_EXPORT bool isMemoryTainted(const triton::arch::MemoryAccess& mem) const; //! [**taint api**] - Returns true if the register is tainted. TRITON_EXPORT bool isRegisterTainted(const triton::arch::Register& reg) const; //! [**taint api**] - Sets the flag (taint or untaint) to an abstract operand (Register or Memory). TRITON_EXPORT bool setTaint(const triton::arch::OperandWrapper& op, bool flag); //! [**taint api**] - Sets the flag (taint or untaint) to a memory. TRITON_EXPORT bool setTaintMemory(const triton::arch::MemoryAccess& mem, bool flag); //! [**taint api**] - Sets the flag (taint or untaint) to a register. TRITON_EXPORT bool setTaintRegister(const triton::arch::Register& reg, bool flag); //! [**taint api**] - Taints an address. Returns TAINTED if the address has been tainted correctly. Otherwise it returns the last defined state. TRITON_EXPORT bool taintMemory(triton::uint64 addr); //! [**taint api**] - Taints a memory. Returns TAINTED if the memory has been tainted correctly. Otherwise it returns the last defined state. TRITON_EXPORT bool taintMemory(const triton::arch::MemoryAccess& mem); //! [**taint api**] - Taints a register. Returns TAINTED if the register has been tainted correctly. Otherwise it returns the last defined state. TRITON_EXPORT bool taintRegister(const triton::arch::Register& reg); //! [**taint api**] - Untaints an address. Returns !TAINTED if the address has been untainted correctly. Otherwise it returns the last defined state. TRITON_EXPORT bool untaintMemory(triton::uint64 addr); //! [**taint api**] - Untaints a memory. Returns !TAINTED if the memory has been untainted correctly. Otherwise it returns the last defined state. TRITON_EXPORT bool untaintMemory(const triton::arch::MemoryAccess& mem); //! [**taint api**] - Untaints a register. Returns !TAINTED if the register has been untainted correctly. Otherwise it returns the last defined state. TRITON_EXPORT bool untaintRegister(const triton::arch::Register& reg); //! [**taint api**] - Abstract union tainting. TRITON_EXPORT bool taintUnion(const triton::arch::OperandWrapper& op1, const triton::arch::OperandWrapper& op2); //! [**taint api**] - Abstract assignment tainting. TRITON_EXPORT bool taintAssignment(const triton::arch::OperandWrapper& op1, const triton::arch::OperandWrapper& op2); //! [**taint api**] - Taints MemoryImmediate with union. Returns true if the memDst is TAINTED. TRITON_EXPORT bool taintUnionMemoryImmediate(const triton::arch::MemoryAccess& memDst); //! [**taint api**] - Taints MemoryMemory with union. Returns true if the memDst or memSrc are TAINTED. TRITON_EXPORT bool taintUnionMemoryMemory(const triton::arch::MemoryAccess& memDst, const triton::arch::MemoryAccess& memSrc); //! [**taint api**] - Taints MemoryRegister with union. Returns true if the memDst or regSrc are TAINTED. TRITON_EXPORT bool taintUnionMemoryRegister(const triton::arch::MemoryAccess& memDst, const triton::arch::Register& regSrc); //! [**taint api**] - Taints RegisterImmediate with union. Returns true if the regDst is TAINTED. TRITON_EXPORT bool taintUnionRegisterImmediate(const triton::arch::Register& regDst); //! [**taint api**] - Taints RegisterMemory with union. Returns true if the regDst or memSrc are TAINTED. TRITON_EXPORT bool taintUnionRegisterMemory(const triton::arch::Register& regDst, const triton::arch::MemoryAccess& memSrc); //! [**taint api**] - Taints RegisterRegister with union. Returns true if the regDst or regSrc are TAINTED. TRITON_EXPORT bool taintUnionRegisterRegister(const triton::arch::Register& regDst, const triton::arch::Register& regSrc); //! [**taint api**] - Taints MemoryImmediate with assignment. Returns always false. TRITON_EXPORT bool taintAssignmentMemoryImmediate(const triton::arch::MemoryAccess& memDst); //! [**taint api**] - Taints MemoryMemory with assignment. Returns true if the memDst is tainted. TRITON_EXPORT bool taintAssignmentMemoryMemory(const triton::arch::MemoryAccess& memDst, const triton::arch::MemoryAccess& memSrc); //! [**taint api**] - Taints MemoryRegister with assignment. Returns true if the memDst is tainted. TRITON_EXPORT bool taintAssignmentMemoryRegister(const triton::arch::MemoryAccess& memDst, const triton::arch::Register& regSrc); //! [**taint api**] - Taints RegisterImmediate with assignment. Returns always false. TRITON_EXPORT bool taintAssignmentRegisterImmediate(const triton::arch::Register& regDst); //! [**taint api**] - Taints RegisterMemory with assignment. Returns true if the regDst is tainted. TRITON_EXPORT bool taintAssignmentRegisterMemory(const triton::arch::Register& regDst, const triton::arch::MemoryAccess& memSrc); //! [**taint api**] - Taints RegisterRegister with assignment. Returns true if the regDst is tainted. TRITON_EXPORT bool taintAssignmentRegisterRegister(const triton::arch::Register& regDst, const triton::arch::Register& regSrc); }; /*! @} End of triton namespace */ }; #endif /* TRITON_API_H */
56.865443
236
0.677198
thebabush
c670e5d05918c4a477525189faa382f6ce3ee177
15,251
cpp
C++
node/Poly1305.cpp
sundys/ZeroTierOne
269501eaa0c22bdc402e689b0d061325fb6ddbce
[ "RSA-MD" ]
8,205
2015-01-02T16:34:03.000Z
2022-03-31T18:18:28.000Z
node/Poly1305.cpp
sundys/ZeroTierOne
269501eaa0c22bdc402e689b0d061325fb6ddbce
[ "RSA-MD" ]
1,401
2015-01-01T05:45:53.000Z
2022-03-31T14:00:00.000Z
node/Poly1305.cpp
sundys/ZeroTierOne
269501eaa0c22bdc402e689b0d061325fb6ddbce
[ "RSA-MD" ]
1,243
2015-01-09T07:30:49.000Z
2022-03-31T12:36:48.000Z
/* 20080912 D. J. Bernstein Public domain. */ #include "Constants.hpp" #include "Poly1305.hpp" #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #ifdef __WINDOWS__ #pragma warning(disable: 4146) #endif namespace ZeroTier { namespace { typedef struct poly1305_context { size_t aligner; unsigned char opaque[136]; } poly1305_context; #if (defined(_MSC_VER) || defined(__GNUC__)) && (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__) || defined(_M_X64)) ////////////////////////////////////////////////////////////////////////////// // 128-bit implementation for MSC and GCC from Poly1305-donna #if defined(_MSC_VER) #include <intrin.h> typedef struct uint128_t { unsigned long long lo; unsigned long long hi; } uint128_t; #define MUL(out, x, y) out.lo = _umul128((x), (y), &out.hi) #define ADD(out, in) { unsigned long long t = out.lo; out.lo += in.lo; out.hi += (out.lo < t) + in.hi; } #define ADDLO(out, in) { unsigned long long t = out.lo; out.lo += in; out.hi += (out.lo < t); } #define SHR(in, shift) (__shiftright128(in.lo, in.hi, (shift))) #define LO(in) (in.lo) // #define POLY1305_NOINLINE __declspec(noinline) #elif defined(__GNUC__) #if defined(__SIZEOF_INT128__) typedef unsigned __int128 uint128_t; #else typedef unsigned uint128_t __attribute__((mode(TI))); #endif #define MUL(out, x, y) out = ((uint128_t)x * y) #define ADD(out, in) out += in #define ADDLO(out, in) out += in #define SHR(in, shift) (unsigned long long)(in >> (shift)) #define LO(in) (unsigned long long)(in) // #define POLY1305_NOINLINE __attribute__((noinline)) #endif #define poly1305_block_size 16 /* 17 + sizeof(size_t) + 8*sizeof(unsigned long long) */ typedef struct poly1305_state_internal_t { unsigned long long r[3]; unsigned long long h[3]; unsigned long long pad[2]; size_t leftover; unsigned char buffer[poly1305_block_size]; unsigned char final; } poly1305_state_internal_t; #if defined(ZT_NO_TYPE_PUNNING) || (__BYTE_ORDER != __LITTLE_ENDIAN) static inline unsigned long long U8TO64(const unsigned char *p) { return (((unsigned long long)(p[0] & 0xff) ) | ((unsigned long long)(p[1] & 0xff) << 8) | ((unsigned long long)(p[2] & 0xff) << 16) | ((unsigned long long)(p[3] & 0xff) << 24) | ((unsigned long long)(p[4] & 0xff) << 32) | ((unsigned long long)(p[5] & 0xff) << 40) | ((unsigned long long)(p[6] & 0xff) << 48) | ((unsigned long long)(p[7] & 0xff) << 56)); } #else #define U8TO64(p) (*reinterpret_cast<const unsigned long long *>(p)) #endif #if defined(ZT_NO_TYPE_PUNNING) || (__BYTE_ORDER != __LITTLE_ENDIAN) static inline void U64TO8(unsigned char *p, unsigned long long v) { p[0] = (v ) & 0xff; p[1] = (v >> 8) & 0xff; p[2] = (v >> 16) & 0xff; p[3] = (v >> 24) & 0xff; p[4] = (v >> 32) & 0xff; p[5] = (v >> 40) & 0xff; p[6] = (v >> 48) & 0xff; p[7] = (v >> 56) & 0xff; } #else #define U64TO8(p,v) ((*reinterpret_cast<unsigned long long *>(p)) = (v)) #endif static inline void poly1305_init(poly1305_context *ctx, const unsigned char key[32]) { poly1305_state_internal_t *st = (poly1305_state_internal_t *)ctx; unsigned long long t0,t1; /* r &= 0xffffffc0ffffffc0ffffffc0fffffff */ t0 = U8TO64(&key[0]); t1 = U8TO64(&key[8]); st->r[0] = ( t0 ) & 0xffc0fffffff; st->r[1] = ((t0 >> 44) | (t1 << 20)) & 0xfffffc0ffff; st->r[2] = ((t1 >> 24) ) & 0x00ffffffc0f; /* h = 0 */ st->h[0] = 0; st->h[1] = 0; st->h[2] = 0; /* save pad for later */ st->pad[0] = U8TO64(&key[16]); st->pad[1] = U8TO64(&key[24]); st->leftover = 0; st->final = 0; } static inline void poly1305_blocks(poly1305_state_internal_t *st, const unsigned char *m, size_t bytes) { const unsigned long long hibit = (st->final) ? 0 : ((unsigned long long)1 << 40); /* 1 << 128 */ unsigned long long r0,r1,r2; unsigned long long s1,s2; unsigned long long h0,h1,h2; unsigned long long c; uint128_t d0,d1,d2,d; r0 = st->r[0]; r1 = st->r[1]; r2 = st->r[2]; h0 = st->h[0]; h1 = st->h[1]; h2 = st->h[2]; s1 = r1 * (5 << 2); s2 = r2 * (5 << 2); while (bytes >= poly1305_block_size) { unsigned long long t0,t1; /* h += m[i] */ t0 = U8TO64(&m[0]); t1 = U8TO64(&m[8]); h0 += (( t0 ) & 0xfffffffffff); h1 += (((t0 >> 44) | (t1 << 20)) & 0xfffffffffff); h2 += (((t1 >> 24) ) & 0x3ffffffffff) | hibit; /* h *= r */ MUL(d0, h0, r0); MUL(d, h1, s2); ADD(d0, d); MUL(d, h2, s1); ADD(d0, d); MUL(d1, h0, r1); MUL(d, h1, r0); ADD(d1, d); MUL(d, h2, s2); ADD(d1, d); MUL(d2, h0, r2); MUL(d, h1, r1); ADD(d2, d); MUL(d, h2, r0); ADD(d2, d); /* (partial) h %= p */ c = SHR(d0, 44); h0 = LO(d0) & 0xfffffffffff; ADDLO(d1, c); c = SHR(d1, 44); h1 = LO(d1) & 0xfffffffffff; ADDLO(d2, c); c = SHR(d2, 42); h2 = LO(d2) & 0x3ffffffffff; h0 += c * 5; c = (h0 >> 44); h0 = h0 & 0xfffffffffff; h1 += c; m += poly1305_block_size; bytes -= poly1305_block_size; } st->h[0] = h0; st->h[1] = h1; st->h[2] = h2; } static inline void poly1305_finish(poly1305_context *ctx, unsigned char mac[16]) { poly1305_state_internal_t *st = (poly1305_state_internal_t *)ctx; unsigned long long h0,h1,h2,c; unsigned long long g0,g1,g2; unsigned long long t0,t1; /* process the remaining block */ if (st->leftover) { size_t i = st->leftover; st->buffer[i] = 1; for (i = i + 1; i < poly1305_block_size; i++) st->buffer[i] = 0; st->final = 1; poly1305_blocks(st, st->buffer, poly1305_block_size); } /* fully carry h */ h0 = st->h[0]; h1 = st->h[1]; h2 = st->h[2]; c = (h1 >> 44); h1 &= 0xfffffffffff; h2 += c; c = (h2 >> 42); h2 &= 0x3ffffffffff; h0 += c * 5; c = (h0 >> 44); h0 &= 0xfffffffffff; h1 += c; c = (h1 >> 44); h1 &= 0xfffffffffff; h2 += c; c = (h2 >> 42); h2 &= 0x3ffffffffff; h0 += c * 5; c = (h0 >> 44); h0 &= 0xfffffffffff; h1 += c; /* compute h + -p */ g0 = h0 + 5; c = (g0 >> 44); g0 &= 0xfffffffffff; g1 = h1 + c; c = (g1 >> 44); g1 &= 0xfffffffffff; g2 = h2 + c - ((unsigned long long)1 << 42); /* select h if h < p, or h + -p if h >= p */ c = (g2 >> ((sizeof(unsigned long long) * 8) - 1)) - 1; g0 &= c; g1 &= c; g2 &= c; c = ~c; h0 = (h0 & c) | g0; h1 = (h1 & c) | g1; h2 = (h2 & c) | g2; /* h = (h + pad) */ t0 = st->pad[0]; t1 = st->pad[1]; h0 += (( t0 ) & 0xfffffffffff) ; c = (h0 >> 44); h0 &= 0xfffffffffff; h1 += (((t0 >> 44) | (t1 << 20)) & 0xfffffffffff) + c; c = (h1 >> 44); h1 &= 0xfffffffffff; h2 += (((t1 >> 24) ) & 0x3ffffffffff) + c; h2 &= 0x3ffffffffff; /* mac = h % (2^128) */ h0 = ((h0 ) | (h1 << 44)); h1 = ((h1 >> 20) | (h2 << 24)); U64TO8(&mac[0], h0); U64TO8(&mac[8], h1); /* zero out the state */ st->h[0] = 0; st->h[1] = 0; st->h[2] = 0; st->r[0] = 0; st->r[1] = 0; st->r[2] = 0; st->pad[0] = 0; st->pad[1] = 0; } ////////////////////////////////////////////////////////////////////////////// #else ////////////////////////////////////////////////////////////////////////////// // More portable 64-bit implementation #define poly1305_block_size 16 /* 17 + sizeof(size_t) + 14*sizeof(unsigned long) */ typedef struct poly1305_state_internal_t { unsigned long r[5]; unsigned long h[5]; unsigned long pad[4]; size_t leftover; unsigned char buffer[poly1305_block_size]; unsigned char final; } poly1305_state_internal_t; /* interpret four 8 bit unsigned integers as a 32 bit unsigned integer in little endian */ static unsigned long U8TO32(const unsigned char *p) { return (((unsigned long)(p[0] & 0xff) ) | ((unsigned long)(p[1] & 0xff) << 8) | ((unsigned long)(p[2] & 0xff) << 16) | ((unsigned long)(p[3] & 0xff) << 24)); } /* store a 32 bit unsigned integer as four 8 bit unsigned integers in little endian */ static void U32TO8(unsigned char *p, unsigned long v) { p[0] = (v ) & 0xff; p[1] = (v >> 8) & 0xff; p[2] = (v >> 16) & 0xff; p[3] = (v >> 24) & 0xff; } static inline void poly1305_init(poly1305_context *ctx, const unsigned char key[32]) { poly1305_state_internal_t *st = (poly1305_state_internal_t *)ctx; /* r &= 0xffffffc0ffffffc0ffffffc0fffffff */ st->r[0] = (U8TO32(&key[ 0]) ) & 0x3ffffff; st->r[1] = (U8TO32(&key[ 3]) >> 2) & 0x3ffff03; st->r[2] = (U8TO32(&key[ 6]) >> 4) & 0x3ffc0ff; st->r[3] = (U8TO32(&key[ 9]) >> 6) & 0x3f03fff; st->r[4] = (U8TO32(&key[12]) >> 8) & 0x00fffff; /* h = 0 */ st->h[0] = 0; st->h[1] = 0; st->h[2] = 0; st->h[3] = 0; st->h[4] = 0; /* save pad for later */ st->pad[0] = U8TO32(&key[16]); st->pad[1] = U8TO32(&key[20]); st->pad[2] = U8TO32(&key[24]); st->pad[3] = U8TO32(&key[28]); st->leftover = 0; st->final = 0; } static inline void poly1305_blocks(poly1305_state_internal_t *st, const unsigned char *m, size_t bytes) { const unsigned long hibit = (st->final) ? 0 : (1 << 24); /* 1 << 128 */ unsigned long r0,r1,r2,r3,r4; unsigned long s1,s2,s3,s4; unsigned long h0,h1,h2,h3,h4; unsigned long long d0,d1,d2,d3,d4; unsigned long c; r0 = st->r[0]; r1 = st->r[1]; r2 = st->r[2]; r3 = st->r[3]; r4 = st->r[4]; s1 = r1 * 5; s2 = r2 * 5; s3 = r3 * 5; s4 = r4 * 5; h0 = st->h[0]; h1 = st->h[1]; h2 = st->h[2]; h3 = st->h[3]; h4 = st->h[4]; while (bytes >= poly1305_block_size) { /* h += m[i] */ h0 += (U8TO32(m+ 0) ) & 0x3ffffff; h1 += (U8TO32(m+ 3) >> 2) & 0x3ffffff; h2 += (U8TO32(m+ 6) >> 4) & 0x3ffffff; h3 += (U8TO32(m+ 9) >> 6) & 0x3ffffff; h4 += (U8TO32(m+12) >> 8) | hibit; /* h *= r */ d0 = ((unsigned long long)h0 * r0) + ((unsigned long long)h1 * s4) + ((unsigned long long)h2 * s3) + ((unsigned long long)h3 * s2) + ((unsigned long long)h4 * s1); d1 = ((unsigned long long)h0 * r1) + ((unsigned long long)h1 * r0) + ((unsigned long long)h2 * s4) + ((unsigned long long)h3 * s3) + ((unsigned long long)h4 * s2); d2 = ((unsigned long long)h0 * r2) + ((unsigned long long)h1 * r1) + ((unsigned long long)h2 * r0) + ((unsigned long long)h3 * s4) + ((unsigned long long)h4 * s3); d3 = ((unsigned long long)h0 * r3) + ((unsigned long long)h1 * r2) + ((unsigned long long)h2 * r1) + ((unsigned long long)h3 * r0) + ((unsigned long long)h4 * s4); d4 = ((unsigned long long)h0 * r4) + ((unsigned long long)h1 * r3) + ((unsigned long long)h2 * r2) + ((unsigned long long)h3 * r1) + ((unsigned long long)h4 * r0); /* (partial) h %= p */ c = (unsigned long)(d0 >> 26); h0 = (unsigned long)d0 & 0x3ffffff; d1 += c; c = (unsigned long)(d1 >> 26); h1 = (unsigned long)d1 & 0x3ffffff; d2 += c; c = (unsigned long)(d2 >> 26); h2 = (unsigned long)d2 & 0x3ffffff; d3 += c; c = (unsigned long)(d3 >> 26); h3 = (unsigned long)d3 & 0x3ffffff; d4 += c; c = (unsigned long)(d4 >> 26); h4 = (unsigned long)d4 & 0x3ffffff; h0 += c * 5; c = (h0 >> 26); h0 = h0 & 0x3ffffff; h1 += c; m += poly1305_block_size; bytes -= poly1305_block_size; } st->h[0] = h0; st->h[1] = h1; st->h[2] = h2; st->h[3] = h3; st->h[4] = h4; } static inline void poly1305_finish(poly1305_context *ctx, unsigned char mac[16]) { poly1305_state_internal_t *st = (poly1305_state_internal_t *)ctx; unsigned long h0,h1,h2,h3,h4,c; unsigned long g0,g1,g2,g3,g4; unsigned long long f; unsigned long mask; /* process the remaining block */ if (st->leftover) { size_t i = st->leftover; st->buffer[i++] = 1; for (; i < poly1305_block_size; i++) st->buffer[i] = 0; st->final = 1; poly1305_blocks(st, st->buffer, poly1305_block_size); } /* fully carry h */ h0 = st->h[0]; h1 = st->h[1]; h2 = st->h[2]; h3 = st->h[3]; h4 = st->h[4]; c = h1 >> 26; h1 = h1 & 0x3ffffff; h2 += c; c = h2 >> 26; h2 = h2 & 0x3ffffff; h3 += c; c = h3 >> 26; h3 = h3 & 0x3ffffff; h4 += c; c = h4 >> 26; h4 = h4 & 0x3ffffff; h0 += c * 5; c = h0 >> 26; h0 = h0 & 0x3ffffff; h1 += c; /* compute h + -p */ g0 = h0 + 5; c = g0 >> 26; g0 &= 0x3ffffff; g1 = h1 + c; c = g1 >> 26; g1 &= 0x3ffffff; g2 = h2 + c; c = g2 >> 26; g2 &= 0x3ffffff; g3 = h3 + c; c = g3 >> 26; g3 &= 0x3ffffff; g4 = h4 + c - (1 << 26); /* select h if h < p, or h + -p if h >= p */ mask = (g4 >> ((sizeof(unsigned long) * 8) - 1)) - 1; g0 &= mask; g1 &= mask; g2 &= mask; g3 &= mask; g4 &= mask; mask = ~mask; h0 = (h0 & mask) | g0; h1 = (h1 & mask) | g1; h2 = (h2 & mask) | g2; h3 = (h3 & mask) | g3; h4 = (h4 & mask) | g4; /* h = h % (2^128) */ h0 = ((h0 ) | (h1 << 26)) & 0xffffffff; h1 = ((h1 >> 6) | (h2 << 20)) & 0xffffffff; h2 = ((h2 >> 12) | (h3 << 14)) & 0xffffffff; h3 = ((h3 >> 18) | (h4 << 8)) & 0xffffffff; /* mac = (h + pad) % (2^128) */ f = (unsigned long long)h0 + st->pad[0] ; h0 = (unsigned long)f; f = (unsigned long long)h1 + st->pad[1] + (f >> 32); h1 = (unsigned long)f; f = (unsigned long long)h2 + st->pad[2] + (f >> 32); h2 = (unsigned long)f; f = (unsigned long long)h3 + st->pad[3] + (f >> 32); h3 = (unsigned long)f; U32TO8(mac + 0, h0); U32TO8(mac + 4, h1); U32TO8(mac + 8, h2); U32TO8(mac + 12, h3); /* zero out the state */ st->h[0] = 0; st->h[1] = 0; st->h[2] = 0; st->h[3] = 0; st->h[4] = 0; st->r[0] = 0; st->r[1] = 0; st->r[2] = 0; st->r[3] = 0; st->r[4] = 0; st->pad[0] = 0; st->pad[1] = 0; st->pad[2] = 0; st->pad[3] = 0; } ////////////////////////////////////////////////////////////////////////////// #endif // MSC/GCC or not static inline void poly1305_update(poly1305_context *ctx, const unsigned char *m, size_t bytes) { poly1305_state_internal_t *st = (poly1305_state_internal_t *)ctx; size_t i; /* handle leftover */ if (st->leftover) { size_t want = (poly1305_block_size - st->leftover); if (want > bytes) want = bytes; for (i = 0; i < want; i++) st->buffer[st->leftover + i] = m[i]; bytes -= want; m += want; st->leftover += want; if (st->leftover < poly1305_block_size) return; poly1305_blocks(st, st->buffer, poly1305_block_size); st->leftover = 0; } /* process full blocks */ if (bytes >= poly1305_block_size) { size_t want = (bytes & ~(poly1305_block_size - 1)); poly1305_blocks(st, m, want); m += want; bytes -= want; } /* store leftover */ if (bytes) { for (i = 0; i < bytes; i++) st->buffer[st->leftover + i] = m[i]; st->leftover += bytes; } } } // anonymous namespace void Poly1305::compute(void *auth,const void *data,unsigned int len,const void *key) { poly1305_context ctx; poly1305_init(&ctx,reinterpret_cast<const unsigned char *>(key)); poly1305_update(&ctx,reinterpret_cast<const unsigned char *>(data),(size_t)len); poly1305_finish(&ctx,reinterpret_cast<unsigned char *>(auth)); } } // namespace ZeroTier
29.328846
193
0.541342
sundys
c6729f5f0fb5e5cf8c9d4befedccf81e2892168d
1,909
cpp
C++
archives/training/2013.03.02 ACME Training Nine - ZOJ Monthly, November 2012/C.cpp
BoleynSu/CP-CompetitiveProgramming
cc256bf402360fe0f689fdcdc4e898473a9594dd
[ "MIT" ]
6
2019-03-23T21:06:25.000Z
2021-06-27T05:22:41.000Z
archives/training/2013.03.02 ACME Training Nine - ZOJ Monthly, November 2012/C.cpp
BoleynSu/CP-CompetitiveProgramming
cc256bf402360fe0f689fdcdc4e898473a9594dd
[ "MIT" ]
1
2020-10-11T08:14:00.000Z
2020-10-11T08:14:00.000Z
archives/training/2013.03.02 ACME Training Nine - ZOJ Monthly, November 2012/C.cpp
BoleynSu/CP-CompetitiveProgramming
cc256bf402360fe0f689fdcdc4e898473a9594dd
[ "MIT" ]
3
2019-03-23T21:06:31.000Z
2021-10-24T01:44:01.000Z
//============================================================================ // Name : test.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <string> #include <map> #include <vector> #include <cstring> #include <set> #include<cstdio> #include<string> #include<map> #include <sstream> using namespace std; vector<int> adj[1000+1],dis[1000+1]; void add_edge(int u,int v,int d) { adj[u].push_back(v); dis[u].push_back(d); } bool ins[1000+1]; int d[1000+1]; bool cmin(int& a,int b) { return a>b?a=b,true:false; } bool spfa(int u) { for (unsigned i=0;i<adj[u].size();i++) { int v=adj[u][i]; if (cmin(d[v],d[u]+dis[u][i])) { if (ins[v]) return false; ins[v]=true; if (!spfa(v)) return false; ins[v]=false; } } return true; } int main() { cin.sync_with_stdio(false); int n,m; while (cin>>n>>m) { for (int i=0;i<=n;i++) adj[i].clear(),dis[i].clear(); for (int i=0;i<m;i++) { int l,r,a,b; cin>>l>>r>>a>>b; add_edge(l-1,r,b); add_edge(r,l-1,-a); } for (int i=0;i<n;i++) add_edge(i+1,i,10000),add_edge(i,i+1,10000); // for (int i=1;i<=n;i++) // { // int l=-10000-1,r=10000; // add_edge(i,i-1,0); // while (l+1!=r) // { // dis[i].back()=(l+r)/2; // memset(ins,0,sizeof(ins)); // memset(d,0x3f,sizeof(d)); // d[0]=0; // ins[0]=true; // if (spfa(0)) r=dis[i].back(); // else l=dis[i].back(); // } // dis[i].back()=r; // } memset(ins,0,sizeof(ins)); memset(d,0x3f,sizeof(d)); d[0]=0; ins[0]=true; if (!spfa(0)) cout<<"The spacecraft is broken!"<<endl; else { for (int i=0;i<n;i++) cout<<d[i+1]-d[i]<<char(i+1==n?'\n':' '); } } }
20.978022
79
0.475118
BoleynSu
c6731fe6f4d0b69900a6e5b7bf5254eee44b1b09
10,697
cpp
C++
nv/g_dbscan.cpp
houwenbo87/DBSCAN
3452d32186f2b59f2f1e515cebdf0ce15cb3e2f7
[ "BSD-2-Clause-FreeBSD" ]
1
2020-09-18T22:40:39.000Z
2020-09-18T22:40:39.000Z
nv/g_dbscan.cpp
houwenbo87/DBSCAN
3452d32186f2b59f2f1e515cebdf0ce15cb3e2f7
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
nv/g_dbscan.cpp
houwenbo87/DBSCAN
3452d32186f2b59f2f1e515cebdf0ce15cb3e2f7
[ "BSD-2-Clause-FreeBSD" ]
1
2021-09-15T11:06:53.000Z
2021-09-15T11:06:53.000Z
#include "g_dbscan.h" #include <cuda.h> namespace { bool has_nonzero(std::vector<int>& v) { for (size_t i = 0; i < v.size(); ++i) { if (v[i] > 0) return true; } return false; } } namespace clustering { GDBSCAN::GDBSCAN(const Dataset::Ptr dset) : m_dset(dset) , d_data(0) , vA_size(sizeof(int) * dset->rows()) , d_Va0(0) , d_Va1(0) , h_Va0(dset->rows(), 0) , h_Va1(dset->rows(), 0) , d_Ea(0) , d_Fa(0) , d_Xa(0) , m_fit_time(.0) , m_predict_time(.0) , core(dset->rows(), false) , labels(dset->rows(), -1) { size_t alloc_size = sizeof(float) * m_dset->num_points(); cudaError_t r = cudaMalloc(reinterpret_cast<void**>(&d_data), alloc_size); if (r != cudaSuccess) { throw std::runtime_error("Cuda d_data malloc error :" + std::to_string(r)); } LOG(INFO) << "Allocated " << alloc_size << " bytes on device for " << m_dset->num_points() << " points"; r = cudaMalloc(reinterpret_cast<void**>(&d_Va0), vA_size); if (r != cudaSuccess) { throw std::runtime_error("Cuda d_Va0 malloc error :" + std::to_string(r)); } r = cudaMalloc(reinterpret_cast<void**>(&d_Va1), vA_size); if (r != cudaSuccess) { throw std::runtime_error("Cuda d_Va1 malloc error :" + std::to_string(r)); } LOG(INFO) << "Allocated " << vA_size << " bytes on device for Va0 and Va1"; r = cudaMalloc(reinterpret_cast<void**>(&d_Fa), vA_size); if (r != cudaSuccess) { throw std::runtime_error("Cuda d_Fa malloc error :" + std::to_string(r)); } LOG(INFO) << "Allocated " << vA_size << " bytes on device for d_Fa"; r = cudaMalloc(reinterpret_cast<void**>(&d_Xa), vA_size); if (r != cudaSuccess) { throw std::runtime_error("Cuda d_Xa malloc error :" + std::to_string(r)); } LOG(INFO) << "Allocated " << vA_size << " bytes on device for d_Xa"; const size_t cols = m_dset->cols(); size_t copysize = cols * sizeof(float); for (size_t i = 0; i < m_dset->rows(); ++i) { r = cudaMemcpy(d_data + i * cols, m_dset->data()[i].data(), copysize, cudaMemcpyHostToDevice); if (r != cudaSuccess) { throw std::runtime_error("Cuda memcpy error :" + std::to_string(r)); } VLOG(3) << "Copied " << i << "th row to device, size = " << copysize; } } GDBSCAN::~GDBSCAN() { if (d_data) { cudaFree(d_data); d_data = 0; } if (d_Va0) { cudaFree(d_Va0); d_Va0 = 0; } if (d_Va1) { cudaFree(d_Va1); d_Va1 = 0; } if (d_Ea) { cudaFree(d_Ea); d_Ea = 0; } if (d_Fa) { cudaFree(d_Fa); d_Fa = 0; } if (d_Xa) { cudaFree(d_Xa); d_Xa = 0; } } void GDBSCAN::Va_device_to_host() { cudaError_t r = cudaMemcpy(&h_Va0[0], d_Va0, vA_size, cudaMemcpyDeviceToHost); if (r != cudaSuccess) { throw std::runtime_error("Cuda memcpy Va0 device to host error :" + std::to_string(r)); } r = cudaMemcpy(&h_Va1[0], d_Va1, vA_size, cudaMemcpyDeviceToHost); if (r != cudaSuccess) { throw std::runtime_error("Cuda memcpy Va1 device to host error :" + std::to_string(r)); } } void GDBSCAN::fit(float eps, size_t min_elems) { const double start = omp_get_wtime(); // First Step (Vertices degree calculation): For each vertex, we calculate the // total number of adjacent vertices. However we can use the multiple cores of // the GPU to process multiple vertices in parallel. Our parallel strategy // using GPU assigns a thread to each vertex, i.e., each entry of the vector // Va. Each GPU thread will count how many adjacent vertex has under its // responsibility, filling the first value on the vector Va. As we can see, // there are no dependency (or communication) between those parallel tasks // (embarrassingly parallel problem). Thus, the computational complexity can // be reduced from O(V2) to O(V). int N = static_cast<int>(m_dset->rows()); int colsize = static_cast<int>(m_dset->cols()); LOG(INFO) << "Starting vertdegree on " << N << "x" << colsize << " " << (N + 255) / 256 << "x" << 256; vertdegree(N, colsize, eps, d_data, d_Va0); LOG(INFO) << "Executed vertdegree transfer"; // Second Step (Calculation of the adjacency lists indices): The second // value in Va is related to the start // index in Ea of the adjacency list of a particular vertex. The calculation // of this value depends on the start index of the vertex adjacency list and // the degree of the previous vertex. For example, the start index for the // vertex 0 is 0, since it is the first vertex. For the vertex 1, the start // index is the start index from the previous vertex (i.e. 0), plus its // degree, already calculated in the previous step. We realize that we have a // data dependency where the next vertex depends on the calculation of the // preceding vertices. This is a problem that can be efficiently done in // parallel using an exclusive scan operation [23]. For this operation, we // used the thrust library, distributed as part of the CUDA SDK. This library // provides, among others algorithms, an optimized exclusive scan // implementation that is suitable for our method adjlistsind(N, d_Va0, d_Va1); LOG(INFO) << "Executed adjlistsind transfer"; Va_device_to_host(); LOG(INFO) << "Finished transfer"; for (int i = 0; i < N; ++i) { if (static_cast<size_t>(h_Va0[i]) >= min_elems) { core[i] = true; } } // Third Step (Assembly of adjacency lists): Having the vector Va been // completely filled, i.e., for each // vertex, we know its degree and the start index of its adjacency list, // calculated in the two previous steps, we can now simply mount the compact // adjacency list, represented by Ea. Following the logic of the first step, // we assign a GPU thread to each vertex. Each of these threads will fill the // adjacency list of its associated vertex with all vertices adjacent to it. // The adjacency list for each vertex starts at the indices present in the // second value of Va, and has an offset related to the degree of the vertex. size_t Ea_size = static_cast<size_t>(h_Va0[h_Va0.size() - 1] + h_Va1[h_Va1.size() - 1]) * sizeof(int); LOG(INFO) << "Allocating " << Ea_size << " bytes for Ea " << h_Va0[h_Va0.size() - 1] << "+" << h_Va1[h_Va1.size() - 1]; if (d_Ea) { cudaFree(d_Ea); d_Ea = 0; } cudaError_t r = cudaMalloc(reinterpret_cast<void**>(&d_Ea), Ea_size); if (r != cudaSuccess) { throw std::runtime_error("Cuda d_Ea malloc error :" + std::to_string(r)); } asmadjlist(N, colsize, eps, d_data, d_Va1, d_Ea); m_fit_time = omp_get_wtime() - start; LOG(INFO) << "Executed asmadjlist transfer"; } void GDBSCAN::Fa_Xa_to_device(const std::vector<int>& Fa, const std::vector<int>& Xa) { cudaError_t r = cudaMemcpy(d_Fa, &Fa[0], vA_size, cudaMemcpyHostToDevice); if (r != cudaSuccess) { throw std::runtime_error("Cuda memcpy Fa host to device :" + std::to_string(r)); } r = cudaMemcpy(d_Xa, &Xa[0], vA_size, cudaMemcpyHostToDevice); if (r != cudaSuccess) { throw std::runtime_error("Cuda memcpy Xa host to device :" + std::to_string(r)); } } void GDBSCAN::Xa_to_host(std::vector<int>& Xa) { cudaError_t r = cudaMemcpy(&Xa[0], d_Xa, vA_size, cudaMemcpyDeviceToHost); if (r != cudaSuccess) { throw std::runtime_error("Cuda memcpy Xa device to host :" + std::to_string(r)); } } void GDBSCAN::Fa_to_host(std::vector<int>& Fa) { cudaError_t r = cudaMemcpy(&Fa[0], d_Fa, vA_size, cudaMemcpyDeviceToHost); if (r != cudaSuccess) { throw std::runtime_error("Cuda memcpy Fa device to host :" + std::to_string(r)); } } void GDBSCAN::breadth_first_search(int i, int32_t cluster, std::vector<bool>& visited) { int N = static_cast<int>(m_dset->rows()); std::vector<int> Xa(m_dset->rows(), 0); std::vector<int> Fa(m_dset->rows(), 0); Fa[i] = 1; Fa_Xa_to_device(Fa, Xa); while (has_nonzero(Fa)) { breadth_first_search_kern(N, d_Ea, d_Va0, d_Va1, d_Fa, d_Xa); Fa_to_host(Fa); } Xa_to_host(Xa); for (size_t j = 0; j < m_dset->rows(); ++j) { if (Xa[j]) { visited[j] = true; labels[j] = cluster; // LOG(INFO) << "Assigning " << j << " " << cluster; } } } int32_t GDBSCAN::predict() { // Clusters identification // For this step, we decided to parallelize the BFS. Our parallelization // approach in CUDA is based on the work presented in [22], which performs a // level synchronization, i.e. the BFS traverses the graph in levels. Once a // level is visited, it is not visited again. The concept of border in the BFS // corresponds to all nodes being processed at the current level. In our // implementation we assign one thread to each vertex. Two Boolean vectors, // Borders and Visiteds, namely Fa and Xa, respectively, of size V are created // to store the vertices that are on the border of BFS (vertices of the // current level) and the vertices already visited. In each iteration, each // thread (vertex) looks for its entry in the vector Fa. If its position is // marked, the vertex removes its own entry on Fa and marks its position in // the vector Xa (it is removed from the border, and it has been visited, so // we can go to the next level). It also adds its neighbours to the vector Fa // if they have not already been visited, thus beginning the search in a new // level. This process is repeated until the boundary becomes empty. We // illustrate the functioning of our BFS parallel implementation in Algorithm // 3 and 4. int32_t cluster = 0; std::vector<bool> visited(m_dset->rows(), false); const double start = omp_get_wtime(); for (size_t i = 0; i < m_dset->rows(); ++i) { if (visited[i]) continue; if (!core[i]) continue; visited[i] = true; labels[i] = cluster; breadth_first_search(static_cast<int>(i), cluster, visited); cluster += 1; } m_predict_time = omp_get_wtime() - start; return cluster; } const GDBSCAN::Labels& GDBSCAN::get_labels() { return labels; } } // namespace clustering
31.09593
81
0.618304
houwenbo87
c6735e0f7e36f1d9c9effe211678d06a91179a9f
307
cpp
C++
Lesson 06/CallByVal2.cpp
noenemy/Book-Quick-Guide-C-
51ddffb6c5e4b1f4351ba878e543b179b744388b
[ "MIT" ]
null
null
null
Lesson 06/CallByVal2.cpp
noenemy/Book-Quick-Guide-C-
51ddffb6c5e4b1f4351ba878e543b179b744388b
[ "MIT" ]
null
null
null
Lesson 06/CallByVal2.cpp
noenemy/Book-Quick-Guide-C-
51ddffb6c5e4b1f4351ba878e543b179b744388b
[ "MIT" ]
null
null
null
#include <stdio.h> void AddAndPrint( int *pnParam ); int main() { int a = 10; AddAndPrint( &a ); printf("a = %d\n", a); return 0; } void AddAndPrint( int *pnParam ) { if ( pnParam == NULL ) return; *pnParam = *pnParam + 10; printf("*pnParam = %d\n", *pnParam); }
12.28
40
0.527687
noenemy
c675088f2de205f41199c5abd29d7447dd6b76c2
13,394
cpp
C++
groups/bdl/bdlt/bdlt_calendar.cpp
apaprocki/bde
ba252cb776f92fae082d5d422aa2852a9be46849
[ "Apache-2.0" ]
1
2021-04-28T13:51:30.000Z
2021-04-28T13:51:30.000Z
groups/bdl/bdlt/bdlt_calendar.cpp
apaprocki/bde
ba252cb776f92fae082d5d422aa2852a9be46849
[ "Apache-2.0" ]
null
null
null
groups/bdl/bdlt/bdlt_calendar.cpp
apaprocki/bde
ba252cb776f92fae082d5d422aa2852a9be46849
[ "Apache-2.0" ]
1
2019-06-26T13:28:48.000Z
2019-06-26T13:28:48.000Z
// bdlt_calendar.cpp -*-C++-*- #include <bdlt_calendar.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(bdlt_calendar_cpp,"$Id$ $CSID$") #include <bslalg_swaputil.h> #include <bslma_default.h> #include <bsls_assert.h> #include <bsl_algorithm.h> #include <bsl_ostream.h> namespace BloombergLP { namespace bdlt { // The implementation requires that return value for an unseccessful // 'bdlc::BitArray::find*', when cast to an 'int', is -1. BSLMF_ASSERT(-1 == static_cast<int>(bdlc::BitArray::k_INVALID_INDEX)); // -------------- // class Calendar // -------------- // PRIVATE MANIPULATORS void Calendar::synchronizeCache() { const int length = d_packedCalendar.length(); d_nonBusinessDays.setLength(length); if (length) { d_nonBusinessDays.assignAll0(); for (PackedCalendar::HolidayConstIterator it = d_packedCalendar.beginHolidays(); it != d_packedCalendar.endHolidays(); ++it) { d_nonBusinessDays.assign1(*it - d_packedCalendar.firstDate()); } // Update 'd_nonBusinessDays' with weekend days information from // 'd_packedCalendar'. PackedCalendar::WeekendDaysTransitionConstIterator nextTransIt = d_packedCalendar.beginWeekendDaysTransitions(); while (nextTransIt != d_packedCalendar.endWeekendDaysTransitions()) { PackedCalendar::WeekendDaysTransitionConstIterator currentTransIt = nextTransIt; if (currentTransIt->first > d_packedCalendar.lastDate()) { break; } ++nextTransIt; Date lastDate; if (nextTransIt == d_packedCalendar.endWeekendDaysTransitions() || nextTransIt->first > d_packedCalendar.lastDate()) { lastDate = d_packedCalendar.lastDate(); } else { lastDate = nextTransIt->first - 1; if (lastDate < d_packedCalendar.firstDate()) { continue; } } Date firstDate = currentTransIt->first < d_packedCalendar.firstDate() ? d_packedCalendar.firstDate() : currentTransIt->first; int lastDateIndex = lastDate - d_packedCalendar.firstDate(); int firstDateIndex = firstDate - d_packedCalendar.firstDate(); int firstDayOfWeek = static_cast<int>(firstDate.dayOfWeek()); for (DayOfWeekSet::const_iterator wdIt = currentTransIt->second.begin(); wdIt != currentTransIt->second.end(); ++wdIt) { int weekendDay = static_cast<int>(*wdIt); int weekendDateIndex = firstDateIndex + (weekendDay - firstDayOfWeek + 7) % 7; while (weekendDateIndex <= lastDateIndex) { d_nonBusinessDays.assign1(weekendDateIndex); weekendDateIndex += 7; } } } } } // PRIVATE ACCESSORS bool Calendar::isCacheSynchronized() const { if (d_packedCalendar.length() != static_cast<int>(d_nonBusinessDays.length())) { return false; // RETURN } if (0 == d_packedCalendar.length()) { return true; // RETURN } PackedCalendar::BusinessDayConstIterator iter = d_packedCalendar.beginBusinessDays(); PackedCalendar::BusinessDayConstIterator endIter = d_packedCalendar.endBusinessDays(); int offset = static_cast<int>(d_nonBusinessDays.find0AtMinIndex(0)); while (iter != endIter) { if (offset != *iter - d_packedCalendar.firstDate()) { return false; // RETURN } ++iter; offset = static_cast<int>( d_nonBusinessDays.find0AtMinIndex(offset + 1)); } return 0 > offset; } // CREATORS Calendar::Calendar(bslma::Allocator *basicAllocator) : d_packedCalendar(basicAllocator) , d_nonBusinessDays(basicAllocator) { } Calendar::Calendar(const Date& firstDate, const Date& lastDate, bslma::Allocator *basicAllocator) : d_packedCalendar(firstDate, lastDate, basicAllocator) , d_nonBusinessDays(basicAllocator) { d_nonBusinessDays.setLength(d_packedCalendar.length(), 0); } Calendar::Calendar(const PackedCalendar& packedCalendar, bslma::Allocator *basicAllocator) : d_packedCalendar(packedCalendar, basicAllocator) , d_nonBusinessDays(basicAllocator) { synchronizeCache(); } Calendar::Calendar(const Calendar& original, bslma::Allocator *basicAllocator) : d_packedCalendar(original.d_packedCalendar, basicAllocator) , d_nonBusinessDays(original.d_nonBusinessDays, basicAllocator) { } Calendar::~Calendar() { BSLS_ASSERT_SAFE(isCacheSynchronized()); } // MANIPULATORS void Calendar::addDay(const Date& date) { if (0 == length()) { setValidRange(date, date); } else if (date < d_packedCalendar.firstDate()) { setValidRange(date, d_packedCalendar.lastDate()); } else if (date > d_packedCalendar.lastDate()) { setValidRange(d_packedCalendar.firstDate(), date); } } void Calendar::addHoliday(const Date& date) { if (0 == length()) { d_nonBusinessDays.reserveCapacity(1); reserveHolidayCapacity(1); d_packedCalendar.addHoliday(date); synchronizeCache(); } else if (date < d_packedCalendar.firstDate()) { d_nonBusinessDays.reserveCapacity( d_packedCalendar.lastDate() - date + 1); reserveHolidayCapacity(numHolidays() + 1); d_packedCalendar.addHoliday(date); synchronizeCache(); } else if (date > d_packedCalendar.lastDate()) { d_nonBusinessDays.reserveCapacity( date - d_packedCalendar.firstDate() + 1); reserveHolidayCapacity(numHolidays() + 1); d_packedCalendar.addHoliday(date); synchronizeCache(); } else { reserveHolidayCapacity(numHolidays() + 1); d_packedCalendar.addHoliday(date); d_nonBusinessDays.assign1(date - d_packedCalendar.firstDate()); } } void Calendar::addHolidayCode(const Date& date, int holidayCode) { if (0 == length()) { d_nonBusinessDays.reserveCapacity(1); reserveHolidayCapacity(1); reserveHolidayCodeCapacity(1); d_packedCalendar.addHolidayCode(date, holidayCode); synchronizeCache(); } else if (date < d_packedCalendar.firstDate()) { d_nonBusinessDays.reserveCapacity( d_packedCalendar.lastDate() - date + 1); reserveHolidayCapacity(numHolidays() + 1); reserveHolidayCodeCapacity(numHolidayCodesTotal() + 1); d_packedCalendar.addHolidayCode(date, holidayCode); synchronizeCache(); } else if (date > d_packedCalendar.lastDate()) { d_nonBusinessDays.reserveCapacity( date - d_packedCalendar.firstDate() + 1); reserveHolidayCapacity(numHolidays() + 1); reserveHolidayCodeCapacity(numHolidayCodesTotal() + 1); d_packedCalendar.addHolidayCode(date, holidayCode); synchronizeCache(); } else { reserveHolidayCapacity(numHolidays() + 1); reserveHolidayCodeCapacity(numHolidayCodesTotal() + 1); d_packedCalendar.addHolidayCode(date, holidayCode); d_nonBusinessDays.assign1(date - d_packedCalendar.firstDate()); } } void Calendar::addWeekendDay(DayOfWeek::Enum weekendDay) { d_packedCalendar.addWeekendDay(weekendDay); if (length()) { int weekendDayIndex = (static_cast<int>(weekendDay) - static_cast<int>( d_packedCalendar.firstDate().dayOfWeek()) + 7) % 7; while (weekendDayIndex < length()) { d_nonBusinessDays.assign1(weekendDayIndex); weekendDayIndex += 7; } } } void Calendar::addWeekendDays(const DayOfWeekSet& weekendDays) { if (!weekendDays.isEmpty()) { for (DayOfWeekSet::iterator it = weekendDays.begin(); it != weekendDays.end(); ++it) { addWeekendDay(*it); } } else { d_packedCalendar.addWeekendDays(weekendDays); } } void Calendar::unionBusinessDays(const PackedCalendar& other) { int newLength; if (length() && other.length()) { newLength = length(); if (other.firstDate() < firstDate()) { newLength += firstDate() - other.firstDate(); } if (other.lastDate() > lastDate()) { newLength += other.lastDate() - lastDate(); } } else { newLength = length() + other.length(); } d_nonBusinessDays.reserveCapacity(newLength); d_packedCalendar.unionBusinessDays(other); synchronizeCache(); } void Calendar::unionNonBusinessDays(const PackedCalendar& other) { int newLength; if (length() && other.length()) { newLength = length(); if (other.firstDate() < firstDate()) { newLength += firstDate() - other.firstDate(); } if (other.lastDate() > lastDate()) { newLength += other.lastDate() - lastDate(); } } else { newLength = length() + other.length(); } d_nonBusinessDays.reserveCapacity(newLength); d_packedCalendar.unionNonBusinessDays(other); synchronizeCache(); } // ACCESSORS int Calendar::getNextBusinessDay(Date *nextBusinessDay, const Date& date, int nth) const { BSLS_ASSERT(nextBusinessDay); BSLS_ASSERT(Date(9999, 12, 31) > date); BSLS_ASSERT(isInRange(date + 1)); BSLS_ASSERT(0 < nth); enum { e_SUCCESS = 0, e_FAILURE = 1 }; int offset = date - firstDate(); while (nth) { offset = static_cast<int>( d_nonBusinessDays.find0AtMinIndex(offset + 1)); if (0 > offset) { return e_FAILURE; // RETURN } --nth; } *nextBusinessDay = firstDate() + offset; return e_SUCCESS; } // ----------------------------------- // class Calendar_BusinessDayConstIter // ----------------------------------- // PRIVATE CREATORS Calendar_BusinessDayConstIter::Calendar_BusinessDayConstIter( const bdlc::BitArray& nonBusinessDays, const Date& firstDateOfCalendar, const Date& startDate, bool endIterFlag) : d_nonBusinessDays_p(&nonBusinessDays) , d_firstDate(firstDateOfCalendar) , d_currentOffset(startDate - firstDateOfCalendar) { if (d_firstDate > startDate) { d_currentOffset = -1; return; // RETURN } BSLS_ASSERT(d_currentOffset >= 0); if (endIterFlag) { // This constructor is called from the overloaded 'endBusinessDays' // method. If 'startDate' is the last date in the valid range of the // calendar, mark this iterator as an 'end' iterator and return. // Otherwise, advance the iterator to reference the next date so we can // find the next business day. if (d_currentOffset == static_cast<int>(d_nonBusinessDays_p->length()) - 1) { d_currentOffset = -1; return; // RETURN } ++d_currentOffset; } d_currentOffset = static_cast<int>( d_nonBusinessDays_p->find0AtMinIndex(d_currentOffset)); if (0 > d_currentOffset) { d_currentOffset = -1; } } } // close package namespace } // close enterprise namespace // ---------------------------------------------------------------------------- // Copyright 2016 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ----------------------------------
33.908861
79
0.565029
apaprocki
c6779b9a90b189149949b14b7c66db635910f0c9
3,049
cpp
C++
src/system/cmd_line.cpp
mzxdream/mzx
831b8ec761af78678f9588f927e12a2279c0b2d7
[ "Apache-2.0" ]
1
2019-04-26T02:54:06.000Z
2019-04-26T02:54:06.000Z
src/system/cmd_line.cpp
mzxdream/mzx
831b8ec761af78678f9588f927e12a2279c0b2d7
[ "Apache-2.0" ]
null
null
null
src/system/cmd_line.cpp
mzxdream/mzx
831b8ec761af78678f9588f927e12a2279c0b2d7
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <list> #include <map> #include <mutex> #include <unistd.h> #include <mzx/string/string_util.h> #include <mzx/system/cmd_line.h> #include <mzx/thread.h> namespace mzx { static int KeyBoardHitReturn() { struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 0; fd_set fds; FD_ZERO(&fds); FD_SET(STDIN_FILENO, &fds); select(STDIN_FILENO + 1, &fds, NULL, NULL, &tv); return FD_ISSET(STDIN_FILENO, &fds); } static CmdLine::Callback cmd_callback_default; static std::map<std::string, CmdLine::Callback> cmd_callback_list; static std::mutex cmd_mutex; static std::list<std::string> cmd_list; static Thread cmd_read_thread([]() { printf("cmd>"); char cmd_buf[1024] = {0}; while (true) { fflush(stdout); while (!KeyBoardHitReturn()) { usleep(100); Thread::CheckCancelPoint(); } Thread::CheckCancelPoint(); char *cmd_str = fgets(cmd_buf, sizeof(cmd_buf), stdin); if (cmd_str) { for (int i = 0; cmd_str[i]; ++i) { if (cmd_str[i] == '\r' || cmd_str[i] == '\n') { cmd_str[i] = '\0'; break; } } if (cmd_str[0] == '\0') { printf("cmd>"); continue; } { std::lock_guard<std::mutex> lock(cmd_mutex); cmd_list.push_back(cmd_str); } } else if (feof(stdin)) { return; } } }); bool CmdLine::Start() { return cmd_read_thread.Start(); } void CmdLine::Stop() { cmd_read_thread.Cancel(); cmd_read_thread.Join(); } void CmdLine::Regist(const CmdLine::Callback &callback) { cmd_callback_default = callback; } void CmdLine::Regist(const std::string &cmd, const CmdLine::Callback &callback) { cmd_callback_list[cmd] = callback; } void CmdLine::Unregist() { cmd_callback_default = nullptr; } void CmdLine::Unregist(const std::string &cmd) { cmd_callback_list.erase(cmd); } void CmdLine::UnregistAll() { cmd_callback_list.clear(); cmd_callback_default = nullptr; } void CmdLine::Execute() { std::list<std::string> cmd_execute_list; { std::lock_guard<std::mutex> lock(cmd_mutex); cmd_execute_list.swap(cmd_list); } for (auto &cmd : cmd_execute_list) { auto args = Split(cmd); if (args.empty()) { continue; } auto iter_callback = cmd_callback_list.find(args[0]); if (iter_callback != cmd_callback_list.end()) { if (iter_callback->second) { (iter_callback->second)(args); continue; } } if (cmd_callback_default) { cmd_callback_default(args); } } if (!cmd_execute_list.empty()) { printf("\ncmd>"); fflush(stdout); } } } // namespace mzx
21.321678
79
0.541161
mzxdream
c678dfa624154fe38517d29e1e7f5058a3da162f
5,099
cpp
C++
samples/cortex/mx-gcc/4-debug-m3-stm32f2xx/src/main.cpp
diamondx131/scmrtos-sample-projects
3b34a485b6ca4b16705c250383ae5d30c81966f1
[ "MIT" ]
9
2015-10-07T15:27:27.000Z
2021-04-07T06:13:24.000Z
samples/cortex/mx-gcc/4-debug-m3-stm32f2xx/src/main.cpp
diamondx131/scmrtos-sample-projects
3b34a485b6ca4b16705c250383ae5d30c81966f1
[ "MIT" ]
4
2017-07-04T10:51:51.000Z
2019-09-25T11:20:24.000Z
samples/cortex/mx-gcc/4-debug-m3-stm32f2xx/src/main.cpp
diamondx131/scmrtos-sample-projects
3b34a485b6ca4b16705c250383ae5d30c81966f1
[ "MIT" ]
9
2015-12-04T15:34:32.000Z
2020-07-01T16:10:59.000Z
//****************************************************************************** //* //* FULLNAME: Single-Chip Microcontroller Real-Time Operating System //* //* NICKNAME: scmRTOS //* //* PROCESSOR: ARM Cortex-M3 //* //* TOOLKIT: ARM GCC //* //* PURPOSE: Port Test File //* //* Version: v5.2.0 //* //* //* Copyright (c) 2003-2021, scmRTOS Team //* //* 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. //* //* ================================================================= //* Project sources: https://github.com/scmrtos/scmrtos //* Documentation: https://github.com/scmrtos/scmrtos/wiki/Documentation //* Wiki: https://github.com/scmrtos/scmrtos/wiki //* Sample projects: https://github.com/scmrtos/scmrtos-sample-projects //* ================================================================= //* //****************************************************************************** //* gcc port by Anton B. Gusev aka AHTOXA, Copyright (c) 2009-2021 #include "stm32f2xx.h" #include "pin.h" #include <scmRTOS.h> //--------------------------------------------------------------------------- // // Process types // typedef OS::process<OS::pr0, 300> TProc0; typedef OS::process<OS::pr1, 300> TProc1; typedef OS::process<OS::pr2, 300> TProc2; //--------------------------------------------------------------------------- // // Process objects // TProc0 Proc0; TProc1 Proc1; TProc2 Proc2; //--------------------------------------------------------------------------- // // IO Pins // typedef Pin<'E', 0> PE0; typedef Pin<'E', 1> PE1; //--------------------------------------------------------------------------- // // Event Flags to test // OS::TEventFlag event; OS::TEventFlag timer_event; int main() { // configure IO pins PE0::Direct(OUTPUT); PE0::Off(); PE1::Direct(OUTPUT); PE1::Off(); // run OS::run(); } /** * Waste some time (payload emulation). */ NOINLINE void waste_time() { for (volatile int i = 0; i < 0x3FF; i++) ; } /** * Stack angry function. * Eats approximately (12 * count) bytes from caller process stack. * Called by different processes some time after start. * Stack usage changes can be observed in debug terminal. */ NOINLINE int waste_stack(int count) { volatile int arr[2]; arr[0] = TIM2->CNT; // any volatile register arr[1] = count ? waste_stack(count - 1) : TIM2->CNT; return (arr[0] + arr[1]) / 2; } namespace OS { template <> OS_PROCESS void TProc0::exec() { for(;;) { // PE0 "ON" time = context switch time (~9.6us at 24MHz) event.wait(); PE0::Off(); // waste some time (simulate payload) waste_time(); // waste some stack (increasing with time) tick_count_t t = (OS::get_tick_count() % 40000) / 5000; waste_stack(t); } } template <> OS_PROCESS void TProc1::exec() { for(;;) { sleep(10); PE0::On(); event.signal(); // waste time (2x Proc0) waste_time(); waste_time(); } } template <> OS_PROCESS void TProc2::exec() { for (;;) { timer_event.wait(); PE1::On(); // increase load, one step at every 5 seconds after start, // resetting at 8th step. tick_count_t t = (OS::get_tick_count() % 40000) / 5000; for (uint32_t i = 0; i < t; i++) waste_time(); // PE1 led "ON" time ~ Proc2 load PE1::Off(); } } } void OS::system_timer_user_hook() { static const int reload_value = 10; // 100 Hz static int counter = reload_value; if (!--counter) { counter = reload_value; timer_event.signal_isr(); } } #if scmRTOS_IDLE_HOOK_ENABLE void OS::idle_process_user_hook() { __WFI(); } #endif
27.413978
80
0.521867
diamondx131
c6794313406de573af08d9f97f4b5f705f70a7a5
1,471
cpp
C++
oclint-rules/rules/basic/ForLoopShouldBeWhileLoopRule.cpp
BGU-AiDnD/oclint
484fed44ca0e34532745b3d4f04124cbf5bb42fa
[ "BSD-3-Clause" ]
3,128
2015-01-01T06:00:31.000Z
2022-03-29T23:43:20.000Z
oclint-rules/rules/basic/ForLoopShouldBeWhileLoopRule.cpp
BGU-AiDnD/oclint
484fed44ca0e34532745b3d4f04124cbf5bb42fa
[ "BSD-3-Clause" ]
432
2015-01-03T15:43:08.000Z
2022-03-29T02:32:48.000Z
oclint-rules/rules/basic/ForLoopShouldBeWhileLoopRule.cpp
BGU-AiDnD/oclint
484fed44ca0e34532745b3d4f04124cbf5bb42fa
[ "BSD-3-Clause" ]
454
2015-01-06T03:11:12.000Z
2022-03-22T05:49:38.000Z
#include "oclint/AbstractASTVisitorRule.h" #include "oclint/RuleSet.h" using namespace std; using namespace clang; using namespace oclint; class ForLoopShouldBeWhileLoopRule : public AbstractASTVisitorRule<ForLoopShouldBeWhileLoopRule> { public: virtual const string name() const override { return "for loop should be while loop"; } virtual int priority() const override { return 3; } virtual const string category() const override { return "basic"; } #ifdef DOCGEN virtual const std::string since() const override { return "0.6"; } virtual const std::string description() const override { return "Under certain circumstances, some ``for`` loops can be simplified to " "``while`` loops to make code more concise."; } virtual const std::string example() const override { return R"rst( .. code-block:: cpp void example(int a) { for (; a < 100;) { foo(a); } } )rst"; } #endif bool VisitForStmt(ForStmt *forStmt) { Stmt *initStmt = forStmt->getInit(); Expr *condExpr = forStmt->getCond(); Expr *incExpr = forStmt->getInc(); if (!initStmt && !incExpr && condExpr && !isa<NullStmt>(condExpr)) { addViolation(forStmt, this); } return true; } }; static RuleSet rules(new ForLoopShouldBeWhileLoopRule());
21.318841
96
0.600952
BGU-AiDnD
c67a7bade02aaedb517201b768f13e0b6607787b
4,676
cpp
C++
libraries/lps/test/linearization_stochastic_test.cpp
tneele/mCRL2
8f2d730d650ffec15130d6419f69c50f81e5125c
[ "BSL-1.0" ]
null
null
null
libraries/lps/test/linearization_stochastic_test.cpp
tneele/mCRL2
8f2d730d650ffec15130d6419f69c50f81e5125c
[ "BSL-1.0" ]
null
null
null
libraries/lps/test/linearization_stochastic_test.cpp
tneele/mCRL2
8f2d730d650ffec15130d6419f69c50f81e5125c
[ "BSL-1.0" ]
null
null
null
// Author(s): Jan Friso Groote // Copyright: see the accompanying file COPYING or copy at // https://github.com/mCRL2org/mCRL2/blob/master/COPYING // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // /// \file stochastic_linearization_test.cpp /// \brief Add your file description here. #include <boost/test/included/unit_test_framework.hpp> #include <iostream> #include <string> #include "mcrl2/data/detail/rewrite_strategies.h" #include "mcrl2/lps/linearise.h" #include "mcrl2/utilities/logger.h" using namespace mcrl2; using namespace mcrl2::lps; typedef data::rewriter::strategy rewrite_strategy; typedef std::vector<rewrite_strategy> rewrite_strategy_vector; void run_linearisation_instance(const std::string& spec, const t_lin_options& options, bool expect_success) { if (expect_success) { lps::stochastic_specification s=linearise(spec, options); BOOST_CHECK(s != lps::stochastic_specification()); } else { BOOST_CHECK_THROW(linearise(spec, options), mcrl2::runtime_error); } } void run_linearisation_test_case(const std::string& spec, const bool expect_success = true) { // Set various rewrite strategies rewrite_strategy_vector rewrite_strategies = data::detail::get_test_rewrite_strategies(false); for (rewrite_strategy_vector::const_iterator i = rewrite_strategies.begin(); i != rewrite_strategies.end(); ++i) { std::clog << std::endl << "Testing with rewrite strategy " << *i << std::endl; t_lin_options options; options.rewrite_strategy=*i; std::clog << " Default options" << std::endl; run_linearisation_instance(spec, options, expect_success); std::clog << " Linearisation method regular2" << std::endl; options.lin_method=lmRegular2; run_linearisation_instance(spec, options, expect_success); std::clog << " Linearisation method stack" << std::endl; options.lin_method=lmStack; run_linearisation_instance(spec, options, expect_success); std::clog << " Linearisation method stack; binary enabled" << std::endl; options.binary=true; run_linearisation_instance(spec, options, expect_success); std::clog << " Linearisation method regular; binary enabled" << std::endl; options.lin_method=lmRegular; run_linearisation_instance(spec, options, expect_success); std::clog << " Linearisation method regular; no intermediate clustering" << std::endl; options.binary=false; // reset binary options.no_intermediate_cluster=true; run_linearisation_instance(spec, options, expect_success); } } BOOST_AUTO_TEST_CASE(Check_that_a_probability_distribution_works_well_in_combination_with_a_nonterminating_initial_process) { const std::string spec = "act a:Bool;\n" "init dist x:Bool[1/2].a(x);\n"; run_linearisation_test_case(spec,true); } BOOST_AUTO_TEST_CASE(Check_distribution_of_dist_over_plus) { const std::string spec = "act a,b:Bool;\n" "init dist x:Bool[1/2].a(x).delta+dist y:Bool[1/2].a(y).delta;\n"; run_linearisation_test_case(spec,true); } BOOST_AUTO_TEST_CASE(Check_distribution_of_dist_over_sum) { const std::string spec = "act a:Bool#Bool;\n" "init dist x:Bool[1/2].sum y:Bool.a(x,y).delta;\n"; run_linearisation_test_case(spec,true); } // The test below represents a problem as the variables that were moved // to the front were not properly renamed. Problem reported by Olav Bunte. BOOST_AUTO_TEST_CASE(renaming_of_initial_stochastic_variables) { const std::string spec = "act\n" " flip: Bool;\n" " dice: Nat;\n" "\n" "proc\n" " COIN(s: Nat, d: Nat) =\n" " (s == 0) -> dist b1:Bool[1/2].(b1 -> flip(b1).COIN(1,0) <> flip(b1).COIN(2,0))\n" " <> (s == 1) -> dist b1:Bool[1/2].(b1 -> flip(b1).COIN(3,0) <> flip(b1).COIN(4,0))\n" " <> (s == 2) -> dist b1:Bool[1/2].(b1 -> flip(b1).COIN(5,0) <> flip(b1).COIN(6,0))\n" " <> (s == 3) -> dist b1:Bool[1/2].(b1 -> flip(b1).COIN(1,0) <> flip(b1).COIN(7,1))\n" " <> (s == 4) -> dist b1:Bool[1/2].(b1 -> flip(b1).COIN(7,2) <> flip(b1).COIN(7,3))\n" " <> (s == 5) -> dist b1:Bool[1/2].(b1 -> flip(b1).COIN(7,4) <> flip(b1).COIN(7,5))\n" " <> (s == 6) -> dist b1:Bool[1/2].(b1 -> flip(b1).COIN(2,0) <> flip(b1).COIN(7,6))\n" " <> (s == 7) -> dice(d).COIN(s,d);\n" "\n" "init COIN(0, 0);\n"; run_linearisation_test_case(spec,true); } boost::unit_test::test_suite* init_unit_test_suite(int, char*[]) { return nullptr; }
34.382353
123
0.666809
tneele
c67d961ea7a2dc7b47b9fbb334881e1989cb8b6a
4,607
cpp
C++
src/DemoRenderer.cpp
fdarling/qt-non-blocking-opengl-demo
8fcc313a8bb7506a2429ddce2cb28944d46b8fc8
[ "Unlicense" ]
2
2020-07-19T17:52:08.000Z
2021-02-14T15:50:20.000Z
src/DemoRenderer.cpp
fdarling/qt-non-blocking-opengl-demo
8fcc313a8bb7506a2429ddce2cb28944d46b8fc8
[ "Unlicense" ]
null
null
null
src/DemoRenderer.cpp
fdarling/qt-non-blocking-opengl-demo
8fcc313a8bb7506a2429ddce2cb28944d46b8fc8
[ "Unlicense" ]
null
null
null
#include "DemoRenderer.h" #include "OpenGLWindow.h" #include <QOpenGLFunctions_3_0> #include <QThread> #define _USE_MATH_DEFINES #include <math.h> void DrawCube(QOpenGLFunctions_3_0 *f) { f->glBegin(GL_QUADS); // Draw The Cube Using quads f->glColor3f(0.0f, 1.0f, 0.0f); // Color Blue f->glVertex3f( 1.0f, 1.0f, -1.0f); // Top Right Of The Quad (Top) f->glVertex3f(-1.0f, 1.0f, -1.0f); // Top Left Of The Quad (Top) f->glVertex3f(-1.0f, 1.0f, 1.0f); // Bottom Left Of The Quad (Top) f->glVertex3f( 1.0f, 1.0f, 1.0f); // Bottom Right Of The Quad (Top) f->glColor3f(1.0f, 0.5f, 0.0f); // Color Orange f->glVertex3f( 1.0f, -1.0f, 1.0f); // Top Right Of The Quad (Bottom) f->glVertex3f(-1.0f, -1.0f, 1.0f); // Top Left Of The Quad (Bottom) f->glVertex3f(-1.0f, -1.0f, -1.0f); // Bottom Left Of The Quad (Bottom) f->glVertex3f( 1.0f, -1.0f, -1.0f); // Bottom Right Of The Quad (Bottom) f->glColor3f(1.0f, 0.0f, 0.0f); // Color Red f->glVertex3f( 1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Front) f->glVertex3f(-1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Front) f->glVertex3f(-1.0f, -1.0f, 1.0f); // Bottom Left Of The Quad (Front) f->glVertex3f( 1.0f, -1.0f, 1.0f); // Bottom Right Of The Quad (Front) f->glColor3f(1.0f, 1.0f, 0.0f); // Color Yellow f->glVertex3f( 1.0f, -1.0f, -1.0f); // Top Right Of The Quad (Back) f->glVertex3f(-1.0f, -1.0f, -1.0f); // Top Left Of The Quad (Back) f->glVertex3f(-1.0f, 1.0f, -1.0f); // Bottom Left Of The Quad (Back) f->glVertex3f( 1.0f, 1.0f, -1.0f); // Bottom Right Of The Quad (Back) f->glColor3f(0.0f, 0.0f, 1.0f); // Color Blue f->glVertex3f(-1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Left) f->glVertex3f(-1.0f, 1.0f, -1.0f); // Top Left Of The Quad (Left) f->glVertex3f(-1.0f, -1.0f, -1.0f); // Bottom Left Of The Quad (Left) f->glVertex3f(-1.0f, -1.0f, 1.0f); // Bottom Right Of The Quad (Left) f->glColor3f(1.0f, 0.0f, 1.0f); // Color Violet f->glVertex3f( 1.0f, 1.0f, -1.0f); // Top Right Of The Quad (Right) f->glVertex3f( 1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Right) f->glVertex3f( 1.0f, -1.0f, 1.0f); // Bottom Left Of The Quad (Right) f->glVertex3f( 1.0f, -1.0f, -1.0f); // Bottom Right Of The Quad (Right) f->glEnd(); // End Drawing The Cube } void gldPerspective(QOpenGLFunctions_3_0 *f, GLdouble fovx, GLdouble aspect, GLdouble zNear, GLdouble zFar) { // This code is based off the MESA source for gluPerspective // *NOTE* This assumes GL_PROJECTION is the current matrix GLdouble xmin, xmax, ymin, ymax; GLdouble m[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; const auto M = [&m](int i, int j)->GLdouble * { return (m + j * 4 + i); }; xmax = zNear * tan(fovx * M_PI / 360.0); xmin = -xmax; ymin = xmin / aspect; ymax = xmax / aspect; // Set up the projection matrix *M(0, 0) = (2.0 * zNear) / (xmax - xmin); *M(1, 1) = (2.0 * zNear) / (ymax - ymin); *M(2, 2) = -(zFar + zNear) / (zFar - zNear); *M(0, 2) = (xmax + xmin) / (xmax - xmin); *M(1, 2) = (ymax + ymin) / (ymax - ymin); *M(3, 2) = -1.0; *M(2, 3) = -(2.0 * zFar * zNear) / (zFar - zNear); // Add to current matrix f->glMultMatrixd(m); } DemoRenderer::DemoRenderer(QObject *parent) : OpenGLRenderer(parent) { _timer.start(); } void DemoRenderer::paintGL(QOpenGLFunctions_3_0 * const f) { f->glViewport(0, 0, _width, _height); f->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); f->glEnable(GL_CULL_FACE); f->glEnable(GL_DEPTH_TEST); f->glDepthMask(GL_TRUE); f->glMatrixMode(GL_PROJECTION); f->glLoadIdentity(); // Calculate The Aspect Ratio Of The Window gldPerspective(f, 45.0f, static_cast<GLfloat>(_width) / static_cast<GLfloat>(_height), 0.1f, 100.0f); f->glMatrixMode(GL_MODELVIEW); f->glLoadIdentity(); const float angle = fmodf(static_cast<float>(_timer.elapsed())/100.0f, 360.0f); f->glTranslatef(0.0f, 0.0f, -7.0f); f->glScalef(_scale, _scale, _scale); f->glRotatef(angle, 0.0f, 1.0f, 0.0f); // Rotate The cube around the Y axis f->glRotatef(angle, 1.0f, 1.0f, 1.0f); DrawCube(f); if (_lagEnabled) QThread::msleep( 250 ); } void DemoRenderer::setScale(float newScale) { _scale = newScale; } void DemoRenderer::setLagEnabled(bool on) { _lagEnabled = on; }
35.992188
108
0.580855
fdarling
c67ec2df87232a37fc71e941cf903ffb37bf6154
7,514
cpp
C++
Server/Shared/src/Memcached.cpp
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
4
2015-08-17T20:12:22.000Z
2020-05-30T19:53:26.000Z
Server/Shared/src/Memcached.cpp
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
null
null
null
Server/Shared/src/Memcached.cpp
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd 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. */ #ifdef HAVE_MEMCACHED #include "Memcached.h" #include "AutoPtr.h" #include "DeleteHelpers.h" #include "Properties.h" #include <libmemcached/memcached.h> typedef AutoPtr<memcached_st> MemcachedAutoPtr; template<> void AutoPtr<memcached_st>::destroy() { if ( get() != NULL ) { memcached_free( get() ); } } namespace Memcached { MemcachedException::MemcachedException( const MC2String& what ) : MC2Exception( "Memcached", what ) { } struct Cache::Implementation { Implementation() : memc( NULL ) { } MemcachedAutoPtr memc; }; /** * Help function for throwing a helpful exception when something * has failed in libmemcached. */ void throwOnFail( memcached_return rc, memcached_st* memc, const MC2String& description ) { if ( rc != MEMCACHED_SUCCESS ) { throw MemcachedException( description + ": " + memcached_strerror( memc, rc ) ); } } Cache::Cache( const MC2String& hosts ) : m_pimpl( new Implementation ) { m_pimpl->memc.reset( memcached_create( NULL ) ); if ( m_pimpl->memc.get() == NULL ) { throw MemcachedException( "Couldn't create memcached_st structure" ); } // Enable asynchronous IO mode memcached_return rc = memcached_behavior_set( m_pimpl->memc.get(), MEMCACHED_BEHAVIOR_NO_BLOCK, 1 /* 1 = enable */ ); throwOnFail( rc, m_pimpl->memc.get(), "Couldn't set asynchronous IO mode" ); uint32 timeout = Properties::getUint32Property( "MEMCACHED_TIMEOUT", 1000 // default, ms ); // Set poll timeout rc = memcached_behavior_set( m_pimpl->memc.get(), MEMCACHED_BEHAVIOR_POLL_TIMEOUT, timeout ); throwOnFail( rc, m_pimpl->memc.get(), "Couldn't set poll timeout" ); // Set connect timeout rc = memcached_behavior_set( m_pimpl->memc.get(), MEMCACHED_BEHAVIOR_CONNECT_TIMEOUT, timeout ); throwOnFail( rc, m_pimpl->memc.get(), "Couldn't set connect timeout" ); // work around the fact that memcached_servers_parse // doesn't take a const char* char* hostsDup = strdup( hosts.c_str() ); memcached_server_st* serverList = memcached_servers_parse( hostsDup ); free( hostsDup ); if ( serverList == NULL ) { throw MemcachedException( "Couldn't parse server string" ); } rc = memcached_server_push( m_pimpl->memc.get(), serverList ); memcached_server_list_free( serverList ); throwOnFail( rc, m_pimpl->memc.get(), "Couldn't add servers" ); } Cache::~Cache() { } void Cache::add( const MC2String& key, const void* data, size_t dataLength, time_t expiration /*= 0*/, uint32_t flags /*= 0*/ ) { SysUtility::IgnorePipe ignorePipe; memcached_return rc = memcached_add( m_pimpl->memc.get(), key.c_str(), strlen( key.c_str() ), (const char*)data, dataLength, expiration, flags ); throwOnFail( rc, m_pimpl->memc.get(), "Couldn't add a value" ); } void Cache::set( const MC2String& key, const void* data, size_t dataLength, time_t expiration /*= 0*/, uint32_t flags /*= 0*/ ) { SysUtility::IgnorePipe ignorePipe; memcached_return rc = memcached_set( m_pimpl->memc.get(), key.c_str(), strlen( key.c_str() ), (const char*)data, dataLength, expiration, flags ); throwOnFail( rc, m_pimpl->memc.get(), "Couldn't set a value" ); } std::pair<boost::shared_ptr<void>, size_t> Cache::get( const MC2String& key, uint32_t* flags /*= NULL*/ ) { SysUtility::IgnorePipe ignorePipe; size_t valueLength; memcached_return rc; uint32_t flagsLocal; boost::shared_ptr<void> storedValue( memcached_get( m_pimpl->memc.get(), key.c_str(), strlen( key.c_str() ), &valueLength, &flagsLocal, &rc ), STLUtility::FreeDeleter() ); if ( storedValue != NULL ) { std::pair<boost::shared_ptr<void>, size_t> result( storedValue , valueLength ); if ( flags != NULL ) { *flags = flagsLocal; } return result; } else { throw MemcachedException( MC2String( "Couldn't get a value: " ) + memcached_strerror( m_pimpl->memc.get(), rc ) ); } } void Cache::remove( const MC2String& key ) { SysUtility::IgnorePipe ignorePipe; memcached_return rc = memcached_delete( m_pimpl->memc.get(), key.c_str(), strlen( key.c_str() ), 0 ); throwOnFail( rc, m_pimpl->memc.get(), "Couldn't delete a value" ); } void Cache::flush() { SysUtility::IgnorePipe ignorePipe; memcached_return rc = memcached_flush( m_pimpl->memc.get(), 0 ); throwOnFail( rc, m_pimpl->memc.get(), "Couldn't flush" ); } } #endif // HAVE_MEMCACHED
37.57
755
0.565611
wayfinder
c681b7875e762a600648e5b7332ccc0ae0817de5
10,769
cpp
C++
Umbrella-Engine/Image/Image.cpp
jfla-fan/JFla-Engine
dcbdcdff815fd1729bed35ec556b850cc94f6553
[ "MIT" ]
null
null
null
Umbrella-Engine/Image/Image.cpp
jfla-fan/JFla-Engine
dcbdcdff815fd1729bed35ec556b850cc94f6553
[ "MIT" ]
null
null
null
Umbrella-Engine/Image/Image.cpp
jfla-fan/JFla-Engine
dcbdcdff815fd1729bed35ec556b850cc94f6553
[ "MIT" ]
null
null
null
#include "Image.h" #include <map> namespace J::Utils { using namespace J::Math; static uint8 _GetBytesPerChannel(ERawImageFormat InFormat) { switch (InFormat) { case ERawImageFormat::L8: case ERawImageFormat::LA8: case ERawImageFormat::R8: case ERawImageFormat::RGB8: case ERawImageFormat::RGBA8: return 1; case ERawImageFormat::RH: case ERawImageFormat::RG8: case ERawImageFormat::RGBH: case ERawImageFormat::RGBAH: return 2; case ERawImageFormat::RF: case ERawImageFormat::RGBF: case ERawImageFormat::RGBAF: return 4; default: throw "Cannot define bytes per channel"; break; } return 0; // should never reach this } static uint32 _GetChannelsCount(ERawImageFormat InFormat) { switch (InFormat) { case ERawImageFormat::L8: case ERawImageFormat::R8: case ERawImageFormat::RF: case ERawImageFormat::RH: return 1; case ERawImageFormat::LA8: case ERawImageFormat::RG8: return 2; case ERawImageFormat::RGB8: case ERawImageFormat::RGBF: case ERawImageFormat::RGBH: return 3; case ERawImageFormat::RGBA8: case ERawImageFormat::RGBAH: case ERawImageFormat::RGBAF: return 4; default: throw "Unknown image format"; break; } return 0; // should never reach this } static std::string _GetImageFormatString(ERawImageFormat format) { #define CASE_LABEL(format_type)\ case ERawImageFormat::format_type:\ return #format_type switch (format) { CASE_LABEL(L8); CASE_LABEL(LA8); CASE_LABEL(R8); CASE_LABEL(RG8); CASE_LABEL(RGB8); CASE_LABEL(RGBA8); CASE_LABEL(RF); CASE_LABEL(RGBF); CASE_LABEL(RGBAF); CASE_LABEL(RH); CASE_LABEL(RGBH); CASE_LABEL(RGBAH); default: return "Unknown"; } #undef CASE_LABEL } Image::Image() : SizeX(0) , SizeY(0) , ChannelsCount(0) , BytesPerChannel(0) , Format(ERawImageFormat::AUTO) , bInitialized(false) { } Image::Image(uint32 InSizeX, uint32 InSizeY, ERawImageFormat InImageFormat) : SizeX(InSizeX) , SizeY(InSizeY) , ChannelsCount(_GetChannelsCount(InImageFormat)) , BytesPerChannel(_GetBytesPerChannel(InImageFormat)) , Format(InImageFormat) , bInitialized(false) { Source.assign((SIZE_T)SizeX * SizeY * ChannelsCount * GetBytesPerPixel(), byte(0x00)); } Image::Image(VectorUInt2 InSize, ERawImageFormat InImageFormat) : Image(InSize.x, InSize.y, InImageFormat) { } Image::Image(const byte* InData, uint32 InSizeX, uint32 InSizeY, ERawImageFormat InImageFormat) : Image(InSizeX, InSizeY, InImageFormat) { Source.assign(InData, InData + Source.size()); bInitialized = true; } Image::Image(const byte* InData, VectorUInt2 InSize, ERawImageFormat InImageFormat) : Image(InData, InSize.x, InSize.y, InImageFormat) { } Image::Image(const Image& another) { this->Source = another.Source; this->SizeX = another.SizeX; this->SizeY = another.SizeY; this->ChannelsCount = another.ChannelsCount; this->BytesPerChannel = another.BytesPerChannel; this->Format = another.Format; this->bInitialized = another.bInitialized; } Image::Image(Image&& another) NOEXCEPT { this->Source = std::move(another.Source); this->SizeX = another.SizeX; this->SizeY = another.SizeY; this->ChannelsCount = another.ChannelsCount; this->BytesPerChannel = another.BytesPerChannel; this->Format = another.Format; this->bInitialized = another.bInitialized; another.SizeX = 0; another.SizeY = 0; another.ChannelsCount = 0; another.BytesPerChannel = 0; another.bInitialized = false; } Image& Image::operator = (const Image& another) { if (this == &another) { return *this; } this->Source = another.Source; this->SizeX = another.SizeX; this->SizeY = another.SizeY; this->ChannelsCount = another.ChannelsCount; this->BytesPerChannel = another.BytesPerChannel; this->Format = another.Format; this->bInitialized = another.bInitialized; return *this; } Image& Image::operator = (Image&& another) NOEXCEPT { this->Source = std::move(another.Source); this->SizeX = another.SizeX; this->SizeY = another.SizeY; this->ChannelsCount = another.ChannelsCount; this->BytesPerChannel = another.BytesPerChannel; this->Format = another.Format; this->bInitialized = another.bInitialized; another.SizeX = 0; another.SizeY = 0; another.ChannelsCount = 0; another.BytesPerChannel = 0; another.bInitialized = false; return *this; } Image::~Image() { Release(); } void Image::Release() { JVector<byte>().swap(Source); // clears and releases vector resources bInitialized = false; } void Image::SetData(byte* Data, SIZE_T Size) { Release(); Source = JVector<byte>(Data, Data + Size); } void Image::MarkInitialized(bool initialized) { this->bInitialized = initialized; } void Image::PrintImageMetaData(std::ostream& os) { os << std::format("Size - ({}, {})\n", SizeX, SizeY) << "Channel count: " << ChannelsCount << '\n' << "Bytes per channel: " << (uint32)BytesPerChannel << '\n' << _GetImageFormatString(Format) << '\n'; } bool Image::IsInitialized() const { return bInitialized; } uint32 Image::GetBytesPerPixel() const { switch (this->Format) { case ERawImageFormat::L8: case ERawImageFormat::R8: return 1; case ERawImageFormat::LA8: case ERawImageFormat::RG8: case ERawImageFormat::RH: return 2; case ERawImageFormat::RGB8: return 3; case ERawImageFormat::RGBA8: case ERawImageFormat::RF: return 4; case ERawImageFormat::RGBH: return 6; case ERawImageFormat::RGBAH: return 8; case ERawImageFormat::RGBF: return 12; case ERawImageFormat::RGBAF: return 16; default: // todo: warning or fatal assert: Unsupported file format break; } return 0; // should never reach this } VectorUInt2 Image::GetSize() const { return { SizeX, SizeY }; } uint32 Image::GetWidth() const { return SizeX; } uint32 Image::GetHeight() const { return SizeY; } SIZE_T Image::GetBytesSize() const { return Source.size(); } uint32 Image::GetChannelsCount() const { return ChannelsCount; } uint32 Image::GetBytesPerChannel() const { return BytesPerChannel; } ERawImageFormat Image::GetFormat() const { return Format; } byte* Image::RawData() { return Source.data(); } const byte* Image::RawData() const { return Source.data(); } // data accessors std::span<byte> Image::RawView() { return std::span<byte>(this->Source); } std::span<uint8> Image::AsL8() { check(this->Format == ERawImageFormat::L8); return std::span((uint8*)this->Source.data(), this->Source.size() / sizeof(uint8)); } std::span<uint8> Image::AsR8() { check(this->Format == ERawImageFormat::R8); return std::span((uint8*)this->Source.data(), this->Source.size() / sizeof(uint8)); } std::span<uint16> Image::AsLA8() { check(this->Format == ERawImageFormat::LA8); return std::span((uint16*)this->Source.data(), this->Source.size() / sizeof(uint16)); } std::span<float16> Image::AsRH() { check(this->Format == ERawImageFormat::RH); return std::span((float16*)this->Source.data(), this->Source.size() / sizeof(float16)); } std::span<uint8> Image::AsRGB8() { check(this->Format == ERawImageFormat::RGB8); return std::span((uint8*)this->Source.data(), this->Source.size() / sizeof(uint8)); } std::span<Color> Image::AsRGBA8() { check(this->Format == ERawImageFormat::RGBA8); return std::span((Color*)this->Source.data(), this->Source.size() / sizeof(Color)); } std::span<float> Image::AsRF() { check(this->Format == ERawImageFormat::RF); return std::span((float*)this->Source.data(), this->Source.size() / sizeof(float)); } std::span<float16> Image::AsRGBH() { check(this->Format == ERawImageFormat::RGBH); return std::span((float16*)this->Source.data(), this->Source.size() / sizeof(float16)); } std::span<float16> Image::AsRGBAH() { check(this->Format == ERawImageFormat::RGBAH); return std::span((float16*)this->Source.data(), this->Source.size() / sizeof(float16)); } std::span<float> Image::AsRGBF() { check(this->Format == ERawImageFormat::RGBF); return std::span((float*)this->Source.data(), this->Source.size() / sizeof(float)); } std::span<LinearColor> Image::AsRGBAF() { check(this->Format == ERawImageFormat::RGBAF); return std::span((LinearColor*)this->Source.data(), this->Source.size() / sizeof(LinearColor)); } // const data accessors std::span<const byte> Image::RawView() const { return std::span<const byte>(this->Source); } std::span<const uint8> Image::AsL8() const { check(this->Format == ERawImageFormat::L8); return std::span((const uint8*)this->Source.data(), this->Source.size() / sizeof(uint8)); } std::span<const uint8> Image::AsR8() const { check(this->Format == ERawImageFormat::R8); return std::span((const uint8*)this->Source.data(), this->Source.size() / sizeof(uint8)); } std::span<const uint16> Image::AsLA8() const { check(this->Format == ERawImageFormat::LA8); return std::span((const uint16*)this->Source.data(), this->Source.size() / sizeof(uint16)); } std::span<const float16> Image::AsRH() const { check(this->Format == ERawImageFormat::RH); return std::span((const float16*)this->Source.data(), this->Source.size() / sizeof(float16)); } std::span<const uint8> Image::AsRGB8() const { check(this->Format == ERawImageFormat::RGB8); return std::span((const uint8*)this->Source.data(), this->Source.size() / sizeof(uint8)); } std::span<const Color> Image::AsRGBA8() const { check(this->Format == ERawImageFormat::RGBA8); return std::span((const Color*)this->Source.data(), this->Source.size() / sizeof(Color)); } std::span<const float> Image::AsRF() const { check(this->Format == ERawImageFormat::RF); return std::span((const float*)this->Source.data(), this->Source.size() / sizeof(float)); } std::span<const float16> Image::AsRGBH() const { check(this->Format == ERawImageFormat::RGBH); return std::span((const float16*)this->Source.data(), this->Source.size() / sizeof(float16)); } std::span<const float16> Image::AsRGBAH() const { check(this->Format == ERawImageFormat::RGBAH); return std::span((const float16*)this->Source.data(), this->Source.size() / sizeof(float16)); } std::span<const float> Image::AsRGBF() const { check(this->Format == ERawImageFormat::RGBF); return std::span((const float*)this->Source.data(), this->Source.size() / sizeof(float)); } std::span<const LinearColor> Image::AsRGBAF() const { check(this->Format == ERawImageFormat::RGBAF); return std::span((const LinearColor*)this->Source.data(), this->Source.size() / sizeof(LinearColor)); } }
24.530752
103
0.679172
jfla-fan
c6834844a8fbe1aaac74578b70ab9dda587242ba
2,101
inl
C++
examples/volcano/command.inl
djohansson/slang
69227ad7d46b8741274c93a42a891d70458f2d45
[ "MIT" ]
2
2019-08-16T13:33:28.000Z
2020-08-12T21:48:24.000Z
examples/volcano/command.inl
djohansson/slang
69227ad7d46b8741274c93a42a891d70458f2d45
[ "MIT" ]
null
null
null
examples/volcano/command.inl
djohansson/slang
69227ad7d46b8741274c93a42a891d70458f2d45
[ "MIT" ]
null
null
null
template <GraphicsBackend B> CommandBufferAccessScope<B> CommandPoolContext<B>::commands(const CommandBufferAccessScopeDesc<B>& beginInfo) { if (myRecordingCommands[beginInfo.level] && myRecordingCommands[beginInfo.level].value().getDesc() == beginInfo) return internalCommands(beginInfo); else return internalBeginScope(beginInfo); } template <GraphicsBackend B> void CommandPoolContext<B>::internalEndCommands(CommandBufferLevel<B> level) { if (myRecordingCommands[level]) myRecordingCommands[level] = std::nullopt; } template <GraphicsBackend B> CommandBufferAccessScope<B>::CommandBufferAccessScope( CommandBufferArray<B>* array, const CommandBufferAccessScopeDesc<B>& beginInfo) : myDesc(beginInfo) , myRefCount(std::make_shared<uint32_t>(1)) , myArray(array) , myIndex(myDesc.scopedBeginEnd ? myArray->begin(beginInfo) : 0) { } template <GraphicsBackend B> CommandBufferAccessScope<B>::CommandBufferAccessScope(const CommandBufferAccessScope& other) : myDesc(other.myDesc) , myRefCount(other.myRefCount) , myArray(other.myArray) , myIndex(other.myIndex) { (*myRefCount)++; } template <GraphicsBackend B> CommandBufferAccessScope<B>::CommandBufferAccessScope(CommandBufferAccessScope&& other) noexcept : myDesc(std::exchange(other.myDesc, {})) , myRefCount(std::exchange(other.myRefCount, {})) , myArray(std::exchange(other.myArray, {})) , myIndex(std::exchange(other.myIndex, {})) { } template <GraphicsBackend B> CommandBufferAccessScope<B>::~CommandBufferAccessScope() { if (myDesc.scopedBeginEnd && myRefCount && (--(*myRefCount) == 0) && myArray->recording(myIndex)) myArray->end(myIndex); } template <GraphicsBackend B> CommandBufferAccessScope<B>& CommandBufferAccessScope<B>::operator=(CommandBufferAccessScope other) { swap(other); return *this; } template <GraphicsBackend B> void CommandBufferAccessScope<B>::swap(CommandBufferAccessScope& rhs) noexcept { std::swap(myDesc, rhs.myDesc); std::swap(myRefCount, rhs.myRefCount); std::swap(myArray, rhs.myArray); std::swap(myIndex, rhs.myIndex); }
30.449275
116
0.753927
djohansson
c685185805e819674063c9e3a3080a6c08931440
140
cxx
C++
Libs/MRML/Widgets/DesignerPlugins/qSlicerTablesModuleWidgetsPlugin.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
Libs/MRML/Widgets/DesignerPlugins/qSlicerTablesModuleWidgetsPlugin.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
Libs/MRML/Widgets/DesignerPlugins/qSlicerTablesModuleWidgetsPlugin.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
#include "qSlicerTablesModuleWidgetsPlugin.h" #include <QtPlugin> Q_EXPORT_PLUGIN2(customwidgetplugin, qSlicerTablesModuleWidgetsPlugin);
23.333333
71
0.864286
TheInterventionCentre
c68595b039476436a4786ce09f3f1702b1cc36b5
1,149
cpp
C++
algorithms/cpp/188.cpp
viing937/leetcode
e21ca52c98bddf59e43522c0aace5e8cf84350eb
[ "MIT" ]
3
2016-10-01T10:15:09.000Z
2017-07-09T02:53:36.000Z
algorithms/cpp/188.cpp
viing937/leetcode
e21ca52c98bddf59e43522c0aace5e8cf84350eb
[ "MIT" ]
null
null
null
algorithms/cpp/188.cpp
viing937/leetcode
e21ca52c98bddf59e43522c0aace5e8cf84350eb
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: int maxProfit(int K, vector<int> &prices) { // dp[k, i] represents the max profit up until prices[i] (Note: NOT ending with prices[i]) using at most k transactions. // dp[k, i] = max(dp[k, i-1], prices[i] - prices[j] + dp[k-1, j]) // = max(dp[k, i-1], prices[i] + max(dp[k-1, j] - prices[j])) if (prices.size() == 0) return 0; if (K >= prices.size()/2) { int result = 0; for (int i = 1; i < prices.size(); i++) result += max(0, prices[i]-prices[i-1]); return result; } vector<vector<int>> dp(2, vector<int>(prices.size(), 0)); for (int k = 1; k <= K; k++) { int tmpMax = dp[(k-1)%2][0] - prices[0]; for (int i = 0; i < prices.size(); i++) { dp[k%2][i] = max(dp[k%2][i-1], prices[i] + tmpMax); tmpMax = max(tmpMax, dp[(k-1)%2][i] - prices[i]); } } return *max_element(dp[K%2].begin(), dp[K%2].end()); } }; int main() { return 0; }
33.794118
128
0.468233
viing937
c686dd7e0019ed44db46fcd2d6130180da316666
346
hpp
C++
src/cif/fusion/table.hpp
academicRobot/mmstructlib
76949620c9e9ca26faf10ff1a21c6fda1a564f5c
[ "MIT" ]
null
null
null
src/cif/fusion/table.hpp
academicRobot/mmstructlib
76949620c9e9ca26faf10ff1a21c6fda1a564f5c
[ "MIT" ]
null
null
null
src/cif/fusion/table.hpp
academicRobot/mmstructlib
76949620c9e9ca26faf10ff1a21c6fda1a564f5c
[ "MIT" ]
null
null
null
#ifndef CIF_FUSION_TABLE_HPP #define CIF_FUSION_TABLE_HPP #include <cif/table.hpp> #include <boost/fusion/include/adapt_struct.hpp> BOOST_FUSION_ADAPT_TPL_STRUCT( (string_tp), (cif::table)(string_tp), (string_tp, name) (std::vector<string_tp>, cellNames) (std::vector<boost::optional<string_tp> >, cells) ) #endif // CIF_FUSION_TABLE_HPP
21.625
50
0.768786
academicRobot
c68717e0c2888726e89bf12a28c2c90853b0bc01
2,132
cpp
C++
Week 2/7_last_digit_of_the_sum_of_fibonacci_numbers_again/fibonacci_partial_sum.cpp
osamamagdy/Algorithmic-Toolbox
c095e64ae89aa376eabf579dafc959975de78a4d
[ "MIT" ]
null
null
null
Week 2/7_last_digit_of_the_sum_of_fibonacci_numbers_again/fibonacci_partial_sum.cpp
osamamagdy/Algorithmic-Toolbox
c095e64ae89aa376eabf579dafc959975de78a4d
[ "MIT" ]
null
null
null
Week 2/7_last_digit_of_the_sum_of_fibonacci_numbers_again/fibonacci_partial_sum.cpp
osamamagdy/Algorithmic-Toolbox
c095e64ae89aa376eabf579dafc959975de78a4d
[ "MIT" ]
1
2021-01-29T21:57:48.000Z
2021-01-29T21:57:48.000Z
/* #include <iostream> #include <vector> using std::vector; long long get_fibonacci_partial_sum_naive(long long from, long long to) { long long sum = 0; long long current = 0; long long next = 1; for (long long i = 0; i <= to; ++i) { if (i >= from) { sum += current; } long long new_current = next; next = next + current; current = new_current; } return sum % 10; } int get_fibonacci_partial_sum_fast(long long m , long long n) { //Start Computing pisano period int prev = 0; int curr = 1; int result; //Store pisano period in a vector vector<int> v; v.push_back(0); v.push_back(1); do { result = (curr + prev) % 10; prev = curr; curr = result; v.push_back(result); } while ((prev != 0) || (curr != 1)); //Get rid of the occurence of 0 1 v.pop_back(); v.pop_back(); //pisano period length int period = v.size(); //Reduce n,m as the last digit of the sum remains the same for each period //it depends only on its index in pisano period n = n % period; m = m % period; //Compute the last digit of the sum of all last digits in pisano period int sum = 0; /// <summary> /// It might happen to you that the index of smaller number(m) in pisano period is actually beyond the index of bigger number (n) /// In that case you need to split your sum into two parts: /// 1-from m to the end of the period /// 2-assign 0 to m and start the next loop from 0 to n /// </summary> /// <param name="m"></param> /// <param name="n"></param> /// <returns></returns> if (m>n) { for (int i = m; i < period; i++) { sum = (sum + v[i]) % 10; } m = 0; } /// <summary> /// The main Computation loop /// </summary> /// <param name="m"></param> /// <param name="n"></param> /// <returns></returns> for (int i = m; i <= n; i++) { sum = (sum + v[i]) % 10; } return sum; } int main() { long long from, to; std::cin >> from >> to; //std::cout << get_fibonacci_partial_sum_naive(from, to) << '\n'; std::cout << get_fibonacci_partial_sum_fast(from, to) << '\n'; return 0; } */
19.207207
131
0.587711
osamamagdy
c689704815cfd5906fc7af2219123219d8e5a0af
6,892
cpp
C++
CWE-399/source_files/CVE-2016-5277/firefox_49.0b1_CVE_2016_5277_dom_animation_DocumentTimeline.cpp
CGCL-codes/VulDeePecker
98610f3e116df97a1e819ffc81fbc7f6f138a8f2
[ "Apache-2.0" ]
185
2017-12-14T08:18:15.000Z
2022-03-30T02:58:36.000Z
CWE-399/source_files/CVE-2016-5277/firefox_49.0b1_CVE_2016_5277_dom_animation_DocumentTimeline.cpp
CGCL-codes/VulDeePecker
98610f3e116df97a1e819ffc81fbc7f6f138a8f2
[ "Apache-2.0" ]
11
2018-01-30T23:31:20.000Z
2022-01-17T05:03:56.000Z
CWE-399/source_files/CVE-2016-5277/firefox_49.0b1_CVE_2016_5277_dom_animation_DocumentTimeline.cpp
CGCL-codes/VulDeePecker
98610f3e116df97a1e819ffc81fbc7f6f138a8f2
[ "Apache-2.0" ]
87
2018-01-10T08:12:32.000Z
2022-02-19T10:29:31.000Z
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "DocumentTimeline.h" #include "mozilla/dom/DocumentTimelineBinding.h" #include "AnimationUtils.h" #include "nsContentUtils.h" #include "nsDOMMutationObserver.h" #include "nsDOMNavigationTiming.h" #include "nsIPresShell.h" #include "nsPresContext.h" #include "nsRefreshDriver.h" namespace mozilla { namespace dom { NS_IMPL_CYCLE_COLLECTION_INHERITED(DocumentTimeline, AnimationTimeline, mDocument) NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN_INHERITED(DocumentTimeline, AnimationTimeline) NS_IMPL_CYCLE_COLLECTION_TRACE_END NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(DocumentTimeline) NS_INTERFACE_MAP_END_INHERITING(AnimationTimeline) NS_IMPL_ADDREF_INHERITED(DocumentTimeline, AnimationTimeline) NS_IMPL_RELEASE_INHERITED(DocumentTimeline, AnimationTimeline) JSObject* DocumentTimeline::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) { return DocumentTimelineBinding::Wrap(aCx, this, aGivenProto); } Nullable<TimeDuration> DocumentTimeline::GetCurrentTime() const { return ToTimelineTime(GetCurrentTimeStamp()); } TimeStamp DocumentTimeline::GetCurrentTimeStamp() const { nsRefreshDriver* refreshDriver = GetRefreshDriver(); TimeStamp refreshTime = refreshDriver ? refreshDriver->MostRecentRefresh() : TimeStamp(); // Always return the same object to benefit from return-value optimization. TimeStamp result = !refreshTime.IsNull() ? refreshTime : mLastRefreshDriverTime; // If we don't have a refresh driver and we've never had one use the // timeline's zero time. if (result.IsNull()) { RefPtr<nsDOMNavigationTiming> timing = mDocument->GetNavigationTiming(); if (timing) { result = timing->GetNavigationStartTimeStamp(); // Also, let this time represent the current refresh time. This way // we'll save it as the last refresh time and skip looking up // navigation timing each time. refreshTime = result; } } if (!refreshTime.IsNull()) { mLastRefreshDriverTime = refreshTime; } return result; } Nullable<TimeDuration> DocumentTimeline::ToTimelineTime(const TimeStamp& aTimeStamp) const { Nullable<TimeDuration> result; // Initializes to null if (aTimeStamp.IsNull()) { return result; } RefPtr<nsDOMNavigationTiming> timing = mDocument->GetNavigationTiming(); if (MOZ_UNLIKELY(!timing)) { return result; } result.SetValue(aTimeStamp - timing->GetNavigationStartTimeStamp()); return result; } void DocumentTimeline::NotifyAnimationUpdated(Animation& aAnimation) { AnimationTimeline::NotifyAnimationUpdated(aAnimation); if (!mIsObservingRefreshDriver) { nsRefreshDriver* refreshDriver = GetRefreshDriver(); if (refreshDriver) { refreshDriver->AddRefreshObserver(this, Flush_Style); mIsObservingRefreshDriver = true; } } } void DocumentTimeline::WillRefresh(mozilla::TimeStamp aTime) { MOZ_ASSERT(mIsObservingRefreshDriver); MOZ_ASSERT(GetRefreshDriver(), "Should be able to reach refresh driver from within WillRefresh"); bool needsTicks = false; nsTArray<Animation*> animationsToRemove(mAnimations.Count()); nsAutoAnimationMutationBatch mb(mDocument); for (Animation* animation = mAnimationOrder.getFirst(); animation; animation = animation->getNext()) { // Skip any animations that are longer need associated with this timeline. if (animation->GetTimeline() != this) { // If animation has some other timeline, it better not be also in the // animation list of this timeline object! MOZ_ASSERT(!animation->GetTimeline()); animationsToRemove.AppendElement(animation); continue; } needsTicks |= animation->NeedsTicks(); // Even if |animation| doesn't need future ticks, we should still // Tick it this time around since it might just need a one-off tick in // order to dispatch events. animation->Tick(); if (!animation->IsRelevant() && !animation->NeedsTicks()) { animationsToRemove.AppendElement(animation); } } for (Animation* animation : animationsToRemove) { RemoveAnimation(animation); } if (!needsTicks) { // We already assert that GetRefreshDriver() is non-null at the beginning // of this function but we check it again here to be sure that ticking // animations does not have any side effects that cause us to lose the // connection with the refresh driver, such as triggering the destruction // of mDocument's PresShell. MOZ_ASSERT(GetRefreshDriver(), "Refresh driver should still be valid at end of WillRefresh"); GetRefreshDriver()->RemoveRefreshObserver(this, Flush_Style); mIsObservingRefreshDriver = false; } } void DocumentTimeline::NotifyRefreshDriverCreated(nsRefreshDriver* aDriver) { MOZ_ASSERT(!mIsObservingRefreshDriver, "Timeline should not be observing the refresh driver before" " it is created"); if (!mAnimationOrder.isEmpty()) { aDriver->AddRefreshObserver(this, Flush_Style); mIsObservingRefreshDriver = true; } } void DocumentTimeline::NotifyRefreshDriverDestroying(nsRefreshDriver* aDriver) { if (!mIsObservingRefreshDriver) { return; } aDriver->RemoveRefreshObserver(this, Flush_Style); mIsObservingRefreshDriver = false; } void DocumentTimeline::RemoveAnimation(Animation* aAnimation) { AnimationTimeline::RemoveAnimation(aAnimation); if (mIsObservingRefreshDriver && mAnimations.IsEmpty()) { MOZ_ASSERT(GetRefreshDriver(), "Refresh driver should still be valid when " "mIsObservingRefreshDriver is true"); GetRefreshDriver()->RemoveRefreshObserver(this, Flush_Style); mIsObservingRefreshDriver = false; } } TimeStamp DocumentTimeline::ToTimeStamp(const TimeDuration& aTimeDuration) const { TimeStamp result; RefPtr<nsDOMNavigationTiming> timing = mDocument->GetNavigationTiming(); if (MOZ_UNLIKELY(!timing)) { return result; } result = timing->GetNavigationStartTimeStamp() + aTimeDuration; return result; } nsRefreshDriver* DocumentTimeline::GetRefreshDriver() const { nsIPresShell* presShell = mDocument->GetShell(); if (MOZ_UNLIKELY(!presShell)) { return nullptr; } nsPresContext* presContext = presShell->GetPresContext(); if (MOZ_UNLIKELY(!presContext)) { return nullptr; } return presContext->RefreshDriver(); } } // namespace dom } // namespace mozilla
30.09607
79
0.719965
CGCL-codes
c68f2536aab3eb7207f1c8fb417e434ea0b30229
1,872
cpp
C++
c++/en/dropbox/representative_numbers/representative_numbers/representative_numbers.cpp
aimldl/coding
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
[ "MIT" ]
null
null
null
c++/en/dropbox/representative_numbers/representative_numbers/representative_numbers.cpp
aimldl/coding
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
[ "MIT" ]
null
null
null
c++/en/dropbox/representative_numbers/representative_numbers/representative_numbers.cpp
aimldl/coding
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
[ "MIT" ]
null
null
null
// representative_numbers.cpp #include "pch.h" #include <iostream> #include <fstream> using namespace std; //#define DEBUG 1 #define DEBUG 0 void swap(int &a, int &b) { int t; t = a; a = b; b = t; } void bubble_sort(int* arr, int N) { int b = N; // bar for (int i = 0; i < N; i++) { for (int j = 0; j < b - 1; j++) // j < b-1 { if (arr[j] > arr[j + 1]) swap(arr[j], arr[j + 1]); } b--; } } int get_most_freq_num(int* nums, int N); int main() { ifstream ifs("representative_numbers-ex1.txt"); // Input int N = 10; int* nums = new int[N]; for (int i = 0; i < N; i++) ifs >> nums[i]; int mean; int freq; // Mean mean = 0; for (int i = 0; i < N; i++) { mean += nums[i]; } mean /= N; // Output cout << mean << endl; cout << get_most_freq_num(nums, N) << endl; return 0; } int get_most_freq_num(int* nums, int N) { bubble_sort(nums, N); // Find the frequency of each number int** arr = new int*[2]; //arr[0][i] : number, arr[1][i] : frequency for (int i = 0; i < 2; i++) arr[i] = new int[N]; int ref = nums[0]; int count = 1; int j = 0; for (int i = 1; i < N; i++) { if (ref == nums[i]) { count++; } else { arr[0][j] = ref; arr[1][j] = count; ref = nums[i]; count = 1; j++; } } arr[0][j] = ref; arr[1][j] = count; arr[0][j+1] = -1; arr[1][j+1] = -1; if ( DEBUG ) { j = 0; while (arr[0][j] >= 0) { cout << arr[0][j] << " " << arr[1][j] << endl; j++; } } // Find the max frequency int max_freq = arr[1][0]; int max_idx = 0; j = 1; while (arr[0][j] >= 0) { if (max_freq < arr[1][j]) { max_freq = arr[1][j]; max_idx = j; } j++; } int num_wt_max_freq = arr[0][max_idx]; return num_wt_max_freq; }
14.740157
71
0.470085
aimldl
c6969b82ae72a203a91f8c208b6ee03e3f884f29
51,555
cpp
C++
src/segmenter.cpp
LLNL/LIST
83c78f9dadc8cdfa2cf1d36985a572ba0b276e8b
[ "MIT" ]
12
2020-08-28T02:01:14.000Z
2022-03-23T07:51:33.000Z
src/segmenter.cpp
LLNL/LIST
83c78f9dadc8cdfa2cf1d36985a572ba0b276e8b
[ "MIT" ]
1
2020-09-15T10:42:44.000Z
2022-02-07T21:03:15.000Z
src/segmenter.cpp
LLNL/LIST
83c78f9dadc8cdfa2cf1d36985a572ba0b276e8b
[ "MIT" ]
1
2021-09-05T12:41:07.000Z
2021-09-05T12:41:07.000Z
//****************************************************************************** // Copyright 2019-2020 Lawrence Livermore National Security, LLC and other // LIST Project Developers. See the LICENSE file for details. // SPDX-License-Identifier: MIT // // LIvermore Sem image Tools (LIST) // Segmentation class (.h, .cpp) //*****************************************************************************/ #include "segmenter.h" #include <assert.h> #include <algorithm> #include <fstream> #include <cassert> #include <cstdlib> #include <cstring> #ifdef __LIB_OPENCV #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> using namespace cv; #endif //------------------------------------------------------------------------------ // CImage class //------------------------------------------------------------------------------ CImage::CImage() { m_Dim = MAKE_INT4(0, 0, 0, 0); m_Allocated = false; m_Pixels = NULL; } CImage::CImage(const CImage& Other) { m_Dim = MAKE_INT4(0, 0, 0, 0); m_Allocated = false; m_Pixels = NULL; this->init(Other.m_Dim.x, Other.m_Dim.y, Other.m_Dim.z, Other.m_Dim.w, Other.m_Pixels, Other.m_Allocated); } CImage::CImage(int Width, int Height, int Depth, int Channel, PixelType* Pixels, bool AllocateImage) { m_Dim = MAKE_INT4(0, 0, 0, 0); m_Allocated = false; m_Pixels = NULL; this->init(Width, Height, Depth, Channel, Pixels, AllocateImage); } CImage::~CImage() { this->free(); } void CImage::init(const CImage& Other) { this->free(); this->init(Other.m_Dim.x, Other.m_Dim.y, Other.m_Dim.z, Other.m_Dim.w, Other.m_Pixels, Other.m_Allocated); } void CImage::init(int Width, int Height, int Depth, int Channel, PixelType* Pixels, bool AllocateImage) { this->free(); m_Dim = MAKE_INT4(Width, Height, Depth, Channel); m_Allocated = AllocateImage; if (m_Allocated) { int count = m_Dim.x * m_Dim.y * m_Dim.z * m_Dim.w; m_Pixels = new PixelType[count]; if (Pixels) memcpy(m_Pixels, Pixels, sizeof(PixelType) * count); } else { m_Pixels = Pixels; } } void CImage::free() { if (m_Allocated && m_Pixels) { delete [] m_Pixels; m_Pixels = NULL; } } CImage& CImage::operator = (const CImage& Other) { this->free(); this->init(Other); return *this; } int CImage::getWidth() { return m_Dim.x; } int CImage::getHeight() { return m_Dim.y; } int CImage::getDepth() { return m_Dim.z; } int CImage::getNumChannels() { return m_Dim.w; } int CImage::getNumPixels() { return (m_Dim.x * m_Dim.y * m_Dim.z); } INT4 CImage::getDimension() { return m_Dim; } PixelType* CImage::getPixel(int x) { assert(x >= 0 && x < m_Dim.x * m_Dim.y * m_Dim.z); return &m_Pixels[x * m_Dim.w]; } PixelType* CImage::getPixel(int x, int y) { assert(x >= 0 && x < m_Dim.x && y >= 0 && y < m_Dim.y); return &m_Pixels[(y * m_Dim.x + x) * m_Dim.w]; } PixelType* CImage::getPixel(int x, int y, int z) { assert(x >= 0 && x < m_Dim.x && y >= 0 && y < m_Dim.y && z >= 0 && z < m_Dim.z); return &m_Pixels[(z * m_Dim.y * m_Dim.x + y * m_Dim.x + x) * m_Dim.w]; } PixelType* CImage::getPixels() { return m_Pixels; } void CImage::setPixel(int x, PixelType* value) { assert(x >= 0 && x < m_Dim.x * m_Dim.y * m_Dim.z); PixelType* p = &m_Pixels[x * m_Dim.w]; for (int n = 0; n < m_Dim.w; n++) p[n] = value[n]; } void CImage::setPixel(int x, int y, PixelType* value) { assert(x >= 0 && x < m_Dim.x && y >= 0 && y < m_Dim.y); PixelType* p = &m_Pixels[(y * m_Dim.x + x) * m_Dim.w]; for (int n = 0; n < m_Dim.w; n++) p[n] = value[n]; } void CImage::setPixel(int x, int y, int z, PixelType* value) { assert(x >= 0 && x < m_Dim.x && y >= 0 && y < m_Dim.y && z >= 0 && z < m_Dim.z); PixelType* p = &m_Pixels[(z * m_Dim.y * m_Dim.x + y * m_Dim.x + x) * m_Dim.w]; for (int n = 0; n < m_Dim.w; n++) p[n] = value[n]; } bool CImage::getHistogram(int NumBins, int* Bins) { if (m_Dim.w != 1) return false; // initialize bins for (int n = 0; n < NumBins; n++) Bins[n] = 0; int numpixels = m_Dim.x * m_Dim.y * m_Dim.z; for (int n = 0; n < numpixels; n++) { int npixel = (int)(m_Pixels[n] * (NumBins - 1)); Bins[npixel]++; } return true; } //------------------------------------------------------------------------------ // CSegment class //------------------------------------------------------------------------------ CSegment::CSegment(CSegmenter* Segmenter) : m_Sid(-1), m_Tag(0), m_Segmenter(Segmenter) { m_BoundMin = 0; m_BoundMax = 0; } CSegment::CSegment(const CSegment& Other) : m_Sid(Other.m_Sid), m_Tag(Other.m_Tag), m_Segmenter(Other.m_Segmenter) { m_BoundMin = Other.m_BoundMin; m_BoundMax = Other.m_BoundMax; m_Pixels = Other.m_Pixels; } CSegment& CSegment::operator = (const CSegment& Other) { m_Segmenter = Other.m_Segmenter; m_Sid = Other.m_Sid; m_Tag = Other.m_Tag; m_BoundMin = Other.m_BoundMin; m_BoundMax = Other.m_BoundMax; m_Pixels = Other.m_Pixels; return *this; } void CSegment::init(int Sid, int NumPixels, int* Pixels) { m_Sid = Sid; m_Pixels.clear(); // add pixels, recompute bounding box m_BoundMin = m_Segmenter->getImage()->getWidth(); m_BoundMax = -1; for (int n = 0; n < NumPixels; n++) { int pixel = Pixels[n]; m_Pixels.push_back(pixel); m_BoundMin = __MIN(m_BoundMin, pixel); m_BoundMax = __MAX(m_BoundMax, pixel); } } void CSegment::init(int Sid, int NumPixels, INT2* Pixels) { m_Sid = Sid; m_Pixels.clear(); // add pixels, recompute bounding box int width = m_Segmenter->getImage()->getWidth(); int xmin = m_Segmenter->getImage()->getWidth(); int ymin = m_Segmenter->getImage()->getHeight(); int xmax = -1; int ymax = -1; for (int n = 0; n < NumPixels; n++) { int pindex = Pixels[n].y * width + Pixels[n].x; m_Pixels.push_back(pindex); xmin = __MIN(xmin, Pixels[n].x); ymin = __MIN(ymin, Pixels[n].y); xmax = __MAX(xmax, Pixels[n].x); ymax = __MAX(ymax, Pixels[n].y); } m_BoundMin = ymin * width + xmin; m_BoundMax = ymax * width + xmax; } void CSegment::init(int Sid, int NumPixels, INT3* Pixels) { m_Sid = Sid; m_Pixels.clear(); // add pixels, recompute bounding box int width = m_Segmenter->getImage()->getWidth(); int height = m_Segmenter->getImage()->getHeight(); int xmin = m_Segmenter->getImage()->getWidth(); int ymin = m_Segmenter->getImage()->getHeight(); int zmin = m_Segmenter->getImage()->getDepth(); int xmax = -1; int ymax = -1; int zmax = -1; for (int n = 0; n < NumPixels; n++) { int pindex = Pixels[n].z * width * height + Pixels[n].y * width + Pixels[n].x; m_Pixels.push_back(pindex); xmin = __MIN(xmin, Pixels[n].x); ymin = __MIN(ymin, Pixels[n].y); zmin = __MIN(zmin, Pixels[n].z); xmax = __MAX(xmax, Pixels[n].x); ymax = __MAX(ymax, Pixels[n].y); zmax = __MAX(zmax, Pixels[n].z); } m_BoundMin = zmin * width * height + ymin * width + xmin; m_BoundMax = zmax * width * height + ymax * width + xmax; } int CSegment::getNumPixels() { return (int)m_Pixels.size(); } int CSegment::getPixels(std::vector<int>& Pixels) { Pixels = m_Pixels; return (int)m_Pixels.size(); } int CSegment::getPixels(std::vector<INT2>& Pixels) { Pixels.resize(m_Pixels.size()); int width = m_Segmenter->getImage()->getWidth(); for (size_t n = 0; n < m_Pixels.size(); n++) { int pindex = m_Pixels[n]; Pixels[n].x = pindex % width; Pixels[n].y = pindex / width; } return (int)m_Pixels.size(); } int CSegment::getPixels(std::vector<INT3>& Pixels) { Pixels.resize(m_Pixels.size()); int width = m_Segmenter->getImage()->getWidth(); int height = m_Segmenter->getImage()->getHeight(); for (size_t n = 0; n < m_Pixels.size(); n++) { int pindex = m_Pixels[n]; int z = pindex / (width * height); int y = (pindex - z * width * height) / width; int x = (pindex - z * width * height - y * width) % width; Pixels[n] = MAKE_INT3(x, y, z); } return (int)m_Pixels.size(); } void CSegment::getBoundBox(int& XMin, int& XMax) { XMin = m_BoundMin; XMax = m_BoundMax; } void CSegment::getBoundBox(int& XMin, int& YMin, int& XMax, int& YMax) { int width = m_Segmenter->getImage()->getWidth(); XMin = m_BoundMin % width; YMin = m_BoundMin / width; XMax = m_BoundMax % width; YMax = m_BoundMax / width; } void CSegment::getBoundBox(int& XMin, int& YMin, int& ZMin, int& XMax, int& YMax, int& ZMax) { int width = m_Segmenter->getImage()->getWidth(); int height = m_Segmenter->getImage()->getHeight(); ZMin = m_BoundMin / (width * height); YMin = (m_BoundMin - ZMin * width * height) / width; XMin = (m_BoundMin - ZMin * width * height - YMin * width) % width; ZMax = m_BoundMax / (width * height); YMax = (m_BoundMax - ZMax * width * height) / width; XMax = (m_BoundMax - ZMax * width * height - YMax * width) % width; } int CSegment::getNumBoundPixels() { int height = m_Segmenter->getImage()->getHeight(); int depth = m_Segmenter->getImage()->getDepth(); int bcount = 0; if (height == 1 && depth == 1) { for (size_t n = 0; n < m_Pixels.size(); n++) { int x = m_Pixels[n]; int sid1 = m_Segmenter->getSegmentId(x - 1); int sid2 = m_Segmenter->getSegmentId(x + 1); if (sid1 != m_Sid || sid2 != m_Sid) bcount++; } } else if (depth == 1) { std::vector<INT2> pixels; this->getPixels(pixels); for (size_t n = 0; n < pixels.size(); n++) { int x = pixels[n].x; int y = pixels[n].y; int sid1 = m_Segmenter->getSegmentId(x - 1, y); int sid2 = m_Segmenter->getSegmentId(x + 1, y); int sid3 = m_Segmenter->getSegmentId(x, y - 1); int sid4 = m_Segmenter->getSegmentId(x, y + 1); if (sid1 != m_Sid || sid2 != m_Sid || sid3 != m_Sid || sid4 != m_Sid) bcount++; } } else { std::vector<INT3> pixels; this->getPixels(pixels); for (size_t n = 0; n < pixels.size(); n++) { int x = pixels[n].x; int y = pixels[n].y; int z = pixels[n].z; int sid1 = m_Segmenter->getSegmentId(x - 1, y, z); int sid2 = m_Segmenter->getSegmentId(x + 1, y, z); int sid3 = m_Segmenter->getSegmentId(x, y - 1, z); int sid4 = m_Segmenter->getSegmentId(x, y + 1, z); int sid5 = m_Segmenter->getSegmentId(x, y, z - 1); int sid6 = m_Segmenter->getSegmentId(x, y, z + 1); if (sid1 != m_Sid || sid2 != m_Sid || sid3 != m_Sid || sid4 != m_Sid || sid5 != m_Sid || sid6 != m_Sid) bcount++; } } return bcount; } int CSegment::getBoundPixels(std::vector<int>& BoundPixels) { for (size_t n = 0; n < m_Pixels.size(); n++) { int x = m_Pixels[n]; int sid1 = m_Segmenter->getSegmentId(x - 1); int sid2 = m_Segmenter->getSegmentId(x + 1); if (sid1 != m_Sid || sid2 != m_Sid) BoundPixels.push_back(x); } return (int)BoundPixels.size(); } int CSegment::getBoundPixels(std::vector<INT2>& BoundPixels) { std::vector<INT2> pixels; this->getPixels(pixels); for (size_t n = 0; n < pixels.size(); n++) { int x = pixels[n].x; int y = pixels[n].y; int sid1 = m_Segmenter->getSegmentId(x - 1, y); int sid2 = m_Segmenter->getSegmentId(x + 1, y); int sid3 = m_Segmenter->getSegmentId(x, y - 1); int sid4 = m_Segmenter->getSegmentId(x, y + 1); if (sid1 != m_Sid || sid2 != m_Sid || sid3 != m_Sid || sid4 != m_Sid) BoundPixels.push_back(MAKE_INT2(x, y)); } return (int)BoundPixels.size(); } int CSegment::getBoundPixels(std::vector<INT3>& BoundPixels) { std::vector<INT3> pixels; this->getPixels(pixels); for (size_t n = 0; n < pixels.size(); n++) { int x = pixels[n].x; int y = pixels[n].y; int z = pixels[n].z; int sid1 = m_Segmenter->getSegmentId(x - 1, y, z); int sid2 = m_Segmenter->getSegmentId(x + 1, y, z); int sid3 = m_Segmenter->getSegmentId(x, y - 1, z); int sid4 = m_Segmenter->getSegmentId(x, y + 1, z); int sid5 = m_Segmenter->getSegmentId(x, y, z - 1); int sid6 = m_Segmenter->getSegmentId(x, y, z + 1); if (sid1 != m_Sid || sid2 != m_Sid || sid3 != m_Sid || sid4 != m_Sid || sid5 != m_Sid || sid6 != m_Sid) BoundPixels.push_back(MAKE_INT3(x, y, z)); } return (int)BoundPixels.size(); } int CSegment::getNumBoundPixels(CSegment& Other) { int height = m_Segmenter->getImage()->getHeight(); int depth = m_Segmenter->getImage()->getDepth(); int asid = Other.getSid(); int bcount = 0; if (height == 1 && depth == 1) { for (size_t n = 0; n < m_Pixels.size(); n++) { int x = m_Pixels[n]; int sid1 = m_Segmenter->getSegmentId(x - 1); int sid2 = m_Segmenter->getSegmentId(x + 1); if (sid1 == asid || sid2 == asid) bcount++; } } else if (depth == 1) { std::vector<INT2> pixels; this->getPixels(pixels); for (size_t n = 0; n < pixels.size(); n++) { int x = pixels[n].x; int y = pixels[n].y; int sid1 = m_Segmenter->getSegmentId(x - 1, y); int sid2 = m_Segmenter->getSegmentId(x + 1, y); int sid3 = m_Segmenter->getSegmentId(x, y - 1); int sid4 = m_Segmenter->getSegmentId(x, y + 1); if (sid1 == asid || sid2 == asid || sid3 == asid || sid4 == asid) bcount++; } } else { std::vector<INT3> pixels; this->getPixels(pixels); for (size_t n = 0; n < pixels.size(); n++) { int x = pixels[n].x; int y = pixels[n].y; int z = pixels[n].z; int sid1 = m_Segmenter->getSegmentId(x - 1, y, z); int sid2 = m_Segmenter->getSegmentId(x + 1, y, z); int sid3 = m_Segmenter->getSegmentId(x, y - 1, z); int sid4 = m_Segmenter->getSegmentId(x, y + 1, z); int sid5 = m_Segmenter->getSegmentId(x, y, z - 1); int sid6 = m_Segmenter->getSegmentId(x, y, z + 1); if (sid1 == asid || sid2 == asid || sid3 == asid || sid4 == asid || sid5 == asid || sid6 == asid) bcount++; } } return bcount; } int CSegment::getBoundPixels(CSegment& Other, std::vector<int>& BoundPixels) { int asid = Other.getSid(); for (size_t n = 0; n < m_Pixels.size(); n++) { int x = m_Pixels[n]; int sid1 = m_Segmenter->getSegmentId(x - 1); int sid2 = m_Segmenter->getSegmentId(x + 1); if (sid1 == asid || sid2 == asid) BoundPixels.push_back(x); } return (int)BoundPixels.size(); } int CSegment::getBoundPixels(CSegment& Other, std::vector<INT2>& BoundPixels) { int asid = Other.getSid(); std::vector<INT2> pixels; this->getPixels(pixels); for (size_t n = 0; n < pixels.size(); n++) { int x = pixels[n].x; int y = pixels[n].y; int sid1 = m_Segmenter->getSegmentId(x - 1, y); int sid2 = m_Segmenter->getSegmentId(x + 1, y); int sid3 = m_Segmenter->getSegmentId(x, y - 1); int sid4 = m_Segmenter->getSegmentId(x, y + 1); if (sid1 == asid || sid2 == asid || sid3 == asid || sid4 == asid) BoundPixels.push_back(MAKE_INT2(x, y)); } return (int)BoundPixels.size(); } int CSegment::getBoundPixels(CSegment& Other, std::vector<INT3>& BoundPixels) { int asid = Other.getSid(); std::vector<INT3> pixels; this->getPixels(pixels); for (size_t n = 0; n < pixels.size(); n++) { int x = pixels[n].x; int y = pixels[n].y; int z = pixels[n].z; int sid1 = m_Segmenter->getSegmentId(x - 1, y, z); int sid2 = m_Segmenter->getSegmentId(x + 1, y, z); int sid3 = m_Segmenter->getSegmentId(x, y - 1, z); int sid4 = m_Segmenter->getSegmentId(x, y + 1, z); int sid5 = m_Segmenter->getSegmentId(x, y, z - 1); int sid6 = m_Segmenter->getSegmentId(x, y, z + 1); if (sid1 == asid || sid2 == asid || sid3 == asid || sid4 == asid || sid5 == asid || sid6 == asid) BoundPixels.push_back(MAKE_INT3(x, y, z)); } return (int)BoundPixels.size(); } int CSegment::getCentroid(int& Centroid) { if (m_Pixels.size() == 0) return 0; std::vector<int> pixels; this->getPixels(pixels); Centroid = 0; for (size_t n = 0; n < pixels.size(); n++) { Centroid += pixels[n]; } Centroid = (int)((float)Centroid / pixels.size()); if (m_Segmenter->getSegmentId(Centroid) == m_Sid) return 1; else return -1; } int CSegment::getCentroid(INT2& Centroid) { if (m_Pixels.size() == 0) return 0; std::vector<INT2> pixels; this->getPixels(pixels); Centroid = MAKE_INT2(0, 0); for (size_t n = 0; n < pixels.size(); n++) { INT2 p = pixels[n]; Centroid.x += p.x; Centroid.y += p.y; } Centroid.x = (int)((float)Centroid.x / pixels.size()); Centroid.y = (int)((float)Centroid.y / pixels.size()); if (m_Segmenter->getSegmentId(Centroid.x, Centroid.y) == m_Sid) return 1; else return -1; } int CSegment::getCentroid(INT3& Centroid) { if (m_Pixels.size() == 0) return 0; std::vector<INT3> pixels; this->getPixels(pixels); Centroid = MAKE_INT3(0, 0, 0); for (size_t n = 0; n < pixels.size(); n++) { INT3 p = pixels[n]; Centroid.x += p.x; Centroid.y += p.y; Centroid.z += p.z; } Centroid.x = (int)((float)Centroid.x / pixels.size()); Centroid.y = (int)((float)Centroid.y / pixels.size()); Centroid.z = (int)((float)Centroid.z / pixels.size()); if (m_Segmenter->getSegmentId(Centroid.x, Centroid.y, Centroid.z) == m_Sid) return 1; else return -1; } int CSegment::getContours(std::vector<std::vector<INT2> >& Contours) { const int delta8[8][2] = {{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}}; // 8-way //const int delta4[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; // 4-way const int dir8[8] = {7, 7, 1, 1, 3, 3, 5, 5}; if (m_Pixels.size() == 0) return 0; // get bounding box int xmin, ymin, xmax, ymax; this->getBoundBox(xmin, ymin, xmax, ymax); int width = xmax - xmin + 1; int height = ymax - ymin + 1; std::vector<INT2> bpixels; this->getBoundPixels(bpixels); std::vector<int> btags(height * width, 0); // 0: no boundary, 1: boundary, 2: traced boundary for (size_t p = 0; p < bpixels.size(); p++) btags[(bpixels[p].y - ymin) * width + (bpixels[p].x - xmin)] = 1; // search for any untraced boundary for (int y = ymin; y <= ymax; y++) { for (int x = xmin; x <= xmax; x++) { if (btags[(y - ymin) * width + (x - xmin)] != 1) continue; std::vector<INT2> contour; contour.push_back(MAKE_INT2(x, y)); int cx = x; int cy = y; int sx = x; int sy = y; int sx2 = x; int sy2 = y; int dir = 0; bool background = false; while (true) { for (int n = 0; n <= 8; n++, dir++) { if (dir > 7) dir = 0; int px = cx + delta8[dir][0]; int py = cy + delta8[dir][1]; if (px < xmin || px > xmax || py < ymin || py > ymax) { background = true; } else if (btags[(py - ymin) * width + (px - xmin)] == 0) { //btags[(py - ymin) * width + (px - xmin)] = -1; background = true; } else if (btags[(py - ymin) * width + (px - xmin)] == 1) { // != -1) { contour.push_back(MAKE_INT2(px, py)); if (sx2 == sx && sy2 == sy && dir % 2 == 1) { // diagonal tracing, then store the first movement sx2 = cx; sy2 = cy; } // for next tracing cx = px; cy = py; dir = dir8[dir]; break; } } // this contour ends with the start point (one point contour also possible) if ((cx == sx && cy == sy) || (cx == sx2 && cy == sy2)) break; } // tag all traced contour pixels to 2 for (size_t p = 0; p < contour.size(); p++) btags[(contour[p].y - ymin) * width + (contour[p].x - xmin)] = 2; Contours.push_back(contour); } } return (int)Contours.size(); } int CSegment::getAdjacentSegments(std::vector<int>& ABSids) { std::set<int> sidset; int height = m_Segmenter->getImage()->getHeight(); int depth = m_Segmenter->getImage()->getDepth(); if (height == 1 && depth == 1) { for (size_t n = 0; n < m_Pixels.size(); n++) { int x = m_Pixels[n]; int sid1 = m_Segmenter->getSegmentId(x - 1); int sid2 = m_Segmenter->getSegmentId(x + 1); if (sid1 != -1 && sid1 != m_Sid) sidset.insert(sid1); if (sid2 != -1 && sid2 != m_Sid) sidset.insert(sid2); } } else if (depth == 1) { std::vector<INT2> pixels; this->getPixels(pixels); for (size_t n = 0; n < pixels.size(); n++) { int x = pixels[n].x; int y = pixels[n].y; int sid1 = m_Segmenter->getSegmentId(x - 1, y); int sid2 = m_Segmenter->getSegmentId(x + 1, y); int sid3 = m_Segmenter->getSegmentId(x, y - 1); int sid4 = m_Segmenter->getSegmentId(x, y + 1); if (sid1 != -1 && sid1 != m_Sid) sidset.insert(sid1); if (sid2 != -1 && sid2 != m_Sid) sidset.insert(sid2); if (sid3 != -1 && sid3 != m_Sid) sidset.insert(sid3); if (sid4 != -1 && sid4 != m_Sid) sidset.insert(sid4); } } else { std::vector<INT3> pixels; this->getPixels(pixels); for (size_t n = 0; n < pixels.size(); n++) { int x = pixels[n].x; int y = pixels[n].y; int z = pixels[n].z; int sid1 = m_Segmenter->getSegmentId(x - 1, y, z); int sid2 = m_Segmenter->getSegmentId(x + 1, y, z); int sid3 = m_Segmenter->getSegmentId(x, y - 1, z); int sid4 = m_Segmenter->getSegmentId(x, y + 1, z); int sid5 = m_Segmenter->getSegmentId(x, y, z - 1); int sid6 = m_Segmenter->getSegmentId(x, y, z + 1); if (sid1 != -1 && sid1 != m_Sid) sidset.insert(sid1); if (sid2 != -1 && sid2 != m_Sid) sidset.insert(sid2); if (sid3 != -1 && sid3 != m_Sid) sidset.insert(sid3); if (sid4 != -1 && sid4 != m_Sid) sidset.insert(sid4); if (sid5 != -1 && sid5 != m_Sid) sidset.insert(sid5); if (sid6 != -1 && sid6 != m_Sid) sidset.insert(sid6); } } ABSids.clear(); ABSids.insert(ABSids.end(), sidset.begin(), sidset.end()); return (int)ABSids.size(); } bool CSegment::isAdjacent(CSegment& Other) { return (this->getNumBoundPixels(Other) > 0); } //------------------------------------------------------------------------------ // CSegmenter class //------------------------------------------------------------------------------ CSegmenter::CSegmenter(CImage* Image) { m_Image = Image; m_Labels = NULL; this->init(); } CSegmenter::CSegmenter(const CSegmenter& Other) { m_Image = Other.m_Image; m_Labels = NULL; this->assign(Other); } CSegmenter::~CSegmenter() { if (m_Labels) delete [] m_Labels; } void CSegmenter::assign(const CSegmenter& Other) { if (m_Labels) delete [] m_Labels; m_Image = Other.m_Image; m_Labels = new int[m_Image->getNumPixels()]; memcpy(m_Labels, Other.m_Labels, sizeof(int) * m_Image->getNumPixels()); m_Segments = Other.m_Segments; } CSegmenter& CSegmenter::operator = (const CSegmenter& Other) { this->assign(Other); return *this; } bool CSegmenter::init() { if (m_Image->getNumPixels() == 0) return false; if (m_Labels) delete [] m_Labels; m_Labels = new int[m_Image->getNumPixels()]; for (int n = 0; n < m_Image->getNumPixels(); n++) m_Labels[n] = -1; m_Segments.clear(); return true; } bool CSegmenter::loadFromLabels(int* PixelLabels, bool KeepLabel, int NConnectivity) { this->init(); if (KeepLabel) { // assuming that there's no empty labeled region int pixelcount = m_Image->getNumPixels(); // copy labels memcpy(m_Labels, PixelLabels, sizeof(int) * pixelcount); // get # segments int maxlabel = 0; for (int p = 0; p < pixelcount; p++) maxlabel = __MAX(maxlabel, m_Labels[p]); int numsegments = maxlabel + 1; // collect each segment's pixels std::vector<INT3>* segmentpixels = new std::vector<INT3>[numsegments]; for (int z = 0; z < m_Image->getDepth(); z++) { for (int y = 0; y < m_Image->getHeight(); y++) { for (int x = 0; x < m_Image->getWidth(); x++) { int offset = z * m_Image->getWidth() * m_Image->getHeight() + y * m_Image->getWidth() + x; int sid = m_Labels[offset]; INT3 pixel = MAKE_INT3(x, y, z); segmentpixels[sid].push_back(pixel); } } } // setup segment list for (int sid = 0; sid < numsegments; sid++) { CSegment segment(this); segment.init(sid, (int)segmentpixels[sid].size(), &segmentpixels[sid][0]); m_Segments.push_back(segment); } delete [] segmentpixels; } else { // separate any labeled region if part of the region is disconnected // set 4- or 8-neighbors (in 2D), 6- or 26-neighbors (in 3D) INT3 neighbors[27]; int numneighbors = getNeighborConnectivity(NConnectivity, neighbors); // allocate search queue INT3* searchlist = new INT3[m_Image->getNumPixels()]; memset(searchlist, 0, sizeof(INT3) * m_Image->getNumPixels()); // traverse labels int sid = 0; for (int z = 0; z < m_Image->getDepth(); z++) { for (int y = 0; y < m_Image->getHeight(); y++) { for (int x = 0; x < m_Image->getWidth(); x++) { int offset = z * m_Image->getWidth() * m_Image->getHeight() + y * m_Image->getWidth() + x; if (m_Labels[offset] != -1) // if already assigned continue; // set segment id m_Labels[offset] = sid; // read integer label int label = PixelLabels[offset]; // initialize segment list searchlist[0].x = x; searchlist[0].y = y; searchlist[0].z = z; int searchlist_current = 0; int searchlist_count = 1; // do until all voxels in the list are evaluated while (searchlist_current < searchlist_count) { // check all neighbors for (int n = 0; n < numneighbors; n++) { int nx = searchlist[searchlist_current].x + neighbors[n].x; int ny = searchlist[searchlist_current].y + neighbors[n].y; int nz = searchlist[searchlist_current].z + neighbors[n].z; if (nx < 0 || nx >= m_Image->getWidth() || ny < 0 || ny >= m_Image->getHeight() || nz < 0 || nz >= m_Image->getDepth()) continue; int noffset = nz * m_Image->getWidth() * m_Image->getHeight() + ny * m_Image->getWidth() + nx; if (m_Labels[noffset] != -1) // if already assigned continue; if (PixelLabels[noffset] != label) continue; // set label m_Labels[noffset] = sid; searchlist[searchlist_count].x = nx; searchlist[searchlist_count].y = ny; searchlist[searchlist_count].z = nz; searchlist_count++; } searchlist_current++; } // set segment info CSegment segment(this); segment.init(sid, searchlist_count, searchlist); m_Segments.push_back(segment); sid++; } } } delete [] searchlist; } return true; } bool CSegmenter::loadFromLabelFile(std::string FilePath) { std::ifstream file(FilePath.c_str(), std::ios::binary); if (!file.is_open()) return false; file.seekg(0, std::ios::end); int filesize = (int)file.tellg(); file.seekg(0, std::ios::beg); std::vector<int> labels(m_Image->getNumPixels()); if (filesize == m_Image->getNumPixels()) { uchar* clabels = new uchar[m_Image->getNumPixels()]; file.read((char*)clabels, sizeof(uchar) * m_Image->getNumPixels()); for (int n = 0; n < m_Image->getNumPixels(); n++) labels[n] = clabels[n]; delete [] clabels; } else if (filesize == m_Image->getNumPixels() * 2) { ushort* clabels = new ushort[m_Image->getNumPixels()]; file.read((char*)clabels, sizeof(ushort) * m_Image->getNumPixels()); for (int n = 0; n < m_Image->getNumPixels(); n++) labels[n] = clabels[n]; delete [] clabels; } else { file.read((char*)&labels[0], sizeof(int) * m_Image->getNumPixels()); } file.close(); return this->loadFromLabels(&labels[0], true); } bool CSegmenter::saveToLabelFile(std::string FilePath, bool Compact) { std::ofstream file(FilePath.c_str(), std::ios::binary); if (!file.is_open()) return false; int maxsid = this->getMaxSegmentId(); if (Compact && maxsid <= 0xff) { uchar* clabels = new uchar[m_Image->getNumPixels()]; for (int n = 0; n < m_Image->getNumPixels(); n++) clabels[n] = (uchar)m_Labels[n]; file.write((char*)clabels, sizeof(uchar) * m_Image->getNumPixels()); delete [] clabels; } else if (Compact && maxsid <= 0xffff) { ushort* clabels = new ushort[m_Image->getNumPixels()]; for (int n = 0; n < m_Image->getNumPixels(); n++) clabels[n] = (ushort)m_Labels[n]; file.write((char*)clabels, sizeof(ushort) * m_Image->getNumPixels()); delete [] clabels; } else { file.write((char*)m_Labels, sizeof(int) * m_Image->getNumPixels()); } file.close(); return true; } bool CSegmenter::saveToImageFile(std::string ImageFilePrefix, int ImageMode, bool Flip, UCHAR3 BoundColor) { if (!m_Labels) return false; for (int slice = 0; slice < m_Image->getDepth(); slice++) { bool ret = this->saveToImageFile(ImageFilePrefix, slice, ImageMode, Flip, BoundColor); if (!ret) return false; } return true; } bool CSegmenter::saveToImageFile(std::string ImageFilePrefix, int SliceIndex, int ImageMode, bool Flip, UCHAR3 BoundColor) { if (!m_Labels) return false; #ifdef __LIB_OPENCV Mat image = Mat(m_Image->getHeight(), m_Image->getWidth(), CV_8UC3); if (!this->setToImage(image.data, SliceIndex, ImageMode, Flip, BoundColor)) return false; char imagefile[512]; if (m_Image->getDepth() <= 1) sprintf(imagefile, "%s.png", ImageFilePrefix.c_str()); else sprintf(imagefile, "%s_slice%d.png", ImageFilePrefix.c_str(), SliceIndex); return imwrite(imagefile, image); #else return false; #endif } // ImageMode // -1: original image // 0: original image color + boundary (boundary color) // 1: original image + boundary (segment color) // 2: segment color + boundary (boundary color) // 3: segment color only // 4: original image + segment color (blended) bool CSegmenter::setToImage(uchar* Image, int SliceIndex, int ImageMode, bool Flip, UCHAR3 BoundColor) { const UCHAR3 __color[18] = {{0, 0, 0}, {32, 32, 32}, {255, 0, 0}, {0, 255, 0}, {0, 0, 255}, {255, 255, 0}, {255, 0, 255}, {0, 255, 255}, {255, 64, 0}, {255, 0, 64}, {64, 0, 255}, {0, 64, 255}, {64, 255, 0}, {0, 255, 64}, {255, 128, 128}, {128, 64, 32}, {64, 128, 32}, {64, 32, 128}}; if (!m_Labels) return false; if (m_Image->getDepth() > 1 && (SliceIndex < 0 || SliceIndex >= m_Image->getDepth())) { printf("Invalid slice index"); return false; } for (int y = 0; y < m_Image->getHeight(); y++) { for (int x = 0; x < m_Image->getWidth(); x++) { int sid; bool bound; PixelType* pixel; if (m_Image->getDepth() == 1) { sid = this->getSegmentId(x, y); bound = this->isBoundPixel(x, y); pixel = m_Image->getPixel(x, y); } else { sid = this->getSegmentId(x, y, SliceIndex); bound = this->isBoundPixelSlice(x, y, SliceIndex); pixel = m_Image->getPixel(x, y, SliceIndex); } int cind = (sid + 1) % 18; UCHAR3 segcolor = MAKE_UCHAR3(__color[cind].x, __color[cind].y, __color[cind].z); UCHAR3 orgcolor; if (m_Image->getNumChannels() >= 3) orgcolor = MAKE_UCHAR3((uchar)(pixel[0] * 255), (uchar)(pixel[1] * 255), (uchar)(pixel[2] * 255)); else orgcolor = MAKE_UCHAR3((uchar)(pixel[0] * 255), (uchar)(pixel[0] * 255), (uchar)(pixel[0] * 255)); UCHAR3 color; if (ImageMode == -1) { color = orgcolor; } else if (ImageMode == 0) { color = ((bound) ? BoundColor : orgcolor); } else if (ImageMode == 1) { color = ((bound) ? segcolor : orgcolor); } else if (ImageMode == 2) { color = ((bound) ? BoundColor : segcolor); } else if (ImageMode == 3) { color = segcolor; } else if (ImageMode == 4) { color.x = (uchar)__MIN(orgcolor.x * 0.6 + segcolor.x * 0.4, 255); color.y = (uchar)__MIN(orgcolor.y * 0.6 + segcolor.y * 0.4, 255); color.z = (uchar)__MIN(orgcolor.z * 0.6 + segcolor.z * 0.4, 255); } int y2 = (Flip) ? (m_Image->getHeight() - 1 - y) : y; Image[(y2 * m_Image->getWidth() + x) * 3 + 0] = color.x; Image[(y2 * m_Image->getWidth() + x) * 3 + 1] = color.y; Image[(y2 * m_Image->getWidth() + x) * 3 + 2] = color.z; } } return true; } int CSegmenter::getNeighborConnectivity(int NConnectivity, INT3 neighbors[27]) { // initialize neighbor info memset(neighbors, 0, sizeof(INT3) * 27); // set 4- or 8-neighbors (in 2D), 6- or 26-neighbors (in 3D) int numneighbors; if (m_Image->getDepth() <= 1) { if (NConnectivity == 2) { numneighbors = 0; for (int y = -1; y <= 1; y++) { for (int x = -1; x <= 1; x++) { if (x == 0 && y == 0) continue; neighbors[numneighbors].x = x; neighbors[numneighbors].y = y; numneighbors++; } } } else { numneighbors = 4; neighbors[0].x = -1; neighbors[0].y = 0; neighbors[1].x = +1; neighbors[1].y = 0; neighbors[2].x = 0; neighbors[2].y = -1; neighbors[3].x = 0; neighbors[3].y = +1; } } else { if (NConnectivity == 2) { numneighbors = 0; for (int z = -1; z <= 1; z++) { for (int y = -1; y <= 1; y++) { for (int x = -1; x <= 1; x++) { if (x == 0 && y == 0 && z == 0) continue; neighbors[numneighbors].x = x; neighbors[numneighbors].y = y; neighbors[numneighbors].z = z; numneighbors++; } } } } else { numneighbors = 6; neighbors[0].x = -1; neighbors[0].y = 0; neighbors[0].z = 0; neighbors[1].x = +1; neighbors[1].y = 0; neighbors[1].z = 0; neighbors[2].x = 0; neighbors[2].y = -1; neighbors[2].z = 0; neighbors[3].x = 0; neighbors[3].y = +1; neighbors[3].z = 0; neighbors[4].x = 0; neighbors[4].y = 0; neighbors[4].z = -1; neighbors[5].x = 0; neighbors[5].y = 0; neighbors[5].z = +1; } } return numneighbors; } bool CSegmenter::segmentSimpleRegionGrowing(int NConnectivity, int MinSegment, int MaxSegment, double Threshold) { this->init(); // set 4- or 8-neighbors (in 2D), 6- or 26-neighbors (in 3D) INT3 neighbors[27]; int numneighbors = getNeighborConnectivity(NConnectivity, neighbors); // initialize search queue int count = m_Image->getNumPixels(); INT3* searchlist = new INT3[count]; memset(searchlist, 0, sizeof(INT3) * count); // for every pixel int sid = 0; for (int z = 0; z < m_Image->getDepth(); z++) { for (int y = 0; y < m_Image->getHeight(); y++) { for (int x = 0; x < m_Image->getWidth(); x++) { int offset = z * m_Image->getWidth() * m_Image->getHeight() + y * m_Image->getWidth() + x; if (m_Labels[offset] != -1) // if already assigned continue; // set segment id m_Labels[offset] = sid; // read pixel std::vector<double> vsum(4); float* pvalue = m_Image->getPixel(x, y, z); for (int c = 0; c < m_Image->getNumChannels(); c++) vsum[c] = pvalue[c]; // initialize segment list searchlist[0].x = x; searchlist[0].y = y; searchlist[0].z = z; int searchlist_current = 0; int searchlist_count = 1; // do until all voxels in the list are evaluated while (searchlist_current < searchlist_count) { // check all neighbors for (int n = 0; n < numneighbors; n++) { int nx = searchlist[searchlist_current].x + neighbors[n].x; int ny = searchlist[searchlist_current].y + neighbors[n].y; int nz = searchlist[searchlist_current].z + neighbors[n].z; if (nx < 0 || nx >= m_Image->getWidth() || ny < 0 || ny >= m_Image->getHeight() || nz < 0 || nz >= m_Image->getDepth()) continue; if (MaxSegment > 0) { if (abs(nx - x) > MaxSegment || abs(ny - y) > MaxSegment || abs(nz - z) > MaxSegment) continue; } int noffset = nz * m_Image->getWidth() * m_Image->getHeight() + ny * m_Image->getWidth() + nx; if (m_Labels[noffset] != -1) // if already assigned continue; // adjust threshold double thres = Threshold; if (searchlist_count < MinSegment) thres = (2 * Threshold) - (Threshold * searchlist_count / MinSegment); // check whether or not difference between the current pixel/voxel value and the mean value is above threshold bool nextneighbor = false; float* npvalue = m_Image->getPixel(nx, ny, nz); for (int c = 0; c < m_Image->getNumChannels(); c++) { double vmean = (double)vsum[c] / searchlist_count; if (fabs(npvalue[c] - vmean) > thres) { nextneighbor = true; break; } } if (nextneighbor) continue; // update sum for (int c = 0; c < m_Image->getNumChannels(); c++) vsum[c] += npvalue[c]; // set label m_Labels[noffset] = sid; searchlist[searchlist_count].x = nx; searchlist[searchlist_count].y = ny; searchlist[searchlist_count].z = nz; searchlist_count++; } searchlist_current++; } // set segment info CSegment segment(this); segment.init(sid, searchlist_count, searchlist); m_Segments.push_back(segment); sid++; } } } delete [] searchlist; return true; } bool CSegmenter::pruneBySegmentId(std::vector<int>& Sids) { if (m_Segments.size() == 0) return false; std::vector<int> segment_labels(m_Segments.size()); for (size_t sid = 0; sid < m_Segments.size(); sid++) segment_labels[sid] = sid; for (size_t s = 0; s < Sids.size(); s++) { int sid = Sids[s]; CSegment* segment = &m_Segments[sid]; std::vector<int> asids; segment->getAdjacentSegments(asids); int asid_max = asids[0]; int asize_max = 0; for (size_t n = 0; n < asids.size(); n++) { int asid = asids[n]; CSegment* asegment = &m_Segments[asid]; int asize = asegment->getNumPixels(); if (asize_max < asize) { asize_max = asize; asid_max = asid; } } segment_labels[sid] = asid_max; } std::vector<int> labels(m_Image->getNumPixels()); for (size_t sid = 0; sid < m_Segments.size(); sid++) { CSegment* segment = &m_Segments[sid]; int seglabel = segment_labels[sid]; std::vector<int> segpixels; segment->getPixels(segpixels); for (size_t p = 0; p < segpixels.size(); p++) { int pindex = segpixels[p]; labels[pindex] = seglabel; } } this->loadFromLabels(&labels[0], false); return true; } bool CSegmenter::pruneBySegmentSize(int SegmentSize) { if (m_Segments.size() == 0) return false; std::vector<int> segment_labels(m_Segments.size()); for (size_t sid = 0; sid < m_Segments.size(); sid++) { CSegment* segment = &m_Segments[sid]; if (segment->getNumPixels() <= SegmentSize) { std::vector<int> asids; segment->getAdjacentSegments(asids); int asid_max = asids[0]; int asize_max = 0; for (size_t n = 0; n < asids.size(); n++) { int asid = asids[n]; CSegment* asegment = &m_Segments[asid]; int asize = asegment->getNumPixels(); if (asize_max < asize) { asize_max = asize; asid_max = asid; } } segment_labels[sid] = asid_max; } else { segment_labels[sid] = sid; } } std::vector<int> labels(m_Image->getNumPixels()); for (size_t sid = 0; sid < m_Segments.size(); sid++) { CSegment* segment = &m_Segments[sid]; int seglabel = segment_labels[sid]; std::vector<int> segpixels; segment->getPixels(segpixels); for (size_t p = 0; p < segpixels.size(); p++) { int pindex = segpixels[p]; labels[pindex] = seglabel; } } this->loadFromLabels(&labels[0], false); return true; } bool CSegmenter::isBoundPixel(int x) { int sid = this->getSegmentId(x); int sid1 = this->getSegmentId(x - 1); int sid2 = this->getSegmentId(x + 1); if ((sid1 != -1 && sid1 != sid) || (sid2 != -1 && sid2 != sid)) return true; else return false; } bool CSegmenter::isBoundPixel(int x, int y) { int sid = this->getSegmentId(x, y); int sid1 = this->getSegmentId(x - 1, y); int sid2 = this->getSegmentId(x + 1, y); int sid3 = this->getSegmentId(x, y - 1); int sid4 = this->getSegmentId(x, y + 1); if ((sid1 != -1 && sid1 != sid) || (sid2 != -1 && sid2 != sid) || (sid3 != -1 && sid3 != sid) || (sid4 != -1 && sid4 != sid)) return true; else return false; } bool CSegmenter::isBoundPixel(int x, int y, int z) { int sid = this->getSegmentId(x, y, z); int sid1 = this->getSegmentId(x - 1, y, z); int sid2 = this->getSegmentId(x + 1, y, z); int sid3 = this->getSegmentId(x, y - 1, z); int sid4 = this->getSegmentId(x, y + 1, z); int sid5 = this->getSegmentId(x, y, z - 1); int sid6 = this->getSegmentId(x, y, z + 1); if ((sid1 != -1 && sid1 != sid) || (sid2 != -1 && sid2 != sid) || (sid3 != -1 && sid3 != sid) || (sid4 != -1 && sid4 != sid) || (sid5 != -1 && sid5 != sid) || (sid6 != -1 && sid6 != sid)) return true; else return false; } bool CSegmenter::isBoundPixel(int x, std::vector<int>& Sids) { int sid[2]; sid[0] = this->getSegmentId(x - 1); sid[1] = this->getSegmentId(x + 1); for (int n = 0; n < 2; n++) { if (sid[n] == -1) continue; bool inside = false; for (size_t s = 0; s < Sids.size(); s++) { if (sid[n] == Sids[s]) { inside = true; break; } } if (!inside) return true; } return false; } bool CSegmenter::isBoundPixel(int x, int y, std::vector<int>& Sids) { int sid[4]; sid[0] = this->getSegmentId(x - 1, y); sid[1] = this->getSegmentId(x + 1, y); sid[2] = this->getSegmentId(x, y - 1); sid[3] = this->getSegmentId(x, y + 1); for (int n = 0; n < 4; n++) { if (sid[n] == -1) continue; bool inside = false; for (size_t s = 0; s < Sids.size(); s++) { if (sid[n] == Sids[s]) { inside = true; break; } } if (!inside) return true; } return false; } bool CSegmenter::isBoundPixel(int x, int y, int z, std::vector<int>& Sids) { int sid[6]; sid[0] = this->getSegmentId(x - 1, y, z); sid[1] = this->getSegmentId(x + 1, y, z); sid[2] = this->getSegmentId(x, y - 1, z); sid[3] = this->getSegmentId(x, y + 1, z); sid[4] = this->getSegmentId(x, y, z - 1); sid[5] = this->getSegmentId(x, y, z + 1); for (int n = 0; n < 6; n++) { if (sid[n] == -1) continue; bool inside = false; for (size_t s = 0; s < Sids.size(); s++) { if (sid[n] == Sids[s]) { inside = true; break; } } if (!inside) return true; } return false; } bool CSegmenter::isBoundPixelSlice(int x, int y, int z) { int sid = this->getSegmentId(x, y, z); int sid1 = this->getSegmentId(x - 1, y, z); int sid2 = this->getSegmentId(x + 1, y, z); int sid3 = this->getSegmentId(x, y - 1, z); int sid4 = this->getSegmentId(x, y + 1, z); if ((sid1 != -1 && sid1 != sid) || (sid2 != -1 && sid2 != sid) || (sid3 != -1 && sid3 != sid) || (sid4 != -1 && sid4 != sid)) return true; else return false; } bool CSegmenter::isBoundPixelSlice(int x, int y, int z, std::vector<int>& Sids) { int sid[4]; sid[0] = this->getSegmentId(x - 1, y, z); sid[1] = this->getSegmentId(x + 1, y, z); sid[2] = this->getSegmentId(x, y - 1, z); sid[3] = this->getSegmentId(x, y + 1, z); for (int n = 0; n < 4; n++) { if (sid[n] == -1) continue; bool inside = false; for (size_t s = 0; s < Sids.size(); s++) { if (sid[n] == Sids[s]) { inside = true; break; } } if (!inside) return true; } return false; } int CSegmenter::getSegmentId(int x) { if (x < 0 || x >= m_Image->getWidth()) return -1; return m_Labels[x]; } int CSegmenter::getSegmentId(int x, int y) { if (x < 0 || x >= m_Image->getWidth() || y < 0 || y >= m_Image->getHeight()) return -1; return m_Labels[y * m_Image->getWidth() + x]; } int CSegmenter::getSegmentId(int x, int y, int z) { if (x < 0 || x >= m_Image->getWidth() || y < 0 || y >= m_Image->getHeight() || z < 0 || z >= m_Image->getDepth()) return -1; return m_Labels[z * m_Image->getWidth() * m_Image->getHeight() + y * m_Image->getWidth() + x]; } int CSegmenter::getMaxSegmentId() { int sid = 0; for (int n = 0; n < m_Image->getNumPixels(); n++) sid = __MAX(sid, m_Labels[n]); return sid; } int CSegmenter::getNumSegments() { return (int)m_Segments.size(); } int* CSegmenter::getLabels() { return m_Labels; } CSegment* CSegmenter::getSegment(int Sid) { assert(Sid >= 0 && Sid < (int)m_Segments.size()); return &m_Segments[Sid]; } CSegment* CSegmenter::getSegment(int x, int y) { int sid = this->getSegmentId(x, y); assert(sid >= 0 && sid < (int)m_Segments.size()); return &m_Segments[sid]; } CSegment* CSegmenter::getSegment(int x, int y, int z) { int sid = this->getSegmentId(x, y, z); assert(sid >= 0 && sid < (int)m_Segments.size()); return &m_Segments[sid]; } std::vector<CSegment>& CSegmenter::getSegments() { return m_Segments; } CImage* CSegmenter::getImage() { return m_Image; }
31.706642
287
0.506372
LLNL
c696f56c8f48b0c5aef6edcd804cadbfa9959707
8,475
cpp
C++
ext/Objects/bytearrayobject-test.cpp
creativemindplus/skybison
d1740e08d8de85a0a56b650675717da67de171a0
[ "CNRI-Python-GPL-Compatible" ]
278
2021-08-31T00:46:51.000Z
2022-02-13T19:43:28.000Z
ext/Objects/bytearrayobject-test.cpp
creativemindplus/skybison
d1740e08d8de85a0a56b650675717da67de171a0
[ "CNRI-Python-GPL-Compatible" ]
9
2021-11-05T22:28:43.000Z
2021-11-23T08:39:04.000Z
ext/Objects/bytearrayobject-test.cpp
tekknolagi/skybison
bea8fc2af0a70e7203b4c19f36c14a745512a335
[ "CNRI-Python-GPL-Compatible" ]
12
2021-08-31T07:49:54.000Z
2021-10-08T01:09:01.000Z
// Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) #include <cstring> #include "Python.h" #include "gtest/gtest.h" #include "capi-fixture.h" #include "capi-testing.h" namespace py { namespace testing { using ByteArrayExtensionApiTest = ExtensionApi; TEST_F(ByteArrayExtensionApiTest, AsStringWithByteArrayReturnsString) { PyObjectPtr array(PyByteArray_FromStringAndSize("hello world", 7)); const char* result = PyByteArray_AsString(array); ASSERT_EQ(PyErr_Occurred(), nullptr); EXPECT_STREQ(result, "hello w"); } TEST_F(ByteArrayExtensionApiTest, AsStringWithModifiedByteArrayReturnsUpdatedString) { PyObjectPtr array(PyByteArray_FromStringAndSize("hello world", 7)); const char* result = PyByteArray_AsString(array); ASSERT_EQ(PyErr_Occurred(), nullptr); EXPECT_STREQ(result, "hello w"); ASSERT_EQ(PyByteArray_Resize(array, 2), 0); result = PyByteArray_AsString(array); ASSERT_EQ(PyErr_Occurred(), nullptr); EXPECT_STREQ(result, "he"); } TEST_F(ByteArrayExtensionApiTest, CheckWithBytesReturnsFalse) { PyObjectPtr bytes(PyBytes_FromString("hello")); EXPECT_FALSE(PyByteArray_CheckExact(bytes)); EXPECT_FALSE(PyByteArray_Check(bytes)); } TEST_F(ByteArrayExtensionApiTest, ConcatWithNonBytesLikeSelfRaisesTypeError) { PyObjectPtr self(PyList_New(0)); PyObjectPtr other(PyByteArray_FromStringAndSize("world", 5)); ASSERT_EQ(PyByteArray_Concat(self, other), nullptr); ASSERT_NE(PyErr_Occurred(), nullptr); EXPECT_TRUE(PyErr_ExceptionMatches(PyExc_TypeError)); } TEST_F(ByteArrayExtensionApiTest, ConcatWithNonBytesLikeOtherRaisesTypeError) { PyObjectPtr self(PyByteArray_FromStringAndSize("hello", 5)); PyObjectPtr other(PyList_New(0)); ASSERT_EQ(PyByteArray_Concat(self, other), nullptr); ASSERT_NE(PyErr_Occurred(), nullptr); EXPECT_TRUE(PyErr_ExceptionMatches(PyExc_TypeError)); } TEST_F(ByteArrayExtensionApiTest, ConcatWithEmptyByteArraysReturnsEmpty) { PyObjectPtr self(PyByteArray_FromStringAndSize("", 0)); PyObjectPtr other(PyByteArray_FromStringAndSize("", 0)); PyObjectPtr result(PyByteArray_Concat(self, other)); ASSERT_EQ(PyErr_Occurred(), nullptr); EXPECT_EQ(PyByteArray_Size(result), 0); } TEST_F(ByteArrayExtensionApiTest, ConcatWithBytesSelfReturnsNewConcatenatedByteArray) { const char* str1 = "hello"; const char* str2 = "world"; Py_ssize_t len1 = static_cast<Py_ssize_t>(std::strlen(str1)); Py_ssize_t len2 = static_cast<Py_ssize_t>(std::strlen(str2)); PyObjectPtr self(PyBytes_FromString(str1)); PyObjectPtr other(PyBytes_FromString(str2)); PyObjectPtr result(PyByteArray_Concat(self, other)); ASSERT_EQ(PyErr_Occurred(), nullptr); ASSERT_EQ(PyBytes_Size(self), len1); ASSERT_TRUE(PyByteArray_CheckExact(result)); EXPECT_EQ(PyByteArray_Size(result), len1 + len2); EXPECT_STREQ(PyByteArray_AsString(result), "helloworld"); } TEST_F(ByteArrayExtensionApiTest, ConcatWithByteArraysReturnsNewConcatenatedByteArray) { const char* str1 = "hello"; const char* str2 = "world"; Py_ssize_t len1 = static_cast<Py_ssize_t>(std::strlen(str1)); Py_ssize_t len2 = static_cast<Py_ssize_t>(std::strlen(str2)); PyObjectPtr self(PyByteArray_FromStringAndSize(str1, len1)); PyObjectPtr other(PyByteArray_FromStringAndSize(str2, len2)); PyObjectPtr result(PyByteArray_Concat(self, other)); ASSERT_EQ(PyErr_Occurred(), nullptr); ASSERT_EQ(PyByteArray_Size(self), len1); ASSERT_TRUE(PyByteArray_CheckExact(result)); EXPECT_EQ(PyByteArray_Size(result), len1 + len2); EXPECT_STREQ(PyByteArray_AsString(result), "helloworld"); } TEST_F(ByteArrayExtensionApiTest, FromObjectWithNullReturnsEmptyByteArray) { PyObjectPtr array(PyByteArray_FromObject(nullptr)); EXPECT_TRUE(PyByteArray_CheckExact(array)); EXPECT_EQ(PyByteArray_Size(array), 0); } TEST_F(ByteArrayExtensionApiTest, FromObjectWithByteArrayReturnsByteArray) { const char* hello = "hello"; Py_ssize_t size = static_cast<Py_ssize_t>(std::strlen(hello)); PyObjectPtr bytes(PyByteArray_FromStringAndSize(hello, size)); PyObjectPtr array(PyByteArray_FromObject(bytes)); EXPECT_TRUE(PyByteArray_CheckExact(array)); EXPECT_EQ(PyByteArray_Size(array), size); } TEST_F(ByteArrayExtensionApiTest, FromObjectWithBytesReturnsByteArray) { PyObjectPtr bytes(PyBytes_FromString("hello")); PyObjectPtr array(PyByteArray_FromObject(bytes)); EXPECT_TRUE(PyByteArray_CheckExact(array)); EXPECT_EQ(PyByteArray_Size(array), 5); } TEST_F(ByteArrayExtensionApiTest, FromObjectWithIntReturnsByteArray) { Py_ssize_t size = 10; PyObjectPtr value(PyLong_FromSsize_t(size)); PyObjectPtr array(PyByteArray_FromObject(value)); EXPECT_TRUE(PyByteArray_CheckExact(array)); EXPECT_EQ(PyByteArray_Size(array), size); } TEST_F(ByteArrayExtensionApiTest, FromObjectWithListReturnsByteArray) { PyObjectPtr list(PyList_New(3)); PyList_SetItem(list, 0, PyLong_FromLong(0)); PyList_SetItem(list, 1, PyLong_FromLong(1)); PyList_SetItem(list, 2, PyLong_FromLong(2)); PyObjectPtr array(PyByteArray_FromObject(list)); EXPECT_TRUE(PyByteArray_CheckExact(array)); EXPECT_EQ(PyByteArray_Size(array), 3); } TEST_F(ByteArrayExtensionApiTest, FromObjectWithStringRaisesTypeError) { PyObjectPtr str(PyUnicode_FromString("hello")); EXPECT_EQ(PyByteArray_FromObject(str), nullptr); EXPECT_NE(PyErr_Occurred(), nullptr); EXPECT_TRUE(PyErr_ExceptionMatches(PyExc_TypeError)); } TEST_F(ByteArrayExtensionApiTest, FromStringAndSizeReturnsByteArray) { PyObjectPtr array(PyByteArray_FromStringAndSize("hello", 5)); EXPECT_TRUE(PyByteArray_Check(array)); EXPECT_TRUE(PyByteArray_CheckExact(array)); } TEST_F(ByteArrayExtensionApiTest, FromStringAndSizeSetsSize) { PyObjectPtr array(PyByteArray_FromStringAndSize("hello", 3)); ASSERT_TRUE(PyByteArray_CheckExact(array)); EXPECT_EQ(PyByteArray_Size(array), 3); } TEST_F(ByteArrayExtensionApiTest, FromStringAndSizeWithNegativeSizeRaisesSystemError) { ASSERT_EQ(PyByteArray_FromStringAndSize("hello", -1), nullptr); ASSERT_NE(PyErr_Occurred(), nullptr); EXPECT_TRUE(PyErr_ExceptionMatches(PyExc_SystemError)); } TEST_F(ByteArrayExtensionApiTest, FromStringAndSizeWithNullReturnsNew) { PyObjectPtr array(PyByteArray_FromStringAndSize(nullptr, 10)); ASSERT_TRUE(PyByteArray_CheckExact(array)); EXPECT_EQ(PyByteArray_Size(array), 10); } TEST_F(ByteArrayExtensionApiTest, ResizeWithSameSizeIsNoop) { const char* hello = "hello"; Py_ssize_t len = static_cast<Py_ssize_t>(std::strlen(hello)); PyObjectPtr array(PyByteArray_FromStringAndSize(hello, len)); ASSERT_EQ(PyByteArray_Resize(array, len), 0); ASSERT_EQ(PyErr_Occurred(), nullptr); EXPECT_EQ(PyByteArray_Size(array), len); } TEST_F(ByteArrayExtensionApiTest, ResizeWithSmallerSizeShrinks) { const char* hello = "hello"; Py_ssize_t len = static_cast<Py_ssize_t>(std::strlen(hello)); PyObjectPtr array(PyByteArray_FromStringAndSize(hello, len)); ASSERT_EQ(PyByteArray_Resize(array, len - 2), 0); ASSERT_EQ(PyErr_Occurred(), nullptr); EXPECT_EQ(PyByteArray_Size(array), len - 2); } TEST_F(ByteArrayExtensionApiTest, ResizeWithLargerSizeGrows) { const char* hello = "hello"; Py_ssize_t len = static_cast<Py_ssize_t>(std::strlen(hello)); PyObjectPtr array(PyByteArray_FromStringAndSize(hello, len)); ASSERT_EQ(PyByteArray_Resize(array, len + 2), 0); ASSERT_EQ(PyErr_Occurred(), nullptr); EXPECT_EQ(PyByteArray_Size(array), len + 2); } TEST_F(ByteArrayExtensionApiTest, ResizeLargerThenSmaller) { const char* hello = "hello"; Py_ssize_t len = static_cast<Py_ssize_t>(std::strlen(hello)); PyObjectPtr array(PyByteArray_FromStringAndSize(hello, len)); ASSERT_EQ(PyByteArray_Resize(array, len + 3), 0); ASSERT_EQ(PyErr_Occurred(), nullptr); EXPECT_EQ(PyByteArray_Size(array), len + 3); ASSERT_EQ(PyByteArray_Resize(array, len - 1), 0); ASSERT_EQ(PyErr_Occurred(), nullptr); EXPECT_EQ(PyByteArray_Size(array), len - 1); } TEST_F(ByteArrayExtensionApiTest, ResizeSmallerThenLarger) { const char* hello = "hello"; Py_ssize_t len = static_cast<Py_ssize_t>(std::strlen(hello)); PyObjectPtr array(PyByteArray_FromStringAndSize(hello, len)); ASSERT_EQ(PyByteArray_Resize(array, len - 3), 0); ASSERT_EQ(PyErr_Occurred(), nullptr); EXPECT_EQ(PyByteArray_Size(array), len - 3); ASSERT_EQ(PyByteArray_Resize(array, len + 1), 0); ASSERT_EQ(PyErr_Occurred(), nullptr); EXPECT_EQ(PyByteArray_Size(array), len + 1); } } // namespace testing } // namespace py
37.834821
79
0.785605
creativemindplus
578dc541119789c17a31f55d05729d25c98556df
6,307
cpp
C++
WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/WebProcess/Storage/WebToStorageProcessConnection.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
1
2021-05-27T07:29:31.000Z
2021-05-27T07:29:31.000Z
WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/WebProcess/Storage/WebToStorageProcessConnection.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/WebProcess/Storage/WebToStorageProcessConnection.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
/* * Copyright (C) 2013 Apple 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 APPLE, INC. ``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 APPLE INC. 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 "config.h" #include "WebToStorageProcessConnection.h" #include "ServiceWorkerClientFetchMessages.h" #include "StorageToWebProcessConnectionMessages.h" #include "WebIDBConnectionToServerMessages.h" #include "WebProcess.h" #include "WebSWClientConnection.h" #include "WebSWClientConnectionMessages.h" #include "WebSWContextManagerConnection.h" #include "WebSWContextManagerConnectionMessages.h" #include "WebServiceWorkerProvider.h" #include <WebCore/SWContextManager.h> using namespace PAL; using namespace WebCore; namespace WebKit { WebToStorageProcessConnection::WebToStorageProcessConnection(IPC::Connection::Identifier connectionIdentifier) : m_connection(IPC::Connection::createClientConnection(connectionIdentifier, *this)) { m_connection->open(); } WebToStorageProcessConnection::~WebToStorageProcessConnection() { m_connection->invalidate(); } void WebToStorageProcessConnection::didReceiveMessage(IPC::Connection& connection, IPC::Decoder& decoder) { #if ENABLE(INDEXED_DATABASE) if (decoder.messageReceiverName() == Messages::WebIDBConnectionToServer::messageReceiverName()) { auto idbConnection = m_webIDBConnectionsByIdentifier.get(decoder.destinationID()); if (idbConnection) idbConnection->didReceiveMessage(connection, decoder); return; } #endif #if ENABLE(SERVICE_WORKER) if (decoder.messageReceiverName() == Messages::WebSWClientConnection::messageReceiverName()) { auto serviceWorkerConnection = m_swConnectionsByIdentifier.get(makeObjectIdentifier<SWServerConnectionIdentifierType>(decoder.destinationID())); if (serviceWorkerConnection) serviceWorkerConnection->didReceiveMessage(connection, decoder); return; } if (decoder.messageReceiverName() == Messages::ServiceWorkerClientFetch::messageReceiverName()) { WebServiceWorkerProvider::singleton().didReceiveServiceWorkerClientFetchMessage(connection, decoder); return; } if (decoder.messageReceiverName() == Messages::WebSWContextManagerConnection::messageReceiverName()) { ASSERT(SWContextManager::singleton().connection()); if (auto* contextManagerConnection = SWContextManager::singleton().connection()) static_cast<WebSWContextManagerConnection&>(*contextManagerConnection).didReceiveMessage(connection, decoder); return; } #endif ASSERT_NOT_REACHED(); } void WebToStorageProcessConnection::didReceiveSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder) { #if ENABLE(SERVICE_WORKER) if (decoder.messageReceiverName() == Messages::WebSWContextManagerConnection::messageReceiverName()) { ASSERT(SWContextManager::singleton().connection()); if (auto* contextManagerConnection = SWContextManager::singleton().connection()) static_cast<WebSWContextManagerConnection&>(*contextManagerConnection).didReceiveSyncMessage(connection, decoder, replyEncoder); return; } #endif ASSERT_NOT_REACHED(); } void WebToStorageProcessConnection::didClose(IPC::Connection& connection) { auto protectedThis = makeRef(*this); #if ENABLE(INDEXED_DATABASE) for (auto& connection : m_webIDBConnectionsByIdentifier.values()) connection->connectionToServerLost(); #endif #if ENABLE(SERVICE_WORKER) for (auto& connection : m_swConnectionsBySession.values()) connection->connectionToServerLost(); m_swConnectionsByIdentifier.clear(); m_swConnectionsBySession.clear(); #endif WebProcess::singleton().webToStorageProcessConnectionClosed(this); #if ENABLE(INDEXED_DATABASE) m_webIDBConnectionsByIdentifier.clear(); m_webIDBConnectionsBySession.clear(); #endif } void WebToStorageProcessConnection::didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference messageReceiverName, IPC::StringReference messageName) { } #if ENABLE(INDEXED_DATABASE) WebIDBConnectionToServer& WebToStorageProcessConnection::idbConnectionToServerForSession(SessionID sessionID) { return *m_webIDBConnectionsBySession.ensure(sessionID, [&] { auto connection = WebIDBConnectionToServer::create(sessionID); auto result = m_webIDBConnectionsByIdentifier.add(connection->identifier(), connection.copyRef()); ASSERT_UNUSED(result, result.isNewEntry); return connection; }).iterator->value; } #endif #if ENABLE(SERVICE_WORKER) WebSWClientConnection& WebToStorageProcessConnection::serviceWorkerConnectionForSession(SessionID sessionID) { ASSERT(sessionID.isValid()); return *m_swConnectionsBySession.ensure(sessionID, [&] { auto connection = WebSWClientConnection::create(m_connection, sessionID); auto result = m_swConnectionsByIdentifier.add(connection->serverConnectionIdentifier(), connection.ptr()); ASSERT_UNUSED(result, result.isNewEntry); return connection; }).iterator->value; } #endif } // namespace WebKit
39.41875
154
0.767243
mlcldh
578e01324ff9a18f505abef35d050a68776d75d7
296
cpp
C++
engine/src/Graphics/TerrainInstance.cpp
aleksigron/graphics-toolkit
f8e60c57316a72dff9de07512e9771deb3799208
[ "MIT" ]
14
2017-10-17T16:20:20.000Z
2021-12-21T14:49:00.000Z
engine/src/Graphics/TerrainInstance.cpp
aleksigron/graphics-toolkit
f8e60c57316a72dff9de07512e9771deb3799208
[ "MIT" ]
null
null
null
engine/src/Graphics/TerrainInstance.cpp
aleksigron/graphics-toolkit
f8e60c57316a72dff9de07512e9771deb3799208
[ "MIT" ]
1
2019-05-12T13:50:23.000Z
2019-05-12T13:50:23.000Z
#include "Graphics/TerrainInstance.hpp" TerrainInstance::TerrainInstance() : meshId(MeshId::Null), terrainSize(128.0f), terrainResolution(128), textureScale(0.25f, 0.25f), minHeight(-0.25f), maxHeight(0.05f), heightData(nullptr), vertexArrayId(0), uniformBufferId(0), textureId(0) { }
18.5
39
0.736486
aleksigron
5790db543563f27ea8ff6c6c0e0ae7f4e464bdc0
845
cpp
C++
Library/Room/Mode.cpp
theater/ArduinoMega
6515e6b6fbe62f75bf67ea2470760757af457b92
[ "Apache-2.0" ]
null
null
null
Library/Room/Mode.cpp
theater/ArduinoMega
6515e6b6fbe62f75bf67ea2470760757af457b92
[ "Apache-2.0" ]
null
null
null
Library/Room/Mode.cpp
theater/ArduinoMega
6515e6b6fbe62f75bf67ea2470760757af457b92
[ "Apache-2.0" ]
null
null
null
/* * Mode.cpp * * Created on: Mar 15, 2018 * Author: theater */ #include <Mode.h> #include <MqttUtil.h> Mode::Mode(ModeType mode) : Mode(mode, NULL) { } Mode::Mode(ModeType mode, char * id ) { this->id = id; this->mode = mode; this->callbackTopic = createCallbackTopic(id); MqttUtil::subscribe(id); } void Mode::updateValue(const char* id, const char* value) { if (!strcmp(id, this->id)) { if (!strcmp(value, "ALL_OFF")) { setMode(ALL_OFF); } else if (!strcmp(value, "MANUAL")) { setMode(MANUAL); } else { setMode(AUTO); } logDebug("Updated MODE " + String(id) + " to value: " + String(value)); } } Mode::~Mode() { } char* Mode::getId() { return id; } ModeType Mode::getMode() { return mode; } void Mode::setMode(ModeType mode) { this->mode = mode; }
17.604167
74
0.577515
theater
5799c85453ccc713e6e2727a3b553576ec20a296
4,057
hpp
C++
RobWork/src/rw/geometry/Cylinder.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
1
2021-12-29T14:16:27.000Z
2021-12-29T14:16:27.000Z
RobWork/src/rw/geometry/Cylinder.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
RobWork/src/rw/geometry/Cylinder.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #ifndef RW_GEOMETRY_CYLINDER_HPP_ #define RW_GEOMETRY_CYLINDER_HPP_ #if !defined(SWIG) #include "Primitive.hpp" #include <rw/math/Transform3D.hpp> #endif namespace rw { namespace geometry { //! @addtogroup geometry // @{ /** * @brief a cylinder primitive. By default the radius is in the x-y plane and height is along * the z-axis */ class Cylinder : public Primitive { public: /** * @brief constructor */ Cylinder (int levels = 16); /** * @brief Constructs cylinder primitive with the specified setup * * The cylinder is aligned with the height in the z-direction. * * @param radius [in] radius of the cylinder. * @param height [in] height of the cylinder. * @param levels [in] granularity of the mesh */ Cylinder (float radius, float height, int levels = 16); /** * @brief Constructor. * @param initQ [in] vector with (height, radius) * @param levels [in] granularity of the mesh */ Cylinder (const rw::math::Q& initQ, int levels = 16); /** * @brief Construct cylinder primitive with specified radius and height and with the given * transform. * * The cylinder will be centered in the position of \b transform and oriented in the * direction of the third column of the rotation matrix of \b transform. * @param transform [in] The transform specifying how the pose of the cylinder * @param radius [in] radius of the cylinder. * @param height [in] height of the cylinder. * @param levels [in] granularity of the mesh */ Cylinder (const rw::math::Transform3D<>& transform, float radius, float height, int levels = 16); //! @brief destructor virtual ~Cylinder (); /** * @brief Get the radius of the cylinder. * @return the radius. */ double getRadius () const { return _radius; } /** * @brief Get the height of the cylinder. * @return the height. */ double getHeight () const { return _height; } /** * @brief Returns the transform of the cylinder. * * Default is the identity matrix unless a transform has been specified. * @return Transform of the cylinder */ const rw::math::Transform3D< float >& getTransform () const { return _transform; } // inherited from Primitive //! @copydoc Primitive::createMesh TriMesh::Ptr createMesh (int resolution) const; //! @copydoc Primitive::getParameters virtual rw::math::Q getParameters () const; //! @copydoc Primitive::setParameters virtual void setParameters (const rw::math::Q& q); //! @copydoc GeometryData::getType GeometryType getType () const { return CylinderPrim; }; private: rw::math::Transform3D< float > _transform; float _radius; float _height; }; //! @} }} // namespace rw::geometry #endif /* CYLINDER_HPP_ */
33.254098
98
0.588366
ZLW07
579cb1a772acc36d0615bf87b7c588fcb54e2326
17,506
cpp
C++
scripts/im2ply/PointCloud.cpp
danielsuo/rgbd-annotator
500ad86a424511c289db6ba458c9335928e130fc
[ "MIT" ]
25
2016-10-22T16:47:28.000Z
2021-08-23T11:58:11.000Z
scripts/im2ply/PointCloud.cpp
danielsuo/rgbd-annotator
500ad86a424511c289db6ba458c9335928e130fc
[ "MIT" ]
null
null
null
scripts/im2ply/PointCloud.cpp
danielsuo/rgbd-annotator
500ad86a424511c289db6ba458c9335928e130fc
[ "MIT" ]
7
2016-11-29T07:33:53.000Z
2018-03-14T11:13:02.000Z
#include "PointCloud.h" Camera *PointCloud::PointCloud::camera = new Camera(298.44268798828125, 247.51919555664062, 615.1951904296875, 615.19525146484375); PointCloud::PointCloud() { color = cv::Mat(0, 3, CV_32FC1); depth = cv::Mat(0, 3, CV_32FC1); } PointCloud::PointCloud(vector<char> *color_buffer, vector<char> *depth_buffer) { color = cv::imdecode(*color_buffer, cv::IMREAD_COLOR); depth = cv::imdecode(*depth_buffer, cv::IMREAD_ANYDEPTH); createPointCloud(); } PointCloud::PointCloud(string color_path, string depth_path) { color = cv::imread(color_path, cv::IMREAD_COLOR); depth = cv::imread(depth_path, cv::IMREAD_ANYDEPTH); createPointCloud(); } void PointCloud::createPointCloud() { // Initialize 3 dimensions for each pixel in depth image cv::Mat result(depth.rows * depth.cols, 3, cv::DataType<float>::type); // TODO: should reinvestigate calibrated cx, cy float half_cols = depth.cols / 2; float half_rows = depth.rows / 2; for (int r = 0; r < depth.rows; r++) { for (int c = 0; c < depth.cols; c++) { float ix = 0; float iy = 0; float iz = (float)depth.at<uint16_t>(r, c) / 1000.0f; if (iz != 0) { ix = iz * (c + 1 - camera->cx) / camera->fx; iy = iz * (r + 1 - camera->cy) / camera->fy; } result.at<float>(r * depth.cols + c, 0) = ix; result.at<float>(r * depth.cols + c, 1) = iy; result.at<float>(r * depth.cols + c, 2) = iz; } } depth.release(); depth = result; } PointCloud::~PointCloud() { color.release(); depth.release(); } void PointCloud::bitShiftDepth() { cv::Mat result(depth.rows, depth.cols, cv::DataType<float>::type); uint16_t lshift = 13; uint16_t rshift = -lshift & 15; for (int i = 0; i < depth.rows; i++) { for (int j = 0; j < depth.cols; j++) { uint16_t s = depth.at<uint16_t>(i, j); float f = 0.0f; if (s != 0) { // In order to visually see depth, we bit shift during // capture. Now we must shift back. s = (s << lshift | s >> rshift); f = (float)s / 1000.0f; } result.at<float>(i, j) = f; } } // According to documentation, assignment operator takes care of this depth.release(); depth = result; } void PointCloud::scalePointCloud(float factor) { for (int v = 0; v < depth.size().height; ++v) { if (depth.at<float>(v, 2) != 0) { depth.at<float>(v, 0) *= factor; depth.at<float>(v, 1) *= factor; depth.at<float>(v, 2) *= factor; } } } // TODO: move to GPU void PointCloud::transformPointCloud(float T[12]) { cv::Mat result(depth.size().height, 3, cv::DataType<float>::type); for (int v = 0; v < depth.size().height; ++v) { float ix = depth.at<float>(v, 0); float iy = depth.at<float>(v, 1); float iz = depth.at<float>(v, 2); if (iz == 0) { result.at<float>(v, 0) = 0; result.at<float>(v, 1) = 0; result.at<float>(v, 2) = 0; } else { result.at<float>(v, 0) = T[0] * ix + T[1] * iy + T[2] * iz + T[3]; result.at<float>(v, 1) = T[4] * ix + T[5] * iy + T[6] * iz + T[7]; result.at<float>(v, 2) = T[8] * ix + T[9] * iy + T[10] * iz + T[11]; } } // According to documentation, assignment operator takes care of this depth.release(); depth = result; } void PointCloud::getExtents(float &minx, float &maxx, float &miny, float &maxy, float &minz, float &maxz) { minx = miny = minz = FLT_MAX; maxx = maxy = maxz = FLT_MIN; for (int v = 0; v < depth.size().height; v++) { if (depth.at<float>(v, 2) != 0) { float ix = depth.at<float>(v, 0); float iy = depth.at<float>(v, 1); float iz = depth.at<float>(v, 2); if (ix < minx) minx = ix; else if (ix > maxx) maxx = ix; if (iy < miny) miny = iy; else if (iy > maxy) maxy = iy; if (iz < minz) minz = iz; else if (iz > maxz) maxz = iz; } } } void PointCloud::writePLY(string path) { FILE *fp = fopen(path.c_str(), "w"); int pointCount = 0; int trueCount = 0; int skip = 1; int lower = 0; int upper = 640 * 480 * 4; for (int v = 0; v < depth.size().height; ++v) { float z = depth.at<float>(v, 2); if ((z > 0.0001 || z < -0.0001) && v >= lower && v < upper) { if (v % skip == 0) pointCount++; trueCount++; } } cout << "Write PLY" << endl; fprintf(fp, "ply\n"); fprintf(fp, "format binary_little_endian 1.0\n"); fprintf(fp, "element vertex %d\n", pointCount); fprintf(fp, "property float x\n"); fprintf(fp, "property float y\n"); fprintf(fp, "property float z\n"); fprintf(fp, "property uchar red\n"); fprintf(fp, "property uchar green\n"); fprintf(fp, "property uchar blue\n"); fprintf(fp, "end_header\n"); for (int v = 0; v < depth.size().height; ++v) { float z = depth.at<float>(v, 2); if ((z > 0.0001 || z < -0.0001) && v % skip == 0 && v >= lower && v < upper){ fwrite(&depth.at<float>(v, 0), sizeof(float), 1, fp); fwrite(&depth.at<float>(v, 1), sizeof(float), 1, fp); fwrite(&depth.at<float>(v, 2), sizeof(float), 1, fp); int i= (int)v/color.size().width; int j= (int)v%color.size().width; fwrite(&color.at<cv::Vec3b>(i, j)[2], sizeof(uchar), 1, fp); fwrite(&color.at<cv::Vec3b>(i, j)[1], sizeof(uchar), 1, fp); fwrite(&color.at<cv::Vec3b>(i, j)[0], sizeof(uchar), 1, fp); } } fclose(fp); cerr << "Finished writing point cloud with points " << trueCount << endl; } cv::Mat PointCloud::readPLY(string path) { ifstream infile(path); int numPoints = 0; // Ignore first 10 lines to skip header while (true) { string line; getline(infile, line); // Grab number of vertices if (line.find("element vertex") != string::npos) { cerr << "Found vertex" << endl; cerr << line << endl; numPoints = stoi(line.replace(0, 15, "")); } if (line.find("end_header") != string::npos) { break; } cerr << line << endl; } cv::Mat result(numPoints, 3, cv::DataType<float>::type); for (int i = 0; i < numPoints; i++) { float x, y, z; char r, g, b; infile.read((char *)&x, sizeof(float)); infile.read((char *)&y, sizeof(float)); infile.read((char *)&z, sizeof(float)); infile.read((char *)&r, sizeof(char)); infile.read((char *)&g, sizeof(char)); infile.read((char *)&b, sizeof(char)); result.at<float>(i, 0) = x; result.at<float>(i, 1) = y; result.at<float>(i, 2) = z; // cerr << x << " " << y << " " << z << endl; } cerr << "Got " << result.size().height << " rows" << endl; infile.close(); return result; } void PointCloud::writePLY(string path, cv::Mat ply) { ofstream outfile(path, ios::binary); outfile << "ply\n"; outfile << "format binary_little_endian 1.0\n"; outfile << "element vertex " + to_string(ply.size().height) + "\n"; outfile << "property float x\n"; outfile << "property float y\n"; outfile << "property float z\n"; outfile << "end_header\n"; for (int i = 0; i < ply.size().height; i++) { outfile.write((const char *)&ply.at<float>(i, 0), sizeof(float)); outfile.write((const char *)&ply.at<float>(i, 1), sizeof(float)); outfile.write((const char *)&ply.at<float>(i, 2), sizeof(float)); } outfile.close(); } void PointCloud::append(PointCloud *other) { color.push_back(other->color); depth.push_back(other->depth); } void PointCloud::copy(PointCloud *other) { color = other->color.clone(); depth = other->depth.clone(); } /****************************************************************************** * Currently unused functions *****************************************************************************/ void PointCloud::linearizeDepth() { // Depth from depth buffer comes out in non-linear units to give // close points more depth precision than far points. We must // convert into linear units so we can use // Assume that far plane is far relative to near such that f / (f - // n) approximately equals 1 // Currently implemented at the end projectPointCloud } // TODO: move to GPU void PointCloud::projectPointCloud() { /** * Step 1: setup off-screen binding. See header file for more * information: * * https://github.com/freedreno/mesa/blob/master/include/GL/osmesa.h */ int num_cols = depth.cols; int num_rows = depth.rows; OSMesaContext ctx = OSMesaCreateContextExt( OSMESA_BGR, /* format: Specifies the format of the pixel data. The following symbolic values are accepted: #define OSMESA_COLOR_INDEX GL_COLOR_INDEX #define OSMESA_RGBA GL_RGBA #define OSMESA_BGRA 0x1 #define OSMESA_ARGB 0x2 #define OSMESA_RGB GL_RGB #define OSMESA_BGR 0x4 #define OSMESA_RGB_565 0x5 NOTE: strange hack not sure why it is not OSMESA_RGB */ 32, // depthBits: size of depth buffer 0, // stencilBits: size of stencil buffer 0, // aaccumBits: size of accumulation buffer NULL // sharelist: OSMesaContext that specifies the context with // which to share display lists. NULL indicates that no // sharing is to take place. ); // Inititalize imageWarp output buffer unsigned char * pbuffer = new unsigned char [3 * depth.cols * depth.rows]; // Bind the buffer to the context and make it current if (!OSMesaMakeCurrent( ctx, // ctx: Context to bind (void*)pbuffer, // buffer: Buffer to bind to GL_UNSIGNED_BYTE, // type: Data typefor pixel components num_cols, // width: Width of buffer in pixels num_rows // height: Height of buffer in pixels )) { fprintf(stderr, "OSMesaMakeCurrent failed!"); } // Y coordinates increase downwardfind_package(OSMesa REQUIRED) OSMesaPixelStore(OSMESA_Y_UP, 0); // -------------------------------------------------------------------------- // Step 2: Setup basic OpenGL setting // -------------------------------------------------------------------------- // Enable depth test: If enabled, do depth comparisons and update the depth // buffer. Note that even if the depth buffer exists and the depth mask is // non-zero, the depth buffer is not updated if the depth test is disabled. glEnable(GL_DEPTH_TEST); // Disable lighting: If enabled and no vertex shader is active, use the // current lighting parameters to compute the vertex color or index. // Otherwise, simply associate the current color or index with each vertex. glDisable(GL_LIGHTING); // Enable face culling: If enabled, cull polygons based on their winding in // window coordinates. glEnable(GL_CULL_FACE); // Cull back face glCullFace(GL_BACK); // Rasterize polygons by filling front-facing polygons glPolygonMode(GL_FRONT, GL_FILL); // Clear buffer to values set by glClearColor, glClearDepthf, and glClearStencil glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Create the viewport glViewport(0, 0, num_cols, num_rows); // -------------------------------------------------------------------------- // Step 3: Set projection matrices // -------------------------------------------------------------------------- double scale = 1.0; double final_matrix[16] = {0}; // Set projection parameters float m_near = 0.3; // TODO float m_far = 1e8; // TODO // new way: faster way by reuse computation and symbolic derive. See // sym_derive.m to check the math. double inv_width_scale = 1.0/(num_cols*scale); double inv_height_scale = 1.0/(num_rows*scale); double inv_width_scale_1 = inv_width_scale - 1.0; double inv_height_scale_1_s = -(inv_height_scale - 1.0); double inv_width_scale_2 = inv_width_scale*2.0; double inv_height_scale_2_s = -inv_height_scale*2.0; double m_far_a_m_near = m_far + m_near; double m_far_s_m_near = m_far - m_near; double m_far_d_m_near = m_far_a_m_near/m_far_s_m_near; final_matrix[ 0]= PointCloud::camera->fx * inv_width_scale_2; final_matrix[ 5]= PointCloud::camera->fy * inv_height_scale_2_s; final_matrix[ 8]= inv_width_scale_1 + PointCloud::camera->cx * inv_width_scale_2; final_matrix[ 9]= inv_height_scale_1_s + PointCloud::camera->cy * inv_height_scale_2_s; final_matrix[10]= m_far_d_m_near; final_matrix[11]= 1; final_matrix[14]= -(2*m_far*m_near)/m_far_s_m_near; // matrix is ready. use it glMatrixMode(GL_PROJECTION); glLoadMatrixd(final_matrix); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // -------------------------------------------------------------------------- // Step 4: render the mesh with depth as color // -------------------------------------------------------------------------- double zThreshold = 0.1; int numPixels = 0; for (unsigned int r = 0; r < num_rows - 1; r++) { for (unsigned int c = 0; c < num_cols - 1; c++) { float x00 = -depth.at<float>(c + r * num_cols, 0); float x01 = -depth.at<float>(c + r * num_cols + 1, 0); float x10 = -depth.at<float>(c + (r + 1) * num_cols, 0); float x11 = -depth.at<float>(c + (r + 1) * num_cols + 1, 0); float y00 = depth.at<float>(c + r * num_cols, 1); float y01 = depth.at<float>(c + r * num_cols + 1, 1); float y10 = depth.at<float>(c + (r + 1) * num_cols, 1); float y11 = depth.at<float>(c + (r + 1) * num_cols + 1, 1); float z00 = depth.at<float>(c + r * num_cols, 2); float z01 = depth.at<float>(c + r * num_cols + 1, 2); float z10 = depth.at<float>(c + (r + 1) * num_cols, 2); float z11 = depth.at<float>(c + (r + 1) * num_cols + 1, 2); // If depth data at 00 is missing (indicated by z00 = 0) if (z00 == 0.0) { // Make sure we can create a triangle from the other three pixels if (z01 != 0.0 && z10 != 0.0 && z11 != 0.0 && fabs(z01 - z10) < zThreshold && fabs(z11 - z10) < zThreshold && fabs(z01 - z11) < zThreshold) { glBegin(GL_TRIANGLES); glVertex3d(x11,y11,z11); glVertex3d(x10,y10,z10); glVertex3d(x01,y01,z01); glEnd(); numPixels++; } } // Else if data is missing at 11 else { if (z11 == 0.0){ if (z01 != 0.0 && z10 != 0.0 && z00 != 0.0 && fabs(z00 - z01) < zThreshold && fabs(z01 - z10) < zThreshold && fabs(z10 - z00) < zThreshold) { glBegin(GL_TRIANGLES); glVertex3d(x00,y00,z00); glVertex3d(x01,y01,z01); glVertex3d(x10,y10,z10); glEnd(); numPixels++; } } // If data is available at both 00 and 11, then check to see if we can form a triangle with 01 or 10 else { if (z01 != 0.0 && fabs(z00 - z01) < zThreshold && fabs(z01 - z11) < zThreshold && fabs(z11 - z00) < zThreshold) { glBegin(GL_TRIANGLES); glVertex3d(x00,y00,z00); glVertex3d(x01,y01,z01); glVertex3d(x11,y11,z11); glEnd(); numPixels++; } if (z10 != 0.0 && fabs(z00 - z11) < zThreshold && fabs(z11 - z10) < zThreshold && fabs(z10 - z00) < zThreshold) { glBegin(GL_TRIANGLES); glVertex3d(x00,y00,z00); glVertex3d(x11,y11,z11); glVertex3d(x10,y10,z10); glEnd(); numPixels++; } } } } } unsigned int* pDepthBuffer; GLint outWidth, outHeight, bitPerDepth; OSMesaGetDepthBuffer(ctx, &outWidth, &outHeight, &bitPerDepth, (void**)&pDepthBuffer); unsigned int shift = -1; // TODO: figure out memcpy and cast // Linearize depth map for (unsigned int r = 0; r < num_rows; r++) { for (unsigned int c = 0; c < num_cols; c++) { unsigned int r_flip = num_rows - r - 1; unsigned int c_flip = num_cols - c - 1; depth.at<float>(r_flip, c_flip) = m_near / (1 - ((float)pDepthBuffer[c + r * num_cols]) / shift); // // Ignore data that is closer than near plane or further than 15 meters if (depth.at<float>(r_flip, c_flip) > 15 || depth.at<float>(r_flip, c_flip) < m_near) { depth.at<float>(r_flip, c_flip) = 0; } depth.at<float>(r_flip, c_flip) *= 50; // fprintf(stderr, "%0.2f ", depth.at<float>(r,c)); } } fprintf(stderr, "\n%u\n", shift); OSMesaDestroyContext(ctx); delete [] pbuffer; }
34.942116
131
0.541129
danielsuo
579f25abdbd7a27642bfc7bf6bca97650fc0110b
1,260
cpp
C++
ke_mode/winnt/ntke_cpprtl/gstatic_test_suite/test_gstatic01.cpp
133a/project_ntke_cpprtl
f2d3fd36a2c44f968f7b10c344abe7e0b7aa2e4c
[ "MIT" ]
12
2016-08-02T19:22:26.000Z
2022-02-28T21:20:18.000Z
ke_mode/winnt/ntke_cpprtl/gstatic_test_suite/test_gstatic01.cpp
133a/project_ntke_cpprtl
f2d3fd36a2c44f968f7b10c344abe7e0b7aa2e4c
[ "MIT" ]
null
null
null
ke_mode/winnt/ntke_cpprtl/gstatic_test_suite/test_gstatic01.cpp
133a/project_ntke_cpprtl
f2d3fd36a2c44f968f7b10c344abe7e0b7aa2e4c
[ "MIT" ]
6
2018-04-15T16:51:40.000Z
2021-04-23T19:32:34.000Z
///////////////////////////////////////////////////////////////////////////// //// copyright (c) 2012-2017 project_ntke_cpprtl //// mailto:kt133a@seznam.cz //// license: the MIT license ///////////////////////////////////////////////////////////////////////////// #ifdef NT_KERNEL_MODE # include "ntddk.include.h" #endif namespace { enum { TEST_101 = 101 , TEST_102 , TEST_103 }; int ftest_101(int&); int ftest_102(int&); int ftest_103(int&); int res = 0; } int test_101 = ftest_101(res); static int test_102 = ftest_102(res); namespace { int test_103 = ftest_103(res); } namespace { int ftest_101(int& r) { #ifdef NT_KERNEL_MODE DbgPrint("test_gstatic01 ---> ftest_101\n"); #endif r += TEST_101; return TEST_101; } int ftest_102(int& r) { #ifdef NT_KERNEL_MODE DbgPrint("test_gstatic01 ---> ftest_102\n"); #endif r += TEST_102; return TEST_102; } int ftest_103(int& r) { #ifdef NT_KERNEL_MODE DbgPrint("test_gstatic01 ---> ftest_103\n"); #endif r += TEST_103; return TEST_103; } } namespace cpprtl { namespace test { namespace gstatic { int test_gstatic01() { return res - test_101 - test_102 - test_103 ; } } } }
15.75
77
0.543651
133a
57a155adde6e6d0de020675cf9b6eaec7ef2d7d4
289
cpp
C++
NCGB/Compile/src/Debug3.cpp
mcdeoliveira/NC
54b2a81ebda9e5260328f88f83f56fe8cf472ac3
[ "BSD-3-Clause" ]
103
2016-09-21T06:01:23.000Z
2022-03-27T06:52:10.000Z
NCGB/Compile/src/Debug3.cpp
albinjames/NC
157a55458931a18dd1f42478872c9df0de5cc450
[ "BSD-3-Clause" ]
11
2017-03-27T13:11:42.000Z
2022-03-08T13:46:14.000Z
NCGB/Compile/src/Debug3.cpp
albinjames/NC
157a55458931a18dd1f42478872c9df0de5cc450
[ "BSD-3-Clause" ]
21
2017-06-23T09:01:21.000Z
2022-02-18T06:24:00.000Z
// Debug3.c #include "Debug3.hpp" OfstreamProxy Debug3::s_ErrorFile("p9c_error_file"); OfstreamProxy Debug3::s_TimingFile("p9c_timing_file"); OfstreamProxy Debug3::s_InefficiencyFile(".impoving.ncgb.efficiency"); OfstreamProxy Debug3::s_NeedToWriteCodeFile(".need.to.write.code");
36.125
71
0.785467
mcdeoliveira
57a619f2aca1fb57f5f0192d2da657303f56d0f5
3,789
cpp
C++
BattleTank/Source/BattleTank/Private/SprungWheel.cpp
rmolinamir/BattleTank
f2887ce0703f9d4efd157aca2988e0be2f436deb
[ "MIT" ]
1
2018-11-29T06:08:16.000Z
2018-11-29T06:08:16.000Z
BattleTank/Source/BattleTank/Private/SprungWheel.cpp
rmolinamir/BattleTank
f2887ce0703f9d4efd157aca2988e0be2f436deb
[ "MIT" ]
null
null
null
BattleTank/Source/BattleTank/Private/SprungWheel.cpp
rmolinamir/BattleTank
f2887ce0703f9d4efd157aca2988e0be2f436deb
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "SprungWheel.h" #include "UObject/ConstructorHelpers.h" #include "Components/SphereComponent.h" #include "PhysicsEngine/PhysicsConstraintComponent.h" #include "Components/SceneComponent.h" #include "GameFramework/Controller.h" // Sets default values ASprungWheel::ASprungWheel() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; PrimaryActorTick.TickGroup = TG_PostPhysics; // No need to protect points as added at construction Spring = CreateDefaultSubobject<UPhysicsConstraintComponent>(FName("Spring")); // Setting up root component SetRootComponent(Spring); // Set physics parameters Spring->SetLinearXLimit(ELinearConstraintMotion::LCM_Locked, 100); Spring->SetLinearYLimit(ELinearConstraintMotion::LCM_Locked, 100); Spring->SetLinearZLimit(ELinearConstraintMotion::LCM_Free, 100); Spring->SetAngularSwing1Limit(EAngularConstraintMotion::ACM_Locked, 45); Spring->SetAngularSwing2Limit(EAngularConstraintMotion::ACM_Locked, 45); Spring->SetAngularTwistLimit(EAngularConstraintMotion::ACM_Locked, 45); Spring->SetLinearPositionTarget(FVector(0, 0, 0)); Spring->SetLinearPositionDrive(false, false, true); Spring->SetLinearVelocityTarget(FVector(0, 0, 0)); Spring->SetLinearVelocityDrive(false, false, true); Spring->SetLinearDriveParams(500, 200, 0); // End physics parameters Axle = CreateDefaultSubobject<USphereComponent>(FName("Axle")); Axle->SetupAttachment(Spring); // No need to protect points as added at construction AxleWheelConstraint = CreateDefaultSubobject<UPhysicsConstraintComponent>(FName("AxleWheelConstraint")); // Setting up root component AxleWheelConstraint->SetupAttachment(Axle); /// No need to protect points as added at construction /// static ConstructorHelpers::FObjectFinder<UStaticMesh> WheelStaticMesh(TEXT("/Game/Tank/SprungWheel_SM.SprungWheel_SM")); Wheel1 = CreateDefaultSubobject<USphereComponent>(FName("Wheel")); Wheel1->SetupAttachment(Axle); /*if (WheelStaticMesh.Object) { Wheel->SetStaticMesh(WheelStaticMesh.Object); }*/ } // Called when the game starts or when spawned void ASprungWheel::BeginPlay() { Super::BeginPlay(); // Finds attached parent actor bool retflag; SetupConstraint(retflag); if (retflag) return; // Activate collision Wheel1->SetNotifyRigidBodyCollision(true); Wheel1->OnComponentHit.AddDynamic(this, &ASprungWheel::OnHit); } // Called every frame void ASprungWheel::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (GetWorld()->TickGroup == TG_PostPhysics) { // Canceling the force TotalForceMagnitude = 0; } } void ASprungWheel::AddDrivingForce(float ForceMagnitude) { TotalForceMagnitude += ForceMagnitude; } void ASprungWheel::SetupConstraint(bool &retflag) { retflag = true; GetAttachParentActor(); if (!GetAttachParentActor()) { return; } UPrimitiveComponent* BodyRoot = Cast<UPrimitiveComponent>(GetAttachParentActor()->GetRootComponent()); // Finds the attached parent actor's root component if (!BodyRoot) { return; } Spring->SetConstrainedComponents( BodyRoot, NAME_None, Axle, NAME_None ); if (!AxleWheelConstraint) { return; } AxleWheelConstraint->SetConstrainedComponents( Axle, NAME_None, Wheel1, NAME_None ); retflag = false; } void ASprungWheel::OnHit(UPrimitiveComponent * HitComponent, AActor * OtherActor, UPrimitiveComponent * OtherComp, FVector NormalImpulse, const FHitResult & Hit) { if (!(Hit.GetActor())) { return; } Wheel1->AddForce(Axle->GetForwardVector() * TotalForceMagnitude); } //void ASprungWheel::SetNumberOfWheels(int32 NumberOfWheels) //{ // this->NumberOfWheels = NumberOfWheels; // //}
30.312
161
0.773555
rmolinamir
57a666a259ae8493beef0554fc47706ad0ab4cec
1,603
hxx
C++
c++/src/laolx/parser/OperatorFunctionId.hxx
kpfalzer/laolx
66e5571a63c289294af69949b9ec56f752efc51b
[ "MIT" ]
null
null
null
c++/src/laolx/parser/OperatorFunctionId.hxx
kpfalzer/laolx
66e5571a63c289294af69949b9ec56f752efc51b
[ "MIT" ]
null
null
null
c++/src/laolx/parser/OperatorFunctionId.hxx
kpfalzer/laolx
66e5571a63c289294af69949b9ec56f752efc51b
[ "MIT" ]
null
null
null
// // OperatorFunctionId.hxx // // // Created by Karl W Pfalzer. // #ifndef laolx_parser_OperatorFunctionId_hxx #define laolx_parser_OperatorFunctionId_hxx #include "laolx/parser/laolx.hxx" namespace laolx { namespace parser { class OverloadableOperator : public _Acceptor { public: explicit OverloadableOperator() {} virtual ~OverloadableOperator() {} class Node : public NodeVector { public: virtual ~Node() {} virtual ostream& operator<<(ostream& os) const; NODE_TYPE_DECLARE; private: friend class OverloadableOperator; explicit Node(const TPNode& node); }; static const OverloadableOperator& THE_ONE; protected: TPNode _accept(Consumer& consumer) const; }; typedef PTRcObjPtr<OverloadableOperator::Node> TPOverloadableOperatorNode; DEF_TO_XXXNODE(OverloadableOperator) class OperatorFunctionId : public _Acceptor { public: explicit OperatorFunctionId() {} virtual ~OperatorFunctionId() {} class Node : public NodeVector { public: virtual ~Node() {} virtual ostream& operator<<(ostream& os) const; NODE_TYPE_DECLARE; private: friend class OperatorFunctionId; explicit Node(const TPNode& node); }; static const OperatorFunctionId& THE_ONE; protected: TPNode _accept(Consumer& consumer) const; }; typedef PTRcObjPtr<OperatorFunctionId::Node> TPOperatorFunctionIdNode; DEF_TO_XXXNODE(OperatorFunctionId) } } #endif /* laolx_parser_OperatorFunctionId_hxx */
19.083333
74
0.679351
kpfalzer
57a71d2cfb1d136a1e75e095ade0219ba494b7fc
159
hh
C++
src/Zynga/Framework/Service/V2/Swagger.hh
chintan-j-patel/zynga-hacklang-framework
d9893b8873e3c8c7223772fd3c94d2531760172a
[ "MIT" ]
19
2018-04-23T09:30:48.000Z
2022-03-06T21:35:18.000Z
src/Zynga/Framework/Service/V2/Swagger.hh
chintan-j-patel/zynga-hacklang-framework
d9893b8873e3c8c7223772fd3c94d2531760172a
[ "MIT" ]
22
2017-11-27T23:39:25.000Z
2019-08-09T08:56:57.000Z
src/Zynga/Framework/Service/V2/Swagger.hh
chintan-j-patel/zynga-hacklang-framework
d9893b8873e3c8c7223772fd3c94d2531760172a
[ "MIT" ]
28
2017-11-16T20:53:56.000Z
2021-01-04T11:13:17.000Z
<?hh // strict namespace Zynga\Framework\Service\V2; use Zynga\Framework\Service\V2\Swagger\Base as SwaggerBase; final class Swagger extends SwaggerBase {}
19.875
59
0.786164
chintan-j-patel
57a769c2dd67e4bc743d914fee078e886c8025d9
1,984
cpp
C++
src/Chapter 2/B - Find a Median String/BA2B.cpp
titansarus/Bioinformatics-Algorithms
f501b2461e7af7f6aee698e14a1c4a0371a4847f
[ "MIT" ]
1
2021-02-08T22:34:08.000Z
2021-02-08T22:34:08.000Z
src/Chapter 2/B - Find a Median String/BA2B.cpp
titansarus/Bioinformatics-Algorithms
f501b2461e7af7f6aee698e14a1c4a0371a4847f
[ "MIT" ]
null
null
null
src/Chapter 2/B - Find a Median String/BA2B.cpp
titansarus/Bioinformatics-Algorithms
f501b2461e7af7f6aee698e14a1c4a0371a4847f
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; char nucleotides[4] = {'A', 'T', 'C', 'G'}; int hamming_distance(const string &a, const string &b) { int answer = 0; for (int i = 0; i < a.size(); i++) { if (a[i] != b[i]) { answer++; } } return answer; } int least_hamming_distance_in_text(const string &text, const string &pattern) { int min = INT_MAX; for (int i = 0; i < text.size() - pattern.size() + 1; i++) { string ss = text.substr(i, pattern.size()); int hamm_dist = hamming_distance(pattern, ss); if (hamm_dist < min) { min = hamm_dist; } } return min; } int distance_of_all_dna(vector<string> &dnas, const string &pattern) { int answer = 0; for (string dna : dnas) { answer += least_hamming_distance_in_text(dna, pattern); } return answer; } string pattern_generator(int pattern_length, int number) { string pattern = ""; int counter = 0; while (counter != pattern_length) { int char_index = number % 4; pattern += nucleotides[char_index]; number = number / 4; counter++; } return pattern; } string median_string(vector<string> &dnas, int pattern_length) { string best_pattern; int min = INT_MAX; for (int i = 0; i < (1 << pattern_length * 2); i++) { string patt = pattern_generator(pattern_length, i); int dist = distance_of_all_dna(dnas, patt); if (dist < min) { min = dist; best_pattern = patt; } } return best_pattern; } int main() { int n; cin >> n; vector<string> dnas; //you must input END at the end of strings to stop getting inputs. while (true) { string temp; cin >> temp; if (temp == "END") { break; } dnas.push_back(temp); } string answer = median_string(dnas, n); cout << answer; return 0; }
22.545455
79
0.558972
titansarus
57a81479a91c16028f54e6b744ceccd16bc4d970
305
cc
C++
CommonTools/RecoAlgos/plugins/CaloJetShallowCloneProducer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
CommonTools/RecoAlgos/plugins/CaloJetShallowCloneProducer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
CommonTools/RecoAlgos/plugins/CaloJetShallowCloneProducer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "DataFormats/JetReco/interface/CaloJet.h" #include "CommonTools/CandAlgos/interface/ShallowCloneProducer.h" typedef ShallowCloneProducer<reco::CaloJetCollection> CaloJetShallowCloneProducer; #include "FWCore/Framework/interface/MakerMacros.h" DEFINE_FWK_MODULE( CaloJetShallowCloneProducer );
33.888889
82
0.855738
nistefan
57a889dd6cc0035632f4a077d0b0dbcc5d09bc6c
76
cpp
C++
src/priv/qfhook.cpp
tomicooler/quickflux
0b0a144afa54a397382605ccea52286107678cb9
[ "Apache-2.0" ]
306
2015-06-12T11:18:53.000Z
2022-02-25T09:53:07.000Z
src/priv/qfhook.cpp
tomicooler/quickflux
0b0a144afa54a397382605ccea52286107678cb9
[ "Apache-2.0" ]
32
2015-06-23T18:11:21.000Z
2021-10-08T21:27:10.000Z
src/priv/qfhook.cpp
tomicooler/quickflux
0b0a144afa54a397382605ccea52286107678cb9
[ "Apache-2.0" ]
74
2015-12-14T13:12:06.000Z
2022-02-02T09:22:55.000Z
#include "qfhook.h" QFHook::QFHook(QObject *parent) : QObject(parent) { }
10.857143
49
0.684211
tomicooler
57b1eb7fd98b09c64f7ee1df48067fc178d13085
1,575
cpp
C++
source/app/iosuhax.cpp
emiyl/dumpling
48d76f5a4c035585683e1b414df2b66d5bb12e15
[ "MIT" ]
53
2020-04-11T15:49:21.000Z
2022-03-20T03:47:33.000Z
source/app/iosuhax.cpp
emiyl/dumpling
48d76f5a4c035585683e1b414df2b66d5bb12e15
[ "MIT" ]
22
2020-08-14T19:45:13.000Z
2022-03-30T00:49:27.000Z
source/app/iosuhax.cpp
emiyl/dumpling
48d76f5a4c035585683e1b414df2b66d5bb12e15
[ "MIT" ]
11
2020-04-19T09:19:08.000Z
2022-03-21T20:16:54.000Z
#include "iosuhax.h" #include "gui.h" int32_t mcpHookHandle = -1; int32_t fsaHandle = -1; int32_t iosuhaxHandle = -1; OSEvent haxStartEvent = {}; void haxStartCallback(IOSError arg1, void *arg2) { } bool openIosuhax() { WHBLogPrint("Preparing iosuhax..."); WHBLogConsoleDraw(); // Open MCP to send the start command mcpHookHandle = MCP_Open(); if (mcpHookHandle < 0) { WHBLogPrint("Failed to open the MCP IPC!"); return false; } // Send 0x62 ioctl command that got replaced in the ios_kernel to run the wupserver IOS_IoctlAsync(mcpHookHandle, 0x62, nullptr, 0, nullptr, 0, haxStartCallback, nullptr); OSSleepTicks(OSSecondsToTicks(1)); // Connect to dumplinghax iosuhaxHandle = IOSUHAX_Open("/dev/mcp"); if (iosuhaxHandle < 0) { WHBLogPrint("Couldn't open iosuhax :/"); WHBLogPrint("Something interfered with the exploit..."); WHBLogPrint("Try restarting your Wii U and launching Dumpling again!"); return false; } fsaHandle = IOSUHAX_FSA_Open(); if (fsaHandle < 0) { WHBLogPrint("Couldn't open iosuhax FSA!"); return false; } return true; } void closeIosuhax() { if (fsaHandle > 0) IOSUHAX_FSA_Close(fsaHandle); if (iosuhaxHandle > 0) IOSUHAX_Close(); if (mcpHookHandle > 0) MCP_Close(mcpHookHandle); OSSleepTicks(OSSecondsToTicks(1)); mcpHookHandle = -1; fsaHandle = -1; iosuhaxHandle = -1; } int32_t getFSAHandle() { return fsaHandle; } int32_t getIosuhaxHandle() { return iosuhaxHandle; }
25.819672
91
0.660317
emiyl
57b23524ca7c81bb0b3701aa84c555431b8cda0c
3,826
cpp
C++
SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.cpp
ercdndrs/Arduino-Source
c0490f0f06aaa38759aa8f11def9e1349e551679
[ "MIT" ]
null
null
null
SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.cpp
ercdndrs/Arduino-Source
c0490f0f06aaa38759aa8f11def9e1349e551679
[ "MIT" ]
null
null
null
SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.cpp
ercdndrs/Arduino-Source
c0490f0f06aaa38759aa8f11def9e1349e551679
[ "MIT" ]
null
null
null
/* Egg Super-Combined 2 * * From: https://github.com/PokemonAutomation/Arduino-Source * */ #include "Common/SwitchFramework/FrameworkSettings.h" #include "PokemonSwSh/Programs/ReleaseHelpers.h" #include "PokemonSwSh_EggHelpers.h" #include "PokemonSwSh_EggCombinedShared.h" #include "PokemonSwSh_EggSuperCombined2.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonSwSh{ EggSuperCombined2::EggSuperCombined2() : SingleSwitchProgram( FeedbackType::NONE, PABotBaseLevel::PABOTBASE_31KB, "Egg Super-Combined 2", "NativePrograms/EggSuperCombined2.md", "Fetch and hatch eggs at the same time. (Fastest - 1700 eggs/day for 5120-step)" ) , BOXES_TO_RELEASE( "<b>Boxes to Release:</b><br>Start by releasing this many boxes.", 2, 0, 32 ) , BOXES_TO_SKIP( "<b>Boxes to Skip:</b><br>Then skip this many boxes.", 1, 0, 32 ) , BOXES_TO_HATCH( "<b>Boxes to Hatch:</b>", 31, 0, 32 ) , FETCHES_PER_BATCH( "<b>Fetches per Batch:</b><br>For each batch of eggs, attempt this many egg fetches.", 6.0, 0, 7 ) , TOUCH_DATE_INTERVAL( "<b>Rollover Prevention:</b><br>Prevent a den from rolling over by periodically touching the date. If set to zero, this feature is disabled.", "4 * 3600 * TICKS_PER_SECOND" ) , m_advanced_options( "<font size=4><b>Advanced Options:</b> You should not need to touch anything below here.</font>" ) , SAFETY_TIME( "<b>Safety Time:</b><br>Additional time added to the spinning.", "8 * TICKS_PER_SECOND" ) , EARLY_HATCH_SAFETY( "<b>Safety Time:</b><br>Additional time added to the spinning.", "5 * TICKS_PER_SECOND" ) , HATCH_DELAY( "<b>Hatch Delay:</b><br>Total animation time for hatching 5 eggs when there are no shinies.", "88 * TICKS_PER_SECOND" ) { m_options.emplace_back(&BOXES_TO_RELEASE, "BOXES_TO_RELEASE"); m_options.emplace_back(&BOXES_TO_SKIP, "BOXES_TO_SKIP"); m_options.emplace_back(&BOXES_TO_HATCH, "BOXES_TO_HATCH"); m_options.emplace_back(&STEPS_TO_HATCH, "STEPS_TO_HATCH"); m_options.emplace_back(&FETCHES_PER_BATCH, "FETCHES_PER_BATCH"); m_options.emplace_back(&TOUCH_DATE_INTERVAL, "TOUCH_DATE_INTERVAL"); m_options.emplace_back(&m_advanced_options, ""); m_options.emplace_back(&SAFETY_TIME, "SAFETY_TIME"); m_options.emplace_back(&EARLY_HATCH_SAFETY, "EARLY_HATCH_SAFETY"); m_options.emplace_back(&HATCH_DELAY, "HATCH_DELAY"); } void EggSuperCombined2::program(SingleSwitchProgramEnvironment& env) const{ EggCombinedSession session{ .BOXES_TO_HATCH = BOXES_TO_HATCH, .STEPS_TO_HATCH = STEPS_TO_HATCH, .FETCHES_PER_BATCH = (float)FETCHES_PER_BATCH, .SAFETY_TIME = SAFETY_TIME, .EARLY_HATCH_SAFETY = EARLY_HATCH_SAFETY, .HATCH_DELAY = HATCH_DELAY, .TOUCH_DATE_INTERVAL = TOUCH_DATE_INTERVAL, }; grip_menu_connect_go_home(env.console); resume_game_back_out(env.console, TOLERATE_SYSTEM_UPDATE_MENU_FAST, 400); // Mass Release ssf_press_button2(env.console, BUTTON_X, OVERWORLD_TO_MENU_DELAY, 20); ssf_press_button1(env.console, BUTTON_A, 200); ssf_press_button1(env.console, BUTTON_R, 250); release_boxes(env.console, BOXES_TO_RELEASE, BOX_SCROLL_DELAY, BOX_CHANGE_DELAY); // Skip Boxes for (uint8_t c = 0; c <= BOXES_TO_SKIP; c++){ ssf_press_button1(env.console, BUTTON_R, 60); } pbf_mash_button(env.console, BUTTON_B, 600); session.eggcombined2_body(env); end_program_callback(env.console); end_program_loop(env.console); } } } }
34.781818
151
0.670413
ercdndrs
57bc0a7501acae5ab7ed283ba9bdc7dd3d49b10a
1,952
hpp
C++
include/Log.hpp
savageking-io/evelengine
f4f31419077e3467db271e82b05164eafa521eb7
[ "Apache-2.0" ]
null
null
null
include/Log.hpp
savageking-io/evelengine
f4f31419077e3467db271e82b05164eafa521eb7
[ "Apache-2.0" ]
null
null
null
include/Log.hpp
savageking-io/evelengine
f4f31419077e3467db271e82b05164eafa521eb7
[ "Apache-2.0" ]
null
null
null
#ifndef __EVEL_ENGINE_LOG_HPP__ #define __EVEL_ENGINE_LOG_HPP__ #include "spdlog/spdlog.h" #include "spdlog/sinks/stdout_color_sinks.h" #include "spdlog/sinks/basic_file_sink.h" namespace EvelEngine { class Log { public: Log(); ~Log(); void initialize(); void setLevel(spdlog::level::level_enum level); std::shared_ptr<spdlog::logger> sget(); template<typename... Args> void trace(const char* fmt, const Args&... args) { if (_log == nullptr) return; _log->trace(fmt, args...); } template<typename... Args> void debug(const char* fmt, const Args&... args) { if (_log == nullptr) return; _log->debug(fmt, args...); } template<typename... Args> void info(const char* fmt, const Args&... args) { if (_log == nullptr) return; _log->info(fmt, args...); } template<typename... Args> void warn(const char* fmt, const Args&... args) { if (_log == nullptr) return; _log->warn(fmt, args...); } template<typename... Args> void error(const char* fmt, const Args&... args) { if (_log == nullptr) return; _log->error(fmt, args...); } template<typename... Args> void critical(const char* fmt, const Args&... args) { if (_log == nullptr) return; _log->critical(fmt, args...); } private: std::shared_ptr<spdlog::logger> _log; ///< Logging subsystem }; } #endif
30.030769
72
0.441598
savageking-io
57bd226413697bca6d490a522c7cc5a8a4f0b247
12,156
cpp
C++
src/OVAFTModel.cpp
kokarare1212/OpenVAFT
42dbec4ed1123a98f465e61833a69f25bc948cd2
[ "Apache-2.0" ]
1
2022-03-23T02:35:52.000Z
2022-03-23T02:35:52.000Z
src/OVAFTModel.cpp
kokarare1212/OpenVAFT
42dbec4ed1123a98f465e61833a69f25bc948cd2
[ "Apache-2.0" ]
null
null
null
src/OVAFTModel.cpp
kokarare1212/OpenVAFT
42dbec4ed1123a98f465e61833a69f25bc948cd2
[ "Apache-2.0" ]
null
null
null
#include "OVAFTModel.h" #include <CubismDefaultParameterId.hpp> #include <CubismModelSettingJson.hpp> #include <Motion/CubismMotion.hpp> #include <fstream> #include <Id/CubismIdManager.hpp> #include <Rendering/OpenGL/CubismRenderer_OpenGLES2.hpp> #include <Utils/CubismString.hpp> #include "OVAFTFaceTracker.h" #include "OVAFTGLWidget.h" #include "OVAFTTextureManager.h" using namespace Live2D::Cubism::Framework; using namespace Live2D::Cubism::Framework::DefaultParameterId; using namespace std; namespace { csmByte *CreateBuffer(const string &filePath, csmSizeInt *outSize) { const char *path = filePath.c_str(); int size = 0; struct stat statBuf{}; if (stat(path, &statBuf) == 0) { size = statBuf.st_size; } std::fstream file; char *buf = new char[size]; file.open(path, std::ios::in | std::ios::binary); if (!file.is_open()) { return nullptr; } file.read(buf, size); file.close(); *outSize = size; return reinterpret_cast<csmByte *>(buf); } } OVAFTModel::OVAFTModel() : CubismUserModel(), modelSetting(nullptr), userTimeSeconds(0.0f) { idParamAngleX = CubismFramework::GetIdManager()->GetId(ParamAngleX); idParamAngleY = CubismFramework::GetIdManager()->GetId(ParamAngleY); idParamAngleZ = CubismFramework::GetIdManager()->GetId(ParamAngleZ); idParamBodyAngleX = CubismFramework::GetIdManager()->GetId(ParamBodyAngleX); idParamBodyAngleY = CubismFramework::GetIdManager()->GetId(ParamBodyAngleY); idParamBodyAngleZ = CubismFramework::GetIdManager()->GetId(ParamBodyAngleZ); idParamCheek = CubismFramework::GetIdManager()->GetId(ParamCheek); idParamEyeLOpen = CubismFramework::GetIdManager()->GetId(ParamEyeLOpen); idParamEyeLSmile = CubismFramework::GetIdManager()->GetId(ParamEyeLSmile); idParamEyeROpen = CubismFramework::GetIdManager()->GetId(ParamEyeROpen); idParamEyeRSmile = CubismFramework::GetIdManager()->GetId(ParamEyeRSmile); idParamMouthForm = CubismFramework::GetIdManager()->GetId(ParamMouthForm); idParamMouthOpenY = CubismFramework::GetIdManager()->GetId(ParamMouthOpenY); } OVAFTModel::~OVAFTModel() { renderBuffer.DestroyOffscreenFrame(); ReleaseMotions(); ReleaseExpressions(); for (csmInt32 i = 0; i < modelSetting->GetMotionGroupCount(); i++) { const csmChar *group = modelSetting->GetMotionGroupName(i); ReleaseMotionGroup(group); } delete (modelSetting); } void OVAFTModel::DoDraw() { if (_model == nullptr) return; GetRenderer<Rendering::CubismRenderer_OpenGLES2>()->DrawModel(); } void OVAFTModel::Draw(CubismMatrix44 &matrix) { if (_model == nullptr) return; matrix.MultiplyByMatrix(_modelMatrix); GetRenderer<Rendering::CubismRenderer_OpenGLES2>()->SetMvpMatrix(&matrix); DoDraw(); } Csm::Rendering::CubismOffscreenFrame_OpenGLES2 &OVAFTModel::GetRenderBuffer() { return renderBuffer; } void OVAFTModel::LoadAssets(const csmChar *dir, const csmChar *fileName) { modelHomeDir = dir; csmSizeInt size; const csmString path = csmString(dir) + fileName; csmByte *buffer = CreateBuffer(path.GetRawString(), &size); ICubismModelSetting *setting = new CubismModelSettingJson(buffer, size); delete[] buffer; SetupModel(setting); CreateRenderer(); SetupTextures(); } void OVAFTModel::PreloadMotionGroup(const csmChar *group) { const csmInt32 count = modelSetting->GetMotionCount(group); for (csmInt32 i = 0; i < count; i++) { csmString name = Utils::CubismString::GetFormatedString("%s_%d", group, i); csmString path = modelSetting->GetMotionFileName(group, i); path = modelHomeDir + path; csmByte *buffer1; csmSizeInt size; buffer1 = CreateBuffer(path.GetRawString(), &size); auto *tmpMotion = dynamic_cast<CubismMotion *>(LoadMotion(buffer1, size, name.GetRawString())); csmFloat32 fadeTime = modelSetting->GetMotionFadeInTimeValue(group, i); if (fadeTime >= 0.0f) { tmpMotion->SetFadeInTime(fadeTime); } fadeTime = modelSetting->GetMotionFadeOutTimeValue(group, i); if (fadeTime >= 0.0f) { tmpMotion->SetFadeOutTime(fadeTime); } tmpMotion->SetEffectIds(eyeBlinkIds, lipSyncIds); if (motions[name] != NULL) { ACubismMotion::Delete(motions[name]); } motions[name] = tmpMotion; } } void OVAFTModel::ReleaseExpressions() { for (csmMap<csmString, ACubismMotion *>::const_iterator iter = expressions.Begin(); iter != expressions.End(); ++iter) { ACubismMotion::Delete(iter->Second); } expressions.Clear(); } void OVAFTModel::ReleaseMotionGroup(const csmChar *group) const { const csmInt32 count = modelSetting->GetMotionCount(group); for (csmInt32 i = 0; i < count; i++) { csmString voice = modelSetting->GetMotionSoundFileName(group, i); if (strcmp(voice.GetRawString(), "") != 0) { csmString path = voice; path = modelHomeDir + path; } } } void OVAFTModel::ReleaseMotions() { for (csmMap<csmString, ACubismMotion *>::const_iterator iter = motions.Begin(); iter != motions.End(); ++iter) { ACubismMotion::Delete(iter->Second); } motions.Clear(); } void OVAFTModel::SetupModel(ICubismModelSetting *setting) { _updating = true; _initialized = false; modelSetting = setting; csmSizeInt size; // Cubism Model if (strcmp(modelSetting->GetModelFileName(), "") != 0) { csmString path = modelSetting->GetModelFileName(); path = modelHomeDir + path; csmByte *buffer1; buffer1 = CreateBuffer(path.GetRawString(), &size); LoadModel(buffer1, size); } // Expression if (modelSetting->GetExpressionCount() > 0) { const csmInt32 count = modelSetting->GetExpressionCount(); for (csmInt32 i = 0; i < count; i++) { csmString name = modelSetting->GetExpressionName(i); csmString path = modelSetting->GetExpressionFileName(i); path = modelHomeDir + path; csmByte *buffer2; buffer2 = CreateBuffer(path.GetRawString(), &size); ACubismMotion *motion = LoadExpression(buffer2, size, name.GetRawString()); if (expressions[name] != NULL) { ACubismMotion::Delete(expressions[name]); expressions[name] = NULL; } expressions[name] = motion; } } // Physics if (strcmp(modelSetting->GetPhysicsFileName(), "") != 0) { csmString path = modelSetting->GetPhysicsFileName(); path = modelHomeDir + path; csmByte *buffer3; buffer3 = CreateBuffer(path.GetRawString(), &size); LoadPhysics(buffer3, size); } // Pose if (strcmp(modelSetting->GetPoseFileName(), "") != 0) { csmString path = modelSetting->GetPoseFileName(); path = modelHomeDir + path; csmByte *buffer4; buffer4 = CreateBuffer(path.GetRawString(), &size); LoadPose(buffer4, size); } // EyeBlink if (modelSetting->GetEyeBlinkParameterCount() > 0) { _eyeBlink = CubismEyeBlink::Create(modelSetting); } // Breath _breath = CubismBreath::Create(); csmVector<CubismBreath::BreathParameterData> breathParameters; breathParameters.PushBack(CubismBreath::BreathParameterData(idParamAngleX, 0.0f, 15.0f, 6.5345f, 0.5f)); breathParameters.PushBack(CubismBreath::BreathParameterData(idParamAngleY, 0.0f, 8.0f, 3.5345f, 0.5f)); breathParameters.PushBack(CubismBreath::BreathParameterData(idParamAngleZ, 0.0f, 10.0f, 5.5345f, 0.5f)); breathParameters.PushBack(CubismBreath::BreathParameterData(idParamBodyAngleX, 0.0f, 4.0f, 15.5345f, 0.5f)); breathParameters.PushBack( CubismBreath::BreathParameterData(CubismFramework::GetIdManager()->GetId(ParamBreath), 0.5f, 0.5f, 3.2345f, 0.5f)); _breath->SetParameters(breathParameters); // UserData if (strcmp(modelSetting->GetUserDataFile(), "") != 0) { csmString path = modelSetting->GetUserDataFile(); path = modelHomeDir + path; csmByte *buffer5; buffer5 = CreateBuffer(path.GetRawString(), &size); LoadUserData(buffer5, size); } // EyeBlinkIds csmInt32 eyeBlinkIdCount = modelSetting->GetEyeBlinkParameterCount(); for (csmInt32 i = 0; i < eyeBlinkIdCount; ++i) { eyeBlinkIds.PushBack(modelSetting->GetEyeBlinkParameterId(i)); } // LipSyncIds csmInt32 lipSyncIdCount = modelSetting->GetLipSyncParameterCount(); for (csmInt32 i = 0; i < lipSyncIdCount; ++i) { lipSyncIds.PushBack(modelSetting->GetLipSyncParameterId(i)); } // Layout csmMap<csmString, csmFloat32> layout; modelSetting->GetLayoutMap(layout); _modelMatrix->SetupFromLayout(layout); _model->SaveParameters(); for (csmInt32 i = 0; i < modelSetting->GetMotionGroupCount(); i++) { const csmChar *group = modelSetting->GetMotionGroupName(i); PreloadMotionGroup(group); } _motionManager->StopAllMotions(); _updating = false; _initialized = true; } void OVAFTModel::SetupTextures() { for (csmInt32 modelTextureNumber = 0; modelTextureNumber < modelSetting->GetTextureCount(); modelTextureNumber++) { // Skip Bind / Load if (strcmp(modelSetting->GetTextureFileName(modelTextureNumber), "") == 0) continue; // Load Texture csmString texturePath = modelSetting->GetTextureFileName(modelTextureNumber); texturePath = modelHomeDir + texturePath; OVAFTTextureManager::TextureInfo *texture = OVAFTGLWidget::GetInstance()->GetTextureManager()->CreateTextureFromPngFile( texturePath.GetRawString()); const auto glTextureNumber = static_cast<csmInt32>(texture->id); // OpenGL GetRenderer<Rendering::CubismRenderer_OpenGLES2>()->BindTexture(modelTextureNumber, glTextureNumber); } GetRenderer<Rendering::CubismRenderer_OpenGLES2>()->IsPremultipliedAlpha(false); } void OVAFTModel::Update() { const csmFloat32 deltaTimeSeconds = OVAFTGLWidget::GetDeltaTime(); userTimeSeconds += deltaTimeSeconds; _dragManager->Update(deltaTimeSeconds); _dragX = _dragManager->GetX(); _dragY = _dragManager->GetY(); // Motion _model->LoadParameters(); _motionManager->UpdateMotion(_model, deltaTimeSeconds); _model->SaveParameters(); if (_expressionManager != nullptr) { _expressionManager->UpdateMotion(_model, deltaTimeSeconds); } // Face Tracking auto *faceTracker = OVAFTFaceTracker::GetInstance(); _model->SetParameterValue(idParamAngleX, faceTracker->AngleX()); _model->SetParameterValue(idParamAngleY, faceTracker->AngleY()); _model->SetParameterValue(idParamAngleZ, faceTracker->AngleZ()); _model->SetParameterValue(idParamBodyAngleX, faceTracker->BodyAngleX()); _model->SetParameterValue(idParamBodyAngleY, faceTracker->BodyAngleY()); _model->SetParameterValue(idParamBodyAngleZ, faceTracker->BodyAngleZ()); _model->SetParameterValue(idParamCheek, faceTracker->Cheek()); _model->SetParameterValue(idParamEyeLOpen, faceTracker->EyeLOpen()); _model->SetParameterValue(idParamEyeLSmile, faceTracker->EyeLSmile()); _model->SetParameterValue(idParamEyeROpen, faceTracker->EyeROpen()); _model->SetParameterValue(idParamEyeRSmile, faceTracker->EyeRSmile()); _model->SetParameterValue(idParamMouthForm, faceTracker->MouthForm()); _model->SetParameterValue(idParamMouthOpenY, faceTracker->MouthOpenY()); // Breath Setting if (_breath != nullptr) { _breath->UpdateParameters(_model, deltaTimeSeconds); } // Physics Setting if (_physics != nullptr) { _physics->Evaluate(_model, deltaTimeSeconds); } // Pose Setting if (_pose != nullptr) { _pose->UpdateParameters(_model, deltaTimeSeconds); } _model->Update(); }
35.964497
128
0.675716
kokarare1212
57be967f71730e8671550a9fd56d1915d458195e
1,136
cpp
C++
LIFA/Firmware/LINX/examples/RaspberryPi_2_B_Tcp/src/RaspberryPi_2_B_Tcp.cpp
Errrneist/AIARG-UWKWT-HighLevel-Break-Controller
78c60f16094c344a32bdc5ff49f4e1b65ff05f97
[ "Apache-2.0" ]
null
null
null
LIFA/Firmware/LINX/examples/RaspberryPi_2_B_Tcp/src/RaspberryPi_2_B_Tcp.cpp
Errrneist/AIARG-UWKWT-HighLevel-Break-Controller
78c60f16094c344a32bdc5ff49f4e1b65ff05f97
[ "Apache-2.0" ]
null
null
null
LIFA/Firmware/LINX/examples/RaspberryPi_2_B_Tcp/src/RaspberryPi_2_B_Tcp.cpp
Errrneist/AIARG-UWKWT-HighLevel-Break-Controller
78c60f16094c344a32bdc5ff49f4e1b65ff05f97
[ "Apache-2.0" ]
null
null
null
/**************************************************************************************** ** LINX TCP Listener For Raspberry Pi 2 Model B ** ** For more information see: www.labviewmakerhub.com/linx ** For support visit the forums at: www.labviewmakerhub.com/forums/linx ** ** Written By Sam Kristoff ** ** BSD2 License. ****************************************************************************************/ #include <stdio.h> #include <iostream> #include "LinxDevice.h" #include "LinxRaspberryPi.h" #include "LinxRaspberryPi2B.h" #include "LinxLinuxTcpListener.h" #define LISTENER_TCP_PORT 44300 LinxRaspberryPi2B* LinxDev; int main() { fprintf(stdout, "\n\n ..:: LINX ::..\n\n"); //Instantiate The LINX Device LinxDev = new LinxRaspberryPi2B(); //The LINXT Listener Is Pre Instantiated, Call Start And Pass A Pointer To The LINX Device And The UART Channel To Listen On LinxTcpConnection.Start(LinxDev, LISTENER_TCP_PORT); fprintf(stdout, "Listening On TCP Port %d.\n", LISTENER_TCP_PORT); //Check for and process commands while(1) { LinxTcpConnection.CheckForCommands(); } return 0; }
26.418605
125
0.607394
Errrneist
57c3da9320fb5e787eb1e9ceacb0f86b57881810
2,190
cpp
C++
minimum-absolute-difference-in-bst/Solution.cpp
marcos-sb/leetcode
35369f5cd9e84d3339343080087e32ec1264f410
[ "Apache-2.0" ]
1
2019-10-07T15:58:39.000Z
2019-10-07T15:58:39.000Z
minimum-absolute-difference-in-bst/Solution.cpp
marcos-sb/leetcode
35369f5cd9e84d3339343080087e32ec1264f410
[ "Apache-2.0" ]
null
null
null
minimum-absolute-difference-in-bst/Solution.cpp
marcos-sb/leetcode
35369f5cd9e84d3339343080087e32ec1264f410
[ "Apache-2.0" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ // this solution implements the following idea but in O(1) space: // the min abs diff between any two nodes in a BST lies between consecutive // values in an in-order traversal of the tree. // this algo calculates the those diffs. without building the in-order list first. class Solution { private: int _min = INT_MAX; pair<int,int> _PAIR = make_pair(-1,-1); pair<int,int> _minDiff(TreeNode* node, int parentVal) { if(!node) return _PAIR; // spread down parentVal when following pointers to the left children // to calculate the absolute difference between parentVal and // the value of the left-most sibling (next in-order value to parentVal) pair<int,int> _left = _minDiff(node->left, parentVal); if(_left.first > -1) _min = min(abs(node->val - _left.second), _min); if(parentVal > -1) _min = min(abs(node->val - parentVal), _min); // push my value when going down the right child // to calculate the absolute difference between // the next in-order value in the tree (left-most sibling of my right child) // and my value (line 29). pair<int,int> _right = _minDiff(node->right, node->val); if(_right.first > -1) { _min = min(abs(node->val - _right.first), _min); // if I have a right child return the pair my value and the right-most sibling's value // why? my value to calculate abs diff with my immediate parent's value, when going up // the recursive call stack; and the right-most of my sibling's value to calculate de abs diff // with the next in-order value if it exists. return make_pair(node->val, _right.second); } else // if I have no right links, return my value return make_pair(node->val, node->val); } public: int getMinimumDifference(TreeNode* root) { if(!root) return -1; _minDiff(root, -1); return _min; } };
38.421053
102
0.626941
marcos-sb
57c513e32a933ef4abb0e53b6e0bec1df76a9448
1,419
cpp
C++
data/dailyCodingProblem457.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
2
2020-09-04T20:56:23.000Z
2021-06-11T07:42:26.000Z
data/dailyCodingProblem457.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
data/dailyCodingProblem457.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /* Given a word W and a string S, find all starting indices in S which are anagrams of W. For example, given that W is "ab", and S is "abxaba", return 0, 3, and 4. */ // return true if umap2 contains all the keys of umap1 with respective values // and all other keys of umap2 are with value zero bool areSame(unordered_map<char, int> umap1, unordered_map<char,int> umap2){ for(auto it : umap1){ if(umap2[it.first] == 0) if(it.second != 0) return false; else{ if(it.second != umap2[it.first]) return false; } } return true; } vector<int> findAnagramIndices(string w, string s){ unordered_map<char, int> wordMap; // stores the characters of word with their respective counts unordered_map<char, int> stringMap; // stores the characters in the window of string with their respective counts vector<int> indices = {}; // stores the starting indices of anagrams for(int i=0;i<w.length();i++){ wordMap[w[i]]++; stringMap[s[i]]++; } for(int i=w.length();i<s.length();i++){ if(areSame(wordMap, stringMap)) indices.push_back(i-w.length()); stringMap[s[i]]++; stringMap[s[i-w.length()]]--; } if(areSame(wordMap,stringMap)) indices.push_back(s.length()-w.length()); return indices; } // main function int main(){ vector<int> indices = findAnagramIndices("ab","abxaba"); for(int i : indices) cout << i << "\n"; return 0; }
26.773585
114
0.676533
vidit1999
57ca944954ffc17cdd2fc142cf3cc7f137dd3804
28,755
cpp
C++
sigaba.cpp
rmsk2/rmsk2
812b2e495c9a15c16075d4358ca9b7b950b7a26c
[ "Apache-2.0" ]
4
2020-06-16T03:52:50.000Z
2021-12-25T13:12:02.000Z
sigaba.cpp
rmsk2/rmsk2
812b2e495c9a15c16075d4358ca9b7b950b7a26c
[ "Apache-2.0" ]
null
null
null
sigaba.cpp
rmsk2/rmsk2
812b2e495c9a15c16075d4358ca9b7b950b7a26c
[ "Apache-2.0" ]
null
null
null
/*************************************************************************** * Copyright 2018 Martin Grap * * 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. ***************************************************************************/ /*! \file sigaba.cpp * \brief This file contains the implementation of a simulator for the SIGABA. */ #include<stdexcept> #include<boost/scoped_ptr.hpp> #include<rmsk_globals.h> #include<alphabet.h> #include<sigaba.h> #include<configurator.h> /*! \brief Position of character O when rotor is *not* inserted in reverse. */ const unsigned int ZERO_POS = 14; /*! \brief Position of character O when rotor is inserted in reverse. */ const unsigned int ZERO_POS_INVERSE = 12; /*! \brief Used to model the contacts of the driver rotors in CSP 2900 which are not * connected to the index rotors. */ const unsigned int N = 1000; /*! \brief The element alphabet used to visualize the rotor position of the index rotors. */ alphabet<char> index_alphabet("0123456789", 10); /*! \brief Holds the default rotor_set for driver and cipher rotors. */ rotor_set sigaba_rotor_factory::normal_set_data(rmsk::std_alpha()->get_size()); /*! \brief Holds the default rotor_set for index rotors. */ rotor_set sigaba_rotor_factory::index_set_data(10); rotor_set *sigaba_rotor_factory::normal_set = &sigaba_rotor_factory::normal_set_data; rotor_set *sigaba_rotor_factory::index_set = &sigaba_rotor_factory::index_set_data; /*! \brief Specifies how the 26 output contacts of the CSP 889 driver rotors are wired to the 10 input contacts * of the index machine. */ unsigned int csp_889_mapping[] = {9, 1, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8}; /*! \brief Specifies how the 26 output contacts of the CSP 2900 driver rotors are wired to the 10 input contacts * of the index machine. The three contacts that are mapped to the vlaue N are not connected to any index * rotor. */ unsigned int csp_2900_mapping[] = {9, 1, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, N, N, N, 7, 7, 0, 0, 8, 8, 8, 8}; /*! \brief Output characters when doing decryptions and input characters for encryptions. */ ustring str_plain_chars = "abcdefghijklmnopqrstuvwxy "; /*! \brief Output characters when doing encryptions and input characters when doing decryptions. */ ustring str_cipher_chars = "abcdefghijklmnopqrstuvwxyz"; /* ----------------------------------------------------------- */ rotor_set *sigaba_rotor_factory::get_cipher_rotor_set() { if (normal_set->get_num_rotors() == 0) { vector<unsigned int> ring_data(rmsk::std_alpha()->get_size(), 0); // Permutations for cipher and driver rotors normal_set->add_rotor_and_ring(SIGABA_ROTOR_0, rmsk::std_alpha()->to_vector(string("ychlqsugbdixnzkerpvjtawfom")), ring_data); normal_set->add_rotor_and_ring(SIGABA_ROTOR_1, rmsk::std_alpha()->to_vector(string("inpxbwetguysaochvldmqkzjfr")), ring_data); normal_set->add_rotor_and_ring(SIGABA_ROTOR_2, rmsk::std_alpha()->to_vector(string("wndriozptaxhfjyqbmsvekucgl")), ring_data); normal_set->add_rotor_and_ring(SIGABA_ROTOR_3, rmsk::std_alpha()->to_vector(string("tzghobkrvuxlqdmpnfwcjyeias")), ring_data); normal_set->add_rotor_and_ring(SIGABA_ROTOR_4, rmsk::std_alpha()->to_vector(string("ywtahrqjvlcexungbipzmsdfok")), ring_data); normal_set->add_rotor_and_ring(SIGABA_ROTOR_5, rmsk::std_alpha()->to_vector(string("qslrbtekogaicfwyvmhjnxzudp")), ring_data); normal_set->add_rotor_and_ring(SIGABA_ROTOR_6, rmsk::std_alpha()->to_vector(string("chjdqignbsakvtuoxfwleprmzy")), ring_data); normal_set->add_rotor_and_ring(SIGABA_ROTOR_7, rmsk::std_alpha()->to_vector(string("cdfajxtimnbeqhsugrylwzkvpo")), ring_data); normal_set->add_rotor_and_ring(SIGABA_ROTOR_8, rmsk::std_alpha()->to_vector(string("xhfeszdnrbcgkqijltvmuoyapw")), ring_data); normal_set->add_rotor_and_ring(SIGABA_ROTOR_9, rmsk::std_alpha()->to_vector(string("ezjqxmogytcsfriupvnadlhwbk")), ring_data); } return normal_set; } rotor_set *sigaba_rotor_factory::get_index_rotor_set() { if (index_set->get_num_rotors() == 0) { // Permutations for index rotors index_set->add_rotor(SIGABA_INDEX_0, index_alphabet.to_vector(string("7591482630"))); index_set->add_rotor(SIGABA_INDEX_1, index_alphabet.to_vector(string("3810592764"))); index_set->add_rotor(SIGABA_INDEX_2, index_alphabet.to_vector(string("4086153297"))); index_set->add_rotor(SIGABA_INDEX_3, index_alphabet.to_vector(string("3980526174"))); index_set->add_rotor(SIGABA_INDEX_4, index_alphabet.to_vector(string("6497135280"))); set<unsigned int> const_index_ids = {SIGABA_INDEX_0, SIGABA_INDEX_1, SIGABA_INDEX_2, SIGABA_INDEX_3, SIGABA_INDEX_4}; index_set->set_const_ids(const_index_ids); } return index_set; } /* ----------------------------------------------------------- */ /*! Visualizing the rotor windows is a bit more difficult for the SIGABA than for other machines. The reason * for this is that when SIGABA rotors are inserted in reverse the inscription of the letters on their * circumfence effectively "changes". This is best explained by an example. The normal stepping order of * a cipher or driver rotor that is inserted in the normal way is AZYXWV... . When the same rotor is inserted * in reverse the stepping sequence becomes ABCDEFGH... where are all the letters are upside down. */ ustring sigaba_base_machine::visualize_sigaba_rotor_pos(string& rotor_identifier, alphabet<char>& alpha) { ustring result; if (get_stepping_gear()->get_descriptor(rotor_identifier).id.insert_inverse) { simple_mod_int help(get_stepping_gear()->get_ring_pos(rotor_identifier), alpha.get_size()); // When inserted in reverse the character shown in the rotor window can be determined by mapping the // additve inverse modulo alpha.get_size() of the current position to a letter of the alphabet referenced // by parameter alpha. result += alpha.to_val(-help); } else { result += alpha.to_val(get_stepping_gear()->get_ring_pos(rotor_identifier)); } return result; } bool sigaba_base_machine::move_all_sigaba_rotors(ustring& new_rotor_positions, alphabet<char>& alpha, bool do_modify) { bool result = (new_rotor_positions.length() != 5); vector<string> ids; unsigned int numeric_position; string new_positions = new_rotor_positions; vector<pair<string, unsigned int> > requested_positions; get_stepping_gear()->get_rotor_identifiers(ids); for (unsigned int count = 0; (count < ids.size()) && (!result); count++) { string identifier = ids[count]; result = !alpha.contains_symbol(new_positions[count]); if (!result) { numeric_position = alpha.from_val(new_positions[count]); if (get_stepping_gear()->get_descriptor(identifier).id.insert_inverse) { simple_mod_int help(numeric_position, alpha.get_size()); // When inserted in reverse the character shown in the rotor window can be determined by mapping the // additve inverse modulo alpha.get_size() of the current position to a letter of the alphabet referenced // by parameter alpha. //get_stepping_gear()->set_ring_pos(identifier, -help); requested_positions.push_back(pair<string, unsigned int>(identifier, -help)); } else { //get_stepping_gear()->set_ring_pos(identifier, numeric_position); requested_positions.push_back(pair<string, unsigned int>(identifier, numeric_position)); } } } // Everything was checked. Now do modifications if verification was successfull and user reqested the modifications for (unsigned int count = 0; (count < 5) && (!result) && (do_modify); count++) { get_stepping_gear()->set_ring_pos(requested_positions[count].first, requested_positions[count].second); } return result; } /* ----------------------------------------------------------- */ sigaba_index_machine::sigaba_index_machine(rotor_id null_id, rotor_id one_id, rotor_id two_id, rotor_id three_id, rotor_id four_id) { add_rotor_set(DEFAULT_SET, sigaba_rotor_factory::get_index_rotor_set()); vector<string> rotor_names; boost::shared_ptr<rotor> help; stepper = NULL; machine_name = MNAME_SIGABA; // Set up names of rotor slots rotor_names.push_back(I_ZERO); rotor_names.push_back(I_ONE); rotor_names.push_back(I_TWO); rotor_names.push_back(I_THREE); rotor_names.push_back(I_FOUR); set_stepping_gear(new stepping_gear(rotor_names, index_alphabet.get_size())); // Insert rotors into machine prepare_rotor(null_id, I_ZERO); prepare_rotor(one_id, I_ONE); prepare_rotor(two_id, I_TWO); prepare_rotor(three_id, I_THREE); prepare_rotor(four_id, I_FOUR); reset(); } bool sigaba_index_machine::move_all_rotors(ustring& new_positions) { return move_all_sigaba_rotors(new_positions, index_alphabet, true); } ustring sigaba_index_machine::visualize_rotor_pos(string& rotor_identifier) { return visualize_sigaba_rotor_pos(rotor_identifier, index_alphabet); } vector<ustring> sigaba_index_machine::visualize_active_permutations() { vector<unsigned int> positions_to_visualize = {0, 1, 2, 3, 4}; return rotor_perm_visualizer_help(positions_to_visualize, index_alphabet); } void sigaba_index_machine::reset() { // Set all rotors to position 0 get_stepping_gear()->set_rotor_displacement(I_ZERO, 0); get_stepping_gear()->set_rotor_displacement(I_ONE, 0); get_stepping_gear()->set_rotor_displacement(I_TWO, 0); get_stepping_gear()->set_rotor_displacement(I_THREE, 0); get_stepping_gear()->set_rotor_displacement(I_FOUR, 0); get_stepping_gear()->reset(); } /* ----------------------------------------------------------- */ sigaba_driver::sigaba_driver(rotor_id stat_l_id, rotor_id slow_id, rotor_id fast_id, rotor_id middle_id, rotor_id stat_r_id) : sigaba_base_machine() { add_rotor_set(DEFAULT_SET, sigaba_rotor_factory::get_cipher_rotor_set()); vector<string> rotor_names; stepper = NULL; machine_name = MNAME_SIGABA; // Set up names of rotor slots rotor_names.push_back(STATOR_L); rotor_names.push_back(S_SLOW); rotor_names.push_back(S_FAST); rotor_names.push_back(S_MIDDLE); rotor_names.push_back(STATOR_R); set_stepping_gear(new sigaba_driver_stepper(rotor_names)); // Insert rotors into machine prepare_rotor(stat_r_id, STATOR_R); prepare_rotor(middle_id, S_MIDDLE); prepare_rotor(fast_id, S_FAST); prepare_rotor(slow_id, S_SLOW); prepare_rotor(stat_l_id, STATOR_L); get_stepping_gear()->reset(); } ustring sigaba_driver::visualize_rotor_pos(string& rotor_identifier) { return visualize_sigaba_rotor_pos(rotor_identifier, *rmsk::std_alpha()); } bool sigaba_driver::move_all_rotors(ustring& new_positions) { return move_all_sigaba_rotors(new_positions, *rmsk::std_alpha(), true); } /* ----------------------------------------------------------- */ void sigaba_driver_stepper::reset() { unsigned int count = 0; stepping_gear::reset(); for (count = 0; count < num_rotors; count++) { // The number of the contact that is identified by the letter O depends on whether // the rotor is inserted normal or in reverse if (!get_descriptor(count).id.insert_inverse) { set_rotor_displacement(count, ZERO_POS); } else { set_rotor_displacement(count, ZERO_POS_INVERSE); } rotors[rotor_positions[count]].ring->set_offset(0); } } void sigaba_driver_stepper::step_rotors() { bool middle_steps, slow_steps; // Do not move rotors when currently uncoupled if (!uncouple_stepper) { stepping_gear::step_rotors(); // The number of the contact that is identified by the letter O depends on whether // the rotor is inserted normal or in reverse // Middle rotor steps if fast rotor is on position O if (get_descriptor(S_FAST).id.insert_inverse) { middle_steps = (get_ring_pos(S_FAST) == ZERO_POS_INVERSE); } else { middle_steps = (get_ring_pos(S_FAST) == ZERO_POS); } // Slow rotor steps if the middle rotor steps and the middle rotor is on position O if (get_descriptor(S_MIDDLE).id.insert_inverse) { slow_steps = middle_steps && (get_ring_pos(S_MIDDLE) == ZERO_POS_INVERSE); } else { slow_steps = middle_steps && (get_ring_pos(S_MIDDLE) == ZERO_POS); } // The fast rotor always steps step_rotor_back(S_FAST); // Move the remaining rotors if (middle_steps) { step_rotor_back(S_MIDDLE); } if (slow_steps) { step_rotor_back(S_SLOW); } } } /* ----------------------------------------------------------- */ sigaba_stepper::sigaba_stepper(vector<string>& rotor_identifiers, bool csp_2900_flag) : stepping_gear(rotor_identifiers, rmsk::std_alpha()->get_size()) { driver = NULL; index = NULL; prepare_machine_type(csp_2900_flag); } void sigaba_stepper::prepare_machine_type(bool csp_2900_flag) { backstepping_rotors.clear(); if (!csp_2900_flag) { // CSP 889 // Four contacts of the driver machine are energized to produce the stepping // information for the cipher rotors energized_contacts = "fghi"; contact_mapping = csp_889_mapping; } else { // CSP 2900 // Six contacts of the driver machine are energized to produce the stepping // information for the cipher rotors energized_contacts = "defghi"; contact_mapping = csp_2900_mapping; // The cipher rotors are numbered from left to right. I.e. in CSP 2900 // the rotors that are next to the leftmost and rightmost rotors step // in the opposite direction backstepping_rotors.insert(1); backstepping_rotors.insert(3); } is_csp_2900 = csp_2900_flag; } unsigned int sigaba_stepper::produce_control_output(unsigned int in_char) { unsigned int result = 0, temp; // Current passes through the driver machine from right to left instead from left to right. // Therefore we have to use the decrypt method of the driver machine temp = driver->get_stepping_gear()->get_stack().decrypt(in_char); // Map driver output to index inputs result = contact_mapping[temp]; // Test if any output contact of driver machine was energized if (result != N) { // Pass current through index machine result = index->encrypt(result); } return result; } void sigaba_stepper::step_rotors() { // Contains the rotor numbers of the rotors which will step in this cycle set<unsigned int> rotors_who_step; set<unsigned int>::iterator set_iter; unsigned int temp; // Mapping that describes which output contacts of the index rotors are used to determine // the stepping motion. I.e. if the index machine output contacts 0 or 9 are energized // cipher rotor 0 steps, if the contacts 1 or 2 are energized rotor 4 steps and so on. unsigned int ind_mapping[] = {0, 4, 4, 3, 3, 2, 2, 1, 1, 0}; // Simulate that the input contacts of the driver rotors which are specified by the instance variable // energized_contacts are energized for (unsigned int count = 0; count < energized_contacts.length(); count++) { // Let current pass through the driver and index rotors temp = produce_control_output(rmsk::std_alpha()->from_val(energized_contacts[count])); // The value N means that no output contact of the index rotors is energized if (temp != N) { // An output contact of the index rotors is energized. Determine which cipher rotor // has to be stepped rotors_who_step.insert(ind_mapping[temp]); } } // Now the rotors of the driver machine are stepped driver->step_rotors(); // Move the cipher rotors for (set_iter = rotors_who_step.begin(); set_iter != rotors_who_step.end(); ++set_iter) { // In CSP 2900 some cipher rotors move in the opposite direction if (backstepping_rotors.count(*set_iter) == 0) { step_rotor_back(rotor_positions[*set_iter]); } else { advance_rotor(rotor_positions[*set_iter]); } } } void sigaba_stepper::setup_step(string& rotor_name) { sigaba_driver_stepper *dr_step = dynamic_cast<sigaba_driver_stepper *>(driver->get_stepping_gear()); bool old_couple_state = dr_step->get_uncouple_state(); // Uncouple driver stepper dr_step->set_uncouple_state(true); // Advance given rotor of driver machine dr_step->step_rotor_back(rotor_name); // Step cipher rotors step_rotors(); // Recouple driver stepper dr_step->set_uncouple_state(old_couple_state); } void sigaba_stepper::setup_step(string& rotor_name, unsigned int num_steps) { for (unsigned int count = 0; count < num_steps; count++) { setup_step(rotor_name); } } void sigaba_stepper::reset() { unsigned int count = 0; stepping_gear::reset(); // Reset positions of driver rotors if (driver != NULL) { driver->get_stepping_gear()->reset(); } // Reset positions of index rotors if (index != NULL) { index->reset(); } // The number of the contact that is identified by the letter O depends on whether // the rotor is inserted normal or in reverse // Reset positions of cipher rotors for (count = 0; count < num_rotors; count++) { if (!get_descriptor(count).id.insert_inverse) { set_rotor_displacement(count, ZERO_POS); } else { set_rotor_displacement(count, ZERO_POS_INVERSE); } rotors[rotor_positions[count]].ring->set_offset(0); } } /* ----------------------------------------------------------- */ void sigaba::save_additional_components(Glib::KeyFile& ini_file) { sigaba_index_machine *index = get_sigaba_stepper()->get_index_bank(); sigaba_driver *driver = get_sigaba_stepper()->get_driver_machine(); ini_file.set_boolean("stepper", "is_csp_2900", get_sigaba_stepper()->is_2900()); index->save_ini(ini_file); driver->save_ini(ini_file); } bool sigaba::load_additional_components(Glib::KeyFile& ini_file) { bool result = false, temp_csp_2900_flag; sigaba_index_machine *index = get_sigaba_stepper()->get_index_bank(); sigaba_driver *driver = get_sigaba_stepper()->get_driver_machine(); do { // Retrieve operating mode if ((result = !ini_file.has_key("stepper", "is_csp_2900"))) { break; } temp_csp_2900_flag = ini_file.get_boolean("stepper", "is_csp_2900"); get_sigaba_stepper()->prepare_machine_type(temp_csp_2900_flag); // Restore state of index machine if ((result = index->load_ini(ini_file))) { break; } // Restore state of driver machine if ((result = driver->load_ini(ini_file))) { break; } } while(0); return result; } void sigaba::set_default_set_name(string default_set_name) { rotor_machine::set_default_set_name(default_set_name); get_sigaba_stepper()->get_driver_machine()->set_default_set_name(default_set_name); get_sigaba_stepper()->get_index_bank()->set_default_set_name(default_set_name); } ustring sigaba::visualize_rotor_pos(string& rotor_identifier) { return visualize_sigaba_rotor_pos(rotor_identifier, *rmsk::std_alpha()); } vector<ustring> sigaba::visualize_active_permutations() { vector<ustring> result; vector<ustring> index_perms = get_sigaba_stepper()->get_index_bank()->visualize_active_permutations(); index_perms.push_back(""); vector<ustring> driver_perms = get_sigaba_stepper()->get_driver_machine()->visualize_active_permutations(); vector<ustring> crypt_perms = rotor_machine::visualize_active_permutations(); result.insert(std::end(result), std::begin(index_perms), std::end(index_perms)); result.insert(std::end(result), std::begin(driver_perms), std::end(driver_perms)); result.insert(std::end(result), std::begin(crypt_perms) + 2, std::end(crypt_perms)); return result; } ustring sigaba::visualize_all_positions() { ustring result; string temp; temp = get_sigaba_stepper()->get_index_bank()->visualize_all_positions(); reverse(temp.begin(), temp.end()); result = temp; temp = get_sigaba_stepper()->get_driver_machine()->visualize_all_positions(); reverse(temp.begin(), temp.end()); result += temp; temp = rotor_machine::visualize_all_positions(); reverse(temp.begin(), temp.end()); result += temp; return result; } bool sigaba::move_all_rotors(ustring& new_positions) { bool result = (new_positions.length() != 15); ustring index_positions = new_positions.substr(0, 5), driver_positions = new_positions.substr(5, 5); ustring cipher_positions = new_positions.substr(10, 5); result = result || get_sigaba_stepper()->get_index_bank()->move_all_sigaba_rotors(index_positions, index_alphabet, false); result = result || get_sigaba_stepper()->get_driver_machine()->move_all_sigaba_rotors(driver_positions, *rmsk::std_alpha(), false); result = result || move_all_sigaba_rotors(cipher_positions, *rmsk::std_alpha(), false); // Everything is checked. Now do actual modifications if (!result) { (void)get_sigaba_stepper()->get_index_bank()->move_all_rotors(index_positions); (void)get_sigaba_stepper()->get_driver_machine()->move_all_rotors(driver_positions); (void)move_all_sigaba_rotors(cipher_positions, *rmsk::std_alpha(), true); } return result; } string sigaba::get_description() { string result; if (get_sigaba_stepper()->is_2900()) { result = "CSP2900"; } else { result = "CSP889"; } return result; } bool sigaba::randomize(string& param) { bool result = false; random_bit_source reverse_rotors(15); urandom_generator rand; bool is_csp2900 = get_sigaba_stepper()->is_2900(); map<string, string> machine_conf; boost::scoped_ptr<configurator> c(configurator_factory::get_configurator(machine_name)); string cipher_rotors, control_rotors, index_rotors; vector<unsigned int> cipher_displacements, control_displacements, index_displacements; if (param == "csp2900") { is_csp2900 = true; } if (param == "csp889") { is_csp2900 = false; } try { permutation rotor_selection_perm = permutation::get_random_permutation(rand, 10); permutation index_selection_perm = permutation::get_random_permutation(rand, 5); for(unsigned int count = 0; count < 5; count++) { cipher_rotors += '0' + (char)(rotor_selection_perm.encrypt(count)); cipher_rotors += ((reverse_rotors.get_next_val() == 0) ? 'N' : 'R'); } for(unsigned int count = 5; count < 10; count++) { control_rotors += '0' + (char)(rotor_selection_perm.encrypt(count)); control_rotors += ((reverse_rotors.get_next_val() == 0) ? 'N' : 'R'); } for(unsigned int count = 0; count < 5; count++) { index_rotors += '0' + (char)(index_selection_perm.encrypt(count)); index_rotors += ((reverse_rotors.get_next_val() == 0) ? 'N' : 'R'); } machine_conf[KW_CIPHER_ROTORS] = cipher_rotors; machine_conf[KW_CONTROL_ROTORS] = control_rotors; machine_conf[KW_INDEX_ROTORS] = index_rotors; machine_conf[KW_CSP_2900_FLAG] = (is_csp2900 ? CONF_TRUE : CONF_FALSE); c->configure_machine(machine_conf, this); cipher_displacements = rmsk::std_alpha()->to_vector(rmsk::std_alpha()->get_random_string(5)); control_displacements = rmsk::std_alpha()->to_vector(rmsk::std_alpha()->get_random_string(5)); index_displacements = index_alphabet.to_vector(index_alphabet.get_random_string(5)); get_sigaba_stepper()->set_all_displacements(cipher_displacements); get_sigaba_stepper()->get_driver_machine()->get_stepping_gear()->set_all_displacements(control_displacements); get_sigaba_stepper()->get_index_bank()->get_stepping_gear()->set_all_displacements(index_displacements); } catch(...) { result = true; } return result; } sigaba::sigaba(vector<rotor_id>& r_ids, bool csp_2900_flag) : sigaba_base_machine() { add_rotor_set(DEFAULT_SET, sigaba_rotor_factory::get_cipher_rotor_set()); // create index machine sigaba_index_machine *ind = new sigaba_index_machine(r_ids[10], r_ids[11], r_ids[12], r_ids[13], r_ids[14]); // create driver machine sigaba_driver *dri = new sigaba_driver(r_ids[5], r_ids[6], r_ids[7], r_ids[8], r_ids[9]); pair<boost::shared_ptr<rotor>, boost::shared_ptr<rotor_ring> > help; vector<string> rotor_names; vector<gunichar> plain_alph, cipher_alph; // Set up names of rotor slots for cipher rotors rotor_names.push_back(R_ZERO); rotor_names.push_back(R_ONE); rotor_names.push_back(R_TWO); rotor_names.push_back(R_THREE); rotor_names.push_back(R_FOUR); machine_name = MNAME_SIGABA; // Set up stepping mechanism sigaba_stepper *s = new sigaba_stepper(rotor_names, csp_2900_flag); s->set_index_bank(ind); s->set_driver_machine(dri); set_stepping_gear(s); // Set up cipher and plaintext alphabets printing_device::ustr_to_vec(str_plain_chars, plain_alph); printing_device::ustr_to_vec(str_cipher_chars, cipher_alph); boost::shared_ptr<alphabet<gunichar> > plain_alpha(new alphabet<gunichar>(plain_alph)); boost::shared_ptr<alphabet<gunichar> > cipher_alpha(new alphabet<gunichar>(cipher_alph)); // Set up printing_device asymmetric_printing_device *sigaba_printer = new asymmetric_printing_device(); sigaba_printer->set_plain_alphabet(plain_alpha); sigaba_printer->set_cipher_alphabet(cipher_alpha); set_printer(boost::shared_ptr<printing_device>(sigaba_printer)); // Set up keyboard boost::shared_ptr<asymmetric_keyboard> sigaba_keyboard(new asymmetric_keyboard()); sigaba_keyboard->set_plain_alphabet(plain_alpha); sigaba_keyboard->set_cipher_alphabet(cipher_alpha); set_keyboard(sigaba_keyboard); // Insert cipher rotors prepare_rotor(r_ids[0], R_ZERO); prepare_rotor(r_ids[1], R_ONE); prepare_rotor(r_ids[2], R_TWO); prepare_rotor(r_ids[3], R_THREE); prepare_rotor(r_ids[4], R_FOUR); randomizer_params.push_back(randomizer_descriptor("csp2900", "Force CSP2900")); randomizer_params.push_back(randomizer_descriptor("csp889", "Force CSP889")); get_stepping_gear()->reset(); }
36.033835
142
0.659503
rmsk2
57d102e39b44fe96aa9215603fa39577802ccf5f
3,259
cxx
C++
src/Conic.cxx
fermi-lat/geometry
71a08bdb0caf952566fed8d8aeb62bd264a4bab7
[ "BSD-3-Clause" ]
null
null
null
src/Conic.cxx
fermi-lat/geometry
71a08bdb0caf952566fed8d8aeb62bd264a4bab7
[ "BSD-3-Clause" ]
null
null
null
src/Conic.cxx
fermi-lat/geometry
71a08bdb0caf952566fed8d8aeb62bd264a4bab7
[ "BSD-3-Clause" ]
null
null
null
// $Id: Conic.cxx,v 1.1.1.1 1999/12/20 22:28:06 burnett Exp $ // Author: T. Burnett // Project: geometry // // Conic class implementation #include "geometry/Conic.h" inline static double sqr(double x){return x*x;} //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Conic::Conic( const Point& origin, const Vector& axis, double radius, double slope ) //---------------------------------------------------- : Surface(origin ,axis.unit()) , m_slope(slope) , m_radius(radius) {} //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ double Conic::how_near( const Point& x ) const //------------------------------------ // Distance from the point x to the nearest point on the Conic. // The distance will be positive if the point is inside the Conic, // negative if the point is outside. { Vector r = x - origin(); double z = r*axis(), rho = sqrt( r.mag2() - sqr(z) ), c = sqrt(1+sqr(m_slope)); return (radius()>0? radius(z)-rho : rho+radius(z))/c ; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Vector Conic::normal( const Point& x )const //---------------------------------- { Vector r = x-origin(); Vector rhohat = (r - (r*axis())*axis()).unit(); // unit vector in rho direction double b = radius()>0? m_slope : -m_slope; // actual slope Vector n = sqrt(1-sqr(b))*rhohat - b* axis(); return radius()>0 ? n : -n; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ double Conic::distance(const Point& x, const Vector& vhat, int inout)const //----------------------------------------------------------------- // solve: | rperp(s) | = R(rpar(s)), // where rperp(s) = r(s)-ahat*(r(s)*ahat) // rpar(s) = r(s)*ahat; // r(s) = x-origin() + vhat*s // R(z) = R0 + alpha*z { Vector ahat = axis(), r = x - origin(); double rpar = r*ahat, vpar = vhat*ahat, alpha= m_slope, R = radius(rpar); Vector rperp = r - rpar*ahat, vperp = vhat-vpar*ahat; double a = vperp.mag2()-sqr(alpha*vpar), b = vperp*rperp-alpha*vpar*R, c = rperp.mag2() - sqr(R), disc = b*b-a*c, s; // now want appropriate root of a*s^2 + 2*b*s + c = 0 if( disc<=0 ) return FLT_MAX; // misses if( radius()<0 ) inout *=-1; // reverse enter/leave sense int leaving = inout==1; if( b<0 ) { // velocity toward axis s = (leaving) ? (-b+sqrt(disc))/a : c/(-b+sqrt(disc)); } else { // heading away from axis: can only leave s = (leaving) ? c/(-b-sqrt(disc)) : FLT_MAX; } // finally see if the solution is invalid, i.e., past the apex of the cone if( m_slope!=0 && (rpar + s*vpar) < -m_radius/m_slope ){ // std::cerr << "s="<< s<< ", rpar(s)= " << rpar+s*vpar << ", apex at " <<- m_radius/m_slope<<std::endl ;; s = FLT_MAX; } return s ; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void Conic::printOn( std::ostream& os ) const //-------------------------------------- { os << "Conic surface with origin: " << origin() << ",\t radius: " << radius() << ",\t axis: " << axis() << ",\t slope: "<< m_slope << "\n"; }
30.175926
115
0.45382
fermi-lat
57d71f638c6d45c8454660e0b733b6641ea36295
771
hpp
C++
3BIT/ISA/argparser.hpp
MisoKov/vutbr-fit-bit
5bee4c50ea231f2f6f9f1ce9260e2a913e1cfc6b
[ "MIT" ]
null
null
null
3BIT/ISA/argparser.hpp
MisoKov/vutbr-fit-bit
5bee4c50ea231f2f6f9f1ce9260e2a913e1cfc6b
[ "MIT" ]
null
null
null
3BIT/ISA/argparser.hpp
MisoKov/vutbr-fit-bit
5bee4c50ea231f2f6f9f1ce9260e2a913e1cfc6b
[ "MIT" ]
null
null
null
/** * @file argparser.hpp * @author Michal Koval, xkoval17 FIT * @date 14.11.2020 * @brief Header file for arguments parsing part of program * @note Compiler: gcc 7.5 */ #ifndef ISA_ARGPARSER_H #define ISA_ARGPARSER_H #include "errors.hpp" #include <string.h> #include <iostream> #include <string> /** * Structure used to return processed arguments */ typedef struct { std::string token; bool help; bool verbose; int ret_code; } Args; /** * Handles and processes the program arguments * @param argc number of arfuments * @param argv list of arguments * @return Args structure containing processed arguments */ Args handle_args(int argc, char *argv[]); /** * Prints help message to stdout */ void print_help(); #endif //ISA_ARGPARSER_H
19.275
59
0.705577
MisoKov