text
stringlengths
54
60.6k
<commit_before>/* * Thread.cpp 15.08.2006 (mueller) * * Copyright (C) 2006 by Universitaet Stuttgart (VIS). Alle Rechte vorbehalten. */ #include "vislib/Thread.h" #ifndef _WIN32 #include <unistd.h> #endif /* !_WIN32 */ #include "vislib/assert.h" #include "vislib/error.h" #include "vislib/IllegalParamException.h" #include "vislib/IllegalStateException.h" #include "vislib/SystemException.h" #include "vislib/Trace.h" #include "vislib/UnsupportedOperationException.h" #include "DynamicFunctionPointer.h" #include <cstdio> #include <iostream> #ifndef _WIN32 /** * Return code that marks a thread as still running. Make sure that the value * is the same as on Windows. */ #define STILL_ACTIVE (259) #endif /* !_WIN32 */ /* * vislib::sys::Thread::Sleep */ void vislib::sys::Thread::Sleep(const DWORD millis) { #ifdef _WIN32 ::Sleep(millis); #else /* _WIN32 */ if (millis >= 1000) { /* At least one second to sleep. Use ::sleep() for full seconds. */ ::sleep(millis / 1000); } ::usleep((millis % 1000) * 1000); #endif /* _WIN32 */ } /* * vislib::sys::Thread::Reschedule */ void vislib::sys::Thread::Reschedule(void) { #ifdef _WIN32 #if (_WIN32_WINNT >= 0x0400) ::SwitchToThread(); #else DynamicFunctionPointer<BOOL (*)(void)> stt("kernel32", "SwitchToThread"); if (stt.IsValid()) { stt(); } else { ::Sleep(0); } #endif #else /* _WIN32 */ if (::sched_yield() != 0) { throw SystemException(__FILE__, __LINE__); } #endif /* _WIN32 */ } /* * vislib::sys::Thread::Thread */ vislib::sys::Thread::Thread(Runnable *runnable) : id(0), runnable(runnable), runnableFunc(NULL) { #ifdef _WIN32 this->handle = NULL; #else /* _WIN32 */ ::pthread_attr_init(&this->attribs); ::pthread_attr_setscope(&this->attribs, PTHREAD_SCOPE_SYSTEM); ::pthread_attr_setdetachstate(&this->attribs, PTHREAD_CREATE_JOINABLE); this->exitCode = 0; #endif /* _WIN32 */ this->threadFuncParam.thread = this; this->threadFuncParam.userData = NULL; } /* * vislib::sys::Thread::Thread */ vislib::sys::Thread::Thread(Runnable::Function runnableFunc) : id(0), runnable(NULL), runnableFunc(runnableFunc) { #ifdef _WIN32 this->handle = NULL; #else /* _WIN32 */ ::pthread_attr_init(&this->attribs); ::pthread_attr_setscope(&this->attribs, PTHREAD_SCOPE_SYSTEM); ::pthread_attr_setdetachstate(&this->attribs, PTHREAD_CREATE_JOINABLE); this->exitCode = 0; #endif /* _WIN32 */ this->threadFuncParam.thread = this; this->threadFuncParam.userData = NULL; } /* * vislib::sys::Thread::~Thread */ vislib::sys::Thread::~Thread(void) { #ifdef _WIN32 if (this->handle != NULL) { ::CloseHandle(this->handle); } #else /* _WIIN32 */ // TODO: Must detach, iff not joined? How should we know this here? //::pthread_detach(this->id); ::pthread_attr_destroy(&this->attribs); #endif /* _WIN32 */ } /* * vislib::sys::Thread::GetExitCode */ DWORD vislib::sys::Thread::GetExitCode(void) const { #ifdef _WIN32 DWORD retval = 0; if (::GetExitCodeThread(this->handle, &retval) == FALSE) { throw SystemException(__FILE__, __LINE__); } return retval; #else /* _WIN32 */ return this->exitCode; #endif /* _WIN32 */ } /* * vislib::sys::Thread::IsRunning */ bool vislib::sys::Thread::IsRunning(void) const { try { return (this->GetExitCode() == STILL_ACTIVE); } catch (SystemException) { return false; } } /* * vislib::sys::Thread::Join */ void vislib::sys::Thread::Join(void) { #ifdef _WIN32 if (this->handle != NULL) { if (::WaitForSingleObject(this->handle, INFINITE) == WAIT_FAILED) { throw SystemException(__FILE__, __LINE__); } } #else /* _WIN32 */ if (this->id != 0) { if (::pthread_join(this->id, NULL) != 0) { throw SystemException(__FILE__, __LINE__); } } #endif /* _WIN32 */ } /* * vislib::sys::Thread::Start */ bool vislib::sys::Thread::Start(void *userData) { if (this->IsRunning()) { /* * The thread must not be started twice at the same time as this would * leave unclosed handles. */ return false; } /* Set the user data. */ this->threadFuncParam.userData = userData; #ifdef _WIN32 /* Close possible old handle. */ if (this->handle != NULL) { ::CloseHandle(this->handle); } if ((this->handle = ::CreateThread(NULL, 0, Thread::ThreadFunc, &this->threadFuncParam, 0, &this->id)) != NULL) { return true; } else { TRACE(Trace::LEVEL_ERROR, "CreateThread() failed with error %d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } #else /* _WIN32 */ if (::pthread_create(&this->id, &this->attribs, Thread::ThreadFunc, static_cast<void *>(&this->threadFuncParam)) == 0) { this->exitCode = STILL_ACTIVE; // Mark thread as running. return true; } else { TRACE(Trace::LEVEL_ERROR, "pthread_create() failed with error %d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } #endif /* _WIN32 */ } /* * vislib::sys::Thread::Terminate */ bool vislib::sys::Thread::Terminate(const bool forceTerminate, const int exitCode) { ASSERT(exitCode != STILL_ACTIVE); // User should never set this. if (forceTerminate) { /* Force immediate termination of the thread. */ #ifdef _WIN32 if (::TerminateThread(this->handle, exitCode) == FALSE) { TRACE(Trace::LEVEL_ERROR, "TerminateThread() failed with error " "%d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } return true; #else /* _WIN32 */ if (::pthread_cancel(this->id) != 0) { TRACE(Trace::LEVEL_ERROR, "pthread_cancel() failed with error " "%d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } return true; #endif /* _WIN32 */ } else { return this->TryTerminate(true); } /* end if (forceTerminate) */ } /* * vislib::sys::Thread::TryTerminate */ bool vislib::sys::Thread::TryTerminate(const bool doWait) { if (this->runnable == NULL) { throw IllegalStateException("TryTerminate can only be used, if the " "thread is using a Runnable.", __FILE__, __LINE__); } ASSERT(this->runnable != NULL); if (this->runnable->Terminate()) { /* * Wait for thread to finish, if Runnable acknowledged and waiting was * requested. */ if (doWait) { this->Join(); } return true; } else { /* Runnable did not acknowledge. */ return false; } } #ifndef _WIN32 /* * vislib::sys::Thread::CleanupFunc */ void vislib::sys::Thread::CleanupFunc(void *param) { ASSERT(param != NULL); Thread *t = static_cast<Thread *>(param); /* * In case the thread has still an exit code of STILL_ACTIVE, set a new one * to mark the thread as finished. */ if (t->exitCode == STILL_ACTIVE) { TRACE(Trace::LEVEL_WARN, "CleanupFunc called with exit code " "STILL_ACTIVE"); t->exitCode = 0; } } #endif /* !_WIN32 */ /* * vislib::sys::Thread::ThreadFunc */ #ifdef _WIN32 DWORD WINAPI vislib::sys::Thread::ThreadFunc(void *param) { #else /* _WIN32 */ void *vislib::sys::Thread::ThreadFunc(void *param) { #endif /* _WIN32 */ ASSERT(param != NULL); int retval = 0; ThreadFuncParam *tfp = static_cast<ThreadFuncParam *>(param); Thread *t = tfp->thread; ASSERT(t != NULL); #ifndef _WIN32 pthread_cleanup_push(Thread::CleanupFunc, t); #endif /* !_WIN32 */ if (t->runnable != NULL) { retval = t->runnable->Run(tfp->userData); } else { ASSERT(t->runnableFunc != NULL); retval = t->runnableFunc(tfp->userData); } ASSERT(retval != STILL_ACTIVE); // Thread should never use STILL_ACTIVE! #ifndef _WIN32 t->exitCode = retval; pthread_cleanup_pop(1); #endif /* !_WIN32 */ TRACE(Trace::LEVEL_INFO, "Thread [%u] has exited with code %d (0x%x).\n", t->id, retval, retval); #ifdef _WIN32 return static_cast<DWORD>(retval); #else /* _WIN32 */ return reinterpret_cast<void *>(retval); #endif /* _WIN32 */ } /* * vislib::sys::Thread::Thread */ vislib::sys::Thread::Thread(const Thread& rhs) { throw UnsupportedOperationException("vislib::sys::Thread::Thread", __FILE__, __LINE__); } /* * vislib::sys::Thread::operator = */ vislib::sys::Thread& vislib::sys::Thread::operator =(const Thread& rhs) { if (this != &rhs) { throw IllegalParamException("rhs_", __FILE__, __LINE__); } return *this; } <commit_msg>Trace level changed to internal VL_ levels.<commit_after>/* * Thread.cpp 15.08.2006 (mueller) * * Copyright (C) 2006 by Universitaet Stuttgart (VIS). Alle Rechte vorbehalten. */ #include "vislib/Thread.h" #ifndef _WIN32 #include <unistd.h> #endif /* !_WIN32 */ #include "vislib/assert.h" #include "vislib/error.h" #include "vislib/IllegalParamException.h" #include "vislib/IllegalStateException.h" #include "vislib/SystemException.h" #include "vislib/Trace.h" #include "vislib/UnsupportedOperationException.h" #include "DynamicFunctionPointer.h" #include <cstdio> #include <iostream> #ifndef _WIN32 /** * Return code that marks a thread as still running. Make sure that the value * is the same as on Windows. */ #define STILL_ACTIVE (259) #endif /* !_WIN32 */ /* * vislib::sys::Thread::Sleep */ void vislib::sys::Thread::Sleep(const DWORD millis) { #ifdef _WIN32 ::Sleep(millis); #else /* _WIN32 */ if (millis >= 1000) { /* At least one second to sleep. Use ::sleep() for full seconds. */ ::sleep(millis / 1000); } ::usleep((millis % 1000) * 1000); #endif /* _WIN32 */ } /* * vislib::sys::Thread::Reschedule */ void vislib::sys::Thread::Reschedule(void) { #ifdef _WIN32 #if (_WIN32_WINNT >= 0x0400) ::SwitchToThread(); #else DynamicFunctionPointer<BOOL (*)(void)> stt("kernel32", "SwitchToThread"); if (stt.IsValid()) { stt(); } else { ::Sleep(0); } #endif #else /* _WIN32 */ if (::sched_yield() != 0) { throw SystemException(__FILE__, __LINE__); } #endif /* _WIN32 */ } /* * vislib::sys::Thread::Thread */ vislib::sys::Thread::Thread(Runnable *runnable) : id(0), runnable(runnable), runnableFunc(NULL) { #ifdef _WIN32 this->handle = NULL; #else /* _WIN32 */ ::pthread_attr_init(&this->attribs); ::pthread_attr_setscope(&this->attribs, PTHREAD_SCOPE_SYSTEM); ::pthread_attr_setdetachstate(&this->attribs, PTHREAD_CREATE_JOINABLE); this->exitCode = 0; #endif /* _WIN32 */ this->threadFuncParam.thread = this; this->threadFuncParam.userData = NULL; } /* * vislib::sys::Thread::Thread */ vislib::sys::Thread::Thread(Runnable::Function runnableFunc) : id(0), runnable(NULL), runnableFunc(runnableFunc) { #ifdef _WIN32 this->handle = NULL; #else /* _WIN32 */ ::pthread_attr_init(&this->attribs); ::pthread_attr_setscope(&this->attribs, PTHREAD_SCOPE_SYSTEM); ::pthread_attr_setdetachstate(&this->attribs, PTHREAD_CREATE_JOINABLE); this->exitCode = 0; #endif /* _WIN32 */ this->threadFuncParam.thread = this; this->threadFuncParam.userData = NULL; } /* * vislib::sys::Thread::~Thread */ vislib::sys::Thread::~Thread(void) { #ifdef _WIN32 if (this->handle != NULL) { ::CloseHandle(this->handle); } #else /* _WIIN32 */ // TODO: Must detach, iff not joined? How should we know this here? //::pthread_detach(this->id); ::pthread_attr_destroy(&this->attribs); #endif /* _WIN32 */ } /* * vislib::sys::Thread::GetExitCode */ DWORD vislib::sys::Thread::GetExitCode(void) const { #ifdef _WIN32 DWORD retval = 0; if (::GetExitCodeThread(this->handle, &retval) == FALSE) { throw SystemException(__FILE__, __LINE__); } return retval; #else /* _WIN32 */ return this->exitCode; #endif /* _WIN32 */ } /* * vislib::sys::Thread::IsRunning */ bool vislib::sys::Thread::IsRunning(void) const { try { return (this->GetExitCode() == STILL_ACTIVE); } catch (SystemException) { return false; } } /* * vislib::sys::Thread::Join */ void vislib::sys::Thread::Join(void) { #ifdef _WIN32 if (this->handle != NULL) { if (::WaitForSingleObject(this->handle, INFINITE) == WAIT_FAILED) { throw SystemException(__FILE__, __LINE__); } } #else /* _WIN32 */ if (this->id != 0) { if (::pthread_join(this->id, NULL) != 0) { throw SystemException(__FILE__, __LINE__); } } #endif /* _WIN32 */ } /* * vislib::sys::Thread::Start */ bool vislib::sys::Thread::Start(void *userData) { if (this->IsRunning()) { /* * The thread must not be started twice at the same time as this would * leave unclosed handles. */ return false; } /* Set the user data. */ this->threadFuncParam.userData = userData; #ifdef _WIN32 /* Close possible old handle. */ if (this->handle != NULL) { ::CloseHandle(this->handle); } if ((this->handle = ::CreateThread(NULL, 0, Thread::ThreadFunc, &this->threadFuncParam, 0, &this->id)) != NULL) { return true; } else { TRACE(Trace::LEVEL_VL_ERROR, "CreateThread() failed with error %d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } #else /* _WIN32 */ if (::pthread_create(&this->id, &this->attribs, Thread::ThreadFunc, static_cast<void *>(&this->threadFuncParam)) == 0) { this->exitCode = STILL_ACTIVE; // Mark thread as running. return true; } else { TRACE(Trace::LEVEL_VL_ERROR, "pthread_create() failed with error %d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } #endif /* _WIN32 */ } /* * vislib::sys::Thread::Terminate */ bool vislib::sys::Thread::Terminate(const bool forceTerminate, const int exitCode) { ASSERT(exitCode != STILL_ACTIVE); // User should never set this. if (forceTerminate) { /* Force immediate termination of the thread. */ #ifdef _WIN32 if (::TerminateThread(this->handle, exitCode) == FALSE) { TRACE(Trace::LEVEL_VL_ERROR, "TerminateThread() failed with error " "%d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } return true; #else /* _WIN32 */ if (::pthread_cancel(this->id) != 0) { TRACE(Trace::LEVEL_VL_ERROR, "pthread_cancel() failed with error " "%d.\n", ::GetLastError()); throw SystemException(__FILE__, __LINE__); } return true; #endif /* _WIN32 */ } else { return this->TryTerminate(true); } /* end if (forceTerminate) */ } /* * vislib::sys::Thread::TryTerminate */ bool vislib::sys::Thread::TryTerminate(const bool doWait) { if (this->runnable == NULL) { throw IllegalStateException("TryTerminate can only be used, if the " "thread is using a Runnable.", __FILE__, __LINE__); } ASSERT(this->runnable != NULL); if (this->runnable->Terminate()) { /* * Wait for thread to finish, if Runnable acknowledged and waiting was * requested. */ if (doWait) { this->Join(); } return true; } else { /* Runnable did not acknowledge. */ return false; } } #ifndef _WIN32 /* * vislib::sys::Thread::CleanupFunc */ void vislib::sys::Thread::CleanupFunc(void *param) { ASSERT(param != NULL); Thread *t = static_cast<Thread *>(param); /* * In case the thread has still an exit code of STILL_ACTIVE, set a new one * to mark the thread as finished. */ if (t->exitCode == STILL_ACTIVE) { TRACE(Trace::LEVEL_VL_WARN, "CleanupFunc called with exit code " "STILL_ACTIVE"); t->exitCode = 0; } } #endif /* !_WIN32 */ /* * vislib::sys::Thread::ThreadFunc */ #ifdef _WIN32 DWORD WINAPI vislib::sys::Thread::ThreadFunc(void *param) { #else /* _WIN32 */ void *vislib::sys::Thread::ThreadFunc(void *param) { #endif /* _WIN32 */ ASSERT(param != NULL); int retval = 0; ThreadFuncParam *tfp = static_cast<ThreadFuncParam *>(param); Thread *t = tfp->thread; ASSERT(t != NULL); #ifndef _WIN32 pthread_cleanup_push(Thread::CleanupFunc, t); #endif /* !_WIN32 */ if (t->runnable != NULL) { retval = t->runnable->Run(tfp->userData); } else { ASSERT(t->runnableFunc != NULL); retval = t->runnableFunc(tfp->userData); } ASSERT(retval != STILL_ACTIVE); // Thread should never use STILL_ACTIVE! #ifndef _WIN32 t->exitCode = retval; pthread_cleanup_pop(1); #endif /* !_WIN32 */ TRACE(Trace::LEVEL_VL_INFO, "Thread [%u] has exited with code %d (0x%x).\n", t->id, retval, retval); #ifdef _WIN32 return static_cast<DWORD>(retval); #else /* _WIN32 */ return reinterpret_cast<void *>(retval); #endif /* _WIN32 */ } /* * vislib::sys::Thread::Thread */ vislib::sys::Thread::Thread(const Thread& rhs) { throw UnsupportedOperationException("vislib::sys::Thread::Thread", __FILE__, __LINE__); } /* * vislib::sys::Thread::operator = */ vislib::sys::Thread& vislib::sys::Thread::operator =(const Thread& rhs) { if (this != &rhs) { throw IllegalParamException("rhs_", __FILE__, __LINE__); } return *this; } <|endoftext|>
<commit_before>#ifndef MJOLNIR_CORE_RANDOM_NUMBER_GENERATOR #define MJOLNIR_CORE_RANDOM_NUMBER_GENERATOR #include <random> #include <cstdint> namespace mjolnir { template<typename traitsT> class RandomNumberGenerator { public: using traits_type = traitsT; using real_type = typename traits_type::real_type; using coordinate_type = typename traits_type::coordinate_type; public: RandomNumberGenerator(const std::uint32_t seed) : seed_(seed), rng_(seed) {} ~RandomNumberGenerator() = default; real_type uniform_real(const real_type min, const real_type max) { return this->uni_(this->rng_) * (max - min) + min; } real_type gaussian(const real_type mean, const real_type stddev) { return this->nrm_(this->rng_) * stddev + mean; } private: const std::uint32_t seed_; std::mt19937 rng_; std::uniform_real_distribution<real_type> uni_; std::normal_distribution<real_type> nrm_; }; template<typename traitsT> inline typename RandomNumberGenerator<traitsT>::real_type RandomNumberGenerator<traitsT>::uniform_real( const real_type min, const real_type max) { return (std::uniform_real_distribution<real_type>(min, max))(rng_); } template<typename traitsT> inline typename RandomNumberGenerator<traitsT>::real_type RandomNumberGenerator<traitsT>::gaussian( const real_type mean, const real_type sigma) { return (std::normal_distribution<real_type>(mean, sigma))(rng_); } } // mjolnir #endif /*MJOLNIR_CORE_RANDOM_NUMBER_GENERATOR*/ <commit_msg>fix silly mistake; remove needless definition<commit_after>#ifndef MJOLNIR_CORE_RANDOM_NUMBER_GENERATOR #define MJOLNIR_CORE_RANDOM_NUMBER_GENERATOR #include <random> #include <cstdint> namespace mjolnir { template<typename traitsT> class RandomNumberGenerator { public: using traits_type = traitsT; using real_type = typename traits_type::real_type; using coordinate_type = typename traits_type::coordinate_type; public: RandomNumberGenerator(const std::uint32_t seed) : seed_(seed), rng_(seed) {} ~RandomNumberGenerator() = default; real_type uniform_real(const real_type min, const real_type max) { return this->uni_(this->rng_) * (max - min) + min; } real_type gaussian(const real_type mean, const real_type stddev) { return this->nrm_(this->rng_) * stddev + mean; } private: const std::uint32_t seed_; std::mt19937 rng_; std::uniform_real_distribution<real_type> uni_; std::normal_distribution<real_type> nrm_; }; } // mjolnir #endif /*MJOLNIR_CORE_RANDOM_NUMBER_GENERATOR*/ <|endoftext|>
<commit_before>#include "config.h" #include "yapp.h" #include "aclock.h" const char *ApplicationName = "iceclock"; int main(int argc, char **argv) { YApplication app(&argc, &argv); YClock *clock = new YClock(); clock->show(); return app.mainLoop(); } // vim: set sw=4 ts=4 et: <commit_msg>make it compile.<commit_after>#include "config.h" #include "yapp.h" #include "aclock.h" const char *ApplicationName = "iceclock"; int main(int argc, char **argv) { YApplication app(&argc, &argv); YClock *clock = new YClock(0); clock->show(); return app.mainLoop(); } // vim: set sw=4 ts=4 et: <|endoftext|>
<commit_before>#include <algorithm> #include <cstring> #include <iostream> int blocks[26]; int memo[1000001]; int minimum_blocks(int m, int n) { if (memo[m]) return memo[m]; int i; for (i = 0; i < n; i++) { if (blocks[i] == m) { memo[m] = 1; return memo[m]; } } int min_solution = m; for (i = 0; i < n; i++) { if (blocks[i] > m) break; min_solution = std::min( min_solution, minimum_blocks(m - blocks[i], n)); } memo[m] = 1 + min_solution; return memo[m]; } int main() { int i, t, n, m; std::cin >> t; while (t--) { std::cin >> n >> m; memset(blocks, 0, sizeof(blocks)); memset(memo, 0, sizeof(memo)); for (i = 0; i < n; i++) std::cin >> blocks[i]; std::sort(blocks, blocks + n); std::cout << minimum_blocks(m, n) << std::endl; } return 0; } <commit_msg>Solves with dynamic programing.<commit_after>#include <algorithm> #include <cstring> #include <iostream> #define INFINITY 1000001 int blocks[26]; int minimum_blocks(long long m, int n) { int j; long long result[m + 1], i; result[0] = 0; for (i = 1; i <= m; i++) { result[i] = INFINITY; } for (j = 0; j < n; j++) { for (i = blocks[j]; i <= m; i++) { result[i] = std::min(result[i], result[i - blocks[j]] + 1); } } return result[m]; } int main() { int i, t, n; long long m; std::cin >> t; while (t--) { std::cin >> n >> m; memset(blocks, 0, sizeof(blocks)); for (i = 0; i < n; i++) std::cin >> blocks[i]; std::sort(blocks, blocks + n); std::cout << minimum_blocks(m, n) << std::endl; } return 0; } <|endoftext|>
<commit_before>// these tests can only be compiled and executed with availability of // MPI #ifdef STAN_MPI #include <stan/math/prim/arr.hpp> #include <test/unit/math/prim/mat/functor/mpi_test_env.hpp> #include <iostream> #include <vector> MPI_TEST(mpi_cluster, chunk_mapping) { if (rank != 0) return; std::vector<int> small_load = stan::math::mpi_map_chunks(world_size - 1, 1); EXPECT_EQ(world_size, small_load.size()); if (world_size > 1) EXPECT_EQ(0, small_load[0]); for (std::size_t i = 1; i < world_size; ++i) EXPECT_EQ(1, small_load[i]); std::vector<int> med_load = stan::math::mpi_map_chunks(world_size + 1, 2); EXPECT_EQ(world_size, med_load.size()); if (world_size > 1) { EXPECT_EQ(2, med_load[0]); EXPECT_EQ(4, med_load[1]); for (std::size_t i = 2; i < world_size; ++i) EXPECT_EQ(2, med_load[i]); } else { EXPECT_EQ(4, med_load[0]); } } MPI_TEST(mpi_cluster, listen_state) { if (rank != 0) return; EXPECT_TRUE(stan::math::mpi_cluster::is_listening()); } /** * simple distributed MPI apply (uses mpi_command implicitly) which * performs the basic communications which we need * (broadcast/scatter/gather). */ struct make_secret { static void distributed_apply() { boost::mpi::communicator world; double common; boost::mpi::broadcast(world, common, 0); double worker_value; boost::mpi::scatter(world, worker_value, 0); double worker_secret = common * worker_value; std::vector<double> secrets; boost::mpi::gather(world, worker_secret, secrets, 0); } }; // register worker command STAN_REGISTER_MPI_DISTRIBUTED_APPLY(make_secret) MPI_TEST(mpi_cluster, communication_apply) { if (rank != 0) return; boost::mpi::communicator world; std::unique_lock<std::mutex> cluster_lock; EXPECT_NO_THROW((cluster_lock = stan::math::mpi_broadcast_command< stan::math::mpi_distributed_apply<make_secret>>())); EXPECT_TRUE(cluster_lock.owns_lock()); // this one will fail std::unique_lock<std::mutex> cluster_lock_fail; EXPECT_THROW((cluster_lock_fail = stan::math::mpi_broadcast_command< stan::math::mpi_distributed_apply<make_secret>>()), stan::math::mpi_is_in_use); EXPECT_FALSE(cluster_lock_fail.owns_lock()); double common = 3.14; boost::mpi::broadcast(world, common, 0); std::vector<double> msgs(world_size, 0.0); for (std::size_t i = 0; i < world_size; ++i) msgs[i] = i; double root_value = -1; boost::mpi::scatter(world, msgs, root_value, 0); EXPECT_DOUBLE_EQ(msgs[0], root_value); double root_secret = common * root_value; std::vector<double> secrets(world_size); boost::mpi::gather(world, root_secret, secrets, 0); for (std::size_t i = 0; i < world_size; ++i) EXPECT_DOUBLE_EQ(common * msgs[i], secrets[i]); } // example using command which is serialized (which adds extra MPI // overhead) struct shared_secret : public stan::math::mpi_command { shared_secret() {} shared_secret(double common) : common_(common) {} friend class boost::serialization::access; template <class Archive> void serialize(Archive& ar, const unsigned int version) { ar& BOOST_SERIALIZATION_BASE_OBJECT_NVP(stan::math::mpi_command); ar& common_; } void run() const { boost::mpi::communicator world; double worker_value; boost::mpi::scatter(world, worker_value, 0); double worker_secret = common_ * worker_value; std::vector<double> secrets; boost::mpi::gather(world, worker_secret, secrets, 0); } private: double common_; }; // register worker command STAN_REGISTER_MPI_COMMAND(shared_secret) MPI_TEST(mpi_cluster, communication_command) { if (rank != 0) return; boost::mpi::communicator world; const double common = 2 * 3.14; boost::shared_ptr<stan::math::mpi_command> command(new shared_secret(common)); std::unique_lock<std::mutex> cluster_lock; EXPECT_NO_THROW((cluster_lock = stan::math::mpi_broadcast_command(command))); EXPECT_TRUE(cluster_lock.owns_lock()); // this one will fail std::unique_lock<std::mutex> cluster_lock_fail; EXPECT_THROW((cluster_lock_fail = stan::math::mpi_broadcast_command(command)), stan::math::mpi_is_in_use); EXPECT_FALSE(cluster_lock_fail.owns_lock()); std::vector<double> msgs(world_size, 0.0); for (std::size_t i = 0; i < world_size; ++i) msgs[i] = i; double root_value = -1; boost::mpi::scatter(world, msgs, root_value, 0); EXPECT_DOUBLE_EQ(msgs[0], root_value); double root_secret = common * root_value; std::vector<double> secrets(world_size); boost::mpi::gather(world, root_secret, secrets, 0); for (std::size_t i = 0; i < world_size; ++i) EXPECT_DOUBLE_EQ(common * msgs[i], secrets[i]); } #endif <commit_msg>cpplint<commit_after>// these tests can only be compiled and executed with availability of // MPI #ifdef STAN_MPI #include <stan/math/prim/arr.hpp> #include <test/unit/math/prim/mat/functor/mpi_test_env.hpp> #include <iostream> #include <vector> MPI_TEST(mpi_cluster, chunk_mapping) { if (rank != 0) return; std::vector<int> small_load = stan::math::mpi_map_chunks(world_size - 1, 1); EXPECT_EQ(world_size, small_load.size()); if (world_size > 1) EXPECT_EQ(0, small_load[0]); for (std::size_t i = 1; i < world_size; ++i) EXPECT_EQ(1, small_load[i]); std::vector<int> med_load = stan::math::mpi_map_chunks(world_size + 1, 2); EXPECT_EQ(world_size, med_load.size()); if (world_size > 1) { EXPECT_EQ(2, med_load[0]); EXPECT_EQ(4, med_load[1]); for (std::size_t i = 2; i < world_size; ++i) EXPECT_EQ(2, med_load[i]); } else { EXPECT_EQ(4, med_load[0]); } } MPI_TEST(mpi_cluster, listen_state) { if (rank != 0) return; EXPECT_TRUE(stan::math::mpi_cluster::is_listening()); } /** * simple distributed MPI apply (uses mpi_command implicitly) which * performs the basic communications which we need * (broadcast/scatter/gather). */ struct make_secret { static void distributed_apply() { boost::mpi::communicator world; double common; boost::mpi::broadcast(world, common, 0); double worker_value; boost::mpi::scatter(world, worker_value, 0); double worker_secret = common * worker_value; std::vector<double> secrets; boost::mpi::gather(world, worker_secret, secrets, 0); } }; // register worker command STAN_REGISTER_MPI_DISTRIBUTED_APPLY(make_secret) MPI_TEST(mpi_cluster, communication_apply) { if (rank != 0) return; boost::mpi::communicator world; std::unique_lock<std::mutex> cluster_lock; EXPECT_NO_THROW((cluster_lock = stan::math::mpi_broadcast_command< stan::math::mpi_distributed_apply<make_secret>>())); EXPECT_TRUE(cluster_lock.owns_lock()); // this one will fail std::unique_lock<std::mutex> cluster_lock_fail; EXPECT_THROW((cluster_lock_fail = stan::math::mpi_broadcast_command< stan::math::mpi_distributed_apply<make_secret>>()), stan::math::mpi_is_in_use); EXPECT_FALSE(cluster_lock_fail.owns_lock()); double common = 3.14; boost::mpi::broadcast(world, common, 0); std::vector<double> msgs(world_size, 0.0); for (std::size_t i = 0; i < world_size; ++i) msgs[i] = i; double root_value = -1; boost::mpi::scatter(world, msgs, root_value, 0); EXPECT_DOUBLE_EQ(msgs[0], root_value); double root_secret = common * root_value; std::vector<double> secrets(world_size); boost::mpi::gather(world, root_secret, secrets, 0); for (std::size_t i = 0; i < world_size; ++i) EXPECT_DOUBLE_EQ(common * msgs[i], secrets[i]); } // example using command which is serialized (which adds extra MPI // overhead) struct shared_secret : public stan::math::mpi_command { shared_secret() {} explicit shared_secret(double common) : common_(common) {} friend class boost::serialization::access; template <class Archive> void serialize(Archive& ar, const unsigned int version) { ar& BOOST_SERIALIZATION_BASE_OBJECT_NVP(stan::math::mpi_command); ar& common_; } void run() const { boost::mpi::communicator world; double worker_value; boost::mpi::scatter(world, worker_value, 0); double worker_secret = common_ * worker_value; std::vector<double> secrets; boost::mpi::gather(world, worker_secret, secrets, 0); } private: double common_; }; // register worker command STAN_REGISTER_MPI_COMMAND(shared_secret) MPI_TEST(mpi_cluster, communication_command) { if (rank != 0) return; boost::mpi::communicator world; const double common = 2 * 3.14; boost::shared_ptr<stan::math::mpi_command> command(new shared_secret(common)); std::unique_lock<std::mutex> cluster_lock; EXPECT_NO_THROW((cluster_lock = stan::math::mpi_broadcast_command(command))); EXPECT_TRUE(cluster_lock.owns_lock()); // this one will fail std::unique_lock<std::mutex> cluster_lock_fail; EXPECT_THROW((cluster_lock_fail = stan::math::mpi_broadcast_command(command)), stan::math::mpi_is_in_use); EXPECT_FALSE(cluster_lock_fail.owns_lock()); std::vector<double> msgs(world_size, 0.0); for (std::size_t i = 0; i < world_size; ++i) msgs[i] = i; double root_value = -1; boost::mpi::scatter(world, msgs, root_value, 0); EXPECT_DOUBLE_EQ(msgs[0], root_value); double root_secret = common * root_value; std::vector<double> secrets(world_size); boost::mpi::gather(world, root_secret, secrets, 0); for (std::size_t i = 0; i < world_size; ++i) EXPECT_DOUBLE_EQ(common * msgs[i], secrets[i]); } #endif <|endoftext|>
<commit_before>/** @file Conversions.cpp @author Philip Abbet Implementation of the scripting-related conversion functions for the Athena-Core module */ #include <Athena-Scripting/Conversions.h> #include <Athena-Scripting/ScriptingManager.h> #include <Athena-Scripting/Utils.h> #include <Athena-Core/Utils/PropertiesList.h> #include <Athena-Core/Utils/Describable.h> using namespace Athena::Signals; using namespace Athena::Scripting; using namespace Athena::Utils; using namespace v8; Signal* Athena::Signals::fromJSSignal(Handle<Value> value) { if (value->IsObject()) { Signal* pSignal = 0; GetObjectPtr(value, &pSignal); return pSignal; } return 0; } //----------------------------------------------------------------------- Handle<Object> Athena::Signals::createJSSignal() { HandleScope handle_scope; Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate( "Athena.Signals.Signal"); Handle<Object> jsSignal = func->GetFunction()->NewInstance(); return handle_scope.Close(jsSignal); } //----------------------------------------------------------------------- Handle<Value> Athena::Signals::toJavaScript(Signal* pSignal) { // Assertions assert(pSignal); HandleScope handle_scope; Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate( "Athena.Signals.Signal"); Handle<Value> argv[1]; argv[0] = External::Wrap(pSignal); Handle<Object> jsSignal = func->GetFunction()->NewInstance(1, argv); return handle_scope.Close(jsSignal); } //----------------------------------------------------------------------- SignalsList* Athena::Signals::fromJSSignalsList(Handle<Value> value) { if (value->IsObject()) { SignalsList* pList = 0; GetObjectPtr(value, &pList); return pList; } return 0; } //----------------------------------------------------------------------- Handle<Object> Athena::Signals::createJSSignalsList() { HandleScope handle_scope; Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate( "Athena.Signals.SignalsList"); Handle<Object> jsList = func->GetFunction()->NewInstance(); return handle_scope.Close(jsList); } //----------------------------------------------------------------------- Handle<Value> Athena::Signals::toJavaScript(SignalsList* pList) { // Assertions assert(pList); HandleScope handle_scope; Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate( "Athena.Signals.SignalsList"); Handle<Value> argv[1]; argv[0] = External::Wrap(pList); Handle<Object> jsList = func->GetFunction()->NewInstance(1, argv); return handle_scope.Close(jsList); } //----------------------------------------------------------------------- Describable* Athena::Utils::fromJSDescribable(Handle<Value> value) { if (value->IsObject()) { Describable* pDescribable = 0; GetObjectPtr(value, &pDescribable); return pDescribable; } return 0; } //----------------------------------------------------------------------- Handle<Object> Athena::Utils::createJSDescribable() { HandleScope handle_scope; Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate( "Athena.Utils.Describable"); Handle<Object> jsDescribable = func->GetFunction()->NewInstance(); return handle_scope.Close(jsDescribable); } //----------------------------------------------------------------------- Handle<Value> Athena::Utils::toJavaScript(Describable* pDescribable) { // Assertions assert(pDescribable); HandleScope handle_scope; Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate( "Athena.Utils.Describable"); Handle<Value> argv[1]; argv[0] = External::Wrap(pDescribable); Handle<Object> jsDescribable = func->GetFunction()->NewInstance(1, argv); return handle_scope.Close(jsDescribable); } //----------------------------------------------------------------------- PropertiesList* Athena::Utils::fromJSPropertiesList(Handle<Value> value) { if (value->IsObject()) { PropertiesList* pList = 0; GetObjectPtr(value, &pList); return pList; } return 0; } //----------------------------------------------------------------------- Handle<Object> Athena::Utils::createJSPropertiesList() { HandleScope handle_scope; Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate( "Athena.Utils.PropertiesList"); Handle<Object> jsList = func->GetFunction()->NewInstance(); return handle_scope.Close(jsList); } //----------------------------------------------------------------------- Handle<Value> Athena::Utils::toJavaScript(PropertiesList* pList) { // Assertions assert(pList); HandleScope handle_scope; Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate( "Athena.Utils.PropertiesList"); Handle<Value> argv[1]; argv[0] = External::Wrap(pList); Handle<Object> jsList = func->GetFunction()->NewInstance(1, argv); return handle_scope.Close(jsList); } <commit_msg>[Scripting] Bugfix: Bad handling of externals<commit_after>/** @file Conversions.cpp @author Philip Abbet Implementation of the scripting-related conversion functions for the Athena-Core module */ #include <Athena-Scripting/Conversions.h> #include <Athena-Scripting/ScriptingManager.h> #include <Athena-Scripting/Utils.h> #include <Athena-Core/Utils/PropertiesList.h> #include <Athena-Core/Utils/Describable.h> using namespace Athena::Signals; using namespace Athena::Scripting; using namespace Athena::Utils; using namespace v8; Signal* Athena::Signals::fromJSSignal(Handle<Value> value) { if (value->IsObject()) { Signal* pSignal = 0; GetObjectPtr(value, &pSignal); return pSignal; } return 0; } //----------------------------------------------------------------------- Handle<Object> Athena::Signals::createJSSignal() { HandleScope handle_scope; Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate( "Athena.Signals.Signal"); Handle<Object> jsSignal = func->GetFunction()->NewInstance(); return handle_scope.Close(jsSignal); } //----------------------------------------------------------------------- Handle<Value> Athena::Signals::toJavaScript(Signal* pSignal) { // Assertions assert(pSignal); HandleScope handle_scope; Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate( "Athena.Signals.Signal"); Handle<Value> argv[1]; argv[0] = External::New(pSignal); Handle<Object> jsSignal = func->GetFunction()->NewInstance(1, argv); return handle_scope.Close(jsSignal); } //----------------------------------------------------------------------- SignalsList* Athena::Signals::fromJSSignalsList(Handle<Value> value) { if (value->IsObject()) { SignalsList* pList = 0; GetObjectPtr(value, &pList); return pList; } return 0; } //----------------------------------------------------------------------- Handle<Object> Athena::Signals::createJSSignalsList() { HandleScope handle_scope; Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate( "Athena.Signals.SignalsList"); Handle<Object> jsList = func->GetFunction()->NewInstance(); return handle_scope.Close(jsList); } //----------------------------------------------------------------------- Handle<Value> Athena::Signals::toJavaScript(SignalsList* pList) { // Assertions assert(pList); HandleScope handle_scope; Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate( "Athena.Signals.SignalsList"); Handle<Value> argv[1]; argv[0] = External::New(pList); Handle<Object> jsList = func->GetFunction()->NewInstance(1, argv); return handle_scope.Close(jsList); } //----------------------------------------------------------------------- Describable* Athena::Utils::fromJSDescribable(Handle<Value> value) { if (value->IsObject()) { Describable* pDescribable = 0; GetObjectPtr(value, &pDescribable); return pDescribable; } return 0; } //----------------------------------------------------------------------- Handle<Object> Athena::Utils::createJSDescribable() { HandleScope handle_scope; Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate( "Athena.Utils.Describable"); Handle<Object> jsDescribable = func->GetFunction()->NewInstance(); return handle_scope.Close(jsDescribable); } //----------------------------------------------------------------------- Handle<Value> Athena::Utils::toJavaScript(Describable* pDescribable) { // Assertions assert(pDescribable); HandleScope handle_scope; Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate( "Athena.Utils.Describable"); Handle<Value> argv[1]; argv[0] = External::New(pDescribable); Handle<Object> jsDescribable = func->GetFunction()->NewInstance(1, argv); return handle_scope.Close(jsDescribable); } //----------------------------------------------------------------------- PropertiesList* Athena::Utils::fromJSPropertiesList(Handle<Value> value) { if (value->IsObject()) { PropertiesList* pList = 0; GetObjectPtr(value, &pList); return pList; } return 0; } //----------------------------------------------------------------------- Handle<Object> Athena::Utils::createJSPropertiesList() { HandleScope handle_scope; Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate( "Athena.Utils.PropertiesList"); Handle<Object> jsList = func->GetFunction()->NewInstance(); return handle_scope.Close(jsList); } //----------------------------------------------------------------------- Handle<Value> Athena::Utils::toJavaScript(PropertiesList* pList) { // Assertions assert(pList); HandleScope handle_scope; Handle<FunctionTemplate> func = ScriptingManager::getSingletonPtr()->getClassTemplate( "Athena.Utils.PropertiesList"); Handle<Value> argv[1]; argv[0] = External::New(pList); printf("%d\n", argv[0]->IsExternal()); Handle<Object> jsList = func->GetFunction()->NewInstance(1, argv); return handle_scope.Close(jsList); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: types.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 04:01:08 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INCLUDED_SHARABLE_BASETYPES_HXX #define INCLUDED_SHARABLE_BASETYPES_HXX #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif //----------------------------------------------------------------------------- namespace rtl { class OUString; } //----------------------------------------------------------------------------- namespace configmgr { //----------------------------------------------------------------------------- namespace memory { class Allocator; class Accessor; } //----------------------------------------------------------------------------- namespace sharable { //----------------------------------------------------------------------------- // some base types typedef sal_uInt32 Address; // points to absolute location in memory segment typedef sal_uInt16 Offset; // Offset relative to 'this' in array of nodes typedef sal_uInt8 Byte; // some derived types typedef Address Name; // points to counted sequence of char (7-bit ASCII) (!?) typedef Address String; // points to counted sequence of sal_Unicode typedef Address List; // singly linked intrusive, used for set elements typedef Address Vector; // points to counted sequence of some type //----------------------------------------------------------------------------- // for now Name == String typedef sal_Unicode NameChar; Name allocName(memory::Allocator const& _anAllocator, ::rtl::OUString const & _sString); // Name copyName(memory::Allocator const& _anAllocator, Name _aName); void freeName(memory::Allocator const& _anAllocator, Name _aName); ::rtl::OUString readName(memory::Accessor const& _anAccessor, Name _aName); NameChar const * accessName(memory::Accessor const& _anAccessor, Name _aName); //----------------------------------------------------------------------------- typedef sal_Unicode StringChar; String allocString(memory::Allocator const& _anAllocator, ::rtl::OUString const & _sString); // String copyString(memory::Allocator const& _anAllocator, String _aString); void freeString(memory::Allocator const& _anAllocator, String _aString); ::rtl::OUString readString(memory::Accessor const& _anAccessor, String _aString); StringChar const * accessString(memory::Accessor const& _anAccessor, String _aString); //----------------------------------------------------------------------------- } //----------------------------------------------------------------------------- } #endif // INCLUDED_SHARABLE_BASETYPES_HXX <commit_msg>INTEGRATION: CWS pj43 (1.2.18); FILE MERGED 2005/12/05 14:00:58 kendy 1.2.18.1: #i33644# "A less simple heap manager is needed": behave better on 64bit platforms.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: types.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2005-12-28 17:31:06 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INCLUDED_SHARABLE_BASETYPES_HXX #define INCLUDED_SHARABLE_BASETYPES_HXX #ifndef CONFIGMGR_MEMORYMODEL_HXX #include "memorymodel.hxx" #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif //----------------------------------------------------------------------------- namespace rtl { class OUString; } //----------------------------------------------------------------------------- namespace configmgr { //----------------------------------------------------------------------------- namespace memory { class Allocator; class Accessor; } //----------------------------------------------------------------------------- namespace sharable { //----------------------------------------------------------------------------- // some base types typedef memory::Address Address; // points to absolute location in memory segment typedef memory::HeapSize HeapSize; // size of memory block within heap typedef sal_uInt16 Offset; // Offset relative to 'this' in array of nodes typedef sal_uInt8 Byte; // some derived types typedef Address Name; // points to counted sequence of char (7-bit ASCII) (!?) typedef Address String; // points to counted sequence of sal_Unicode typedef Address List; // singly linked intrusive, used for set elements typedef Address Vector; // points to counted sequence of some type //----------------------------------------------------------------------------- // for now Name == String typedef sal_Unicode NameChar; Name allocName(memory::Allocator const& _anAllocator, ::rtl::OUString const & _sString); // Name copyName(memory::Allocator const& _anAllocator, Name _aName); void freeName(memory::Allocator const& _anAllocator, Name _aName); ::rtl::OUString readName(memory::Accessor const& _anAccessor, Name _aName); NameChar const * accessName(memory::Accessor const& _anAccessor, Name _aName); //----------------------------------------------------------------------------- typedef sal_Unicode StringChar; String allocString(memory::Allocator const& _anAllocator, ::rtl::OUString const & _sString); // String copyString(memory::Allocator const& _anAllocator, String _aString); void freeString(memory::Allocator const& _anAllocator, String _aString); ::rtl::OUString readString(memory::Accessor const& _anAccessor, String _aString); StringChar const * accessString(memory::Accessor const& _anAccessor, String _aString); //----------------------------------------------------------------------------- } //----------------------------------------------------------------------------- } #endif // INCLUDED_SHARABLE_BASETYPES_HXX <|endoftext|>
<commit_before>#include <fstream> #include <unordered_map> #include <string> #include <sstream> #include <unordered_map> #include<iostream> using namespace std; int main (int argc, char* argv[]) { // parameters if(argc != 3) { return 1; } const char* inputFile = argv[1]; const char* outputMem = argv[2]; cout << "running..." << endl; ifstream infile(inputFile); ofstream outfile(outputMem); long id, size, t=0, simpleId=0; unordered_map<long,long> dSimpleId; const char row_delim = '\n'; const char field_delim = '\t'; const char xcache_delim = ' '; string row; getline(infile, row, row_delim); for (; getline(infile, row, row_delim); ) { // parse row istringstream ss(row); string field; getline(ss, field, field_delim); // get ID if(field.empty()) { cerr << "empty id " << row << endl; continue; } stringstream fieldstream( field ); fieldstream >> id; int i; field.clear(); for (i=2; i<=4; i++) getline(ss, field, field_delim); // get size if(field.empty()) { cerr << "empty size " << row << endl; continue; } stringstream fieldstream2( field ); fieldstream2 >> size; // get cache id for (; i<=6; i++) getline(ss, field, field_delim); istringstream xcache(field); for (int j=1; j<=7; j++) { field.clear(); getline(xcache, field, xcache_delim); } if(field.empty()) { // cerr << "empty xcache " << row << endl; continue; } // match cp4006 if(field.compare("cp4006") != 0) { continue; } // cout << id << " " << size << endl; if (size <= 1) continue; if(dSimpleId.count(id)==0) dSimpleId[id]=simpleId++; t++; outfile << t << " " << dSimpleId[id] << " " << size << endl; } infile.close(); cout << "rewrote " << t << " requests" << endl; return 0; } <commit_msg>code cleanup<commit_after>#include <fstream> #include <string> #include <sstream> #include <unordered_map> #include<iostream> using namespace std; int main (int argc, char* argv[]) { // parameters if(argc != 3) { return 1; } const char* inputFile = argv[1]; const char* outputMem = argv[2]; cout << "running..." << endl; ifstream infile(inputFile); ofstream outfile(outputMem); long id, size, t=0, simpleId=0; unordered_map<long,long> dSimpleId; const char row_delim = '\n'; const char field_delim = '\t'; const char xcache_delim = ' '; string row; getline(infile, row, row_delim); for (; getline(infile, row, row_delim); ) { // parse row istringstream ss(row); string field; getline(ss, field, field_delim); // get ID if(field.empty()) { cerr << "empty id " << row << endl; continue; } stringstream fieldstream( field ); fieldstream >> id; int i; field.clear(); for (i=2; i<=4; i++) getline(ss, field, field_delim); // get size if(field.empty()) { cerr << "empty size " << row << endl; continue; } stringstream fieldstream2( field ); fieldstream2 >> size; // get cache id for (; i<=6; i++) getline(ss, field, field_delim); istringstream xcache(field); for (int j=1; j<=7; j++) { field.clear(); getline(xcache, field, xcache_delim); } if(field.empty()) { // cerr << "empty xcache " << row << endl; continue; } // match cp4006 if(field.compare("cp4006") != 0) { continue; } // cout << id << " " << size << endl; if (size <= 1) continue; if(dSimpleId.count(id)==0) dSimpleId[id]=simpleId++; t++; outfile << t << " " << dSimpleId[id] << " " << size << endl; } infile.close(); cout << "rewrote " << t << " requests" << endl; return 0; } <|endoftext|>
<commit_before>#include "Convolution.hpp" #include "mlo_internal.hpp" mlopenConvolutionDescriptor::mlopenConvolutionDescriptor() : _pad_h(0), _pad_w(0), _u(1), _v(1), _upscalex(0), _upscaley(0) { printf("In convolution Ctor\n"); _mode = mlopenConvolution; } mlopenStatus_t mlopenConvolutionDescriptor::GetForwardOutputDim(const mlopenTensorDescriptor_t inputTensorDesc, const mlopenTensorDescriptor_t filterDesc, int *n, int *c, int *h, int *w) { printf("To be implemented (GetForwardOutputDim)\n"); return mlopenStatusSuccess; } mlopenStatus_t mlopenConvolutionDescriptor::FindConvFwdAlgorithm(mlopenHandle_t handle, const mlopenTensorDescriptor_t xDesc, const void *x, const mlopenTensorDescriptor_t wDesc, const void *w, const mlopenTensorDescriptor_t yDesc, const void *y, const int requestAlgoCount, int *returnedAlgoCount, mlopenConvAlgoPerf_t *perfResults, mlopenConvPreference_t preference, void *workSpace, size_t workSpaceSize) { printf("To be implemented (FindConvFwdAlgo) \n"); #if 0 if(handle == nullptr) { return mlopenStatusBadParm; } if(xDesc == nullptr || wDesc == nullptr || yDesc == nullptr) { return mlopenStatusBadParm; } if(x == nullptr || w == nullptr || y == nullptr) { return mlopenStatusBadParm; } if(returnedAlgoCount == nullptr || perfResults == nullptr) { return mlopenStatusBadParm; } if(requestAlgoCount < 1) { return mlopenStatusBadParm; } #endif // Generate kernels if OpenCL // Compile, cache kernels, etc. // Launch all kernels and store the perf, workspace limits, etc. mlo_construct_direct2D construct_params(1); // forward, no bias { construct_params.setTimerIter(100); // HOW TO DEFINE??? construct_params.doSearch(false); // construct_params.saveSearchRequest(true); // TO DO WHERE IS THE PATH ? std::string kernel_path = "../src"; construct_params.setKernelPath(kernel_path); std::string generic_comp_otions = std::string(" -I ") + kernel_path + " "; // if (debug) { generic_comp_otions += std::string(" -cl-std=CL2.0 "); } construct_params.setGeneralCompOptions(generic_comp_otions); mlopenStream_t queue; handle->GetStream(&queue); construct_params.setStream(queue); int nOut; int cOut; int hOut; int wOut; int nOutStride; int cOutStride; int hOutStride; int wOutStride; yDesc->Get4Dims(&nOut, &cOut, &hOut, &wOut); yDesc->Get4Strides(&nOutStride, &cOutStride, &hOutStride, &wOutStride); construct_params.setOutputDescr( "NCHW", "FP32", nOut, cOut, hOut, wOut, nOutStride, cOutStride, hOutStride, wOutStride); int nIn; int cIn; int hIn; int wIn; int nInStride; int cInStride; int hInStride; int wInStride; xDesc->Get4Dims(&nIn, &cIn, &hIn, &wIn); yDesc->Get4Strides(&nInStride, &cInStride, &hInStride, &wInStride); construct_params.setInputDescr( "NCHW", "FP32", nIn, cIn, hIn, wIn, nInStride, cInStride, hInStride, wInStride); int nWei; int cWei; int hWei; int wWei; int nWeiStride; int cWeiStride; int hWeiStride; int wWeiStride; wDesc->Get4Dims(&nWei, &cWei, &hWei, &wWei); wDesc->Get4Strides(&nWeiStride, &cWeiStride, &hWeiStride, &wWeiStride); construct_params.setWeightsDescr( "NCHW", "FP32", nWei, cWei, hWei, wWei, nWeiStride, cWeiStride, hWeiStride, wWeiStride ); construct_params.setConvDescr(_pad_h, _pad_w, _u, _v, _upscalex, _upscaley); construct_params.mloConstructDirect2D(); } std::string program_name = std::string("../src/") + construct_params.getKernelFile(); //"../src/Hello.cl"; // CL kernel filename std::string kernel_name = construct_params.getKernelFile(); // "hello_world_kernel"; // kernel name std::string parms = construct_params.getCompilerOptions(); // kernel parameters // Get the queue associated with this handle mlopenStream_t queue; handle->GetStream(&queue); // Compile the kernel if not aleady compiled OCLKernel obj = KernelCache::get(queue, program_name, kernel_name); cl_int status; std::string kernName; obj.GetKernelName(kernName); printf("kname: %s\n", kernName.c_str()); #if 0 // Test to see if we can launch the kernel and get the results back float *a = new float[1024]; float *b = new float[1024]; float *c = new float[1024]; for(int i = 0; i < 1024; i++) { a[i] = 1.0; b[i] = 7.0; c[i] = 0.0; } int sz = 1024; cl_context ctx; clGetCommandQueueInfo(queue, CL_QUEUE_CONTEXT, sizeof(cl_context), &ctx, NULL); cl_mem adev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz,NULL, &status); if(status != CL_SUCCESS) { printf("error %d\n", status); } cl_mem bdev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz,NULL, NULL); cl_mem cdev = clCreateBuffer(ctx, CL_MEM_READ_WRITE, 4*sz,NULL, NULL); status = clEnqueueWriteBuffer(queue, adev, CL_TRUE, 0, 4*sz, a, 0, NULL, NULL); status |= clEnqueueWriteBuffer(queue, bdev, CL_TRUE, 0, 4*sz, b, 0, NULL, NULL); status |= clEnqueueWriteBuffer(queue, cdev, CL_TRUE, 0, 4*sz, c, 0, NULL, NULL); // Set kernel arguments // Use proper arguments //obj.SetArgs(0, adev, bdev, cdev, sz); size_t gd = 1024; size_t ld = 256; // Run the kernel obj.run(queue, 1, 0, gd, ld); clFinish(queue); #endif // Test #if 0 // Read results back clEnqueueReadBuffer(queue, cdev, CL_TRUE, 0, 4*sz, c, 0, NULL, NULL); float sum = 0.0; for(int i = 0; i < 1024; i++) { b[i] = 6; sum += c[i]; } printf("\nsum %f\n, ", sum); sum = 0.0; status |= clEnqueueWriteBuffer(queue, bdev, CL_TRUE, 0, 4*sz, b, 0, NULL, NULL); getchar(); #endif //Results return mlopenStatusSuccess; } mlopenStatus_t mlopenConvolutionDescriptor::ConvolutionForward(mlopenHandle_t handle, const void *alpha, const mlopenTensorDescriptor_t xDesc, const void *x, const mlopenTensorDescriptor_t wDesc, const void *w, mlopenConvFwdAlgorithm_t algo, const void *beta, const mlopenTensorDescriptor_t yDesc, void *y) { printf("To be implemented (ConvolutionForward) \n"); if(handle == nullptr) { return mlopenStatusBadParm; } if(xDesc == nullptr || wDesc == nullptr || yDesc == nullptr) { return mlopenStatusBadParm; } if(x == nullptr || w == nullptr || y == nullptr) { return mlopenStatusBadParm; } if(xDesc->_CheckTensorDims(yDesc) != mlopenStatusSuccess || xDesc->_CheckTensorDims(wDesc) != mlopenStatusSuccess) { return mlopenStatusBadParm; } if(xDesc->_CheckTensorDataTypes(yDesc) != mlopenStatusSuccess || xDesc->_CheckTensorDataTypes(wDesc) != mlopenStatusSuccess) { return mlopenStatusBadParm; } if(xDesc->_dimA[0] != wDesc->_dimA[0]) { return mlopenStatusBadParm; } if(xDesc->_dims < 3) { return mlopenStatusBadParm; } std::string program_name; // CL kernel filename std::string kernel_name; // kernel name std::string parms; // kernel parameters mlopenStream_t queue; handle->GetStream(&queue); #if MLOpen_BACKEND_OPENCL // OCLKernel kernel = KernelCache::get(queue, program_name, kernel_name); #endif return mlopenStatusSuccess; } <commit_msg>minor Conv fix<commit_after>#include "Convolution.hpp" #include "mlo_internal.hpp" mlopenConvolutionDescriptor::mlopenConvolutionDescriptor() : _pad_h(0), _pad_w(0), _u(1), _v(1), _upscalex(0), _upscaley(0) { printf("In convolution Ctor\n"); _mode = mlopenConvolution; } mlopenStatus_t mlopenConvolutionDescriptor::GetForwardOutputDim(const mlopenTensorDescriptor_t inputTensorDesc, const mlopenTensorDescriptor_t filterDesc, int *n, int *c, int *h, int *w) { printf("To be implemented (GetForwardOutputDim)\n"); return mlopenStatusSuccess; } mlopenStatus_t mlopenConvolutionDescriptor::FindConvFwdAlgorithm(mlopenHandle_t handle, const mlopenTensorDescriptor_t xDesc, const void *x, const mlopenTensorDescriptor_t wDesc, const void *w, const mlopenTensorDescriptor_t yDesc, const void *y, const int requestAlgoCount, int *returnedAlgoCount, mlopenConvAlgoPerf_t *perfResults, mlopenConvPreference_t preference, void *workSpace, size_t workSpaceSize) { printf("To be implemented (FindConvFwdAlgo) \n"); #if 0 if(handle == nullptr) { return mlopenStatusBadParm; } if(xDesc == nullptr || wDesc == nullptr || yDesc == nullptr) { return mlopenStatusBadParm; } if(x == nullptr || w == nullptr || y == nullptr) { return mlopenStatusBadParm; } if(returnedAlgoCount == nullptr || perfResults == nullptr) { return mlopenStatusBadParm; } if(requestAlgoCount < 1) { return mlopenStatusBadParm; } #endif // Generate kernels if OpenCL // Compile, cache kernels, etc. // Launch all kernels and store the perf, workspace limits, etc. mlo_construct_direct2D construct_params(1); // forward, no bias { construct_params.setTimerIter(100); // HOW TO DEFINE??? construct_params.doSearch(false); // construct_params.saveSearchRequest(true); // TO DO WHERE IS THE PATH ? std::string kernel_path = "../src"; construct_params.setKernelPath(kernel_path); std::string generic_comp_otions = std::string(" -I ") + kernel_path + " "; // if (debug) { generic_comp_otions += std::string(" -cl-std=CL2.0 "); } construct_params.setGeneralCompOptions(generic_comp_otions); mlopenStream_t queue; handle->GetStream(&queue); construct_params.setStream(queue); int nOut; int cOut; int hOut; int wOut; int nOutStride; int cOutStride; int hOutStride; int wOutStride; yDesc->Get4Dims(&nOut, &cOut, &hOut, &wOut); yDesc->Get4Strides(&nOutStride, &cOutStride, &hOutStride, &wOutStride); construct_params.setOutputDescr( "NCHW", "FP32", nOut, cOut, hOut, wOut, nOutStride, cOutStride, hOutStride, wOutStride); int nIn; int cIn; int hIn; int wIn; int nInStride; int cInStride; int hInStride; int wInStride; xDesc->Get4Dims(&nIn, &cIn, &hIn, &wIn); yDesc->Get4Strides(&nInStride, &cInStride, &hInStride, &wInStride); construct_params.setInputDescr( "NCHW", "FP32", nIn, cIn, hIn, wIn, nInStride, cInStride, hInStride, wInStride); int nWei; int cWei; int hWei; int wWei; int nWeiStride; int cWeiStride; int hWeiStride; int wWeiStride; wDesc->Get4Dims(&nWei, &cWei, &hWei, &wWei); wDesc->Get4Strides(&nWeiStride, &cWeiStride, &hWeiStride, &wWeiStride); construct_params.setWeightsDescr( "NCHW", "FP32", nWei, cWei, hWei, wWei, nWeiStride, cWeiStride, hWeiStride, wWeiStride ); construct_params.setConvDescr(_pad_h, _pad_w, _u, _v, _upscalex, _upscaley); construct_params.mloConstructDirect2D(); } std::string program_name = std::string("../src/") + construct_params.getKernelFile(); //"../src/Hello.cl"; // CL kernel filename std::string kernel_name = construct_params.getKernelFile(); // "hello_world_kernel"; // kernel name std::string parms = construct_params.getCompilerOptions(); // kernel parameters // Get the queue associated with this handle mlopenStream_t queue; handle->GetStream(&queue); // Compile the kernel if not aleady compiled OCLKernel obj = KernelCache::get(queue, program_name, kernel_name, parms); cl_int status; std::string kernName; obj.GetKernelName(kernName); printf("kname: %s\n", kernName.c_str()); #if 0 // Test to see if we can launch the kernel and get the results back float *a = new float[1024]; float *b = new float[1024]; float *c = new float[1024]; for(int i = 0; i < 1024; i++) { a[i] = 1.0; b[i] = 7.0; c[i] = 0.0; } int sz = 1024; cl_context ctx; clGetCommandQueueInfo(queue, CL_QUEUE_CONTEXT, sizeof(cl_context), &ctx, NULL); cl_mem adev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz,NULL, &status); if(status != CL_SUCCESS) { printf("error %d\n", status); } cl_mem bdev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz,NULL, NULL); cl_mem cdev = clCreateBuffer(ctx, CL_MEM_READ_WRITE, 4*sz,NULL, NULL); status = clEnqueueWriteBuffer(queue, adev, CL_TRUE, 0, 4*sz, a, 0, NULL, NULL); status |= clEnqueueWriteBuffer(queue, bdev, CL_TRUE, 0, 4*sz, b, 0, NULL, NULL); status |= clEnqueueWriteBuffer(queue, cdev, CL_TRUE, 0, 4*sz, c, 0, NULL, NULL); // Set kernel arguments // Use proper arguments //obj.SetArgs(0, adev, bdev, cdev, sz); size_t gd = 1024; size_t ld = 256; // Run the kernel obj.run(queue, 1, 0, gd, ld); clFinish(queue); #endif // Test #if 0 // Read results back clEnqueueReadBuffer(queue, cdev, CL_TRUE, 0, 4*sz, c, 0, NULL, NULL); float sum = 0.0; for(int i = 0; i < 1024; i++) { b[i] = 6; sum += c[i]; } printf("\nsum %f\n, ", sum); sum = 0.0; status |= clEnqueueWriteBuffer(queue, bdev, CL_TRUE, 0, 4*sz, b, 0, NULL, NULL); getchar(); #endif //Results return mlopenStatusSuccess; } mlopenStatus_t mlopenConvolutionDescriptor::ConvolutionForward(mlopenHandle_t handle, const void *alpha, const mlopenTensorDescriptor_t xDesc, const void *x, const mlopenTensorDescriptor_t wDesc, const void *w, mlopenConvFwdAlgorithm_t algo, const void *beta, const mlopenTensorDescriptor_t yDesc, void *y) { printf("To be implemented (ConvolutionForward) \n"); if(handle == nullptr) { return mlopenStatusBadParm; } if(xDesc == nullptr || wDesc == nullptr || yDesc == nullptr) { return mlopenStatusBadParm; } if(x == nullptr || w == nullptr || y == nullptr) { return mlopenStatusBadParm; } if(xDesc->_CheckTensorDims(yDesc) != mlopenStatusSuccess || xDesc->_CheckTensorDims(wDesc) != mlopenStatusSuccess) { return mlopenStatusBadParm; } if(xDesc->_CheckTensorDataTypes(yDesc) != mlopenStatusSuccess || xDesc->_CheckTensorDataTypes(wDesc) != mlopenStatusSuccess) { return mlopenStatusBadParm; } if(xDesc->_dimA[0] != wDesc->_dimA[0]) { return mlopenStatusBadParm; } if(xDesc->_dims < 3) { return mlopenStatusBadParm; } std::string program_name; // CL kernel filename std::string kernel_name; // kernel name std::string parms; // kernel parameters mlopenStream_t queue; handle->GetStream(&queue); #if MLOpen_BACKEND_OPENCL // OCLKernel kernel = KernelCache::get(queue, program_name, kernel_name); #endif return mlopenStatusSuccess; } <|endoftext|>
<commit_before>#ifdef _WIN32 #define _USE_MATH_DEFINES #endif #include <iostream> #include <list> #include "core/Halite.hpp" inline std::istream& operator>>(std::istream& i, std::pair<signed int, signed int>& p) { i >> p.first >> p.second; return i; } inline std::ostream& operator<<(std::ostream& o, const std::pair<signed int, signed int>& p) { o << p.first << ' ' << p.second; return o; } #include <tclap/CmdLine.h> namespace TCLAP { template<> struct ArgTraits<std::pair<signed int, signed int> > { typedef TCLAP::ValueLike ValueCategory; }; } bool quiet_output = false; //Need to be passed to a bunch of classes; extern is cleaner. Halite* my_game; //Is a pointer to avoid problems with assignment, dynamic memory, and default constructors. Networking promptNetworking(); void promptDimensions(unsigned short& w, unsigned short& h); int main(int argc, char** argv) { srand(time(NULL)); //For all non-seeded randomness. Networking networking; std::vector<std::string>* names = NULL; auto id = std::chrono::duration_cast<std::chrono::seconds>( std::chrono::high_resolution_clock().now().time_since_epoch()).count(); TCLAP::CmdLine cmd("Halite Game Environment", ' ', "1.2"); //Switch Args. TCLAP::SwitchArg quietSwitch("q", "quiet", "Runs game in quiet mode, producing machine-parsable output.", cmd, false); TCLAP::SwitchArg overrideSwitch("o", "override", "Overrides player-sent names using cmd args [SERVER ONLY].", cmd, false); TCLAP::SwitchArg timeoutSwitch("t", "timeout", "Causes game environment to ignore timeouts (give all bots infinite time).", cmd, false); TCLAP::SwitchArg noReplaySwitch ("r", "noreplay", "Turns off the replay generation.", cmd, false); //Value Args TCLAP::ValueArg<unsigned int> nPlayersArg("n", "nplayers", "Create a map that will accommodate n players [SINGLE PLAYER MODE ONLY].", false, 1, "{1,2,3,4,5,6}", cmd); TCLAP::ValueArg<std::pair<signed int, signed int> > dimensionArgs("d", "dimensions", "The dimensions of the map.", false, { 0, 0 }, "a string containing two space-seprated positive integers", cmd); TCLAP::ValueArg<unsigned int> seedArg("s", "seed", "The seed for the map generator.", false, 0, "positive integer", cmd); TCLAP::ValueArg<std::string> replayDirectoryArg("i", "replaydirectory", "The path to directory for replay output.", false, ".", "path to directory", cmd); TCLAP::ValueArg<std::string> constantsArg( "", "constantsfile", "JSON file containing runtime constants to use.", false, "", "path to file", cmd ); TCLAP::SwitchArg printConstantsSwitch( "", "print-constants", "Print out the default constants and exit.", cmd, false ); //Remaining Args, be they start commands and/or override names. Description only includes start commands since it will only be seen on local testing. TCLAP::UnlabeledMultiArg<std::string> otherArgs("NonspecifiedArgs", "Start commands for bots.", false, "Array of strings", cmd); cmd.parse(argc, argv); unsigned short mapWidth = dimensionArgs.getValue().first; unsigned short mapHeight = dimensionArgs.getValue().second; unsigned int seed; if (seedArg.getValue() != 0) seed = seedArg.getValue(); else seed = (std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count() % 4294967295); unsigned short n_players_for_map_creation = nPlayersArg.getValue(); quiet_output = quietSwitch.getValue(); bool override_names = overrideSwitch.getValue(); bool ignore_timeout = timeoutSwitch.getValue(); if (printConstantsSwitch.getValue()) { std::cout << hlt::GameConstants::get().to_json().dump(4) << '\n'; return 0; } // Update the game constants. if (constantsArg.isSet()) { std::ifstream constants_file(constantsArg.getValue()); nlohmann::json constants_json; constants_file >> constants_json; auto& constants = hlt::GameConstants::get_mut(); constants.from_json(constants_json); if (!quiet_output) { std::cout << "Game constants: \n" << constants.to_json().dump(4) << '\n'; } } else { if (!quiet_output) { std::cout << "Game constants: all default\n"; } } std::vector<std::string> unlabeledArgsVector = otherArgs.getValue(); std::list<std::string> unlabeledArgs; for (auto a = unlabeledArgsVector.begin(); a != unlabeledArgsVector.end(); a++) { unlabeledArgs.push_back(*a); } if (mapWidth == 0 && mapHeight == 0) { std::vector<unsigned short> mapSizeChoices = { 160, 160, 192, 192, 192, 256, 256, 256, 256, 384, 384, 384 }; std::mt19937 prg(seed); std::uniform_int_distribution<unsigned short> size_dist(0, mapSizeChoices.size() - 1); mapWidth = mapSizeChoices[size_dist(prg)]; mapHeight = mapSizeChoices[size_dist(prg)]; if (mapHeight > mapWidth) { auto temp = mapWidth; mapWidth = mapHeight; mapHeight = temp; } } const auto override_factor = overrideSwitch.getValue() ? 2 : 1; if (unlabeledArgs.size() != 1 && unlabeledArgs.size() != 2 * override_factor && unlabeledArgs.size() != 4 * override_factor) { std::cout << "Must have either 2 or 4 players, or a solo player.\n"; return 1; } if (unlabeledArgs.size() == 1 && n_players_for_map_creation != 2 && n_players_for_map_creation != 4) { // Limiation of solar system map generator used std::cout << "Must have either 2 or 4 players for map creation.\n"; return 1; } if (override_names) { if (unlabeledArgs.size() < 4 || unlabeledArgs.size() % 2 != 0) { std::cout << "Invalid number of player parameters with override switch enabled. Override intended for server use only." << std::endl; exit(1); } else { try { names = new std::vector<std::string>(); while (!unlabeledArgs.empty()) { networking.launch_bot(unlabeledArgs.front()); unlabeledArgs.pop_front(); names->push_back(unlabeledArgs.front()); unlabeledArgs.pop_front(); } } catch (...) { std::cout << "Invalid player parameters with override switch enabled. Override intended for server use only." << std::endl; delete names; names = NULL; exit(1); } } } else { if (unlabeledArgs.size() < 1) { std::cout << "Please provide the launch command string for at least one bot." << std::endl << "Use the --help flag for usage details.\n"; exit(1); } try { while (!unlabeledArgs.empty()) { networking.launch_bot(unlabeledArgs.front()); unlabeledArgs.pop_front(); } } catch (...) { std::cout << "One or more of your bot launch command strings failed. Please check for correctness and try again." << std::endl; exit(1); } } if (networking.player_count() > 1 && n_players_for_map_creation != 1) { std::cout << std::endl << "Only single-player mode enables specified n-player maps. When entering multiple bots, please do not try to specify n." << std::endl << std::endl; exit(1); } if (networking.player_count() > 1) n_players_for_map_creation = networking.player_count(); if (n_players_for_map_creation > 6 || n_players_for_map_creation < 1) { std::cout << std::endl << "A map can only accommodate between 1 and 6 players." << std::endl << std::endl; exit(1); } //Create game. Null parameters will be ignored. my_game = new Halite(mapWidth, mapHeight, seed, n_players_for_map_creation, networking, ignore_timeout); std::string outputFilename = replayDirectoryArg.getValue(); #ifdef _WIN32 if(outputFilename.back() != '\\') outputFilename.push_back('\\'); #else if (outputFilename.back() != '/') outputFilename.push_back('/'); #endif GameStatistics stats = my_game->run_game(names, id, !noReplaySwitch.getValue(), outputFilename); if (names != NULL) delete names; std::string victoryOut; if (!quiet_output) { for (unsigned int player_id = 0; player_id < stats.player_statistics.size(); player_id++) { auto& player_stats = stats.player_statistics[player_id]; std::cout << "Player #" << player_stats.tag << ", " << my_game->get_name(player_stats.tag) << ", came in rank #" << player_stats.rank << " and was last alive on frame #" << player_stats.last_frame_alive << ", producing " << player_stats.total_ship_count << " ships" << " and dealing " << player_stats.damage_dealt << " damage" << "!\n"; } } delete my_game; return 0; } <commit_msg>Make maps always 3:2 aspect ratio<commit_after>#ifdef _WIN32 #define _USE_MATH_DEFINES #endif #include <iostream> #include <list> #include "core/Halite.hpp" inline std::istream& operator>>(std::istream& i, std::pair<signed int, signed int>& p) { i >> p.first >> p.second; return i; } inline std::ostream& operator<<(std::ostream& o, const std::pair<signed int, signed int>& p) { o << p.first << ' ' << p.second; return o; } #include <tclap/CmdLine.h> namespace TCLAP { template<> struct ArgTraits<std::pair<signed int, signed int> > { typedef TCLAP::ValueLike ValueCategory; }; } bool quiet_output = false; //Need to be passed to a bunch of classes; extern is cleaner. Halite* my_game; //Is a pointer to avoid problems with assignment, dynamic memory, and default constructors. Networking promptNetworking(); void promptDimensions(unsigned short& w, unsigned short& h); int main(int argc, char** argv) { srand(time(NULL)); //For all non-seeded randomness. Networking networking; std::vector<std::string>* names = NULL; auto id = std::chrono::duration_cast<std::chrono::seconds>( std::chrono::high_resolution_clock().now().time_since_epoch()).count(); TCLAP::CmdLine cmd("Halite Game Environment", ' ', "1.2"); //Switch Args. TCLAP::SwitchArg quietSwitch("q", "quiet", "Runs game in quiet mode, producing machine-parsable output.", cmd, false); TCLAP::SwitchArg overrideSwitch("o", "override", "Overrides player-sent names using cmd args [SERVER ONLY].", cmd, false); TCLAP::SwitchArg timeoutSwitch("t", "timeout", "Causes game environment to ignore timeouts (give all bots infinite time).", cmd, false); TCLAP::SwitchArg noReplaySwitch ("r", "noreplay", "Turns off the replay generation.", cmd, false); //Value Args TCLAP::ValueArg<unsigned int> nPlayersArg("n", "nplayers", "Create a map that will accommodate n players [SINGLE PLAYER MODE ONLY].", false, 1, "{1,2,3,4,5,6}", cmd); TCLAP::ValueArg<std::pair<signed int, signed int> > dimensionArgs("d", "dimensions", "The dimensions of the map.", false, { 0, 0 }, "a string containing two space-seprated positive integers", cmd); TCLAP::ValueArg<unsigned int> seedArg("s", "seed", "The seed for the map generator.", false, 0, "positive integer", cmd); TCLAP::ValueArg<std::string> replayDirectoryArg("i", "replaydirectory", "The path to directory for replay output.", false, ".", "path to directory", cmd); TCLAP::ValueArg<std::string> constantsArg( "", "constantsfile", "JSON file containing runtime constants to use.", false, "", "path to file", cmd ); TCLAP::SwitchArg printConstantsSwitch( "", "print-constants", "Print out the default constants and exit.", cmd, false ); //Remaining Args, be they start commands and/or override names. Description only includes start commands since it will only be seen on local testing. TCLAP::UnlabeledMultiArg<std::string> otherArgs("NonspecifiedArgs", "Start commands for bots.", false, "Array of strings", cmd); cmd.parse(argc, argv); unsigned short mapWidth = dimensionArgs.getValue().first; unsigned short mapHeight = dimensionArgs.getValue().second; unsigned int seed; if (seedArg.getValue() != 0) seed = seedArg.getValue(); else seed = (std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count() % 4294967295); unsigned short n_players_for_map_creation = nPlayersArg.getValue(); quiet_output = quietSwitch.getValue(); bool override_names = overrideSwitch.getValue(); bool ignore_timeout = timeoutSwitch.getValue(); if (printConstantsSwitch.getValue()) { std::cout << hlt::GameConstants::get().to_json().dump(4) << '\n'; return 0; } // Update the game constants. if (constantsArg.isSet()) { std::ifstream constants_file(constantsArg.getValue()); nlohmann::json constants_json; constants_file >> constants_json; auto& constants = hlt::GameConstants::get_mut(); constants.from_json(constants_json); if (!quiet_output) { std::cout << "Game constants: \n" << constants.to_json().dump(4) << '\n'; } } else { if (!quiet_output) { std::cout << "Game constants: all default\n"; } } std::vector<std::string> unlabeledArgsVector = otherArgs.getValue(); std::list<std::string> unlabeledArgs; for (auto arg : unlabeledArgsVector) { unlabeledArgs.push_back(arg); } if (mapWidth == 0 && mapHeight == 0) { // Always generate a 3:2 aspect ratio std::vector<unsigned short> mapSizeChoices = { 80, 80, 88, 88, 96, 96, 96, 112, 112, 112, 120, 120, 128, 128 }; std::mt19937 prg(seed); std::uniform_int_distribution<unsigned long> size_dist(0, mapSizeChoices.size() - 1); auto mapBase = mapSizeChoices[size_dist(prg)]; mapWidth = 3 * mapBase; mapHeight = 2 * mapBase; } const auto override_factor = overrideSwitch.getValue() ? 2 : 1; if (unlabeledArgs.size() != 1 && unlabeledArgs.size() != 2 * override_factor && unlabeledArgs.size() != 4 * override_factor) { std::cout << "Must have either 2 or 4 players, or a solo player.\n"; return 1; } if (unlabeledArgs.size() == 1 && n_players_for_map_creation != 2 && n_players_for_map_creation != 4) { // Limiation of solar system map generator used std::cout << "Must have either 2 or 4 players for map creation.\n"; return 1; } if (override_names) { if (unlabeledArgs.size() < 4 || unlabeledArgs.size() % 2 != 0) { std::cout << "Invalid number of player parameters with override switch enabled. Override intended for server use only." << std::endl; exit(1); } else { try { names = new std::vector<std::string>(); while (!unlabeledArgs.empty()) { networking.launch_bot(unlabeledArgs.front()); unlabeledArgs.pop_front(); names->push_back(unlabeledArgs.front()); unlabeledArgs.pop_front(); } } catch (...) { std::cout << "Invalid player parameters with override switch enabled. Override intended for server use only." << std::endl; delete names; names = NULL; exit(1); } } } else { if (unlabeledArgs.size() < 1) { std::cout << "Please provide the launch command string for at least one bot." << std::endl << "Use the --help flag for usage details.\n"; exit(1); } try { while (!unlabeledArgs.empty()) { networking.launch_bot(unlabeledArgs.front()); unlabeledArgs.pop_front(); } } catch (...) { std::cout << "One or more of your bot launch command strings failed. Please check for correctness and try again." << std::endl; exit(1); } } if (networking.player_count() > 1 && n_players_for_map_creation != 1) { std::cout << std::endl << "Only single-player mode enables specified n-player maps. When entering multiple bots, please do not try to specify n." << std::endl << std::endl; exit(1); } if (networking.player_count() > 1) n_players_for_map_creation = networking.player_count(); if (n_players_for_map_creation > 6 || n_players_for_map_creation < 1) { std::cout << std::endl << "A map can only accommodate between 1 and 6 players." << std::endl << std::endl; exit(1); } //Create game. Null parameters will be ignored. my_game = new Halite(mapWidth, mapHeight, seed, n_players_for_map_creation, networking, ignore_timeout); std::string outputFilename = replayDirectoryArg.getValue(); #ifdef _WIN32 if(outputFilename.back() != '\\') outputFilename.push_back('\\'); #else if (outputFilename.back() != '/') outputFilename.push_back('/'); #endif GameStatistics stats = my_game->run_game(names, id, !noReplaySwitch.getValue(), outputFilename); if (names != NULL) delete names; std::string victoryOut; if (!quiet_output) { for (unsigned int player_id = 0; player_id < stats.player_statistics.size(); player_id++) { auto& player_stats = stats.player_statistics[player_id]; std::cout << "Player #" << player_stats.tag << ", " << my_game->get_name(player_stats.tag) << ", came in rank #" << player_stats.rank << " and was last alive on frame #" << player_stats.last_frame_alive << ", producing " << player_stats.total_ship_count << " ships" << " and dealing " << player_stats.damage_dealt << " damage" << "!\n"; } } delete my_game; return 0; } <|endoftext|>
<commit_before><commit_msg>Build: fix modules/common/math/... build caused by upgraded osqp<commit_after><|endoftext|>
<commit_before>#include "Convolution.hpp" #include "mlo_internal.hpp" mlopenConvolutionDescriptor::mlopenConvolutionDescriptor() : _pad_h(0), _pad_w(0), _u(1), _v(1), _upscalex(0), _upscaley(0) { printf("In convolution Ctor\n"); _mode = mlopenConvolution; } mlopenStatus_t mlopenConvolutionDescriptor::GetForwardOutputDim(const mlopenTensorDescriptor_t inputTensorDesc, const mlopenTensorDescriptor_t filterDesc, int *n, int *c, int *h, int *w) { printf("To be implemented (GetForwardOutputDim)\n"); return mlopenStatusSuccess; } mlopenStatus_t mlopenConvolutionDescriptor::FindConvFwdAlgorithm(mlopenHandle_t handle, const mlopenTensorDescriptor_t xDesc, const void *x, const mlopenTensorDescriptor_t wDesc, const void *w, const mlopenTensorDescriptor_t yDesc, const void *y, const int requestAlgoCount, int *returnedAlgoCount, mlopenConvAlgoPerf_t *perfResults, mlopenConvPreference_t preference, void *workSpace, size_t workSpaceSize) { printf("To be implemented (FindConvFwdAlgo) \n"); #if 0 if(handle == nullptr) { return mlopenStatusBadParm; } if(xDesc == nullptr || wDesc == nullptr || yDesc == nullptr) { return mlopenStatusBadParm; } if(x == nullptr || w == nullptr || y == nullptr) { return mlopenStatusBadParm; } if(returnedAlgoCount == nullptr || perfResults == nullptr) { return mlopenStatusBadParm; } if(requestAlgoCount < 1) { return mlopenStatusBadParm; } #endif // Generate kernels if OpenCL // Compile, cache kernels, etc. // Launch all kernels and store the perf, workspace limits, etc. mlo_construct_direct2D construct_params(1); // forward, no bias { construct_params.setTimerIter(100); // HOW TO DEFINE??? construct_params.doSearch(false); // construct_params.saveSearchRequest(true); // TO DO WHERE IS THE PATH ? std::string kernel_path = "../src"; construct_params.setKernelPath(kernel_path); std::string generic_comp_otions = std::string(" -I ") + kernel_path + " "; // if (debug) { generic_comp_otions += std::string(" -cl-std=CL2.0 "); } construct_params.setGeneralCompOptions(generic_comp_otions); mlopenStream_t queue; handle->GetStream(&queue); construct_params.setStream(queue); int nOut; int cOut; int hOut; int wOut; int nOutStride; int cOutStride; int hOutStride; int wOutStride; yDesc->Get4Dims(&nOut, &cOut, &hOut, &wOut); yDesc->Get4Strides(&nOutStride, &cOutStride, &hOutStride, &wOutStride); construct_params.setOutputDescr( "NCHW", "FP32", nOut, cOut, hOut, wOut, nOutStride, cOutStride, hOutStride, wOutStride); int nIn; int cIn; int hIn; int wIn; int nInStride; int cInStride; int hInStride; int wInStride; xDesc->Get4Dims(&nIn, &cIn, &hIn, &wIn); yDesc->Get4Strides(&nInStride, &cInStride, &hInStride, &wInStride); construct_params.setInputDescr( "NCHW", "FP32", nIn, cIn, hIn, wIn, nInStride, cInStride, hInStride, wInStride); int nWei; int cWei; int hWei; int wWei; int nWeiStride; int cWeiStride; int hWeiStride; int wWeiStride; wDesc->Get4Dims(&nWei, &cWei, &hWei, &wWei); wDesc->Get4Strides(&nWeiStride, &cWeiStride, &hWeiStride, &wWeiStride); construct_params.setWeightsDescr( "NCHW", "FP32", nWei, cWei, hWei, wWei, nWeiStride, cWeiStride, hWeiStride, wWeiStride ); construct_params.setConvDescr(_pad_h, _pad_w, _u, _v, _upscalex, _upscaley); construct_params.mloConstructDirect2D(); } std::string program_name = std::string("../src/") + construct_params.getKernelFile(); //"../src/Hello.cl"; // CL kernel filename std::string kernel_name = construct_params.getKernelFile(); // "hello_world_kernel"; // kernel name std::string parms = construct_params.getCompilerOptions(); // kernel parameters // Get the queue associated with this handle mlopenStream_t queue; handle->GetStream(&queue); // Compile the kernel if not aleady compiled OCLKernel obj = KernelCache::get(queue, program_name, kernel_name, parms); cl_int status; std::string kernName; obj.GetKernelName(kernName); printf("kname: %s\n", kernName.c_str()); #if 0 // Test to see if we can launch the kernel and get the results back float *a = new float[1024]; float *b = new float[1024]; float *c = new float[1024]; for(int i = 0; i < 1024; i++) { a[i] = 1.0; b[i] = 7.0; c[i] = 0.0; } int sz = 1024; cl_context ctx; clGetCommandQueueInfo(queue, CL_QUEUE_CONTEXT, sizeof(cl_context), &ctx, NULL); cl_mem adev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz,NULL, &status); if(status != CL_SUCCESS) { printf("error %d\n", status); } cl_mem bdev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz,NULL, NULL); cl_mem cdev = clCreateBuffer(ctx, CL_MEM_READ_WRITE, 4*sz,NULL, NULL); status = clEnqueueWriteBuffer(queue, adev, CL_TRUE, 0, 4*sz, a, 0, NULL, NULL); status |= clEnqueueWriteBuffer(queue, bdev, CL_TRUE, 0, 4*sz, b, 0, NULL, NULL); status |= clEnqueueWriteBuffer(queue, cdev, CL_TRUE, 0, 4*sz, c, 0, NULL, NULL); // Set kernel arguments // Use proper arguments //obj.SetArgs(0, adev, bdev, cdev, sz); size_t gd = 1024; size_t ld = 256; // Run the kernel obj.run(queue, 1, 0, gd, ld); clFinish(queue); #endif // Test #if 0 // Read results back clEnqueueReadBuffer(queue, cdev, CL_TRUE, 0, 4*sz, c, 0, NULL, NULL); float sum = 0.0; for(int i = 0; i < 1024; i++) { b[i] = 6; sum += c[i]; } printf("\nsum %f\n, ", sum); sum = 0.0; status |= clEnqueueWriteBuffer(queue, bdev, CL_TRUE, 0, 4*sz, b, 0, NULL, NULL); getchar(); #endif //Results return mlopenStatusSuccess; } mlopenStatus_t mlopenConvolutionDescriptor::ConvolutionForward(mlopenHandle_t handle, const void *alpha, const mlopenTensorDescriptor_t xDesc, const void *x, const mlopenTensorDescriptor_t wDesc, const void *w, mlopenConvFwdAlgorithm_t algo, const void *beta, const mlopenTensorDescriptor_t yDesc, void *y) { printf("To be implemented (ConvolutionForward) \n"); if(handle == nullptr) { return mlopenStatusBadParm; } if(xDesc == nullptr || wDesc == nullptr || yDesc == nullptr) { return mlopenStatusBadParm; } if(x == nullptr || w == nullptr || y == nullptr) { return mlopenStatusBadParm; } if(xDesc->_CheckTensorDims(yDesc) != mlopenStatusSuccess || xDesc->_CheckTensorDims(wDesc) != mlopenStatusSuccess) { return mlopenStatusBadParm; } if(xDesc->_CheckTensorDataTypes(yDesc) != mlopenStatusSuccess || xDesc->_CheckTensorDataTypes(wDesc) != mlopenStatusSuccess) { return mlopenStatusBadParm; } if(xDesc->_dimA[0] != wDesc->_dimA[0]) { return mlopenStatusBadParm; } if(xDesc->_dims < 3) { return mlopenStatusBadParm; } std::string program_name; // CL kernel filename std::string kernel_name; // kernel name std::string parms; // kernel parameters mlopenStream_t queue; handle->GetStream(&queue); #if MLOpen_BACKEND_OPENCL // OCLKernel kernel = KernelCache::get(queue, program_name, kernel_name); #endif return mlopenStatusSuccess; } <commit_msg>conv fix<commit_after>#include "Convolution.hpp" #include "mlo_internal.hpp" mlopenConvolutionDescriptor::mlopenConvolutionDescriptor() : _pad_h(0), _pad_w(0), _u(1), _v(1), _upscalex(0), _upscaley(0) { printf("In convolution Ctor\n"); _mode = mlopenConvolution; } mlopenStatus_t mlopenConvolutionDescriptor::GetForwardOutputDim(const mlopenTensorDescriptor_t inputTensorDesc, const mlopenTensorDescriptor_t filterDesc, int *n, int *c, int *h, int *w) { printf("To be implemented (GetForwardOutputDim)\n"); return mlopenStatusSuccess; } mlopenStatus_t mlopenConvolutionDescriptor::FindConvFwdAlgorithm(mlopenHandle_t handle, const mlopenTensorDescriptor_t xDesc, const void *x, const mlopenTensorDescriptor_t wDesc, const void *w, const mlopenTensorDescriptor_t yDesc, const void *y, const int requestAlgoCount, int *returnedAlgoCount, mlopenConvAlgoPerf_t *perfResults, mlopenConvPreference_t preference, void *workSpace, size_t workSpaceSize) { printf("To be implemented (FindConvFwdAlgo) \n"); #if 0 if(handle == nullptr) { return mlopenStatusBadParm; } if(xDesc == nullptr || wDesc == nullptr || yDesc == nullptr) { return mlopenStatusBadParm; } if(x == nullptr || w == nullptr || y == nullptr) { return mlopenStatusBadParm; } if(returnedAlgoCount == nullptr || perfResults == nullptr) { return mlopenStatusBadParm; } if(requestAlgoCount < 1) { return mlopenStatusBadParm; } #endif // Generate kernels if OpenCL // Compile, cache kernels, etc. // Launch all kernels and store the perf, workspace limits, etc. mlo_construct_direct2D construct_params(1); // forward, no bias { construct_params.setTimerIter(100); // HOW TO DEFINE??? construct_params.doSearch(false); // construct_params.saveSearchRequest(true); // TO DO WHERE IS THE PATH ? std::string kernel_path = "../src"; construct_params.setKernelPath(kernel_path); std::string generic_comp_otions = std::string(" -I ") + kernel_path + " "; // if (debug) { generic_comp_otions += std::string(" -cl-std=CL2.0 "); } construct_params.setGeneralCompOptions(generic_comp_otions); mlopenStream_t queue; handle->GetStream(&queue); construct_params.setStream(queue); int nOut; int cOut; int hOut; int wOut; int nOutStride; int cOutStride; int hOutStride; int wOutStride; yDesc->Get4Dims(&nOut, &cOut, &hOut, &wOut); yDesc->Get4Strides(&nOutStride, &cOutStride, &hOutStride, &wOutStride); construct_params.setOutputDescr( "NCHW", "FP32", nOut, cOut, hOut, wOut, nOutStride, cOutStride, hOutStride, wOutStride); int nIn; int cIn; int hIn; int wIn; int nInStride; int cInStride; int hInStride; int wInStride; xDesc->Get4Dims(&nIn, &cIn, &hIn, &wIn); yDesc->Get4Strides(&nInStride, &cInStride, &hInStride, &wInStride); construct_params.setInputDescr( "NCHW", "FP32", nIn, cIn, hIn, wIn, nInStride, cInStride, hInStride, wInStride); int nWei; int cWei; int hWei; int wWei; int nWeiStride; int cWeiStride; int hWeiStride; int wWeiStride; wDesc->Get4Dims(&nWei, &cWei, &hWei, &wWei); wDesc->Get4Strides(&nWeiStride, &cWeiStride, &hWeiStride, &wWeiStride); construct_params.setWeightsDescr( "NCHW", "FP32", nWei, cWei, hWei, wWei, nWeiStride, cWeiStride, hWeiStride, wWeiStride ); construct_params.setConvDescr(_pad_h, _pad_w, _u, _v, _upscalex, _upscaley); construct_params.mloConstructDirect2D(); } std::string program_name = std::string("../src/") + construct_params.getKernelFile(); //"../src/Hello.cl"; // CL kernel filename std::string kernel_name = construct_params.getKernelName(); // "hello_world_kernel"; // kernel name std::string parms = construct_params.getCompilerOptions(); // kernel parameters // Get the queue associated with this handle mlopenStream_t queue; handle->GetStream(&queue); // Compile the kernel if not aleady compiled OCLKernel obj = KernelCache::get(queue, program_name, kernel_name, parms); cl_int status; std::string kernName; obj.GetKernelName(kernName); printf("kname: %s\n", kernName.c_str()); #if 0 // Test to see if we can launch the kernel and get the results back float *a = new float[1024]; float *b = new float[1024]; float *c = new float[1024]; for(int i = 0; i < 1024; i++) { a[i] = 1.0; b[i] = 7.0; c[i] = 0.0; } int sz = 1024; cl_context ctx; clGetCommandQueueInfo(queue, CL_QUEUE_CONTEXT, sizeof(cl_context), &ctx, NULL); cl_mem adev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz,NULL, &status); if(status != CL_SUCCESS) { printf("error %d\n", status); } cl_mem bdev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz,NULL, NULL); cl_mem cdev = clCreateBuffer(ctx, CL_MEM_READ_WRITE, 4*sz,NULL, NULL); status = clEnqueueWriteBuffer(queue, adev, CL_TRUE, 0, 4*sz, a, 0, NULL, NULL); status |= clEnqueueWriteBuffer(queue, bdev, CL_TRUE, 0, 4*sz, b, 0, NULL, NULL); status |= clEnqueueWriteBuffer(queue, cdev, CL_TRUE, 0, 4*sz, c, 0, NULL, NULL); // Set kernel arguments // Use proper arguments //obj.SetArgs(0, adev, bdev, cdev, sz); size_t gd = 1024; size_t ld = 256; // Run the kernel obj.run(queue, 1, 0, gd, ld); clFinish(queue); #endif // Test #if 0 // Read results back clEnqueueReadBuffer(queue, cdev, CL_TRUE, 0, 4*sz, c, 0, NULL, NULL); float sum = 0.0; for(int i = 0; i < 1024; i++) { b[i] = 6; sum += c[i]; } printf("\nsum %f\n, ", sum); sum = 0.0; status |= clEnqueueWriteBuffer(queue, bdev, CL_TRUE, 0, 4*sz, b, 0, NULL, NULL); getchar(); #endif //Results return mlopenStatusSuccess; } mlopenStatus_t mlopenConvolutionDescriptor::ConvolutionForward(mlopenHandle_t handle, const void *alpha, const mlopenTensorDescriptor_t xDesc, const void *x, const mlopenTensorDescriptor_t wDesc, const void *w, mlopenConvFwdAlgorithm_t algo, const void *beta, const mlopenTensorDescriptor_t yDesc, void *y) { printf("To be implemented (ConvolutionForward) \n"); if(handle == nullptr) { return mlopenStatusBadParm; } if(xDesc == nullptr || wDesc == nullptr || yDesc == nullptr) { return mlopenStatusBadParm; } if(x == nullptr || w == nullptr || y == nullptr) { return mlopenStatusBadParm; } if(xDesc->_CheckTensorDims(yDesc) != mlopenStatusSuccess || xDesc->_CheckTensorDims(wDesc) != mlopenStatusSuccess) { return mlopenStatusBadParm; } if(xDesc->_CheckTensorDataTypes(yDesc) != mlopenStatusSuccess || xDesc->_CheckTensorDataTypes(wDesc) != mlopenStatusSuccess) { return mlopenStatusBadParm; } if(xDesc->_dimA[0] != wDesc->_dimA[0]) { return mlopenStatusBadParm; } if(xDesc->_dims < 3) { return mlopenStatusBadParm; } std::string program_name; // CL kernel filename std::string kernel_name; // kernel name std::string parms; // kernel parameters mlopenStream_t queue; handle->GetStream(&queue); #if MLOpen_BACKEND_OPENCL // OCLKernel kernel = KernelCache::get(queue, program_name, kernel_name); #endif return mlopenStatusSuccess; } <|endoftext|>
<commit_before>// @(#)root/mathmore:$Id$ // Author: L. Moneta Wed Sep 6 09:52:26 2006 /********************************************************************** * * * Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT * * * * * **********************************************************************/ // implementation file for class WrappedTF1 and WrappedMultiTF1 #include "Math/WrappedTF1.h" #include "Math/WrappedMultiTF1.h" #include <cmath> namespace ROOT { namespace Math { // static value for epsilon used in derivative calculations double WrappedTF1::fgEps = 0.001; double WrappedMultiTF1::fgEps = 0.001; WrappedTF1::WrappedTF1 ( TF1 & f ) : fLinear(false), fPolynomial(false), fFunc(&f), fX (), fParams(f.GetParameters(),f.GetParameters()+f.GetNpar()) { // constructor from a TF1 function pointer. // init the pointers for CINT if (fFunc->GetMethodCall() ) fFunc->InitArgs(fX, &fParams.front() ); // distinguish case of polynomial functions and linear functions if (fFunc->GetNumber() >= 300 && fFunc->GetNumber() < 310) { fLinear = true; fPolynomial = true; } // check that in case function is linear the linear terms are not zero if (fFunc->IsLinear() ) { unsigned int ip = 0; fLinear = true; while (fLinear && ip < fParams.size() ) { fLinear &= (fFunc->GetLinearPart(ip) != 0) ; ip++; } } } WrappedTF1::WrappedTF1(const WrappedTF1 & rhs) : BaseFunc(), BaseGradFunc(), IGrad(), fLinear(rhs.fLinear), fPolynomial(rhs.fPolynomial), fFunc(rhs.fFunc), fX(), fParams(rhs.fParams) { // copy constructor fFunc->InitArgs(fX,&fParams.front() ); } WrappedTF1 & WrappedTF1::operator = (const WrappedTF1 & rhs) { // assignment operator if (this == &rhs) return *this; // time saving self-test fLinear = rhs.fLinear; fPolynomial = rhs.fPolynomial; fFunc = rhs.fFunc; fFunc->InitArgs(fX, &fParams.front() ); fParams = rhs.fParams; return *this; } void WrappedTF1::ParameterGradient(double x, const double * par, double * grad ) const { // evaluate the derivative of the function with respect to the parameters if (!fLinear) { // need to set parameter values fFunc->SetParameters( par ); // no need to call InitArgs (it is called in TF1::GradientPar) fFunc->GradientPar(&x,grad,fgEps); } else { unsigned int np = NPar(); for (unsigned int i = 0; i < np; ++i) grad[i] = DoParameterDerivative(x, par, i); } } double WrappedTF1::DoDerivative( double x ) const { // return the function derivatives w.r.t. x // parameter are passed as non-const in Derivative double * p = (fParams.size() > 0) ? const_cast<double *>( &fParams.front()) : 0; return fFunc->Derivative(x,p,fgEps); } double WrappedTF1::DoParameterDerivative(double x, const double * p, unsigned int ipar ) const { // evaluate the derivative of the function with respect to the parameters //IMPORTANT NOTE: TF1::GradientPar returns 0 for fixed parameters to avoid computing useless derivatives // BUT the TLinearFitter wants to have the derivatives also for fixed parameters. // so in case of fLinear (or fPolynomial) a non-zero value will be returned for fixed parameters if (! fLinear ) { fFunc->SetParameters( p ); return fFunc->GradientPar(ipar, &x,fgEps); } else if (fPolynomial) { // case of polynomial function (no parameter dependency) return std::pow(x, static_cast<int>(ipar) ); } else { // case of general linear function (built in TFormula with ++ ) const TFormula * df = dynamic_cast<const TFormula*>( fFunc->GetLinearPart(ipar) ); assert(df != 0); fX[0] = x; // hack since TFormula::EvalPar is not const return (const_cast<TFormula*> ( df) )->EvalPar( fX ) ; // derivatives should not depend on parameters since func is linear } } void WrappedTF1::SetDerivPrecision(double eps) { fgEps = eps; } double WrappedTF1::GetDerivPrecision( ) { return fgEps; } // impelmentations for WrappedMultiTF1 WrappedMultiTF1::WrappedMultiTF1 (TF1 & f, unsigned int dim ) : fLinear(false), fFunc(&f), fDim(dim), fParams(f.GetParameters(),f.GetParameters()+f.GetNpar()) { // constructor of WrappedMultiTF1 // pass a dimension if dimension specified in TF1 does not correspond to real dimension // for example in case of multi-dimensional TF1 objects defined as TF1 (i.e. for functions with dims > 3 ) if (fDim == 0) fDim = fFunc->GetNdim(); // check that in case function is linear the linear terms are not zero // function is linear when is a TFormula created with "++" // hyperplane are not yet existing in TFormula if (fFunc->IsLinear() ) { unsigned int ip = 0; fLinear = true; while (fLinear && ip < fParams.size() ) { fLinear &= (fFunc->GetLinearPart(ip) != 0) ; ip++; } } // distinguish case of polynomial functions and linear functions if (fDim == 1 && fFunc->GetNumber() >= 300 && fFunc->GetNumber() < 310) { fLinear = true; fPolynomial = true; } } WrappedMultiTF1::WrappedMultiTF1(const WrappedMultiTF1 & rhs) : BaseFunc(), BaseParamFunc(), fLinear(rhs.fLinear), fPolynomial(rhs.fPolynomial), fFunc(rhs.fFunc), fDim(rhs.fDim), fParams(rhs.fParams) { // copy constructor } WrappedMultiTF1 & WrappedMultiTF1::operator= (const WrappedMultiTF1 & rhs) { // Assignment operator if (this == &rhs) return *this; // time saving self-test fLinear = rhs.fLinear; fPolynomial = rhs.fPolynomial; fFunc = rhs.fFunc; fDim = rhs.fDim; fParams = rhs.fParams; return *this; } void WrappedMultiTF1::ParameterGradient(const double * x, const double * par, double * grad ) const { // evaluate the gradient of the function with respect to the parameters //IMPORTANT NOTE: TF1::GradientPar returns 0 for fixed parameters to avoid computing useless derivatives // BUT the TLinearFitter wants to have the derivatives also for fixed parameters. // so in case of fLinear (or fPolynomial) a non-zero value will be returned for fixed parameters if (!fLinear) { // need to set parameter values fFunc->SetParameters( par ); // no need to call InitArgs (it is called in TF1::GradientPar) fFunc->GradientPar(x,grad,fgEps); } else { // case of linear functions unsigned int np = NPar(); for (unsigned int i = 0; i < np; ++i) grad[i] = DoParameterDerivative(x, par, i); } } double WrappedMultiTF1::DoParameterDerivative(const double * x, const double * p, unsigned int ipar ) const { // evaluate the derivative of the function with respect to parameter ipar // see note above concerning the fixed parameters if (! fLinear ) { fFunc->SetParameters( p ); return fFunc->GradientPar(ipar, x,fgEps); } if (fPolynomial) { // case of polynomial function (no parameter dependency) (case for dim = 1) assert (fDim == 1); return std::pow(x[0], static_cast<int>(ipar) ); } else { // case of general linear function (built in TFormula with ++ ) const TFormula * df = dynamic_cast<const TFormula*>( fFunc->GetLinearPart(ipar) ); assert(df != 0); // hack since TFormula::EvalPar is not const return (const_cast<TFormula*> ( df) )->EvalPar( x ) ; // derivatives should not depend on parameters since // function is linear } } void WrappedMultiTF1::SetDerivPrecision(double eps) { fgEps = eps; } double WrappedMultiTF1::GetDerivPrecision( ) { return fgEps; } } // end namespace Fit } // end namespace ROOT <commit_msg>fix initialization in ctor (coverity)<commit_after>// @(#)root/mathmore:$Id$ // Author: L. Moneta Wed Sep 6 09:52:26 2006 /********************************************************************** * * * Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT * * * * * **********************************************************************/ // implementation file for class WrappedTF1 and WrappedMultiTF1 #include "Math/WrappedTF1.h" #include "Math/WrappedMultiTF1.h" #include <cmath> namespace ROOT { namespace Math { // static value for epsilon used in derivative calculations double WrappedTF1::fgEps = 0.001; double WrappedMultiTF1::fgEps = 0.001; WrappedTF1::WrappedTF1 ( TF1 & f ) : fLinear(false), fPolynomial(false), fFunc(&f), fX (), fParams(f.GetParameters(),f.GetParameters()+f.GetNpar()) { // constructor from a TF1 function pointer. // init the pointers for CINT if (fFunc->GetMethodCall() ) fFunc->InitArgs(fX, &fParams.front() ); // distinguish case of polynomial functions and linear functions if (fFunc->GetNumber() >= 300 && fFunc->GetNumber() < 310) { fLinear = true; fPolynomial = true; } // check that in case function is linear the linear terms are not zero if (fFunc->IsLinear() ) { unsigned int ip = 0; fLinear = true; while (fLinear && ip < fParams.size() ) { fLinear &= (fFunc->GetLinearPart(ip) != 0) ; ip++; } } } WrappedTF1::WrappedTF1(const WrappedTF1 & rhs) : BaseFunc(), BaseGradFunc(), IGrad(), fLinear(rhs.fLinear), fPolynomial(rhs.fPolynomial), fFunc(rhs.fFunc), fX(), fParams(rhs.fParams) { // copy constructor fFunc->InitArgs(fX,&fParams.front() ); } WrappedTF1 & WrappedTF1::operator = (const WrappedTF1 & rhs) { // assignment operator if (this == &rhs) return *this; // time saving self-test fLinear = rhs.fLinear; fPolynomial = rhs.fPolynomial; fFunc = rhs.fFunc; fFunc->InitArgs(fX, &fParams.front() ); fParams = rhs.fParams; return *this; } void WrappedTF1::ParameterGradient(double x, const double * par, double * grad ) const { // evaluate the derivative of the function with respect to the parameters if (!fLinear) { // need to set parameter values fFunc->SetParameters( par ); // no need to call InitArgs (it is called in TF1::GradientPar) fFunc->GradientPar(&x,grad,fgEps); } else { unsigned int np = NPar(); for (unsigned int i = 0; i < np; ++i) grad[i] = DoParameterDerivative(x, par, i); } } double WrappedTF1::DoDerivative( double x ) const { // return the function derivatives w.r.t. x // parameter are passed as non-const in Derivative double * p = (fParams.size() > 0) ? const_cast<double *>( &fParams.front()) : 0; return fFunc->Derivative(x,p,fgEps); } double WrappedTF1::DoParameterDerivative(double x, const double * p, unsigned int ipar ) const { // evaluate the derivative of the function with respect to the parameters //IMPORTANT NOTE: TF1::GradientPar returns 0 for fixed parameters to avoid computing useless derivatives // BUT the TLinearFitter wants to have the derivatives also for fixed parameters. // so in case of fLinear (or fPolynomial) a non-zero value will be returned for fixed parameters if (! fLinear ) { fFunc->SetParameters( p ); return fFunc->GradientPar(ipar, &x,fgEps); } else if (fPolynomial) { // case of polynomial function (no parameter dependency) return std::pow(x, static_cast<int>(ipar) ); } else { // case of general linear function (built in TFormula with ++ ) const TFormula * df = dynamic_cast<const TFormula*>( fFunc->GetLinearPart(ipar) ); assert(df != 0); fX[0] = x; // hack since TFormula::EvalPar is not const return (const_cast<TFormula*> ( df) )->EvalPar( fX ) ; // derivatives should not depend on parameters since func is linear } } void WrappedTF1::SetDerivPrecision(double eps) { fgEps = eps; } double WrappedTF1::GetDerivPrecision( ) { return fgEps; } // impelmentations for WrappedMultiTF1 WrappedMultiTF1::WrappedMultiTF1 (TF1 & f, unsigned int dim ) : fLinear(false), fPolynomial(false), fFunc(&f), fDim(dim), fParams(f.GetParameters(),f.GetParameters()+f.GetNpar()) { // constructor of WrappedMultiTF1 // pass a dimension if dimension specified in TF1 does not correspond to real dimension // for example in case of multi-dimensional TF1 objects defined as TF1 (i.e. for functions with dims > 3 ) if (fDim == 0) fDim = fFunc->GetNdim(); // check that in case function is linear the linear terms are not zero // function is linear when is a TFormula created with "++" // hyperplane are not yet existing in TFormula if (fFunc->IsLinear() ) { unsigned int ip = 0; fLinear = true; while (fLinear && ip < fParams.size() ) { fLinear &= (fFunc->GetLinearPart(ip) != 0) ; ip++; } } // distinguish case of polynomial functions and linear functions if (fDim == 1 && fFunc->GetNumber() >= 300 && fFunc->GetNumber() < 310) { fLinear = true; fPolynomial = true; } } WrappedMultiTF1::WrappedMultiTF1(const WrappedMultiTF1 & rhs) : BaseFunc(), BaseParamFunc(), fLinear(rhs.fLinear), fPolynomial(rhs.fPolynomial), fFunc(rhs.fFunc), fDim(rhs.fDim), fParams(rhs.fParams) { // copy constructor } WrappedMultiTF1 & WrappedMultiTF1::operator= (const WrappedMultiTF1 & rhs) { // Assignment operator if (this == &rhs) return *this; // time saving self-test fLinear = rhs.fLinear; fPolynomial = rhs.fPolynomial; fFunc = rhs.fFunc; fDim = rhs.fDim; fParams = rhs.fParams; return *this; } void WrappedMultiTF1::ParameterGradient(const double * x, const double * par, double * grad ) const { // evaluate the gradient of the function with respect to the parameters //IMPORTANT NOTE: TF1::GradientPar returns 0 for fixed parameters to avoid computing useless derivatives // BUT the TLinearFitter wants to have the derivatives also for fixed parameters. // so in case of fLinear (or fPolynomial) a non-zero value will be returned for fixed parameters if (!fLinear) { // need to set parameter values fFunc->SetParameters( par ); // no need to call InitArgs (it is called in TF1::GradientPar) fFunc->GradientPar(x,grad,fgEps); } else { // case of linear functions unsigned int np = NPar(); for (unsigned int i = 0; i < np; ++i) grad[i] = DoParameterDerivative(x, par, i); } } double WrappedMultiTF1::DoParameterDerivative(const double * x, const double * p, unsigned int ipar ) const { // evaluate the derivative of the function with respect to parameter ipar // see note above concerning the fixed parameters if (! fLinear ) { fFunc->SetParameters( p ); return fFunc->GradientPar(ipar, x,fgEps); } if (fPolynomial) { // case of polynomial function (no parameter dependency) (case for dim = 1) assert (fDim == 1); return std::pow(x[0], static_cast<int>(ipar) ); } else { // case of general linear function (built in TFormula with ++ ) const TFormula * df = dynamic_cast<const TFormula*>( fFunc->GetLinearPart(ipar) ); assert(df != 0); // hack since TFormula::EvalPar is not const return (const_cast<TFormula*> ( df) )->EvalPar( x ) ; // derivatives should not depend on parameters since // function is linear } } void WrappedMultiTF1::SetDerivPrecision(double eps) { fgEps = eps; } double WrappedMultiTF1::GetDerivPrecision( ) { return fgEps; } } // end namespace Fit } // end namespace ROOT <|endoftext|>
<commit_before><commit_msg>random_text_writer: adding tab separator and limiting size better<commit_after><|endoftext|>
<commit_before>#pragma once #include <type_traits> #include <iterator> #include <utility> namespace helene { namespace detail { template <class Iterator, class IteratorTag> constexpr bool is_iterator_of_category_v = std::is_same<typename std::iterator_traits<Iterator>::iterator_category, IteratorTag>::value; template <class Iterator, class IteratorTag> constexpr bool is_at_least_iterator_of_category_v = std::is_base_of< IteratorTag, typename std::iterator_traits<Iterator>::iterator_category>::value; // undefined base, specialized for each iterator category template <class UnderlyingIterator, class = void> class circular_iterator_base; // specialization for UnderlyingIterator satisfying ForwardIterator template <class UnderlyingIterator> class circular_iterator_base< UnderlyingIterator, std::enable_if_t<is_iterator_of_category_v<UnderlyingIterator, std::forward_iterator_tag>>> { public: // inherited access to types from traits typedef typename std::iterator_traits<UnderlyingIterator>::value_type value_type; typedef typename std::iterator_traits<UnderlyingIterator>::difference_type difference_type; typedef typename std::iterator_traits<UnderlyingIterator>::reference reference; typedef typename std::iterator_traits<UnderlyingIterator>::pointer pointer; typedef typename std::iterator_traits<UnderlyingIterator>::iterator_category iterator_category; public: circular_iterator_base() = default; public: // ForwardIterator conformance bool operator==(const circular_iterator_base& other) const { return current_ == other.current_; } bool operator!=(const circular_iterator_base& other) const { return current_ != other.current_; } reference operator*() { return *current_; } pointer operator->() { return current_.operator->(); } protected: UnderlyingIterator current_; }; } // namespace detail /** \class circular_iterator circular_iterator.hpp <circular_iterator.hpp> * * \brief An iterator adaptor that adapts any iterator to wrap around when * incremented beyond a range determined on construction */ template <class UnderlyingIterator> class circular_iterator : public detail::circular_iterator_base<UnderlyingIterator> { public: static_assert( detail::is_at_least_iterator_of_category_v<UnderlyingIterator, std::forward_iterator_tag>, "UnderlyingIterator needs to at least satisfy ForwardIterator for its " "multipass ability"); public: circular_iterator() = default; private: }; } // namespace helene <commit_msg>Add circular_iterator_base constructor taking underlying iterator to current position. modified: include/circular_iterator.hpp<commit_after>#pragma once #include <type_traits> #include <iterator> #include <utility> namespace helene { namespace detail { template <class Iterator, class IteratorTag> constexpr bool is_iterator_of_category_v = std::is_same<typename std::iterator_traits<Iterator>::iterator_category, IteratorTag>::value; template <class Iterator, class IteratorTag> constexpr bool is_at_least_iterator_of_category_v = std::is_base_of< IteratorTag, typename std::iterator_traits<Iterator>::iterator_category>::value; // undefined base, specialized for each iterator category template <class UnderlyingIterator, class = void> class circular_iterator_base; // specialization for UnderlyingIterator satisfying ForwardIterator template <class UnderlyingIterator> class circular_iterator_base< UnderlyingIterator, std::enable_if_t<is_iterator_of_category_v<UnderlyingIterator, std::forward_iterator_tag>>> { public: // inherited access to types from traits typedef typename std::iterator_traits<UnderlyingIterator>::value_type value_type; typedef typename std::iterator_traits<UnderlyingIterator>::difference_type difference_type; typedef typename std::iterator_traits<UnderlyingIterator>::reference reference; typedef typename std::iterator_traits<UnderlyingIterator>::pointer pointer; typedef typename std::iterator_traits<UnderlyingIterator>::iterator_category iterator_category; public: circular_iterator_base() = default; circular_iterator_base(UnderlyingIterator current) : current_(current) { } public: // ForwardIterator conformance bool operator==(const circular_iterator_base& other) const { return current_ == other.current_; } bool operator!=(const circular_iterator_base& other) const { return current_ != other.current_; } reference operator*() { return *current_; } pointer operator->() { return current_.operator->(); } protected: UnderlyingIterator current_; }; } // namespace detail /** \class circular_iterator circular_iterator.hpp <circular_iterator.hpp> * * \brief An iterator adaptor that adapts any iterator to wrap around when * incremented beyond a range determined on construction */ template <class UnderlyingIterator> class circular_iterator : public detail::circular_iterator_base<UnderlyingIterator> { public: static_assert( detail::is_at_least_iterator_of_category_v<UnderlyingIterator, std::forward_iterator_tag>, "UnderlyingIterator needs to at least satisfy ForwardIterator for its " "multipass ability"); public: circular_iterator() = default; private: }; } // namespace helene <|endoftext|>
<commit_before><commit_msg>hooked up more sounds to the menus<commit_after><|endoftext|>
<commit_before>/* * OpenSSL Block Cipher * (C) 1999-2007 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/internal/openssl_engine.h> #include <openssl/evp.h> namespace Botan { namespace { /* * EVP Block Cipher */ class EVP_BlockCipher : public BlockCipher { public: void clear(); std::string name() const { return cipher_name; } BlockCipher* clone() const; EVP_BlockCipher(const EVP_CIPHER*, const std::string&); EVP_BlockCipher(const EVP_CIPHER*, const std::string&, u32bit, u32bit, u32bit); ~EVP_BlockCipher(); private: void encrypt_n(const byte in[], byte out[], size_t blocks) const; void decrypt_n(const byte in[], byte out[], size_t blocks) const; void key_schedule(const byte[], size_t); std::string cipher_name; mutable EVP_CIPHER_CTX encrypt, decrypt; }; /* * EVP Block Cipher Constructor */ EVP_BlockCipher::EVP_BlockCipher(const EVP_CIPHER* algo, const std::string& algo_name) : BlockCipher(EVP_CIPHER_block_size(algo), EVP_CIPHER_key_length(algo)), cipher_name(algo_name) { if(EVP_CIPHER_mode(algo) != EVP_CIPH_ECB_MODE) throw Invalid_Argument("EVP_BlockCipher: Non-ECB EVP was passed in"); EVP_CIPHER_CTX_init(&encrypt); EVP_CIPHER_CTX_init(&decrypt); EVP_EncryptInit_ex(&encrypt, algo, 0, 0, 0); EVP_DecryptInit_ex(&decrypt, algo, 0, 0, 0); EVP_CIPHER_CTX_set_padding(&encrypt, 0); EVP_CIPHER_CTX_set_padding(&decrypt, 0); } /* * EVP Block Cipher Constructor */ EVP_BlockCipher::EVP_BlockCipher(const EVP_CIPHER* algo, const std::string& algo_name, u32bit key_min, u32bit key_max, u32bit key_mod) : BlockCipher(EVP_CIPHER_block_size(algo), key_min, key_max, key_mod), cipher_name(algo_name) { if(EVP_CIPHER_mode(algo) != EVP_CIPH_ECB_MODE) throw Invalid_Argument("EVP_BlockCipher: Non-ECB EVP was passed in"); EVP_CIPHER_CTX_init(&encrypt); EVP_CIPHER_CTX_init(&decrypt); EVP_EncryptInit_ex(&encrypt, algo, 0, 0, 0); EVP_DecryptInit_ex(&decrypt, algo, 0, 0, 0); EVP_CIPHER_CTX_set_padding(&encrypt, 0); EVP_CIPHER_CTX_set_padding(&decrypt, 0); } /* * EVP Block Cipher Destructor */ EVP_BlockCipher::~EVP_BlockCipher() { EVP_CIPHER_CTX_cleanup(&encrypt); EVP_CIPHER_CTX_cleanup(&decrypt); } /* * Encrypt a block */ void EVP_BlockCipher::encrypt_n(const byte in[], byte out[], size_t blocks) const { int out_len = 0; EVP_EncryptUpdate(&encrypt, out, &out_len, in, blocks * BLOCK_SIZE); } /* * Decrypt a block */ void EVP_BlockCipher::decrypt_n(const byte in[], byte out[], size_t blocks) const { int out_len = 0; EVP_DecryptUpdate(&decrypt, out, &out_len, in, blocks * BLOCK_SIZE); } /* * Set the key */ void EVP_BlockCipher::key_schedule(const byte key[], size_t length) { SecureVector<byte> full_key(key, length); if(cipher_name == "TripleDES" && length == 16) { full_key += std::make_pair(key, 8); } else if(EVP_CIPHER_CTX_set_key_length(&encrypt, length) == 0 || EVP_CIPHER_CTX_set_key_length(&decrypt, length) == 0) throw Invalid_Argument("EVP_BlockCipher: Bad key length for " + cipher_name); if(cipher_name == "RC2") { EVP_CIPHER_CTX_ctrl(&encrypt, EVP_CTRL_SET_RC2_KEY_BITS, length*8, 0); EVP_CIPHER_CTX_ctrl(&decrypt, EVP_CTRL_SET_RC2_KEY_BITS, length*8, 0); } EVP_EncryptInit_ex(&encrypt, 0, 0, full_key.begin(), 0); EVP_DecryptInit_ex(&decrypt, 0, 0, full_key.begin(), 0); } /* * Return a clone of this object */ BlockCipher* EVP_BlockCipher::clone() const { return new EVP_BlockCipher(EVP_CIPHER_CTX_cipher(&encrypt), cipher_name, MINIMUM_KEYLENGTH, MAXIMUM_KEYLENGTH, KEYLENGTH_MULTIPLE); } /* * Clear memory of sensitive data */ void EVP_BlockCipher::clear() { const EVP_CIPHER* algo = EVP_CIPHER_CTX_cipher(&encrypt); EVP_CIPHER_CTX_cleanup(&encrypt); EVP_CIPHER_CTX_cleanup(&decrypt); EVP_CIPHER_CTX_init(&encrypt); EVP_CIPHER_CTX_init(&decrypt); EVP_EncryptInit_ex(&encrypt, algo, 0, 0, 0); EVP_DecryptInit_ex(&decrypt, algo, 0, 0, 0); EVP_CIPHER_CTX_set_padding(&encrypt, 0); EVP_CIPHER_CTX_set_padding(&decrypt, 0); } } /* * Look for an algorithm with this name */ BlockCipher* OpenSSL_Engine::find_block_cipher(const SCAN_Name& request, Algorithm_Factory&) const { #define HANDLE_EVP_CIPHER(NAME, EVP) \ if(request.algo_name() == NAME && request.arg_count() == 0) \ return new EVP_BlockCipher(EVP, NAME); #define HANDLE_EVP_CIPHER_KEYLEN(NAME, EVP, MIN, MAX, MOD) \ if(request.algo_name() == NAME && request.arg_count() == 0) \ return new EVP_BlockCipher(EVP, NAME, MIN, MAX, MOD); #if !defined(OPENSSL_NO_AES) /* Using OpenSSL's AES causes crashes inside EVP on x86-64 with OpenSSL 0.9.8g cause is unknown */ HANDLE_EVP_CIPHER("AES-128", EVP_aes_128_ecb()); HANDLE_EVP_CIPHER("AES-192", EVP_aes_192_ecb()); HANDLE_EVP_CIPHER("AES-256", EVP_aes_256_ecb()); #endif #if !defined(OPENSSL_NO_DES) HANDLE_EVP_CIPHER("DES", EVP_des_ecb()); HANDLE_EVP_CIPHER_KEYLEN("TripleDES", EVP_des_ede3_ecb(), 16, 24, 8); #endif #if !defined(OPENSSL_NO_BF) HANDLE_EVP_CIPHER_KEYLEN("Blowfish", EVP_bf_ecb(), 1, 56, 1); #endif #if !defined(OPENSSL_NO_CAST) HANDLE_EVP_CIPHER_KEYLEN("CAST-128", EVP_cast5_ecb(), 1, 16, 1); #endif #if !defined(OPENSSL_NO_CAMELLIA) HANDLE_EVP_CIPHER("Camellia-128", EVP_camellia_128_ecb()); HANDLE_EVP_CIPHER("Camellia-192", EVP_camellia_192_ecb()); HANDLE_EVP_CIPHER("Camellia-256", EVP_camellia_256_ecb()); #endif #if !defined(OPENSSL_NO_RC2) HANDLE_EVP_CIPHER_KEYLEN("RC2", EVP_rc2_ecb(), 1, 32, 1); #endif #if !defined(OPENSSL_NO_RC5) && 0 if(request.algo_name() == "RC5") if(request.arg_as_integer(0, 12) == 12) return new EVP_BlockCipher(EVP_rc5_32_12_16_ecb(), "RC5(12)", 1, 32, 1); #endif #if !defined(OPENSSL_NO_IDEA) && 0 HANDLE_EVP_CIPHER("IDEA", EVP_idea_ecb()); #endif #if !defined(OPENSSL_NO_SEED) HANDLE_EVP_CIPHER("SEED", EVP_seed_ecb()); #endif #undef HANDLE_EVP_CIPHER #undef HANDLE_EVP_CIPHER_KEYLEN return 0; } } <commit_msg>Compile fix<commit_after>/* * OpenSSL Block Cipher * (C) 1999-2010 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/internal/openssl_engine.h> #include <openssl/evp.h> namespace Botan { namespace { /* * EVP Block Cipher */ class EVP_BlockCipher : public BlockCipher { public: void clear(); std::string name() const { return cipher_name; } BlockCipher* clone() const; size_t block_size() const { return block_sz; } EVP_BlockCipher(const EVP_CIPHER*, const std::string&); EVP_BlockCipher(const EVP_CIPHER*, const std::string&, u32bit, u32bit, u32bit); ~EVP_BlockCipher(); private: void encrypt_n(const byte in[], byte out[], size_t blocks) const; void decrypt_n(const byte in[], byte out[], size_t blocks) const; void key_schedule(const byte[], size_t); size_t block_sz; std::string cipher_name; mutable EVP_CIPHER_CTX encrypt, decrypt; }; /* * EVP Block Cipher Constructor */ EVP_BlockCipher::EVP_BlockCipher(const EVP_CIPHER* algo, const std::string& algo_name) : BlockCipher(EVP_CIPHER_key_length(algo)), block_sz(EVP_CIPHER_block_size(algo)), cipher_name(algo_name) { if(EVP_CIPHER_mode(algo) != EVP_CIPH_ECB_MODE) throw Invalid_Argument("EVP_BlockCipher: Non-ECB EVP was passed in"); EVP_CIPHER_CTX_init(&encrypt); EVP_CIPHER_CTX_init(&decrypt); EVP_EncryptInit_ex(&encrypt, algo, 0, 0, 0); EVP_DecryptInit_ex(&decrypt, algo, 0, 0, 0); EVP_CIPHER_CTX_set_padding(&encrypt, 0); EVP_CIPHER_CTX_set_padding(&decrypt, 0); } /* * EVP Block Cipher Constructor */ EVP_BlockCipher::EVP_BlockCipher(const EVP_CIPHER* algo, const std::string& algo_name, u32bit key_min, u32bit key_max, u32bit key_mod) : BlockCipher(key_min, key_max, key_mod), block_sz(EVP_CIPHER_block_size(algo)), cipher_name(algo_name) { if(EVP_CIPHER_mode(algo) != EVP_CIPH_ECB_MODE) throw Invalid_Argument("EVP_BlockCipher: Non-ECB EVP was passed in"); EVP_CIPHER_CTX_init(&encrypt); EVP_CIPHER_CTX_init(&decrypt); EVP_EncryptInit_ex(&encrypt, algo, 0, 0, 0); EVP_DecryptInit_ex(&decrypt, algo, 0, 0, 0); EVP_CIPHER_CTX_set_padding(&encrypt, 0); EVP_CIPHER_CTX_set_padding(&decrypt, 0); } /* * EVP Block Cipher Destructor */ EVP_BlockCipher::~EVP_BlockCipher() { EVP_CIPHER_CTX_cleanup(&encrypt); EVP_CIPHER_CTX_cleanup(&decrypt); } /* * Encrypt a block */ void EVP_BlockCipher::encrypt_n(const byte in[], byte out[], size_t blocks) const { int out_len = 0; EVP_EncryptUpdate(&encrypt, out, &out_len, in, blocks * block_sz); } /* * Decrypt a block */ void EVP_BlockCipher::decrypt_n(const byte in[], byte out[], size_t blocks) const { int out_len = 0; EVP_DecryptUpdate(&decrypt, out, &out_len, in, blocks * block_sz); } /* * Set the key */ void EVP_BlockCipher::key_schedule(const byte key[], size_t length) { SecureVector<byte> full_key(key, length); if(cipher_name == "TripleDES" && length == 16) { full_key += std::make_pair(key, 8); } else if(EVP_CIPHER_CTX_set_key_length(&encrypt, length) == 0 || EVP_CIPHER_CTX_set_key_length(&decrypt, length) == 0) throw Invalid_Argument("EVP_BlockCipher: Bad key length for " + cipher_name); if(cipher_name == "RC2") { EVP_CIPHER_CTX_ctrl(&encrypt, EVP_CTRL_SET_RC2_KEY_BITS, length*8, 0); EVP_CIPHER_CTX_ctrl(&decrypt, EVP_CTRL_SET_RC2_KEY_BITS, length*8, 0); } EVP_EncryptInit_ex(&encrypt, 0, 0, full_key.begin(), 0); EVP_DecryptInit_ex(&decrypt, 0, 0, full_key.begin(), 0); } /* * Return a clone of this object */ BlockCipher* EVP_BlockCipher::clone() const { return new EVP_BlockCipher(EVP_CIPHER_CTX_cipher(&encrypt), cipher_name, MINIMUM_KEYLENGTH, MAXIMUM_KEYLENGTH, KEYLENGTH_MULTIPLE); } /* * Clear memory of sensitive data */ void EVP_BlockCipher::clear() { const EVP_CIPHER* algo = EVP_CIPHER_CTX_cipher(&encrypt); EVP_CIPHER_CTX_cleanup(&encrypt); EVP_CIPHER_CTX_cleanup(&decrypt); EVP_CIPHER_CTX_init(&encrypt); EVP_CIPHER_CTX_init(&decrypt); EVP_EncryptInit_ex(&encrypt, algo, 0, 0, 0); EVP_DecryptInit_ex(&decrypt, algo, 0, 0, 0); EVP_CIPHER_CTX_set_padding(&encrypt, 0); EVP_CIPHER_CTX_set_padding(&decrypt, 0); } } /* * Look for an algorithm with this name */ BlockCipher* OpenSSL_Engine::find_block_cipher(const SCAN_Name& request, Algorithm_Factory&) const { #define HANDLE_EVP_CIPHER(NAME, EVP) \ if(request.algo_name() == NAME && request.arg_count() == 0) \ return new EVP_BlockCipher(EVP, NAME); #define HANDLE_EVP_CIPHER_KEYLEN(NAME, EVP, MIN, MAX, MOD) \ if(request.algo_name() == NAME && request.arg_count() == 0) \ return new EVP_BlockCipher(EVP, NAME, MIN, MAX, MOD); #if !defined(OPENSSL_NO_AES) /* Using OpenSSL's AES causes crashes inside EVP on x86-64 with OpenSSL 0.9.8g cause is unknown */ HANDLE_EVP_CIPHER("AES-128", EVP_aes_128_ecb()); HANDLE_EVP_CIPHER("AES-192", EVP_aes_192_ecb()); HANDLE_EVP_CIPHER("AES-256", EVP_aes_256_ecb()); #endif #if !defined(OPENSSL_NO_DES) HANDLE_EVP_CIPHER("DES", EVP_des_ecb()); HANDLE_EVP_CIPHER_KEYLEN("TripleDES", EVP_des_ede3_ecb(), 16, 24, 8); #endif #if !defined(OPENSSL_NO_BF) HANDLE_EVP_CIPHER_KEYLEN("Blowfish", EVP_bf_ecb(), 1, 56, 1); #endif #if !defined(OPENSSL_NO_CAST) HANDLE_EVP_CIPHER_KEYLEN("CAST-128", EVP_cast5_ecb(), 1, 16, 1); #endif #if !defined(OPENSSL_NO_CAMELLIA) HANDLE_EVP_CIPHER("Camellia-128", EVP_camellia_128_ecb()); HANDLE_EVP_CIPHER("Camellia-192", EVP_camellia_192_ecb()); HANDLE_EVP_CIPHER("Camellia-256", EVP_camellia_256_ecb()); #endif #if !defined(OPENSSL_NO_RC2) HANDLE_EVP_CIPHER_KEYLEN("RC2", EVP_rc2_ecb(), 1, 32, 1); #endif #if !defined(OPENSSL_NO_RC5) && 0 if(request.algo_name() == "RC5") if(request.arg_as_integer(0, 12) == 12) return new EVP_BlockCipher(EVP_rc5_32_12_16_ecb(), "RC5(12)", 1, 32, 1); #endif #if !defined(OPENSSL_NO_IDEA) && 0 HANDLE_EVP_CIPHER("IDEA", EVP_idea_ecb()); #endif #if !defined(OPENSSL_NO_SEED) HANDLE_EVP_CIPHER("SEED", EVP_seed_ecb()); #endif #undef HANDLE_EVP_CIPHER #undef HANDLE_EVP_CIPHER_KEYLEN return 0; } } <|endoftext|>
<commit_before>#ifndef ASTI_CONSTANT_ITER_HPP #define ASTI_CONSTANT_ITER_HPP #include <iterator> namespace util { template <typename T> struct constant_iterator: std::iterator<std::input_iterator_tag, T> { constant_iterator(T v_,std::ptrdiff_t idx_=0): v(v_), idx(idx_) { } constant_iterator(const constant_iterator&other) :v(other.v),idx(other.idx) { } T operator*() const { return v; } constant_iterator& operator+=(std::ptrdiff_t sz) { idx+=sz; return *this; } T operator[](size_t i) const { return v;} constant_iterator& operator++() { // pretend to preincrement ++idx; return (*this); } constant_iterator operator++(int) { // pretend to postincrement constant_iterator tmp(*this); ++idx; return tmp; } constant_iterator& operator--() { // pretend to preincrement --idx; return (*this); } constant_iterator operator--(int) { // pretend to postincrement constant_iterator tmp(*this); --idx; return tmp; } T v; std::ptrdiff_t idx; }; template <class T> constant_iterator<T> operator+(constant_iterator<T>& it, std::ptrdiff_t sz) { constant_iterator<T> it_(it); it_+=sz; return it_; } template <class T> bool operator==(const constant_iterator<T>&it1, const constant_iterator<T>&it2) { return std::make_pair(it1.v,it1.idx)==std::make_pair(it2.v,it2.idx); } template <class T> bool operator!=(const constant_iterator<T>&it1, const constant_iterator<T>&it2) { return std::make_pair(it1.v,it1.idx)!=std::make_pair(it2.v,it2.idx); } template <class T> constant_iterator<T> make_constant_iterator( T v, std::ptrdiff_t idx=0) { return constant_iterator<T>(v, idx) ; } } namespace std { template<class T> struct _Is_checked_helper<util::constant_iterator<T> > : public true_type { // mark constant_iterator as checked }; } #endif //CONSTANT_ITER_HPP <commit_msg>Fix compiler errors<commit_after>#ifndef ASTI_CONSTANT_ITER_HPP #define ASTI_CONSTANT_ITER_HPP #include <iterator> namespace util { template <typename T> struct constant_iterator: std::iterator<std::input_iterator_tag, T> { constant_iterator(T v_,std::ptrdiff_t idx_=0): v(v_), idx(idx_) { } constant_iterator(const constant_iterator&other) :v(other.v),idx(other.idx) { } T operator*() const { return v; } constant_iterator& operator+=(std::ptrdiff_t sz) { idx+=sz; return *this; } T operator[](size_t i) const { return v;} constant_iterator& operator++() { // pretend to preincrement ++idx; return (*this); } constant_iterator operator++(int) { // pretend to postincrement constant_iterator tmp(*this); ++idx; return tmp; } constant_iterator& operator--() { // pretend to preincrement --idx; return (*this); } constant_iterator operator--(int) { // pretend to postincrement constant_iterator tmp(*this); --idx; return tmp; } T v; std::ptrdiff_t idx; }; template <class T> constant_iterator<T> operator+(constant_iterator<T>& it, std::ptrdiff_t sz) { constant_iterator<T> it_(it); it_+=sz; return it_; } template <class T> bool operator==(const constant_iterator<T>&it1, const constant_iterator<T>&it2) { return std::make_pair(it1.v,it1.idx)==std::make_pair(it2.v,it2.idx); } template <class T> bool operator!=(const constant_iterator<T>&it1, const constant_iterator<T>&it2) { return std::make_pair(it1.v,it1.idx)!=std::make_pair(it2.v,it2.idx); } template <class T> constant_iterator<T> make_constant_iterator( T v, std::ptrdiff_t idx=0) { return constant_iterator<T>(v, idx) ; } } #ifdef WIN32 //msvc checked iter namespace std { template<class T> struct _Is_checked_helper<util::constant_iterator<T> > : public true_type { // mark constant_iterator as checked }; } #endif #endif //CONSTANT_ITER_HPP <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * drawElements Quality Program EGL Module * --------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Simple Context construction test. *//*--------------------------------------------------------------------*/ #include "teglCreateContextTests.hpp" #include "teglSimpleConfigCase.hpp" #include "egluStrUtil.hpp" #include "egluUtil.hpp" #include "egluUnique.hpp" #include "eglwLibrary.hpp" #include "eglwEnums.hpp" #include "tcuTestLog.hpp" #include "deSTLUtil.hpp" namespace deqp { namespace egl { using std::vector; using tcu::TestLog; using namespace eglw; static const EGLint s_es1Attrs[] = { EGL_CONTEXT_CLIENT_VERSION, 1, EGL_NONE }; static const EGLint s_es2Attrs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; static const EGLint s_es3Attrs[] = { EGL_CONTEXT_MAJOR_VERSION_KHR, 3, EGL_NONE }; static const struct { const char* name; EGLenum api; EGLint apiBit; const EGLint* ctxAttrs; } s_apis[] = { { "OpenGL", EGL_OPENGL_API, EGL_OPENGL_BIT, DE_NULL }, { "OpenGL ES 1", EGL_OPENGL_ES_API, EGL_OPENGL_ES_BIT, s_es1Attrs }, { "OpenGL ES 2", EGL_OPENGL_ES_API, EGL_OPENGL_ES2_BIT, s_es2Attrs }, { "OpenGL ES 3", EGL_OPENGL_ES_API, EGL_OPENGL_ES3_BIT_KHR, s_es3Attrs }, { "OpenVG", EGL_OPENVG_API, EGL_OPENVG_BIT, DE_NULL } }; class CreateContextCase : public SimpleConfigCase { public: CreateContextCase (EglTestContext& eglTestCtx, const char* name, const char* description, const eglu::FilterList& filters); ~CreateContextCase (void); void executeForConfig (EGLDisplay display, EGLConfig config); }; CreateContextCase::CreateContextCase (EglTestContext& eglTestCtx, const char* name, const char* description, const eglu::FilterList& filters) : SimpleConfigCase(eglTestCtx, name, description, filters) { } CreateContextCase::~CreateContextCase (void) { } void CreateContextCase::executeForConfig (EGLDisplay display, EGLConfig config) { const Library& egl = m_eglTestCtx.getLibrary(); TestLog& log = m_testCtx.getLog(); EGLint id = eglu::getConfigAttribInt(egl, display, config, EGL_CONFIG_ID); EGLint apiBits = eglu::getConfigAttribInt(egl, display, config, EGL_RENDERABLE_TYPE); for (int apiNdx = 0; apiNdx < (int)DE_LENGTH_OF_ARRAY(s_apis); apiNdx++) { if ((apiBits & s_apis[apiNdx].apiBit) == 0) continue; // Not supported API log << TestLog::Message << "Creating " << s_apis[apiNdx].name << " context with config ID " << id << TestLog::EndMessage; EGLU_CHECK_MSG(egl, "init"); EGLU_CHECK_CALL(egl, bindAPI(s_apis[apiNdx].api)); EGLContext context = egl.createContext(display, config, EGL_NO_CONTEXT, s_apis[apiNdx].ctxAttrs); EGLenum err = egl.getError(); if (context == EGL_NO_CONTEXT || err != EGL_SUCCESS) { log << TestLog::Message << " Fail, context: " << tcu::toHex(context) << ", error: " << eglu::getErrorName(err) << TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Failed to create context"); } else { // Destroy EGLU_CHECK_CALL(egl, destroyContext(display, context)); log << TestLog::Message << " Pass" << TestLog::EndMessage; } } } class CreateContextNoConfigCase : public TestCase { public: CreateContextNoConfigCase (EglTestContext& eglTestCtx) : TestCase(eglTestCtx, "no_config", "EGL_KHR_no_config_context") { } IterateResult iterate (void) { const eglw::Library& egl = m_eglTestCtx.getLibrary(); const eglu::UniqueDisplay display (egl, eglu::getAndInitDisplay(m_eglTestCtx.getNativeDisplay(), DE_NULL)); tcu::TestLog& log = m_testCtx.getLog(); if (!eglu::hasExtension(egl, *display, "EGL_KHR_no_config_context")) TCU_THROW(NotSupportedError, "EGL_KHR_no_config_context is not supported"); for (int apiNdx = 0; apiNdx < (int)DE_LENGTH_OF_ARRAY(s_apis); apiNdx++) { const EGLenum api = s_apis[apiNdx].api; if (egl.bindAPI(api) != EGL_FALSE) { TCU_CHECK(egl.getError() == EGL_BAD_PARAMETER); log << TestLog::Message << "eglBindAPI(" << eglu::getAPIStr(api) << ") failed, skipping" << TestLog::EndMessage; continue; } log << TestLog::Message << "Creating " << s_apis[apiNdx].name << " context" << TestLog::EndMessage; const EGLContext context = egl.createContext(*display, (EGLConfig)0, EGL_NO_CONTEXT, s_apis[apiNdx].ctxAttrs); const EGLenum err = egl.getError(); if (context == EGL_NO_CONTEXT || err != EGL_SUCCESS) { log << TestLog::Message << " Fail, context: " << tcu::toHex(context) << ", error: " << eglu::getErrorName(err) << TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Failed to create context"); } else { // Destroy EGLU_CHECK_CALL(egl, destroyContext(*display, context)); log << TestLog::Message << " Pass" << TestLog::EndMessage; } } return STOP; } }; CreateContextTests::CreateContextTests (EglTestContext& eglTestCtx) : TestCaseGroup(eglTestCtx, "create_context", "Basic eglCreateContext() tests") { } CreateContextTests::~CreateContextTests (void) { } void CreateContextTests::init (void) { vector<NamedFilterList> filterLists; getDefaultFilterLists(filterLists, eglu::FilterList()); for (vector<NamedFilterList>::iterator i = filterLists.begin(); i != filterLists.end(); i++) addChild(new CreateContextCase(m_eglTestCtx, i->getName(), i->getDescription(), *i)); addChild(new CreateContextNoConfigCase(m_eglTestCtx)); } } // egl } // deqp <commit_msg>Fix a few bugs in a EGL_KHR_no_config_context test. am: 2a2a2ab8c7 am: e06124d7f5 am: 08bf23d700<commit_after>/*------------------------------------------------------------------------- * drawElements Quality Program EGL Module * --------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Simple Context construction test. *//*--------------------------------------------------------------------*/ #include "teglCreateContextTests.hpp" #include "teglSimpleConfigCase.hpp" #include "egluStrUtil.hpp" #include "egluUtil.hpp" #include "egluUnique.hpp" #include "eglwLibrary.hpp" #include "eglwEnums.hpp" #include "tcuTestLog.hpp" #include "deSTLUtil.hpp" namespace deqp { namespace egl { using std::vector; using tcu::TestLog; using namespace eglw; static const EGLint s_es1Attrs[] = { EGL_CONTEXT_CLIENT_VERSION, 1, EGL_NONE }; static const EGLint s_es2Attrs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; static const EGLint s_es3Attrs[] = { EGL_CONTEXT_MAJOR_VERSION_KHR, 3, EGL_NONE }; static const struct { const char* name; EGLenum api; EGLint apiBit; const EGLint* ctxAttrs; } s_apis[] = { { "OpenGL", EGL_OPENGL_API, EGL_OPENGL_BIT, DE_NULL }, { "OpenGL ES 1", EGL_OPENGL_ES_API, EGL_OPENGL_ES_BIT, s_es1Attrs }, { "OpenGL ES 2", EGL_OPENGL_ES_API, EGL_OPENGL_ES2_BIT, s_es2Attrs }, { "OpenGL ES 3", EGL_OPENGL_ES_API, EGL_OPENGL_ES3_BIT_KHR, s_es3Attrs }, { "OpenVG", EGL_OPENVG_API, EGL_OPENVG_BIT, DE_NULL } }; class CreateContextCase : public SimpleConfigCase { public: CreateContextCase (EglTestContext& eglTestCtx, const char* name, const char* description, const eglu::FilterList& filters); ~CreateContextCase (void); void executeForConfig (EGLDisplay display, EGLConfig config); }; CreateContextCase::CreateContextCase (EglTestContext& eglTestCtx, const char* name, const char* description, const eglu::FilterList& filters) : SimpleConfigCase(eglTestCtx, name, description, filters) { } CreateContextCase::~CreateContextCase (void) { } void CreateContextCase::executeForConfig (EGLDisplay display, EGLConfig config) { const Library& egl = m_eglTestCtx.getLibrary(); TestLog& log = m_testCtx.getLog(); EGLint id = eglu::getConfigAttribInt(egl, display, config, EGL_CONFIG_ID); EGLint apiBits = eglu::getConfigAttribInt(egl, display, config, EGL_RENDERABLE_TYPE); for (int apiNdx = 0; apiNdx < (int)DE_LENGTH_OF_ARRAY(s_apis); apiNdx++) { if ((apiBits & s_apis[apiNdx].apiBit) == 0) continue; // Not supported API log << TestLog::Message << "Creating " << s_apis[apiNdx].name << " context with config ID " << id << TestLog::EndMessage; EGLU_CHECK_MSG(egl, "init"); EGLU_CHECK_CALL(egl, bindAPI(s_apis[apiNdx].api)); EGLContext context = egl.createContext(display, config, EGL_NO_CONTEXT, s_apis[apiNdx].ctxAttrs); EGLenum err = egl.getError(); if (context == EGL_NO_CONTEXT || err != EGL_SUCCESS) { log << TestLog::Message << " Fail, context: " << tcu::toHex(context) << ", error: " << eglu::getErrorName(err) << TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Failed to create context"); } else { // Destroy EGLU_CHECK_CALL(egl, destroyContext(display, context)); log << TestLog::Message << " Pass" << TestLog::EndMessage; } } } class CreateContextNoConfigCase : public TestCase { public: CreateContextNoConfigCase (EglTestContext& eglTestCtx) : TestCase(eglTestCtx, "no_config", "EGL_KHR_no_config_context") { } IterateResult iterate (void) { const eglw::Library& egl = m_eglTestCtx.getLibrary(); const eglu::UniqueDisplay display (egl, eglu::getAndInitDisplay(m_eglTestCtx.getNativeDisplay(), DE_NULL)); tcu::TestLog& log = m_testCtx.getLog(); if (!eglu::hasExtension(egl, *display, "EGL_KHR_no_config_context")) TCU_THROW(NotSupportedError, "EGL_KHR_no_config_context is not supported"); m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "pass"); for (int apiNdx = 0; apiNdx < (int)DE_LENGTH_OF_ARRAY(s_apis); apiNdx++) { const EGLenum api = s_apis[apiNdx].api; if (egl.bindAPI(api) == EGL_FALSE) { TCU_CHECK(egl.getError() == EGL_BAD_PARAMETER); log << TestLog::Message << "eglBindAPI(" << eglu::getAPIStr(api) << ") failed, skipping" << TestLog::EndMessage; continue; } log << TestLog::Message << "Creating " << s_apis[apiNdx].name << " context" << TestLog::EndMessage; const EGLContext context = egl.createContext(*display, (EGLConfig)0, EGL_NO_CONTEXT, s_apis[apiNdx].ctxAttrs); const EGLenum err = egl.getError(); if (context == EGL_NO_CONTEXT || err != EGL_SUCCESS) { log << TestLog::Message << " Fail, context: " << tcu::toHex(context) << ", error: " << eglu::getErrorName(err) << TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Failed to create context"); } else { // Destroy EGLU_CHECK_CALL(egl, destroyContext(*display, context)); log << TestLog::Message << " Pass" << TestLog::EndMessage; } } return STOP; } }; CreateContextTests::CreateContextTests (EglTestContext& eglTestCtx) : TestCaseGroup(eglTestCtx, "create_context", "Basic eglCreateContext() tests") { } CreateContextTests::~CreateContextTests (void) { } void CreateContextTests::init (void) { vector<NamedFilterList> filterLists; getDefaultFilterLists(filterLists, eglu::FilterList()); for (vector<NamedFilterList>::iterator i = filterLists.begin(); i != filterLists.end(); i++) addChild(new CreateContextCase(m_eglTestCtx, i->getName(), i->getDescription(), *i)); addChild(new CreateContextNoConfigCase(m_eglTestCtx)); } } // egl } // deqp <|endoftext|>
<commit_before>/* qgvdial is a cross platform Google Voice Dialer Copyright (C) 2010 Yuvraaj Kelkar This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Contact: [email protected] */ #include "DialContext.h" #include "Singletons.h" DialContext::DialContext (const QString &strMy, const QString &strT, QDeclarativeView *mV) : QObject(mV) , bDialOut (false) , ci (NULL) , strMyNumber (strMy) , strTarget (strT) , fallbackCi (NULL) , mainView (mV) { QObject *pRoot = mainView->rootObject (); bool rv = connect (pRoot, SIGNAL (sigMsgBoxDone(bool)), this , SLOT (onSigMsgBoxDone(bool))); Q_ASSERT(rv); Q_UNUSED(rv); }//DialContext::DialContext DialContext::~DialContext() { hideMsgBox (); }//DialContext::~DialContext void DialContext::showMsgBox () { ObserverFactory &obsF = Singletons::getRef().getObserverFactory (); obsF.startObservers (strMyNumber, this, SLOT (callStarted())); QString strMessage = QString("Dialing\n%1").arg(strTarget); QDeclarativeContext *ctx = mainView->rootContext(); bool bTemp = true; ctx->setContextProperty ("g_bShowMsg", bTemp); ctx->setContextProperty ("g_strMsgText", strMessage); }//DialContext::showMsgBox void DialContext::hideMsgBox () { QDeclarativeContext *ctx = mainView->rootContext(); bool bTemp = false; ctx->setContextProperty ("g_bShowMsg", bTemp); }//DialContext::hideMsgBox void DialContext::callStarted () { onSigMsgBoxDone (true); }//DialContext::callStarted void DialContext::onSigMsgBoxDone (bool ok) { ObserverFactory &obsF = Singletons::getRef().getObserverFactory (); obsF.stopObservers (); hideMsgBox (); emit sigDialComplete (this, ok); }//DialContext::onSigMsgBoxDone <commit_msg>Dial context failed to get the correct pointer for the MainPage.<commit_after>/* qgvdial is a cross platform Google Voice Dialer Copyright (C) 2010 Yuvraaj Kelkar This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Contact: [email protected] */ #include "DialContext.h" #include "Singletons.h" DialContext::DialContext (const QString &strMy, const QString &strT, QDeclarativeView *mV) : QObject(mV) , bDialOut (false) , ci (NULL) , strMyNumber (strMy) , strTarget (strT) , fallbackCi (NULL) , mainView (mV) { QObject *pMain = NULL; do { // Begin cleanup block (not a loop) QObject *pRoot = mainView->rootObject (); if (NULL == pRoot) { qWarning ("Couldn't get root object in QML for MainPage"); break; } if (pRoot->objectName() == "MainPage") { pMain = pRoot; break; } pMain = pRoot->findChild <QObject*> ("MainPage"); if (NULL == pMain) { qWarning ("Could not get to MainPage"); break; } } while (0); // End cleanup block (not a loop) bool rv = connect (pMain, SIGNAL (sigMsgBoxDone(bool)), this , SLOT (onSigMsgBoxDone(bool))); Q_ASSERT(rv); Q_UNUSED(rv); }//DialContext::DialContext DialContext::~DialContext() { hideMsgBox (); }//DialContext::~DialContext void DialContext::showMsgBox () { ObserverFactory &obsF = Singletons::getRef().getObserverFactory (); obsF.startObservers (strMyNumber, this, SLOT (callStarted())); QString strMessage = QString("Dialing\n%1").arg(strTarget); QDeclarativeContext *ctx = mainView->rootContext(); bool bTemp = true; ctx->setContextProperty ("g_bShowMsg", bTemp); ctx->setContextProperty ("g_strMsgText", strMessage); }//DialContext::showMsgBox void DialContext::hideMsgBox () { QDeclarativeContext *ctx = mainView->rootContext(); bool bTemp = false; ctx->setContextProperty ("g_bShowMsg", bTemp); }//DialContext::hideMsgBox void DialContext::callStarted () { onSigMsgBoxDone (true); }//DialContext::callStarted void DialContext::onSigMsgBoxDone (bool ok) { ObserverFactory &obsF = Singletons::getRef().getObserverFactory (); obsF.stopObservers (); hideMsgBox (); emit sigDialComplete (this, ok); }//DialContext::onSigMsgBoxDone <|endoftext|>
<commit_before>#include <catch.hpp> #include "Chip8.hpp" #include "CPU.hpp" namespace { using namespace Core8; SCENARIO("CPUs can skip instructions if a register equals a constant value", "[conditional]") { GIVEN("A CPU with some initialized registers") { CPU cpu{}; cpu.writeRegister(Chip8::REGISTER::V1, 0x11); cpu.writeRegister(Chip8::REGISTER::V4, 0x35); const auto pc0 = cpu.getPc(); WHEN("the CPU executes a skip op comparing a matching register and constant") { cpu.setInstruction(0x3111); cpu.decode(); cpu.execute(); const auto pc1 = cpu.getPc(); cpu.setInstruction(0x3435); cpu.decode(); cpu.execute(); const auto pc2 = cpu.getPc(); THEN("the CPUs program counter is updated") { REQUIRE(pc1 == pc0 + Chip8::INSTRUCTION_BYTE_SIZE); REQUIRE(pc2 == pc0 + 2 * Chip8::INSTRUCTION_BYTE_SIZE); } } AND_WHEN("the CPU executes a skip op comparing a non-matching register and constant") { cpu.setInstruction(0x31FF); cpu.decode(); cpu.execute(); const auto pc1 = cpu.getPc(); cpu.setInstruction(0x34EE); cpu.decode(); cpu.execute(); const auto pc2 = cpu.getPc(); THEN("the CPUs program counter is remains unchanged") { REQUIRE(pc1 == pc0); REQUIRE(pc2 == pc0); } } } } SCENARIO("CPUs can skip instructions if a register differs from a constant", "[conditional]") { GIVEN("A CPU with some initialized registers") { CPU cpu{}; cpu.writeRegister(Chip8::REGISTER::VA, 0x1A); cpu.writeRegister(Chip8::REGISTER::VB, 0x2B); const auto pc0 = cpu.getPc(); WHEN("the CPU executes a skip op comparing a non-matching register and constant") { cpu.setInstruction(0x4AA1); cpu.decode(); cpu.execute(); const auto pc1 = cpu.getPc(); cpu.setInstruction(0x4BB2); cpu.decode(); cpu.execute(); const auto pc2 = cpu.getPc(); THEN("the CPUs program counter is updated") { REQUIRE(pc1 == pc0 + Chip8::INSTRUCTION_BYTE_SIZE); REQUIRE(pc2 == pc0 + 2 * Chip8::INSTRUCTION_BYTE_SIZE); } } AND_WHEN("the CPU executes a skip op comparing a matching register and constant") { cpu.setInstruction(0x4A1A); cpu.decode(); cpu.execute(); const auto pc1 = cpu.getPc(); cpu.setInstruction(0x4B2B); cpu.decode(); cpu.execute(); const auto pc2 = cpu.getPc(); THEN("the CPUs program counter is updated") { REQUIRE(pc1 == pc0); REQUIRE(pc2 == pc0); } } } } } // unnamed namespace<commit_msg>Fix test description<commit_after>#include <catch.hpp> #include "Chip8.hpp" #include "CPU.hpp" namespace { using namespace Core8; SCENARIO("CPUs can skip instructions if a register equals a constant value", "[conditional]") { GIVEN("A CPU with some initialized registers") { CPU cpu{}; cpu.writeRegister(Chip8::REGISTER::V1, 0x11); cpu.writeRegister(Chip8::REGISTER::V4, 0x35); const auto pc0 = cpu.getPc(); WHEN("the CPU executes a 3XNN opcode on matching register x constant") { cpu.setInstruction(0x3111); cpu.decode(); cpu.execute(); const auto pc1 = cpu.getPc(); cpu.setInstruction(0x3435); cpu.decode(); cpu.execute(); const auto pc2 = cpu.getPc(); THEN("the CPUs program counter is updated") { REQUIRE(pc1 == pc0 + Chip8::INSTRUCTION_BYTE_SIZE); REQUIRE(pc2 == pc0 + 2 * Chip8::INSTRUCTION_BYTE_SIZE); } } AND_WHEN("the CPU executes a 3XNN opcode on non-matching register x constant") { cpu.setInstruction(0x31FF); cpu.decode(); cpu.execute(); const auto pc1 = cpu.getPc(); cpu.setInstruction(0x34EE); cpu.decode(); cpu.execute(); const auto pc2 = cpu.getPc(); THEN("the CPUs program counter is remains unchanged") { REQUIRE(pc1 == pc0); REQUIRE(pc2 == pc0); } } } } SCENARIO("CPUs can skip instructions if a register differs from a constant", "[conditional]") { GIVEN("A CPU with some initialized registers") { CPU cpu{}; cpu.writeRegister(Chip8::REGISTER::VA, 0x1A); cpu.writeRegister(Chip8::REGISTER::VB, 0x2B); const auto pc0 = cpu.getPc(); WHEN("the CPU executes a 4XNN opcode on non-matching register x constant") { cpu.setInstruction(0x4AA1); cpu.decode(); cpu.execute(); const auto pc1 = cpu.getPc(); cpu.setInstruction(0x4BB2); cpu.decode(); cpu.execute(); const auto pc2 = cpu.getPc(); THEN("the CPUs program counter is updated") { REQUIRE(pc1 == pc0 + Chip8::INSTRUCTION_BYTE_SIZE); REQUIRE(pc2 == pc0 + 2 * Chip8::INSTRUCTION_BYTE_SIZE); } } WHEN("the CPU executes a 4XNN opcode on matching register x constant") { cpu.setInstruction(0x4A1A); cpu.decode(); cpu.execute(); const auto pc1 = cpu.getPc(); cpu.setInstruction(0x4B2B); cpu.decode(); cpu.execute(); const auto pc2 = cpu.getPc(); THEN("the CPUs program counter is remains unchanged") { REQUIRE(pc1 == pc0); REQUIRE(pc2 == pc0); } } } } } // unnamed namespace<|endoftext|>
<commit_before>#include "jaco_custom.h" using namespace std; JacoCustom::JacoCustom(ros::NodeHandle &node){ end_program = false; arm_is_stopped = false; check_arm_status = false; arm_is_stopped_counter = 0; fingers_are_stopped = false; check_fingers_status = false; fingers_are_stopped_counter = 0; } void JacoCustom::arm_position_callback (const geometry_msgs::PoseStampedConstPtr& input_pose){ if(check_arm_status){ bool same_pose = is_same_pose(&arm_pose,input_pose); if(same_pose){ arm_is_stopped_counter++; } if(arm_is_stopped_counter >= 5){ arm_is_stopped = true; } } // Assign new value to arm pose arm_mutex.lock(); arm_pose = *input_pose; arm_mutex.unlock(); // Publish the topic data received to a TF tool_position_tf.setOrigin(tf::Vector3(input_pose->pose.position.x,input_pose->pose.position.y,input_pose->pose.position.z)); tool_position_tf.setRotation(tf::Quaternion(input_pose->pose.orientation.x,input_pose->pose.orientation.y,input_pose->pose.orientation.z,input_pose->pose.orientation.w)); position_broadcaster.sendTransform(tf::StampedTransform(tf_,ros::Time::now(),"jaco_api_origin","jaco_tool_position")); } void JacoCustom::fingers_position_callback(const jaco_msgs::FingerPositionConstPtr& input_fingers){ if(check_fingers_status){ bool same_pose = is_same_pose(&fingers_pose,input_fingers); //create a new function if(same_pose){ fingers_are_stopped_counter++; } if(fingers_are_stopped_counter >= 5){ fingers_are_stopped = true; } } // Assign new value to arm pose fingers_mutex.lock(); fingers_pose = *input_fingers; fingers_mutex.unlock(); //cout << "finger 1 : " << input_fingers->Finger_1 << endl; } void JacoCustom::open_fingers(){ actionlib::SimpleActionClient<jaco_msgs::SetFingersPositionAction> action_client("jaco/finger_joint_angles",true); action_client.waitForServer(); jaco_msgs::SetFingersPositionGoal fingers = jaco_msgs::SetFingersPositionGoal(); fingers.fingers.Finger_1 = 0; fingers.fingers.Finger_2 = 0; fingers.fingers.Finger_3 = 0; action_client.sendGoal(fingers); wait_for_fingers_stopped(); } void JacoCustom::close_fingers(){ actionlib::SimpleActionClient<jaco_msgs::SetFingersPositionAction> action_client("jaco/finger_joint_angles",true); action_client.waitForServer(); jaco_msgs::SetFingersPositionGoal fingers = jaco_msgs::SetFingersPositionGoal(); fingers.fingers.Finger_1 = 60; fingers.fingers.Finger_2 = 60; fingers.fingers.Finger_3 = 60; action_client.sendGoal(fingers); wait_for_fingers_stopped(); } void JacoCustom::move_up(double distance){ actionlib::SimpleActionClient<jaco_msgs::ArmPoseAction> action_client("/jaco/arm_pose",true); action_client.waitForServer(); jaco_msgs::ArmPoseGoal pose_goal = jaco_msgs::ArmPoseGoal(); arm_mutex.lock(); pose_goal.pose = this->arm_pose; pose_goal.pose.header.frame_id = "/jaco_api_origin"; pose_goal.pose.pose.position.z += distance; arm_mutex.unlock(); action_client.sendGoal(pose_goal); wait_for_arm_stopped(); } void JacoCustom::moveToPoint(double x, double y, double z, double rotx, double roty, double rotz, double rotw){ actionlib::SimpleActionClient<jaco_msgs::ArmPoseAction> action_client("/jaco/arm_pose",true); action_client.waitForServer(); jaco_msgs::ArmPoseGoal pose_goal = jaco_msgs::ArmPoseGoal(); pose_goal.pose.header.frame_id = "/jaco_api_origin"; pose_goal.pose.pose.position.x = x; pose_goal.pose.pose.position.y = y; pose_goal.pose.pose.position.z = z; pose_goal.pose.pose.orientation.x = rotx; pose_goal.pose.pose.orientation.y = roty; pose_goal.pose.pose.orientation.z = rotz; pose_goal.pose.pose.orientation.w = rotw; action_client.sendGoal(pose_goal); wait_for_arm_stopped(); } geometry_msgs::PoseStamped JacoCustom::getArmPosition(){ arm_mutex.lock(); geometry_msgs::PoseStamped arm = arm_pose; arm_mutex.unlock(); return arm; } tf::StampedTransform JacoCustom::getArmPositionFromCamera(){ tf::TransformListener listener; tf::StampedTransform transform; listener.waitForTransform("camera_rgb_frame","jaco_tool_position",ros::Time(0),ros::Duration(1.0)); listener.lookupTransform("camera_rgb_frame","jaco_tool_position",ros::Time(0),transform); return transform; } jaco_msgs::FingerPosition JacoCustom::getFingersPosition(){ fingers_mutex.lock(); jaco_msgs::FingerPosition pose = fingers_pose; fingers_mutex.unlock(); return pose; } tf::StampedTransform JacoCustom::getGraspArmPosition(){ // It is supposed that the fingers are open at the beginning and that the user is teaching the grasp // position when the fingers are closing jaco_msgs::FingerPosition old_pose = getFingersPosition(); jaco_msgs::FingerPosition new_pose; // If the fingers are closed by more than threshold angle, open the fingers double treshold = 10.0; if(old_pose.Finger_1 > treshold || old_pose.Finger_2 > treshold || old_pose.Finger_3 > treshold){ open_fingers(); } bool cond = true; ros::Rate r(4); int closing_count = 0; double closed_threshold = 45; while(cond){ r.sleep(); new_pose = getFingersPosition(); // break the loop if the count is bigger or equal than 5 or if the angle of the fingers are bigger than a certain angle (threshold) if(closing_count >= 5 || new_pose.Finger_1 > closed_threshold || new_pose.Finger_2 > closed_threshold || new_pose.Finger_3 > closed_threshold){ cond = false; } // increment the counter if the angles of the fingers are bigger than the previous iteration else if(new_pose.Finger_1 > old_pose.Finger_1 || new_pose.Finger_2 > old_pose.Finger_2 || new_pose.Finger_3 > old_pose.Finger_3){ closing_count++; } else{ closing_count = 0; } } return getArmPositionFromCamera(); } bool JacoCustom::is_same_pose(geometry_msgs::PoseStamped* pose1, geometry_msgs::PoseStampedConstPtr pose2){ bool cond1 = pose1->pose.position.x == pose2->pose.position.x; bool cond2 = pose1->pose.position.y == pose2->pose.position.y; bool cond3 = pose1->pose.position.z == pose2->pose.position.z; bool cond4 = pose1->pose.orientation.x == pose2->pose.orientation.x; bool cond5 = pose1->pose.orientation.y == pose2->pose.orientation.y; bool cond6 = pose1->pose.orientation.z == pose2->pose.orientation.z; bool cond7 = pose1->pose.orientation.w == pose2->pose.orientation.w; if(cond1 && cond2 && cond3 && cond4 && cond5 && cond6 && cond7){ return true; } else{ return false; } } bool JacoCustom::is_same_pose(jaco_msgs::FingerPosition* pose1, jaco_msgs::FingerPositionConstPtr pose2){ bool cond1 = pose1->Finger_1 == pose2->Finger_1; bool cond2 = pose1->Finger_2 == pose2->Finger_2; bool cond3 = pose1->Finger_3 == pose2->Finger_3; if(cond1 && cond2 && cond3){ return true; } else{ return false; } } void JacoCustom::wait_for_arm_stopped(){ arm_is_stopped_counter = 0; arm_is_stopped = false; check_arm_status = true; ros::Rate r(30); while(true){ if(arm_is_stopped) break; else {r.sleep();} } std::cout << "Finished moving the arm!" << std::endl; check_arm_status = false; } void JacoCustom::wait_for_fingers_stopped(){ fingers_are_stopped_counter = 0; fingers_are_stopped = false; check_fingers_status = true; ros::Rate r(30); while(true){ if(fingers_are_stopped) break; else {r.sleep();} } std::cout << "Finished moving the fingers!" << std::endl; check_fingers_status = false; } <commit_msg>minor error correction<commit_after>#include "jaco_custom.h" using namespace std; JacoCustom::JacoCustom(ros::NodeHandle &node){ end_program = false; arm_is_stopped = false; check_arm_status = false; arm_is_stopped_counter = 0; fingers_are_stopped = false; check_fingers_status = false; fingers_are_stopped_counter = 0; } void JacoCustom::arm_position_callback (const geometry_msgs::PoseStampedConstPtr& input_pose){ if(check_arm_status){ bool same_pose = is_same_pose(&arm_pose,input_pose); if(same_pose){ arm_is_stopped_counter++; } if(arm_is_stopped_counter >= 5){ arm_is_stopped = true; } } // Assign new value to arm pose arm_mutex.lock(); arm_pose = *input_pose; arm_mutex.unlock(); // Publish the topic data received to a TF tool_position_tf.setOrigin(tf::Vector3(input_pose->pose.position.x,input_pose->pose.position.y,input_pose->pose.position.z)); tool_position_tf.setRotation(tf::Quaternion(input_pose->pose.orientation.x,input_pose->pose.orientation.y,input_pose->pose.orientation.z,input_pose->pose.orientation.w)); position_broadcaster.sendTransform(tf::StampedTransform(tool_position_tf,ros::Time::now(),"jaco_api_origin","jaco_tool_position")); } void JacoCustom::fingers_position_callback(const jaco_msgs::FingerPositionConstPtr& input_fingers){ if(check_fingers_status){ bool same_pose = is_same_pose(&fingers_pose,input_fingers); //create a new function if(same_pose){ fingers_are_stopped_counter++; } if(fingers_are_stopped_counter >= 5){ fingers_are_stopped = true; } } // Assign new value to arm pose fingers_mutex.lock(); fingers_pose = *input_fingers; fingers_mutex.unlock(); //cout << "finger 1 : " << input_fingers->Finger_1 << endl; } void JacoCustom::open_fingers(){ actionlib::SimpleActionClient<jaco_msgs::SetFingersPositionAction> action_client("jaco/finger_joint_angles",true); action_client.waitForServer(); jaco_msgs::SetFingersPositionGoal fingers = jaco_msgs::SetFingersPositionGoal(); fingers.fingers.Finger_1 = 0; fingers.fingers.Finger_2 = 0; fingers.fingers.Finger_3 = 0; action_client.sendGoal(fingers); wait_for_fingers_stopped(); } void JacoCustom::close_fingers(){ actionlib::SimpleActionClient<jaco_msgs::SetFingersPositionAction> action_client("jaco/finger_joint_angles",true); action_client.waitForServer(); jaco_msgs::SetFingersPositionGoal fingers = jaco_msgs::SetFingersPositionGoal(); fingers.fingers.Finger_1 = 60; fingers.fingers.Finger_2 = 60; fingers.fingers.Finger_3 = 60; action_client.sendGoal(fingers); wait_for_fingers_stopped(); } void JacoCustom::move_up(double distance){ actionlib::SimpleActionClient<jaco_msgs::ArmPoseAction> action_client("/jaco/arm_pose",true); action_client.waitForServer(); jaco_msgs::ArmPoseGoal pose_goal = jaco_msgs::ArmPoseGoal(); arm_mutex.lock(); pose_goal.pose = this->arm_pose; pose_goal.pose.header.frame_id = "/jaco_api_origin"; pose_goal.pose.pose.position.z += distance; arm_mutex.unlock(); action_client.sendGoal(pose_goal); wait_for_arm_stopped(); } void JacoCustom::moveToPoint(double x, double y, double z, double rotx, double roty, double rotz, double rotw){ actionlib::SimpleActionClient<jaco_msgs::ArmPoseAction> action_client("/jaco/arm_pose",true); action_client.waitForServer(); jaco_msgs::ArmPoseGoal pose_goal = jaco_msgs::ArmPoseGoal(); pose_goal.pose.header.frame_id = "/jaco_api_origin"; pose_goal.pose.pose.position.x = x; pose_goal.pose.pose.position.y = y; pose_goal.pose.pose.position.z = z; pose_goal.pose.pose.orientation.x = rotx; pose_goal.pose.pose.orientation.y = roty; pose_goal.pose.pose.orientation.z = rotz; pose_goal.pose.pose.orientation.w = rotw; action_client.sendGoal(pose_goal); wait_for_arm_stopped(); } geometry_msgs::PoseStamped JacoCustom::getArmPosition(){ arm_mutex.lock(); geometry_msgs::PoseStamped arm = arm_pose; arm_mutex.unlock(); return arm; } tf::StampedTransform JacoCustom::getArmPositionFromCamera(){ tf::TransformListener listener; tf::StampedTransform transform; listener.waitForTransform("camera_rgb_frame","jaco_tool_position",ros::Time(0),ros::Duration(1.0)); listener.lookupTransform("camera_rgb_frame","jaco_tool_position",ros::Time(0),transform); return transform; } jaco_msgs::FingerPosition JacoCustom::getFingersPosition(){ fingers_mutex.lock(); jaco_msgs::FingerPosition pose = fingers_pose; fingers_mutex.unlock(); return pose; } tf::StampedTransform JacoCustom::getGraspArmPosition(){ // It is supposed that the fingers are open at the beginning and that the user is teaching the grasp // position when the fingers are closing jaco_msgs::FingerPosition old_pose = getFingersPosition(); jaco_msgs::FingerPosition new_pose; // If the fingers are closed by more than threshold angle, open the fingers double treshold = 10.0; if(old_pose.Finger_1 > treshold || old_pose.Finger_2 > treshold || old_pose.Finger_3 > treshold){ open_fingers(); } bool cond = true; ros::Rate r(4); int closing_count = 0; double closed_threshold = 45; while(cond){ r.sleep(); new_pose = getFingersPosition(); // break the loop if the count is bigger or equal than 5 or if the angle of the fingers are bigger than a certain angle (threshold) if(closing_count >= 5 || new_pose.Finger_1 > closed_threshold || new_pose.Finger_2 > closed_threshold || new_pose.Finger_3 > closed_threshold){ cond = false; } // increment the counter if the angles of the fingers are bigger than the previous iteration else if(new_pose.Finger_1 > old_pose.Finger_1 || new_pose.Finger_2 > old_pose.Finger_2 || new_pose.Finger_3 > old_pose.Finger_3){ closing_count++; } else{ closing_count = 0; } } return getArmPositionFromCamera(); } bool JacoCustom::is_same_pose(geometry_msgs::PoseStamped* pose1, geometry_msgs::PoseStampedConstPtr pose2){ bool cond1 = pose1->pose.position.x == pose2->pose.position.x; bool cond2 = pose1->pose.position.y == pose2->pose.position.y; bool cond3 = pose1->pose.position.z == pose2->pose.position.z; bool cond4 = pose1->pose.orientation.x == pose2->pose.orientation.x; bool cond5 = pose1->pose.orientation.y == pose2->pose.orientation.y; bool cond6 = pose1->pose.orientation.z == pose2->pose.orientation.z; bool cond7 = pose1->pose.orientation.w == pose2->pose.orientation.w; if(cond1 && cond2 && cond3 && cond4 && cond5 && cond6 && cond7){ return true; } else{ return false; } } bool JacoCustom::is_same_pose(jaco_msgs::FingerPosition* pose1, jaco_msgs::FingerPositionConstPtr pose2){ bool cond1 = pose1->Finger_1 == pose2->Finger_1; bool cond2 = pose1->Finger_2 == pose2->Finger_2; bool cond3 = pose1->Finger_3 == pose2->Finger_3; if(cond1 && cond2 && cond3){ return true; } else{ return false; } } void JacoCustom::wait_for_arm_stopped(){ arm_is_stopped_counter = 0; arm_is_stopped = false; check_arm_status = true; ros::Rate r(30); while(true){ if(arm_is_stopped) break; else {r.sleep();} } std::cout << "Finished moving the arm!" << std::endl; check_arm_status = false; } void JacoCustom::wait_for_fingers_stopped(){ fingers_are_stopped_counter = 0; fingers_are_stopped = false; check_fingers_status = true; ros::Rate r(30); while(true){ if(fingers_are_stopped) break; else {r.sleep();} } std::cout << "Finished moving the fingers!" << std::endl; check_fingers_status = false; } <|endoftext|>
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gin/public/isolate_holder.h" #include <stdlib.h> #include <string.h> #include "base/files/memory_mapped_file.h" #include "base/logging.h" #include "base/message_loop/message_loop.h" #include "base/rand_util.h" #include "base/sys_info.h" #include "gin/array_buffer.h" #include "gin/debug_impl.h" #include "gin/function_template.h" #include "gin/per_isolate_data.h" #include "gin/public/v8_platform.h" #include "gin/run_microtasks_observer.h" #ifdef V8_USE_EXTERNAL_STARTUP_DATA #include "base/path_service.h" #endif // V8_USE_EXTERNAL_STARTUP_DATA namespace gin { namespace { v8::ArrayBuffer::Allocator* g_array_buffer_allocator = NULL; bool GenerateEntropy(unsigned char* buffer, size_t amount) { base::RandBytes(buffer, amount); return true; } base::MemoryMappedFile* g_mapped_natives = NULL; base::MemoryMappedFile* g_mapped_snapshot = NULL; #ifdef V8_USE_EXTERNAL_STARTUP_DATA bool MapV8Files(base::FilePath* natives_path, base::FilePath* snapshot_path, int natives_fd = -1, int snapshot_fd = -1) { int flags = base::File::FLAG_OPEN | base::File::FLAG_READ; g_mapped_natives = new base::MemoryMappedFile; if (!g_mapped_natives->IsValid()) { if (natives_fd == -1 ? !g_mapped_natives->Initialize(base::File(*natives_path, flags)) : !g_mapped_natives->Initialize(base::File(natives_fd))) { delete g_mapped_natives; g_mapped_natives = NULL; LOG(FATAL) << "Couldn't mmap v8 natives data file"; return false; } } g_mapped_snapshot = new base::MemoryMappedFile; if (!g_mapped_snapshot->IsValid()) { if (snapshot_fd == -1 ? !g_mapped_snapshot->Initialize(base::File(*snapshot_path, flags)) : !g_mapped_snapshot->Initialize(base::File(snapshot_fd))) { delete g_mapped_snapshot; g_mapped_snapshot = NULL; LOG(ERROR) << "Couldn't mmap v8 snapshot data file"; return false; } } return true; } #endif // V8_USE_EXTERNAL_STARTUP_DATA } // namespace #ifdef V8_USE_EXTERNAL_STARTUP_DATA // static bool IsolateHolder::LoadV8Snapshot() { if (g_mapped_natives && g_mapped_snapshot) return true; base::FilePath data_path; PathService::Get( #if defined(OS_ANDROID) base::DIR_ANDROID_APP_DATA, #elif defined(OS_POSIX) base::DIR_EXE, #endif &data_path); DCHECK(!data_path.empty()); base::FilePath natives_path = data_path.AppendASCII("natives_blob.bin"); base::FilePath snapshot_path = data_path.AppendASCII("snapshot_blob.bin"); return MapV8Files(&natives_path, &snapshot_path); } //static bool IsolateHolder::LoadV8SnapshotFD(int natives_fd, int snapshot_fd) { if (g_mapped_natives && g_mapped_snapshot) return true; return MapV8Files(NULL, NULL, natives_fd, snapshot_fd); } #endif // V8_USE_EXTERNAL_STARTUP_DATA //static void IsolateHolder::GetV8ExternalSnapshotData(const char** natives_data_out, int* natives_size_out, const char** snapshot_data_out, int* snapshot_size_out) { if (!g_mapped_natives || !g_mapped_snapshot) { *natives_data_out = *snapshot_data_out = NULL; *natives_size_out = *snapshot_size_out = 0; return; } *natives_data_out = reinterpret_cast<const char*>(g_mapped_natives->data()); *snapshot_data_out = reinterpret_cast<const char*>(g_mapped_snapshot->data()); *natives_size_out = static_cast<int>(g_mapped_natives->length()); *snapshot_size_out = static_cast<int>(g_mapped_snapshot->length()); } IsolateHolder::IsolateHolder() { CHECK(g_array_buffer_allocator) << "You need to invoke gin::IsolateHolder::Initialize first"; v8::Isolate::CreateParams params; params.entry_hook = DebugImpl::GetFunctionEntryHook(); params.code_event_handler = DebugImpl::GetJitCodeEventHandler(); params.constraints.ConfigureDefaults(base::SysInfo::AmountOfPhysicalMemory(), base::SysInfo::AmountOfVirtualMemory(), base::SysInfo::NumberOfProcessors()); isolate_ = v8::Isolate::New(params); isolate_data_.reset(new PerIsolateData(isolate_, g_array_buffer_allocator)); #if defined(OS_WIN) { void* code_range; size_t size; isolate_->GetCodeRange(&code_range, &size); Debug::CodeRangeCreatedCallback callback = DebugImpl::GetCodeRangeCreatedCallback(); if (code_range && size && callback) callback(code_range, size); } #endif } IsolateHolder::~IsolateHolder() { if (task_observer_.get()) base::MessageLoop::current()->RemoveTaskObserver(task_observer_.get()); #if defined(OS_WIN) { void* code_range; size_t size; isolate_->GetCodeRange(&code_range, &size); Debug::CodeRangeDeletedCallback callback = DebugImpl::GetCodeRangeDeletedCallback(); if (code_range && callback) callback(code_range); } #endif isolate_data_.reset(); isolate_->Dispose(); } // static void IsolateHolder::Initialize(ScriptMode mode, v8::ArrayBuffer::Allocator* allocator) { CHECK(allocator); static bool v8_is_initialized = false; if (v8_is_initialized) return; v8::V8::InitializePlatform(V8Platform::Get()); v8::V8::SetArrayBufferAllocator(allocator); g_array_buffer_allocator = allocator; if (mode == gin::IsolateHolder::kStrictMode) { static const char v8_flags[] = "--use_strict"; v8::V8::SetFlagsFromString(v8_flags, sizeof(v8_flags) - 1); } v8::V8::SetEntropySource(&GenerateEntropy); #ifdef V8_USE_EXTERNAL_STARTUP_DATA v8::StartupData natives; natives.data = reinterpret_cast<const char*>(g_mapped_natives->data()); natives.raw_size = static_cast<int>(g_mapped_natives->length()); natives.compressed_size = static_cast<int>(g_mapped_natives->length()); v8::V8::SetNativesDataBlob(&natives); v8::StartupData snapshot; snapshot.data = reinterpret_cast<const char*>(g_mapped_snapshot->data()); snapshot.raw_size = static_cast<int>(g_mapped_snapshot->length()); snapshot.compressed_size = static_cast<int>(g_mapped_snapshot->length()); v8::V8::SetSnapshotDataBlob(&snapshot); #endif // V8_USE_EXTERNAL_STARTUP_DATA v8::V8::Initialize(); v8_is_initialized = true; } void IsolateHolder::AddRunMicrotasksObserver() { DCHECK(!task_observer_.get()); task_observer_.reset(new RunMicrotasksObserver(isolate_));; base::MessageLoop::current()->AddTaskObserver(task_observer_.get()); } void IsolateHolder::RemoveRunMicrotasksObserver() { DCHECK(task_observer_.get()); base::MessageLoop::current()->RemoveTaskObserver(task_observer_.get()); task_observer_.reset(); } } // namespace gin <commit_msg>Remove use of deprecated v8::StartupData::compressed_size (part 2).<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gin/public/isolate_holder.h" #include <stdlib.h> #include <string.h> #include "base/files/memory_mapped_file.h" #include "base/logging.h" #include "base/message_loop/message_loop.h" #include "base/rand_util.h" #include "base/sys_info.h" #include "gin/array_buffer.h" #include "gin/debug_impl.h" #include "gin/function_template.h" #include "gin/per_isolate_data.h" #include "gin/public/v8_platform.h" #include "gin/run_microtasks_observer.h" #ifdef V8_USE_EXTERNAL_STARTUP_DATA #include "base/path_service.h" #endif // V8_USE_EXTERNAL_STARTUP_DATA namespace gin { namespace { v8::ArrayBuffer::Allocator* g_array_buffer_allocator = NULL; bool GenerateEntropy(unsigned char* buffer, size_t amount) { base::RandBytes(buffer, amount); return true; } base::MemoryMappedFile* g_mapped_natives = NULL; base::MemoryMappedFile* g_mapped_snapshot = NULL; #ifdef V8_USE_EXTERNAL_STARTUP_DATA bool MapV8Files(base::FilePath* natives_path, base::FilePath* snapshot_path, int natives_fd = -1, int snapshot_fd = -1) { int flags = base::File::FLAG_OPEN | base::File::FLAG_READ; g_mapped_natives = new base::MemoryMappedFile; if (!g_mapped_natives->IsValid()) { if (natives_fd == -1 ? !g_mapped_natives->Initialize(base::File(*natives_path, flags)) : !g_mapped_natives->Initialize(base::File(natives_fd))) { delete g_mapped_natives; g_mapped_natives = NULL; LOG(FATAL) << "Couldn't mmap v8 natives data file"; return false; } } g_mapped_snapshot = new base::MemoryMappedFile; if (!g_mapped_snapshot->IsValid()) { if (snapshot_fd == -1 ? !g_mapped_snapshot->Initialize(base::File(*snapshot_path, flags)) : !g_mapped_snapshot->Initialize(base::File(snapshot_fd))) { delete g_mapped_snapshot; g_mapped_snapshot = NULL; LOG(ERROR) << "Couldn't mmap v8 snapshot data file"; return false; } } return true; } #endif // V8_USE_EXTERNAL_STARTUP_DATA } // namespace #ifdef V8_USE_EXTERNAL_STARTUP_DATA // static bool IsolateHolder::LoadV8Snapshot() { if (g_mapped_natives && g_mapped_snapshot) return true; base::FilePath data_path; PathService::Get( #if defined(OS_ANDROID) base::DIR_ANDROID_APP_DATA, #elif defined(OS_POSIX) base::DIR_EXE, #endif &data_path); DCHECK(!data_path.empty()); base::FilePath natives_path = data_path.AppendASCII("natives_blob.bin"); base::FilePath snapshot_path = data_path.AppendASCII("snapshot_blob.bin"); return MapV8Files(&natives_path, &snapshot_path); } //static bool IsolateHolder::LoadV8SnapshotFD(int natives_fd, int snapshot_fd) { if (g_mapped_natives && g_mapped_snapshot) return true; return MapV8Files(NULL, NULL, natives_fd, snapshot_fd); } #endif // V8_USE_EXTERNAL_STARTUP_DATA //static void IsolateHolder::GetV8ExternalSnapshotData(const char** natives_data_out, int* natives_size_out, const char** snapshot_data_out, int* snapshot_size_out) { if (!g_mapped_natives || !g_mapped_snapshot) { *natives_data_out = *snapshot_data_out = NULL; *natives_size_out = *snapshot_size_out = 0; return; } *natives_data_out = reinterpret_cast<const char*>(g_mapped_natives->data()); *snapshot_data_out = reinterpret_cast<const char*>(g_mapped_snapshot->data()); *natives_size_out = static_cast<int>(g_mapped_natives->length()); *snapshot_size_out = static_cast<int>(g_mapped_snapshot->length()); } IsolateHolder::IsolateHolder() { CHECK(g_array_buffer_allocator) << "You need to invoke gin::IsolateHolder::Initialize first"; v8::Isolate::CreateParams params; params.entry_hook = DebugImpl::GetFunctionEntryHook(); params.code_event_handler = DebugImpl::GetJitCodeEventHandler(); params.constraints.ConfigureDefaults(base::SysInfo::AmountOfPhysicalMemory(), base::SysInfo::AmountOfVirtualMemory(), base::SysInfo::NumberOfProcessors()); isolate_ = v8::Isolate::New(params); isolate_data_.reset(new PerIsolateData(isolate_, g_array_buffer_allocator)); #if defined(OS_WIN) { void* code_range; size_t size; isolate_->GetCodeRange(&code_range, &size); Debug::CodeRangeCreatedCallback callback = DebugImpl::GetCodeRangeCreatedCallback(); if (code_range && size && callback) callback(code_range, size); } #endif } IsolateHolder::~IsolateHolder() { if (task_observer_.get()) base::MessageLoop::current()->RemoveTaskObserver(task_observer_.get()); #if defined(OS_WIN) { void* code_range; size_t size; isolate_->GetCodeRange(&code_range, &size); Debug::CodeRangeDeletedCallback callback = DebugImpl::GetCodeRangeDeletedCallback(); if (code_range && callback) callback(code_range); } #endif isolate_data_.reset(); isolate_->Dispose(); } // static void IsolateHolder::Initialize(ScriptMode mode, v8::ArrayBuffer::Allocator* allocator) { CHECK(allocator); static bool v8_is_initialized = false; if (v8_is_initialized) return; v8::V8::InitializePlatform(V8Platform::Get()); v8::V8::SetArrayBufferAllocator(allocator); g_array_buffer_allocator = allocator; if (mode == gin::IsolateHolder::kStrictMode) { static const char v8_flags[] = "--use_strict"; v8::V8::SetFlagsFromString(v8_flags, sizeof(v8_flags) - 1); } v8::V8::SetEntropySource(&GenerateEntropy); #ifdef V8_USE_EXTERNAL_STARTUP_DATA v8::StartupData natives; natives.data = reinterpret_cast<const char*>(g_mapped_natives->data()); natives.raw_size = static_cast<int>(g_mapped_natives->length()); v8::V8::SetNativesDataBlob(&natives); v8::StartupData snapshot; snapshot.data = reinterpret_cast<const char*>(g_mapped_snapshot->data()); snapshot.raw_size = static_cast<int>(g_mapped_snapshot->length()); v8::V8::SetSnapshotDataBlob(&snapshot); #endif // V8_USE_EXTERNAL_STARTUP_DATA v8::V8::Initialize(); v8_is_initialized = true; } void IsolateHolder::AddRunMicrotasksObserver() { DCHECK(!task_observer_.get()); task_observer_.reset(new RunMicrotasksObserver(isolate_));; base::MessageLoop::current()->AddTaskObserver(task_observer_.get()); } void IsolateHolder::RemoveRunMicrotasksObserver() { DCHECK(task_observer_.get()); base::MessageLoop::current()->RemoveTaskObserver(task_observer_.get()); task_observer_.reset(); } } // namespace gin <|endoftext|>
<commit_before>// Copyright (C) 2016 xaizek <[email protected]> // // This file is part of uncov. // // uncov is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // uncov 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with uncov. If not, see <http://www.gnu.org/licenses/>. #include "FilePrinter.hpp" #include <boost/multi_array.hpp> #include <srchilite/sourcehighlight.h> #include <srchilite/langmap.h> #include <cassert> #include <algorithm> #include <deque> #include <iomanip> #include <ostream> #include <sstream> #include <string> #include <vector> #include "decoration.hpp" namespace { enum class LineType { Note, Common, Identical, Added, Removed }; struct DiffLine { LineType type; std::string text; int oldLine; int newLine; DiffLine(LineType type, const std::string &text, int oldLine, int newLine) : type(type), text(text), oldLine(oldLine), newLine(newLine) { } int getLine() const { return std::max(oldLine, newLine); } }; struct local { static int countWidth(int n); static std::deque<DiffLine> computeDiff(const std::vector<std::string> &o, const std::vector<int> &oCov, const std::vector<std::string> &n, const std::vector<int> &nCov); }; class CoverageColumn { struct Blank { const CoverageColumn &cc; }; struct LineAt { const CoverageColumn &cc; const int lineNo; }; friend std::ostream & operator<<(std::ostream &os, const Blank &blank) { blank.cc.printBlank(); return os; } friend std::ostream & operator<<(std::ostream &os, const LineAt &lineAt) { lineAt.cc.printAt(lineAt.lineNo); return os; } public: CoverageColumn(std::ostream &os, const std::vector<int> &coverage) : os(os), coverage(coverage) { const int MinHitsNumWidth = 5; // XXX: this could in principle be stored in database. int maxHits = 0; if (!coverage.empty()) { maxHits = *std::max_element(coverage.cbegin(), coverage.cend()); } hitsNumWidth = std::max(MinHitsNumWidth, local::countWidth(maxHits)); } public: Blank blank() const { return { *this }; } LineAt operator[](int lineNo) const { return { *this, lineNo }; } private: void printBlank() const { os << std::setw(hitsNumWidth) << "" << ' '; } void printAt(std::size_t lineNo) const { if (lineNo >= coverage.size()) { os << (decor::red_bg + decor::inv + decor::bold << std::setw(hitsNumWidth) << "ERROR" << ' '); return; } const int hits = coverage[lineNo]; decor::Decoration dec; std::string prefix; if (hits == 0) { dec = decor::red_fg + decor::inv + decor::bold; prefix = "x0"; } else if (hits > 0) { dec = decor::green_fg + decor::inv + decor::bold; prefix = 'x' + std::to_string(hits); } os << (dec << std::setw(hitsNumWidth) << prefix << ' '); } private: std::ostream &os; const std::vector<int> &coverage; int hitsNumWidth; }; } Text::Text(const std::string &text) : iss(text) { } const std::vector<std::string> & Text::asLines() { if (lines.empty()) { const std::string &text = iss.str(); lines.reserve(std::count(text.cbegin(), text.cend(), '\n') + 1); for (std::string line; std::getline(iss, line); ) { lines.push_back(line); } } return lines; } std::istringstream & Text::asStream() { iss.clear(); iss.seekg(0); return iss; } std::size_t Text::size() { return asLines().size(); } FilePrinter::FilePrinter() : sourceHighlight("esc256.outlang"), langMap("lang.map") { sourceHighlight.setStyleFile("esc256.style"); // XXX: hard-coded value of 4 spaces per tabulation. sourceHighlight.setTabSpaces(4); } void FilePrinter::print(std::ostream &os, const std::string &path, const std::string &contents, const std::vector<int> &coverage) { const int MinLineNoWidth = 5; std::istringstream iss(contents); std::stringstream ss; sourceHighlight.highlight(iss, ss, getLang(path)); const int nLines = coverage.size(); const int lineNoWidth = std::max(MinLineNoWidth, local::countWidth(nLines)); CoverageColumn covCol(os, coverage); std::size_t lineNo = 0U; for (std::string fileLine; std::getline(ss, fileLine); ++lineNo) { os << (decor::white_bg + decor::black_fg << std::setw(lineNoWidth) << lineNo + 1 << ' ') << covCol[lineNo] << ": " << fileLine << '\n'; } if (lineNo < coverage.size()) { os << (decor::red_bg + decor::bold << "ERROR:") << " not enough lines in the file.\n"; } else if (lineNo > coverage.size()) { os << (decor::red_bg + decor::bold << "ERROR:") << " too many lines in the file.\n"; } } int local::countWidth(int n) { int width = 1; while (n > 0) { n /= 10; ++width; } return width; } void FilePrinter::printDiff(std::ostream &os, const std::string &path, Text &oText, const std::vector<int> &oCov, Text &nText, const std::vector<int> &nCov) { const std::vector<std::string> &o = oText.asLines(); const std::vector<std::string> &n = nText.asLines(); assert(o.size() == oCov.size() && n.size() == nCov.size() && "Coverage information must be accurate"); const std::deque<DiffLine> diff = local::computeDiff(o, oCov, n, nCov); CoverageColumn oldCovCol(os, oCov), newCovCol(os, nCov); const std::string &lang = getLang(path); std::stringstream fss, sss; sourceHighlight.highlight(oText.asStream(), fss, lang); sourceHighlight.highlight(nText.asStream(), sss, lang); auto getOLine = [&fss, currLine = -1](int lineNo) mutable { std::string line; do { std::getline(fss, line); } while (++currLine != lineNo); return line; }; auto getNLine = [&sss, currLine = -1](int lineNo) mutable { std::string line; do { std::getline(sss, line); } while (++currLine != lineNo); return line; }; decor::Decoration additionDec = decor::green_fg + decor::bold; decor::Decoration removalDec = decor::red_fg + decor::bold; for (const DiffLine &line : diff) { switch (line.type) { case LineType::Added: os << oldCovCol.blank() << ':' << newCovCol[line.newLine] << ':' << (additionDec << '+') << getNLine(line.newLine); break; case LineType::Removed: os << oldCovCol[line.oldLine] << ':' << newCovCol.blank() << ':' << (removalDec << '-') << getOLine(line.oldLine); break; case LineType::Note: os << " <<< " + line.text + " >>>"; break; case LineType::Common: os << oldCovCol[line.oldLine] << ':' << newCovCol[line.newLine] << ": " << getOLine(line.oldLine); break; case LineType::Identical: os << oldCovCol.blank() << ':' << newCovCol.blank() << ": " << getOLine(line.oldLine); break; } os << '\n'; } } std::deque<DiffLine> local::computeDiff(const std::vector<std::string> &o, const std::vector<int> &oCov, const std::vector<std::string> &n, const std::vector<int> &nCov) { boost::multi_array<int, 2> d(boost::extents[o.size() + 1U][n.size() + 1U]); // Modified edit distance finding. using size_type = std::vector<std::string>::size_type; for (size_type i = 0U, nf = o.size(); i <= nf; ++i) { for (size_type j = 0U, ns = n.size(); j <= ns; ++j) { if (i == 0U) { d[i][j] = j; } else if (j == 0U) { d[i][j] = i; } else { d[i][j] = std::min(d[i - 1U][j] + 1, d[i][j - 1U] + 1); if (o[i - 1U] == n[j - 1U]) { d[i][j] = std::min(d[i - 1U][j - 1U], d[i][j]); } } } } std::deque<DiffLine> diff; int identicalLines = 0; auto foldIdentical = [&identicalLines, &diff]() { if (identicalLines > 4) { diff.erase(diff.cbegin() + 1, diff.cbegin() + (identicalLines - 1)); diff.emplace(diff.cbegin() + 1, LineType::Note, std::to_string(identicalLines - 2) + " identical lines folded", -1, -1); } identicalLines = 0; }; // Compose results with folding of long runs of identical lines (longer // than two lines). int i = o.size(), j = n.size(); while (i != 0 || j != 0) { if (i == 0) { --j; foldIdentical(); diff.emplace_front(LineType::Added, n[j], -1, j); } else if (j == 0) { foldIdentical(); --i; diff.emplace_front(LineType::Removed, o[i], i, -1); } else if (d[i][j] == d[i][j - 1] + 1) { foldIdentical(); --j; diff.emplace_front(LineType::Added, n[j], -1, j); } else if (d[i][j] == d[i - 1][j] + 1) { foldIdentical(); --i; diff.emplace_front(LineType::Removed, o[i], i, -1); } else if (o[--i] == n[--j]) { if (oCov[i] == -1 && nCov[j] == -1) { diff.emplace_front(LineType::Identical, o[i], i, j); ++identicalLines; } else { foldIdentical(); diff.emplace_front(LineType::Common, o[i], i, j); } } } foldIdentical(); return diff; } std::string FilePrinter::getLang(const std::string &path) { std::string lang = langMap.getMappedFileNameFromFileName(path); if (lang.empty()) { lang = "cpp.lang"; } return lang; } <commit_msg>Small highlighting optimization for diffing<commit_after>// Copyright (C) 2016 xaizek <[email protected]> // // This file is part of uncov. // // uncov is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // uncov 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with uncov. If not, see <http://www.gnu.org/licenses/>. #include "FilePrinter.hpp" #include <boost/multi_array.hpp> #include <srchilite/sourcehighlight.h> #include <srchilite/langmap.h> #include <srchilite/lineranges.h> #include <cassert> #include <algorithm> #include <deque> #include <iomanip> #include <ostream> #include <sstream> #include <string> #include <vector> #include "decoration.hpp" namespace { enum class LineType { Note, Common, Identical, Added, Removed }; struct DiffLine { LineType type; std::string text; int oldLine; int newLine; DiffLine(LineType type, const std::string &text, int oldLine, int newLine) : type(type), text(text), oldLine(oldLine), newLine(newLine) { } int getLine() const { return std::max(oldLine, newLine); } }; struct local { static int countWidth(int n); static std::deque<DiffLine> computeDiff(const std::vector<std::string> &o, const std::vector<int> &oCov, const std::vector<std::string> &n, const std::vector<int> &nCov); }; class CoverageColumn { struct Blank { const CoverageColumn &cc; }; struct LineAt { const CoverageColumn &cc; const int lineNo; }; friend std::ostream & operator<<(std::ostream &os, const Blank &blank) { blank.cc.printBlank(); return os; } friend std::ostream & operator<<(std::ostream &os, const LineAt &lineAt) { lineAt.cc.printAt(lineAt.lineNo); return os; } public: CoverageColumn(std::ostream &os, const std::vector<int> &coverage) : os(os), coverage(coverage) { const int MinHitsNumWidth = 5; // XXX: this could in principle be stored in database. int maxHits = 0; if (!coverage.empty()) { maxHits = *std::max_element(coverage.cbegin(), coverage.cend()); } hitsNumWidth = std::max(MinHitsNumWidth, local::countWidth(maxHits)); } public: Blank blank() const { return { *this }; } LineAt operator[](int lineNo) const { return { *this, lineNo }; } private: void printBlank() const { os << std::setw(hitsNumWidth) << "" << ' '; } void printAt(std::size_t lineNo) const { if (lineNo >= coverage.size()) { os << (decor::red_bg + decor::inv + decor::bold << std::setw(hitsNumWidth) << "ERROR" << ' '); return; } const int hits = coverage[lineNo]; decor::Decoration dec; std::string prefix; if (hits == 0) { dec = decor::red_fg + decor::inv + decor::bold; prefix = "x0"; } else if (hits > 0) { dec = decor::green_fg + decor::inv + decor::bold; prefix = 'x' + std::to_string(hits); } os << (dec << std::setw(hitsNumWidth) << prefix << ' '); } private: std::ostream &os; const std::vector<int> &coverage; int hitsNumWidth; }; } Text::Text(const std::string &text) : iss(text) { } const std::vector<std::string> & Text::asLines() { if (lines.empty()) { const std::string &text = iss.str(); lines.reserve(std::count(text.cbegin(), text.cend(), '\n') + 1); for (std::string line; std::getline(iss, line); ) { lines.push_back(line); } } return lines; } std::istringstream & Text::asStream() { iss.clear(); iss.seekg(0); return iss; } std::size_t Text::size() { return asLines().size(); } FilePrinter::FilePrinter() : sourceHighlight("esc256.outlang"), langMap("lang.map") { sourceHighlight.setStyleFile("esc256.style"); // XXX: hard-coded value of 4 spaces per tabulation. sourceHighlight.setTabSpaces(4); } void FilePrinter::print(std::ostream &os, const std::string &path, const std::string &contents, const std::vector<int> &coverage) { const int MinLineNoWidth = 5; std::istringstream iss(contents); std::stringstream ss; sourceHighlight.setLineRanges(nullptr); sourceHighlight.highlight(iss, ss, getLang(path)); const int nLines = coverage.size(); const int lineNoWidth = std::max(MinLineNoWidth, local::countWidth(nLines)); CoverageColumn covCol(os, coverage); std::size_t lineNo = 0U; for (std::string fileLine; std::getline(ss, fileLine); ++lineNo) { os << (decor::white_bg + decor::black_fg << std::setw(lineNoWidth) << lineNo + 1 << ' ') << covCol[lineNo] << ": " << fileLine << '\n'; } if (lineNo < coverage.size()) { os << (decor::red_bg + decor::bold << "ERROR:") << " not enough lines in the file.\n"; } else if (lineNo > coverage.size()) { os << (decor::red_bg + decor::bold << "ERROR:") << " too many lines in the file.\n"; } } int local::countWidth(int n) { int width = 1; while (n > 0) { n /= 10; ++width; } return width; } void FilePrinter::printDiff(std::ostream &os, const std::string &path, Text &oText, const std::vector<int> &oCov, Text &nText, const std::vector<int> &nCov) { const std::vector<std::string> &o = oText.asLines(); const std::vector<std::string> &n = nText.asLines(); assert(o.size() == oCov.size() && n.size() == nCov.size() && "Coverage information must be accurate"); const std::deque<DiffLine> diff = local::computeDiff(o, oCov, n, nCov); srchilite::LineRanges fLines, sLines; for (const DiffLine &line : diff) { switch (line.type) { case LineType::Added: sLines.addRange(std::to_string(line.newLine + 1)); break; case LineType::Removed: case LineType::Common: case LineType::Identical: fLines.addRange(std::to_string(line.oldLine + 1)); break; case LineType::Note: // Do nothing. break; } } const std::string &lang = getLang(path); std::stringstream fss, sss; sourceHighlight.setLineRanges(&fLines); sourceHighlight.highlight(oText.asStream(), fss, lang); sourceHighlight.setLineRanges(&sLines); sourceHighlight.highlight(nText.asStream(), sss, lang); auto getLine = [](std::stringstream &ss) { std::string line; std::getline(ss, line); return line; }; CoverageColumn oldCovCol(os, oCov), newCovCol(os, nCov); decor::Decoration additionDec = decor::green_fg + decor::bold; decor::Decoration removalDec = decor::red_fg + decor::bold; for (const DiffLine &line : diff) { switch (line.type) { case LineType::Added: os << oldCovCol.blank() << ':' << newCovCol[line.newLine] << ':' << (additionDec << '+') << getLine(sss); break; case LineType::Removed: os << oldCovCol[line.oldLine] << ':' << newCovCol.blank() << ':' << (removalDec << '-') << getLine(fss); break; case LineType::Note: os << " <<< " + line.text + " >>>"; break; case LineType::Common: os << oldCovCol[line.oldLine] << ':' << newCovCol[line.newLine] << ": " << getLine(fss); break; case LineType::Identical: os << oldCovCol.blank() << ':' << newCovCol.blank() << ": " << getLine(fss); break; } os << '\n'; } } std::deque<DiffLine> local::computeDiff(const std::vector<std::string> &o, const std::vector<int> &oCov, const std::vector<std::string> &n, const std::vector<int> &nCov) { boost::multi_array<int, 2> d(boost::extents[o.size() + 1U][n.size() + 1U]); // Modified edit distance finding. using size_type = std::vector<std::string>::size_type; for (size_type i = 0U, nf = o.size(); i <= nf; ++i) { for (size_type j = 0U, ns = n.size(); j <= ns; ++j) { if (i == 0U) { d[i][j] = j; } else if (j == 0U) { d[i][j] = i; } else { d[i][j] = std::min(d[i - 1U][j] + 1, d[i][j - 1U] + 1); if (o[i - 1U] == n[j - 1U]) { d[i][j] = std::min(d[i - 1U][j - 1U], d[i][j]); } } } } std::deque<DiffLine> diff; int identicalLines = 0; auto foldIdentical = [&identicalLines, &diff]() { if (identicalLines > 4) { diff.erase(diff.cbegin() + 1, diff.cbegin() + (identicalLines - 1)); diff.emplace(diff.cbegin() + 1, LineType::Note, std::to_string(identicalLines - 2) + " identical lines folded", -1, -1); } identicalLines = 0; }; // Compose results with folding of long runs of identical lines (longer // than two lines). int i = o.size(), j = n.size(); while (i != 0 || j != 0) { if (i == 0) { --j; foldIdentical(); diff.emplace_front(LineType::Added, n[j], -1, j); } else if (j == 0) { foldIdentical(); --i; diff.emplace_front(LineType::Removed, o[i], i, -1); } else if (d[i][j] == d[i][j - 1] + 1) { foldIdentical(); --j; diff.emplace_front(LineType::Added, n[j], -1, j); } else if (d[i][j] == d[i - 1][j] + 1) { foldIdentical(); --i; diff.emplace_front(LineType::Removed, o[i], i, -1); } else if (o[--i] == n[--j]) { if (oCov[i] == -1 && nCov[j] == -1) { diff.emplace_front(LineType::Identical, o[i], i, j); ++identicalLines; } else { foldIdentical(); diff.emplace_front(LineType::Common, o[i], i, j); } } } foldIdentical(); return diff; } std::string FilePrinter::getLang(const std::string &path) { std::string lang = langMap.getMappedFileNameFromFileName(path); if (lang.empty()) { lang = "cpp.lang"; } return lang; } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #ifndef ETL_COUNTERS namespace etl { inline void dump_counters() { //No counters } void inc_counter(const char* name){ cpp_unused(name); } } //end of namespace etl #else #include <chrono> #include <iosfwd> #include <iomanip> #include <sstream> namespace etl { constexpr const std::size_t max_counters = 64; struct counter_t { const char* name; std::atomic<std::size_t> count; counter_t() : name(nullptr), count(0) {} counter_t(const counter_t& rhs) : name(rhs.name), count(rhs.count.load()) {} counter_t& operator=(const counter_t& rhs) { if (&rhs != this) { name = rhs.name; count = rhs.count.load(); } return *this; } counter_t(counter_t&& rhs) : name(std::move(rhs.name)), count(rhs.count.load()) {} counter_t& operator=(counter_t&& rhs) { if (&rhs != this) { name = std::move(rhs.name); count = rhs.count.load(); } return *this; } }; struct counters_t { std::array<counter_t, max_counters> counters; std::mutex lock; void reset(){ std::lock_guard<std::mutex> l(lock); for(auto& counter : counters){ counter.name = nullptr; counter.count = 0; } } }; inline counters_t& get_counters() { static counters_t counters; return counters; } /*! * \brief Reset all counters */ inline void reset_counters() { decltype(auto) counters = get_counters(); counters.reset(); } /*! * \brief Dump all counters values to the console. */ inline void dump_counters() { decltype(auto) counters = get_counters().counters; //Sort the counters by count (DESC) std::sort(counters.begin(), counters.end(), [](auto& left, auto& right) { return left.count > right.count; }); // Print all the used counters for (decltype(auto) counter : counters) { if (counter.name) { std::cout << counter.name << ": " << counter.count << std::endl; } } } void inc_counter(const char* name) { decltype(auto) counters = get_counters(); for (decltype(auto) counter : counters.counters) { if (counter.name == name) { ++counter.count; return; } } std::lock_guard<std::mutex> lock(counters.lock); for (decltype(auto) counter : counters.counters) { if (counter.name == name) { ++counter.count; return; } } for (decltype(auto) counter : counters.counters) { if (!counter.name) { counter.name = name; counter.count = 1; return; } } std::cerr << "Unable to register counter " << name << std::endl; } } //end of namespace etl #endif <commit_msg>Fix counters<commit_after>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #ifndef ETL_COUNTERS namespace etl { inline void dump_counters() { //No counters } inline void inc_counter(const char* name){ cpp_unused(name); } } //end of namespace etl #else #include <chrono> #include <iosfwd> #include <iomanip> #include <sstream> namespace etl { constexpr const std::size_t max_counters = 64; struct counter_t { const char* name; std::atomic<std::size_t> count; counter_t() : name(nullptr), count(0) {} counter_t(const counter_t& rhs) : name(rhs.name), count(rhs.count.load()) {} counter_t& operator=(const counter_t& rhs) { if (&rhs != this) { name = rhs.name; count = rhs.count.load(); } return *this; } counter_t(counter_t&& rhs) : name(std::move(rhs.name)), count(rhs.count.load()) {} counter_t& operator=(counter_t&& rhs) { if (&rhs != this) { name = std::move(rhs.name); count = rhs.count.load(); } return *this; } }; struct counters_t { std::array<counter_t, max_counters> counters; std::mutex lock; void reset(){ std::lock_guard<std::mutex> l(lock); for(auto& counter : counters){ counter.name = nullptr; counter.count = 0; } } }; inline counters_t& get_counters() { static counters_t counters; return counters; } /*! * \brief Reset all counters */ inline void reset_counters() { decltype(auto) counters = get_counters(); counters.reset(); } /*! * \brief Dump all counters values to the console. */ inline void dump_counters() { decltype(auto) counters = get_counters().counters; //Sort the counters by count (DESC) std::sort(counters.begin(), counters.end(), [](auto& left, auto& right) { return left.count > right.count; }); // Print all the used counters for (decltype(auto) counter : counters) { if (counter.name) { std::cout << counter.name << ": " << counter.count << std::endl; } } } inline void inc_counter(const char* name) { decltype(auto) counters = get_counters(); for (decltype(auto) counter : counters.counters) { if (counter.name == name) { ++counter.count; return; } } std::lock_guard<std::mutex> lock(counters.lock); for (decltype(auto) counter : counters.counters) { if (counter.name == name) { ++counter.count; return; } } for (decltype(auto) counter : counters.counters) { if (!counter.name) { counter.name = name; counter.count = 1; return; } } std::cerr << "Unable to register counter " << name << std::endl; } } //end of namespace etl #endif <|endoftext|>
<commit_before>#ifndef MISC_UI_HPP #define MISC_UI_HPP #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/filename.h> #include <wx/stdpaths.h> #include <map> #include <utility> #include "Settings.hpp" #include "Log.hpp" #include "Point.hpp" /// Macro to build std::wstring that slic3r::log expects using << syntax of wxString /// Avoids wx pollution of libslic3r #define LOG_WSTRING(...) ((wxString("") << __VA_ARGS__).ToStdWstring()) /// Common static (that is, free-standing) functions, not part of an object hierarchy. namespace Slic3r { namespace GUI { enum class OS { Linux, Mac, Windows } ; // constants to reduce the proliferation of macros in the rest of the code #ifdef __WIN32 constexpr OS the_os = OS::Windows; constexpr bool wxGTK {false}; #elif __APPLE__ constexpr OS the_os = OS::Mac; constexpr bool wxGTK {false}; #elif __linux__ constexpr OS the_os = OS::Linux; #ifdef __WXGTK__ constexpr bool wxGTK {true}; #else constexpr bool wxGTK {false}; #endif #endif #ifdef SLIC3R_DEV constexpr bool isDev = true; #else constexpr bool isDev = false; #endif constexpr bool threaded = false; // hopefully the compiler is smart enough to figure this out const std::map<const std::string, const std::string> FILE_WILDCARDS { std::make_pair("known", "Known files (*.stl, *.obj, *.amf, *.xml, *.3mf)|*.3mf;*.3MF;*.stl;*.STL;*.obj;*.OBJ;*.amf;*.AMF;*.xml;*.XML"), std::make_pair("stl", "STL files (*.stl)|*.stl;*.STL"), std::make_pair("obj", "OBJ files (*.obj)|*.obj;*.OBJ"), std::make_pair("amf", "AMF files (*.amf)|*.amf;*.AMF;*.xml;*.XML"), std::make_pair("tmf", "3MF files (*.3mf)|*.3mf;*.3MF"), std::make_pair("ini", "INI files *.ini|*.ini;*.INI"), std::make_pair("gcode", "G-code files (*.gcode, *.gco, *.g, *.ngc)|*.gcode;*.GCODE;*.gco;*.GCO;*.g;*.G;*.ngc;*.NGC"), std::make_pair("svg", "SVG files *.svg|*.svg;*.SVG") }; const std::string MODEL_WILDCARD { FILE_WILDCARDS.at("known") + std::string("|") + FILE_WILDCARDS.at("stl")+ std::string("|") + FILE_WILDCARDS.at("obj") + std::string("|") + FILE_WILDCARDS.at("amf")+ std::string("|") + FILE_WILDCARDS.at("tmf")}; const std::string STL_MODEL_WILDCARD { FILE_WILDCARDS.at("stl") }; const std::string AMF_MODEL_WILDCARD { FILE_WILDCARDS.at("amf") }; const std::string TMF_MODEL_WILDCARD { FILE_WILDCARDS.at("tmf") }; /// Mostly useful for Linux distro maintainers, this will change where Slic3r assumes /// its ./var directory lives (where its art assets are). /// Define VAR_ABS and VAR_ABS_PATH #ifndef VAR_ABS #define VAR_ABS false #else #define VAR_ABS true #endif #ifndef VAR_ABS_PATH #define VAR_ABS_PATH "/usr/share/Slic3r/var" #endif #ifndef VAR_REL // Redefine on compile #define VAR_REL L"/../var" #endif /// Performs a check via the Internet for a new version of Slic3r. /// If this version of Slic3r was compiled with -DSLIC3R_DEV, check the development /// space instead of release. void check_version(bool manual = false); /// Provides a path to Slic3r's var dir. const wxString var(const wxString& in); /// Provide a path to where Slic3r exec'd from. const wxString bin(); /// Always returns path to home directory. const wxString home(const wxString& in = "Slic3r"); /// Shows an error messagebox void show_error(wxWindow* parent, const wxString& message); /// Shows an info messagebox. void show_info(wxWindow* parent, const wxString& message, const wxString& title); /// Show an error messagebox and then throw an exception. void fatal_error(wxWindow* parent, const wxString& message); /// Assign a menu item icon void set_menu_item_icon(wxMenuItem* item, const wxString& icon); template <typename T> wxMenuItem* append_menu_item(wxMenu* menu, const wxString& name,const wxString& help, T lambda, int id = wxID_ANY, const wxString& icon = "", const wxString& accel = "", const wxItemKind kind = wxITEM_NORMAL) { wxMenuItem* tmp = menu->Append(wxID_ANY, name, help, kind); wxAcceleratorEntry* a = new wxAcceleratorEntry(); if (!accel.IsEmpty()) { a->FromString(accel); tmp->SetAccel(a); // set the accelerator if and only if the accelerator is fine } tmp->SetHelp(help); set_menu_item_icon(tmp, icon); if (typeid(lambda) != typeid(nullptr)) menu->Bind(wxEVT_MENU, lambda, tmp->GetId(), tmp->GetId()); return tmp; } wxMenuItem* append_submenu(wxMenu* menu, const wxString& name, const wxString& help, wxMenu* submenu, int id = wxID_ANY, const wxString& icon = ""); /* sub CallAfter { my ($self, $cb) = @_; push @cb, $cb; } */ wxString decode_path(const wxString& in); wxString encode_path(const wxString& in); std::vector<wxString> open_model(wxWindow* parent, const Settings& settings, wxWindow* top); inline Slic3r::Point new_scale(const wxPoint& p) { return Slic3r::Point::new_scale(p.x, p.y); } }} // namespace Slic3r::GUI #endif // MISC_UI_HPP <commit_msg>added comment to append_menu_item and append_submenu.<commit_after>#ifndef MISC_UI_HPP #define MISC_UI_HPP #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/filename.h> #include <wx/stdpaths.h> #include <map> #include <utility> #include "Settings.hpp" #include "Log.hpp" #include "Point.hpp" /// Macro to build std::wstring that slic3r::log expects using << syntax of wxString /// Avoids wx pollution of libslic3r #define LOG_WSTRING(...) ((wxString("") << __VA_ARGS__).ToStdWstring()) /// Common static (that is, free-standing) functions, not part of an object hierarchy. namespace Slic3r { namespace GUI { enum class OS { Linux, Mac, Windows } ; // constants to reduce the proliferation of macros in the rest of the code #ifdef __WIN32 constexpr OS the_os = OS::Windows; constexpr bool wxGTK {false}; #elif __APPLE__ constexpr OS the_os = OS::Mac; constexpr bool wxGTK {false}; #elif __linux__ constexpr OS the_os = OS::Linux; #ifdef __WXGTK__ constexpr bool wxGTK {true}; #else constexpr bool wxGTK {false}; #endif #endif #ifdef SLIC3R_DEV constexpr bool isDev = true; #else constexpr bool isDev = false; #endif constexpr bool threaded = false; // hopefully the compiler is smart enough to figure this out const std::map<const std::string, const std::string> FILE_WILDCARDS { std::make_pair("known", "Known files (*.stl, *.obj, *.amf, *.xml, *.3mf)|*.3mf;*.3MF;*.stl;*.STL;*.obj;*.OBJ;*.amf;*.AMF;*.xml;*.XML"), std::make_pair("stl", "STL files (*.stl)|*.stl;*.STL"), std::make_pair("obj", "OBJ files (*.obj)|*.obj;*.OBJ"), std::make_pair("amf", "AMF files (*.amf)|*.amf;*.AMF;*.xml;*.XML"), std::make_pair("tmf", "3MF files (*.3mf)|*.3mf;*.3MF"), std::make_pair("ini", "INI files *.ini|*.ini;*.INI"), std::make_pair("gcode", "G-code files (*.gcode, *.gco, *.g, *.ngc)|*.gcode;*.GCODE;*.gco;*.GCO;*.g;*.G;*.ngc;*.NGC"), std::make_pair("svg", "SVG files *.svg|*.svg;*.SVG") }; const std::string MODEL_WILDCARD { FILE_WILDCARDS.at("known") + std::string("|") + FILE_WILDCARDS.at("stl")+ std::string("|") + FILE_WILDCARDS.at("obj") + std::string("|") + FILE_WILDCARDS.at("amf")+ std::string("|") + FILE_WILDCARDS.at("tmf")}; const std::string STL_MODEL_WILDCARD { FILE_WILDCARDS.at("stl") }; const std::string AMF_MODEL_WILDCARD { FILE_WILDCARDS.at("amf") }; const std::string TMF_MODEL_WILDCARD { FILE_WILDCARDS.at("tmf") }; /// Mostly useful for Linux distro maintainers, this will change where Slic3r assumes /// its ./var directory lives (where its art assets are). /// Define VAR_ABS and VAR_ABS_PATH #ifndef VAR_ABS #define VAR_ABS false #else #define VAR_ABS true #endif #ifndef VAR_ABS_PATH #define VAR_ABS_PATH "/usr/share/Slic3r/var" #endif #ifndef VAR_REL // Redefine on compile #define VAR_REL L"/../var" #endif /// Performs a check via the Internet for a new version of Slic3r. /// If this version of Slic3r was compiled with -DSLIC3R_DEV, check the development /// space instead of release. void check_version(bool manual = false); /// Provides a path to Slic3r's var dir. const wxString var(const wxString& in); /// Provide a path to where Slic3r exec'd from. const wxString bin(); /// Always returns path to home directory. const wxString home(const wxString& in = "Slic3r"); /// Shows an error messagebox void show_error(wxWindow* parent, const wxString& message); /// Shows an info messagebox. void show_info(wxWindow* parent, const wxString& message, const wxString& title); /// Show an error messagebox and then throw an exception. void fatal_error(wxWindow* parent, const wxString& message); /// Assign a menu item icon void set_menu_item_icon(wxMenuItem* item, const wxString& icon); /// Construct a menu item for Slic3r, append it to a menu, and return it. /// Automatically binds the lambda method to the event handler of the menu for this menu item's id. /// Assign the accelerator separately if one is desired (instead of the \t interface in the name) /// to permit translation. template <typename T> wxMenuItem* append_menu_item(wxMenu* menu, const wxString& name,const wxString& help, T lambda, int id = wxID_ANY, const wxString& icon = "", const wxString& accel = "", const wxItemKind kind = wxITEM_NORMAL) { wxMenuItem* tmp = menu->Append(wxID_ANY, name, help, kind); wxAcceleratorEntry* a = new wxAcceleratorEntry(); if (!accel.IsEmpty()) { a->FromString(accel); tmp->SetAccel(a); // set the accelerator if and only if the accelerator is fine } tmp->SetHelp(help); set_menu_item_icon(tmp, icon); if (typeid(lambda) != typeid(nullptr)) menu->Bind(wxEVT_MENU, lambda, tmp->GetId(), tmp->GetId()); return tmp; } /// Construct and return a submenu to the menu, optionally with an icon. wxMenuItem* append_submenu(wxMenu* menu, const wxString& name, const wxString& help, wxMenu* submenu, int id = wxID_ANY, const wxString& icon = ""); /* sub CallAfter { my ($self, $cb) = @_; push @cb, $cb; } */ wxString decode_path(const wxString& in); wxString encode_path(const wxString& in); std::vector<wxString> open_model(wxWindow* parent, const Settings& settings, wxWindow* top); inline Slic3r::Point new_scale(const wxPoint& p) { return Slic3r::Point::new_scale(p.x, p.y); } }} // namespace Slic3r::GUI #endif // MISC_UI_HPP <|endoftext|>
<commit_before>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_ALLOCA #include "libtorrent/config.hpp" #ifdef TORRENT_WINDOWS #include <malloc.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * n)); #else #include <alloca.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * n)); #endif #endif <commit_msg>alloca macro fix<commit_after>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_ALLOCA #include "libtorrent/config.hpp" #ifdef TORRENT_WINDOWS #include <malloc.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n))); #else #include <alloca.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n))); #endif #endif <|endoftext|>
<commit_before>/* Copyright (c) 2005, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_CONFIG_HPP_INCLUDED #define TORRENT_CONFIG_HPP_INCLUDED #include <boost/config.hpp> #include <boost/version.hpp> #include <stdio.h> // for snprintf #ifndef WIN32 #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif #ifndef PRId64 #ifdef _WIN32 #define PRId64 "I64d" #else #define PRId64 "lld" #endif #endif // ======= GCC ========= #if defined __GNUC__ # define TORRENT_DEPRECATED __attribute__ ((deprecated)) // GCC pre 4.0 did not have support for the visibility attribute # if __GNUC__ >= 4 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __attribute__ ((visibility("default"))) # else # define TORRENT_EXPORT # endif # else # define TORRENT_EXPORT # endif // ======= SUNPRO ========= #elif defined __SUNPRO_CC # if __SUNPRO_CC >= 0x550 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __global # else # define TORRENT_EXPORT # endif # else # define TORRENT_EXPORT # endif // ======= MSVC ========= #elif defined BOOST_MSVC #pragma warning(disable: 4258) #pragma warning(disable: 4251) # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # else # define TORRENT_EXPORT # endif #define TORRENT_DEPRECATED_PREFIX __declspec(deprecated("function is deprecated")) // ======= GENERIC COMPILER ========= #else # define TORRENT_EXPORT #endif #ifndef TORRENT_DEPRECATED_PREFIX #define TORRENT_DEPRECATED_PREFIX #endif #ifndef TORRENT_DEPRECATED #define TORRENT_DEPRECATED #endif // set up defines for target environments #if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \ || defined __FreeBSD_kernel__ #define TORRENT_BSD #elif defined __linux__ #define TORRENT_LINUX #elif defined __MINGW32__ #define TORRENT_MINGW #elif defined WIN32 #define TORRENT_WINDOWS #elif defined sun || defined __sun #define TORRENT_SOLARIS #else #warning unkown OS, assuming BSD #define TORRENT_BSD #endif #define TORRENT_USE_IPV6 1 #define TORRENT_USE_MLOCK 1 #define TORRENT_USE_READV 1 #define TORRENT_USE_WRITEV 1 #define TORRENT_USE_IOSTREAM 1 #define TORRENT_USE_I2P 1 // should wpath or path be used? #if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \ && BOOST_VERSION >= 103400 && !defined __APPLE__ #define TORRENT_USE_WPATH 1 #else #define TORRENT_USE_WPATH 0 #endif // set this to 1 to disable all floating point operations // (disables some float-dependent APIs) #define TORRENT_NO_FPU 0 // make sure NAME_MAX is defined #ifndef NAME_MAX #ifdef MAXPATH #define NAME_MAX MAXPATH #else // this is the maximum number of characters in a // path element / filename on windows #define NAME_MAX 255 #endif // MAXPATH #endif // NAME_MAX #ifdef TORRENT_WINDOWS #pragma warning(disable:4251) // class X needs to have dll-interface to be used by clients of class Y #include <stdarg.h> inline int snprintf(char* buf, int len, char const* fmt, ...) { va_list lp; va_start(lp, fmt); int ret = _vsnprintf(buf, len, fmt, lp); va_end(lp); if (ret < 0) { buf[len-1] = 0; ret = len-1; } return ret; } #define strtoll _strtoi64 #else #include <limits.h> #endif #if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING) #define TORRENT_UPNP_LOGGING #endif #if !TORRENT_USE_WPATH && defined TORRENT_LINUX // libiconv presnce, not implemented yet #define TORRENT_USE_LOCALE_FILENAMES 1 #else #define TORRENT_USE_LOCALE_FILENAMES 0 #endif #if !defined(TORRENT_READ_HANDLER_MAX_SIZE) # define TORRENT_READ_HANDLER_MAX_SIZE 256 #endif #if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE) # define TORRENT_WRITE_HANDLER_MAX_SIZE 256 #endif #if defined _MSC_VER && _MSC_VER <= 1200 #define for if (false) {} else for #endif // determine what timer implementation we can use #if defined(__MACH__) #define TORRENT_USE_ABSOLUTE_TIME 1 #elif defined(_WIN32) #define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1 #elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 #define TORRENT_USE_CLOCK_GETTIME 1 #else #define TORRENT_USE_BOOST_DATE_TIME 1 #endif #endif // TORRENT_CONFIG_HPP_INCLUDED <commit_msg>msvc 7.1 build fix<commit_after>/* Copyright (c) 2005, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_CONFIG_HPP_INCLUDED #define TORRENT_CONFIG_HPP_INCLUDED #include <boost/config.hpp> #include <boost/version.hpp> #include <stdio.h> // for snprintf #ifndef WIN32 #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif #ifndef PRId64 #ifdef _WIN32 #define PRId64 "I64d" #else #define PRId64 "lld" #endif #endif // ======= GCC ========= #if defined __GNUC__ # define TORRENT_DEPRECATED __attribute__ ((deprecated)) // GCC pre 4.0 did not have support for the visibility attribute # if __GNUC__ >= 4 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __attribute__ ((visibility("default"))) # else # define TORRENT_EXPORT # endif # else # define TORRENT_EXPORT # endif // ======= SUNPRO ========= #elif defined __SUNPRO_CC # if __SUNPRO_CC >= 0x550 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __global # else # define TORRENT_EXPORT # endif # else # define TORRENT_EXPORT # endif // ======= MSVC ========= #elif defined BOOST_MSVC #pragma warning(disable: 4258) #pragma warning(disable: 4251) # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # else # define TORRENT_EXPORT # endif #define TORRENT_DEPRECATED_PREFIX __declspec(deprecated) // ======= GENERIC COMPILER ========= #else # define TORRENT_EXPORT #endif #ifndef TORRENT_DEPRECATED_PREFIX #define TORRENT_DEPRECATED_PREFIX #endif #ifndef TORRENT_DEPRECATED #define TORRENT_DEPRECATED #endif // set up defines for target environments #if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \ || defined __FreeBSD_kernel__ #define TORRENT_BSD #elif defined __linux__ #define TORRENT_LINUX #elif defined __MINGW32__ #define TORRENT_MINGW #elif defined WIN32 #define TORRENT_WINDOWS #elif defined sun || defined __sun #define TORRENT_SOLARIS #else #warning unkown OS, assuming BSD #define TORRENT_BSD #endif #define TORRENT_USE_IPV6 1 #define TORRENT_USE_MLOCK 1 #define TORRENT_USE_READV 1 #define TORRENT_USE_WRITEV 1 #define TORRENT_USE_IOSTREAM 1 #define TORRENT_USE_I2P 1 // should wpath or path be used? #if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \ && BOOST_VERSION >= 103400 && !defined __APPLE__ #define TORRENT_USE_WPATH 1 #else #define TORRENT_USE_WPATH 0 #endif // set this to 1 to disable all floating point operations // (disables some float-dependent APIs) #define TORRENT_NO_FPU 0 // make sure NAME_MAX is defined #ifndef NAME_MAX #ifdef MAXPATH #define NAME_MAX MAXPATH #else // this is the maximum number of characters in a // path element / filename on windows #define NAME_MAX 255 #endif // MAXPATH #endif // NAME_MAX #ifdef TORRENT_WINDOWS #pragma warning(disable:4251) // class X needs to have dll-interface to be used by clients of class Y #include <stdarg.h> inline int snprintf(char* buf, int len, char const* fmt, ...) { va_list lp; va_start(lp, fmt); int ret = _vsnprintf(buf, len, fmt, lp); va_end(lp); if (ret < 0) { buf[len-1] = 0; ret = len-1; } return ret; } #define strtoll _strtoi64 #else #include <limits.h> #endif #if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING) #define TORRENT_UPNP_LOGGING #endif #if !TORRENT_USE_WPATH && defined TORRENT_LINUX // libiconv presnce, not implemented yet #define TORRENT_USE_LOCALE_FILENAMES 1 #else #define TORRENT_USE_LOCALE_FILENAMES 0 #endif #if !defined(TORRENT_READ_HANDLER_MAX_SIZE) # define TORRENT_READ_HANDLER_MAX_SIZE 256 #endif #if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE) # define TORRENT_WRITE_HANDLER_MAX_SIZE 256 #endif #if defined _MSC_VER && _MSC_VER <= 1200 #define for if (false) {} else for #endif // determine what timer implementation we can use #if defined(__MACH__) #define TORRENT_USE_ABSOLUTE_TIME 1 #elif defined(_WIN32) #define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1 #elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 #define TORRENT_USE_CLOCK_GETTIME 1 #else #define TORRENT_USE_BOOST_DATE_TIME 1 #endif #endif // TORRENT_CONFIG_HPP_INCLUDED <|endoftext|>
<commit_before>//Copyright (c) 2019 Ultimaker B.V. #include "GcodeWriter.h" #include "pathOrderOptimizer.h" namespace arachne { GcodeWriter::GcodeWriter(std::string filename, int type, coord_t layer_thickness, float print_speed, float travel_speed, float extrusion_multiplier) : file(filename.c_str()) , type(type) , layer_thickness(layer_thickness) , print_speed(print_speed) , travel_speed(travel_speed) , extrusion_multiplier(extrusion_multiplier) { assert(file.good()); file << ";START_OF_HEADER\n"; file << ";HEADER_VERSION:0.1\n"; file << ";FLAVOR:Griffin\n"; file << ";GENERATOR.NAME:libArachne\n"; file << ";GENERATOR.VERSION:3.1.0\n"; file << ";GENERATOR.BUILD_DATE:2017-12-05\n"; file << ";TARGET_MACHINE.NAME:Ultimaker 3\n"; file << ";EXTRUDER_TRAIN.0.INITIAL_TEMPERATURE:215\n"; file << ";EXTRUDER_TRAIN.0.MATERIAL.VOLUME_USED:9172\n"; file << ";EXTRUDER_TRAIN.0.MATERIAL.GUID:506c9f0d-e3aa-4bd4-b2d2-23e2425b1aa9\n"; file << ";EXTRUDER_TRAIN.0.NOZZLE.DIAMETER:0.4\n"; file << ";EXTRUDER_TRAIN.0.NOZZLE.NAME:AA 0.4\n"; file << ";BUILD_PLATE.INITIAL_TEMPERATURE:20\n"; file << ";PRINT.TIME:5201\n"; file << ";PRINT.SIZE.MIN.X:9\n"; file << ";PRINT.SIZE.MIN.Y:6\n"; file << ";PRINT.SIZE.MIN.Z:0.27\n"; file << ";PRINT.SIZE.MAX.X:173.325\n"; file << ";PRINT.SIZE.MAX.Y:164.325\n"; file << ";PRINT.SIZE.MAX.Z:60.03\n"; file << ";END_OF_HEADER\n"; file << ";Generated with libArachne\n"; file << "\n"; file << "T0\n"; file << "M82 ; absolute extrusion mode\n"; file << "G92 E0\n"; file << "M109 S215\n"; file << "G0 F15000 X9 Y6 Z2\n"; file << "G280\n"; file << "G1 F1500 E-6.5\n"; file << ";LAYER_COUNT:1\n"; file << ";LAYER:0\n"; file << "M107\n"; file << "M204 S625; set acceleration\n"; file << "M205 X6 Y6; set jerk\n"; file << "G0 F" << travel_speed << " X" << INT2MM(build_plate_middle.X / 2) << " Y" << INT2MM(build_plate_middle.Y / 2) << " Z" << (INT2MM(layer_thickness) + 0.18) << " ; start location\n"; file << "G0 E0 F1500 ; unretract\n"; file << "\n"; file << "M214 K1.0 ; bueno linear advance\n"; // file << "M83 ;relative extrusion mode\n"; file << "\n"; cur_pos = build_plate_middle; } GcodeWriter::~GcodeWriter() { // file << "M214 K0.0\n"; file << "M107\n"; file.close(); } void GcodeWriter::printBrim(AABB aabb, coord_t count, coord_t w, coord_t dist) { std::vector<std::list<ExtrusionLine>> polygons_per_index; std::vector<std::list<ExtrusionLine>> polylines_per_index; polygons_per_index.resize(1); std::list<ExtrusionLine>& polygons = polygons_per_index[0]; Polygons prev; prev.add(aabb.toPolygon()); prev = prev.offset(dist * 2); for (int i = 0; i < count; i++) { Polygons skuurt = prev.offset(dist, ClipperLib::jtRound); for (PolygonRef poly : skuurt) { polygons.emplace_back(0, true); ExtrusionLine& polygon = polygons.back(); for (Point p : poly) { polygon.junctions.emplace_back(p, w, 0); } } prev = skuurt; } print(polygons_per_index, polylines_per_index, aabb); } void GcodeWriter::print(std::vector<std::list<ExtrusionLine>>& polygons_per_index, std::vector<std::list<ExtrusionLine>>& polylines_per_index, AABB aabb) { std::vector<std::vector<ExtrusionLine>> polygons_per_index_vector; polygons_per_index_vector.resize(polygons_per_index.size()); for (coord_t inset_idx = 0; inset_idx < polygons_per_index.size(); inset_idx++) polygons_per_index_vector[inset_idx].insert(polygons_per_index_vector[inset_idx].end(), polygons_per_index[inset_idx].begin(), polygons_per_index[inset_idx].end()); std::vector<std::vector<ExtrusionLine>> polylines_per_index_vector; polylines_per_index_vector.resize(polylines_per_index.size()); for (coord_t inset_idx = 0; inset_idx < polylines_per_index.size(); inset_idx++) polylines_per_index_vector[inset_idx].insert(polylines_per_index_vector[inset_idx].end(), polylines_per_index[inset_idx].begin(), polylines_per_index[inset_idx].end()); reduction = aabb.getMiddle() - build_plate_middle; for (int inset_idx = 0; inset_idx < std::max(polygons_per_index_vector.size(), polylines_per_index_vector.size()); inset_idx++) { if (inset_idx < polylines_per_index_vector.size()) { LineOrderOptimizer order_optimizer(cur_pos); Polygons recreated; for (ExtrusionLine& polyline : polylines_per_index_vector[inset_idx]) { PolygonRef recreated_poly = recreated.newPoly(); recreated_poly.add(polyline.junctions.front().p); recreated_poly.add(polyline.junctions.back().p); } order_optimizer.addPolygons(recreated); order_optimizer.optimize(); for (int poly_idx : order_optimizer.polyOrder) { ExtrusionLine& polyline = polylines_per_index_vector[inset_idx][poly_idx]; int start_idx = order_optimizer.polyStart[poly_idx]; assert(start_idx < polyline.junctions.size()); if (start_idx == 0) { auto last = polyline.junctions.begin(); move(last->p); for (auto junction_it = ++polyline.junctions.begin(); junction_it != polyline.junctions.end(); ++junction_it) { ExtrusionJunction& junction = *junction_it; print(*last, junction); last = junction_it; } } else { auto last = polyline.junctions.rbegin(); move(last->p); for (auto junction_it = ++polyline.junctions.rbegin(); junction_it != polyline.junctions.rend(); ++junction_it) { ExtrusionJunction& junction = *junction_it; print(*last, junction); last = junction_it; } } } } if (inset_idx < polygons_per_index_vector.size()) { PathOrderOptimizer order_optimizer(cur_pos); Polygons recreated; for (ExtrusionLine& polygon : polygons_per_index_vector[inset_idx]) { PolygonRef recreated_poly = recreated.newPoly(); for (ExtrusionJunction& j : polygon.junctions) { recreated_poly.add(j.p); } } order_optimizer.addPolygons(recreated); order_optimizer.optimize(); for (int poly_idx : order_optimizer.polyOrder) { ExtrusionLine& polygon = polygons_per_index_vector[inset_idx][poly_idx]; int start_idx = order_optimizer.polyStart[poly_idx]; assert(start_idx < polygon.junctions.size()); auto first = polygon.junctions.begin(); std::advance(first, start_idx); move(first->p); auto prev = first; auto second = first; second++; for (auto junction_it = second; ; ++junction_it) { if (junction_it == polygon.junctions.end()) junction_it = polygon.junctions.begin(); ExtrusionJunction& junction = *junction_it; print(*prev, junction); prev = junction_it; if (junction_it == first) break; } } } } } void GcodeWriter::move(Point p) { file << "\n"; p -= reduction; switch(type) { case type_P3: file << "G5 F" << travel_speed << " X" << INT2MM(p.X) << " Y" << INT2MM(p.Y) << " S0 E0\n"; break; case type_UM3: default: file << "G0 X" << INT2MM(p.X) << " Y" << INT2MM(p.Y) << "\n"; break; } cur_pos = p; } void GcodeWriter::print(ExtrusionJunction from, ExtrusionJunction to) { from.p -= reduction; to.p -= reduction; assert(from.p == cur_pos); bool discretize = type != type_P3 && std::abs(to.w - from.w) > 10; if (from.p == to.p) { return; } if (!discretize) { printSingleExtrusionMove(from, to); } else { Point vec = to.p - from.p; coord_t length = vSize(vec); coord_t segment_count = (length + discretization_size / 2) / discretization_size; // round to nearest ExtrusionJunction last = from; for (coord_t segment_idx = 0; segment_idx < segment_count; segment_idx++) { ExtrusionJunction here(from.p + vec * (segment_idx + 1) / segment_count, from.w + (to.w - from.w) * (segment_idx + 1) / segment_count, last.perimeter_index); printSingleExtrusionMove(last, here); last = here; } } cur_pos = to.p; } void GcodeWriter::printSingleExtrusionMove(ExtrusionJunction& from, ExtrusionJunction& to) { switch(type) { case type_P3: file << "G5 F" << print_speed << " X" << INT2MM(to.p.X) << " Y" << INT2MM(to.p.Y) << " S" << getExtrusionFilamentMmPerMmMove(from.w) << " E" << getExtrusionFilamentMmPerMmMove(to.w) << "\n"; break; case type_UM3: default: coord_t w = (from.w + to.w) / 2; float speed = print_speed * nozzle_size / w; last_E += getExtrusionFilamentMmPerMmMove(w) * vSize(to.p - from.p); file << "G1 F" << print_speed << " X" << INT2MM(to.p.X) << " Y" << INT2MM(to.p.Y) << " E" << last_E << "\n"; break; } } float GcodeWriter::getExtrusionFilamentMmPerMmMove(coord_t width) { float filament_radius = 0.5 * filament_diameter; float volume_per_mm_filament = M_PI * filament_radius * filament_radius; float volume_per_mm_move = INT2MM(width) * INT2MM(layer_thickness); // v / m / (v / f) = f / m return volume_per_mm_move / volume_per_mm_filament * extrusion_multiplier; } } // namespace arachne <commit_msg>lil end gcode<commit_after>//Copyright (c) 2019 Ultimaker B.V. #include "GcodeWriter.h" #include "pathOrderOptimizer.h" namespace arachne { GcodeWriter::GcodeWriter(std::string filename, int type, coord_t layer_thickness, float print_speed, float travel_speed, float extrusion_multiplier) : file(filename.c_str()) , type(type) , layer_thickness(layer_thickness) , print_speed(print_speed) , travel_speed(travel_speed) , extrusion_multiplier(extrusion_multiplier) { assert(file.good()); file << ";START_OF_HEADER\n"; file << ";HEADER_VERSION:0.1\n"; file << ";FLAVOR:Griffin\n"; file << ";GENERATOR.NAME:libArachne\n"; file << ";GENERATOR.VERSION:3.1.0\n"; file << ";GENERATOR.BUILD_DATE:2017-12-05\n"; file << ";TARGET_MACHINE.NAME:Ultimaker 3\n"; file << ";EXTRUDER_TRAIN.0.INITIAL_TEMPERATURE:215\n"; file << ";EXTRUDER_TRAIN.0.MATERIAL.VOLUME_USED:9172\n"; file << ";EXTRUDER_TRAIN.0.MATERIAL.GUID:506c9f0d-e3aa-4bd4-b2d2-23e2425b1aa9\n"; file << ";EXTRUDER_TRAIN.0.NOZZLE.DIAMETER:0.4\n"; file << ";EXTRUDER_TRAIN.0.NOZZLE.NAME:AA 0.4\n"; file << ";BUILD_PLATE.INITIAL_TEMPERATURE:20\n"; file << ";PRINT.TIME:5201\n"; file << ";PRINT.SIZE.MIN.X:9\n"; file << ";PRINT.SIZE.MIN.Y:6\n"; file << ";PRINT.SIZE.MIN.Z:0.27\n"; file << ";PRINT.SIZE.MAX.X:173.325\n"; file << ";PRINT.SIZE.MAX.Y:164.325\n"; file << ";PRINT.SIZE.MAX.Z:60.03\n"; file << ";END_OF_HEADER\n"; file << ";Generated with libArachne\n"; file << "\n"; file << "T0\n"; file << "M82 ; absolute extrusion mode\n"; file << "G92 E0\n"; file << "M109 S215\n"; file << "G0 F15000 X9 Y6 Z2\n"; file << "G280\n"; file << "G1 F1500 E-6.5\n"; file << ";LAYER_COUNT:1\n"; file << ";LAYER:0\n"; file << "M107\n"; file << "M204 S625; set acceleration\n"; file << "M205 X6 Y6; set jerk\n"; file << "G0 F" << travel_speed << " X" << INT2MM(build_plate_middle.X / 2) << " Y" << INT2MM(build_plate_middle.Y / 2) << " Z" << (INT2MM(layer_thickness) + 0.18) << " ; start location\n"; file << "G0 E0 F1500 ; unretract\n"; file << "\n"; file << "M214 K1.0 ; bueno linear advance\n"; // file << "M83 ;relative extrusion mode\n"; file << "\n"; cur_pos = build_plate_middle; } GcodeWriter::~GcodeWriter() { file << "G0 F" << travel_speed << " X" << 20 << " Y" << 20 << " Z" << (INT2MM(layer_thickness) + 0.18) << " ; start location\n"; // file << "M214 K0.0\n"; file << "G92 E0\n"; file << "M107\n"; file.close(); } void GcodeWriter::printBrim(AABB aabb, coord_t count, coord_t w, coord_t dist) { std::vector<std::list<ExtrusionLine>> polygons_per_index; std::vector<std::list<ExtrusionLine>> polylines_per_index; polygons_per_index.resize(1); std::list<ExtrusionLine>& polygons = polygons_per_index[0]; Polygons prev; prev.add(aabb.toPolygon()); prev = prev.offset(dist * 2); for (int i = 0; i < count; i++) { Polygons skuurt = prev.offset(dist, ClipperLib::jtRound); for (PolygonRef poly : skuurt) { polygons.emplace_back(0, true); ExtrusionLine& polygon = polygons.back(); for (Point p : poly) { polygon.junctions.emplace_back(p, w, 0); } } prev = skuurt; } print(polygons_per_index, polylines_per_index, aabb); } void GcodeWriter::print(std::vector<std::list<ExtrusionLine>>& polygons_per_index, std::vector<std::list<ExtrusionLine>>& polylines_per_index, AABB aabb) { std::vector<std::vector<ExtrusionLine>> polygons_per_index_vector; polygons_per_index_vector.resize(polygons_per_index.size()); for (coord_t inset_idx = 0; inset_idx < polygons_per_index.size(); inset_idx++) polygons_per_index_vector[inset_idx].insert(polygons_per_index_vector[inset_idx].end(), polygons_per_index[inset_idx].begin(), polygons_per_index[inset_idx].end()); std::vector<std::vector<ExtrusionLine>> polylines_per_index_vector; polylines_per_index_vector.resize(polylines_per_index.size()); for (coord_t inset_idx = 0; inset_idx < polylines_per_index.size(); inset_idx++) polylines_per_index_vector[inset_idx].insert(polylines_per_index_vector[inset_idx].end(), polylines_per_index[inset_idx].begin(), polylines_per_index[inset_idx].end()); reduction = aabb.getMiddle() - build_plate_middle; for (int inset_idx = 0; inset_idx < std::max(polygons_per_index_vector.size(), polylines_per_index_vector.size()); inset_idx++) { if (inset_idx < polylines_per_index_vector.size()) { LineOrderOptimizer order_optimizer(cur_pos); Polygons recreated; for (ExtrusionLine& polyline : polylines_per_index_vector[inset_idx]) { PolygonRef recreated_poly = recreated.newPoly(); recreated_poly.add(polyline.junctions.front().p); recreated_poly.add(polyline.junctions.back().p); } order_optimizer.addPolygons(recreated); order_optimizer.optimize(); for (int poly_idx : order_optimizer.polyOrder) { ExtrusionLine& polyline = polylines_per_index_vector[inset_idx][poly_idx]; int start_idx = order_optimizer.polyStart[poly_idx]; assert(start_idx < polyline.junctions.size()); if (start_idx == 0) { auto last = polyline.junctions.begin(); move(last->p); for (auto junction_it = ++polyline.junctions.begin(); junction_it != polyline.junctions.end(); ++junction_it) { ExtrusionJunction& junction = *junction_it; print(*last, junction); last = junction_it; } } else { auto last = polyline.junctions.rbegin(); move(last->p); for (auto junction_it = ++polyline.junctions.rbegin(); junction_it != polyline.junctions.rend(); ++junction_it) { ExtrusionJunction& junction = *junction_it; print(*last, junction); last = junction_it; } } } } if (inset_idx < polygons_per_index_vector.size()) { PathOrderOptimizer order_optimizer(cur_pos); Polygons recreated; for (ExtrusionLine& polygon : polygons_per_index_vector[inset_idx]) { PolygonRef recreated_poly = recreated.newPoly(); for (ExtrusionJunction& j : polygon.junctions) { recreated_poly.add(j.p); } } order_optimizer.addPolygons(recreated); order_optimizer.optimize(); for (int poly_idx : order_optimizer.polyOrder) { ExtrusionLine& polygon = polygons_per_index_vector[inset_idx][poly_idx]; int start_idx = order_optimizer.polyStart[poly_idx]; assert(start_idx < polygon.junctions.size()); auto first = polygon.junctions.begin(); std::advance(first, start_idx); move(first->p); auto prev = first; auto second = first; second++; for (auto junction_it = second; ; ++junction_it) { if (junction_it == polygon.junctions.end()) junction_it = polygon.junctions.begin(); ExtrusionJunction& junction = *junction_it; print(*prev, junction); prev = junction_it; if (junction_it == first) break; } } } } } void GcodeWriter::move(Point p) { file << "\n"; p -= reduction; switch(type) { case type_P3: file << "G5 F" << travel_speed << " X" << INT2MM(p.X) << " Y" << INT2MM(p.Y) << " S0 E0\n"; break; case type_UM3: default: file << "G0 X" << INT2MM(p.X) << " Y" << INT2MM(p.Y) << "\n"; break; } cur_pos = p; } void GcodeWriter::print(ExtrusionJunction from, ExtrusionJunction to) { from.p -= reduction; to.p -= reduction; assert(from.p == cur_pos); bool discretize = type != type_P3 && std::abs(to.w - from.w) > 10; if (from.p == to.p) { return; } if (!discretize) { printSingleExtrusionMove(from, to); } else { Point vec = to.p - from.p; coord_t length = vSize(vec); coord_t segment_count = (length + discretization_size / 2) / discretization_size; // round to nearest ExtrusionJunction last = from; for (coord_t segment_idx = 0; segment_idx < segment_count; segment_idx++) { ExtrusionJunction here(from.p + vec * (segment_idx + 1) / segment_count, from.w + (to.w - from.w) * (segment_idx + 1) / segment_count, last.perimeter_index); printSingleExtrusionMove(last, here); last = here; } } cur_pos = to.p; } void GcodeWriter::printSingleExtrusionMove(ExtrusionJunction& from, ExtrusionJunction& to) { switch(type) { case type_P3: file << "G5 F" << print_speed << " X" << INT2MM(to.p.X) << " Y" << INT2MM(to.p.Y) << " S" << getExtrusionFilamentMmPerMmMove(from.w) << " E" << getExtrusionFilamentMmPerMmMove(to.w) << "\n"; break; case type_UM3: default: coord_t w = (from.w + to.w) / 2; float speed = print_speed * nozzle_size / w; last_E += getExtrusionFilamentMmPerMmMove(w) * vSize(to.p - from.p); file << "G1 F" << print_speed << " X" << INT2MM(to.p.X) << " Y" << INT2MM(to.p.Y) << " E" << last_E << "\n"; break; } } float GcodeWriter::getExtrusionFilamentMmPerMmMove(coord_t width) { float filament_radius = 0.5 * filament_diameter; float volume_per_mm_filament = M_PI * filament_radius * filament_radius; float volume_per_mm_move = INT2MM(width) * INT2MM(layer_thickness); // v / m / (v / f) = f / m return volume_per_mm_move / volume_per_mm_filament * extrusion_multiplier; } } // namespace arachne <|endoftext|>
<commit_before>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Miodrag Milanovic <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "treemodel.h" NEXTPNR_NAMESPACE_BEGIN static bool contextTreeItemLessThan(const ContextTreeItem *v1, const ContextTreeItem *v2) { return v1->name() < v2->name(); } ContextTreeItem::ContextTreeItem() { parentNode = nullptr; } ContextTreeItem::ContextTreeItem(QString name) : parentNode(nullptr), itemId(IdString()), itemType(ElementType::NONE), itemName(name) { } ContextTreeItem::ContextTreeItem(IdString id, ElementType type, QString name) : parentNode(nullptr), itemId(id), itemType(type), itemName(name) { } ContextTreeItem::~ContextTreeItem() { if (parentNode) parentNode->children.removeOne(this); qDeleteAll(children); } void ContextTreeItem::addChild(ContextTreeItem *item) { item->parentNode = this; children.append(item); } void ContextTreeItem::sort() { for (auto item : children) if (item->count()>1) item->sort(); qSort(children.begin(), children.end(), contextTreeItemLessThan); } ContextTreeModel::ContextTreeModel(QObject *parent) : QAbstractItemModel(parent) { root = new ContextTreeItem(); } ContextTreeModel::~ContextTreeModel() { delete root; } void ContextTreeModel::loadData(Context *ctx) { if (!ctx) return; beginResetModel(); delete root; root = new ContextTreeItem(); for (int i = 0; i < 6; i++) nameToItem[i].clear(); IdString none; ContextTreeItem *bels_root = new ContextTreeItem("Bels"); root->addChild(bels_root); QMap<QString, ContextTreeItem *> bel_items; // Add bels to tree for (auto bel : ctx->getBels()) { IdString id = ctx->getBelName(bel); QStringList items = QString(id.c_str(ctx)).split("/"); QString name; ContextTreeItem *parent = bels_root; for (int i = 0; i < items.size(); i++) { if (!name.isEmpty()) name += "/"; name += items.at(i); if (!bel_items.contains(name)) { if (i == items.size() - 1) { ContextTreeItem *item = new ContextTreeItem(id, ElementType::BEL, items.at(i)); parent->addChild(item); nameToItem[0].insert(name, item); } else { ContextTreeItem *item = new ContextTreeItem(none, ElementType::NONE, items.at(i)); parent->addChild(item); bel_items.insert(name, item); } } parent = bel_items[name]; } } bels_root->sort(); ContextTreeItem *wire_root = new ContextTreeItem("Wires"); root->addChild(wire_root); QMap<QString, ContextTreeItem *> wire_items; // Add wires to tree for (auto wire : ctx->getWires()) { auto id = ctx->getWireName(wire); QStringList items = QString(id.c_str(ctx)).split("/"); QString name; ContextTreeItem *parent = wire_root; for (int i = 0; i < items.size(); i++) { if (!name.isEmpty()) name += "/"; name += items.at(i); if (!wire_items.contains(name)) { if (i == items.size() - 1) { ContextTreeItem *item = new ContextTreeItem(id, ElementType::WIRE, items.at(i)); parent->addChild(item); nameToItem[1].insert(name, item); } else { ContextTreeItem *item = new ContextTreeItem(none, ElementType::NONE, items.at(i)); parent->addChild(item); wire_items.insert(name, item); } } parent = wire_items[name]; } } wire_root->sort(); ContextTreeItem *pip_root = new ContextTreeItem("Pips"); root->addChild(pip_root); QMap<QString, ContextTreeItem *> pip_items; // Add pips to tree for (auto pip : ctx->getPips()) { auto id = ctx->getPipName(pip); QStringList items = QString(id.c_str(ctx)).split("/"); QString name; ContextTreeItem *parent = pip_root; for (int i = 0; i < items.size(); i++) { if (!name.isEmpty()) name += "/"; name += items.at(i); if (!pip_items.contains(name)) { if (i == items.size() - 1) { ContextTreeItem *item = new ContextTreeItem(id, ElementType::PIP, items.at(i)); parent->addChild(item); nameToItem[2].insert(name, item); } else { ContextTreeItem *item = new ContextTreeItem(none, ElementType::NONE, items.at(i)); parent->addChild(item); pip_items.insert(name, item); } } parent = pip_items[name]; } } pip_root->sort(); nets_root = new ContextTreeItem("Nets"); root->addChild(nets_root); cells_root = new ContextTreeItem("Cells"); root->addChild(cells_root); endResetModel(); } void ContextTreeModel::updateData(Context *ctx) { if (!ctx) return; beginResetModel(); //QModelIndex nets_index = indexFromNode(nets_root); // Remove nets not existing any more QMap<QString, ContextTreeItem *>::iterator i = nameToItem[3].begin(); while (i != nameToItem[3].end()) { QMap<QString, ContextTreeItem *>::iterator prev = i; ++i; if (ctx->nets.find(ctx->id(prev.key().toStdString())) == ctx->nets.end()) { //int pos = prev.value()->parent()->indexOf(prev.value()); //beginRemoveRows(nets_index, pos, pos); delete prev.value(); nameToItem[3].erase(prev); //endRemoveRows(); } } // Add nets to tree for (auto &item : ctx->nets) { auto id = item.first; QString name = QString(id.c_str(ctx)); if (!nameToItem[3].contains(name)) { //beginInsertRows(nets_index, nets_root->count() + 1, nets_root->count() + 1); ContextTreeItem *newItem = new ContextTreeItem(id, ElementType::NET, name); nets_root->addChild(newItem); nameToItem[3].insert(name, newItem); //endInsertRows(); } } nets_root->sort(); //QModelIndex cell_index = indexFromNode(cells_root); // Remove cells not existing any more i = nameToItem[4].begin(); while (i != nameToItem[4].end()) { QMap<QString, ContextTreeItem *>::iterator prev = i; ++i; if (ctx->cells.find(ctx->id(prev.key().toStdString())) == ctx->cells.end()) { //int pos = prev.value()->parent()->indexOf(prev.value()); //beginRemoveRows(cell_index, pos, pos); delete prev.value(); nameToItem[4].erase(prev); //endRemoveRows(); } } // Add cells to tree for (auto &item : ctx->cells) { auto id = item.first; QString name = QString(id.c_str(ctx)); if (!nameToItem[4].contains(name)) { //beginInsertRows(cell_index, cells_root->count() + 1, cells_root->count() + 1); ContextTreeItem *newItem = new ContextTreeItem(id, ElementType::CELL, name); cells_root->addChild(newItem); nameToItem[4].insert(name, newItem); //endInsertRows(); } } cells_root->sort(); endResetModel(); } int ContextTreeModel::rowCount(const QModelIndex &parent) const { return nodeFromIndex(parent)->count(); } int ContextTreeModel::columnCount(const QModelIndex &parent) const { return 1; } QModelIndex ContextTreeModel::index(int row, int column, const QModelIndex &parent) const { ContextTreeItem *node = nodeFromIndex(parent); if (row >= node->count()) return QModelIndex(); return createIndex(row, column, node->at(row)); } QModelIndex ContextTreeModel::parent(const QModelIndex &child) const { ContextTreeItem *parent = nodeFromIndex(child)->parent(); if (parent == root) return QModelIndex(); ContextTreeItem *node = parent->parent(); return createIndex(node->indexOf(parent), 0, parent); } QVariant ContextTreeModel::data(const QModelIndex &index, int role) const { if (index.column() != 0) return QVariant(); if (role != Qt::DisplayRole) return QVariant(); ContextTreeItem *node = nodeFromIndex(index); return node->name(); } QVariant ContextTreeModel::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(section); if (orientation == Qt::Horizontal && role == Qt::DisplayRole) return QString("Items"); return QVariant(); } ContextTreeItem *ContextTreeModel::nodeFromIndex(const QModelIndex &idx) const { if (idx.isValid()) return (ContextTreeItem *)idx.internalPointer(); return root; } static int getElementIndex(ElementType type) { if (type == ElementType::BEL) return 0; if (type == ElementType::WIRE) return 1; if (type == ElementType::PIP) return 2; if (type == ElementType::NET) return 3; if (type == ElementType::CELL) return 4; return -1; } ContextTreeItem *ContextTreeModel::nodeForIdType(const ElementType type, const QString name) const { int index = getElementIndex(type); if (type != ElementType::NONE && nameToItem[index].contains(name)) return nameToItem[index].value(name); return nullptr; } QModelIndex ContextTreeModel::indexFromNode(ContextTreeItem *node) { ContextTreeItem *parent = node->parent(); if (parent == root) return QModelIndex(); return createIndex(parent->indexOf(node), 0, node); } Qt::ItemFlags ContextTreeModel::flags(const QModelIndex &index) const { ContextTreeItem *node = nodeFromIndex(index); return Qt::ItemIsEnabled | (node->type() != ElementType::NONE ? Qt::ItemIsSelectable : Qt::NoItemFlags); } QList<QModelIndex> ContextTreeModel::search(QString text) { QList<QModelIndex> list; for (int i = 0; i < 6; i++) { for (auto key : nameToItem[i].keys()) { if (key.contains(text, Qt::CaseInsensitive)) { list.append(indexFromNode(nameToItem[i].value(key))); if (list.count() > 500) break; // limit to 500 results } } } return list; } NEXTPNR_NAMESPACE_END<commit_msg>ecp5: Disable Pip list in GUI for now<commit_after>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Miodrag Milanovic <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "treemodel.h" NEXTPNR_NAMESPACE_BEGIN static bool contextTreeItemLessThan(const ContextTreeItem *v1, const ContextTreeItem *v2) { return v1->name() < v2->name(); } ContextTreeItem::ContextTreeItem() { parentNode = nullptr; } ContextTreeItem::ContextTreeItem(QString name) : parentNode(nullptr), itemId(IdString()), itemType(ElementType::NONE), itemName(name) { } ContextTreeItem::ContextTreeItem(IdString id, ElementType type, QString name) : parentNode(nullptr), itemId(id), itemType(type), itemName(name) { } ContextTreeItem::~ContextTreeItem() { if (parentNode) parentNode->children.removeOne(this); qDeleteAll(children); } void ContextTreeItem::addChild(ContextTreeItem *item) { item->parentNode = this; children.append(item); } void ContextTreeItem::sort() { for (auto item : children) if (item->count()>1) item->sort(); qSort(children.begin(), children.end(), contextTreeItemLessThan); } ContextTreeModel::ContextTreeModel(QObject *parent) : QAbstractItemModel(parent) { root = new ContextTreeItem(); } ContextTreeModel::~ContextTreeModel() { delete root; } void ContextTreeModel::loadData(Context *ctx) { if (!ctx) return; beginResetModel(); delete root; root = new ContextTreeItem(); for (int i = 0; i < 6; i++) nameToItem[i].clear(); IdString none; ContextTreeItem *bels_root = new ContextTreeItem("Bels"); root->addChild(bels_root); QMap<QString, ContextTreeItem *> bel_items; // Add bels to tree for (auto bel : ctx->getBels()) { IdString id = ctx->getBelName(bel); QStringList items = QString(id.c_str(ctx)).split("/"); QString name; ContextTreeItem *parent = bels_root; for (int i = 0; i < items.size(); i++) { if (!name.isEmpty()) name += "/"; name += items.at(i); if (!bel_items.contains(name)) { if (i == items.size() - 1) { ContextTreeItem *item = new ContextTreeItem(id, ElementType::BEL, items.at(i)); parent->addChild(item); nameToItem[0].insert(name, item); } else { ContextTreeItem *item = new ContextTreeItem(none, ElementType::NONE, items.at(i)); parent->addChild(item); bel_items.insert(name, item); } } parent = bel_items[name]; } } bels_root->sort(); ContextTreeItem *wire_root = new ContextTreeItem("Wires"); root->addChild(wire_root); QMap<QString, ContextTreeItem *> wire_items; // Add wires to tree for (auto wire : ctx->getWires()) { auto id = ctx->getWireName(wire); QStringList items = QString(id.c_str(ctx)).split("/"); QString name; ContextTreeItem *parent = wire_root; for (int i = 0; i < items.size(); i++) { if (!name.isEmpty()) name += "/"; name += items.at(i); if (!wire_items.contains(name)) { if (i == items.size() - 1) { ContextTreeItem *item = new ContextTreeItem(id, ElementType::WIRE, items.at(i)); parent->addChild(item); nameToItem[1].insert(name, item); } else { ContextTreeItem *item = new ContextTreeItem(none, ElementType::NONE, items.at(i)); parent->addChild(item); wire_items.insert(name, item); } } parent = wire_items[name]; } } wire_root->sort(); ContextTreeItem *pip_root = new ContextTreeItem("Pips"); root->addChild(pip_root); QMap<QString, ContextTreeItem *> pip_items; // Add pips to tree #ifndef ARCH_ECP5 for (auto pip : ctx->getPips()) { auto id = ctx->getPipName(pip); QStringList items = QString(id.c_str(ctx)).split("/"); QString name; ContextTreeItem *parent = pip_root; for (int i = 0; i < items.size(); i++) { if (!name.isEmpty()) name += "/"; name += items.at(i); if (!pip_items.contains(name)) { if (i == items.size() - 1) { ContextTreeItem *item = new ContextTreeItem(id, ElementType::PIP, items.at(i)); parent->addChild(item); nameToItem[2].insert(name, item); } else { ContextTreeItem *item = new ContextTreeItem(none, ElementType::NONE, items.at(i)); parent->addChild(item); pip_items.insert(name, item); } } parent = pip_items[name]; } } #endif pip_root->sort(); nets_root = new ContextTreeItem("Nets"); root->addChild(nets_root); cells_root = new ContextTreeItem("Cells"); root->addChild(cells_root); endResetModel(); } void ContextTreeModel::updateData(Context *ctx) { if (!ctx) return; beginResetModel(); //QModelIndex nets_index = indexFromNode(nets_root); // Remove nets not existing any more QMap<QString, ContextTreeItem *>::iterator i = nameToItem[3].begin(); while (i != nameToItem[3].end()) { QMap<QString, ContextTreeItem *>::iterator prev = i; ++i; if (ctx->nets.find(ctx->id(prev.key().toStdString())) == ctx->nets.end()) { //int pos = prev.value()->parent()->indexOf(prev.value()); //beginRemoveRows(nets_index, pos, pos); delete prev.value(); nameToItem[3].erase(prev); //endRemoveRows(); } } // Add nets to tree for (auto &item : ctx->nets) { auto id = item.first; QString name = QString(id.c_str(ctx)); if (!nameToItem[3].contains(name)) { //beginInsertRows(nets_index, nets_root->count() + 1, nets_root->count() + 1); ContextTreeItem *newItem = new ContextTreeItem(id, ElementType::NET, name); nets_root->addChild(newItem); nameToItem[3].insert(name, newItem); //endInsertRows(); } } nets_root->sort(); //QModelIndex cell_index = indexFromNode(cells_root); // Remove cells not existing any more i = nameToItem[4].begin(); while (i != nameToItem[4].end()) { QMap<QString, ContextTreeItem *>::iterator prev = i; ++i; if (ctx->cells.find(ctx->id(prev.key().toStdString())) == ctx->cells.end()) { //int pos = prev.value()->parent()->indexOf(prev.value()); //beginRemoveRows(cell_index, pos, pos); delete prev.value(); nameToItem[4].erase(prev); //endRemoveRows(); } } // Add cells to tree for (auto &item : ctx->cells) { auto id = item.first; QString name = QString(id.c_str(ctx)); if (!nameToItem[4].contains(name)) { //beginInsertRows(cell_index, cells_root->count() + 1, cells_root->count() + 1); ContextTreeItem *newItem = new ContextTreeItem(id, ElementType::CELL, name); cells_root->addChild(newItem); nameToItem[4].insert(name, newItem); //endInsertRows(); } } cells_root->sort(); endResetModel(); } int ContextTreeModel::rowCount(const QModelIndex &parent) const { return nodeFromIndex(parent)->count(); } int ContextTreeModel::columnCount(const QModelIndex &parent) const { return 1; } QModelIndex ContextTreeModel::index(int row, int column, const QModelIndex &parent) const { ContextTreeItem *node = nodeFromIndex(parent); if (row >= node->count()) return QModelIndex(); return createIndex(row, column, node->at(row)); } QModelIndex ContextTreeModel::parent(const QModelIndex &child) const { ContextTreeItem *parent = nodeFromIndex(child)->parent(); if (parent == root) return QModelIndex(); ContextTreeItem *node = parent->parent(); return createIndex(node->indexOf(parent), 0, parent); } QVariant ContextTreeModel::data(const QModelIndex &index, int role) const { if (index.column() != 0) return QVariant(); if (role != Qt::DisplayRole) return QVariant(); ContextTreeItem *node = nodeFromIndex(index); return node->name(); } QVariant ContextTreeModel::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(section); if (orientation == Qt::Horizontal && role == Qt::DisplayRole) return QString("Items"); return QVariant(); } ContextTreeItem *ContextTreeModel::nodeFromIndex(const QModelIndex &idx) const { if (idx.isValid()) return (ContextTreeItem *)idx.internalPointer(); return root; } static int getElementIndex(ElementType type) { if (type == ElementType::BEL) return 0; if (type == ElementType::WIRE) return 1; if (type == ElementType::PIP) return 2; if (type == ElementType::NET) return 3; if (type == ElementType::CELL) return 4; return -1; } ContextTreeItem *ContextTreeModel::nodeForIdType(const ElementType type, const QString name) const { int index = getElementIndex(type); if (type != ElementType::NONE && nameToItem[index].contains(name)) return nameToItem[index].value(name); return nullptr; } QModelIndex ContextTreeModel::indexFromNode(ContextTreeItem *node) { ContextTreeItem *parent = node->parent(); if (parent == root) return QModelIndex(); return createIndex(parent->indexOf(node), 0, node); } Qt::ItemFlags ContextTreeModel::flags(const QModelIndex &index) const { ContextTreeItem *node = nodeFromIndex(index); return Qt::ItemIsEnabled | (node->type() != ElementType::NONE ? Qt::ItemIsSelectable : Qt::NoItemFlags); } QList<QModelIndex> ContextTreeModel::search(QString text) { QList<QModelIndex> list; for (int i = 0; i < 6; i++) { for (auto key : nameToItem[i].keys()) { if (key.contains(text, Qt::CaseInsensitive)) { list.append(indexFromNode(nameToItem[i].value(key))); if (list.count() > 500) break; // limit to 500 results } } } return list; } NEXTPNR_NAMESPACE_END <|endoftext|>
<commit_before>/// @brief Unit test for the allpass filter class /// @author Timothy Place // @copyright Copyright (c) 2017, Cycling '74 /// @license This project is released under the terms of the MIT License. #define CATCH_CONFIG_MAIN #include "c74_min_catch.h" SCENARIO ("Produce the correct impulse response") { GIVEN ("An instance of the allpass filter class") { c74::min::lib::allpass f; REQUIRE( f.gain() == 0.0 ); // check the defaults REQUIRE( f.delay() == 4410 ); // ... f.delay(1); f.gain(0.5); WHEN ("processing a 64-sample impulse") { // create an impulse buffer to process const int buffersize = 64; c74::min::sample_vector impulse(buffersize); std::fill_n(impulse.begin(), buffersize, 0.0); impulse[0] = 1.0; // output from our object's processing c74::min::sample_vector output; // run the calculations for (auto x : impulse) { auto y = f(x); output.push_back(y); } // coefficients calculated in Octave // a = [0.5, 1.0]; % numerator (fir) // b = [1.0, 0.5]; % denominator (iir) // i = impz(a, b, 64); c74::min::sample_vector reference = { 0.500000000000000 , 0.750000000000000 , -0.375000000000000 , 0.187500000000000 , -0.0937500000000000 , 0.0468750000000000 , -0.0234375000000000 , 0.0117187500000000 , -0.00585937500000000 , 0.00292968750000000 , -0.00146484375000000 , 0.000732421875000000 , -0.000366210937500000, 0.000183105468750000 , -9.15527343750000e-05, 4.57763671875000e-05 , -2.28881835937500e-05, 1.14440917968750e-05 , -5.72204589843750e-06, 2.86102294921875e-06 , -1.43051147460938e-06, 7.15255737304688e-07 , -3.57627868652344e-07, 1.78813934326172e-07 , -8.94069671630859e-08, 4.47034835815430e-08 , -2.23517417907715e-08, 1.11758708953857e-08 , -5.58793544769287e-09, 2.79396772384644e-09 , -1.39698386192322e-09, 6.98491930961609e-10 , -3.49245965480804e-10, 1.74622982740402e-10 , -8.73114913702011e-11, 4.36557456851006e-11 , -2.18278728425503e-11, 1.09139364212751e-11 , -5.45696821063757e-12, 2.72848410531878e-12 , -1.36424205265939e-12, 6.82121026329696e-13 , -3.41060513164848e-13, 1.70530256582424e-13 , -8.52651282912120e-14, 4.26325641456060e-14 , -2.13162820728030e-14, 1.06581410364015e-14 , -5.32907051820075e-15, 2.66453525910038e-15 , -1.33226762955019e-15, 6.66133814775094e-16 , -3.33066907387547e-16, 1.66533453693773e-16 , -8.32667268468867e-17, 4.16333634234434e-17 , -2.08166817117217e-17, 1.04083408558608e-17 , -5.20417042793042e-18, 2.60208521396521e-18 , -1.30104260698261e-18, 6.50521303491303e-19 , -3.25260651745651e-19, 1.62630325872826e-19 }; THEN("The result produced matches an externally produced reference impulse") // check it REQUIRE_VECTOR_APPROX(output, reference); } } } SCENARIO ("Using non-default settings") { WHEN ("Overriding the default capacity for allpass filter") { c74::min::lib::allpass f(4800); THEN("The size has been set correctly.") REQUIRE( f.delay() == 4800 ); WHEN("Changing the size to less than default capacity") { f.delay(1000); THEN("The size has been set correctly.") REQUIRE( f.delay() == 1000 ); WHEN ("processing a 1100-sample impulse") { // create an impulse buffer to process const int buffersize = 1100; c74::min::sample_vector impulse(buffersize); std::fill_n(impulse.begin(), buffersize, 0.0); impulse[0] = 1.0; // output from our object's processing c74::min::sample_vector output; // run the calculations for (auto x : impulse) { auto y = f(x); output.push_back(y); } } // What can we test here? WHEN("Changing the size again to a higher value, but still less than default capacity") f.delay(2000); THEN("The size has been set correctly.") REQUIRE( f.delay() == 2000 ); WHEN ("processing another 1100-sample impulse") { // create an impulse buffer to process const int buffersize = 1100; c74::min::sample_vector impulse(buffersize); std::fill_n(impulse.begin(), buffersize, 0.0); impulse[0] = 1.0; // output from our object's processing c74::min::sample_vector output; // run the calculations for (auto x : impulse) { auto y = f(x); output.push_back(y); } } // What can we test here? } } } <commit_msg>allpass unit test: commenting out all the evil Catch macros that make the order of execution completely non-obvious and not what is intended.<commit_after>/// @brief Unit test for the allpass filter class /// @author Timothy Place // @copyright Copyright (c) 2017, Cycling '74 /// @license This project is released under the terms of the MIT License. #define CATCH_CONFIG_MAIN #include "c74_min_catch.h" SCENARIO ("Produce the correct impulse response") { GIVEN ("An instance of the allpass filter class") { c74::min::lib::allpass f; REQUIRE( f.gain() == 0.0 ); // check the defaults REQUIRE( f.delay() == 4410 ); // ... f.delay(1); f.gain(0.5); WHEN ("processing a 64-sample impulse") { // create an impulse buffer to process const int buffersize = 64; c74::min::sample_vector impulse(buffersize); std::fill_n(impulse.begin(), buffersize, 0.0); impulse[0] = 1.0; // output from our object's processing c74::min::sample_vector output; // run the calculations for (auto x : impulse) { auto y = f(x); output.push_back(y); } // coefficients calculated in Octave // a = [0.5, 1.0]; % numerator (fir) // b = [1.0, 0.5]; % denominator (iir) // i = impz(a, b, 64); c74::min::sample_vector reference = { 0.500000000000000 , 0.750000000000000 , -0.375000000000000 , 0.187500000000000 , -0.0937500000000000 , 0.0468750000000000 , -0.0234375000000000 , 0.0117187500000000 , -0.00585937500000000 , 0.00292968750000000 , -0.00146484375000000 , 0.000732421875000000 , -0.000366210937500000, 0.000183105468750000 , -9.15527343750000e-05, 4.57763671875000e-05 , -2.28881835937500e-05, 1.14440917968750e-05 , -5.72204589843750e-06, 2.86102294921875e-06 , -1.43051147460938e-06, 7.15255737304688e-07 , -3.57627868652344e-07, 1.78813934326172e-07 , -8.94069671630859e-08, 4.47034835815430e-08 , -2.23517417907715e-08, 1.11758708953857e-08 , -5.58793544769287e-09, 2.79396772384644e-09 , -1.39698386192322e-09, 6.98491930961609e-10 , -3.49245965480804e-10, 1.74622982740402e-10 , -8.73114913702011e-11, 4.36557456851006e-11 , -2.18278728425503e-11, 1.09139364212751e-11 , -5.45696821063757e-12, 2.72848410531878e-12 , -1.36424205265939e-12, 6.82121026329696e-13 , -3.41060513164848e-13, 1.70530256582424e-13 , -8.52651282912120e-14, 4.26325641456060e-14 , -2.13162820728030e-14, 1.06581410364015e-14 , -5.32907051820075e-15, 2.66453525910038e-15 , -1.33226762955019e-15, 6.66133814775094e-16 , -3.33066907387547e-16, 1.66533453693773e-16 , -8.32667268468867e-17, 4.16333634234434e-17 , -2.08166817117217e-17, 1.04083408558608e-17 , -5.20417042793042e-18, 2.60208521396521e-18 , -1.30104260698261e-18, 6.50521303491303e-19 , -3.25260651745651e-19, 1.62630325872826e-19 }; THEN("The result produced matches an externally produced reference impulse") // check it REQUIRE_VECTOR_APPROX(output, reference); } } } SCENARIO ("Using non-default settings") { // WHEN ("Overriding the default capacity for allpass filter") { c74::min::lib::allpass f(4800); // THEN("The size has been set correctly.") REQUIRE( f.delay() == 4800 ); // WHEN("Changing the size to less than default capacity") { f.delay(1000); // THEN("The size has been set correctly.") REQUIRE( f.delay() == 1000 ); // WHEN ("processing a 1100-sample impulse") { { // create an impulse buffer to process const int buffersize = 1100; c74::min::sample_vector impulse(buffersize); std::fill_n(impulse.begin(), buffersize, 0.0); impulse[0] = 1.0; // output from our object's processing c74::min::sample_vector output; // run the calculations for (auto x : impulse) { auto y = f(x); output.push_back(y); } } // What can we test here? // WHEN("Changing the size again to a higher value, but still less than default capacity") f.delay(2000); // THEN("The size has been set correctly.") REQUIRE( f.delay() == 2000 ); // WHEN ("processing another 1100-sample impulse") { // create an impulse buffer to process const int buffersize = 1100; c74::min::sample_vector impulse(buffersize); std::fill_n(impulse.begin(), buffersize, 0.0); impulse[0] = 1.0; // output from our object's processing c74::min::sample_vector output; // run the calculations for (auto x : impulse) { auto y = f(x); output.push_back(y); } } // What can we test here? // } // } } <|endoftext|>
<commit_before>#pragma once #include <coppa/oscquery/json/parser.detail.hpp> namespace coppa { namespace oscquery { namespace JSON { using val_t = json_value::type; class parser { public: static int getPort(const std::string& message) { using namespace detail; const json_map obj{ message }; json_assert(obj.get(Key::osc_port()).is(val_t::integer)); return obj.get<int>(Key::osc_port()); } static MessageType messageType(const std::string& message) { using namespace detail; const json_map obj{ message }; if(obj.find(Key::osc_port()) != obj.end()) return MessageType::Device; else if(obj.find(Key::path_added()) != obj.end()) return MessageType::PathAdded; else if(obj.find(Key::path_removed()) != obj.end()) return MessageType::PathRemoved; else if(obj.find(Key::path_changed()) != obj.end()) return MessageType::PathChanged; else if(obj.find(Key::attributes_changed()) != obj.end()) return MessageType::AttributesChanged; else if(obj.find(Key::paths_added()) != obj.end()) return MessageType::PathsAdded; else if(obj.find(Key::paths_removed()) != obj.end()) return MessageType::PathsRemoved; else if(obj.find(Key::paths_changed()) != obj.end()) return MessageType::PathsChanged; else if(obj.find(Key::attributes_changed_array()) != obj.end()) return MessageType::AttributesChangedArray; else return MessageType::Namespace; // TODO More checks needed } template<typename Map> static auto parseNamespace(const json_map& obj) { using namespace detail; Map map; readObject(map, obj); return map; } template<typename Map> static auto parseNamespace(const std::string& message) { using namespace detail; return parseNamespace<Map>(json_map{message}); } template<typename BaseMapType, typename Map> static void path_added(Map& map, const std::string& message) { using namespace detail; json_map obj{message}; map.merge(parseNamespace<BaseMapType>(obj.get<json_map>(Key::path_added()))); } template<typename Map> static void path_changed(Map& map, const std::string& message) { using namespace detail; json_map mess{message}; // Get the object const auto& obj = mess.get<json_map>(Key::path_changed()); // 2. Remove the existing path map.remove(valToString(obj.get(Key::full_path()))); // 3. Replace it readObject(map, obj); } template<typename Map> static void path_removed(Map& map, const std::string& message) { using namespace detail; json_map obj{message}; const auto& path = valToString(obj.get(Key::path_removed())); json_assert(map.existing_path(path)); map.remove(path); } template<typename Map> static void attributes_changed(Map& map, const std::string& message) { using namespace detail; json_map obj{message}; const auto& attr_changed = obj.get<json_map>(Key::attributes_changed()); // 1. Search for the paths for(const auto& path : attr_changed.get_keys()) { json_assert(map.has(path)); const auto& path_obj = attr_changed.get<json_map>(path); // A lambda used to update the boost map. // Here, since we are in attributes_changed, we will just ignore // the missing members. auto mapper = [&] (const std::string& name, auto&& member, auto&& method) { if(path_obj.find(name) != path_obj.end()) map.update(path, [&] (Parameter& p) { p.*member = method(path_obj.get(name)); }); }; // 2. Map the values mapper(Key::attribute<Description>(), &Parameter::description, &valToString); mapper(Key::attribute<Tags>(), &Parameter::tags, &jsonToTags); mapper(Key::attribute<Access>(), &Parameter::accessmode, &jsonToAccessMode); mapper(Key::attribute<Values>(), &Parameter::values, &jsonToVariantArray); mapper(Key::attribute<Ranges>(), &Parameter::ranges, &jsonToRangeArray); mapper(Key::attribute<ClipModes>(), &Parameter::clipmodes, &jsonToClipModeArray); } } // Plural forms template<typename BaseMapType, typename Map> static void paths_added(Map& map, const std::string& message) { using namespace detail; json_map mess{message}; const auto& arr = detail::valToArray(mess["paths_added"]); for(const auto& elt : arr) { map.merge(parseNamespace<BaseMapType>(elt.as<json_map>())); } } template<typename Map> static void paths_changed(Map& map, const std::string& message) { std::cerr << "TODO" << std::endl; } template<typename Map> static void paths_removed(Map& map, const std::string& message) { json_map mess{message}; const auto& arr = detail::valToArray(mess["paths_removed"]); for(const auto& elt : arr) { const auto& path = detail::valToString(elt); json_assert(map.existing_path(path)); map.remove(path); } } template<typename Map> static void attributes_changed_array(Map& map, const std::string& message) { std::cerr << "TODO" << std::endl; } }; } } } <commit_msg>Cosmetic<commit_after>#pragma once #include <coppa/oscquery/json/parser.detail.hpp> namespace coppa { namespace oscquery { namespace JSON { using val_t = json_value::type; class parser { public: static int getPort(const std::string& message) { using namespace detail; const json_map obj{ message }; json_assert(obj.get(Key::osc_port()).is(val_t::integer)); return obj.get<int>(Key::osc_port()); } static MessageType messageType(const std::string& message) { using namespace detail; const json_map obj{ message }; if(obj.find(Key::osc_port()) != obj.end()) return MessageType::Device; else if(obj.find(Key::path_added()) != obj.end()) return MessageType::PathAdded; else if(obj.find(Key::path_removed()) != obj.end()) return MessageType::PathRemoved; else if(obj.find(Key::path_changed()) != obj.end()) return MessageType::PathChanged; else if(obj.find(Key::attributes_changed()) != obj.end()) return MessageType::AttributesChanged; else if(obj.find(Key::paths_added()) != obj.end()) return MessageType::PathsAdded; else if(obj.find(Key::paths_removed()) != obj.end()) return MessageType::PathsRemoved; else if(obj.find(Key::paths_changed()) != obj.end()) return MessageType::PathsChanged; else if(obj.find(Key::attributes_changed_array()) != obj.end()) return MessageType::AttributesChangedArray; else return MessageType::Namespace; // TODO More checks needed } template<typename Map> static auto parseNamespace(const json_map& obj) { using namespace detail; Map map; readObject(map, obj); return map; } template<typename Map> static auto parseNamespace(const std::string& message) { using namespace detail; return parseNamespace<Map>(json_map{message}); } template<typename BaseMapType, typename Map> static void path_added(Map& map, const std::string& message) { using namespace detail; json_map obj{message}; map.merge(parseNamespace<BaseMapType>(obj.get<json_map>(Key::path_added()))); } template<typename Map> static void path_changed(Map& map, const std::string& message) { using namespace detail; json_map mess{message}; // Get the object const auto& obj = mess.get<json_map>(Key::path_changed()); // 2. Remove the existing path map.remove(valToString(obj.get(Key::full_path()))); // 3. Replace it readObject(map, obj); } template<typename Map> static void path_removed(Map& map, const std::string& message) { using namespace detail; json_map obj{message}; const auto& path = valToString(obj.get(Key::path_removed())); json_assert(map.existing_path(path)); map.remove(path); } template<typename Map> static void attributes_changed(Map& map, const std::string& message) { using namespace detail; json_map obj{message}; const auto& attr_changed = obj.get<json_map>(Key::attributes_changed()); // 1. Search for the paths for(const auto& path : attr_changed.get_keys()) { json_assert(map.has(path)); const auto& path_obj = attr_changed.get<json_map>(path); // A lambda used to update the boost map. // Here, since we are in attributes_changed, we will just ignore // the missing members. auto mapper = [&] (const std::string& name, auto&& member, auto&& method) { if(path_obj.find(name) != path_obj.end()) map.update(path, [&] (Parameter& p) { p.*member = method(path_obj.get(name)); }); }; // 2. Map the values // TODO check that they are correct (and put in detail). mapper(Key::attribute<Description>(), &Parameter::description, &valToString); mapper(Key::attribute<Tags>(), &Parameter::tags, &jsonToTags); mapper(Key::attribute<Access>(), &Parameter::accessmode, &jsonToAccessMode); mapper(Key::attribute<Values>(), &Parameter::values, &jsonToVariantArray); mapper(Key::attribute<Ranges>(), &Parameter::ranges, &jsonToRangeArray); mapper(Key::attribute<ClipModes>(), &Parameter::clipmodes, &jsonToClipModeArray); } } // Plural forms template<typename BaseMapType, typename Map> static void paths_added(Map& map, const std::string& message) { using namespace detail; json_map mess{message}; const auto& arr = detail::valToArray(mess["paths_added"]); for(const auto& elt : arr) { map.merge(parseNamespace<BaseMapType>(elt.as<json_map>())); } } template<typename Map> static void paths_changed(Map& map, const std::string& message) { std::cerr << "TODO" << std::endl; } template<typename Map> static void paths_removed(Map& map, const std::string& message) { json_map mess{message}; const auto& arr = detail::valToArray(mess["paths_removed"]); for(const auto& elt : arr) { const auto& path = detail::valToString(elt); json_assert(map.existing_path(path)); map.remove(path); } } template<typename Map> static void attributes_changed_array(Map& map, const std::string& message) { std::cerr << "TODO" << std::endl; } }; } } } <|endoftext|>
<commit_before>/* * Copyright 2007-2019 CM4all GmbH * All rights reserved. * * author: Max Kellermann <[email protected]> * * 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. * * 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 * FOUNDATION 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 "direct.hxx" #include "CommandLine.hxx" #include "Instance.hxx" #include "TcpConnection.hxx" #include "HttpConnection.hxx" #include "Config.hxx" #include "lb_check.hxx" #include "fs/Stock.hxx" #include "fs/Balancer.hxx" #include "pipe_stock.hxx" #include "access_log/Glue.hxx" #include "ssl/Init.hxx" #include "pool/pool.hxx" #include "thread_pool.hxx" #include "fb_pool.hxx" #include "capabilities.hxx" #include "net/FailureManager.hxx" #include "system/Isolate.hxx" #include "system/SetupProcess.hxx" #include "util/PrintException.hxx" #if defined(HAVE_LIBSYSTEMD) || defined(HAVE_AVAHI) #include "odbus/Init.hxx" #include "odbus/Connection.hxx" #endif #ifdef HAVE_LIBSYSTEMD #include <systemd/sd-daemon.h> #endif #include <postgresql/libpq-fe.h> #include <assert.h> #include <unistd.h> #include <sys/signal.h> #include <sys/wait.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <netdb.h> #ifdef __linux #include <sys/prctl.h> #ifndef PR_SET_NO_NEW_PRIVS #define PR_SET_NO_NEW_PRIVS 38 #endif #endif static constexpr cap_value_t cap_keep_list[1] = { /* keep the NET_RAW capability to be able to to use the socket option IP_TRANSPARENT */ CAP_NET_RAW, }; void LbInstance::ShutdownCallback() noexcept { if (should_exit) return; should_exit = true; deinit_signals(this); thread_pool_stop(); #ifdef HAVE_AVAHI avahi_client.Close(); #endif compress_event.Cancel(); DeinitAllControls(); while (!tcp_connections.empty()) tcp_connections.front().Destroy(); while (!http_connections.empty()) http_connections.front().CloseAndDestroy(); goto_map.Clear(); DisconnectCertCaches(); DeinitAllListeners(); thread_pool_join(); monitors.clear(); pool_commit(); delete std::exchange(fs_balancer, nullptr); delete std::exchange(fs_stock, nullptr); delete std::exchange(balancer, nullptr); delete std::exchange(pipe_stock, nullptr); pool_commit(); } void LbInstance::ReloadEventCallback(int) noexcept { unsigned n_ssl_sessions = FlushSSLSessionCache(LONG_MAX); logger(3, "flushed ", n_ssl_sessions, " SSL sessions"); goto_map.FlushCaches(); Compress(); } void init_signals(LbInstance *instance) { instance->shutdown_listener.Enable(); instance->sighup_event.Enable(); } void deinit_signals(LbInstance *instance) { instance->shutdown_listener.Disable(); instance->sighup_event.Disable(); } int main(int argc, char **argv) try { const ScopeFbPoolInit fb_pool_init; /* configuration */ LbCmdLine cmdline; LbConfig config; ParseCommandLine(cmdline, config, argc, argv); LoadConfigFile(config, cmdline.config_path); LbInstance instance(config); if (cmdline.check) { const ScopeSslGlobalInit ssl_init; lb_check(instance.event_loop, config); return EXIT_SUCCESS; } /* initialize */ SetupProcess(); const ScopeSslGlobalInit ssl_init; #if defined(HAVE_LIBSYSTEMD) || defined(HAVE_AVAHI) const ODBus::ScopeInit dbus_init; dbus_connection_set_exit_on_disconnect(ODBus::Connection::GetSystem(), false); #endif /* prevent libpq from initializing libssl & libcrypto again */ PQinitOpenSSL(0, 0); direct_global_init(); init_signals(&instance); instance.InitAllControls(); instance.InitAllListeners(); instance.balancer = new BalancerMap(instance.failure_manager); instance.fs_stock = new FilteredSocketStock(instance.event_loop, cmdline.tcp_stock_limit); instance.fs_balancer = new FilteredSocketBalancer(*instance.fs_stock, instance.failure_manager); instance.pipe_stock = new PipeStock(instance.event_loop); /* launch the access logger */ instance.access_log.reset(AccessLogGlue::Create(config.access_log, &cmdline.logger_user)); /* daemonize II */ if (!cmdline.user.IsEmpty()) capabilities_pre_setuid(); cmdline.user.Apply(); #ifdef __linux /* revert the "dumpable" flag to "true" after it was cleared by setreuid(); this is necessary for two reasons: (1) we want core dumps to be able to analyze crashes; and (2) Linux kernels older than 4.10 (commit 68eb94f16227) don't allow writing to /proc/self/setgroups etc. without it, which isolate_from_filesystem() needs to do */ prctl(PR_SET_DUMPABLE, 1, 0, 0, 0); #endif /* can't change to new (empty) rootfs if we may need to reconnect to PostgreSQL eventually */ // TODO: bind-mount the PostgreSQL socket into the new rootfs if (!config.HasCertDatabase()) isolate_from_filesystem(config.HasZeroConf()); if (!cmdline.user.IsEmpty()) capabilities_post_setuid(cap_keep_list, std::size(cap_keep_list)); #ifdef __linux prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); #endif /* main loop */ instance.InitWorker(); #ifdef HAVE_LIBSYSTEMD /* tell systemd we're ready */ sd_notify(0, "READY=1"); #endif instance.event_loop.Dispatch(); /* cleanup */ instance.DeinitAllListeners(); instance.DeinitAllControls(); thread_pool_deinit(); } catch (...) { PrintException(std::current_exception()); return EXIT_FAILURE; } <commit_msg>lb/Main: drop "postgresql/" prefix from #include<commit_after>/* * Copyright 2007-2019 CM4all GmbH * All rights reserved. * * author: Max Kellermann <[email protected]> * * 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. * * 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 * FOUNDATION 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 "direct.hxx" #include "CommandLine.hxx" #include "Instance.hxx" #include "TcpConnection.hxx" #include "HttpConnection.hxx" #include "Config.hxx" #include "lb_check.hxx" #include "fs/Stock.hxx" #include "fs/Balancer.hxx" #include "pipe_stock.hxx" #include "access_log/Glue.hxx" #include "ssl/Init.hxx" #include "pool/pool.hxx" #include "thread_pool.hxx" #include "fb_pool.hxx" #include "capabilities.hxx" #include "net/FailureManager.hxx" #include "system/Isolate.hxx" #include "system/SetupProcess.hxx" #include "util/PrintException.hxx" #if defined(HAVE_LIBSYSTEMD) || defined(HAVE_AVAHI) #include "odbus/Init.hxx" #include "odbus/Connection.hxx" #endif #ifdef HAVE_LIBSYSTEMD #include <systemd/sd-daemon.h> #endif #include <libpq-fe.h> #include <assert.h> #include <unistd.h> #include <sys/signal.h> #include <sys/wait.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <netdb.h> #ifdef __linux #include <sys/prctl.h> #ifndef PR_SET_NO_NEW_PRIVS #define PR_SET_NO_NEW_PRIVS 38 #endif #endif static constexpr cap_value_t cap_keep_list[1] = { /* keep the NET_RAW capability to be able to to use the socket option IP_TRANSPARENT */ CAP_NET_RAW, }; void LbInstance::ShutdownCallback() noexcept { if (should_exit) return; should_exit = true; deinit_signals(this); thread_pool_stop(); #ifdef HAVE_AVAHI avahi_client.Close(); #endif compress_event.Cancel(); DeinitAllControls(); while (!tcp_connections.empty()) tcp_connections.front().Destroy(); while (!http_connections.empty()) http_connections.front().CloseAndDestroy(); goto_map.Clear(); DisconnectCertCaches(); DeinitAllListeners(); thread_pool_join(); monitors.clear(); pool_commit(); delete std::exchange(fs_balancer, nullptr); delete std::exchange(fs_stock, nullptr); delete std::exchange(balancer, nullptr); delete std::exchange(pipe_stock, nullptr); pool_commit(); } void LbInstance::ReloadEventCallback(int) noexcept { unsigned n_ssl_sessions = FlushSSLSessionCache(LONG_MAX); logger(3, "flushed ", n_ssl_sessions, " SSL sessions"); goto_map.FlushCaches(); Compress(); } void init_signals(LbInstance *instance) { instance->shutdown_listener.Enable(); instance->sighup_event.Enable(); } void deinit_signals(LbInstance *instance) { instance->shutdown_listener.Disable(); instance->sighup_event.Disable(); } int main(int argc, char **argv) try { const ScopeFbPoolInit fb_pool_init; /* configuration */ LbCmdLine cmdline; LbConfig config; ParseCommandLine(cmdline, config, argc, argv); LoadConfigFile(config, cmdline.config_path); LbInstance instance(config); if (cmdline.check) { const ScopeSslGlobalInit ssl_init; lb_check(instance.event_loop, config); return EXIT_SUCCESS; } /* initialize */ SetupProcess(); const ScopeSslGlobalInit ssl_init; #if defined(HAVE_LIBSYSTEMD) || defined(HAVE_AVAHI) const ODBus::ScopeInit dbus_init; dbus_connection_set_exit_on_disconnect(ODBus::Connection::GetSystem(), false); #endif /* prevent libpq from initializing libssl & libcrypto again */ PQinitOpenSSL(0, 0); direct_global_init(); init_signals(&instance); instance.InitAllControls(); instance.InitAllListeners(); instance.balancer = new BalancerMap(instance.failure_manager); instance.fs_stock = new FilteredSocketStock(instance.event_loop, cmdline.tcp_stock_limit); instance.fs_balancer = new FilteredSocketBalancer(*instance.fs_stock, instance.failure_manager); instance.pipe_stock = new PipeStock(instance.event_loop); /* launch the access logger */ instance.access_log.reset(AccessLogGlue::Create(config.access_log, &cmdline.logger_user)); /* daemonize II */ if (!cmdline.user.IsEmpty()) capabilities_pre_setuid(); cmdline.user.Apply(); #ifdef __linux /* revert the "dumpable" flag to "true" after it was cleared by setreuid(); this is necessary for two reasons: (1) we want core dumps to be able to analyze crashes; and (2) Linux kernels older than 4.10 (commit 68eb94f16227) don't allow writing to /proc/self/setgroups etc. without it, which isolate_from_filesystem() needs to do */ prctl(PR_SET_DUMPABLE, 1, 0, 0, 0); #endif /* can't change to new (empty) rootfs if we may need to reconnect to PostgreSQL eventually */ // TODO: bind-mount the PostgreSQL socket into the new rootfs if (!config.HasCertDatabase()) isolate_from_filesystem(config.HasZeroConf()); if (!cmdline.user.IsEmpty()) capabilities_post_setuid(cap_keep_list, std::size(cap_keep_list)); #ifdef __linux prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); #endif /* main loop */ instance.InitWorker(); #ifdef HAVE_LIBSYSTEMD /* tell systemd we're ready */ sd_notify(0, "READY=1"); #endif instance.event_loop.Dispatch(); /* cleanup */ instance.DeinitAllListeners(); instance.DeinitAllControls(); thread_pool_deinit(); } catch (...) { PrintException(std::current_exception()); return EXIT_FAILURE; } <|endoftext|>
<commit_before>/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/profiling/memory/client.h" #include <inttypes.h> #include <sys/socket.h> #include <sys/syscall.h> #include <sys/un.h> #include <unistd.h> #include <atomic> #include <new> #include <unwindstack/MachineArm.h> #include <unwindstack/MachineArm64.h> #include <unwindstack/MachineMips.h> #include <unwindstack/MachineMips64.h> #include <unwindstack/MachineX86.h> #include <unwindstack/MachineX86_64.h> #include <unwindstack/Regs.h> #include <unwindstack/RegsGetLocal.h> #include "perfetto/base/logging.h" #include "perfetto/base/scoped_file.h" #include "perfetto/base/unix_socket.h" #include "perfetto/base/utils.h" #include "src/profiling/memory/sampler.h" #include "src/profiling/memory/wire_protocol.h" namespace perfetto { namespace profiling { namespace { constexpr struct timeval kSendTimeout = {1 /* s */, 0 /* us */}; #if !PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) // glibc does not define a wrapper around gettid, bionic does. pid_t gettid() { return static_cast<pid_t>(syscall(__NR_gettid)); } #endif std::vector<base::ScopedFile> ConnectPool(const std::string& sock_name, size_t n) { sockaddr_un addr; socklen_t addr_size; if (!base::MakeSockAddr(sock_name, &addr, &addr_size)) return {}; std::vector<base::ScopedFile> res; res.reserve(n); for (size_t i = 0; i < n; ++i) { auto sock = base::CreateSocket(); if (connect(*sock, reinterpret_cast<sockaddr*>(&addr), addr_size) == -1) { PERFETTO_PLOG("Failed to connect to %s", sock_name.c_str()); continue; } if (setsockopt(*sock, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char*>(&kSendTimeout), sizeof(kSendTimeout)) != 0) { PERFETTO_PLOG("Failed to set timeout for %s", sock_name.c_str()); continue; } res.emplace_back(std::move(sock)); } return res; } inline bool IsMainThread() { return getpid() == gettid(); } // TODO(b/117203899): Remove this after making bionic implementation safe to // use. char* FindMainThreadStack() { base::ScopedFstream maps(fopen("/proc/self/maps", "r")); if (!maps) { return nullptr; } while (!feof(*maps)) { char line[1024]; char* data = fgets(line, sizeof(line), *maps); if (data != nullptr && strstr(data, "[stack]")) { char* sep = strstr(data, "-"); if (sep == nullptr) continue; sep++; return reinterpret_cast<char*>(strtoll(sep, nullptr, 16)); } } return nullptr; } } // namespace void FreePage::Add(const uint64_t addr, const uint64_t sequence_number, SocketPool* pool) { std::lock_guard<std::mutex> l(mutex_); if (offset_ == kFreePageSize) { FlushLocked(pool); // Now that we have flushed, reset to after the header. offset_ = 0; } FreePageEntry& current_entry = free_page_.entries[offset_++]; current_entry.sequence_number = sequence_number; current_entry.addr = addr; } void FreePage::FlushLocked(SocketPool* pool) { WireMessage msg = {}; msg.record_type = RecordType::Free; free_page_.num_entries = offset_; msg.free_header = &free_page_; BorrowedSocket fd(pool->Borrow()); if (!fd || !SendWireMessage(*fd, msg)) { PERFETTO_DFATAL("Failed to send wire message"); fd.Close(); } } SocketPool::SocketPool(std::vector<base::ScopedFile> sockets) : sockets_(std::move(sockets)), available_sockets_(sockets_.size()) {} BorrowedSocket SocketPool::Borrow() { std::unique_lock<std::mutex> lck_(mutex_); cv_.wait(lck_, [this] { return available_sockets_ > 0 || dead_sockets_ == sockets_.size() || shutdown_; }); if (dead_sockets_ == sockets_.size() || shutdown_) { return {base::ScopedFile(), nullptr}; } PERFETTO_CHECK(available_sockets_ > 0); return {std::move(sockets_[--available_sockets_]), this}; } void SocketPool::Return(base::ScopedFile sock) { std::unique_lock<std::mutex> lck_(mutex_); PERFETTO_CHECK(dead_sockets_ + available_sockets_ < sockets_.size()); if (sock && !shutdown_) { PERFETTO_CHECK(available_sockets_ < sockets_.size()); sockets_[available_sockets_++] = std::move(sock); lck_.unlock(); cv_.notify_one(); } else { dead_sockets_++; if (dead_sockets_ == sockets_.size()) { lck_.unlock(); cv_.notify_all(); } } } void SocketPool::Shutdown() { { std::lock_guard<std::mutex> l(mutex_); for (size_t i = 0; i < available_sockets_; ++i) sockets_[i].reset(); dead_sockets_ += available_sockets_; available_sockets_ = 0; shutdown_ = true; } cv_.notify_all(); } const char* GetThreadStackBase() { pthread_attr_t attr; if (pthread_getattr_np(pthread_self(), &attr) != 0) return nullptr; base::ScopedResource<pthread_attr_t*, pthread_attr_destroy, nullptr> cleanup( &attr); char* stackaddr; size_t stacksize; if (pthread_attr_getstack(&attr, reinterpret_cast<void**>(&stackaddr), &stacksize) != 0) return nullptr; return stackaddr + stacksize; } Client::Client(std::vector<base::ScopedFile> socks) : pthread_key_(ThreadLocalSamplingData::KeyDestructor), socket_pool_(std::move(socks)), main_thread_stack_base_(FindMainThreadStack()) { PERFETTO_DCHECK(pthread_key_.valid()); uint64_t size = 0; base::ScopedFile maps(base::OpenFile("/proc/self/maps", O_RDONLY)); base::ScopedFile mem(base::OpenFile("/proc/self/mem", O_RDONLY)); if (!maps || !mem) { PERFETTO_DFATAL("Failed to open /proc/self/{maps,mem}"); return; } int fds[2]; fds[0] = *maps; fds[1] = *mem; auto fd = socket_pool_.Borrow(); if (!fd) return; // Send an empty record to transfer fds for /proc/self/maps and // /proc/self/mem. if (base::SockSend(*fd, &size, sizeof(size), fds, 2) != sizeof(size)) { PERFETTO_DFATAL("Failed to send file descriptors."); return; } if (recv(*fd, &client_config_, sizeof(client_config_), 0) != sizeof(client_config_)) { PERFETTO_DFATAL("Failed to receive client config."); return; } PERFETTO_DCHECK(client_config_.interval >= 1); PERFETTO_DLOG("Initialized client."); inited_.store(true, std::memory_order_release); } Client::Client(const std::string& sock_name, size_t conns) : Client(ConnectPool(sock_name, conns)) {} const char* Client::GetStackBase() { if (IsMainThread()) { if (!main_thread_stack_base_) // Because pthread_attr_getstack reads and parses /proc/self/maps and // /proc/self/stat, we have to cache the result here. main_thread_stack_base_ = GetThreadStackBase(); return main_thread_stack_base_; } return GetThreadStackBase(); } // The stack grows towards numerically smaller addresses, so the stack layout // of main calling malloc is as follows. // // +------------+ // |SendWireMsg | // stacktop +--> +------------+ 0x1000 // |RecordMalloc| + // +------------+ | // | malloc | | // +------------+ | // | main | v // stackbase +-> +------------+ 0xffff void Client::RecordMalloc(uint64_t alloc_size, uint64_t total_size, uint64_t alloc_address) { if (!inited_.load(std::memory_order_acquire)) return; AllocMetadata metadata; const char* stackbase = GetStackBase(); const char* stacktop = reinterpret_cast<char*>(__builtin_frame_address(0)); unwindstack::AsmGetRegs(metadata.register_data); if (stackbase < stacktop) { PERFETTO_DFATAL("Stackbase >= stacktop."); return; } uint64_t stack_size = static_cast<uint64_t>(stackbase - stacktop); metadata.total_size = total_size; metadata.alloc_size = alloc_size; metadata.alloc_address = alloc_address; metadata.stack_pointer = reinterpret_cast<uint64_t>(stacktop); metadata.stack_pointer_offset = sizeof(AllocMetadata); metadata.arch = unwindstack::Regs::CurrentArch(); metadata.sequence_number = ++sequence_number_; WireMessage msg{}; msg.record_type = RecordType::Malloc; msg.alloc_header = &metadata; msg.payload = const_cast<char*>(stacktop); msg.payload_size = static_cast<size_t>(stack_size); BorrowedSocket fd = socket_pool_.Borrow(); if (!fd || !SendWireMessage(*fd, msg)) { PERFETTO_DFATAL("Failed to send wire message."); fd.Close(); } } void Client::RecordFree(uint64_t alloc_address) { if (!inited_.load(std::memory_order_acquire)) return; free_page_.Add(alloc_address, ++sequence_number_, &socket_pool_); } size_t Client::ShouldSampleAlloc(uint64_t alloc_size, void* (*unhooked_malloc)(size_t), void (*unhooked_free)(void*)) { if (!inited_.load(std::memory_order_acquire)) return false; return SampleSize(pthread_key_.get(), alloc_size, client_config_.interval, unhooked_malloc, unhooked_free); } void Client::MaybeSampleAlloc(uint64_t alloc_size, uint64_t alloc_address, void* (*unhooked_malloc)(size_t), void (*unhooked_free)(void*)) { size_t total_size = ShouldSampleAlloc(alloc_size, unhooked_malloc, unhooked_free); if (total_size > 0) RecordMalloc(alloc_size, total_size, alloc_address); } void Client::Shutdown() { socket_pool_.Shutdown(); inited_.store(false, std::memory_order_release); } } // namespace profiling } // namespace perfetto <commit_msg>profiling: Use less strict memory order for sequence_number.<commit_after>/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/profiling/memory/client.h" #include <inttypes.h> #include <sys/socket.h> #include <sys/syscall.h> #include <sys/un.h> #include <unistd.h> #include <atomic> #include <new> #include <unwindstack/MachineArm.h> #include <unwindstack/MachineArm64.h> #include <unwindstack/MachineMips.h> #include <unwindstack/MachineMips64.h> #include <unwindstack/MachineX86.h> #include <unwindstack/MachineX86_64.h> #include <unwindstack/Regs.h> #include <unwindstack/RegsGetLocal.h> #include "perfetto/base/logging.h" #include "perfetto/base/scoped_file.h" #include "perfetto/base/unix_socket.h" #include "perfetto/base/utils.h" #include "src/profiling/memory/sampler.h" #include "src/profiling/memory/wire_protocol.h" namespace perfetto { namespace profiling { namespace { constexpr struct timeval kSendTimeout = {1 /* s */, 0 /* us */}; #if !PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) // glibc does not define a wrapper around gettid, bionic does. pid_t gettid() { return static_cast<pid_t>(syscall(__NR_gettid)); } #endif std::vector<base::ScopedFile> ConnectPool(const std::string& sock_name, size_t n) { sockaddr_un addr; socklen_t addr_size; if (!base::MakeSockAddr(sock_name, &addr, &addr_size)) return {}; std::vector<base::ScopedFile> res; res.reserve(n); for (size_t i = 0; i < n; ++i) { auto sock = base::CreateSocket(); if (connect(*sock, reinterpret_cast<sockaddr*>(&addr), addr_size) == -1) { PERFETTO_PLOG("Failed to connect to %s", sock_name.c_str()); continue; } if (setsockopt(*sock, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char*>(&kSendTimeout), sizeof(kSendTimeout)) != 0) { PERFETTO_PLOG("Failed to set timeout for %s", sock_name.c_str()); continue; } res.emplace_back(std::move(sock)); } return res; } inline bool IsMainThread() { return getpid() == gettid(); } // TODO(b/117203899): Remove this after making bionic implementation safe to // use. char* FindMainThreadStack() { base::ScopedFstream maps(fopen("/proc/self/maps", "r")); if (!maps) { return nullptr; } while (!feof(*maps)) { char line[1024]; char* data = fgets(line, sizeof(line), *maps); if (data != nullptr && strstr(data, "[stack]")) { char* sep = strstr(data, "-"); if (sep == nullptr) continue; sep++; return reinterpret_cast<char*>(strtoll(sep, nullptr, 16)); } } return nullptr; } } // namespace void FreePage::Add(const uint64_t addr, const uint64_t sequence_number, SocketPool* pool) { std::lock_guard<std::mutex> l(mutex_); if (offset_ == kFreePageSize) { FlushLocked(pool); // Now that we have flushed, reset to after the header. offset_ = 0; } FreePageEntry& current_entry = free_page_.entries[offset_++]; current_entry.sequence_number = sequence_number; current_entry.addr = addr; } void FreePage::FlushLocked(SocketPool* pool) { WireMessage msg = {}; msg.record_type = RecordType::Free; free_page_.num_entries = offset_; msg.free_header = &free_page_; BorrowedSocket fd(pool->Borrow()); if (!fd || !SendWireMessage(*fd, msg)) { PERFETTO_DFATAL("Failed to send wire message"); fd.Close(); } } SocketPool::SocketPool(std::vector<base::ScopedFile> sockets) : sockets_(std::move(sockets)), available_sockets_(sockets_.size()) {} BorrowedSocket SocketPool::Borrow() { std::unique_lock<std::mutex> lck_(mutex_); cv_.wait(lck_, [this] { return available_sockets_ > 0 || dead_sockets_ == sockets_.size() || shutdown_; }); if (dead_sockets_ == sockets_.size() || shutdown_) { return {base::ScopedFile(), nullptr}; } PERFETTO_CHECK(available_sockets_ > 0); return {std::move(sockets_[--available_sockets_]), this}; } void SocketPool::Return(base::ScopedFile sock) { std::unique_lock<std::mutex> lck_(mutex_); PERFETTO_CHECK(dead_sockets_ + available_sockets_ < sockets_.size()); if (sock && !shutdown_) { PERFETTO_CHECK(available_sockets_ < sockets_.size()); sockets_[available_sockets_++] = std::move(sock); lck_.unlock(); cv_.notify_one(); } else { dead_sockets_++; if (dead_sockets_ == sockets_.size()) { lck_.unlock(); cv_.notify_all(); } } } void SocketPool::Shutdown() { { std::lock_guard<std::mutex> l(mutex_); for (size_t i = 0; i < available_sockets_; ++i) sockets_[i].reset(); dead_sockets_ += available_sockets_; available_sockets_ = 0; shutdown_ = true; } cv_.notify_all(); } const char* GetThreadStackBase() { pthread_attr_t attr; if (pthread_getattr_np(pthread_self(), &attr) != 0) return nullptr; base::ScopedResource<pthread_attr_t*, pthread_attr_destroy, nullptr> cleanup( &attr); char* stackaddr; size_t stacksize; if (pthread_attr_getstack(&attr, reinterpret_cast<void**>(&stackaddr), &stacksize) != 0) return nullptr; return stackaddr + stacksize; } Client::Client(std::vector<base::ScopedFile> socks) : pthread_key_(ThreadLocalSamplingData::KeyDestructor), socket_pool_(std::move(socks)), main_thread_stack_base_(FindMainThreadStack()) { PERFETTO_DCHECK(pthread_key_.valid()); uint64_t size = 0; base::ScopedFile maps(base::OpenFile("/proc/self/maps", O_RDONLY)); base::ScopedFile mem(base::OpenFile("/proc/self/mem", O_RDONLY)); if (!maps || !mem) { PERFETTO_DFATAL("Failed to open /proc/self/{maps,mem}"); return; } int fds[2]; fds[0] = *maps; fds[1] = *mem; auto fd = socket_pool_.Borrow(); if (!fd) return; // Send an empty record to transfer fds for /proc/self/maps and // /proc/self/mem. if (base::SockSend(*fd, &size, sizeof(size), fds, 2) != sizeof(size)) { PERFETTO_DFATAL("Failed to send file descriptors."); return; } if (recv(*fd, &client_config_, sizeof(client_config_), 0) != sizeof(client_config_)) { PERFETTO_DFATAL("Failed to receive client config."); return; } PERFETTO_DCHECK(client_config_.interval >= 1); PERFETTO_DLOG("Initialized client."); inited_.store(true, std::memory_order_release); } Client::Client(const std::string& sock_name, size_t conns) : Client(ConnectPool(sock_name, conns)) {} const char* Client::GetStackBase() { if (IsMainThread()) { if (!main_thread_stack_base_) // Because pthread_attr_getstack reads and parses /proc/self/maps and // /proc/self/stat, we have to cache the result here. main_thread_stack_base_ = GetThreadStackBase(); return main_thread_stack_base_; } return GetThreadStackBase(); } // The stack grows towards numerically smaller addresses, so the stack layout // of main calling malloc is as follows. // // +------------+ // |SendWireMsg | // stacktop +--> +------------+ 0x1000 // |RecordMalloc| + // +------------+ | // | malloc | | // +------------+ | // | main | v // stackbase +-> +------------+ 0xffff void Client::RecordMalloc(uint64_t alloc_size, uint64_t total_size, uint64_t alloc_address) { if (!inited_.load(std::memory_order_acquire)) return; AllocMetadata metadata; const char* stackbase = GetStackBase(); const char* stacktop = reinterpret_cast<char*>(__builtin_frame_address(0)); unwindstack::AsmGetRegs(metadata.register_data); if (stackbase < stacktop) { PERFETTO_DFATAL("Stackbase >= stacktop."); return; } uint64_t stack_size = static_cast<uint64_t>(stackbase - stacktop); metadata.total_size = total_size; metadata.alloc_size = alloc_size; metadata.alloc_address = alloc_address; metadata.stack_pointer = reinterpret_cast<uint64_t>(stacktop); metadata.stack_pointer_offset = sizeof(AllocMetadata); metadata.arch = unwindstack::Regs::CurrentArch(); metadata.sequence_number = 1 + sequence_number_.fetch_add(1, std::memory_order_acq_rel); WireMessage msg{}; msg.record_type = RecordType::Malloc; msg.alloc_header = &metadata; msg.payload = const_cast<char*>(stacktop); msg.payload_size = static_cast<size_t>(stack_size); BorrowedSocket fd = socket_pool_.Borrow(); if (!fd || !SendWireMessage(*fd, msg)) { PERFETTO_DFATAL("Failed to send wire message."); fd.Close(); } } void Client::RecordFree(uint64_t alloc_address) { if (!inited_.load(std::memory_order_acquire)) return; free_page_.Add(alloc_address, 1 + sequence_number_.fetch_add(1, std::memory_order_acq_rel), &socket_pool_); } size_t Client::ShouldSampleAlloc(uint64_t alloc_size, void* (*unhooked_malloc)(size_t), void (*unhooked_free)(void*)) { if (!inited_.load(std::memory_order_acquire)) return false; return SampleSize(pthread_key_.get(), alloc_size, client_config_.interval, unhooked_malloc, unhooked_free); } void Client::MaybeSampleAlloc(uint64_t alloc_size, uint64_t alloc_address, void* (*unhooked_malloc)(size_t), void (*unhooked_free)(void*)) { size_t total_size = ShouldSampleAlloc(alloc_size, unhooked_malloc, unhooked_free); if (total_size > 0) RecordMalloc(alloc_size, total_size, alloc_address); } void Client::Shutdown() { socket_pool_.Shutdown(); inited_.store(false, std::memory_order_release); } } // namespace profiling } // namespace perfetto <|endoftext|>
<commit_before>/*************************************************************************** wpcontact.cpp - description ------------------- begin : Fri Apr 12 2002 copyright : (C) 2002 by Gav Wood email : [email protected] ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ // Qt Includes #include <qregexp.h> // KDE Includes #include <kdebug.h> // Kopete Includes // Local Includes #include "wpcontact.h" #include "wpaccount.h" WPContact::WPContact(Kopete::Account *account, const QString &newHostName, const QString &nickName, Kopete::MetaContact *metaContact) : Kopete::Contact(account, newHostName, metaContact) { // kdDebug(14170) << "WPContact::WPContact(<account>, " << newHostName << ", " << nickName << ", <parent>)" << endl; kdDebug(14170) << "I am " << this << "!" << endl; QString theNickName = nickName; if (theNickName.isEmpty()) { // Construct nickname from hostname with first letter to upper. GF theNickName = newHostName.lower(); theNickName = theNickName.replace(0, 1, theNickName[0].upper()); } setNickName(theNickName); myWasConnected = false; // Initialise and start the periodical checking for contact's status setOnlineStatus(static_cast<WPProtocol *>(protocol())->WPOffline); //TODO: makes checking more often than hostcheck cycle sense? GF connect(&checkStatus, SIGNAL(timeout()), this, SLOT(slotCheckStatus())); checkStatus.start(1000, false); m_manager = 0; m_infoDialog = 0; } QPtrList<KAction> * WPContact::customContextMenuActions() { //myActionCollection = new KActionCollection(parent); return 0; } void WPContact::serialize(QMap<QString, QString> &serializedData, QMap<QString, QString> &addressBookData) { // kdDebug(14170) << "WP::serialize(...)" << endl; Kopete::Contact::serialize(serializedData, addressBookData); } Kopete::ChatSession* WPContact::manager( Kopete::Contact::CanCreateFlags /*canCreate*/ ) // TODO: use the parameter as canCreate { if (m_manager == 0) { // Set up the message managers QPtrList<Kopete::Contact> singleContact; singleContact.append(this); m_manager = Kopete::ChatSessionManager::self()->create( account()->myself(), singleContact, protocol() ); connect(m_manager, SIGNAL(messageSent(Kopete::Message &, Kopete::ChatSession *)), this, SLOT(slotSendMessage(Kopete::Message &))); connect(m_manager, SIGNAL(messageSent(Kopete::Message &, Kopete::ChatSession *)), m_manager, SLOT(appendMessage(Kopete::Message &))); connect(m_manager, SIGNAL(destroyed()), this, SLOT(slotChatSessionDestroyed())); } return m_manager; } /* bool WPContact::isOnline() const { kdDebug(14170) << "[WPContact::isOnline()]" << endl; return onlineStatus().status() != Kopete::OnlineStatus::Offline && onlineStatus().status() != Kopete::OnlineStatus::Unknown; } */ bool WPContact::isReachable() { // kdDebug(14170) << "[WPContact::isReachable()]" << endl; return onlineStatus().status() != Kopete::OnlineStatus::Offline && onlineStatus().status() != Kopete::OnlineStatus::Unknown; } void WPContact::slotChatSessionDestroyed() { m_manager = 0; } void WPContact::slotUserInfo() { kdDebug( 14170 ) << k_funcinfo << endl; if (!m_infoDialog) { m_infoDialog = new WPUserInfo( this, static_cast<WPAccount*>( account() ) ); if (!m_infoDialog) return; connect( m_infoDialog, SIGNAL( closing() ), this, SLOT( slotCloseUserInfoDialog() ) ); m_infoDialog->show(); } else { m_infoDialog->raise(); } } void WPContact::slotCloseUserInfoDialog() { m_infoDialog->delayedDestruct(); m_infoDialog = 0; } /* void deleteContact() { // deleteLater(); } */ void WPContact::slotCheckStatus() { bool oldWasConnected = myWasConnected; bool newIsOnline = false; myWasConnected = protocol() != 0 && account() != 0; WPAccount *acct = dynamic_cast<WPAccount *>(account()); if (acct) newIsOnline = acct->checkHost(contactId()); if(newIsOnline != isOnline() || myWasConnected != oldWasConnected) { Kopete::OnlineStatus tmpStatus; if (myWasConnected) { if (newIsOnline) tmpStatus = WPProtocol::protocol()->WPOnline; else WPProtocol::protocol()->WPOffline; } else { WPProtocol::protocol()->WPOffline; } setOnlineStatus(tmpStatus); } } void WPContact::slotNewMessage(const QString &Body, const QDateTime &Arrival) { kdDebug(14170) << "WPContact::slotNewMessage(" << Body << ", " << Arrival.toString() << ")" << endl; QPtrList<Kopete::Contact> contactList; contactList.append(account()->myself()); QRegExp subj("^Subject: ([^\n]*)\n(.*)$"); Kopete::Message msg; if(subj.search(Body) == -1) { msg = Kopete::Message(this, contactList, Body, Kopete::Message::Inbound); } else { msg = Kopete::Message(this, contactList, subj.cap(2), subj.cap(1), Kopete::Message::Inbound); } manager(Kopete::Contact::CannotCreate)->appendMessage(msg); } void WPContact::slotSendMessage( Kopete::Message& message ) { // kdDebug(14170) << "WPContact::slotSendMessage(<message>)" << endl; // Warning: this could crash kdDebug(14170) << message.to().first() << " is " << dynamic_cast<WPContact *>( message.to().first() )->contactId() << endl; QString Message = (!message.subject().isEmpty() ? "Subject: " + message.subject() + "\n" : QString("")) + message.plainBody(); WPAccount *acct = dynamic_cast<WPAccount *>(account()); WPContact *contact = dynamic_cast<WPContact *>( message.to().first() ); if (acct && contact) { acct->slotSendMessage( Message, contact->contactId() ); m_manager->messageSucceeded(); } } #include "wpcontact.moc" // kate: tab-width 4; indent-width 4; replace-trailing-space-save on; <commit_msg>fix stupid bug in checking online status<commit_after>/*************************************************************************** wpcontact.cpp - description ------------------- begin : Fri Apr 12 2002 copyright : (C) 2002 by Gav Wood email : [email protected] ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ // Qt Includes #include <qregexp.h> // KDE Includes #include <kdebug.h> // Kopete Includes // Local Includes #include "wpcontact.h" #include "wpaccount.h" WPContact::WPContact(Kopete::Account *account, const QString &newHostName, const QString &nickName, Kopete::MetaContact *metaContact) : Kopete::Contact(account, newHostName, metaContact) { // kdDebug(14170) << "WPContact::WPContact(<account>, " << newHostName << ", " << nickName << ", <parent>)" << endl; kdDebug(14170) << "I am " << this << "!" << endl; QString theNickName = nickName; if (theNickName.isEmpty()) { // Construct nickname from hostname with first letter to upper. GF theNickName = newHostName.lower(); theNickName = theNickName.replace(0, 1, theNickName[0].upper()); } setNickName(theNickName); myWasConnected = false; // Initialise and start the periodical checking for contact's status setOnlineStatus(static_cast<WPProtocol *>(protocol())->WPOffline); //TODO: makes checking more often than hostcheck cycle sense? GF connect(&checkStatus, SIGNAL(timeout()), this, SLOT(slotCheckStatus())); checkStatus.start(1000, false); m_manager = 0; m_infoDialog = 0; } QPtrList<KAction> * WPContact::customContextMenuActions() { //myActionCollection = new KActionCollection(parent); return 0; } void WPContact::serialize(QMap<QString, QString> &serializedData, QMap<QString, QString> &addressBookData) { // kdDebug(14170) << "WP::serialize(...)" << endl; Kopete::Contact::serialize(serializedData, addressBookData); } Kopete::ChatSession* WPContact::manager( Kopete::Contact::CanCreateFlags /*canCreate*/ ) // TODO: use the parameter as canCreate { if (m_manager == 0) { // Set up the message managers QPtrList<Kopete::Contact> singleContact; singleContact.append(this); m_manager = Kopete::ChatSessionManager::self()->create( account()->myself(), singleContact, protocol() ); connect(m_manager, SIGNAL(messageSent(Kopete::Message &, Kopete::ChatSession *)), this, SLOT(slotSendMessage(Kopete::Message &))); connect(m_manager, SIGNAL(messageSent(Kopete::Message &, Kopete::ChatSession *)), m_manager, SLOT(appendMessage(Kopete::Message &))); connect(m_manager, SIGNAL(destroyed()), this, SLOT(slotChatSessionDestroyed())); } return m_manager; } /* bool WPContact::isOnline() const { kdDebug(14170) << "[WPContact::isOnline()]" << endl; return onlineStatus().status() != Kopete::OnlineStatus::Offline && onlineStatus().status() != Kopete::OnlineStatus::Unknown; } */ bool WPContact::isReachable() { // kdDebug(14170) << "[WPContact::isReachable()]" << endl; return onlineStatus().status() != Kopete::OnlineStatus::Offline && onlineStatus().status() != Kopete::OnlineStatus::Unknown; } void WPContact::slotChatSessionDestroyed() { m_manager = 0; } void WPContact::slotUserInfo() { kdDebug( 14170 ) << k_funcinfo << endl; if (!m_infoDialog) { m_infoDialog = new WPUserInfo( this, static_cast<WPAccount*>( account() ) ); if (!m_infoDialog) return; connect( m_infoDialog, SIGNAL( closing() ), this, SLOT( slotCloseUserInfoDialog() ) ); m_infoDialog->show(); } else { m_infoDialog->raise(); } } void WPContact::slotCloseUserInfoDialog() { m_infoDialog->delayedDestruct(); m_infoDialog = 0; } /* void deleteContact() { // deleteLater(); } */ void WPContact::slotCheckStatus() { bool oldWasConnected = myWasConnected; bool newIsOnline = false; myWasConnected = protocol() != 0 && account() != 0; WPAccount *acct = dynamic_cast<WPAccount *>(account()); if (acct) newIsOnline = acct->checkHost(contactId()); if(newIsOnline != isOnline() || myWasConnected != oldWasConnected) { Kopete::OnlineStatus tmpStatus = WPProtocol::protocol()->WPOffline; if (myWasConnected && newIsOnline) { tmpStatus = WPProtocol::protocol()->WPOnline; } setOnlineStatus(tmpStatus); } } void WPContact::slotNewMessage(const QString &Body, const QDateTime &Arrival) { kdDebug(14170) << "WPContact::slotNewMessage(" << Body << ", " << Arrival.toString() << ")" << endl; QPtrList<Kopete::Contact> contactList; contactList.append(account()->myself()); QRegExp subj("^Subject: ([^\n]*)\n(.*)$"); Kopete::Message msg; if(subj.search(Body) == -1) { msg = Kopete::Message(this, contactList, Body, Kopete::Message::Inbound); } else { msg = Kopete::Message(this, contactList, subj.cap(2), subj.cap(1), Kopete::Message::Inbound); } manager(Kopete::Contact::CannotCreate)->appendMessage(msg); } void WPContact::slotSendMessage( Kopete::Message& message ) { // kdDebug(14170) << "WPContact::slotSendMessage(<message>)" << endl; // Warning: this could crash kdDebug(14170) << message.to().first() << " is " << dynamic_cast<WPContact *>( message.to().first() )->contactId() << endl; QString Message = (!message.subject().isEmpty() ? "Subject: " + message.subject() + "\n" : QString("")) + message.plainBody(); WPAccount *acct = dynamic_cast<WPAccount *>(account()); WPContact *contact = dynamic_cast<WPContact *>( message.to().first() ); if (acct && contact) { acct->slotSendMessage( Message, contact->contactId() ); m_manager->messageSucceeded(); } } #include "wpcontact.moc" // kate: tab-width 4; indent-width 4; replace-trailing-space-save on; <|endoftext|>
<commit_before>/** * Appcelerator Titanium - licensed under the Apache Public License 2 * see LICENSE in the root folder for details on the license. * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved. */ #include <kroll/kroll.h> #include <Poco/Environment.h> #include <Poco/Process.h> #include "process_binding.h" #include "process.h" #ifdef OS_OSX #include <Foundation/Foundation.h> #endif #ifdef OS_WIN32 #include <windows.h> #endif namespace ti { ProcessBinding::ProcessBinding(Host *h, SharedBoundObject global) : host(h),global(global) { #ifdef OS_OSX NSProcessInfo *p = [NSProcessInfo processInfo]; this->Set("pid",Value::NewInt([p processIdentifier])); #else this->Set("pid",Value::NewInt((int)Poco::Process::id())); #endif //TODO: support times api //static void times(long& userTime, long& kernelTime); this->SetMethod("getEnv",&ProcessBinding::GetEnv); this->SetMethod("setEnv",&ProcessBinding::SetEnv); this->SetMethod("hasEnv",&ProcessBinding::HasEnv); this->SetMethod("launch",&ProcessBinding::Launch); this->SetMethod("restart",&ProcessBinding::Restart); } ProcessBinding::~ProcessBinding() { } void ProcessBinding::Launch(const ValueList& args, SharedValue result) { std::vector<std::string> arguments; std::string cmd = std::string(args.at(0)->ToString()); if (args.size()>1) { if (args.at(1)->IsString()) { std::string arglist = args.at(1)->ToString(); kroll::FileUtils::Tokenize(arglist,arguments," "); } else if (args.at(1)->IsList()) { SharedBoundList list = args.at(1)->ToList(); for (unsigned int c = 0; c < list->Size(); c++) { SharedValue value = list->At(c); arguments.push_back(value->ToString()); } } } SharedBoundObject p = new Process(this, cmd, arguments); processes.push_back(p); result->SetObject(p); } void ProcessBinding::Terminated(Process* p) { std::vector<SharedBoundObject>::iterator i = processes.begin(); while(i!=processes.end()) { SharedBoundObject obj = (*i); if (obj.get()==p) { processes.erase(i); break; } i++; } } void ProcessBinding::GetEnv(const ValueList& args, SharedValue result) { std::string key(args.at(0)->ToString()); try { std::string value = Poco::Environment::get(key); result->SetString(value.c_str()); } catch(...) { // if they specified a default as 2nd parameter, return it // otherwise, return null if (args.size()==2) { result->SetString(args.at(1)->ToString()); } else { result->SetNull(); } } } void ProcessBinding::HasEnv(const ValueList& args, SharedValue result) { std::string key(args.at(0)->ToString()); result->SetBool(Poco::Environment::has(key)); } void ProcessBinding::SetEnv(const ValueList& args, SharedValue result) { std::string key(args.at(0)->ToString()); std::string value(args.at(1)->ToString()); Poco::Environment::set(key,value); } void ProcessBinding::Restart(const ValueList& args, SharedValue result) { #ifdef OS_OSX NSProcessInfo *p = [NSProcessInfo processInfo]; NSString *path = [[NSBundle mainBundle] bundlePath]; NSString *killArg1AndOpenArg2Script = [NSString stringWithFormat:@"kill -9 %d\n open \"%@\"",[p processIdentifier],path]; NSArray *shArgs = [NSArray arrayWithObjects:@"-c", // -c tells sh to execute the next argument, passing it the remaining arguments. killArg1AndOpenArg2Script,nil]; NSTask *restartTask = [NSTask launchedTaskWithLaunchPath:@"/bin/sh" arguments:shArgs]; [restartTask waitUntilExit]; //wait for killArg1AndOpenArg2Script to finish #elif OS_WIN32 std::string cmdline = host->GetCommandLineArg(0); STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); CreateProcessA(NULL, (LPSTR)cmdline.c_str(), NULL, /*lpProcessAttributes*/ NULL, /*lpThreadAttributes*/ FALSE, /*bInheritHandles*/ NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi); CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); #elif OS_LINUX std::string cmdline = host->GetCommandLineArg(0); std::string script = "sh " + cmdline + " &"; system(script.c_str()); #endif host->Exit(999); } } <commit_msg>Fix Process.Restart() on Linux<commit_after>/** * Appcelerator Titanium - licensed under the Apache Public License 2 * see LICENSE in the root folder for details on the license. * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved. */ #include <kroll/kroll.h> #include <Poco/Environment.h> #include <Poco/Process.h> #include "process_binding.h" #include "process.h" #ifdef OS_OSX #include <Foundation/Foundation.h> #endif #ifdef OS_WIN32 #include <windows.h> #endif namespace ti { ProcessBinding::ProcessBinding(Host *h, SharedBoundObject global) : host(h),global(global) { #ifdef OS_OSX NSProcessInfo *p = [NSProcessInfo processInfo]; this->Set("pid",Value::NewInt([p processIdentifier])); #else this->Set("pid",Value::NewInt((int)Poco::Process::id())); #endif //TODO: support times api //static void times(long& userTime, long& kernelTime); this->SetMethod("getEnv",&ProcessBinding::GetEnv); this->SetMethod("setEnv",&ProcessBinding::SetEnv); this->SetMethod("hasEnv",&ProcessBinding::HasEnv); this->SetMethod("launch",&ProcessBinding::Launch); this->SetMethod("restart",&ProcessBinding::Restart); } ProcessBinding::~ProcessBinding() { } void ProcessBinding::Launch(const ValueList& args, SharedValue result) { std::vector<std::string> arguments; std::string cmd = std::string(args.at(0)->ToString()); if (args.size()>1) { if (args.at(1)->IsString()) { std::string arglist = args.at(1)->ToString(); kroll::FileUtils::Tokenize(arglist,arguments," "); } else if (args.at(1)->IsList()) { SharedBoundList list = args.at(1)->ToList(); for (unsigned int c = 0; c < list->Size(); c++) { SharedValue value = list->At(c); arguments.push_back(value->ToString()); } } } SharedBoundObject p = new Process(this, cmd, arguments); processes.push_back(p); result->SetObject(p); } void ProcessBinding::Terminated(Process* p) { std::vector<SharedBoundObject>::iterator i = processes.begin(); while(i!=processes.end()) { SharedBoundObject obj = (*i); if (obj.get()==p) { processes.erase(i); break; } i++; } } void ProcessBinding::GetEnv(const ValueList& args, SharedValue result) { std::string key(args.at(0)->ToString()); try { std::string value = Poco::Environment::get(key); result->SetString(value.c_str()); } catch(...) { // if they specified a default as 2nd parameter, return it // otherwise, return null if (args.size()==2) { result->SetString(args.at(1)->ToString()); } else { result->SetNull(); } } } void ProcessBinding::HasEnv(const ValueList& args, SharedValue result) { std::string key(args.at(0)->ToString()); result->SetBool(Poco::Environment::has(key)); } void ProcessBinding::SetEnv(const ValueList& args, SharedValue result) { std::string key(args.at(0)->ToString()); std::string value(args.at(1)->ToString()); Poco::Environment::set(key,value); } void ProcessBinding::Restart(const ValueList& args, SharedValue result) { #ifdef OS_OSX NSProcessInfo *p = [NSProcessInfo processInfo]; NSString *path = [[NSBundle mainBundle] bundlePath]; NSString *killArg1AndOpenArg2Script = [NSString stringWithFormat:@"kill -9 %d\n open \"%@\"",[p processIdentifier],path]; NSArray *shArgs = [NSArray arrayWithObjects:@"-c", // -c tells sh to execute the next argument, passing it the remaining arguments. killArg1AndOpenArg2Script,nil]; NSTask *restartTask = [NSTask launchedTaskWithLaunchPath:@"/bin/sh" arguments:shArgs]; [restartTask waitUntilExit]; //wait for killArg1AndOpenArg2Script to finish #elif OS_WIN32 std::string cmdline = host->GetCommandLineArg(0); STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); CreateProcessA(NULL, (LPSTR)cmdline.c_str(), NULL, /*lpProcessAttributes*/ NULL, /*lpThreadAttributes*/ FALSE, /*bInheritHandles*/ NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi); CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); #elif OS_LINUX std::string cmdline = host->GetCommandLineArg(0); size_t idx; while ((idx = cmdline.find_first_of('\"')) != std::string::npos) { cmdline.replace(idx, 1, "\\\""); } std::string script = "\"" + cmdline + "\" &"; system(script.c_str()); #endif host->Exit(999); } } <|endoftext|>
<commit_before>#ifndef movement3d_filter_HPP #define movement3d_filter_HPP #include "movement3d.hpp" #include <GL/gl.h> #include <iostream> #include <opencv2/opencv.hpp> class movement3d_average { std::deque<movement3d> _movements; unsigned int _samples = 1; private: public: movement3d_average (unsigned int samples = 1); ~movement3d_average (); /** * calculate average between all movements stored * @return returns the calculated movement */ movement3d average (); /** * add a movement and calculate average between all movements stored * @param movement a movement to add * @return returns the calculated movement */ movement3d average (movement3d movement); }; #endif // movement3d_filter_HPP <commit_msg>fix compile error<commit_after>#ifndef movement3d_filter_HPP #define movement3d_filter_HPP #include "movement3d.hpp" #include <GL/gl.h> #include <deque> #include <iostream> class movement3d_average { std::deque<movement3d> _movements; unsigned int _samples = 1; private: public: movement3d_average (unsigned int samples = 1); ~movement3d_average (); /** * calculate average between all movements stored * @return returns the calculated movement */ movement3d average (); /** * add a movement and calculate average between all movements stored * @param movement a movement to add * @return returns the calculated movement */ movement3d average (movement3d movement); }; #endif // movement3d_filter_HPP <|endoftext|>
<commit_before>/* * Copyright (c) 2013 Nicholas Corgan ([email protected]) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #ifndef INCLUDED_PKMNSIM_TYPES_VLA_IPP #define INCLUDED_PKMNSIM_TYPES_VLA_IPP #include <iostream> #include <pkmnsim/config.hpp> namespace pkmnsim { template<typename item_type> vla<item_type>::vla () {} template<typename item_type> vla<item_type>::vla(int items) { _vec.clear(); max_items = items; _vec = std::vector<item_type>(items); invalid_pos_err_msg = "Position must be 0-" + to_string(max_items - 1) + "."; } template<typename item_type> std::size_t vla<item_type>::size(void) const { return max_items; } template<typename item_type> item_type& vla<item_type>::operator[](int pos) { if(pos < 0 or pos >= max_items) { std::cerr << invalid_pos_err_msg << std::endl; exit(EXIT_FAILURE); } else return _vec[pos]; } template<typename item_type> void vla<item_type>::set(int pos, item_type val) { if(pos < 0 or pos >= max_items) { std::cerr << invalid_pos_err_msg << std::endl; exit(EXIT_FAILURE); } else _vec[pos] = val; } template<typename item_type> item_type vla<item_type>::get(int pos) const { if(pos < 0 or pos >= max_items) { std::cerr << invalid_pos_err_msg << std::endl; exit(EXIT_FAILURE); } return _vec[pos]; } } #endif /* INCLUDED_PKMNSIM_TYPES_VLA_IPP */ <commit_msg>vla: added cstdlib include for Cygwin+GCC compatibility<commit_after>/* * Copyright (c) 2013 Nicholas Corgan ([email protected]) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #ifndef INCLUDED_PKMNSIM_TYPES_VLA_IPP #define INCLUDED_PKMNSIM_TYPES_VLA_IPP #include <cstdlib> #include <iostream> #include <pkmnsim/config.hpp> namespace pkmnsim { template<typename item_type> vla<item_type>::vla () {} template<typename item_type> vla<item_type>::vla(int items) { _vec.clear(); max_items = items; _vec = std::vector<item_type>(items); invalid_pos_err_msg = "Position must be 0-" + to_string(max_items - 1) + "."; } template<typename item_type> std::size_t vla<item_type>::size(void) const { return max_items; } template<typename item_type> item_type& vla<item_type>::operator[](int pos) { if(pos < 0 or pos >= max_items) { std::cerr << invalid_pos_err_msg << std::endl; exit(EXIT_FAILURE); } else return _vec[pos]; } template<typename item_type> void vla<item_type>::set(int pos, item_type val) { if(pos < 0 or pos >= max_items) { std::cerr << invalid_pos_err_msg << std::endl; exit(EXIT_FAILURE); } else _vec[pos] = val; } template<typename item_type> item_type vla<item_type>::get(int pos) const { if(pos < 0 or pos >= max_items) { std::cerr << invalid_pos_err_msg << std::endl; exit(EXIT_FAILURE); } return _vec[pos]; } } #endif /* INCLUDED_PKMNSIM_TYPES_VLA_IPP */ <|endoftext|>
<commit_before>#ifndef V_SMC_CORE_SAMPLER_HPP #define V_SMC_CORE_SAMPLER_HPP #include <vSMC/internal/common.hpp> #include <iostream> #include <map> #include <set> #include <string> namespace vSMC { /// \brief SMC Sampler /// /// \tparam T State state type. Requiment: /// \li Consturctor: T (IntType N) /// \li Method: copy (IntType from, IntType to) template <typename T> class Sampler { public : /// The type of initialization functor typedef internal::function<std::size_t (Particle<T> &, void *)> initialize_type; /// The type of move functor typedef internal::function<std::size_t (std::size_t, Particle<T> &)> move_type; /// The type ESS history vector typedef std::vector<double> ess_type; /// The type resampling history vector typedef std::vector<bool> resampled_type; /// The type accept count history vector typedef std::vector<std::size_t> accept_type; /// \brief Construct a sampler with given number of particles /// /// \param N The number of particles /// \param init The functor used to initialize the particles /// \param move The functor used to move the particles and weights /// \param mcmc The functor used to perform MCMC move /// \param scheme The resampling scheme. See ResampleScheme /// \param threshold The threshold for performing resampling /// \param seed The seed to the parallel RNG system explicit Sampler ( typename Particle<T>::size_type N, const initialize_type &init = NULL, const move_type &move = NULL, const move_type &mcmc = NULL, ResampleScheme scheme = STRATIFIED, double threshold = 0.5, typename Particle<T>::seed_type seed = V_SMC_CRNG_SEED) : initialized_(false), init_(init), move_(move), mcmc_(mcmc), scheme_(scheme), threshold_(threshold * N), particle_(N, seed), iter_num_(0) { particle_.sampler(this); } /// \brief Size of the particle set /// /// \return The number of particles typename Particle<T>::size_type size () const { return particle_.size(); } /// \brief Size of records /// /// \return The number of iterations recorded (including the /// initialization step) std::size_t iter_size () const { return ess_.size(); } /// \brief Get the current resampling scheme /// /// \return The current resampling scheme ResampleScheme resample_scheme () const { return scheme_; } /// \brief Set new resampling scheme /// /// \param scheme The new scheme for resampling void resample_scheme (ResampleScheme scheme) { scheme_ = scheme; } /// \brief Get the current threshold /// /// \return The current threshold for resmapling double resample_threshold () const { return threshold_; } /// \brief Set new resampling threshold /// /// \param threshold The new threshold for resampling void resample_threshold (double threshold) { threshold_ = threshold * particle_.size(); } /// \brief ESS /// /// \return The ESS value of the latest iteration ess_type::value_type ess () const { return ess_.back(); } /// \brief ESS history /// /// \return A const reference to the history of ESS const ess_type &ess_history () const { return ess_; } /// \brief Indicator of resampling /// /// \return A bool value, \b true if the latest iteration was resampled resampled_type::value_type resampled () const { return resampled_.back(); } /// \brief Resampling history /// /// \return A const reference to the history of resampling const resampled_type &resampled_history () const { return resampled_; } /// \brief Accept count /// /// \return The accept count of the latest iteration accept_type::value_type accept () const { return accept_.back(); } /// \brief Accept count history /// /// \return A const reference to the history of accept count const accept_type &accept_history () const { return accept_; } /// \brief Read and write access to the particle set /// /// \return A reference to the latest particle set Particle<T> &particle () { return particle_; } /// \brief Read only access to the particle set /// /// \return A const reference to the latest particle set. const Particle<T> &particle () const { return particle_; } /// \brief Replace initialization functor /// /// \param init New Initialization functor void initialize (initialize_type &init) { init_ = init; } /// \brief Initialize the particle set /// /// \param param Additional parameters passed to the initialization /// functor void initialize (void *param = NULL) { ess_.clear(); resampled_.clear(); accept_.clear(); path_.clear(); for (typename std::map<std::string, Monitor<T> >::iterator imap = monitor_.begin(); imap != monitor_.end(); ++imap) imap->second.clear(); iter_num_ = 0; accept_.push_back(init_(particle_, param)); post_move(); particle_.reset_zconst(); initialized_ = true; } /// \brief Replace iteration functor /// /// \param move New Move functor /// \param mcmc New MCMC functor void iterate (const move_type &move, const move_type &mcmc = NULL) { move_ = move; mcmc_ = mcmc; } /// \brief Perform iteration void iterate () { assert(initialized_); ++iter_num_; accept_.push_back(move_(iter_num_, particle_)); if (bool(mcmc_)) accept_.back() = mcmc_(iter_num_, particle_); post_move(); } /// \brief Perform iteration /// /// \param n The number of iterations to be performed void iterate (std::size_t n) { for (std::size_t i = 0; i != n; ++i) iterate(); } /// \brief Perform importance sampling integration /// /// \param integral The functor used to compute the integrands /// \param res The result, an array of length dim template<typename MonitorType> void integrate (const MonitorType &integral, double *res) { Monitor<T> m(integral.dim(), integral); m.eval(iter_num_, particle_); Eigen::Map<Eigen::VectorXd> r(res, m.dim()); r = m.record().back(); } /// \brief Perform importance sampling integration /// /// \param dim The dimension of the parameter /// \param integral The functor used to compute the integrands /// \param res The result, an array of length dim void integrate (unsigned dim, const typename Monitor<T>::integral_type &integral, double *res) { Monitor<T> m(dim, integral); m.eval(iter_num_, particle_); Eigen::Map<Eigen::VectorXd> r(res, m.dim()); r = m.record().back(); } /// \brief Add a monitor, similar to \b monitor in \b BUGS /// /// \param name The name of the monitor /// \param integral The functor used to compute the integrands template<typename MonitorType> void monitor (const std::string &name, const MonitorType &integral) { monitor_.insert(std::make_pair( name, Monitor<T>(integral.dim(), integral))); monitor_name_.insert(name); } /// \brief Add a monitor, similar to \b monitor in \b BUGS /// /// \param name The name of the monitor /// \param dim The dimension of the monitor /// \param integral The functor used to compute the integrands void monitor (const std::string &name, unsigned dim, const typename Monitor<T>::integral_type &integral) { monitor_.insert(std::make_pair(name, Monitor<T>(dim, integral))); monitor_name_.insert(name); } /// \brief Read only access to a named monitor through iterator /// /// \param name The name of the monitor /// /// \return An const_iterator point to the monitor for the given name typename std::map<std::string, Monitor<T> >::const_iterator monitor (const std::string &name) const { return monitor_.find(name); } /// \brief Read only access to all monitors /// /// \return A const reference to monitors const std::map<std::string, Monitor<T> > &monitor () const { return monitor_; } /// \brief Erase a named monitor /// /// \param name The name of the monitor void clear_monitor (const std::string &name) { monitor_.erase(name); monitor_name_.erase(name); } /// \brief Erase all monitors void clear_monitor () { monitor_.clear(); monitor_name_.clear(); } /// \brief Read only access to the Path sampling monitor /// /// \return A const reference to the Path sampling monitor const Path<T> &path () const { return path_; } /// \brief Set the path sampling integral /// /// \param integral The functor used to compute the integrands void path_sampling (const typename Path<T>::integral_type &integral) { path_.integral(integral); } /// \brief Path sampling estimate of normalizing constant /// /// \return The log ratio of normalizing constants double path_sampling () const { return path_.zconst(); } /// \brief SMC estimate of normalizing constant /// /// \return The log of SMC normalizng constant estimate double zconst () const { return particle_.zconst(); } /// \brief Print the history of the sampler /// /// \param os The ostream to which the contents are printed /// \param print_header Print header if \b true void print (std::ostream &os = std::cout, bool print_header = true) const { print(os, print_header, !path_.index().empty(), monitor_name_); } /// \brief Print the history of the sampler /// /// \param os The ostream to which the contents are printed /// \param print_path Print path sampling history if \b true /// \param print_monitor A set of monitor names to be printed /// \param print_header Print header if \b true void print (std::ostream &os, bool print_header, bool print_path, const std::set<std::string> &print_monitor) const { if (print_header) { os << "iter\tESS\tresample\taccept\t"; if (print_path) os << "path.integrand\tpath.width\tpath.grid\t"; } typename Path<T>::index_type::const_iterator iter_path_index = path_.index().begin(); typename Path<T>::integrand_type::const_iterator iter_path_integrand = path_.integrand().begin(); typename Path<T>::width_type::const_iterator iter_path_width = path_.width().begin(); typename Path<T>::grid_type::const_iterator iter_path_grid = path_.grid().begin(); std::vector<bool> monitor_index_empty; std::vector<unsigned> monitor_dim; std::vector<typename Monitor<T>::index_type::const_iterator> iter_monitor_index; std::vector<typename Monitor<T>::record_type::const_iterator> iter_monitor_record; for (typename std::map<std::string, Monitor<T> >::const_iterator imap = monitor_.begin(); imap != monitor_.end(); ++imap) { if (print_monitor.count(imap->first)) { monitor_index_empty.push_back(imap->second.index().empty()); monitor_dim.push_back(imap->second.dim()); iter_monitor_index.push_back(imap->second.index().begin()); iter_monitor_record.push_back(imap->second.record().begin()); if (print_header) { if (monitor_dim.back() > 1) { for (unsigned d = 0; d != monitor_dim.back(); ++d) os << imap->first << d + 1 << '\t'; } else { os << imap->first << '\t'; } } } } if (print_header) os << '\n'; for (std::size_t i = 0; i != iter_size(); ++i) { os << i << '\t' << ess_[i] / size() << '\t' << resampled_[i] << '\t' << static_cast<double>(accept_[i]) / size(); if (print_path) { if (!path_.index().empty() && *iter_path_index == i) { os << '\t' << *iter_path_integrand++ << '\t' << *iter_path_width++ << '\t' << *iter_path_grid++; ++iter_path_index; } else { os << '\t' << '.' << '\t' << '.' << '\t' << '.'; } } for (std::size_t m = 0; m != monitor_index_empty.size(); ++m) { if (!monitor_index_empty[m] && *iter_monitor_index[m] == i) { for (unsigned d = 0; d != monitor_dim[m]; ++d) os << '\t' << (*iter_monitor_record[m])[d]; ++iter_monitor_index[m]; ++iter_monitor_record[m]; } else { for (unsigned d = 0; d != monitor_dim[m]; ++d) os << '\t' << '.'; } } if (i != iter_size() - 1) os << '\n'; } } private : /// Initialization indicator bool initialized_; /// Initialization and movement initialize_type init_; move_type move_; move_type mcmc_; /// Resampling ResampleScheme scheme_; double threshold_; /// Particle sets Particle<T> particle_; std::size_t iter_num_; ess_type ess_; resampled_type resampled_; accept_type accept_; /// Monte Carlo estimation by integration std::map<std::string, Monitor<T> > monitor_; std::set<std::string> monitor_name_; /// Path sampling Path<T> path_; void post_move () { ess_.push_back(particle_.ess()); particle_.resampled(ess_.back() < threshold_); resampled_.push_back(particle_.resampled()); if (particle_.resampled()) { particle_.resample(scheme_); ess_.back() = particle_.size(); } if (!path_.empty()) path_.eval(iter_num_, particle_); for (typename std::map<std::string, Monitor<T> >::iterator imap = monitor_.begin(); imap != monitor_.end(); ++imap) { if (!imap->second.empty()) imap->second.eval(iter_num_, particle_); } } }; // class Sampler } // namespace vSMC namespace std { /// \brief Print the sampler /// /// \param os The ostream to which the contents are printed /// \param sampler The sampler to be printed /// /// \note This is the same as <tt>sampler.print(os)</tt> template<typename T> std::ostream & operator<< (std::ostream &os, const vSMC::Sampler<T> &sampler) { sampler.print(os); return os; } } // namespace std #endif // V_SMC_CORE_SAMPLER_HPP <commit_msg>fix non const initialize_type argument<commit_after>#ifndef V_SMC_CORE_SAMPLER_HPP #define V_SMC_CORE_SAMPLER_HPP #include <vSMC/internal/common.hpp> #include <iostream> #include <map> #include <set> #include <string> namespace vSMC { /// \brief SMC Sampler /// /// \tparam T State state type. Requiment: /// \li Consturctor: T (IntType N) /// \li Method: copy (IntType from, IntType to) template <typename T> class Sampler { public : /// The type of initialization functor typedef internal::function<std::size_t (Particle<T> &, void *)> initialize_type; /// The type of move functor typedef internal::function<std::size_t (std::size_t, Particle<T> &)> move_type; /// The type ESS history vector typedef std::vector<double> ess_type; /// The type resampling history vector typedef std::vector<bool> resampled_type; /// The type accept count history vector typedef std::vector<std::size_t> accept_type; /// \brief Construct a sampler with given number of particles /// /// \param N The number of particles /// \param init The functor used to initialize the particles /// \param move The functor used to move the particles and weights /// \param mcmc The functor used to perform MCMC move /// \param scheme The resampling scheme. See ResampleScheme /// \param threshold The threshold for performing resampling /// \param seed The seed to the parallel RNG system explicit Sampler ( typename Particle<T>::size_type N, const initialize_type &init = NULL, const move_type &move = NULL, const move_type &mcmc = NULL, ResampleScheme scheme = STRATIFIED, double threshold = 0.5, typename Particle<T>::seed_type seed = V_SMC_CRNG_SEED) : initialized_(false), init_(init), move_(move), mcmc_(mcmc), scheme_(scheme), threshold_(threshold * N), particle_(N, seed), iter_num_(0) { particle_.sampler(this); } /// \brief Size of the particle set /// /// \return The number of particles typename Particle<T>::size_type size () const { return particle_.size(); } /// \brief Size of records /// /// \return The number of iterations recorded (including the /// initialization step) std::size_t iter_size () const { return ess_.size(); } /// \brief Get the current resampling scheme /// /// \return The current resampling scheme ResampleScheme resample_scheme () const { return scheme_; } /// \brief Set new resampling scheme /// /// \param scheme The new scheme for resampling void resample_scheme (ResampleScheme scheme) { scheme_ = scheme; } /// \brief Get the current threshold /// /// \return The current threshold for resmapling double resample_threshold () const { return threshold_; } /// \brief Set new resampling threshold /// /// \param threshold The new threshold for resampling void resample_threshold (double threshold) { threshold_ = threshold * particle_.size(); } /// \brief ESS /// /// \return The ESS value of the latest iteration ess_type::value_type ess () const { return ess_.back(); } /// \brief ESS history /// /// \return A const reference to the history of ESS const ess_type &ess_history () const { return ess_; } /// \brief Indicator of resampling /// /// \return A bool value, \b true if the latest iteration was resampled resampled_type::value_type resampled () const { return resampled_.back(); } /// \brief Resampling history /// /// \return A const reference to the history of resampling const resampled_type &resampled_history () const { return resampled_; } /// \brief Accept count /// /// \return The accept count of the latest iteration accept_type::value_type accept () const { return accept_.back(); } /// \brief Accept count history /// /// \return A const reference to the history of accept count const accept_type &accept_history () const { return accept_; } /// \brief Read and write access to the particle set /// /// \return A reference to the latest particle set Particle<T> &particle () { return particle_; } /// \brief Read only access to the particle set /// /// \return A const reference to the latest particle set. const Particle<T> &particle () const { return particle_; } /// \brief Replace initialization functor /// /// \param init New Initialization functor void initialize (const initialize_type &init) { init_ = init; } /// \brief Initialize the particle set /// /// \param param Additional parameters passed to the initialization /// functor void initialize (void *param = NULL) { ess_.clear(); resampled_.clear(); accept_.clear(); path_.clear(); for (typename std::map<std::string, Monitor<T> >::iterator imap = monitor_.begin(); imap != monitor_.end(); ++imap) imap->second.clear(); iter_num_ = 0; accept_.push_back(init_(particle_, param)); post_move(); particle_.reset_zconst(); initialized_ = true; } /// \brief Replace iteration functor /// /// \param move New Move functor /// \param mcmc New MCMC functor void iterate (const move_type &move, const move_type &mcmc = NULL) { move_ = move; mcmc_ = mcmc; } /// \brief Perform iteration void iterate () { assert(initialized_); ++iter_num_; accept_.push_back(move_(iter_num_, particle_)); if (bool(mcmc_)) accept_.back() = mcmc_(iter_num_, particle_); post_move(); } /// \brief Perform iteration /// /// \param n The number of iterations to be performed void iterate (std::size_t n) { for (std::size_t i = 0; i != n; ++i) iterate(); } /// \brief Perform importance sampling integration /// /// \param integral The functor used to compute the integrands /// \param res The result, an array of length dim template<typename MonitorType> void integrate (const MonitorType &integral, double *res) { Monitor<T> m(integral.dim(), integral); m.eval(iter_num_, particle_); Eigen::Map<Eigen::VectorXd> r(res, m.dim()); r = m.record().back(); } /// \brief Perform importance sampling integration /// /// \param dim The dimension of the parameter /// \param integral The functor used to compute the integrands /// \param res The result, an array of length dim void integrate (unsigned dim, const typename Monitor<T>::integral_type &integral, double *res) { Monitor<T> m(dim, integral); m.eval(iter_num_, particle_); Eigen::Map<Eigen::VectorXd> r(res, m.dim()); r = m.record().back(); } /// \brief Add a monitor, similar to \b monitor in \b BUGS /// /// \param name The name of the monitor /// \param integral The functor used to compute the integrands template<typename MonitorType> void monitor (const std::string &name, const MonitorType &integral) { monitor_.insert(std::make_pair( name, Monitor<T>(integral.dim(), integral))); monitor_name_.insert(name); } /// \brief Add a monitor, similar to \b monitor in \b BUGS /// /// \param name The name of the monitor /// \param dim The dimension of the monitor /// \param integral The functor used to compute the integrands void monitor (const std::string &name, unsigned dim, const typename Monitor<T>::integral_type &integral) { monitor_.insert(std::make_pair(name, Monitor<T>(dim, integral))); monitor_name_.insert(name); } /// \brief Read only access to a named monitor through iterator /// /// \param name The name of the monitor /// /// \return An const_iterator point to the monitor for the given name typename std::map<std::string, Monitor<T> >::const_iterator monitor (const std::string &name) const { return monitor_.find(name); } /// \brief Read only access to all monitors /// /// \return A const reference to monitors const std::map<std::string, Monitor<T> > &monitor () const { return monitor_; } /// \brief Erase a named monitor /// /// \param name The name of the monitor void clear_monitor (const std::string &name) { monitor_.erase(name); monitor_name_.erase(name); } /// \brief Erase all monitors void clear_monitor () { monitor_.clear(); monitor_name_.clear(); } /// \brief Read only access to the Path sampling monitor /// /// \return A const reference to the Path sampling monitor const Path<T> &path () const { return path_; } /// \brief Set the path sampling integral /// /// \param integral The functor used to compute the integrands void path_sampling (const typename Path<T>::integral_type &integral) { path_.integral(integral); } /// \brief Path sampling estimate of normalizing constant /// /// \return The log ratio of normalizing constants double path_sampling () const { return path_.zconst(); } /// \brief SMC estimate of normalizing constant /// /// \return The log of SMC normalizng constant estimate double zconst () const { return particle_.zconst(); } /// \brief Print the history of the sampler /// /// \param os The ostream to which the contents are printed /// \param print_header Print header if \b true void print (std::ostream &os = std::cout, bool print_header = true) const { print(os, print_header, !path_.index().empty(), monitor_name_); } /// \brief Print the history of the sampler /// /// \param os The ostream to which the contents are printed /// \param print_path Print path sampling history if \b true /// \param print_monitor A set of monitor names to be printed /// \param print_header Print header if \b true void print (std::ostream &os, bool print_header, bool print_path, const std::set<std::string> &print_monitor) const { if (print_header) { os << "iter\tESS\tresample\taccept\t"; if (print_path) os << "path.integrand\tpath.width\tpath.grid\t"; } typename Path<T>::index_type::const_iterator iter_path_index = path_.index().begin(); typename Path<T>::integrand_type::const_iterator iter_path_integrand = path_.integrand().begin(); typename Path<T>::width_type::const_iterator iter_path_width = path_.width().begin(); typename Path<T>::grid_type::const_iterator iter_path_grid = path_.grid().begin(); std::vector<bool> monitor_index_empty; std::vector<unsigned> monitor_dim; std::vector<typename Monitor<T>::index_type::const_iterator> iter_monitor_index; std::vector<typename Monitor<T>::record_type::const_iterator> iter_monitor_record; for (typename std::map<std::string, Monitor<T> >::const_iterator imap = monitor_.begin(); imap != monitor_.end(); ++imap) { if (print_monitor.count(imap->first)) { monitor_index_empty.push_back(imap->second.index().empty()); monitor_dim.push_back(imap->second.dim()); iter_monitor_index.push_back(imap->second.index().begin()); iter_monitor_record.push_back(imap->second.record().begin()); if (print_header) { if (monitor_dim.back() > 1) { for (unsigned d = 0; d != monitor_dim.back(); ++d) os << imap->first << d + 1 << '\t'; } else { os << imap->first << '\t'; } } } } if (print_header) os << '\n'; for (std::size_t i = 0; i != iter_size(); ++i) { os << i << '\t' << ess_[i] / size() << '\t' << resampled_[i] << '\t' << static_cast<double>(accept_[i]) / size(); if (print_path) { if (!path_.index().empty() && *iter_path_index == i) { os << '\t' << *iter_path_integrand++ << '\t' << *iter_path_width++ << '\t' << *iter_path_grid++; ++iter_path_index; } else { os << '\t' << '.' << '\t' << '.' << '\t' << '.'; } } for (std::size_t m = 0; m != monitor_index_empty.size(); ++m) { if (!monitor_index_empty[m] && *iter_monitor_index[m] == i) { for (unsigned d = 0; d != monitor_dim[m]; ++d) os << '\t' << (*iter_monitor_record[m])[d]; ++iter_monitor_index[m]; ++iter_monitor_record[m]; } else { for (unsigned d = 0; d != monitor_dim[m]; ++d) os << '\t' << '.'; } } if (i != iter_size() - 1) os << '\n'; } } private : /// Initialization indicator bool initialized_; /// Initialization and movement initialize_type init_; move_type move_; move_type mcmc_; /// Resampling ResampleScheme scheme_; double threshold_; /// Particle sets Particle<T> particle_; std::size_t iter_num_; ess_type ess_; resampled_type resampled_; accept_type accept_; /// Monte Carlo estimation by integration std::map<std::string, Monitor<T> > monitor_; std::set<std::string> monitor_name_; /// Path sampling Path<T> path_; void post_move () { ess_.push_back(particle_.ess()); particle_.resampled(ess_.back() < threshold_); resampled_.push_back(particle_.resampled()); if (particle_.resampled()) { particle_.resample(scheme_); ess_.back() = particle_.size(); } if (!path_.empty()) path_.eval(iter_num_, particle_); for (typename std::map<std::string, Monitor<T> >::iterator imap = monitor_.begin(); imap != monitor_.end(); ++imap) { if (!imap->second.empty()) imap->second.eval(iter_num_, particle_); } } }; // class Sampler } // namespace vSMC namespace std { /// \brief Print the sampler /// /// \param os The ostream to which the contents are printed /// \param sampler The sampler to be printed /// /// \note This is the same as <tt>sampler.print(os)</tt> template<typename T> std::ostream & operator<< (std::ostream &os, const vSMC::Sampler<T> &sampler) { sampler.print(os); return os; } } // namespace std #endif // V_SMC_CORE_SAMPLER_HPP <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "codec_def.h" #include "codec_app_def.h" #include "codec_api.h" #include "wels_common_basis.h" #include "mem_align.h" #include "ls_defines.h" using namespace WelsDec; #define BUF_SIZE 100 //payload size exclude 6 bytes: 0001, nal type and final '\0' #define PAYLOAD_SIZE (BUF_SIZE - 6) class DecoderInterfaceTest : public ::testing::Test { public: virtual void SetUp() { int rv = WelsCreateDecoder (&m_pDec); ASSERT_EQ (0, rv); ASSERT_TRUE (m_pDec != NULL); } virtual void TearDown() { if (m_pDec) { WelsDestroyDecoder (m_pDec); } } //Init members void Init(); //Uninit members void Uninit(); //Mock input data for test void MockPacketType (const EWelsNalUnitType eNalUnitType, const int iPacketLength); //Test Initialize/Uninitialize void TestInitUninit(); //DECODER_OPTION_DATAFORMAT void TestDataFormat(); //DECODER_OPTION_END_OF_STREAM void TestEndOfStream(); //DECODER_OPTION_VCL_NAL void TestVclNal(); //DECODER_OPTION_TEMPORAL_ID void TestTemporalId(); //DECODER_OPTION_FRAME_NUM void TestFrameNum(); //DECODER_OPTION_IDR_PIC_ID void TestIdrPicId(); //DECODER_OPTION_LTR_MARKING_FLAG void TestLtrMarkingFlag(); //DECODER_OPTION_LTR_MARKED_FRAME_NUM void TestLtrMarkedFrameNum(); //DECODER_OPTION_ERROR_CON_IDC void TestErrorConIdc(); //DECODER_OPTION_TRACE_LEVEL void TestTraceLevel(); //DECODER_OPTION_TRACE_CALLBACK void TestTraceCallback(); //DECODER_OPTION_TRACE_CALLBACK_CONTEXT void TestTraceCallbackContext(); //Do whole tests here void DecoderInterfaceAll(); public: ISVCDecoder* m_pDec; SDecodingParam m_sDecParam; SBufferInfo m_sBufferInfo; uint8_t* m_pData[3]; unsigned char m_szBuffer[BUF_SIZE]; //for mocking packet int m_iBufLength; //record the valid data in m_szBuffer }; //Init members void DecoderInterfaceTest::Init() { memset (&m_sBufferInfo, 0, sizeof (SBufferInfo)); memset (&m_sDecParam, 0, sizeof (SDecodingParam)); m_sDecParam.pFileNameRestructed = NULL; m_sDecParam.eOutputColorFormat = (EVideoFormatType) (rand() % 100); m_sDecParam.uiCpuLoad = rand() % 100; m_sDecParam.uiTargetDqLayer = rand() % 100; m_sDecParam.eEcActiveIdc = (ERROR_CON_IDC) (rand() & 3); m_sDecParam.sVideoProperty.size = sizeof (SVideoProperty); m_sDecParam.sVideoProperty.eVideoBsType = (VIDEO_BITSTREAM_TYPE) (rand() % 3); m_pData[0] = m_pData[1] = m_pData[2] = NULL; m_szBuffer[0] = m_szBuffer[1] = m_szBuffer[2] = 0; m_szBuffer[3] = 1; m_iBufLength = 4; CM_RETURN eRet = (CM_RETURN) m_pDec->Initialize (&m_sDecParam); if ((m_sDecParam.eOutputColorFormat != videoFormatI420) || (m_sDecParam.eOutputColorFormat != videoFormatInternal)) ASSERT_EQ (eRet, cmUnsupportedData); else ASSERT_EQ (eRet, cmResultSuccess); } void DecoderInterfaceTest::Uninit() { if (m_pDec) { CM_RETURN eRet = (CM_RETURN) m_pDec->Uninitialize(); ASSERT_EQ (eRet, cmResultSuccess); } memset (&m_sDecParam, 0, sizeof (SDecodingParam)); memset (&m_sBufferInfo, 0, sizeof (SBufferInfo)); m_pData[0] = m_pData[1] = m_pData[2] = NULL; m_iBufLength = 0; } //Mock input data for test void DecoderInterfaceTest::MockPacketType (const EWelsNalUnitType eNalUnitType, const int iPacketLength) { switch (eNalUnitType) { case NAL_UNIT_SEI: m_szBuffer[m_iBufLength++] = 6; break; case NAL_UNIT_SPS: m_szBuffer[m_iBufLength++] = 67; break; case NAL_UNIT_PPS: m_szBuffer[m_iBufLength++] = 68; break; case NAL_UNIT_SUBSET_SPS: m_szBuffer[m_iBufLength++] = 15; break; case NAL_UNIT_PREFIX: m_szBuffer[m_iBufLength++] = 14; break; case NAL_UNIT_CODED_SLICE: m_szBuffer[m_iBufLength++] = 61; break; case NAL_UNIT_CODED_SLICE_IDR: m_szBuffer[m_iBufLength++] = 65; break; default: m_szBuffer[m_iBufLength++] = 0; //NAL_UNIT_UNSPEC_0 break; int iAddLength = iPacketLength - 5; //excluding 0001 and type if (iAddLength > PAYLOAD_SIZE) iAddLength = PAYLOAD_SIZE; for (int i = 0; i < iAddLength; ++i) { m_szBuffer[m_iBufLength++] = rand() % 256; } m_szBuffer[m_iBufLength++] = '\0'; } } //Test Initialize/Uninitialize void DecoderInterfaceTest::TestInitUninit() { int iOutput; CM_RETURN eRet; //No initialize, no GetOption can be done m_pDec->Uninitialize(); for (int i = 0; i <= (int) DECODER_OPTION_TRACE_CALLBACK_CONTEXT; ++i) { eRet = (CM_RETURN) m_pDec->GetOption ((DECODER_OPTION) i, &iOutput); EXPECT_EQ (eRet, cmInitExpected); } //Initialize first, can get input color format m_sDecParam.eOutputColorFormat = (EVideoFormatType) 20; //just for test m_pDec->Initialize (&m_sDecParam); eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_DATAFORMAT, &iOutput); EXPECT_EQ (eRet, cmResultSuccess); EXPECT_EQ ((int32_t) videoFormatI420, iOutput); //Uninitialize, no GetOption can be done m_pDec->Uninitialize(); iOutput = 21; for (int i = 0; i <= (int) DECODER_OPTION_TRACE_CALLBACK_CONTEXT; ++i) { eRet = (CM_RETURN) m_pDec->GetOption ((DECODER_OPTION) i, &iOutput); EXPECT_EQ (iOutput, 21); EXPECT_EQ (eRet, cmInitExpected); } } //DECODER_OPTION_DATAFORMAT void DecoderInterfaceTest::TestDataFormat() { int iTmp = rand(); int iOut; CM_RETURN eRet; Init(); //invalid input eRet = (CM_RETURN) m_pDec->SetOption (DECODER_OPTION_DATAFORMAT, NULL); EXPECT_EQ (eRet, cmInitParaError); //valid input eRet = (CM_RETURN) m_pDec->SetOption (DECODER_OPTION_DATAFORMAT, &iTmp); if ((iTmp != (int32_t) videoFormatI420) && (iTmp != (int32_t) videoFormatInternal)) EXPECT_EQ (eRet, cmUnsupportedData); else EXPECT_EQ (eRet, cmResultSuccess); eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_DATAFORMAT, &iOut); EXPECT_EQ (eRet, cmResultSuccess); EXPECT_EQ (iOut, (int32_t) videoFormatI420); Uninit(); } //DECODER_OPTION_END_OF_STREAM void DecoderInterfaceTest::TestEndOfStream() { int iTmp, iOut; CM_RETURN eRet; Init(); //invalid input eRet = (CM_RETURN) m_pDec->SetOption (DECODER_OPTION_END_OF_STREAM, NULL); EXPECT_EQ (eRet, cmInitParaError); //valid random input for (int i = 0; i < 10; ++i) { iTmp = rand(); eRet = (CM_RETURN) m_pDec->SetOption (DECODER_OPTION_END_OF_STREAM, &iTmp); EXPECT_EQ (eRet, cmResultSuccess); eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_END_OF_STREAM, &iOut); EXPECT_EQ (eRet, cmResultSuccess); EXPECT_EQ (iOut, iTmp != 0); } //set false as input iTmp = false; eRet = (CM_RETURN) m_pDec->SetOption (DECODER_OPTION_END_OF_STREAM, &iTmp); EXPECT_EQ (eRet, cmResultSuccess); eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_END_OF_STREAM, &iOut); EXPECT_EQ (eRet, cmResultSuccess); EXPECT_EQ (iOut, false); //set true as input iTmp = true; eRet = (CM_RETURN) m_pDec->SetOption (DECODER_OPTION_END_OF_STREAM, &iTmp); EXPECT_EQ (eRet, cmResultSuccess); eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_END_OF_STREAM, &iOut); EXPECT_EQ (eRet, cmResultSuccess); EXPECT_EQ (iOut, true); //Mock data packet in //Test NULL data input for decoder, should be true for EOS eRet = (CM_RETURN) m_pDec->DecodeFrame2 (NULL, 0, m_pData, &m_sBufferInfo); EXPECT_EQ (eRet, 0); //decode should return OK eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_END_OF_STREAM, &iOut); EXPECT_EQ (iOut, true); //decoder should have EOS == true //Test valid data input for decoder, should be false for EOS MockPacketType (NAL_UNIT_UNSPEC_0, 50); eRet = (CM_RETURN) m_pDec->DecodeFrame2 (m_szBuffer, m_iBufLength, m_pData, &m_sBufferInfo); eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_END_OF_STREAM, &iOut); EXPECT_EQ (iOut, false); //decoder should have EOS == false //Test NULL data input for decoder, should be true for EOS eRet = (CM_RETURN) m_pDec->DecodeFrame2 (NULL, 0, m_pData, &m_sBufferInfo); eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_END_OF_STREAM, &iOut); EXPECT_EQ (iOut, true); //decoder should have EOS == true Uninit(); } //DECODER_OPTION_VCL_NAL //Here Test illegal bitstream input //legal bitstream decoding test, please see api test void DecoderInterfaceTest::TestVclNal() { int iTmp, iOut; CM_RETURN eRet; Init(); //Test SetOption //VclNal never supports SetOption iTmp = rand(); eRet = (CM_RETURN) m_pDec->SetOption (DECODER_OPTION_VCL_NAL, &iTmp); EXPECT_EQ (eRet, cmInitParaError); //Test GetOption //invalid input eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_VCL_NAL, NULL); EXPECT_EQ (eRet, cmInitParaError); //valid input without actual decoding eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_VCL_NAL, &iOut); EXPECT_EQ (eRet, cmResultSuccess); EXPECT_EQ (iOut, FEEDBACK_NON_VCL_NAL); //valid input with decoding error MockPacketType (NAL_UNIT_CODED_SLICE_IDR, 50); m_pDec->DecodeFrame2 (m_szBuffer, m_iBufLength, m_pData, &m_sBufferInfo); eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_VCL_NAL, &iOut); EXPECT_EQ (eRet, cmResultSuccess); EXPECT_EQ (iOut, FEEDBACK_UNKNOWN_NAL); m_pDec->DecodeFrame2 (NULL, 0, m_pData, &m_sBufferInfo); eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_VCL_NAL, &iOut); EXPECT_EQ (eRet, cmResultSuccess); EXPECT_EQ (iOut, FEEDBACK_UNKNOWN_NAL); Uninit(); } //DECODER_OPTION_TEMPORAL_ID void DecoderInterfaceTest::TestTemporalId() { //TODO } //DECODER_OPTION_FRAME_NUM void DecoderInterfaceTest::TestFrameNum() { //TODO } //DECODER_OPTION_IDR_PIC_ID void DecoderInterfaceTest::TestIdrPicId() { //TODO } //DECODER_OPTION_LTR_MARKING_FLAG void DecoderInterfaceTest::TestLtrMarkingFlag() { //TODO } //DECODER_OPTION_LTR_MARKED_FRAME_NUM void DecoderInterfaceTest::TestLtrMarkedFrameNum() { //TODO } //DECODER_OPTION_ERROR_CON_IDC void DecoderInterfaceTest::TestErrorConIdc() { //TODO } //DECODER_OPTION_TRACE_LEVEL void DecoderInterfaceTest::TestTraceLevel() { //TODO } //DECODER_OPTION_TRACE_CALLBACK void DecoderInterfaceTest::TestTraceCallback() { //TODO } //DECODER_OPTION_TRACE_CALLBACK_CONTEXT void DecoderInterfaceTest::TestTraceCallbackContext() { //TODO } //TEST here for whole tests TEST_F (DecoderInterfaceTest, DecoderInterfaceAll) { //Initialize Uninitialize TestInitUninit(); //DECODER_OPTION_DATAFORMAT TestDataFormat(); //DECODER_OPTION_END_OF_STREAM TestEndOfStream(); //DECODER_OPTION_VCL_NAL TestVclNal(); //DECODER_OPTION_TEMPORAL_ID TestTemporalId(); //DECODER_OPTION_FRAME_NUM TestFrameNum(); //DECODER_OPTION_IDR_PIC_ID TestIdrPicId(); //DECODER_OPTION_LTR_MARKING_FLAG TestLtrMarkingFlag(); //DECODER_OPTION_LTR_MARKED_FRAME_NUM TestLtrMarkedFrameNum(); //DECODER_OPTION_ERROR_CON_IDC TestErrorConIdc(); //DECODER_OPTION_TRACE_LEVEL TestTraceLevel(); //DECODER_OPTION_TRACE_CALLBACK TestTraceCallback(); //DECODER_OPTION_TRACE_CALLBACK_CONTEXT TestTraceCallbackContext(); } <commit_msg>bug fix for dataformat UT<commit_after>#include <gtest/gtest.h> #include "codec_def.h" #include "codec_app_def.h" #include "codec_api.h" #include "wels_common_basis.h" #include "mem_align.h" #include "ls_defines.h" using namespace WelsDec; #define BUF_SIZE 100 //payload size exclude 6 bytes: 0001, nal type and final '\0' #define PAYLOAD_SIZE (BUF_SIZE - 6) class DecoderInterfaceTest : public ::testing::Test { public: virtual void SetUp() { int rv = WelsCreateDecoder (&m_pDec); ASSERT_EQ (0, rv); ASSERT_TRUE (m_pDec != NULL); } virtual void TearDown() { if (m_pDec) { WelsDestroyDecoder (m_pDec); } } //Init members void Init(); //Uninit members void Uninit(); //Mock input data for test void MockPacketType (const EWelsNalUnitType eNalUnitType, const int iPacketLength); //Test Initialize/Uninitialize void TestInitUninit(); //DECODER_OPTION_DATAFORMAT void TestDataFormat(); //DECODER_OPTION_END_OF_STREAM void TestEndOfStream(); //DECODER_OPTION_VCL_NAL void TestVclNal(); //DECODER_OPTION_TEMPORAL_ID void TestTemporalId(); //DECODER_OPTION_FRAME_NUM void TestFrameNum(); //DECODER_OPTION_IDR_PIC_ID void TestIdrPicId(); //DECODER_OPTION_LTR_MARKING_FLAG void TestLtrMarkingFlag(); //DECODER_OPTION_LTR_MARKED_FRAME_NUM void TestLtrMarkedFrameNum(); //DECODER_OPTION_ERROR_CON_IDC void TestErrorConIdc(); //DECODER_OPTION_TRACE_LEVEL void TestTraceLevel(); //DECODER_OPTION_TRACE_CALLBACK void TestTraceCallback(); //DECODER_OPTION_TRACE_CALLBACK_CONTEXT void TestTraceCallbackContext(); //Do whole tests here void DecoderInterfaceAll(); public: ISVCDecoder* m_pDec; SDecodingParam m_sDecParam; SBufferInfo m_sBufferInfo; uint8_t* m_pData[3]; unsigned char m_szBuffer[BUF_SIZE]; //for mocking packet int m_iBufLength; //record the valid data in m_szBuffer }; //Init members void DecoderInterfaceTest::Init() { memset (&m_sBufferInfo, 0, sizeof (SBufferInfo)); memset (&m_sDecParam, 0, sizeof (SDecodingParam)); m_sDecParam.pFileNameRestructed = NULL; m_sDecParam.eOutputColorFormat = (EVideoFormatType) (rand() % 100); m_sDecParam.uiCpuLoad = rand() % 100; m_sDecParam.uiTargetDqLayer = rand() % 100; m_sDecParam.eEcActiveIdc = (ERROR_CON_IDC) (rand() & 3); m_sDecParam.sVideoProperty.size = sizeof (SVideoProperty); m_sDecParam.sVideoProperty.eVideoBsType = (VIDEO_BITSTREAM_TYPE) (rand() % 3); m_pData[0] = m_pData[1] = m_pData[2] = NULL; m_szBuffer[0] = m_szBuffer[1] = m_szBuffer[2] = 0; m_szBuffer[3] = 1; m_iBufLength = 4; CM_RETURN eRet = (CM_RETURN) m_pDec->Initialize (&m_sDecParam); if ((m_sDecParam.eOutputColorFormat != videoFormatI420) && (m_sDecParam.eOutputColorFormat != videoFormatInternal)) ASSERT_EQ (eRet, cmUnsupportedData); else ASSERT_EQ (eRet, cmResultSuccess); } void DecoderInterfaceTest::Uninit() { if (m_pDec) { CM_RETURN eRet = (CM_RETURN) m_pDec->Uninitialize(); ASSERT_EQ (eRet, cmResultSuccess); } memset (&m_sDecParam, 0, sizeof (SDecodingParam)); memset (&m_sBufferInfo, 0, sizeof (SBufferInfo)); m_pData[0] = m_pData[1] = m_pData[2] = NULL; m_iBufLength = 0; } //Mock input data for test void DecoderInterfaceTest::MockPacketType (const EWelsNalUnitType eNalUnitType, const int iPacketLength) { switch (eNalUnitType) { case NAL_UNIT_SEI: m_szBuffer[m_iBufLength++] = 6; break; case NAL_UNIT_SPS: m_szBuffer[m_iBufLength++] = 67; break; case NAL_UNIT_PPS: m_szBuffer[m_iBufLength++] = 68; break; case NAL_UNIT_SUBSET_SPS: m_szBuffer[m_iBufLength++] = 15; break; case NAL_UNIT_PREFIX: m_szBuffer[m_iBufLength++] = 14; break; case NAL_UNIT_CODED_SLICE: m_szBuffer[m_iBufLength++] = 61; break; case NAL_UNIT_CODED_SLICE_IDR: m_szBuffer[m_iBufLength++] = 65; break; default: m_szBuffer[m_iBufLength++] = 0; //NAL_UNIT_UNSPEC_0 break; int iAddLength = iPacketLength - 5; //excluding 0001 and type if (iAddLength > PAYLOAD_SIZE) iAddLength = PAYLOAD_SIZE; for (int i = 0; i < iAddLength; ++i) { m_szBuffer[m_iBufLength++] = rand() % 256; } m_szBuffer[m_iBufLength++] = '\0'; } } //Test Initialize/Uninitialize void DecoderInterfaceTest::TestInitUninit() { int iOutput; CM_RETURN eRet; //No initialize, no GetOption can be done m_pDec->Uninitialize(); for (int i = 0; i <= (int) DECODER_OPTION_TRACE_CALLBACK_CONTEXT; ++i) { eRet = (CM_RETURN) m_pDec->GetOption ((DECODER_OPTION) i, &iOutput); EXPECT_EQ (eRet, cmInitExpected); } //Initialize first, can get input color format m_sDecParam.eOutputColorFormat = (EVideoFormatType) 20; //just for test m_pDec->Initialize (&m_sDecParam); eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_DATAFORMAT, &iOutput); EXPECT_EQ (eRet, cmResultSuccess); EXPECT_EQ ((int32_t) videoFormatI420, iOutput); //Uninitialize, no GetOption can be done m_pDec->Uninitialize(); iOutput = 21; for (int i = 0; i <= (int) DECODER_OPTION_TRACE_CALLBACK_CONTEXT; ++i) { eRet = (CM_RETURN) m_pDec->GetOption ((DECODER_OPTION) i, &iOutput); EXPECT_EQ (iOutput, 21); EXPECT_EQ (eRet, cmInitExpected); } } //DECODER_OPTION_DATAFORMAT void DecoderInterfaceTest::TestDataFormat() { int iTmp = rand(); int iOut; CM_RETURN eRet; Init(); //invalid input eRet = (CM_RETURN) m_pDec->SetOption (DECODER_OPTION_DATAFORMAT, NULL); EXPECT_EQ (eRet, cmInitParaError); //valid input eRet = (CM_RETURN) m_pDec->SetOption (DECODER_OPTION_DATAFORMAT, &iTmp); if ((iTmp != (int32_t) videoFormatI420) && (iTmp != (int32_t) videoFormatInternal)) EXPECT_EQ (eRet, cmUnsupportedData); else EXPECT_EQ (eRet, cmResultSuccess); eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_DATAFORMAT, &iOut); EXPECT_EQ (eRet, cmResultSuccess); EXPECT_EQ (iOut, (int32_t) videoFormatI420); Uninit(); } //DECODER_OPTION_END_OF_STREAM void DecoderInterfaceTest::TestEndOfStream() { int iTmp, iOut; CM_RETURN eRet; Init(); //invalid input eRet = (CM_RETURN) m_pDec->SetOption (DECODER_OPTION_END_OF_STREAM, NULL); EXPECT_EQ (eRet, cmInitParaError); //valid random input for (int i = 0; i < 10; ++i) { iTmp = rand(); eRet = (CM_RETURN) m_pDec->SetOption (DECODER_OPTION_END_OF_STREAM, &iTmp); EXPECT_EQ (eRet, cmResultSuccess); eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_END_OF_STREAM, &iOut); EXPECT_EQ (eRet, cmResultSuccess); EXPECT_EQ (iOut, iTmp != 0); } //set false as input iTmp = false; eRet = (CM_RETURN) m_pDec->SetOption (DECODER_OPTION_END_OF_STREAM, &iTmp); EXPECT_EQ (eRet, cmResultSuccess); eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_END_OF_STREAM, &iOut); EXPECT_EQ (eRet, cmResultSuccess); EXPECT_EQ (iOut, false); //set true as input iTmp = true; eRet = (CM_RETURN) m_pDec->SetOption (DECODER_OPTION_END_OF_STREAM, &iTmp); EXPECT_EQ (eRet, cmResultSuccess); eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_END_OF_STREAM, &iOut); EXPECT_EQ (eRet, cmResultSuccess); EXPECT_EQ (iOut, true); //Mock data packet in //Test NULL data input for decoder, should be true for EOS eRet = (CM_RETURN) m_pDec->DecodeFrame2 (NULL, 0, m_pData, &m_sBufferInfo); EXPECT_EQ (eRet, 0); //decode should return OK eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_END_OF_STREAM, &iOut); EXPECT_EQ (iOut, true); //decoder should have EOS == true //Test valid data input for decoder, should be false for EOS MockPacketType (NAL_UNIT_UNSPEC_0, 50); eRet = (CM_RETURN) m_pDec->DecodeFrame2 (m_szBuffer, m_iBufLength, m_pData, &m_sBufferInfo); eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_END_OF_STREAM, &iOut); EXPECT_EQ (iOut, false); //decoder should have EOS == false //Test NULL data input for decoder, should be true for EOS eRet = (CM_RETURN) m_pDec->DecodeFrame2 (NULL, 0, m_pData, &m_sBufferInfo); eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_END_OF_STREAM, &iOut); EXPECT_EQ (iOut, true); //decoder should have EOS == true Uninit(); } //DECODER_OPTION_VCL_NAL //Here Test illegal bitstream input //legal bitstream decoding test, please see api test void DecoderInterfaceTest::TestVclNal() { int iTmp, iOut; CM_RETURN eRet; Init(); //Test SetOption //VclNal never supports SetOption iTmp = rand(); eRet = (CM_RETURN) m_pDec->SetOption (DECODER_OPTION_VCL_NAL, &iTmp); EXPECT_EQ (eRet, cmInitParaError); //Test GetOption //invalid input eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_VCL_NAL, NULL); EXPECT_EQ (eRet, cmInitParaError); //valid input without actual decoding eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_VCL_NAL, &iOut); EXPECT_EQ (eRet, cmResultSuccess); EXPECT_EQ (iOut, FEEDBACK_NON_VCL_NAL); //valid input with decoding error MockPacketType (NAL_UNIT_CODED_SLICE_IDR, 50); m_pDec->DecodeFrame2 (m_szBuffer, m_iBufLength, m_pData, &m_sBufferInfo); eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_VCL_NAL, &iOut); EXPECT_EQ (eRet, cmResultSuccess); EXPECT_EQ (iOut, FEEDBACK_UNKNOWN_NAL); m_pDec->DecodeFrame2 (NULL, 0, m_pData, &m_sBufferInfo); eRet = (CM_RETURN) m_pDec->GetOption (DECODER_OPTION_VCL_NAL, &iOut); EXPECT_EQ (eRet, cmResultSuccess); EXPECT_EQ (iOut, FEEDBACK_UNKNOWN_NAL); Uninit(); } //DECODER_OPTION_TEMPORAL_ID void DecoderInterfaceTest::TestTemporalId() { //TODO } //DECODER_OPTION_FRAME_NUM void DecoderInterfaceTest::TestFrameNum() { //TODO } //DECODER_OPTION_IDR_PIC_ID void DecoderInterfaceTest::TestIdrPicId() { //TODO } //DECODER_OPTION_LTR_MARKING_FLAG void DecoderInterfaceTest::TestLtrMarkingFlag() { //TODO } //DECODER_OPTION_LTR_MARKED_FRAME_NUM void DecoderInterfaceTest::TestLtrMarkedFrameNum() { //TODO } //DECODER_OPTION_ERROR_CON_IDC void DecoderInterfaceTest::TestErrorConIdc() { //TODO } //DECODER_OPTION_TRACE_LEVEL void DecoderInterfaceTest::TestTraceLevel() { //TODO } //DECODER_OPTION_TRACE_CALLBACK void DecoderInterfaceTest::TestTraceCallback() { //TODO } //DECODER_OPTION_TRACE_CALLBACK_CONTEXT void DecoderInterfaceTest::TestTraceCallbackContext() { //TODO } //TEST here for whole tests TEST_F (DecoderInterfaceTest, DecoderInterfaceAll) { //Initialize Uninitialize TestInitUninit(); //DECODER_OPTION_DATAFORMAT TestDataFormat(); //DECODER_OPTION_END_OF_STREAM TestEndOfStream(); //DECODER_OPTION_VCL_NAL TestVclNal(); //DECODER_OPTION_TEMPORAL_ID TestTemporalId(); //DECODER_OPTION_FRAME_NUM TestFrameNum(); //DECODER_OPTION_IDR_PIC_ID TestIdrPicId(); //DECODER_OPTION_LTR_MARKING_FLAG TestLtrMarkingFlag(); //DECODER_OPTION_LTR_MARKED_FRAME_NUM TestLtrMarkedFrameNum(); //DECODER_OPTION_ERROR_CON_IDC TestErrorConIdc(); //DECODER_OPTION_TRACE_LEVEL TestTraceLevel(); //DECODER_OPTION_TRACE_CALLBACK TestTraceCallback(); //DECODER_OPTION_TRACE_CALLBACK_CONTEXT TestTraceCallbackContext(); } <|endoftext|>
<commit_before>// http://thispointer.com/c-how-to-find-duplicates-in-a-vector/ #include <algorithm> #include <functional> #include <iostream> #include <map> #include <string> #include <vector> // Print the contents of vector template <typename T> void print(T& vecOfElements, std::string delimeter = " , ") { for (auto elem : vecOfElements) std::cout << elem << delimeter; std::cout << std::endl; } /* * Generic function to find duplicates elements in vector. * It adds the duplicate elements and their duplication count in given map * countMap */ template <typename T> void findDuplicates(std::vector<T>& vecOfElements, std::map<T, int>& countMap) { // Iterate over the vector and store the frequency of each element in map for (auto& elem : vecOfElements) { auto result = countMap.insert(std::pair<std::string, int>(elem, 1)); if (result.second == false) result.first->second++; } // Remove the elements from Map which has 1 frequency count for (auto it = countMap.begin(); it != countMap.end();) { if (it->second == 1) it = countMap.erase(it); else it++; } } int main() { // Vector of strings std::vector<std::string> vecOfStings{"at", "hello", "hi", "there", "where", "now", "is", "that", "hi", "where", "at", "no", "yes", "at"}; print(vecOfStings); // Create a map to store the frequency of each element in vector std::map<std::string, int> countMap; // Iterate over the vector and store the frequency of each element in map for (auto& elem : vecOfStings) { auto result = countMap.insert(std::pair<std::string, int>(elem, 1)); if (result.second == false) result.first->second++; } std::cout << "Duplicate elements and their duplication count " << std::endl; // Iterate over the map for (auto& elem : countMap) { // If frequency count is greater than 1 then its a duplicate element if (elem.second > 1) { std::cout << elem.first << " :: " << elem.second << std::endl; } } /* * Finding duplicates in vector using generic function */ std::map<std::string, int> duplicateElements; // Get the duplicate elements in vector findDuplicates(vecOfStings, duplicateElements); std::cout << "Duplicate elements and their duplication count " << std::endl; for (auto& elem : duplicateElements) std::cout << elem.first << " :: " << elem.second << std::endl; return 0; } <commit_msg>Use std::begin/end and proper const usage.<commit_after>// http://thispointer.com/c-how-to-find-duplicates-in-a-vector/ // https://stackoverflow.com/q/32590764/496459 #include <algorithm> #include <functional> #include <iostream> #include <map> #include <string> #include <vector> // Print the contents of vector template <typename T> void print(T& vecOfElements, std::string delimeter = " , ") { for (auto const& elem : vecOfElements) std::cout << elem << delimeter; std::cout << std::endl; } /* * Generic function to find duplicates elements in vector. * It adds the duplicate elements and their duplication count in given map * countMap */ template <typename T> void findDuplicates(std::vector<T>& vecOfElements, std::map<T, int>& countMap) { // Iterate over the vector and store the frequency of each element in map for (auto& elem : vecOfElements) { auto result = countMap.insert(std::pair<std::string, int>(elem, 1)); if (result.second == false) result.first->second++; } // Remove the elements from Map which has 1 frequency count for (auto it = std::begin(countMap); it != std::end(countMap);) { if (it->second == 1) it = countMap.erase(it); else it++; } } int main() { // Vector of strings std::vector<std::string> vecOfStings{"at", "hello", "hi", "there", "where", "now", "is", "that", "hi", "where", "at", "no", "yes", "at"}; print(vecOfStings); /* * Finding duplicates in vector using generic function */ std::map<std::string, int> duplicateElements; // Get the duplicate elements in vector findDuplicates(vecOfStings, duplicateElements); std::cout << "Duplicate elements and their duplication count " << std::endl; for (auto const& elem : duplicateElements) std::cout << elem.first << " :: " << elem.second << std::endl; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: string.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2007-11-02 17:47:05 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <precomp.h> #include <cosv/string.hxx> // NOT FULLY DECLARED SERVICES #include <string.h> #include <cosv/comfunc.hxx> namespace csv { inline const char * str_from_StringOffset( const String & i_rStr, str::size i_nOffset ) { return i_nOffset < i_rStr.size() ? i_rStr.c_str() + i_nOffset : ""; } inline const char * str_from_ptr( const char * i_str ) { return valid_str(i_str); } //********************* String::S_Data **********************// inline String:: S_Data::S_Data() : nCount(1) { } String:: S_Data::S_Data( const char * i_sData, size_type i_nValidLength ) : aStr( str_from_ptr(i_sData), (i_nValidLength != str::maxsize ? i_nValidLength : strlen(i_sData)) ), nCount(1) { } String:: S_Data::~S_Data() { csv_assert( nCount == 0 ); } const String::S_Data * String:: S_Data::Acquire() const { #ifdef CSV_NO_MUTABLE ++ (const_cast< uintt& >(nCount)); #else ++nCount; #endif return this; } void String:: S_Data::Release() const { #ifdef CSV_NO_MUTABLE -- (const_cast< uintt& >(nCount)); #else --nCount; #endif if (nCount == 0) delete (const_cast< S_Data* >(this)); } //************************** String **************************// String::String() : pd( String::Null_().pd->Acquire() ) { } String::String( const char * i_str ) : pd( new S_Data(i_str) ) { } String::String( const char * i_str, size_type i_nLength ) : pd( new S_Data(i_str, i_nLength) ) { } /* For efficiency see the previous c'tor. */ String::String( const self & i_rStr, position_type i_nStartPosition, size_type i_nLength ) : pd( new S_Data(str_from_StringOffset(i_rStr, i_nStartPosition), i_nLength) ) { } String::String( const_iterator i_itBegin, const_iterator i_itEnd ) : pd( new S_Data(i_itBegin, size_type(i_itEnd - i_itBegin)) ) { } String::String( const self & i_rStr ) : pd( i_rStr.pd->Acquire() ) { } String::~String() { pd->Release(); } String & String::operator=( const self & i_rStr ) { i_rStr.pd->Acquire(); pd->Release(); pd = i_rStr.pd; return *this; } String & String::operator=( const char * i_str ) { const S_Data * pTemp = new S_Data(i_str); pd->Release(); pd = pTemp; return *this; } void String::swap( self & i_rStr ) { const S_Data * pTemp = pd; pd = i_rStr.pd; i_rStr.pd = pTemp; } void String::assign( const self & i_rStr, position_type i_nStartPosition, size_type i_nLength ) { const S_Data * pTemp = new S_Data( str_from_StringOffset(i_rStr, i_nStartPosition), i_nLength ); pd->Release(); pd = pTemp; } void String::assign( const char * i_str ) { const S_Data * pTemp = new S_Data( i_str ); pd->Release(); pd = pTemp; } void String::assign( const char * i_str, size_type i_nLength ) { const S_Data * pTemp = new S_Data( i_str, i_nLength ); pd->Release(); pd = pTemp; } void String::assign( const_iterator i_itBegin, const_iterator i_itEnd ) { const S_Data * pTemp = new S_Data( i_itBegin, size_type(i_itEnd - i_itBegin) ); pd->Release(); pd = pTemp; } int String::compare( const self & i_rStr ) const { return strcmp( c_str(), i_rStr.c_str() ); } int String::compare( const CharOrder_Table & i_rOrder, const self & i_rStr ) const { return csv::compare( i_rOrder, c_str(), i_rStr.c_str() ); } String String::substr( position_type i_nStartPosition, size_type i_nLength ) const { size_type nSize = size(); if ( i_nStartPosition < nSize ) { if ( i_nLength == str::maxsize OR i_nLength >= nSize - i_nStartPosition ) return String( c_str() + i_nStartPosition ); else return String( c_str() + i_nStartPosition, i_nLength ); } return Null_(); } String::position_type String::find( const char * i_strToSearch, position_type i_nSearchStartPosition ) const { csv_assert(i_strToSearch != 0); if ( i_nSearchStartPosition < length() AND *i_strToSearch != '\0' ) { const char * p = strstr(c_str() + i_nSearchStartPosition, i_strToSearch); if (p != 0) return static_cast<position_type>(p - c_str()); } return str::position(str::npos); } String::position_type String::find( char i_charToSearch, position_type i_nSearchStartPosition ) const { if (i_nSearchStartPosition <= length()) { const char * p = strchr(c_str() + i_nSearchStartPosition, i_charToSearch); if (p != 0) return static_cast<position_type>(p - c_str()); } return str::position(str::npos); } const String & String::Null_() { // Must not use the default constructor! Because that one calls // this function, which would create a circular dependency. static const String aNull_(""); return aNull_; } const char & String::Nulch_() { static const char cNull_ = '\0'; return cNull_; } int compare( const String & i_s1, csv::str::position i_nStartPosition1, const char * i_s2, csv::str::size i_nLength ) { const char * pS1 = str_from_StringOffset( i_s1, i_nStartPosition1 ); if ( i_nLength != csv::str::maxsize ) return strncmp( pS1, i_s2, i_nLength ); else return strcmp( pS1, i_s2 ); } int compare( const char * i_s1, const String & i_s2, csv::str::position i_nStartPosition2, csv::str::size i_nLength ) { const char * pS2 = str_from_StringOffset( i_s2, i_nStartPosition2 ); if ( i_nLength != csv::str::maxsize ) return strncmp( i_s1, pS2, i_nLength ); else return strcmp( i_s1, pS2 ); } int compare( const CharOrder_Table & i_rOrder, const char * i_s1, const char * i_s2 ) { const char * it1 = i_s1; const char * it2 = i_s2; for ( ; i_rOrder(*it1) == i_rOrder(*it2) AND *it1 != '\0'; ++it1, ++it2 ) {} return int( i_rOrder(*it1) - i_rOrder(*it2) ); } int compare( const CharOrder_Table & i_rOrder, const String & i_s1, csv::str::position i_nStartPosition1, const char * i_s2, csv::str::size i_nLength ) { const char * pS1 = str_from_StringOffset( i_s1, i_nStartPosition1 ); if ( i_nLength != csv::str::maxsize ) return compare( i_rOrder, pS1, i_s2, i_nLength ); else return compare( i_rOrder, pS1, i_s2 ); } int compare( const CharOrder_Table & i_rOrder, const char * i_s1, const String & i_s2, csv::str::position i_nStartPosition2, csv::str::size i_nLength ) { const char * pS2 = str_from_StringOffset( i_s2, i_nStartPosition2 ); if ( i_nLength != csv::str::maxsize ) return compare( i_rOrder, i_s1, pS2, i_nLength ); else return compare( i_rOrder, i_s1, pS2 ); } int compare( const CharOrder_Table & i_rOrder, const char * i_s1, const char * i_s2, csv::str::size i_nLength ) { const char * sEnd = i_s1 + i_nLength; const char * it1 = i_s1; const char * it2 = i_s2; for ( ; i_rOrder(*it1) == i_rOrder(*it2) AND *it1 != '\0' AND it1 != sEnd; ++it1, ++it2 ) {} if ( it1 != sEnd ) return int( i_rOrder(*it1) - i_rOrder(*it2) ); else return 0; } } // namespace csv <commit_msg>INTEGRATION: CWS changefileheader (1.5.12); FILE MERGED 2008/03/31 13:04:49 rt 1.5.12.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: string.cxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include <precomp.h> #include <cosv/string.hxx> // NOT FULLY DECLARED SERVICES #include <string.h> #include <cosv/comfunc.hxx> namespace csv { inline const char * str_from_StringOffset( const String & i_rStr, str::size i_nOffset ) { return i_nOffset < i_rStr.size() ? i_rStr.c_str() + i_nOffset : ""; } inline const char * str_from_ptr( const char * i_str ) { return valid_str(i_str); } //********************* String::S_Data **********************// inline String:: S_Data::S_Data() : nCount(1) { } String:: S_Data::S_Data( const char * i_sData, size_type i_nValidLength ) : aStr( str_from_ptr(i_sData), (i_nValidLength != str::maxsize ? i_nValidLength : strlen(i_sData)) ), nCount(1) { } String:: S_Data::~S_Data() { csv_assert( nCount == 0 ); } const String::S_Data * String:: S_Data::Acquire() const { #ifdef CSV_NO_MUTABLE ++ (const_cast< uintt& >(nCount)); #else ++nCount; #endif return this; } void String:: S_Data::Release() const { #ifdef CSV_NO_MUTABLE -- (const_cast< uintt& >(nCount)); #else --nCount; #endif if (nCount == 0) delete (const_cast< S_Data* >(this)); } //************************** String **************************// String::String() : pd( String::Null_().pd->Acquire() ) { } String::String( const char * i_str ) : pd( new S_Data(i_str) ) { } String::String( const char * i_str, size_type i_nLength ) : pd( new S_Data(i_str, i_nLength) ) { } /* For efficiency see the previous c'tor. */ String::String( const self & i_rStr, position_type i_nStartPosition, size_type i_nLength ) : pd( new S_Data(str_from_StringOffset(i_rStr, i_nStartPosition), i_nLength) ) { } String::String( const_iterator i_itBegin, const_iterator i_itEnd ) : pd( new S_Data(i_itBegin, size_type(i_itEnd - i_itBegin)) ) { } String::String( const self & i_rStr ) : pd( i_rStr.pd->Acquire() ) { } String::~String() { pd->Release(); } String & String::operator=( const self & i_rStr ) { i_rStr.pd->Acquire(); pd->Release(); pd = i_rStr.pd; return *this; } String & String::operator=( const char * i_str ) { const S_Data * pTemp = new S_Data(i_str); pd->Release(); pd = pTemp; return *this; } void String::swap( self & i_rStr ) { const S_Data * pTemp = pd; pd = i_rStr.pd; i_rStr.pd = pTemp; } void String::assign( const self & i_rStr, position_type i_nStartPosition, size_type i_nLength ) { const S_Data * pTemp = new S_Data( str_from_StringOffset(i_rStr, i_nStartPosition), i_nLength ); pd->Release(); pd = pTemp; } void String::assign( const char * i_str ) { const S_Data * pTemp = new S_Data( i_str ); pd->Release(); pd = pTemp; } void String::assign( const char * i_str, size_type i_nLength ) { const S_Data * pTemp = new S_Data( i_str, i_nLength ); pd->Release(); pd = pTemp; } void String::assign( const_iterator i_itBegin, const_iterator i_itEnd ) { const S_Data * pTemp = new S_Data( i_itBegin, size_type(i_itEnd - i_itBegin) ); pd->Release(); pd = pTemp; } int String::compare( const self & i_rStr ) const { return strcmp( c_str(), i_rStr.c_str() ); } int String::compare( const CharOrder_Table & i_rOrder, const self & i_rStr ) const { return csv::compare( i_rOrder, c_str(), i_rStr.c_str() ); } String String::substr( position_type i_nStartPosition, size_type i_nLength ) const { size_type nSize = size(); if ( i_nStartPosition < nSize ) { if ( i_nLength == str::maxsize OR i_nLength >= nSize - i_nStartPosition ) return String( c_str() + i_nStartPosition ); else return String( c_str() + i_nStartPosition, i_nLength ); } return Null_(); } String::position_type String::find( const char * i_strToSearch, position_type i_nSearchStartPosition ) const { csv_assert(i_strToSearch != 0); if ( i_nSearchStartPosition < length() AND *i_strToSearch != '\0' ) { const char * p = strstr(c_str() + i_nSearchStartPosition, i_strToSearch); if (p != 0) return static_cast<position_type>(p - c_str()); } return str::position(str::npos); } String::position_type String::find( char i_charToSearch, position_type i_nSearchStartPosition ) const { if (i_nSearchStartPosition <= length()) { const char * p = strchr(c_str() + i_nSearchStartPosition, i_charToSearch); if (p != 0) return static_cast<position_type>(p - c_str()); } return str::position(str::npos); } const String & String::Null_() { // Must not use the default constructor! Because that one calls // this function, which would create a circular dependency. static const String aNull_(""); return aNull_; } const char & String::Nulch_() { static const char cNull_ = '\0'; return cNull_; } int compare( const String & i_s1, csv::str::position i_nStartPosition1, const char * i_s2, csv::str::size i_nLength ) { const char * pS1 = str_from_StringOffset( i_s1, i_nStartPosition1 ); if ( i_nLength != csv::str::maxsize ) return strncmp( pS1, i_s2, i_nLength ); else return strcmp( pS1, i_s2 ); } int compare( const char * i_s1, const String & i_s2, csv::str::position i_nStartPosition2, csv::str::size i_nLength ) { const char * pS2 = str_from_StringOffset( i_s2, i_nStartPosition2 ); if ( i_nLength != csv::str::maxsize ) return strncmp( i_s1, pS2, i_nLength ); else return strcmp( i_s1, pS2 ); } int compare( const CharOrder_Table & i_rOrder, const char * i_s1, const char * i_s2 ) { const char * it1 = i_s1; const char * it2 = i_s2; for ( ; i_rOrder(*it1) == i_rOrder(*it2) AND *it1 != '\0'; ++it1, ++it2 ) {} return int( i_rOrder(*it1) - i_rOrder(*it2) ); } int compare( const CharOrder_Table & i_rOrder, const String & i_s1, csv::str::position i_nStartPosition1, const char * i_s2, csv::str::size i_nLength ) { const char * pS1 = str_from_StringOffset( i_s1, i_nStartPosition1 ); if ( i_nLength != csv::str::maxsize ) return compare( i_rOrder, pS1, i_s2, i_nLength ); else return compare( i_rOrder, pS1, i_s2 ); } int compare( const CharOrder_Table & i_rOrder, const char * i_s1, const String & i_s2, csv::str::position i_nStartPosition2, csv::str::size i_nLength ) { const char * pS2 = str_from_StringOffset( i_s2, i_nStartPosition2 ); if ( i_nLength != csv::str::maxsize ) return compare( i_rOrder, i_s1, pS2, i_nLength ); else return compare( i_rOrder, i_s1, pS2 ); } int compare( const CharOrder_Table & i_rOrder, const char * i_s1, const char * i_s2, csv::str::size i_nLength ) { const char * sEnd = i_s1 + i_nLength; const char * it1 = i_s1; const char * it2 = i_s2; for ( ; i_rOrder(*it1) == i_rOrder(*it2) AND *it1 != '\0' AND it1 != sEnd; ++it1, ++it2 ) {} if ( it1 != sEnd ) return int( i_rOrder(*it1) - i_rOrder(*it2) ); else return 0; } } // namespace csv <|endoftext|>
<commit_before>// NanoTexture.cpp // RenderToTexture // // Created by Eric Mika on 2/28/16. // #include "cinder/Log.h" #include "NanoTexture.h" NanoTextureRef NanoTexture::create() { return NanoTexture::create(512, 512); } NanoTextureRef NanoTexture::create(float width, float height) { NanoTextureRef ref = std::shared_ptr<NanoTexture>(new NanoTexture()); ref->setup(width, height); return ref; } NanoTexture::NanoTexture() { CI_LOG_V("NanoTexture Created"); } NanoTexture::~NanoTexture() { CI_LOG_V("NanoTexture Destroyed"); } void NanoTexture::setup(float width, float height) { // auto fboSize = mBounds.getSize() * getWindow()->getContentScale(); // TODO HIDPI mFbo = ci::gl::Fbo::create(width, height, ci::gl::Fbo::Format().stencilBuffer()); mCtx = std::make_shared<ci::nvg::Context>(ci::nvg::createContextGL()); // todo unique? } void NanoTexture::renderWithFunction(const std::function<void(ci::nvg::Context &, float, float)> &renderFunction) { auto &vg = *mCtx; ci::gl::ScopedFramebuffer fboScope(mFbo); ci::gl::viewport(mFbo->getSize()); ci::gl::clear(ci::ColorAf::zero()); ci::gl::clear(GL_STENCIL_BUFFER_BIT); vg.beginFrame(mFbo->getSize(), 1.0); // TODO HIDPI renderFunction(vg, mFbo->getWidth(), mFbo->getHeight()); vg.endFrame(); mTexture = mFbo->getColorTexture(); } const ci::gl::TextureRef NanoTexture::getTexture() const { return mTexture; } <commit_msg>Mip mapping for nanovg textures.<commit_after>// NanoTexture.cpp // RenderToTexture // // Created by Eric Mika on 2/28/16. // #include "cinder/Log.h" #include "NanoTexture.h" NanoTextureRef NanoTexture::create() { return NanoTexture::create(512, 512); } NanoTextureRef NanoTexture::create(float width, float height) { NanoTextureRef ref = std::shared_ptr<NanoTexture>(new NanoTexture()); ref->setup(width, height); return ref; } NanoTexture::NanoTexture() { CI_LOG_V("NanoTexture Created"); } NanoTexture::~NanoTexture() { CI_LOG_V("NanoTexture Destroyed"); } void NanoTexture::setup(float width, float height) { // auto fboSize = mBounds.getSize() * getWindow()->getContentScale(); // TODO HIDPI // mip map... ci::gl::Texture::Format textureFormat; textureFormat.setMinFilter(GL_LINEAR_MIPMAP_NEAREST); textureFormat.setMagFilter(GL_LINEAR); textureFormat.enableMipmapping(true); ci::gl::Fbo::Format fboFormat; fboFormat.enableStencilBuffer(); fboFormat.setColorTextureFormat(textureFormat); mFbo = ci::gl::Fbo::create(width, height, fboFormat); mCtx = std::make_shared<ci::nvg::Context>(ci::nvg::createContextGL()); // todo unique? } void NanoTexture::renderWithFunction(const std::function<void(ci::nvg::Context &, float, float)> &renderFunction) { auto &vg = *mCtx; ci::gl::ScopedFramebuffer fboScope(mFbo); ci::gl::viewport(mFbo->getSize()); ci::gl::clear(ci::ColorAf::zero()); ci::gl::clear(GL_STENCIL_BUFFER_BIT); vg.beginFrame(mFbo->getSize(), 1.0); // TODO HIDPI renderFunction(vg, mFbo->getWidth(), mFbo->getHeight()); vg.endFrame(); mTexture = mFbo->getColorTexture(); } const ci::gl::TextureRef NanoTexture::getTexture() const { return mTexture; } <|endoftext|>
<commit_before>#include <cstdlib> #include "game/lane_length_model.h" #include "gflags/gflags.h" #include "jsoncons_ext/csv/csv_reader.hpp" #include "jsoncons_ext/csv/csv_serializer.hpp" DECLARE_string(race_id); DECLARE_bool(print_models); DECLARE_bool(read_switch_models); DECLARE_bool(write_switch_models); using jsoncons_ext::csv::csv_reader; using jsoncons_ext::csv::csv_serializer; namespace game { LaneLengthModel::LaneLengthModel(const Track* track) : track_(track) { if (FLAGS_read_switch_models) { LoadSwitchLengths(); } } LaneLengthModel::~LaneLengthModel() { if (FLAGS_print_models) { std::cout << "==== Lane Length Model ====" << std::endl; std::cout << "Straight:" << std::endl; for (const auto& p : switch_on_straight_length_) { std::cout << "(" << p.first.first << "," << p.first.second << ") => " << p.second << std::endl; } std::cout << "Turn:" << std::endl; for (const auto& p : switch_on_turn_length_) { std::cout << "(" << std::get<0>(p.first) << "," << std::get<1>(p.first) << "," << std::get<2>(p.first) << ") => " << p.second << std::endl; } } if (FLAGS_write_switch_models) { SaveSwitchLengths(); } } double LaneLengthModel::Length(const Position& position, bool* perfect) const { if (perfect) *perfect = true; const auto& piece = track_->pieces()[position.piece()]; if (piece.type() == PieceType::kStraight) { if (position.start_lane() == position.end_lane()) { return piece.length(); } if (!piece.has_switch()) { std::cerr << "Changing lane on non switch piece?" << std::endl; } const double width = fabs(track_->lanes()[position.start_lane()].distance_from_center() - track_->lanes()[position.end_lane()].distance_from_center()); if (switch_on_straight_length_.count({piece.length(), width}) > 0) { return switch_on_straight_length_.at({piece.length(), width}); } if (perfect) *perfect = false; return std::sqrt(width * width + piece.length() * piece.length()); } if (position.start_lane() == position.end_lane()) { double radius = track_->LaneRadius(position.piece(), position.start_lane()); return 2.0 * M_PI * radius * (fabs(piece.angle()) / 360.0); } if (!piece.has_switch()) { std::cerr << "Changing lane on non switch piece?" << std::endl; } double radius1 = track_->LaneRadius(position.piece(), position.start_lane()); double radius2 = track_->LaneRadius(position.piece(), position.end_lane()); if (switch_on_turn_length_.count(std::make_tuple(radius1, radius2, fabs(piece.angle()))) > 0) { return switch_on_turn_length_.at(std::make_tuple(radius1, radius2, fabs(piece.angle()))); } if (perfect) *perfect = false; // The opposite switch is much better predictor if available if (switch_on_turn_length_.count(std::make_tuple(radius2, radius1, fabs(piece.angle()))) > 0) { return switch_on_turn_length_.at(std::make_tuple(radius2, radius1, fabs(piece.angle()))); } return M_PI * radius1 * (fabs(piece.angle()) / 360.0) + M_PI * radius2 * (fabs(piece.angle()) / 360.0); } void LaneLengthModel::Record(const Position& previous, const Position& current, double predicted_velocity) { if (previous.piece() == current.piece()) return; if (previous.start_lane() == previous.end_lane()) return; const auto& piece = track_->pieces()[previous.piece()]; double length = previous.piece_distance() + predicted_velocity - current.piece_distance(); if (piece.type() == PieceType::kStraight) { const double width = fabs(track_->lanes()[previous.start_lane()].distance_from_center() - track_->lanes()[previous.end_lane()].distance_from_center()); switch_on_straight_length_[{piece.length(), width}] = length; return; } double radius1 = track_->LaneRadius(previous.piece(), previous.start_lane()); double radius2 = track_->LaneRadius(previous.piece(), previous.end_lane()); switch_on_turn_length_[std::make_tuple(radius1, radius2, fabs(piece.angle()))] = length; } static jsoncons::json LoadCSV(const string& file_name) { std::ifstream file(file_name); if (!file.good()) { file.close(); return jsoncons::json(::jsoncons::json::an_array); } jsoncons::json_deserializer handler; jsoncons::json params; params["has_header"] = true; csv_reader reader(file, handler, params); reader.read(); jsoncons::json j = std::move(handler.root()); return j; } static double ToDouble(jsoncons::json data) { return std::strtod(data.as_string().c_str(), nullptr); } void LaneLengthModel::LoadSwitchLengths() { jsoncons::json straight_lengths = LoadCSV("data/switch-straight-lengths.csv"); for (auto it = straight_lengths.begin_elements(); it != straight_lengths.end_elements(); ++it) { const auto& data = *it; switch_on_straight_length_[{ToDouble(data["length"]), ToDouble(data["width"])}] = ToDouble(data["switch_length"]); } jsoncons::json turn_lengths = LoadCSV("data/switch-turn-lengths.csv"); for (auto it = turn_lengths.begin_elements(); it != turn_lengths.end_elements(); ++it) { const auto& data = *it; switch_on_turn_length_[std::make_tuple(ToDouble(data["start_radius"]), ToDouble(data["end_radius"]), ToDouble(data["angle"]))] = ToDouble(data["switch_length"]); } // Check if we are missing any data for current track. bool has_all = true; for (const auto& piece : track_->pieces()) { if (!piece.has_switch()) continue; if (piece.type() == PieceType::kStraight) { for (int i = 1; i < track_->lanes().size(); ++i) { double width = fabs(track_->lanes()[i].distance_from_center() - track_->lanes()[i - 1].distance_from_center()); if (switch_on_straight_length_.count({piece.length(), width}) == 0) { has_all = false; std::cout << "WARNING: Missing length for switch on straight with length " << piece.length() << " and width " << width << std::endl; } } } else { for (int i = 1; i < track_->lanes().size(); ++i) { double start_radius = piece.radius() + track_->lanes()[i - 1].distance_from_center(); double end_radius = piece.radius() + track_->lanes()[i].distance_from_center(); if (switch_on_turn_length_.count(std::make_tuple(start_radius, end_radius, fabs(piece.angle()))) == 0) { has_all = false; std::cout << "WARNING: Missing length for switch on turn start_radius: " << start_radius << " end_radius: " << end_radius << " angle: " << fabs(piece.angle()) << std::endl; } if (switch_on_turn_length_.count(std::make_tuple(end_radius, start_radius, fabs(piece.angle()))) == 0) { has_all = false; std::cout << "WARNING: Missing length for switch on turn start_radius: " << end_radius << " end_radius: " << start_radius << " angle: " << fabs(piece.angle()) << std::endl; } } } } if (has_all) { std::cout << "We have all switch lengths!" << std::endl; } } void LaneLengthModel::SaveSwitchLengths() { std::ofstream file("data/switch-straight-lengths.csv"); file << "length,width,switch_length" << std::endl; for (const auto& it : switch_on_straight_length_) { file << std::setprecision(20) << it.first.first << "," << it.first.second << "," << it.second << std::endl; } file.close(); file.open("data/switch-turn-lengths.csv"); file << "start_radius,end_radius,angle,switch_length" << std::endl; for (const auto& it : switch_on_turn_length_) { file << std::setprecision(20) << std::get<0>(it.first) << "," << std::get<1>(it.first) << "," << std::get<2>(it.first) << "," << it.second << std::endl; } file.close(); } } // namespace game <commit_msg>Do not change the memorized switch lengths<commit_after>#include <cstdlib> #include "game/lane_length_model.h" #include "gflags/gflags.h" #include "jsoncons_ext/csv/csv_reader.hpp" #include "jsoncons_ext/csv/csv_serializer.hpp" DECLARE_string(race_id); DECLARE_bool(print_models); DECLARE_bool(read_switch_models); DECLARE_bool(write_switch_models); using jsoncons_ext::csv::csv_reader; using jsoncons_ext::csv::csv_serializer; namespace game { LaneLengthModel::LaneLengthModel(const Track* track) : track_(track) { if (FLAGS_read_switch_models) { LoadSwitchLengths(); } } LaneLengthModel::~LaneLengthModel() { if (FLAGS_print_models) { std::cout << "==== Lane Length Model ====" << std::endl; std::cout << "Straight:" << std::endl; for (const auto& p : switch_on_straight_length_) { std::cout << "(" << p.first.first << "," << p.first.second << ") => " << p.second << std::endl; } std::cout << "Turn:" << std::endl; for (const auto& p : switch_on_turn_length_) { std::cout << "(" << std::get<0>(p.first) << "," << std::get<1>(p.first) << "," << std::get<2>(p.first) << ") => " << p.second << std::endl; } } if (FLAGS_write_switch_models) { SaveSwitchLengths(); } } double LaneLengthModel::Length(const Position& position, bool* perfect) const { if (perfect) *perfect = true; const auto& piece = track_->pieces()[position.piece()]; if (piece.type() == PieceType::kStraight) { if (position.start_lane() == position.end_lane()) { return piece.length(); } if (!piece.has_switch()) { std::cerr << "Changing lane on non switch piece?" << std::endl; } const double width = fabs(track_->lanes()[position.start_lane()].distance_from_center() - track_->lanes()[position.end_lane()].distance_from_center()); if (switch_on_straight_length_.count({piece.length(), width}) > 0) { return switch_on_straight_length_.at({piece.length(), width}); } if (perfect) *perfect = false; return std::sqrt(width * width + piece.length() * piece.length()); } if (position.start_lane() == position.end_lane()) { double radius = track_->LaneRadius(position.piece(), position.start_lane()); return 2.0 * M_PI * radius * (fabs(piece.angle()) / 360.0); } if (!piece.has_switch()) { std::cerr << "Changing lane on non switch piece?" << std::endl; } double radius1 = track_->LaneRadius(position.piece(), position.start_lane()); double radius2 = track_->LaneRadius(position.piece(), position.end_lane()); if (switch_on_turn_length_.count(std::make_tuple(radius1, radius2, fabs(piece.angle()))) > 0) { return switch_on_turn_length_.at(std::make_tuple(radius1, radius2, fabs(piece.angle()))); } if (perfect) *perfect = false; // The opposite switch is much better predictor if available if (switch_on_turn_length_.count(std::make_tuple(radius2, radius1, fabs(piece.angle()))) > 0) { return switch_on_turn_length_.at(std::make_tuple(radius2, radius1, fabs(piece.angle()))); } return M_PI * radius1 * (fabs(piece.angle()) / 360.0) + M_PI * radius2 * (fabs(piece.angle()) / 360.0); } void LaneLengthModel::Record(const Position& previous, const Position& current, double predicted_velocity) { if (previous.piece() == current.piece()) return; if (previous.start_lane() == previous.end_lane()) return; const auto& piece = track_->pieces()[previous.piece()]; double switch_length = previous.piece_distance() + predicted_velocity - current.piece_distance(); if (piece.type() == PieceType::kStraight) { const double width = fabs(track_->lanes()[previous.start_lane()].distance_from_center() - track_->lanes()[previous.end_lane()].distance_from_center()); auto it = switch_on_straight_length_.insert({{piece.length(), width}, switch_length}); if (fabs(it.first->second - switch_length) > 1e-6) { std::cerr << std::setprecision(8) << "ERROR: Memorized switch length (" << it.first->second << ") is different that calculated one (" << switch_length << ") for straight switch " << piece.length() << " " << width << std::endl; } return; } double radius1 = track_->LaneRadius(previous.piece(), previous.start_lane()); double radius2 = track_->LaneRadius(previous.piece(), previous.end_lane()); auto it = switch_on_turn_length_.insert( {std::make_tuple(radius1, radius2, fabs(piece.angle())), switch_length}); if (fabs(it.first->second - switch_length) > 1e-6) { std::cerr << std::setprecision(8) << "ERROR: Memorized switch length (" << it.first->second << ") is different that calculated one (" << switch_length << ") for turn switch " << radius1 << " " << radius2 << std::endl; } } static jsoncons::json LoadCSV(const string& file_name) { std::ifstream file(file_name); if (!file.good()) { file.close(); return jsoncons::json(::jsoncons::json::an_array); } jsoncons::json_deserializer handler; jsoncons::json params; params["has_header"] = true; csv_reader reader(file, handler, params); reader.read(); jsoncons::json j = std::move(handler.root()); return j; } static double ToDouble(jsoncons::json data) { return std::strtod(data.as_string().c_str(), nullptr); } void LaneLengthModel::LoadSwitchLengths() { jsoncons::json straight_lengths = LoadCSV("data/switch-straight-lengths.csv"); for (auto it = straight_lengths.begin_elements(); it != straight_lengths.end_elements(); ++it) { const auto& data = *it; switch_on_straight_length_[{ToDouble(data["length"]), ToDouble(data["width"])}] = ToDouble(data["switch_length"]); } jsoncons::json turn_lengths = LoadCSV("data/switch-turn-lengths.csv"); for (auto it = turn_lengths.begin_elements(); it != turn_lengths.end_elements(); ++it) { const auto& data = *it; switch_on_turn_length_[std::make_tuple(ToDouble(data["start_radius"]), ToDouble(data["end_radius"]), ToDouble(data["angle"]))] = ToDouble(data["switch_length"]); } // Check if we are missing any data for current track. bool has_all = true; for (const auto& piece : track_->pieces()) { if (!piece.has_switch()) continue; if (piece.type() == PieceType::kStraight) { for (int i = 1; i < track_->lanes().size(); ++i) { double width = fabs(track_->lanes()[i].distance_from_center() - track_->lanes()[i - 1].distance_from_center()); if (switch_on_straight_length_.count({piece.length(), width}) == 0) { has_all = false; std::cout << "WARNING: Missing length for switch on straight with length " << piece.length() << " and width " << width << std::endl; } } } else { for (int i = 1; i < track_->lanes().size(); ++i) { double start_radius = piece.radius() + track_->lanes()[i - 1].distance_from_center(); double end_radius = piece.radius() + track_->lanes()[i].distance_from_center(); if (switch_on_turn_length_.count(std::make_tuple(start_radius, end_radius, fabs(piece.angle()))) == 0) { has_all = false; std::cout << "WARNING: Missing length for switch on turn start_radius: " << start_radius << " end_radius: " << end_radius << " angle: " << fabs(piece.angle()) << std::endl; } if (switch_on_turn_length_.count(std::make_tuple(end_radius, start_radius, fabs(piece.angle()))) == 0) { has_all = false; std::cout << "WARNING: Missing length for switch on turn start_radius: " << end_radius << " end_radius: " << start_radius << " angle: " << fabs(piece.angle()) << std::endl; } } } } if (has_all) { std::cout << "We have all switch lengths!" << std::endl; } } void LaneLengthModel::SaveSwitchLengths() { std::ofstream file("data/switch-straight-lengths.csv"); file << "length,width,switch_length" << std::endl; for (const auto& it : switch_on_straight_length_) { file << std::setprecision(20) << it.first.first << "," << it.first.second << "," << it.second << std::endl; } file.close(); file.open("data/switch-turn-lengths.csv"); file << "start_radius,end_radius,angle,switch_length" << std::endl; for (const auto& it : switch_on_turn_length_) { file << std::setprecision(20) << std::get<0>(it.first) << "," << std::get<1>(it.first) << "," << std::get<2>(it.first) << "," << it.second << std::endl; } file.close(); } } // namespace game <|endoftext|>
<commit_before>/** \file SimpleXmlParser.cc * \brief A non-validating XML parser class. * \author Dr. Johannes Ruscheinski ([email protected]) * * \copyright 2015 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "SimpleXmlParser.h" #include <stdexcept> #include "Compiler.h" #include "StringUtil.h" #include "TextUtil.h" namespace { bool DecodeEnity(const std::string &entity_string, std::string * const decoded_char) { if (unlikely(entity_string.empty())) return false; if (unlikely(entity_string[0] == '#')) { if (entity_string.length() < 2) return false; unsigned code_point; if (entity_string[1] == 'x') { if (entity_string.length() < 3 or entity_string.length() > 6) return false; if (not StringUtil::ToUnsigned(entity_string.substr(2), &code_point, 16)) return false; } else { if (entity_string.length() < 2 or entity_string.length() > 6) return false; if (not StringUtil::ToUnsigned(entity_string.substr(1), &code_point)) return false; } if (not TextUtil::WCharToUTF8String(std::wstring(1, static_cast<wchar_t>(code_point)), decoded_char)) return false; } else if (entity_string == "quot") *decoded_char = "\""; else if (entity_string =="amp") *decoded_char = "&"; else if (entity_string =="apos") *decoded_char = "'"; else if (entity_string =="lt") *decoded_char = "<"; else if (entity_string =="gt") *decoded_char = ">"; else return false; return true; } inline bool DecodeEntities(const std::string &raw_string, std::string * const decoded_string) { bool in_entity(false); std::string entity; for (const auto ch : raw_string) { if (unlikely(in_entity)) { if (ch == ';') { std::string decoded_char; if (not DecodeEnity(entity, &decoded_char)) return false; *decoded_string += decoded_char; in_entity = false; } else entity += ch; } else if (unlikely(ch == '&')) { in_entity = true; entity.clear(); } else *decoded_string += ch; } return not in_entity; } } // unnamed namespace bool SimpleXmlParser::getNext(Type * const type, std::map<std::string, std::string> * const attrib_map, std::string * const data) { if (unlikely(last_type_ == ERROR)) throw std::runtime_error("in SimpleXmlParser::getNext: previous call already indicated an error!"); attrib_map->clear(); data->clear(); if (last_element_was_empty_) { last_type_ = *type = CLOSING_TAG; data->swap(last_tag_name_); last_element_was_empty_ = false; last_type_ = CLOSING_TAG; return true; } int ch; if (last_type_ == OPENING_TAG) { last_type_ = *type = CHARACTERS; std::string raw_string; while ((ch = input_->get()) != '<') { if (unlikely(ch == EOF)) { last_error_message_ = "Unexpected EOF while looking for the start of a closing tag!"; return false; } if (unlikely(ch == '\n')) ++line_no_; raw_string += static_cast<char>(ch); } input_->putback(ch); // Putting back the '<'. if (not DecodeEntities(raw_string, data)) { last_type_ = *type = ERROR; last_error_message_ = "Invalid entity in character data ending on line " + std::to_string(line_no_) + "!"; return false; } } else { // end-of-document or opening or closing tag skipWhiteSpace(); ch = input_->get(); if (unlikely(ch == EOF)) { last_type_ = *type = END_OF_DOCUMENT; return true; } if (ch != '<') { last_type_ = *type = ERROR; last_error_message_ = "Expected '<' on line " + std::to_string(line_no_) + ", found '" + std::string(1, static_cast<char>(ch)) + "' instead!"; return false; } // If we're at the beginning, we may have an XML prolog: if (unlikely(last_type_ == UNINITIALISED) and input_->peek() == '?') { if (not parseProlog()) { last_type_ = *type = ERROR; return false; } last_type_ = *type = START_OF_DOCUMENT; return true; } ch = input_->get(); if (ch == '/') { // A closing tag. if (unlikely(not parseClosingTag(data))) { last_type_ = *type = ERROR; last_error_message_ = "Error while parsing a closing tag on line " + std::to_string(line_no_) + "!"; return false; } last_type_ = *type = CLOSING_TAG; } else { // An opening tag. input_->putback(ch); std::string error_message; if (unlikely(not parseOpeningTag(data, attrib_map, &error_message))) { last_type_ = *type = ERROR; last_error_message_ = "Error while parsing an opening tag on line " + std::to_string(line_no_) + "! (" + error_message + ")"; return false; } ch = input_->get(); if (ch == '/') { last_element_was_empty_ = true; last_tag_name_ = *data; ch = input_->get(); } if (unlikely(ch != '>')) { last_type_ = *type = ERROR; last_error_message_ = "Error while parsing a opening tag on line " + std::to_string(line_no_) + "! (" "Closing angle bracket not found.)"; return false; } last_type_ = *type = OPENING_TAG; } } return true; } void SimpleXmlParser::skipWhiteSpace() { for (;;) { const int ch(input_->get()); if (unlikely(ch == EOF)) return; if (ch != ' ' and ch != '\t' and ch != '\n' and ch != '\r') { input_->putback(ch); return; } else if (ch == '\n') ++line_no_; } } bool SimpleXmlParser::extractName(std::string * const name) { name->clear(); int ch(input_->get()); if (unlikely(ch == EOF or (not StringUtil::IsAsciiLetter(ch) and ch != '_' and ch != ':'))) { input_->putback(ch); return false; } *name += static_cast<char>(ch); for (;;) { ch = input_->get(); if (unlikely(ch == EOF)) return false; if (not (StringUtil::IsAsciiLetter(ch) or StringUtil::IsDigit(ch) or ch == '_' or ch == ':' or ch == '.')) { input_->putback(ch); return true; } *name += static_cast<char>(ch); } } bool SimpleXmlParser::extractQuotedString(const int closing_quote, std::string * const s) { s->clear(); for (;;) { const int ch(input_->get()); if (unlikely(ch == EOF)) return false; if (unlikely(ch == closing_quote)) return true; *s += static_cast<char>(ch); } } bool SimpleXmlParser::parseProlog() { if (input_->peek() != '?') return true; input_->get(); std::string prolog_tag_name; std::map<std::string, std::string> prolog_attrib_map; std::string error_message; if (not parseOpeningTag(&prolog_tag_name, &prolog_attrib_map, &error_message)) { last_error_message_ = "Error in prolog! (" + error_message + ")"; return false; } int ch(input_->get()); if (unlikely(ch != '?')) { last_error_message_ = "Error in prolog, expected '?' but found '" + std::string(1, static_cast<char>(ch)) + "'!"; return false; } ch = input_->get(); if (unlikely(ch != '>')) { last_error_message_ = "Error in prolog, closing angle bracket not found!"; return false; } const auto encoding(prolog_attrib_map.find("encoding")); if (encoding != prolog_attrib_map.cend()) { if (::strcasecmp(encoding->second.c_str(), "utf-8") != 0) { last_error_message_ = "Error in prolog: We only support the UTF-8 encoding!"; return false; } } return true; } bool SimpleXmlParser::parseOpeningTag(std::string * const tag_name, std::map<std::string, std::string> * const attrib_map, std::string * const error_message) { attrib_map->clear(); error_message->clear(); if (unlikely(not extractName(tag_name))) { *error_message = "Failed to extract the tag name."; return false; } skipWhiteSpace(); std::string attrib_name; while (extractName(&attrib_name)) { if (unlikely(attrib_map->find(attrib_name) != attrib_map->cend())) { // Duplicate attribute name? *error_message = "Found a duplicate tag name."; return false; } skipWhiteSpace(); const int ch(input_->get()); if (unlikely(ch != '=')) { *error_message = "Could not find an equal sign as part of an attribute."; return false; } skipWhiteSpace(); const int quote(input_->get()); if (unlikely(quote != '"' and quote != '\'')) { *error_message = "Found neither a single- nor a double-quote starting an attribute value."; return false; } std::string attrib_value; if (unlikely(not extractQuotedString(quote, &attrib_value))) { *error_message = "Failed to extract the attribute value."; return false; } (*attrib_map)[attrib_name] = attrib_value; skipWhiteSpace(); } return true; } bool SimpleXmlParser::parseClosingTag(std::string * const tag_name) { tag_name->clear(); if (not extractName(tag_name)) return false; skipWhiteSpace(); return input_->get() == '>'; } std::string SimpleXmlParser::TypeToString(const Type type) { switch (type) { case UNINITIALISED: return "UNINITIALISED"; case START_OF_DOCUMENT: return "START_OF_DOCUMENT"; case END_OF_DOCUMENT: return "END_OF_DOCUMENT"; case ERROR: return "ERROR"; case OPENING_TAG: return "OPENING_TAG"; case CLOSING_TAG: return "CLOSING_TAG"; case CHARACTERS: return "CHARACTERS"; } __builtin_unreachable(); } <commit_msg>Further small speed improvements.<commit_after>/** \file SimpleXmlParser.cc * \brief A non-validating XML parser class. * \author Dr. Johannes Ruscheinski ([email protected]) * * \copyright 2015 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "SimpleXmlParser.h" #include <stdexcept> #include "Compiler.h" #include "StringUtil.h" #include "TextUtil.h" namespace { bool DecodeEnity(const std::string &entity_string, std::string * const decoded_char) { if (unlikely(entity_string.empty())) return false; if (unlikely(entity_string[0] == '#')) { if (entity_string.length() < 2) return false; unsigned code_point; if (entity_string[1] == 'x') { if (entity_string.length() < 3 or entity_string.length() > 6) return false; if (not StringUtil::ToUnsigned(entity_string.substr(2), &code_point, 16)) return false; } else { if (entity_string.length() < 2 or entity_string.length() > 6) return false; if (not StringUtil::ToUnsigned(entity_string.substr(1), &code_point)) return false; } if (not TextUtil::WCharToUTF8String(std::wstring(1, static_cast<wchar_t>(code_point)), decoded_char)) return false; } else if (entity_string == "quot") *decoded_char = "\""; else if (entity_string =="amp") *decoded_char = "&"; else if (entity_string =="apos") *decoded_char = "'"; else if (entity_string =="lt") *decoded_char = "<"; else if (entity_string =="gt") *decoded_char = ">"; else return false; return true; } inline bool DecodeEntities(const std::string &raw_string, std::string * const decoded_string) { bool in_entity(false); std::string entity; for (const auto ch : raw_string) { if (unlikely(in_entity)) { if (ch == ';') { std::string decoded_char; if (not DecodeEnity(entity, &decoded_char)) return false; *decoded_string += decoded_char; in_entity = false; } else entity += ch; } else if (unlikely(ch == '&')) { in_entity = true; entity.clear(); } else *decoded_string += ch; } return not in_entity; } } // unnamed namespace inline void SimpleXmlParser::skipWhiteSpace() { for (;;) { const int ch(input_->get()); if (unlikely(ch == EOF)) return; if (ch != ' ' and ch != '\t' and ch != '\n' and ch != '\r') { input_->putback(ch); return; } else if (ch == '\n') ++line_no_; } } inline bool SimpleXmlParser::extractName(std::string * const name) { name->clear(); int ch(input_->get()); if (unlikely(ch == EOF or (not StringUtil::IsAsciiLetter(ch) and ch != '_' and ch != ':'))) { input_->putback(ch); return false; } *name += static_cast<char>(ch); for (;;) { ch = input_->get(); if (unlikely(ch == EOF)) return false; if (not (StringUtil::IsAsciiLetter(ch) or StringUtil::IsDigit(ch) or ch == '_' or ch == ':' or ch == '.')) { input_->putback(ch); return true; } *name += static_cast<char>(ch); } } inline bool SimpleXmlParser::extractQuotedString(const int closing_quote, std::string * const s) { s->clear(); for (;;) { const int ch(input_->get()); if (unlikely(ch == EOF)) return false; if (unlikely(ch == closing_quote)) return true; *s += static_cast<char>(ch); } } bool SimpleXmlParser::getNext(Type * const type, std::map<std::string, std::string> * const attrib_map, std::string * const data) { if (unlikely(last_type_ == ERROR)) throw std::runtime_error("in SimpleXmlParser::getNext: previous call already indicated an error!"); attrib_map->clear(); data->clear(); if (last_element_was_empty_) { last_type_ = *type = CLOSING_TAG; data->swap(last_tag_name_); last_element_was_empty_ = false; last_type_ = CLOSING_TAG; return true; } int ch; if (last_type_ == OPENING_TAG) { last_type_ = *type = CHARACTERS; std::string raw_string; while ((ch = input_->get()) != '<') { if (unlikely(ch == EOF)) { last_error_message_ = "Unexpected EOF while looking for the start of a closing tag!"; return false; } if (unlikely(ch == '\n')) ++line_no_; raw_string += static_cast<char>(ch); } input_->putback(ch); // Putting back the '<'. if (not DecodeEntities(raw_string, data)) { last_type_ = *type = ERROR; last_error_message_ = "Invalid entity in character data ending on line " + std::to_string(line_no_) + "!"; return false; } } else { // end-of-document or opening or closing tag skipWhiteSpace(); ch = input_->get(); if (unlikely(ch == EOF)) { last_type_ = *type = END_OF_DOCUMENT; return true; } if (ch != '<') { last_type_ = *type = ERROR; last_error_message_ = "Expected '<' on line " + std::to_string(line_no_) + ", found '" + std::string(1, static_cast<char>(ch)) + "' instead!"; return false; } // If we're at the beginning, we may have an XML prolog: if (unlikely(last_type_ == UNINITIALISED) and input_->peek() == '?') { if (not parseProlog()) { last_type_ = *type = ERROR; return false; } last_type_ = *type = START_OF_DOCUMENT; return true; } ch = input_->get(); if (ch == '/') { // A closing tag. if (unlikely(not parseClosingTag(data))) { last_type_ = *type = ERROR; last_error_message_ = "Error while parsing a closing tag on line " + std::to_string(line_no_) + "!"; return false; } last_type_ = *type = CLOSING_TAG; } else { // An opening tag. input_->putback(ch); std::string error_message; if (unlikely(not parseOpeningTag(data, attrib_map, &error_message))) { last_type_ = *type = ERROR; last_error_message_ = "Error while parsing an opening tag on line " + std::to_string(line_no_) + "! (" + error_message + ")"; return false; } ch = input_->get(); if (ch == '/') { last_element_was_empty_ = true; last_tag_name_ = *data; ch = input_->get(); } if (unlikely(ch != '>')) { last_type_ = *type = ERROR; last_error_message_ = "Error while parsing a opening tag on line " + std::to_string(line_no_) + "! (" "Closing angle bracket not found.)"; return false; } last_type_ = *type = OPENING_TAG; } } return true; } bool SimpleXmlParser::parseProlog() { if (input_->peek() != '?') return true; input_->get(); std::string prolog_tag_name; std::map<std::string, std::string> prolog_attrib_map; std::string error_message; if (not parseOpeningTag(&prolog_tag_name, &prolog_attrib_map, &error_message)) { last_error_message_ = "Error in prolog! (" + error_message + ")"; return false; } int ch(input_->get()); if (unlikely(ch != '?')) { last_error_message_ = "Error in prolog, expected '?' but found '" + std::string(1, static_cast<char>(ch)) + "'!"; return false; } ch = input_->get(); if (unlikely(ch != '>')) { last_error_message_ = "Error in prolog, closing angle bracket not found!"; return false; } const auto encoding(prolog_attrib_map.find("encoding")); if (encoding != prolog_attrib_map.cend()) { if (::strcasecmp(encoding->second.c_str(), "utf-8") != 0) { last_error_message_ = "Error in prolog: We only support the UTF-8 encoding!"; return false; } } return true; } bool SimpleXmlParser::parseOpeningTag(std::string * const tag_name, std::map<std::string, std::string> * const attrib_map, std::string * const error_message) { attrib_map->clear(); error_message->clear(); if (unlikely(not extractName(tag_name))) { *error_message = "Failed to extract the tag name."; return false; } skipWhiteSpace(); std::string attrib_name; while (extractName(&attrib_name)) { if (unlikely(attrib_map->find(attrib_name) != attrib_map->cend())) { // Duplicate attribute name? *error_message = "Found a duplicate tag name."; return false; } skipWhiteSpace(); const int ch(input_->get()); if (unlikely(ch != '=')) { *error_message = "Could not find an equal sign as part of an attribute."; return false; } skipWhiteSpace(); const int quote(input_->get()); if (unlikely(quote != '"' and quote != '\'')) { *error_message = "Found neither a single- nor a double-quote starting an attribute value."; return false; } std::string attrib_value; if (unlikely(not extractQuotedString(quote, &attrib_value))) { *error_message = "Failed to extract the attribute value."; return false; } (*attrib_map)[attrib_name] = attrib_value; skipWhiteSpace(); } return true; } bool SimpleXmlParser::parseClosingTag(std::string * const tag_name) { tag_name->clear(); if (not extractName(tag_name)) return false; skipWhiteSpace(); return input_->get() == '>'; } std::string SimpleXmlParser::TypeToString(const Type type) { switch (type) { case UNINITIALISED: return "UNINITIALISED"; case START_OF_DOCUMENT: return "START_OF_DOCUMENT"; case END_OF_DOCUMENT: return "END_OF_DOCUMENT"; case ERROR: return "ERROR"; case OPENING_TAG: return "OPENING_TAG"; case CLOSING_TAG: return "CLOSING_TAG"; case CHARACTERS: return "CHARACTERS"; } __builtin_unreachable(); } <|endoftext|>
<commit_before>// ========================================================================== // // This file is part of Sara, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2013-2016 David Ok <[email protected]> // // 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/. // ========================================================================== // //! @file #ifdef _WIN32 # include <windows.h> #else # include <sys/time.h> #endif #include <DO/Sara/Core/Timer.hpp> namespace DO { namespace Sara { Timer::Timer() { #ifdef _WIN32 LARGE_INTEGER freq; if (!QueryPerformanceFrequency(&freq)) { auto msg = "Failed to initialize high resolution timer!"; throw std::runtime_error{msg}; } _frequency = static_cast<double>(freq.QuadPart); #endif restart(); } void Timer::restart() { #ifdef _WIN32 LARGE_INTEGER _li_start; QueryPerformanceCounter(&_li_start); _start = static_cast<double>(_li_start.QuadPart); #else timeval start; gettimeofday(&start, NULL); _start = start.tv_sec + start.tv_usec * 1e-6; #endif } double Timer::elapsed() { #ifdef _WIN32 LARGE_INTEGER _end; QueryPerformanceCounter(&_end); return (static_cast<double>(_end.QuadPart) - _start) / _frequency; #else timeval end; gettimeofday(&end, NULL); double _end = end.tv_sec + end.tv_usec * 1e-6; return _end - _start; #endif } double Timer::elapsed_ms() { return elapsed() * 1000.; } } /* namespace Sara */ } /* namespace DO */ <commit_msg>MAINT: fix compile errors for GitLab CI.<commit_after>// ========================================================================== // // This file is part of Sara, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2013-2016 David Ok <[email protected]> // // 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/. // ========================================================================== // //! @file #ifdef _WIN32 # include <windows.h> #else # include <sys/time.h> #endif #include <DO/Sara/Core/Timer.hpp> namespace DO { namespace Sara { Timer::Timer() { #ifdef _WIN32 LARGE_INTEGER freq; if (!QueryPerformanceFrequency(&freq)) { auto msg = "Failed to initialize high resolution timer!"; throw std::runtime_error{msg}; } _frequency = static_cast<double>(freq.QuadPart); #endif restart(); } void Timer::restart() { #ifdef _WIN32 LARGE_INTEGER _li_start; QueryPerformanceCounter(&_li_start); _start = static_cast<double>(_li_start.QuadPart); #else timeval start; gettimeofday(&start, nullptr); _start = start.tv_sec + start.tv_usec * 1e-6; #endif } double Timer::elapsed() { #ifdef _WIN32 LARGE_INTEGER _end; QueryPerformanceCounter(&_end); return (static_cast<double>(_end.QuadPart) - _start) / _frequency; #else timeval end; gettimeofday(&end, NULL); double _end = end.tv_sec + end.tv_usec * 1e-6; return _end - _start; #endif } double Timer::elapsed_ms() { return elapsed() * 1000.; } } /* namespace Sara */ } /* namespace DO */ <|endoftext|>
<commit_before>#ifdef HAS_WCSLIB #include "../../include/frame/WCSTransformation.h" #include "../../include/utils/IO.h" #include "../../include/utils/MathHelper.h" #include <wcslib/wcshdr.h> #include <wcslib/wcsfix.h> #include <wcslib/wcs.h> #include <iostream> #include <iomanip> namespace shapelens { WCSTransformation::WCSTransformation(fitsfile* fptr, bool intermediate_) : intermediate(intermediate_) { int status = 0, nkeyrec, nreject, nwcs; char *header; // Read in the FITS header, excluding COMMENT and HISTORY keyrecords. if (fits_hdr2str(fptr, 1, NULL, 0, &header, &nkeyrec, &status)) { throw std::runtime_error("WCSTransformation: Cannot read header of file ");// + IO::getFITSFileName(fptr)); } // Interpret the WCS keywords struct wcsprm* wcss; // use pointer to read multiple wcs structs if necessary status = wcspih(header, nkeyrec, WCSHDR_all, 0, &nreject, &nwcs, &wcss); free(header); if (status) throw std::runtime_error("WCSTransformation: Cannot read WCS header keywords (" + std::string(wcshdr_errmsg[status]) + ")"); // check there is one (and one only) WCS with 2 coordinate axes if (wcss == NULL) { throw std::runtime_error("WCSTransformation: No world coordinate systems found in ");// + IO::getFITSFileName(fptr)); } else if (nwcs > 1) { wcsvfree(&nwcs, &wcss); throw std::runtime_error("WCSTransformation: More than one world coordinate systems found in ");// + IO::getFITSFileName(fptr)); } else if (wcss->naxis != 2) { wcsvfree(&nwcs, &wcss); throw std::runtime_error("WCSTransformation: WCS does not have 2 axes in ");// + IO::getFITSFileName(fptr)); } // initialize this wcs structure and copy it from first (and only) // entry of wcss wcs.flag = -1; // wcslib implementation detail wcsini(1, 2, &wcs); // 1: allocate memory for 2: axes wcscopy(0, wcss, &wcs); status = wcsset(&wcs); // set remaining wcs fields from read information wcsvfree(&nwcs, &wcss); // free the read-in structure if (status) throw std::runtime_error("WCSTransformation: wcsset error (");// + std::string(wcs_errmsg[status]) + ")"); // initialize coordinate containers world = (double*) realloc(NULL, 2 * sizeof(double)); imgcrd = (double*) realloc(NULL, 2 * sizeof(double)); pixcrd = (double*) realloc(NULL, 2 * sizeof(double)); stat = (int*) realloc(NULL, 2 * sizeof(int)); // since wcslib does not deal with SIP distortions, we have to read // the distortion coefficients if present std::string ctype1; IO::readFITSKeywordString(fptr, "CTYPE1", ctype1); if (ctype1.find("TAN-SIP") != std::string::npos) { has_sip = true; std::ostringstream key; int A_order, B_order; IO::readFITSKeyword(fptr, "A_ORDER", A_order); IO::readFITSKeyword(fptr, "B_ORDER", B_order); A = NumMatrix<data_t>(A_order+1, A_order+1); B = NumMatrix<data_t>(B_order+1, B_order+1); for (int i=0; i <= A_order; i++) { for (int j=0; j <= A_order; j++) { key.str(""); key << "A_" << i << "_" << j; try { // not all coefficients need to be present IO::readFITSKeyword(fptr, key.str(), A(i,j)); } catch (std::invalid_argument) {} } } for (int i=0; i <= B_order; i++) { for (int j=0; j <= B_order; j++) { key.str(""); key << "B_" << i << "_" << j; try { IO::readFITSKeyword(fptr, key.str(), B(i,j)); } catch (std::invalid_argument) {} } } IO::readFITSKeyword(fptr, "CRPIX1", crpix1); IO::readFITSKeyword(fptr, "CRPIX2", crpix2); } //else has_sip = false; } // explicit definition since we have to allocate containers // and perform a deep copy of wcs WCSTransformation::WCSTransformation(const WCSTransformation& W) { world = (double*) realloc(NULL, 2 * sizeof(double)); imgcrd = (double*) realloc(NULL, 2 * sizeof(double)); pixcrd = (double*) realloc(NULL, 2 * sizeof(double)); stat = (int*) realloc(NULL, 2 * sizeof(int)); wcs.flag = -1; wcsini(1, 2, &wcs); wcscopy(0, &(W.wcs), &wcs); wcsset(&wcs); intermediate = W.intermediate; has_sip = W.has_sip; A = W.A; B = W.B; crpix1 = W.crpix1; crpix2 = W.crpix2; } // explicit definition to deallocate all structures WCSTransformation::~WCSTransformation() { int nwcs = 1; wcsfree(&wcs); free(world); free(imgcrd); free(pixcrd); free(stat); } data_t WCSTransformation::sip_polynomial(const NumMatrix<data_t>& M, data_t& u, data_t& v) const { data_t f = 0; for (int i=0; i < M.getRows(); i++) for (int j=0; j < M.getColumns(); j++) f += M(i,j) * pow_int(u,i) * pow_int(v,j); return f; } void WCSTransformation::f(Point<data_t>& P) const { // apply sip transform if necessary if (has_sip) { double u = P(0) - crpix1, v = P(1) - crpix2; double f = sip_polynomial(A,u,v), g = sip_polynomial(B, u, v); *pixcrd = u + f + crpix1; *(pixcrd+1) = v + g + crpix2; } else { *pixcrd = P(0); *(pixcrd+1) = P(1); } // use intermediate world coordinates // rather then celestial if (intermediate) { linp2x(const_cast<linprm*>(&(wcs.lin)), 1, 2, pixcrd, imgcrd); P(0) = *imgcrd; P(1) = *(imgcrd+1); } else { double phi, theta; wcsp2s(const_cast<wcsprm*>(&wcs), 1, 2, pixcrd, imgcrd, &phi, &theta, world, stat); P(0) = *world; P(1) = *(world+1); } stack_transform(P); } void WCSTransformation::f_1(Point<data_t>& P) const { // inverse: this trafo comes last stack_inverse_transform(P); // use intermediate world coordinates (as input) // rather than celestial if (intermediate) { *imgcrd = P(0); *(imgcrd+1) = P(1); linx2p(const_cast<linprm*>(&(wcs.lin)), 1, 2, imgcrd, pixcrd); } else { *world = P(0); *(world+1) = P(1); double phi, theta; wcss2p (const_cast<wcsprm*>(&wcs), 1, 2, world, &phi, &theta, imgcrd, pixcrd, stat); } P(0) = (*pixcrd); P(1) = *(pixcrd+1); // need to invert non-linear SIP distortion if necessary if (has_sip) { data_t u, u_, u__, v, v_, v__; u = u_ = P(0) - crpix1; v = v_ = P(1) - crpix2; do { // simple solver, assumes distortion to be small u__ = u; v__ = v; u = u_ - sip_polynomial(A, u, v); v = v_ - sip_polynomial(B, u, v); } while (fabs(u - u__) > 1e-2 || fabs(v - v__) >1e-2); P(0) = u + crpix1; P(1) = v + crpix2; } } boost::shared_ptr<CoordinateTransformation> WCSTransformation::clone() const { return boost::shared_ptr<CoordinateTransformation>(new WCSTransformation(*this)); } } // end namespace #endif // HAS_WCSLIB <commit_msg>bugfix<commit_after>#ifdef HAS_WCSLIB #include "../../include/frame/WCSTransformation.h" #include "../../include/utils/IO.h" #include "../../include/utils/MathHelper.h" #include <wcslib/wcshdr.h> #include <wcslib/wcsfix.h> #include <wcslib/wcs.h> #include <iostream> #include <iomanip> namespace shapelens { WCSTransformation::WCSTransformation(fitsfile* fptr, bool intermediate_) : intermediate(intermediate_) { int status = 0, nkeyrec, nreject, nwcs; char *header; // Read in the FITS header, excluding COMMENT and HISTORY keyrecords. if (fits_hdr2str(fptr, 1, NULL, 0, &header, &nkeyrec, &status)) { throw std::runtime_error("WCSTransformation: Cannot read header of file ");// + IO::getFITSFileName(fptr)); } // Interpret the WCS keywords struct wcsprm* wcss; // use pointer to read multiple wcs structs if necessary status = wcspih(header, nkeyrec, WCSHDR_all, 0, &nreject, &nwcs, &wcss); free(header); if (status) throw std::runtime_error("WCSTransformation: Cannot read WCS header keywords (" + std::string(wcshdr_errmsg[status]) + ")"); // check there is one (and one only) WCS with 2 coordinate axes if (wcss == NULL) { throw std::runtime_error("WCSTransformation: No world coordinate systems found in ");// + IO::getFITSFileName(fptr)); } else if (nwcs > 1) { wcsvfree(&nwcs, &wcss); throw std::runtime_error("WCSTransformation: More than one world coordinate systems found in ");// + IO::getFITSFileName(fptr)); } else if (wcss->naxis != 2) { wcsvfree(&nwcs, &wcss); throw std::runtime_error("WCSTransformation: WCS does not have 2 axes in ");// + IO::getFITSFileName(fptr)); } // initialize this wcs structure and copy it from first (and only) // entry of wcss wcs.flag = -1; // wcslib implementation detail wcsini(1, 2, &wcs); // 1: allocate memory for 2: axes wcscopy(0, wcss, &wcs); status = wcsset(&wcs); // set remaining wcs fields from read information wcsvfree(&nwcs, &wcss); // free the read-in structure if (status) throw std::runtime_error("WCSTransformation: wcsset error (");// + std::string(wcs_errmsg[status]) + ")"); // initialize coordinate containers world = (double*) realloc(NULL, 2 * sizeof(double)); imgcrd = (double*) realloc(NULL, 2 * sizeof(double)); pixcrd = (double*) realloc(NULL, 2 * sizeof(double)); stat = (int*) realloc(NULL, 2 * sizeof(int)); // since wcslib does not deal with SIP distortions, we have to read // the distortion coefficients if present std::string ctype1; IO::readFITSKeywordString(fptr, "CTYPE1", ctype1); if (ctype1.find("TAN-SIP") != std::string::npos) { has_sip = true; std::ostringstream key; int A_order, B_order; IO::readFITSKeyword(fptr, "A_ORDER", A_order); IO::readFITSKeyword(fptr, "B_ORDER", B_order); A = NumMatrix<data_t>(A_order+1, A_order+1); B = NumMatrix<data_t>(B_order+1, B_order+1); for (int i=0; i <= A_order; i++) { for (int j=0; j <= A_order; j++) { key.str(""); key << "A_" << i << "_" << j; try { // not all coefficients need to be present IO::readFITSKeyword(fptr, key.str(), A(i,j)); } catch (std::invalid_argument) {} } } for (int i=0; i <= B_order; i++) { for (int j=0; j <= B_order; j++) { key.str(""); key << "B_" << i << "_" << j; try { IO::readFITSKeyword(fptr, key.str(), B(i,j)); } catch (std::invalid_argument) {} } } IO::readFITSKeyword(fptr, "CRPIX1", crpix1); IO::readFITSKeyword(fptr, "CRPIX2", crpix2); } else has_sip = false; } // explicit definition since we have to allocate containers // and perform a deep copy of wcs WCSTransformation::WCSTransformation(const WCSTransformation& W) { world = (double*) realloc(NULL, 2 * sizeof(double)); imgcrd = (double*) realloc(NULL, 2 * sizeof(double)); pixcrd = (double*) realloc(NULL, 2 * sizeof(double)); stat = (int*) realloc(NULL, 2 * sizeof(int)); wcs.flag = -1; wcsini(1, 2, &wcs); wcscopy(0, &(W.wcs), &wcs); wcsset(&wcs); intermediate = W.intermediate; has_sip = W.has_sip; A = W.A; B = W.B; crpix1 = W.crpix1; crpix2 = W.crpix2; } // explicit definition to deallocate all structures WCSTransformation::~WCSTransformation() { int nwcs = 1; wcsfree(&wcs); free(world); free(imgcrd); free(pixcrd); free(stat); } data_t WCSTransformation::sip_polynomial(const NumMatrix<data_t>& M, data_t& u, data_t& v) const { data_t f = 0; for (int i=0; i < M.getRows(); i++) for (int j=0; j < M.getColumns(); j++) f += M(i,j) * pow_int(u,i) * pow_int(v,j); return f; } void WCSTransformation::f(Point<data_t>& P) const { // apply sip transform if necessary if (has_sip) { double u = P(0) - crpix1, v = P(1) - crpix2; double f = sip_polynomial(A,u,v), g = sip_polynomial(B, u, v); *pixcrd = u + f + crpix1; *(pixcrd+1) = v + g + crpix2; } else { *pixcrd = P(0); *(pixcrd+1) = P(1); } // use intermediate world coordinates // rather then celestial if (intermediate) { linp2x(const_cast<linprm*>(&(wcs.lin)), 1, 2, pixcrd, imgcrd); P(0) = *imgcrd; P(1) = *(imgcrd+1); } else { double phi, theta; wcsp2s(const_cast<wcsprm*>(&wcs), 1, 2, pixcrd, imgcrd, &phi, &theta, world, stat); P(0) = *world; P(1) = *(world+1); } stack_transform(P); } void WCSTransformation::f_1(Point<data_t>& P) const { // inverse: this trafo comes last stack_inverse_transform(P); // use intermediate world coordinates (as input) // rather than celestial if (intermediate) { *imgcrd = P(0); *(imgcrd+1) = P(1); linx2p(const_cast<linprm*>(&(wcs.lin)), 1, 2, imgcrd, pixcrd); } else { *world = P(0); *(world+1) = P(1); double phi, theta; wcss2p (const_cast<wcsprm*>(&wcs), 1, 2, world, &phi, &theta, imgcrd, pixcrd, stat); } P(0) = (*pixcrd); P(1) = *(pixcrd+1); // need to invert non-linear SIP distortion if necessary if (has_sip) { data_t u, u_, u__, v, v_, v__; u = u_ = P(0) - crpix1; v = v_ = P(1) - crpix2; do { // simple solver, assumes distortion to be small u__ = u; v__ = v; u = u_ - sip_polynomial(A, u, v); v = v_ - sip_polynomial(B, u, v); } while (fabs(u - u__) > 1e-2 || fabs(v - v__) >1e-2); P(0) = u + crpix1; P(1) = v + crpix2; } } boost::shared_ptr<CoordinateTransformation> WCSTransformation::clone() const { return boost::shared_ptr<CoordinateTransformation>(new WCSTransformation(*this)); } } // end namespace #endif // HAS_WCSLIB <|endoftext|>
<commit_before>#include "i_render.h" #include "renderable_repo.h" #include "sprite_collection.h" #include "platform\filesystem_utils.h" RenderableRepo::RenderableRepo() : RepoBase( mDefaultRenderable ) { Init(); } void RenderableRepo::Init() { ElementMap_t Renderables; fs_utils::for_each( "actors", ".sprite", [&]( Json::Value const& desc, boost::filesystem::path const& path ) { std::string PathStr; auto const& ActorVisuals = desc["actor_visuals"]; if (!ActorVisuals.isArray()) { return; } if (!Json::GetStr( desc["texture_path"], PathStr )) { return; } bool isAbsolute = PathStr.size() > 1 && (PathStr.substr( 0, 2 ) == ":/" || PathStr.substr( 0, 2 ) == ":\\"); boost::filesystem::path newPath; if (!isAbsolute) { L2( "Path is not absolute %s, %s\n", path.generic_string().c_str(), PathStr.c_str() ); newPath = path.parent_path() / PathStr; } else { newPath = boost::filesystem::path( PathStr.substr( 2 ) ); L2( "Path is absolute %s\n", newPath.generic_string().c_str() ); } int32_t TexId = AutoId( newPath.generic_string() ); for (auto&& ActorVisualDesc : ActorVisuals) { if (!ActorVisualDesc.isObject()) { return; } std::auto_ptr<SpriteCollection> Renderable( new SpriteCollection ); if (!Renderable->Load( TexId, ActorVisualDesc )) { return; } int32_t Id = Renderable->Id(); ElementMap_t::iterator It = Renderables.find( Id ); if (It == Renderables.end()) { Renderables.insert( Id, Renderable.release() ); } else { It->second->Merge( *Renderable ); } } } ); for( auto i = Renderables.begin(), e = Renderables.end(); i != e; ++i ) { auto const& spriteColl = *i->second; float max = 0.0f; for( auto ii = spriteColl.begin(), ee = spriteColl.end(); ii != ee; ++ii) { if( max < ii->second->GetScale() ) { max = ii->second->GetScale(); } } mMaxScaleMap[i->first] = max; } // all done using std::swap; swap( mElements, Renderables ); } float RenderableRepo::GetMaxScale( int32_t actorId ) const { auto it = mMaxScaleMap.find( actorId ); return it == mMaxScaleMap.end() ? 1.0 : it->second; } <commit_msg>compile fix<commit_after>#include "i_render.h" #include "renderable_repo.h" #include "sprite_collection.h" #include "platform/filesystem_utils.h" RenderableRepo::RenderableRepo() : RepoBase( mDefaultRenderable ) { Init(); } void RenderableRepo::Init() { ElementMap_t Renderables; fs_utils::for_each( "actors", ".sprite", [&]( Json::Value const& desc, boost::filesystem::path const& path ) { std::string PathStr; auto const& ActorVisuals = desc["actor_visuals"]; if (!ActorVisuals.isArray()) { return; } if (!Json::GetStr( desc["texture_path"], PathStr )) { return; } bool isAbsolute = PathStr.size() > 1 && (PathStr.substr( 0, 2 ) == ":/" || PathStr.substr( 0, 2 ) == ":\\"); boost::filesystem::path newPath; if (!isAbsolute) { L2( "Path is not absolute %s, %s\n", path.generic_string().c_str(), PathStr.c_str() ); newPath = path.parent_path() / PathStr; } else { newPath = boost::filesystem::path( PathStr.substr( 2 ) ); L2( "Path is absolute %s\n", newPath.generic_string().c_str() ); } int32_t TexId = AutoId( newPath.generic_string() ); for (auto&& ActorVisualDesc : ActorVisuals) { if (!ActorVisualDesc.isObject()) { return; } std::auto_ptr<SpriteCollection> Renderable( new SpriteCollection ); if (!Renderable->Load( TexId, ActorVisualDesc )) { return; } int32_t Id = Renderable->Id(); ElementMap_t::iterator It = Renderables.find( Id ); if (It == Renderables.end()) { Renderables.insert( Id, Renderable.release() ); } else { It->second->Merge( *Renderable ); } } } ); for( auto i = Renderables.begin(), e = Renderables.end(); i != e; ++i ) { auto const& spriteColl = *i->second; float max = 0.0f; for( auto ii = spriteColl.begin(), ee = spriteColl.end(); ii != ee; ++ii) { if( max < ii->second->GetScale() ) { max = ii->second->GetScale(); } } mMaxScaleMap[i->first] = max; } // all done using std::swap; swap( mElements, Renderables ); } float RenderableRepo::GetMaxScale( int32_t actorId ) const { auto it = mMaxScaleMap.find( actorId ); return it == mMaxScaleMap.end() ? 1.0 : it->second; } <|endoftext|>
<commit_before>/* * quickXPlain.cpp * * Created on: 22.03.2015 * Author: Benjamin Musitsch */ #include "QuickXPlain.h" #include "Solver.h" #include <string> // Calculates the preferred conflict out of a number of conflicting literals using the QuickXplain algorithm // Used for debugging INCOHERENT programs // debugLiterals ... vector of IDs from literals (_debug literals) // returns the preferred conflict (vector of literal IDs) vector< unsigned int > QuickXPlain::quickXPlain(vector< unsigned int > debugLiterals) { trace_msg (debug, 0, "Start quickXPlain"); vector< unsigned int > empty; if ( debugLiterals.empty() ) { trace_msg (debug, 0, "No conflicting literals"); return empty; } else return quickXPlainIntern(0, empty, empty, debugLiterals); } // Calculation of the preferred conflict // level ... current level in the algorithm // toCheck ... current part of conflict to be checked (see QXP Paper - Background) // addedToCheck ... conflict added to toCheck in the last step (see QXP Paper - Delta) // toSplit ... not considered conlicts (see QXP Paper - Constraints) // return (part of a) preferred conflict vector< unsigned int > QuickXPlain::quickXPlainIntern(int level, vector< unsigned int > toCheck, vector< unsigned int > addedToCheck, vector< unsigned int > toSplit) { // empty vector to return vector< unsigned int > empty; // vector for both half of the splittet vector toSplit vector< unsigned int > firstHalf; vector< unsigned int > secondHalf; // partial results vector< unsigned int > result1; vector< unsigned int > result2; // result vector< unsigned int > result; trace_msg( debug, level+1, "QXP lvl " << level << " with " << vectorToString(toCheck) << " to check (added " << vectorToString(addedToCheck) << ") and " << vectorToString(toSplit) << " not checked"); // assembly assumption for the next check vector< Literal > assumptionsAND; vector< Literal > assumptionsOR; for (unsigned int i = 0; i < toCheck.size(); i++) { assumptionsAND.push_back( Literal( toCheck[i]) ); } if ( addedToCheck.empty() && solveAndClearWithAssumptions(assumptionsAND, assumptionsOR) == INCOHERENT) { trace_msg( debug, level+1, "QXP lvl " << level << ": nothing to check and INCOHERENT -> prune"); return empty; } else if ( toSplit.size() == 1 ) { trace_msg( debug, level+1, "QXP lvl " << level << ": only " << toSplit.front() << " left -> add to preferred conflict"); return toSplit; } else { // split vector and calculate partial results vectorSplit(toSplit, firstHalf, secondHalf); trace_msg( debug, level+1, "QXP lvl " << level << ": split " << vectorToString(toSplit) << " into " << vectorToString(firstHalf) << " and " << vectorToString(secondHalf) ); // first partial result result2 = quickXPlainIntern(level + 1, vectorAdd(toCheck, firstHalf), firstHalf, secondHalf); trace_msg (debug, level+1, "QXP lvl " << level << ": first result is " << vectorToString(result2)); // second partial result result1 = quickXPlainIntern(level + 1, vectorAdd(toCheck, result2), result2, firstHalf); trace_msg (debug, level+1, "QXP lvl " << level << ": second result is " << vectorToString(result1)); result = vectorAdd(result1, result2); trace_msg (debug, level+1, "QXP lvl " << level << ": add " << vectorToString(result) << " to preferred conflict"); return result; } } // split the given vector in two equal sized parts // used in quickXPlainIntern // toSplit ... vector to split // v1 ... first half of the vector // v2 ... second half of the vector void QuickXPlain::vectorSplit(vector< unsigned int > toSplit, vector< unsigned int >& v1, vector< unsigned int >& v2) { unsigned int splitAt = (toSplit.size() + 2 - 1) / 2; for (unsigned int i = 0; i < splitAt; i++) v1.push_back(toSplit[i]); for (unsigned int i = splitAt; i < toSplit.size(); i++) v2.push_back(toSplit[i]); } // combines the two given vectors into one (no duplicated elements) // v1 ... the first vector // v2 ... the second vector vector< unsigned int > QuickXPlain::vectorAdd(vector< unsigned int > v1, vector< unsigned int > v2) { std::vector<unsigned int>::iterator it; for (unsigned int i = 0; i < v2.size(); i++) { it = find(v1.begin(), v1.end(), v2[i]); if (it == v1.end()) v1.push_back(v2[i]); } return v1; } // constructs a string of the given vector (form: [ element_1 | ... | element_n ]) // v ... the vector // returns the vector as string string QuickXPlain::vectorToString(vector < unsigned int > v) { string s = "["; if (!v.empty()) { s += " " + std::to_string((unsigned int)v.at(0)); for (unsigned int i = 1; i < v.size(); i++) s += " | " + std::to_string((unsigned int)v.at(i)); } s += " ]"; return s; } // solve the program (with the given assumptions) using the solver instance from the constructor // unrolls and clears the conflict status afterwards unsigned int QuickXPlain::solveAndClearWithAssumptions(vector< Literal >& assumptionsAND, vector< Literal >& assumptionsOR) { unsigned int result = solver.solve(assumptionsAND, assumptionsOR); solver.unrollToZero(); solver.clearConflictStatus(); return result; } <commit_msg>Fixed bug in QuickXPlain<commit_after>/* * quickXPlain.cpp * * Created on: 22.03.2015 * Author: Benjamin Musitsch */ #include "QuickXPlain.h" #include "Solver.h" #include <string> // Calculates the preferred conflict out of a number of conflicting literals using the QuickXplain algorithm // Used for debugging INCOHERENT programs // debugLiterals ... vector of IDs from literals (_debug literals) // returns the preferred conflict (vector of literal IDs) vector< unsigned int > QuickXPlain::quickXPlain(vector< unsigned int > debugLiterals) { trace_msg (debug, 0, "Start quickXPlain"); vector< unsigned int > empty; if ( debugLiterals.empty() ) { trace_msg (debug, 0, "No conflicting literals"); return empty; } else return quickXPlainIntern(0, empty, empty, debugLiterals); } // Calculation of the preferred conflict // level ... current level in the algorithm // toCheck ... current part of conflict to be checked (see QXP Paper - Background) // addedToCheck ... conflict added to toCheck in the last step (see QXP Paper - Delta) // toSplit ... not considered conlicts (see QXP Paper - Constraints) // return (part of a) preferred conflict vector< unsigned int > QuickXPlain::quickXPlainIntern(int level, vector< unsigned int > toCheck, vector< unsigned int > addedToCheck, vector< unsigned int > toSplit) { // empty vector to return vector< unsigned int > empty; // vector for both half of the splittet vector toSplit vector< unsigned int > firstHalf; vector< unsigned int > secondHalf; // partial results vector< unsigned int > result1; vector< unsigned int > result2; // result vector< unsigned int > result; trace_msg( debug, level+1, "QXP lvl " << level << " with " << vectorToString(toCheck) << " to check (added " << vectorToString(addedToCheck) << ") and " << vectorToString(toSplit) << " not checked"); // assembly assumption for the next check vector< Literal > assumptionsAND; vector< Literal > assumptionsOR; for (unsigned int i = 0; i < toCheck.size(); i++) { assumptionsAND.push_back( Literal( toCheck[i]) ); } if ( !addedToCheck.empty() && solveAndClearWithAssumptions(assumptionsAND, assumptionsOR) == INCOHERENT) { trace_msg( debug, level+1, "QXP lvl " << level << ": nothing to check and INCOHERENT for " << vectorToString(toCheck) << " -> prune"); return empty; } else if ( toSplit.size() == 1 ) { trace_msg( debug, level+1, "QXP lvl " << level << ": only " << toSplit.front() << " left -> add to preferred conflict"); return toSplit; } else { // split vector and calculate partial results vectorSplit(toSplit, firstHalf, secondHalf); trace_msg( debug, level+1, "QXP lvl " << level << ": split " << vectorToString(toSplit) << " into " << vectorToString(firstHalf) << " and " << vectorToString(secondHalf) ); // first partial result result2 = quickXPlainIntern(level + 1, vectorAdd(toCheck, firstHalf), firstHalf, secondHalf); trace_msg (debug, level+1, "QXP lvl " << level << ": first result is " << vectorToString(result2)); // second partial result result1 = quickXPlainIntern(level + 1, vectorAdd(toCheck, result2), result2, firstHalf); trace_msg (debug, level+1, "QXP lvl " << level << ": second result is " << vectorToString(result1)); result = vectorAdd(result1, result2); trace_msg (debug, level+1, "QXP lvl " << level << ": add " << vectorToString(result) << " to preferred conflict"); return result; } } // split the given vector in two equal sized parts // used in quickXPlainIntern // toSplit ... vector to split // v1 ... first half of the vector // v2 ... second half of the vector void QuickXPlain::vectorSplit(vector< unsigned int > toSplit, vector< unsigned int >& v1, vector< unsigned int >& v2) { unsigned int splitAt = (toSplit.size() + 2 - 1) / 2; for (unsigned int i = 0; i < splitAt; i++) v1.push_back(toSplit[i]); for (unsigned int i = splitAt; i < toSplit.size(); i++) v2.push_back(toSplit[i]); } // combines the two given vectors into one (no duplicated elements) // v1 ... the first vector // v2 ... the second vector vector< unsigned int > QuickXPlain::vectorAdd(vector< unsigned int > v1, vector< unsigned int > v2) { std::vector<unsigned int>::iterator it; for (unsigned int i = 0; i < v2.size(); i++) { it = find(v1.begin(), v1.end(), v2[i]); if (it == v1.end()) v1.push_back(v2[i]); } return v1; } // constructs a string of the given vector (form: [ element_1 | ... | element_n ]) // v ... the vector // returns the vector as string string QuickXPlain::vectorToString(vector < unsigned int > v) { string s = "["; if (!v.empty()) { s += " " + std::to_string((unsigned int)v.at(0)); for (unsigned int i = 1; i < v.size(); i++) s += " | " + std::to_string((unsigned int)v.at(i)); } s += " ]"; return s; } // solve the program (with the given assumptions) using the solver instance from the constructor // unrolls and clears the conflict status afterwards unsigned int QuickXPlain::solveAndClearWithAssumptions(vector< Literal >& assumptionsAND, vector< Literal >& assumptionsOR) { unsigned int result = solver.solve(assumptionsAND, assumptionsOR); solver.unrollToZero(); solver.clearConflictStatus(); return result; } <|endoftext|>
<commit_before>#include "catch.hpp" #include "util.h" #include <shl_exception.h> #include <grammar_compiler.h> using namespace shl; TEST_CASE("GrammarCompiler Test") { string data = load_string("fixture/valid.json"); GrammarCompiler compiler; Grammar g = compiler.compile(data); compiler.resolve_include(g, nullptr); // do not check external grammar include here SECTION("can load a valid grammar") { REQUIRE(g.desc == "C"); REQUIRE(g.file_types.size() == 2); REQUIRE(g.name == "source.c"); REQUIRE(g.repository.size() == 3); REQUIRE(g.repository["preprocessor-rule-enabled"].begin.source() == "^\\s*(#(if)\\s+(0*1)\\b)"); } SECTION("can load an enclosing rule") { REQUIRE(g.repository.find("hello") != g.repository.end()); auto object = g.repository["hello"]; REQUIRE(object.patterns.size() == 1); REQUIRE(object.patterns[0].patterns.size() == 2); } SECTION("captures can be regard as begin_captures if is a begin/end rule and has no begin_captures") { REQUIRE(g.repository["preprocessor-rule-enabled"].begin_captures.size() == 3); REQUIRE(g.repository["preprocessor-rule-enabled"].begin_captures[2] == "keyword.control.import.if.c"); } SECTION("captures can be regard as end_captures if is a begin/end rule and has no end_captures") { REQUIRE(g.repository["preprocessor-rule-enabled"].end_captures.size() == 3); REQUIRE(g.repository["preprocessor-rule-enabled"].end_captures[2] == "keyword.control.import.if.c"); } SECTION("match rule merged with begin, and captures merge with begin_captures") { REQUIRE(g.repository["string_escaped_char"].patterns[1].begin.source() == "\\\\."); REQUIRE(g.patterns[1].begin_captures.size() == 1); REQUIRE(g.patterns[1].begin.source() == "\""); REQUIRE(g.repository["preprocessor-rule-enabled"].begin.source() == "^\\s*(#(if)\\s+(0*1)\\b)"); REQUIRE(g.repository["preprocessor-rule-enabled"].begin_captures.size() == 3); } SECTION("can resolve includes") { REQUIRE(g.patterns[0].include.ptr == &g.repository["preprocessor-rule-enabled"]); REQUIRE(g.patterns[1].patterns[0].include.ptr == &g.repository["string_escaped_char"]); REQUIRE(g.patterns[1].patterns[1].include.ptr == &g); REQUIRE(g.patterns[1].patterns[2].include.ptr == nullptr); REQUIRE(g.patterns[1].patterns[2].include.is_base_ref == true); REQUIRE(g.repository["preprocessor-rule-enabled"].patterns[0].patterns[0].include.ptr == &g); REQUIRE(g.repository["preprocessor-rule-enabled"].patterns[0].patterns[1].include.ptr == &g.repository["string_escaped_char"]); REQUIRE(g.repository["preprocessor-rule-enabled"].patterns[1].patterns[0].include.ptr == nullptr); REQUIRE(g.repository["preprocessor-rule-enabled"].patterns[1].patterns[0].include.is_base_ref == true); REQUIRE(g.repository["hello"].patterns[0].patterns[0].include.ptr == &g.repository["preprocessor-rule-enabled"]); REQUIRE(g.repository["hello"].patterns[0].patterns[1].include.ptr == &g.repository["hello"]); } SECTION("will throw if encounter a external grammar include but GrammarRegister is not set") { string data = load_string("fixture/ruby.json"); GrammarCompiler compiler; Grammar g = compiler.compile(data); REQUIRE_THROWS_AS( compiler.resolve_include(g, nullptr), ShlException); } } <commit_msg>add testing for php grammar<commit_after>#include "catch.hpp" #include "util.h" #include <shl_exception.h> #include <grammar_compiler.h> using namespace shl; TEST_CASE("GrammarCompiler Test") { string data = load_string("fixture/valid.json"); GrammarCompiler compiler; Grammar g = compiler.compile(data); compiler.resolve_include(g, nullptr); // do not check external grammar include here SECTION("can load a valid grammar") { REQUIRE(g.desc == "C"); REQUIRE(g.file_types.size() == 2); REQUIRE(g.name == "source.c"); REQUIRE(g.repository.size() == 3); REQUIRE(g.repository["preprocessor-rule-enabled"].begin.source() == "^\\s*(#(if)\\s+(0*1)\\b)"); } SECTION("can load an enclosing rule") { REQUIRE(g.repository.find("hello") != g.repository.end()); auto object = g.repository["hello"]; REQUIRE(object.patterns.size() == 1); REQUIRE(object.patterns[0].patterns.size() == 2); } SECTION("captures can be regard as begin_captures if is a begin/end rule and has no begin_captures") { REQUIRE(g.repository["preprocessor-rule-enabled"].begin_captures.size() == 3); REQUIRE(g.repository["preprocessor-rule-enabled"].begin_captures[2] == "keyword.control.import.if.c"); } SECTION("captures can be regard as end_captures if is a begin/end rule and has no end_captures") { REQUIRE(g.repository["preprocessor-rule-enabled"].end_captures.size() == 3); REQUIRE(g.repository["preprocessor-rule-enabled"].end_captures[2] == "keyword.control.import.if.c"); } SECTION("match rule merged with begin, and captures merge with begin_captures") { REQUIRE(g.repository["string_escaped_char"].patterns[1].begin.source() == "\\\\."); REQUIRE(g.patterns[1].begin_captures.size() == 1); REQUIRE(g.patterns[1].begin.source() == "\""); REQUIRE(g.repository["preprocessor-rule-enabled"].begin.source() == "^\\s*(#(if)\\s+(0*1)\\b)"); REQUIRE(g.repository["preprocessor-rule-enabled"].begin_captures.size() == 3); } SECTION("can resolve includes") { REQUIRE(g.patterns[0].include.ptr == &g.repository["preprocessor-rule-enabled"]); REQUIRE(g.patterns[1].patterns[0].include.ptr == &g.repository["string_escaped_char"]); REQUIRE(g.patterns[1].patterns[1].include.ptr == &g); REQUIRE(g.patterns[1].patterns[2].include.ptr == nullptr); REQUIRE(g.patterns[1].patterns[2].include.is_base_ref == true); REQUIRE(g.repository["preprocessor-rule-enabled"].patterns[0].patterns[0].include.ptr == &g); REQUIRE(g.repository["preprocessor-rule-enabled"].patterns[0].patterns[1].include.ptr == &g.repository["string_escaped_char"]); REQUIRE(g.repository["preprocessor-rule-enabled"].patterns[1].patterns[0].include.ptr == nullptr); REQUIRE(g.repository["preprocessor-rule-enabled"].patterns[1].patterns[0].include.is_base_ref == true); REQUIRE(g.repository["hello"].patterns[0].patterns[0].include.ptr == &g.repository["preprocessor-rule-enabled"]); REQUIRE(g.repository["hello"].patterns[0].patterns[1].include.ptr == &g.repository["hello"]); } SECTION("will throw if encounter a external grammar include but GrammarRegister is not set") { string data = load_string("fixture/ruby.json"); GrammarCompiler compiler; Grammar g = compiler.compile(data); REQUIRE_THROWS_AS( compiler.resolve_include(g, nullptr), ShlException); } SECTION("will load the injection rule") { string data = load_string("fixture/php.json"); GrammarCompiler compiler; Grammar g = compiler.compile(data); compiler.resolve_include(g, nullptr); // do not check external grammar include here REQUIRE( g.injections.size() == 1 ); } } <|endoftext|>
<commit_before>#include "replication/backfill_in.hpp" #ifndef NDEBUG // We really shouldn't include this from here (the dependencies are // backwards), but we need it for // master_t::inside_backfill_done_or_backfill. #include "replication/master.hpp" #endif template<class value_t> std::vector<value_t> make_vector(value_t v1) { std::vector<value_t> vec; vec.push_back(v1); return vec; } template<class value_t> std::vector<value_t> make_vector(value_t v1, value_t v2) { std::vector<value_t> vec; vec.push_back(v1); vec.push_back(v2); return vec; } namespace replication { // Stats for the current depth of realtime and backfill queues. // The `replication_slave_realtime_queue` stat is mentioned in the manual, so if // you change it, be sure to update the manual as well. perfmon_counter_t pm_replication_slave_realtime_queue("replication_slave_realtime_queue", false), pm_replication_slave_backfill_queue("replication_slave_backfill_queue"); // Stats for how long it takes to push something onto the queue (it should be // very fast unless the queue is backed up) perfmon_duration_sampler_t pm_replication_slave_realtime_enqueue("replication_slave_realtime_enqueue", secs_to_ticks(1.0)), pm_replication_slave_backfill_enqueue("replication_slave_backfill_enqueue", secs_to_ticks(1.0)); #define BACKFILL_QUEUE_CAPACITY 2048 #define REALTIME_QUEUE_CAPACITY 2048 #define CORO_POOL_SIZE 512 backfill_storer_t::backfill_storer_t(btree_key_value_store_t *underlying) : kvs_(underlying), backfilling_(false), print_backfill_warning_(false), backfill_queue_(BACKFILL_QUEUE_CAPACITY), realtime_queue_(SEMAPHORE_NO_LIMIT, 0.5, &pm_replication_slave_realtime_queue), queue_picker_(make_vector<passive_producer_t<boost::function<void()> > *>(&backfill_queue_)), coro_pool_(CORO_POOL_SIZE, &queue_picker_) { } backfill_storer_t::~backfill_storer_t() { if (print_backfill_warning_) { logWRN("A backfill operation is being interrupted. The data in this database is now " "in an inconsistent state. To get the data back into a consistent state, " "reestablish the master-slave connection and allow the backfill to run to " "completion.\n"); } } void backfill_storer_t::ensure_backfilling() { if (!backfilling_) { // Make sure that realtime operations are not processed until we finish // backfilling // In order to do that, we first drain all realtime operations that are // still lingering around (is it possible at all that there are any?). // Then we set the queue_picker_ to only take requests from the backfill queue. coro_pool_.drain(); queue_picker_.set_sources(make_vector<passive_producer_t<boost::function<void()> > *>(&backfill_queue_)); } backfilling_ = true; } void backfill_storer_t::backfill_delete_everything(order_token_t token) { print_backfill_warning_ = true; ensure_backfilling(); block_pm_duration timer(&pm_replication_slave_backfill_enqueue); backfill_queue_.push(boost::bind(&btree_key_value_store_t::delete_all_keys_for_backfill, kvs_, token)); } void backfill_storer_t::backfill_deletion(store_key_t key, order_token_t token) { print_backfill_warning_ = true; ensure_backfilling(); delete_mutation_t mut; mut.key = key; mut.dont_put_in_delete_queue = true; block_pm_duration timer(&pm_replication_slave_backfill_enqueue); backfill_queue_.push(boost::bind( &btree_key_value_store_t::change, kvs_, mut, // NO_CAS_SUPPLIED is not used in any way for deletions, and the // timestamp is part of the "->change" interface in a way not // relevant to slaves -- it's used when putting deletions into the // delete queue. castime_t(NO_CAS_SUPPLIED, repli_timestamp::invalid), token )); } void backfill_storer_t::backfill_set(backfill_atom_t atom, order_token_t token) { print_backfill_warning_ = true; ensure_backfilling(); sarc_mutation_t mut; mut.key = atom.key; mut.data = atom.value; mut.flags = atom.flags; mut.exptime = atom.exptime; mut.add_policy = add_policy_yes; mut.replace_policy = replace_policy_yes; mut.old_cas = NO_CAS_SUPPLIED; block_pm_duration timer(&pm_replication_slave_backfill_enqueue); backfill_queue_.push(boost::bind( &btree_key_value_store_t::change, kvs_, mut, castime_t(atom.cas_or_zero, atom.recency), token )); if (atom.cas_or_zero != 0) { /* We need to make sure that the key gets assigned a CAS, because it has a CAS on the other node. If the key did not have a CAS before we sent "mut", then it will still lack a CAS after we send "mut", so we also send "cas_mut" to force it to have a CAS. Since we send "atom.cas_or_zero" as the "proposed_cas" for "cas_mut", the CAS will be correct. If the key had a CAS before we sent "mut", then "mut" will set the CAS to the correct value, and "cas_mut" will be a noop. */ get_cas_mutation_t cas_mut; cas_mut.key = mut.key; block_pm_duration timer(&pm_replication_slave_backfill_enqueue); backfill_queue_.push(boost::bind( &btree_key_value_store_t::change, kvs_, cas_mut, castime_t(atom.cas_or_zero, atom.recency), token)); } } void backfill_storer_t::backfill_done(repli_timestamp_t timestamp, order_token_t token) { #ifndef NDEBUG rassert(!master_t::inside_backfill_done_or_backfill); master_t::inside_backfill_done_or_backfill = true; #endif /* Call ensure_backfilling() a last time just to make sure that the queue_picker_ is set up correctly (i.e. does not process the realtime queue yet). Otherwise draining the coro_pool as we do below wouldn't work as expected. */ ensure_backfilling(); print_backfill_warning_ = false; backfilling_ = false; backfill_queue_.push(boost::bind( &btree_key_value_store_t::set_timestampers, kvs_, timestamp)); /* Write replication clock before timestamp so that if the flush happens between them, we will redo the backfill instead of proceeding with a wrong replication clock. */ backfill_queue_.push(boost::bind(&btree_key_value_store_t::set_replication_clock, kvs_, timestamp, token)); backfill_queue_.push(boost::bind(&btree_key_value_store_t::set_last_sync, kvs_, timestamp, token)); /* We want the realtime queue to accept operations without throttling until the backfill is over, and then to start throttling. To make sure that we start throttling right when the realtime queue actually starts draining, we make the final operation on the backfilling queue be the operation that enables throttling on the realtime queue. */ backfill_queue_.push(boost::bind( &limited_fifo_queue_t<boost::function<void()> >::set_capacity, &realtime_queue_, REALTIME_QUEUE_CAPACITY)); // We need to make sure all the backfill queue operations are finished // before we return, before the net_backfill_t handler gets // called. // As we are sure that queue_picker_ does only fetch requests from the backfill // queue at the moment (see call to ensure_backfilling() above), we can do that // by draining the coro pool which processes the requests. // Note: This does not allow any new requests to get in on the backfill queue // while draining, but that should be ok. // TODO: The cleaner way of implementing this semantics would be to pass // a lock object with each operation we push on the backfill_queue. That lock's // lifespan would be until the corresponding operation finishes. We would then // wait until all the locks have been released. coro_pool_.drain(); /* Allow the `listing_passive_producer_t` to run operations from the `realtime_queue_` once the `backfill_queue_` is empty (which it actually should be anyway by now). */ queue_picker_.set_sources( make_vector<passive_producer_t<boost::function<void()> > *>( &backfill_queue_, &realtime_queue_)); #ifndef NDEBUG master_t::inside_backfill_done_or_backfill = false; #endif } void backfill_storer_t::realtime_get_cas(const store_key_t& key, castime_t castime, order_token_t token) { get_cas_mutation_t mut; mut.key = key; block_pm_duration timer(&pm_replication_slave_realtime_enqueue); realtime_queue_.push(boost::bind(&btree_key_value_store_t::change, kvs_, mut, castime, token)); } void backfill_storer_t::realtime_sarc(sarc_mutation_t& m, castime_t castime, order_token_t token) { block_pm_duration timer(&pm_replication_slave_realtime_enqueue); realtime_queue_.push(boost::bind(&btree_key_value_store_t::change, kvs_, m, castime, token)); } void backfill_storer_t::realtime_incr_decr(incr_decr_kind_t kind, const store_key_t &key, uint64_t amount, castime_t castime, order_token_t token) { incr_decr_mutation_t mut; mut.key = key; mut.kind = kind; mut.amount = amount; block_pm_duration timer(&pm_replication_slave_realtime_enqueue); realtime_queue_.push(boost::bind(&btree_key_value_store_t::change, kvs_, mut, castime, token)); } void backfill_storer_t::realtime_append_prepend(append_prepend_kind_t kind, const store_key_t &key, unique_ptr_t<data_provider_t> data, castime_t castime, order_token_t token) { append_prepend_mutation_t mut; mut.key = key; mut.data = data; mut.kind = kind; block_pm_duration timer(&pm_replication_slave_realtime_enqueue); realtime_queue_.push(boost::bind(&btree_key_value_store_t::change, kvs_, mut, castime, token)); } void backfill_storer_t::realtime_delete_key(const store_key_t &key, repli_timestamp timestamp, order_token_t token) { delete_mutation_t mut; mut.key = key; mut.dont_put_in_delete_queue = true; block_pm_duration timer(&pm_replication_slave_realtime_enqueue); realtime_queue_.push(boost::bind( &btree_key_value_store_t::change, kvs_, mut, // TODO: where does "timestamp" go??? IS THIS RIGHT?? WHO KNOWS. castime_t(NO_CAS_SUPPLIED /* This isn't even used, why is it a parameter. */, timestamp), token )); } void backfill_storer_t::realtime_time_barrier(repli_timestamp_t timestamp, order_token_t token) { /* Write the replication clock before writing `last_sync` so that if we crash between them, we'll re-sync that second instead of proceeding with a wrong replication clock. There is no need to change the timestamper because there are no sets being sent to this node; the master is still up. */ block_pm_duration timer(&pm_replication_slave_realtime_enqueue); realtime_queue_.push(boost::bind(&btree_key_value_store_t::set_replication_clock, kvs_, timestamp, token)); realtime_queue_.push(boost::bind(&btree_key_value_store_t::set_last_sync, kvs_, timestamp, token)); } } <commit_msg>Added debugfs around drain operations in backfill_storer_t.<commit_after>#include "replication/backfill_in.hpp" #ifndef NDEBUG // We really shouldn't include this from here (the dependencies are // backwards), but we need it for // master_t::inside_backfill_done_or_backfill. #include "replication/master.hpp" #endif template<class value_t> std::vector<value_t> make_vector(value_t v1) { std::vector<value_t> vec; vec.push_back(v1); return vec; } template<class value_t> std::vector<value_t> make_vector(value_t v1, value_t v2) { std::vector<value_t> vec; vec.push_back(v1); vec.push_back(v2); return vec; } namespace replication { // Stats for the current depth of realtime and backfill queues. // The `replication_slave_realtime_queue` stat is mentioned in the manual, so if // you change it, be sure to update the manual as well. perfmon_counter_t pm_replication_slave_realtime_queue("replication_slave_realtime_queue", false), pm_replication_slave_backfill_queue("replication_slave_backfill_queue"); // Stats for how long it takes to push something onto the queue (it should be // very fast unless the queue is backed up) perfmon_duration_sampler_t pm_replication_slave_realtime_enqueue("replication_slave_realtime_enqueue", secs_to_ticks(1.0)), pm_replication_slave_backfill_enqueue("replication_slave_backfill_enqueue", secs_to_ticks(1.0)); #define BACKFILL_QUEUE_CAPACITY 2048 #define REALTIME_QUEUE_CAPACITY 2048 #define CORO_POOL_SIZE 512 backfill_storer_t::backfill_storer_t(btree_key_value_store_t *underlying) : kvs_(underlying), backfilling_(false), print_backfill_warning_(false), backfill_queue_(BACKFILL_QUEUE_CAPACITY), realtime_queue_(SEMAPHORE_NO_LIMIT, 0.5, &pm_replication_slave_realtime_queue), queue_picker_(make_vector<passive_producer_t<boost::function<void()> > *>(&backfill_queue_)), coro_pool_(CORO_POOL_SIZE, &queue_picker_) { } backfill_storer_t::~backfill_storer_t() { if (print_backfill_warning_) { logWRN("A backfill operation is being interrupted. The data in this database is now " "in an inconsistent state. To get the data back into a consistent state, " "reestablish the master-slave connection and allow the backfill to run to " "completion.\n"); } } void backfill_storer_t::ensure_backfilling() { if (!backfilling_) { // Make sure that realtime operations are not processed until we finish // backfilling // In order to do that, we first drain all realtime operations that are // still lingering around (is it possible at all that there are any?). // Then we set the queue_picker_ to only take requests from the backfill queue. debugf("backfill_storer_t: Draining coro_pool_ for realtime operations to finish.\n"); coro_pool_.drain(); debugf("backfill_storer_t: DONE Draining coro_pool_ for realtime operations to finish.\n"); queue_picker_.set_sources(make_vector<passive_producer_t<boost::function<void()> > *>(&backfill_queue_)); } backfilling_ = true; } void backfill_storer_t::backfill_delete_everything(order_token_t token) { print_backfill_warning_ = true; ensure_backfilling(); block_pm_duration timer(&pm_replication_slave_backfill_enqueue); backfill_queue_.push(boost::bind(&btree_key_value_store_t::delete_all_keys_for_backfill, kvs_, token)); } void backfill_storer_t::backfill_deletion(store_key_t key, order_token_t token) { print_backfill_warning_ = true; ensure_backfilling(); delete_mutation_t mut; mut.key = key; mut.dont_put_in_delete_queue = true; block_pm_duration timer(&pm_replication_slave_backfill_enqueue); backfill_queue_.push(boost::bind( &btree_key_value_store_t::change, kvs_, mut, // NO_CAS_SUPPLIED is not used in any way for deletions, and the // timestamp is part of the "->change" interface in a way not // relevant to slaves -- it's used when putting deletions into the // delete queue. castime_t(NO_CAS_SUPPLIED, repli_timestamp::invalid), token )); } void backfill_storer_t::backfill_set(backfill_atom_t atom, order_token_t token) { print_backfill_warning_ = true; ensure_backfilling(); sarc_mutation_t mut; mut.key = atom.key; mut.data = atom.value; mut.flags = atom.flags; mut.exptime = atom.exptime; mut.add_policy = add_policy_yes; mut.replace_policy = replace_policy_yes; mut.old_cas = NO_CAS_SUPPLIED; block_pm_duration timer(&pm_replication_slave_backfill_enqueue); backfill_queue_.push(boost::bind( &btree_key_value_store_t::change, kvs_, mut, castime_t(atom.cas_or_zero, atom.recency), token )); if (atom.cas_or_zero != 0) { /* We need to make sure that the key gets assigned a CAS, because it has a CAS on the other node. If the key did not have a CAS before we sent "mut", then it will still lack a CAS after we send "mut", so we also send "cas_mut" to force it to have a CAS. Since we send "atom.cas_or_zero" as the "proposed_cas" for "cas_mut", the CAS will be correct. If the key had a CAS before we sent "mut", then "mut" will set the CAS to the correct value, and "cas_mut" will be a noop. */ get_cas_mutation_t cas_mut; cas_mut.key = mut.key; block_pm_duration timer(&pm_replication_slave_backfill_enqueue); backfill_queue_.push(boost::bind( &btree_key_value_store_t::change, kvs_, cas_mut, castime_t(atom.cas_or_zero, atom.recency), token)); } } void backfill_storer_t::backfill_done(repli_timestamp_t timestamp, order_token_t token) { #ifndef NDEBUG rassert(!master_t::inside_backfill_done_or_backfill); master_t::inside_backfill_done_or_backfill = true; #endif /* Call ensure_backfilling() a last time just to make sure that the queue_picker_ is set up correctly (i.e. does not process the realtime queue yet). Otherwise draining the coro_pool as we do below wouldn't work as expected. */ ensure_backfilling(); print_backfill_warning_ = false; backfilling_ = false; backfill_queue_.push(boost::bind( &btree_key_value_store_t::set_timestampers, kvs_, timestamp)); /* Write replication clock before timestamp so that if the flush happens between them, we will redo the backfill instead of proceeding with a wrong replication clock. */ backfill_queue_.push(boost::bind(&btree_key_value_store_t::set_replication_clock, kvs_, timestamp, token)); backfill_queue_.push(boost::bind(&btree_key_value_store_t::set_last_sync, kvs_, timestamp, token)); /* We want the realtime queue to accept operations without throttling until the backfill is over, and then to start throttling. To make sure that we start throttling right when the realtime queue actually starts draining, we make the final operation on the backfilling queue be the operation that enables throttling on the realtime queue. */ backfill_queue_.push(boost::bind( &limited_fifo_queue_t<boost::function<void()> >::set_capacity, &realtime_queue_, REALTIME_QUEUE_CAPACITY)); // We need to make sure all the backfill queue operations are finished // before we return, before the net_backfill_t handler gets // called. // As we are sure that queue_picker_ does only fetch requests from the backfill // queue at the moment (see call to ensure_backfilling() above), we can do that // by draining the coro pool which processes the requests. // Note: This does not allow any new requests to get in on the backfill queue // while draining, but that should be ok. // TODO: The cleaner way of implementing this semantics would be to pass // a lock object with each operation we push on the backfill_queue. That lock's // lifespan would be until the corresponding operation finishes. We would then // wait until all the locks have been released. debugf("backfill_storer_t: Draining coro_pool_ to make sure that backfill operations finish.\n"); coro_pool_.drain(); debugf("backfill_storer_t: DONE Draining coro_pool_ to make sure that backfill operations finish.\n"); /* Allow the `listing_passive_producer_t` to run operations from the `realtime_queue_` once the `backfill_queue_` is empty (which it actually should be anyway by now). */ queue_picker_.set_sources( make_vector<passive_producer_t<boost::function<void()> > *>( &backfill_queue_, &realtime_queue_)); #ifndef NDEBUG master_t::inside_backfill_done_or_backfill = false; #endif } void backfill_storer_t::realtime_get_cas(const store_key_t& key, castime_t castime, order_token_t token) { get_cas_mutation_t mut; mut.key = key; block_pm_duration timer(&pm_replication_slave_realtime_enqueue); realtime_queue_.push(boost::bind(&btree_key_value_store_t::change, kvs_, mut, castime, token)); } void backfill_storer_t::realtime_sarc(sarc_mutation_t& m, castime_t castime, order_token_t token) { block_pm_duration timer(&pm_replication_slave_realtime_enqueue); realtime_queue_.push(boost::bind(&btree_key_value_store_t::change, kvs_, m, castime, token)); } void backfill_storer_t::realtime_incr_decr(incr_decr_kind_t kind, const store_key_t &key, uint64_t amount, castime_t castime, order_token_t token) { incr_decr_mutation_t mut; mut.key = key; mut.kind = kind; mut.amount = amount; block_pm_duration timer(&pm_replication_slave_realtime_enqueue); realtime_queue_.push(boost::bind(&btree_key_value_store_t::change, kvs_, mut, castime, token)); } void backfill_storer_t::realtime_append_prepend(append_prepend_kind_t kind, const store_key_t &key, unique_ptr_t<data_provider_t> data, castime_t castime, order_token_t token) { append_prepend_mutation_t mut; mut.key = key; mut.data = data; mut.kind = kind; block_pm_duration timer(&pm_replication_slave_realtime_enqueue); realtime_queue_.push(boost::bind(&btree_key_value_store_t::change, kvs_, mut, castime, token)); } void backfill_storer_t::realtime_delete_key(const store_key_t &key, repli_timestamp timestamp, order_token_t token) { delete_mutation_t mut; mut.key = key; mut.dont_put_in_delete_queue = true; block_pm_duration timer(&pm_replication_slave_realtime_enqueue); realtime_queue_.push(boost::bind( &btree_key_value_store_t::change, kvs_, mut, // TODO: where does "timestamp" go??? IS THIS RIGHT?? WHO KNOWS. castime_t(NO_CAS_SUPPLIED /* This isn't even used, why is it a parameter. */, timestamp), token )); } void backfill_storer_t::realtime_time_barrier(repli_timestamp_t timestamp, order_token_t token) { /* Write the replication clock before writing `last_sync` so that if we crash between them, we'll re-sync that second instead of proceeding with a wrong replication clock. There is no need to change the timestamper because there are no sets being sent to this node; the master is still up. */ block_pm_duration timer(&pm_replication_slave_realtime_enqueue); realtime_queue_.push(boost::bind(&btree_key_value_store_t::set_replication_clock, kvs_, timestamp, token)); realtime_queue_.push(boost::bind(&btree_key_value_store_t::set_last_sync, kvs_, timestamp, token)); } } <|endoftext|>
<commit_before>/** * \file StatusFrame.cpp * \brief Main Windows Class */ #include "StatusFrame.h" BEGIN_EVENT_TABLE(StatusFrame,wxFrame) EVT_MENU(ID_NEWSTATUS, StatusFrame::NewStatusWindow) EVT_MENU(ID_NEWGRAPH, StatusFrame::NewGraphWindow) EVT_MENU(-1, StatusFrame::SelectDevice) EVT_CLOSE(StatusFrame::OnClose) END_EVENT_TABLE() /** Constructor for the Main frame. */ StatusFrame::StatusFrame(wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style) : wxFrame(parent, id, title, position, size, style) { deviceId = "Please select a device from the menu."; CreateGUIControls(); } /** Destructor for the Main form. */ StatusFrame::~StatusFrame() { } /** Updates the GUI with new database information */ void StatusFrame::Update() { wxMenuBar *menubar = new wxMenuBar; wxMenu *devices = new wxMenu; wxMenu *view = new wxMenu; deviceIds = DB_getAllDevices(); menubar->Append(devices, wxT("&Devices")); for(unsigned int i = 0; i < deviceIds.size(); i++) { devices->Append(10000+i, deviceIds[i]); } menubar->Append(view, wxT("&View")); view->Append(ID_NEWSTATUS, "New Status Window"); view->Append(ID_NEWGRAPH, "New Graph Window"); SetMenuBar(menubar); map<string, string> gps_info; gps_info = DB_getMostRecentGPS(atoi(deviceId.c_str())); wxString info = wxString::Format(wxT("" "<body bgcolor=black text=white>" "<b>Device: <font color=#33ff33>%s</font></b>\n" "<hr>\n" "<b>Location</b>\n<br />" "Latitude: <font color=#33ff33>%s</font>\n<br />" "Longitude: <font color=#33ff33>%s</font>\n<br />" "Altitude (M): <font color=#33ff33>%s</font>\n<br />" "Altitude (Ft): <font color=#33ff33>%s</font>\n<br />" "Speed (Knots): <font color=#33ff33>%s</font>\n<br />" "Speed (M/S): <font color=#33ff33>%s</font>\n<br />" "Bearing: <font color=#33ff33>%s</font>\n<br />" "Climb: <font color=#33ff33>%s</font>\n<br />" "GPS Status: <font color=#33ff33>%s</font>\n" "\n<hr>" "<b>Status</b>\n<br />" "Battery 1 (V): \n<br />" "Battery 2 (V): \n<br />" "Buss (V): \n<br />" "Signal (%%): \n<br />" "Temperature Int. (c): \n<br />" "Temperature Ext. (c): \n<br />" "Pressure (HPA): \n<br />" "RH (%%): \n" "</body>" ), deviceId.c_str(), gps_info["Latitude"].c_str(), gps_info["Longitude"].c_str(), gps_info["Altitude_m"].c_str(), gps_info["Altitude_ft"].c_str(), gps_info["Spd_knots"].c_str(), gps_info["Spd_mps"].c_str(), gps_info["Hdg"].c_str(), gps_info["Rate_mps"].c_str(), gps_info["Status"].c_str() ); deviceInfo->SetPage(info); } /** Creates all of the GUI controls on the main form. */ void StatusFrame::CreateGUIControls() { // Set window properties and title bar SetTitle(wxT("Device Status")); SetIcon(wxNullIcon); mainPanel = new wxPanel(this, wxID_ANY); mainSizer = new wxBoxSizer(wxVERTICAL); mainPanel->SetSizer(mainSizer); deviceInfo = new wxHtmlWindow(mainPanel); mainSizer->Add(deviceInfo, 1, wxEXPAND | wxALL); Update(); } /** Event handler for the form closing event Exit the ChaosConnect Program */ void StatusFrame::OnClose(wxCloseEvent& event) { Destroy(); } /** Selects a device from the menu This is a catchall menu event handler becasue I couldn't think of a better way to do this because the menu is dynamic */ void StatusFrame::SelectDevice( wxCommandEvent& event ) { int id = event.GetId(); if(id > 10000) { /// We're selecting a device deviceId = deviceIds[id - 10000]; } Update(); } /** Launches a new status window */ void StatusFrame::NewStatusWindow( wxCommandEvent& event ) { StatusFrame* frame = new StatusFrame(NULL); frame->Show(); } /** Launches a new graph window */ void StatusFrame::NewGraphWindow( wxCommandEvent& event ) { GraphFrame* frame = new GraphFrame(NULL); frame->Show(); } <commit_msg>- added slight transparency to status window<commit_after>/** * \file StatusFrame.cpp * \brief Main Windows Class */ #include "StatusFrame.h" BEGIN_EVENT_TABLE(StatusFrame,wxFrame) EVT_MENU(ID_NEWSTATUS, StatusFrame::NewStatusWindow) EVT_MENU(ID_NEWGRAPH, StatusFrame::NewGraphWindow) EVT_MENU(-1, StatusFrame::SelectDevice) EVT_CLOSE(StatusFrame::OnClose) END_EVENT_TABLE() /** Constructor for the Main frame. */ StatusFrame::StatusFrame(wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style) : wxFrame(parent, id, title, position, size, style) { deviceId = "Please select a device from the menu."; CreateGUIControls(); SetTransparent(225); } /** Destructor for the Main form. */ StatusFrame::~StatusFrame() { } /** Updates the GUI with new database information */ void StatusFrame::Update() { wxMenuBar *menubar = new wxMenuBar; wxMenu *devices = new wxMenu; wxMenu *view = new wxMenu; deviceIds = DB_getAllDevices(); menubar->Append(devices, wxT("&Devices")); for(unsigned int i = 0; i < deviceIds.size(); i++) { devices->Append(10000+i, deviceIds[i]); } menubar->Append(view, wxT("&View")); view->Append(ID_NEWSTATUS, "New Status Window"); view->Append(ID_NEWGRAPH, "New Graph Window"); SetMenuBar(menubar); map<string, string> gps_info; gps_info = DB_getMostRecentGPS(atoi(deviceId.c_str())); wxString info = wxString::Format(wxT("" "<body bgcolor=black text=white>" "<b>Device: <font color=#33ff33>%s</font></b>\n" "<hr>\n" "<b>Location</b>\n<br />" "Latitude: <font color=#33ff33>%s</font>\n<br />" "Longitude: <font color=#33ff33>%s</font>\n<br />" "Altitude (M): <font color=#33ff33>%s</font>\n<br />" "Altitude (Ft): <font color=#33ff33>%s</font>\n<br />" "Speed (Knots): <font color=#33ff33>%s</font>\n<br />" "Speed (M/S): <font color=#33ff33>%s</font>\n<br />" "Bearing: <font color=#33ff33>%s</font>\n<br />" "Climb: <font color=#33ff33>%s</font>\n<br />" "GPS Status: <font color=#33ff33>%s</font>\n" "\n<hr>" "<b>Status</b>\n<br />" "Battery 1 (V): \n<br />" "Battery 2 (V): \n<br />" "Buss (V): \n<br />" "Signal (%%): \n<br />" "Temperature Int. (c): \n<br />" "Temperature Ext. (c): \n<br />" "Pressure (HPA): \n<br />" "RH (%%): \n" "</body>" ), deviceId.c_str(), gps_info["Latitude"].c_str(), gps_info["Longitude"].c_str(), gps_info["Altitude_m"].c_str(), gps_info["Altitude_ft"].c_str(), gps_info["Spd_knots"].c_str(), gps_info["Spd_mps"].c_str(), gps_info["Hdg"].c_str(), gps_info["Rate_mps"].c_str(), gps_info["Status"].c_str() ); deviceInfo->SetPage(info); } /** Creates all of the GUI controls on the main form. */ void StatusFrame::CreateGUIControls() { // Set window properties and title bar SetTitle(wxT("Device Status")); SetIcon(wxNullIcon); mainPanel = new wxPanel(this, wxID_ANY); mainSizer = new wxBoxSizer(wxVERTICAL); mainPanel->SetSizer(mainSizer); deviceInfo = new wxHtmlWindow(mainPanel); mainSizer->Add(deviceInfo, 1, wxEXPAND | wxALL); Update(); } /** Event handler for the form closing event Exit the ChaosConnect Program */ void StatusFrame::OnClose(wxCloseEvent& event) { Destroy(); } /** Selects a device from the menu This is a catchall menu event handler becasue I couldn't think of a better way to do this because the menu is dynamic */ void StatusFrame::SelectDevice( wxCommandEvent& event ) { int id = event.GetId(); if(id > 10000) { /// We're selecting a device deviceId = deviceIds[id - 10000]; } Update(); } /** Launches a new status window */ void StatusFrame::NewStatusWindow( wxCommandEvent& event ) { StatusFrame* frame = new StatusFrame(NULL); frame->Show(); } /** Launches a new graph window */ void StatusFrame::NewGraphWindow( wxCommandEvent& event ) { GraphFrame* frame = new GraphFrame(NULL); frame->Show(); } <|endoftext|>
<commit_before>// @(#)root/gui:$Name: $:$Id: TGToolTip.cxx,v 1.7 2003/11/05 13:08:26 rdm Exp $ // Author: Fons Rademakers 22/02/98 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ /************************************************************************** This source is based on Xclass95, a Win95-looking GUI toolkit. Copyright (C) 1996, 1997 David Barth, Ricky Ralston, Hector Peraza. Xclass95 is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. **************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TGToolTip // // // // A tooltip is a one line help text that is displayed in a window // // when the cursor rests over a widget. For an example of usage see // // the TGButton class. // // // ////////////////////////////////////////////////////////////////////////// #include "TGToolTip.h" #include "TGLabel.h" #include "TGResourcePool.h" #include "TTimer.h" #include "TSystem.h" #include "TVirtualPad.h" #include "TBox.h" ClassImp(TGToolTip) //______________________________________________________________________________ class TTipDelayTimer : public TTimer { private: TGToolTip *fTip; public: TTipDelayTimer(TGToolTip *tip, Long_t ms) : TTimer(ms, kTRUE) { fTip = tip; } Bool_t Notify(); }; //______________________________________________________________________________ Bool_t TTipDelayTimer::Notify() { fTip->HandleTimer(0); Reset(); return kFALSE; } //______________________________________________________________________________ TGToolTip::TGToolTip(const TGWindow *p, const TGFrame *f, const char *text, Long_t delayms) : TGCompositeFrame(p, 10, 10, kTempFrame | kHorizontalFrame | kRaisedFrame) { // Create a tool tip. P is the tool tips parent window (normally // fClient->GetRoot(), f is the frame to which the tool tip is associated, // text is the tool tip one-liner and delayms is the delay in ms before // the tool tip is shown. SetWindowAttributes_t attr; attr.fMask = kWAOverrideRedirect | kWASaveUnder; attr.fOverrideRedirect = kTRUE; attr.fSaveUnder = kTRUE; gVirtualX->ChangeWindowAttributes(fId, &attr); SetBackgroundColor(fClient->GetResourcePool()->GetTipBgndColor()); fLabel = new TGLabel(this, text); fLabel->SetBackgroundColor(fClient->GetResourcePool()->GetTipBgndColor()); AddFrame(fLabel, fL1 = new TGLayoutHints(kLHintsLeft | kLHintsTop, 2, 3, 0, 0)); MapSubwindows(); Resize(GetDefaultSize()); fWindow = f; fPad = 0; fBox = 0; fX = fY = -1; fDelay = new TTipDelayTimer(this, delayms); } //______________________________________________________________________________ TGToolTip::TGToolTip(const TGWindow *p, const TBox *box, const char *text, Long_t delayms) : TGCompositeFrame(p, 10, 10, kTempFrame | kHorizontalFrame | kRaisedFrame) { // Create a tool tip. P is the tool tips parent window (normally // fClient->GetRoot(), box is the area to which the tool tip is associated, // text is the tool tip one-liner and delayms is the delay in ms before // the tool tip is shown. When using this ctor with the box argument // you have to use Reset(const TVirtualPad *parent). SetWindowAttributes_t attr; attr.fMask = kWAOverrideRedirect | kWASaveUnder; attr.fOverrideRedirect = kTRUE; attr.fSaveUnder = kTRUE; gVirtualX->ChangeWindowAttributes(fId, &attr); SetBackgroundColor(fClient->GetResourcePool()->GetTipBgndColor()); fLabel = new TGLabel(this, text); fLabel->SetBackgroundColor(fClient->GetResourcePool()->GetTipBgndColor()); AddFrame(fLabel, fL1 = new TGLayoutHints(kLHintsLeft | kLHintsTop, 2, 3, 0, 0)); MapSubwindows(); Resize(GetDefaultSize()); fWindow = 0; fPad = 0; fBox = box; fDelay = new TTipDelayTimer(this, delayms); } //______________________________________________________________________________ TGToolTip::TGToolTip(const TBox *box, const char *text,Long_t delayms) : TGCompositeFrame(gClient->GetRoot(), 10, 10, kTempFrame | kHorizontalFrame | kRaisedFrame) { // Create a tool tip in the parent window gClient->GetRoot(), // box is the area to which the tool tip is associated, // text is the tool tip one-liner and delayms is the delay in ms before // the tool tip is shown. When using this ctor with the box argument // you have to use Reset(const TVirtualPad *parent). SetWindowAttributes_t attr; attr.fMask = kWAOverrideRedirect | kWASaveUnder; attr.fOverrideRedirect = kTRUE; attr.fSaveUnder = kTRUE; gVirtualX->ChangeWindowAttributes(fId, &attr); SetBackgroundColor(fClient->GetResourcePool()->GetTipBgndColor()); fLabel = new TGLabel(this, text); fLabel->SetBackgroundColor(fClient->GetResourcePool()->GetTipBgndColor()); AddFrame(fLabel, fL1 = new TGLayoutHints(kLHintsLeft | kLHintsTop, 2, 3, 0, 0)); MapSubwindows(); Resize(GetDefaultSize()); fWindow = 0; fPad = 0; fBox = box; fDelay = new TTipDelayTimer(this, delayms); } //______________________________________________________________________________ TGToolTip::~TGToolTip() { // Delete a tool tip object. delete fDelay; delete fLabel; delete fL1; } //______________________________________________________________________________ void TGToolTip::DrawBorder() { // Draw border of tool tip window. gVirtualX->DrawLine(fId, GetShadowGC()(), 0, 0, fWidth-2, 0); gVirtualX->DrawLine(fId, GetShadowGC()(), 0, 0, 0, fHeight-2); gVirtualX->DrawLine(fId, GetBlackGC()(), 0, fHeight-1, fWidth-1, fHeight-1); gVirtualX->DrawLine(fId, GetBlackGC()(), fWidth-1, fHeight-1, fWidth-1, 0); } //______________________________________________________________________________ void TGToolTip::Show(Int_t x, Int_t y) { // Show tool tip window. Move(x, y); MapWindow(); RaiseWindow(); } //______________________________________________________________________________ void TGToolTip::Hide() { // Hide tool tip window. Use this method to hide the tool tip in a client // class. UnmapWindow(); fDelay->Remove(); } //______________________________________________________________________________ void TGToolTip::Reset() { // Reset tool tip popup delay timer. Use this method to activate tool tip // in a client class. fDelay->Reset(); gSystem->AddTimer(fDelay); } //______________________________________________________________________________ void TGToolTip::Reset(const TVirtualPad *parent) { // Reset tool tip popup delay timer. Use this method to activate tool tip // in a client class. Use this method for graphics objects drawn in a // TCanvas, also the tool tip must have been created with the ctor // taking the TBox as argument. fPad = parent; fDelay->Reset(); gSystem->AddTimer(fDelay); } //______________________________________________________________________________ Bool_t TGToolTip::HandleTimer(TTimer *) { // If tool tip delay timer times out show tool tip window. Int_t x = 0, y = 0, px1 = 0, px2 = 0, py1 = 0, py2 = 0; Window_t wtarget; if (fWindow) { gVirtualX->TranslateCoordinates(fWindow->GetId(), GetParent()->GetId(), fX == -1 ? fWindow->GetWidth() >> 1 : fX, fY == -1 ? fWindow->GetHeight() : fY, x, y, wtarget); } else { if (!fPad) { Error("HandleTimer", "parent pad not set for tool tip"); return kTRUE; } if (fBox) { px1 = fPad->XtoAbsPixel(fBox->GetX1()); px2 = fPad->XtoAbsPixel(fBox->GetX2()); py1 = fPad->YtoAbsPixel(fBox->GetY1()); py2 = fPad->YtoAbsPixel(fBox->GetY2()); } else { px1 = fPad->XtoAbsPixel(fPad->GetX1()); px2 = fPad->XtoAbsPixel(fPad->GetX2()); py1 = fPad->YtoAbsPixel(fPad->GetY1()); py2 = fPad->YtoAbsPixel(fPad->GetY2()); } gVirtualX->TranslateCoordinates(gVirtualX->GetWindowID(fPad->GetCanvasID()), GetParent()->GetId(), px1 + ((px2-px1) >> 1), py1, x, y, wtarget); } Int_t screenX, screenY; UInt_t screenW, screenH; // width and height of screen gVirtualX->GetWindowSize(gClient->GetRoot()->GetId(), screenX, screenY, screenW, screenH); if (x + fWidth > screenW) x = screenW - fWidth; if (y+4 + GetHeight() > screenH) if (fWindow) y -= GetHeight() + fWindow->GetHeight() + 2*4; else y -= GetHeight() + py1-py2 + 2*4; Show(x, y+4); fDelay->Remove(); return kTRUE; } //______________________________________________________________________________ void TGToolTip::SetText(const char *new_text) { // Set new tool tip text. fLabel->SetText(new TGString(new_text)); Resize(GetDefaultSize()); } //______________________________________________________________________________ void TGToolTip::SetPosition(Int_t x, Int_t y) { // Set popup position within specified frame (as specified in the ctor). // To get back default behaviour (in the middle just below the designated // frame) set position to -1,-1. fX = x; fY = y; if (fX < -1) fX = 0; if (fY < -1) fY = 0; if (fWindow) { if (fX > (Int_t) fWindow->GetWidth()) fX = fWindow->GetWidth(); if (fY > (Int_t) fWindow->GetHeight()) fY = fWindow->GetHeight(); } } //______________________________________________________________________________ const TGString *TGToolTip::GetText() const { // Get the tool tip text. return fLabel->GetText(); } <commit_msg>use TGClient::GetDisplayWidth() and Height() instead of GetWindowSize() (saves X11 server round trip).<commit_after>// @(#)root/gui:$Name: $:$Id: TGToolTip.cxx,v 1.8 2004/04/20 14:48:01 brun Exp $ // Author: Fons Rademakers 22/02/98 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ /************************************************************************** This source is based on Xclass95, a Win95-looking GUI toolkit. Copyright (C) 1996, 1997 David Barth, Ricky Ralston, Hector Peraza. Xclass95 is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. **************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TGToolTip // // // // A tooltip is a one line help text that is displayed in a window // // when the cursor rests over a widget. For an example of usage see // // the TGButton class. // // // ////////////////////////////////////////////////////////////////////////// #include "TGToolTip.h" #include "TGLabel.h" #include "TGResourcePool.h" #include "TTimer.h" #include "TSystem.h" #include "TVirtualPad.h" #include "TBox.h" ClassImp(TGToolTip) //______________________________________________________________________________ class TTipDelayTimer : public TTimer { private: TGToolTip *fTip; public: TTipDelayTimer(TGToolTip *tip, Long_t ms) : TTimer(ms, kTRUE) { fTip = tip; } Bool_t Notify(); }; //______________________________________________________________________________ Bool_t TTipDelayTimer::Notify() { fTip->HandleTimer(0); Reset(); return kFALSE; } //______________________________________________________________________________ TGToolTip::TGToolTip(const TGWindow *p, const TGFrame *f, const char *text, Long_t delayms) : TGCompositeFrame(p, 10, 10, kTempFrame | kHorizontalFrame | kRaisedFrame) { // Create a tool tip. P is the tool tips parent window (normally // fClient->GetRoot(), f is the frame to which the tool tip is associated, // text is the tool tip one-liner and delayms is the delay in ms before // the tool tip is shown. SetWindowAttributes_t attr; attr.fMask = kWAOverrideRedirect | kWASaveUnder; attr.fOverrideRedirect = kTRUE; attr.fSaveUnder = kTRUE; gVirtualX->ChangeWindowAttributes(fId, &attr); SetBackgroundColor(fClient->GetResourcePool()->GetTipBgndColor()); fLabel = new TGLabel(this, text); fLabel->SetBackgroundColor(fClient->GetResourcePool()->GetTipBgndColor()); AddFrame(fLabel, fL1 = new TGLayoutHints(kLHintsLeft | kLHintsTop, 2, 3, 0, 0)); MapSubwindows(); Resize(GetDefaultSize()); fWindow = f; fPad = 0; fBox = 0; fX = fY = -1; fDelay = new TTipDelayTimer(this, delayms); } //______________________________________________________________________________ TGToolTip::TGToolTip(const TGWindow *p, const TBox *box, const char *text, Long_t delayms) : TGCompositeFrame(p, 10, 10, kTempFrame | kHorizontalFrame | kRaisedFrame) { // Create a tool tip. P is the tool tips parent window (normally // fClient->GetRoot(), box is the area to which the tool tip is associated, // text is the tool tip one-liner and delayms is the delay in ms before // the tool tip is shown. When using this ctor with the box argument // you have to use Reset(const TVirtualPad *parent). SetWindowAttributes_t attr; attr.fMask = kWAOverrideRedirect | kWASaveUnder; attr.fOverrideRedirect = kTRUE; attr.fSaveUnder = kTRUE; gVirtualX->ChangeWindowAttributes(fId, &attr); SetBackgroundColor(fClient->GetResourcePool()->GetTipBgndColor()); fLabel = new TGLabel(this, text); fLabel->SetBackgroundColor(fClient->GetResourcePool()->GetTipBgndColor()); AddFrame(fLabel, fL1 = new TGLayoutHints(kLHintsLeft | kLHintsTop, 2, 3, 0, 0)); MapSubwindows(); Resize(GetDefaultSize()); fWindow = 0; fPad = 0; fBox = box; fDelay = new TTipDelayTimer(this, delayms); } //______________________________________________________________________________ TGToolTip::TGToolTip(const TBox *box, const char *text,Long_t delayms) : TGCompositeFrame(gClient->GetRoot(), 10, 10, kTempFrame | kHorizontalFrame | kRaisedFrame) { // Create a tool tip in the parent window gClient->GetRoot(), // box is the area to which the tool tip is associated, // text is the tool tip one-liner and delayms is the delay in ms before // the tool tip is shown. When using this ctor with the box argument // you have to use Reset(const TVirtualPad *parent). SetWindowAttributes_t attr; attr.fMask = kWAOverrideRedirect | kWASaveUnder; attr.fOverrideRedirect = kTRUE; attr.fSaveUnder = kTRUE; gVirtualX->ChangeWindowAttributes(fId, &attr); SetBackgroundColor(fClient->GetResourcePool()->GetTipBgndColor()); fLabel = new TGLabel(this, text); fLabel->SetBackgroundColor(fClient->GetResourcePool()->GetTipBgndColor()); AddFrame(fLabel, fL1 = new TGLayoutHints(kLHintsLeft | kLHintsTop, 2, 3, 0, 0)); MapSubwindows(); Resize(GetDefaultSize()); fWindow = 0; fPad = 0; fBox = box; fDelay = new TTipDelayTimer(this, delayms); } //______________________________________________________________________________ TGToolTip::~TGToolTip() { // Delete a tool tip object. delete fDelay; delete fLabel; delete fL1; } //______________________________________________________________________________ void TGToolTip::DrawBorder() { // Draw border of tool tip window. gVirtualX->DrawLine(fId, GetShadowGC()(), 0, 0, fWidth-2, 0); gVirtualX->DrawLine(fId, GetShadowGC()(), 0, 0, 0, fHeight-2); gVirtualX->DrawLine(fId, GetBlackGC()(), 0, fHeight-1, fWidth-1, fHeight-1); gVirtualX->DrawLine(fId, GetBlackGC()(), fWidth-1, fHeight-1, fWidth-1, 0); } //______________________________________________________________________________ void TGToolTip::Show(Int_t x, Int_t y) { // Show tool tip window. Move(x, y); MapWindow(); RaiseWindow(); } //______________________________________________________________________________ void TGToolTip::Hide() { // Hide tool tip window. Use this method to hide the tool tip in a client // class. UnmapWindow(); fDelay->Remove(); } //______________________________________________________________________________ void TGToolTip::Reset() { // Reset tool tip popup delay timer. Use this method to activate tool tip // in a client class. fDelay->Reset(); gSystem->AddTimer(fDelay); } //______________________________________________________________________________ void TGToolTip::Reset(const TVirtualPad *parent) { // Reset tool tip popup delay timer. Use this method to activate tool tip // in a client class. Use this method for graphics objects drawn in a // TCanvas, also the tool tip must have been created with the ctor // taking the TBox as argument. fPad = parent; fDelay->Reset(); gSystem->AddTimer(fDelay); } //______________________________________________________________________________ Bool_t TGToolTip::HandleTimer(TTimer *) { // If tool tip delay timer times out show tool tip window. Int_t x = 0, y = 0, px1 = 0, px2 = 0, py1 = 0, py2 = 0; Window_t wtarget; if (fWindow) { gVirtualX->TranslateCoordinates(fWindow->GetId(), GetParent()->GetId(), fX == -1 ? fWindow->GetWidth() >> 1 : fX, fY == -1 ? fWindow->GetHeight() : fY, x, y, wtarget); } else { if (!fPad) { Error("HandleTimer", "parent pad not set for tool tip"); return kTRUE; } if (fBox) { px1 = fPad->XtoAbsPixel(fBox->GetX1()); px2 = fPad->XtoAbsPixel(fBox->GetX2()); py1 = fPad->YtoAbsPixel(fBox->GetY1()); py2 = fPad->YtoAbsPixel(fBox->GetY2()); } else { px1 = fPad->XtoAbsPixel(fPad->GetX1()); px2 = fPad->XtoAbsPixel(fPad->GetX2()); py1 = fPad->YtoAbsPixel(fPad->GetY1()); py2 = fPad->YtoAbsPixel(fPad->GetY2()); } gVirtualX->TranslateCoordinates(gVirtualX->GetWindowID(fPad->GetCanvasID()), GetParent()->GetId(), px1 + ((px2-px1) >> 1), py1, x, y, wtarget); } UInt_t screenW = fClient->GetDisplayWidth(); UInt_t screenH = fClient->GetDisplayHeight(); if (x + fWidth > screenW) x = screenW - fWidth; if (y+4 + GetHeight() > screenH) if (fWindow) y -= GetHeight() + fWindow->GetHeight() + 2*4; else y -= GetHeight() + py1-py2 + 2*4; Show(x, y+4); fDelay->Remove(); return kTRUE; } //______________________________________________________________________________ void TGToolTip::SetText(const char *new_text) { // Set new tool tip text. fLabel->SetText(new TGString(new_text)); Resize(GetDefaultSize()); } //______________________________________________________________________________ void TGToolTip::SetPosition(Int_t x, Int_t y) { // Set popup position within specified frame (as specified in the ctor). // To get back default behaviour (in the middle just below the designated // frame) set position to -1,-1. fX = x; fY = y; if (fX < -1) fX = 0; if (fY < -1) fY = 0; if (fWindow) { if (fX > (Int_t) fWindow->GetWidth()) fX = fWindow->GetWidth(); if (fY > (Int_t) fWindow->GetHeight()) fY = fWindow->GetHeight(); } } //______________________________________________________________________________ const TGString *TGToolTip::GetText() const { // Get the tool tip text. return fLabel->GetText(); } <|endoftext|>
<commit_before>#ifndef TETRIS_DEFS_HPP_ #define TETRIS_DEFS_HPP_ #include <array> namespace tetris { template <typename T, std::size_t I, std::size_t J> using Matrix = std::array< std::array<T, J>, I>; } /* namespace tetris */ #endif /* TETRIS_DEFS_HPP_ */ <commit_msg>Create Defs.hpp<commit_after>#ifndef TETRIS_DEFS_HPP_ #define TETRIS_DEFS_HPP_ #include <memory> #include <array> namespace tetris { template <typename T, std::size_t I, std::size_t J> using Matrix = std::array< std::array<T, J>, I>; template <typename T, std::size_t N> using PtrArray = std::array<std::unique_ptr<T>, N>; } /* namespace tetris */ #endif /* TETRIS_DEFS_HPP_ */ <|endoftext|>
<commit_before>/* * manager.cpp * * Created on: 23/03/2015 * * ========================================================================= * Copyright (C) 2015-, Daniele De Sensi ([email protected]) * * This file is part of AdaptiveFastFlow. * * AdaptiveFastFlow is free software: you can redistribute it and/or * modify it under the terms of the Lesser GNU General Public * License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. * AdaptiveFastFlow 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 * Lesser GNU General Public License for more details. * * You should have received a copy of the Lesser GNU General Public * License along with AdaptiveFastFlow. * If not, see <http://www.gnu.org/licenses/>. * * ========================================================================= */ #include "./manager.hpp" #include "parameters.hpp" #include "predictors.hpp" #include "./node.hpp" #include "utils.hpp" #include <ff/farm.hpp> #include <mammut/module.hpp> #include <mammut/utils.hpp> #include <mammut/mammut.hpp> #include <cmath> #include <iostream> #include <limits> #include <string> #undef DEBUG #undef DEBUGB #ifdef DEBUG_MANAGER #define DEBUG(x) do { cerr << "[Manager] " << x << endl; } while (0) #define DEBUGB(x) do {x;} while(0) #else #define DEBUG(x) #define DEBUGB(x) #endif namespace adpff{ class Parameters; using namespace std; using namespace ff; using namespace mammut::cpufreq; using namespace mammut::energy; using namespace mammut::task; using namespace mammut::topology; using namespace mammut::utils; template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::setDomainToHighestFrequency(const Domain* domain){ if(!domain->setGovernor(GOVERNOR_PERFORMANCE)){ if(!domain->setGovernor(GOVERNOR_USERSPACE) || !domain->setHighestFrequencyUserspace()){ throw runtime_error("AdaptivityManagerFarm: Fatal error while " "setting highest frequency for sensitive " "emitter/collector. Try to run it without " "sensitivity parameters."); } } } template <typename lb_t, typename gt_t> double ManagerFarm<lb_t, gt_t>::getPrimaryValue(const MonitoredSample& sample) const{ switch(_p.contractType){ case CONTRACT_PERF_UTILIZATION:{ return sample.utilization; }break; case CONTRACT_PERF_BANDWIDTH: case CONTRACT_PERF_COMPLETION_TIME:{ return sample.bandwidth; }break; case CONTRACT_POWER_BUDGET:{ return sample.watts; }break; default:{ return 0; }break; } } template <typename lb_t, typename gt_t> double ManagerFarm<lb_t, gt_t>::getSecondaryValue(const MonitoredSample& sample) const{ switch(_p.contractType){ case CONTRACT_PERF_UTILIZATION: case CONTRACT_PERF_BANDWIDTH: case CONTRACT_PERF_COMPLETION_TIME:{ return sample.watts; }break; case CONTRACT_POWER_BUDGET:{ return sample.bandwidth; }break; default:{ return 0; }break; } } template <typename lb_t, typename gt_t> double ManagerFarm<lb_t, gt_t>::getPrimaryValue() const{ return getPrimaryValue(_samples->average()); } template <typename lb_t, typename gt_t> double ManagerFarm<lb_t, gt_t>::getSecondaryValue() const{ return getSecondaryValue(_samples->average()); } template <typename lb_t, typename gt_t> bool ManagerFarm<lb_t, gt_t>::terminated(){ /** * We do not need to wait if the emitter is terminated. * Indeed, if the workers terminated, the emitter surely terminated * too. */ for(size_t i = 0; i < _activeWorkers.size(); i++){ if(!_activeWorkers.at(i)->isTerminated()){ return false; }else{ DEBUG("Worker " << i << " terminated."); } } if(_collector && !_collector->isTerminated()){ return false; }else{ DEBUG("Collector terminated."); } return true; } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::changeKnobs(){ KnobsValues values = _calibrator->getNextKnobsValues(getPrimaryValue(), getSecondaryValue(), _remainingTasks); if(values != _configuration.getRealValues()){ _configuration.setValues(values); _activeWorkers = dynamic_cast<const KnobWorkers*>(_configuration.getKnob(KNOB_TYPE_WORKERS))->getActiveWorkers(); /****************** Clean state ******************/ _lastStoredSampleMs = getMillisecondsTime(); _samples->reset(); if(_counter){ _counter->reset(); } _totalTasks = 0; } } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::observe(){ if(_p.observer){ const KnobMapping* kMapping = dynamic_cast<const KnobMapping*>(_configuration.getKnob(KNOB_TYPE_MAPPING)); _p.observer->observe(_lastStoredSampleMs, _configuration.getRealValue(KNOB_TYPE_WORKERS), _configuration.getRealValue(KNOB_TYPE_FREQUENCY), kMapping->getEmitterVirtualCore(), kMapping->getWorkersVirtualCore(), kMapping->getCollectorVirtualCore(), _samples->getLastSample().bandwidth, _samples->average().bandwidth, _samples->coefficientVariation().bandwidth, _samples->average().utilization, _samples->average().watts); } } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::askForWorkersSamples(){ for(size_t i = 0; i < _activeWorkers.size(); i++){ _activeWorkers.at(i)->askForSample(); } } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::getWorkersSamples(WorkerSample& sample){ AdaptiveNode* w; uint numActiveWorkers = _activeWorkers.size(); sample = WorkerSample(); for(size_t i = 0; i < numActiveWorkers; i++){ WorkerSample tmp; w = _activeWorkers.at(i); w->getSampleResponse(tmp, _p.strategyPolling, _samples->average().latency); sample += tmp; } sample.loadPercentage /= numActiveWorkers; sample.latency /= numActiveWorkers; } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::storeNewSample(){ MonitoredSample sample; WorkerSample ws; Joules joules = 0.0; askForWorkersSamples(); getWorkersSamples(ws); _totalTasks += ws.tasksCount; if(_p.contractType == CONTRACT_PERF_COMPLETION_TIME){ if(_remainingTasks > ws.tasksCount){ _remainingTasks -= ws.tasksCount; }else{ _remainingTasks = 0; } } if(_counter){ switch(_counter->getType()){ case COUNTER_CPUS:{ joules = ((CounterCpus*) _counter)->getJoulesCoresAll(); }break; default:{ joules = _counter->getJoules(); }break; } } double now = getMillisecondsTime(); double durationSecs = (now - _lastStoredSampleMs) / 1000.0; _lastStoredSampleMs = now; sample.watts = joules / durationSecs; sample.utilization = ws.loadPercentage; // ATTENTION: Bandwidth is not the number of task since the // last observation but the number of expected // tasks that will be processed in 1 second. // For this reason, if we sum all the bandwidths in // the result observation file, we may have an higher // number than the number of tasks. sample.bandwidth = ws.bandwidthTotal; sample.latency = ws.latency; if(_counter){ _counter->reset(); } _samples->add(sample); DEBUGB(samplesFile << *_samples << "\n"); } template <typename lb_t, typename gt_t> bool ManagerFarm<lb_t, gt_t>::persist() const{ bool r = false; switch(_p.strategyPersistence){ case STRATEGY_PERSISTENCE_SAMPLES:{ r = _samples->size() < _p.persistenceValue; }break; case STRATEGY_PERSISTENCE_TASKS:{ r = _totalTasks < _p.persistenceValue; }break; case STRATEGY_PERSISTENCE_VARIATION:{ const MonitoredSample& variation = _samples->coefficientVariation(); r = getPrimaryValue(variation) < _p.persistenceValue && getSecondaryValue(variation) < _p.persistenceValue; }break; } return r; } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::initPredictors(){ if(_p.strategyCalibration == STRATEGY_CALIBRATION_RANDOM){ ; //CREARE TODO: Ci deve sempre essere un calibratore }else{ switch(_p.strategyPrediction){ case STRATEGY_PREDICTION_SIMPLE:{ _calibrator = new CalibratorDummy(_p, _configuration, _samples); }break; case STRATEGY_PREDICTION_REGRESSION_LINEAR:{ _calibrator = new CalibratorLowDiscrepancy(_p, _configuration, _samples); }break; } } } static Parameters& validate(Parameters& p){ ParametersValidation apv = p.validate(); if(apv != VALIDATION_OK){ throw runtime_error("Invalid adaptivity parameters: " + std::to_string(apv)); } return p; } static std::vector<AdaptiveNode*> convertWorkers(svector<ff_node*> w){ std::vector<AdaptiveNode*> r; for(size_t i = 0; i < w.size(); i++){ r.push_back(dynamic_cast<AdaptiveNode*>(w[i])); } return r; } template <typename lb_t, typename gt_t> ManagerFarm<lb_t, gt_t>::ManagerFarm(ff_farm<lb_t, gt_t>* farm, Parameters parameters): _farm(farm), _p(validate(parameters)), _startTimeMs(0), _cpufreq(_p.mammut.getInstanceCpuFreq()), _counter(_p.mammut.getInstanceEnergy()->getCounter()), _task(_p.mammut.getInstanceTask()), _topology(_p.mammut.getInstanceTopology()), _emitter(dynamic_cast<AdaptiveNode*>(_farm->getEmitter())), _collector(dynamic_cast<AdaptiveNode*>(_farm->getCollector())), _activeWorkers(convertWorkers(_farm->getWorkers())), _configuration(_p, _emitter, _collector, _farm->getgt(), _activeWorkers), _samples(NULL), _totalTasks(0), _remainingTasks(0), _deadline(0), _lastStoredSampleMs(0), _calibrator(NULL){ _samples = NULL; switch(_p.strategySmoothing){ case STRATEGY_SMOOTHING_MOVING_AVERAGE:{ _samples = new MovingAverageSimple<MonitoredSample>(_p.smoothingFactor); }break; case STRATEGY_SMOOTHING_EXPONENTIAL:{ _samples = new MovingAverageExponential<MonitoredSample>(_p.smoothingFactor); }break; } DEBUGB(samplesFile.open("samples.csv")); } template <typename lb_t, typename gt_t> ManagerFarm<lb_t, gt_t>::~ManagerFarm(){ delete _samples; if(_calibrator){ delete _calibrator; } DEBUGB(samplesFile.close()); } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::initNodesPreRun() { for (size_t i = 0; i < _activeWorkers.size(); i++) { _activeWorkers.at(i)->initPreRun(_p.mammut, _p.archData.ticksPerNs, NODE_TYPE_WORKER); } if (_emitter) { _emitter->initPreRun(_p.mammut, _p.archData.ticksPerNs, NODE_TYPE_EMITTER); } else { throw runtime_error("Emitter is needed to use the manager."); } if (_collector) { _collector->initPreRun(_p.mammut, _p.archData.ticksPerNs, NODE_TYPE_COLLECTOR); } } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::initNodesPostRun() { for (size_t i = 0; i < _activeWorkers.size(); i++) { _activeWorkers.at(i)->initPostRun(); } _emitter->initPostRun(); if (_collector) { _collector->initPostRun(); } } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::cleanNodes() { for (size_t i = 0; i < _activeWorkers.size(); i++) { _activeWorkers.at(i)->clean(); } if (_emitter) { _emitter->clean(); } if (_collector) { _collector->clean(); } } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::run(){ initNodesPreRun(); _farm->run_then_freeze(); initNodesPostRun(); _configuration.maxAllKnobs(); _startTimeMs = getMillisecondsTime(); if(_counter){ _counter->reset(); } _lastStoredSampleMs = _startTimeMs; if(_p.observer){ _p.observer->_startMonitoringMs = _lastStoredSampleMs; } if(_p.contractType == CONTRACT_PERF_COMPLETION_TIME){ _remainingTasks = _p.expectedTasksNumber; _deadline = getMillisecondsTime()/1000.0 + _p.requiredCompletionTime; } initPredictors(); double microsecsSleep = 0; if(_p.contractType == CONTRACT_NONE){ _farm->wait(); storeNewSample(); observe(); }else{ /* Force the first calibration point. **/ assert(_calibrator); changeKnobs(); double startSample = getMillisecondsTime(); while(!terminated()){ double overheadMs = getMillisecondsTime() - startSample; microsecsSleep = ((double)_p.samplingInterval - overheadMs)* (double)MAMMUT_MICROSECS_IN_MILLISEC; if(microsecsSleep < 0){ microsecsSleep = 0; } usleep(microsecsSleep); startSample = getMillisecondsTime(); storeNewSample(); DEBUG("New sample stored."); if(_p.contractType == CONTRACT_PERF_COMPLETION_TIME){ double now = getMillisecondsTime()/1000.0; if(now >= _deadline){ _p.requiredBandwidth = numeric_limits<double>::max(); }else{ _p.requiredBandwidth = _remainingTasks / (_deadline - now); } } observe(); if(!persist()){ assert(_calibrator); changeKnobs(); startSample = getMillisecondsTime(); } } DEBUG("Terminated."); } uint duration = getMillisecondsTime() - _startTimeMs; if(_p.observer){ vector<CalibrationStats> cs; if(_calibrator){ cs = _calibrator->getCalibrationsStats(); _p.observer->calibrationStats(cs, duration); } _p.observer->summaryStats(cs, duration); } cleanNodes(); } } <commit_msg>[FIX] Fixed knobs maximization when contract is NONE.<commit_after>/* * manager.cpp * * Created on: 23/03/2015 * * ========================================================================= * Copyright (C) 2015-, Daniele De Sensi ([email protected]) * * This file is part of AdaptiveFastFlow. * * AdaptiveFastFlow is free software: you can redistribute it and/or * modify it under the terms of the Lesser GNU General Public * License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. * AdaptiveFastFlow 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 * Lesser GNU General Public License for more details. * * You should have received a copy of the Lesser GNU General Public * License along with AdaptiveFastFlow. * If not, see <http://www.gnu.org/licenses/>. * * ========================================================================= */ #include "./manager.hpp" #include "parameters.hpp" #include "predictors.hpp" #include "./node.hpp" #include "utils.hpp" #include <ff/farm.hpp> #include <mammut/module.hpp> #include <mammut/utils.hpp> #include <mammut/mammut.hpp> #include <cmath> #include <iostream> #include <limits> #include <string> #undef DEBUG #undef DEBUGB #ifdef DEBUG_MANAGER #define DEBUG(x) do { cerr << "[Manager] " << x << endl; } while (0) #define DEBUGB(x) do {x;} while(0) #else #define DEBUG(x) #define DEBUGB(x) #endif namespace adpff{ class Parameters; using namespace std; using namespace ff; using namespace mammut::cpufreq; using namespace mammut::energy; using namespace mammut::task; using namespace mammut::topology; using namespace mammut::utils; template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::setDomainToHighestFrequency(const Domain* domain){ if(!domain->setGovernor(GOVERNOR_PERFORMANCE)){ if(!domain->setGovernor(GOVERNOR_USERSPACE) || !domain->setHighestFrequencyUserspace()){ throw runtime_error("AdaptivityManagerFarm: Fatal error while " "setting highest frequency for sensitive " "emitter/collector. Try to run it without " "sensitivity parameters."); } } } template <typename lb_t, typename gt_t> double ManagerFarm<lb_t, gt_t>::getPrimaryValue(const MonitoredSample& sample) const{ switch(_p.contractType){ case CONTRACT_PERF_UTILIZATION:{ return sample.utilization; }break; case CONTRACT_PERF_BANDWIDTH: case CONTRACT_PERF_COMPLETION_TIME:{ return sample.bandwidth; }break; case CONTRACT_POWER_BUDGET:{ return sample.watts; }break; default:{ return 0; }break; } } template <typename lb_t, typename gt_t> double ManagerFarm<lb_t, gt_t>::getSecondaryValue(const MonitoredSample& sample) const{ switch(_p.contractType){ case CONTRACT_PERF_UTILIZATION: case CONTRACT_PERF_BANDWIDTH: case CONTRACT_PERF_COMPLETION_TIME:{ return sample.watts; }break; case CONTRACT_POWER_BUDGET:{ return sample.bandwidth; }break; default:{ return 0; }break; } } template <typename lb_t, typename gt_t> double ManagerFarm<lb_t, gt_t>::getPrimaryValue() const{ return getPrimaryValue(_samples->average()); } template <typename lb_t, typename gt_t> double ManagerFarm<lb_t, gt_t>::getSecondaryValue() const{ return getSecondaryValue(_samples->average()); } template <typename lb_t, typename gt_t> bool ManagerFarm<lb_t, gt_t>::terminated(){ /** * We do not need to wait if the emitter is terminated. * Indeed, if the workers terminated, the emitter surely terminated * too. */ for(size_t i = 0; i < _activeWorkers.size(); i++){ if(!_activeWorkers.at(i)->isTerminated()){ return false; }else{ DEBUG("Worker " << i << " terminated."); } } if(_collector && !_collector->isTerminated()){ return false; }else{ DEBUG("Collector terminated."); } return true; } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::changeKnobs(){ KnobsValues values = _calibrator->getNextKnobsValues(getPrimaryValue(), getSecondaryValue(), _remainingTasks); if(values != _configuration.getRealValues()){ _configuration.setValues(values); _activeWorkers = dynamic_cast<const KnobWorkers*>(_configuration.getKnob(KNOB_TYPE_WORKERS))->getActiveWorkers(); /****************** Clean state ******************/ _lastStoredSampleMs = getMillisecondsTime(); _samples->reset(); if(_counter){ _counter->reset(); } _totalTasks = 0; } } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::observe(){ if(_p.observer){ const KnobMapping* kMapping = dynamic_cast<const KnobMapping*>(_configuration.getKnob(KNOB_TYPE_MAPPING)); _p.observer->observe(_lastStoredSampleMs, _configuration.getRealValue(KNOB_TYPE_WORKERS), _configuration.getRealValue(KNOB_TYPE_FREQUENCY), kMapping->getEmitterVirtualCore(), kMapping->getWorkersVirtualCore(), kMapping->getCollectorVirtualCore(), _samples->getLastSample().bandwidth, _samples->average().bandwidth, _samples->coefficientVariation().bandwidth, _samples->average().utilization, _samples->average().watts); } } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::askForWorkersSamples(){ for(size_t i = 0; i < _activeWorkers.size(); i++){ _activeWorkers.at(i)->askForSample(); } } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::getWorkersSamples(WorkerSample& sample){ AdaptiveNode* w; uint numActiveWorkers = _activeWorkers.size(); sample = WorkerSample(); for(size_t i = 0; i < numActiveWorkers; i++){ WorkerSample tmp; w = _activeWorkers.at(i); w->getSampleResponse(tmp, _p.strategyPolling, _samples->average().latency); sample += tmp; } sample.loadPercentage /= numActiveWorkers; sample.latency /= numActiveWorkers; } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::storeNewSample(){ MonitoredSample sample; WorkerSample ws; Joules joules = 0.0; askForWorkersSamples(); getWorkersSamples(ws); _totalTasks += ws.tasksCount; if(_p.contractType == CONTRACT_PERF_COMPLETION_TIME){ if(_remainingTasks > ws.tasksCount){ _remainingTasks -= ws.tasksCount; }else{ _remainingTasks = 0; } } if(_counter){ switch(_counter->getType()){ case COUNTER_CPUS:{ joules = ((CounterCpus*) _counter)->getJoulesCoresAll(); }break; default:{ joules = _counter->getJoules(); }break; } } double now = getMillisecondsTime(); double durationSecs = (now - _lastStoredSampleMs) / 1000.0; _lastStoredSampleMs = now; sample.watts = joules / durationSecs; sample.utilization = ws.loadPercentage; // ATTENTION: Bandwidth is not the number of task since the // last observation but the number of expected // tasks that will be processed in 1 second. // For this reason, if we sum all the bandwidths in // the result observation file, we may have an higher // number than the number of tasks. sample.bandwidth = ws.bandwidthTotal; sample.latency = ws.latency; if(_counter){ _counter->reset(); } _samples->add(sample); DEBUGB(samplesFile << *_samples << "\n"); } template <typename lb_t, typename gt_t> bool ManagerFarm<lb_t, gt_t>::persist() const{ bool r = false; switch(_p.strategyPersistence){ case STRATEGY_PERSISTENCE_SAMPLES:{ r = _samples->size() < _p.persistenceValue; }break; case STRATEGY_PERSISTENCE_TASKS:{ r = _totalTasks < _p.persistenceValue; }break; case STRATEGY_PERSISTENCE_VARIATION:{ const MonitoredSample& variation = _samples->coefficientVariation(); r = getPrimaryValue(variation) < _p.persistenceValue && getSecondaryValue(variation) < _p.persistenceValue; }break; } return r; } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::initPredictors(){ if(_p.strategyCalibration == STRATEGY_CALIBRATION_RANDOM){ ; //CREARE TODO: Ci deve sempre essere un calibratore }else{ switch(_p.strategyPrediction){ case STRATEGY_PREDICTION_SIMPLE:{ _calibrator = new CalibratorDummy(_p, _configuration, _samples); }break; case STRATEGY_PREDICTION_REGRESSION_LINEAR:{ _calibrator = new CalibratorLowDiscrepancy(_p, _configuration, _samples); }break; } } } static Parameters& validate(Parameters& p){ ParametersValidation apv = p.validate(); if(apv != VALIDATION_OK){ throw runtime_error("Invalid adaptivity parameters: " + std::to_string(apv)); } return p; } static std::vector<AdaptiveNode*> convertWorkers(svector<ff_node*> w){ std::vector<AdaptiveNode*> r; for(size_t i = 0; i < w.size(); i++){ r.push_back(dynamic_cast<AdaptiveNode*>(w[i])); } return r; } template <typename lb_t, typename gt_t> ManagerFarm<lb_t, gt_t>::ManagerFarm(ff_farm<lb_t, gt_t>* farm, Parameters parameters): _farm(farm), _p(validate(parameters)), _startTimeMs(0), _cpufreq(_p.mammut.getInstanceCpuFreq()), _counter(_p.mammut.getInstanceEnergy()->getCounter()), _task(_p.mammut.getInstanceTask()), _topology(_p.mammut.getInstanceTopology()), _emitter(dynamic_cast<AdaptiveNode*>(_farm->getEmitter())), _collector(dynamic_cast<AdaptiveNode*>(_farm->getCollector())), _activeWorkers(convertWorkers(_farm->getWorkers())), _configuration(_p, _emitter, _collector, _farm->getgt(), _activeWorkers), _samples(NULL), _totalTasks(0), _remainingTasks(0), _deadline(0), _lastStoredSampleMs(0), _calibrator(NULL){ _samples = NULL; switch(_p.strategySmoothing){ case STRATEGY_SMOOTHING_MOVING_AVERAGE:{ _samples = new MovingAverageSimple<MonitoredSample>(_p.smoothingFactor); }break; case STRATEGY_SMOOTHING_EXPONENTIAL:{ _samples = new MovingAverageExponential<MonitoredSample>(_p.smoothingFactor); }break; } DEBUGB(samplesFile.open("samples.csv")); } template <typename lb_t, typename gt_t> ManagerFarm<lb_t, gt_t>::~ManagerFarm(){ delete _samples; if(_calibrator){ delete _calibrator; } DEBUGB(samplesFile.close()); } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::initNodesPreRun() { for (size_t i = 0; i < _activeWorkers.size(); i++) { _activeWorkers.at(i)->initPreRun(_p.mammut, _p.archData.ticksPerNs, NODE_TYPE_WORKER); } if (_emitter) { _emitter->initPreRun(_p.mammut, _p.archData.ticksPerNs, NODE_TYPE_EMITTER); } else { throw runtime_error("Emitter is needed to use the manager."); } if (_collector) { _collector->initPreRun(_p.mammut, _p.archData.ticksPerNs, NODE_TYPE_COLLECTOR); } } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::initNodesPostRun() { for (size_t i = 0; i < _activeWorkers.size(); i++) { _activeWorkers.at(i)->initPostRun(); } _emitter->initPostRun(); if (_collector) { _collector->initPostRun(); } } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::cleanNodes() { for (size_t i = 0; i < _activeWorkers.size(); i++) { _activeWorkers.at(i)->clean(); } if (_emitter) { _emitter->clean(); } if (_collector) { _collector->clean(); } } template <typename lb_t, typename gt_t> void ManagerFarm<lb_t, gt_t>::run(){ initNodesPreRun(); _farm->run_then_freeze(); initNodesPostRun(); if(_p.contractType != CONTRACT_NONE){ _configuration.maxAllKnobs(); } _startTimeMs = getMillisecondsTime(); if(_counter){ _counter->reset(); } _lastStoredSampleMs = _startTimeMs; if(_p.observer){ _p.observer->_startMonitoringMs = _lastStoredSampleMs; } if(_p.contractType == CONTRACT_PERF_COMPLETION_TIME){ _remainingTasks = _p.expectedTasksNumber; _deadline = getMillisecondsTime()/1000.0 + _p.requiredCompletionTime; } initPredictors(); double microsecsSleep = 0; if(_p.contractType == CONTRACT_NONE){ _farm->wait(); storeNewSample(); observe(); }else{ /* Force the first calibration point. **/ assert(_calibrator); changeKnobs(); double startSample = getMillisecondsTime(); while(!terminated()){ double overheadMs = getMillisecondsTime() - startSample; microsecsSleep = ((double)_p.samplingInterval - overheadMs)* (double)MAMMUT_MICROSECS_IN_MILLISEC; if(microsecsSleep < 0){ microsecsSleep = 0; } usleep(microsecsSleep); startSample = getMillisecondsTime(); storeNewSample(); DEBUG("New sample stored."); if(_p.contractType == CONTRACT_PERF_COMPLETION_TIME){ double now = getMillisecondsTime()/1000.0; if(now >= _deadline){ _p.requiredBandwidth = numeric_limits<double>::max(); }else{ _p.requiredBandwidth = _remainingTasks / (_deadline - now); } } observe(); if(!persist()){ assert(_calibrator); changeKnobs(); startSample = getMillisecondsTime(); } } DEBUG("Terminated."); } uint duration = getMillisecondsTime() - _startTimeMs; if(_p.observer){ vector<CalibrationStats> cs; if(_calibrator){ cs = _calibrator->getCalibrationsStats(); _p.observer->calibrationStats(cs, duration); } _p.observer->summaryStats(cs, duration); } cleanNodes(); } } <|endoftext|>
<commit_before>/* Copyright (C) 2016 Martin Albrecht This file is part of fplll. fplll is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. fplll is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with fplll. If not, see <http://www.gnu.org/licenses/>. */ #include "io/json.hpp" #include <cstring> #include <fplll.h> using json = nlohmann::json; #ifndef TESTDATADIR #define TESTDATADIR ".." #endif using namespace std; using namespace fplll; template <class ZT> void read_matrix(ZZ_mat<ZT> &A, const char *input_filename) { istream *is = new ifstream(input_filename); *is >> A; delete is; } /** @brief Test BKZ reduction. @param A test matrix @param block_size block size @param float_type floating point type to test @param flags flags to use @param prec precision if mpfr is used @return zero on success. */ template <class ZT> int test_bkz(ZZ_mat<ZT> &A, const int block_size, FloatType float_type, int flags = BKZ_DEFAULT, int prec = 0) { int status = 0; // zero on success status = bkz_reduction(A, block_size, flags, float_type, prec); if (status != RED_SUCCESS) { cerr << "BKZ reduction failed with error '" << get_red_status_str(status); cerr << " for float type " << FLOAT_TYPE_STR[float_type] << endl; } return status; } /** @brief Test BKZ strategy interface. @param A test matrix @param block_size block size @return zero on success. */ template <class ZT> int test_bkz_param(ZZ_mat<ZT> &A, const int block_size, int flags = BKZ_DEFAULT) { int status = 0; vector<Strategy> strategies; for (long b = 0; b <= block_size; b++) { Strategy strategy = Strategy::EmptyStrategy(b); if (b == 10) { strategy.preprocessing_block_sizes.emplace_back(5); } else if (b == 20) { strategy.preprocessing_block_sizes.emplace_back(10); } else if (b == 30) { strategy.preprocessing_block_sizes.emplace_back(15); } strategies.emplace_back(std::move(strategy)); } BKZParam params(block_size, strategies); params.flags = flags; // zero on success status = bkz_reduction(&A, NULL, params, FT_DEFAULT, 53); if (status != RED_SUCCESS) { cerr << "BKZ parameter test failed with error '" << get_red_status_str(status) << "'" << endl; } return status; } /** @brief Test BKZ with pruning. @param A test matrix @param block_size block size @return zero on success. */ template <class ZT> int test_bkz_param_linear_pruning(ZZ_mat<ZT> &A, const int block_size, int flags = BKZ_DEFAULT) { int status = 0; vector<Strategy> strategies; for (long b = 0; b < block_size; b++) { Strategy strategy = Strategy::EmptyStrategy(b); if (b == 10) { strategy.preprocessing_block_sizes.emplace_back(5); } else if (b == 20) { strategy.preprocessing_block_sizes.emplace_back(10); } else if (b == 30) { strategy.preprocessing_block_sizes.emplace_back(15); } strategies.emplace_back(std::move(strategy)); } Strategy strategy; strategy.pruning_parameters.emplace_back(Pruning::LinearPruning(block_size, block_size / 2)); strategies.emplace_back(std::move(strategy)); BKZParam params(block_size, strategies); params.flags = flags; // zero on success status = bkz_reduction(&A, NULL, params, FT_DEFAULT, 53); if (status != RED_SUCCESS) { cerr << "BKZ parameter test failed with error '" << get_red_status_str(status) << "'" << endl; } return status; } template <class ZT> int test_bkz_param_pruning(ZZ_mat<ZT> &A, const int block_size, int flags = BKZ_DEFAULT) { int status = 0; vector<Strategy> strategies = load_strategies_json(TESTDATADIR "/strategies/default.json"); BKZParam params(block_size, strategies); params.flags = flags; // zero on success status = bkz_reduction(&A, NULL, params, FT_DEFAULT, 53); if (status != RED_SUCCESS) { cerr << "BKZ parameter test failed with error '" << get_red_status_str(status) << "'" << endl; } return status; } /** @brief Test BKZ for matrix stored in file pointed to by `input_filename`. @param input_filename a path */ int test_filename_bkz_dump_gso(const char *input_filename) { ZZ_mat<mpz_t> A; read_matrix(A, input_filename); json js; std::ifstream fs("gso.json"); if (fs.fail()) { return 1; } fs >> js; int loop = -1; double time = 0.0; for (auto i : js) { // Verify if there are as much norms as there are rows in A if (A.get_rows() != (int)i["norms"].size()) { return 1; } // Extract data from json file const string step_js = i["step"]; const int loop_js = i["loop"]; const double time_js = i["time"]; // Verify if loop of Input and Output have loop = -1 if (step_js.compare("Input") == 0 || step_js.compare("Output") == 0) { if (loop_js != -1) { return 1; } } else { // Verify that loop increases loop++; if (loop_js != loop) { return 1; } // Verify that time increases if (time > time_js) { return 1; } time = time_js; } } return 0; } /** @brief Test BKZ for matrix stored in file pointed to by `input_filename`. @param input_filename a path @param block_size block size @param float_type floating point type to test @param flags flags to use @param prec precision if mpfr is used @return zero on success */ template <class ZT> int test_filename(const char *input_filename, const int block_size, FloatType float_type = FT_DEFAULT, int flags = BKZ_DEFAULT, int prec = 0) { ZZ_mat<ZT> A, B; read_matrix(A, input_filename); B = A; int status = 0; status |= test_bkz<ZT>(A, block_size, float_type, flags, prec); status |= test_bkz_param<ZT>(B, block_size); return status; } /** @brief Construct d × (d+1) integer relations matrix with bit size b and test BKZ. @param d dimension @param b bit size @param block_size block size @param float_type floating point type to test @param flags flags to use @param prec precision if mpfr is used @return zero on success */ template <class ZT> int test_int_rel(int d, int b, const int block_size, FloatType float_type = FT_DEFAULT, int flags = BKZ_DEFAULT, int prec = 0) { ZZ_mat<ZT> A, B; A.resize(d, d + 1); A.gen_intrel(b); B = A; int status = 0; status |= test_bkz<ZT>(A, block_size, float_type, flags | BKZ_VERBOSE, prec); status |= test_bkz_param<ZT>(B, block_size); status |= test_bkz_param_linear_pruning<ZT>(B, block_size); status |= test_bkz_param_pruning<ZT>(B, block_size); return status; } int test_linear_dep() { ZZ_mat<mpz_t> A; std::stringstream("[[1 2 3]\n [4 5 6]\n [7 8 9]]\n") >> A; return test_bkz_param<mpz_t>(A, 3); } int main(int /*argc*/, char ** /*argv*/) { int status = 0; status |= test_linear_dep(); status |= test_filename<mpz_t>("lattices/dim55_in", 10, FT_DEFAULT, BKZ_DEFAULT | BKZ_AUTO_ABORT); #ifdef FPLLL_HAVE_QD status |= test_filename<mpz_t>("lattices/dim55_in", 10, FT_DD, BKZ_SD_VARIANT | BKZ_AUTO_ABORT); #endif status |= test_filename<mpz_t>("lattices/dim55_in", 10, FT_DEFAULT, BKZ_SLD_RED); status |= test_filename<mpz_t>("lattices/dim55_in", 20, FT_MPFR, BKZ_DEFAULT | BKZ_AUTO_ABORT, 128); status |= test_filename<mpz_t>("lattices/dim55_in", 20, FT_MPFR, BKZ_SD_VARIANT | BKZ_AUTO_ABORT, 128); status |= test_filename<mpz_t>("lattices/dim55_in", 20, FT_MPFR, BKZ_SLD_RED, 128); status |= test_int_rel<mpz_t>(50, 1000, 10, FT_DOUBLE, BKZ_DEFAULT | BKZ_AUTO_ABORT); status |= test_int_rel<mpz_t>(50, 1000, 10, FT_DOUBLE, BKZ_SD_VARIANT | BKZ_AUTO_ABORT); status |= test_int_rel<mpz_t>(50, 1000, 10, FT_DOUBLE, BKZ_SLD_RED); status |= test_int_rel<mpz_t>(50, 1000, 15, FT_MPFR, BKZ_DEFAULT | BKZ_AUTO_ABORT, 100); status |= test_int_rel<mpz_t>(50, 1000, 15, FT_MPFR, BKZ_SD_VARIANT | BKZ_AUTO_ABORT, 100); status |= test_int_rel<mpz_t>(50, 1000, 15, FT_MPFR, BKZ_SLD_RED, 100); status |= test_int_rel<mpz_t>(30, 2000, 10, FT_DPE, BKZ_DEFAULT | BKZ_AUTO_ABORT); status |= test_int_rel<mpz_t>(30, 2000, 10, FT_DPE, BKZ_SD_VARIANT | BKZ_AUTO_ABORT); status |= test_int_rel<mpz_t>(30, 2000, 10, FT_DPE, BKZ_SLD_RED); status |= test_int_rel<mpz_t>(30, 2000, 10, FT_MPFR, BKZ_DEFAULT | BKZ_AUTO_ABORT, 53); status |= test_int_rel<mpz_t>(30, 2000, 10, FT_MPFR, BKZ_SD_VARIANT | BKZ_AUTO_ABORT, 53); status |= test_int_rel<mpz_t>(30, 2000, 10, FT_MPFR, BKZ_SLD_RED, 53); status |= test_filename<mpz_t>("lattices/example_in", 10); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_DEFAULT, BKZ_SD_VARIANT); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_DEFAULT, BKZ_SLD_RED); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_DOUBLE); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_DOUBLE, BKZ_SD_VARIANT); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_DOUBLE, BKZ_SLD_RED); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_MPFR, BKZ_AUTO_ABORT, 212); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_MPFR, BKZ_SD_VARIANT | BKZ_AUTO_ABORT, 212); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_MPFR, BKZ_SLD_RED | BKZ_AUTO_ABORT, 212); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_DOUBLE); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_DOUBLE, BKZ_SD_VARIANT); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_DOUBLE, BKZ_SLD_RED); // Test BKZ_DUMP_GSO status |= test_filename<mpz_t>("lattices/dim55_in", 10, FT_DEFAULT, BKZ_DEFAULT | BKZ_DUMP_GSO); // Use the produced gso.json of the previous call of test_filename<mpz_t> status |= test_filename_bkz_dump_gso("lattices/dim55_in"); if (status == 0) { cerr << "All tests passed." << endl; return 0; } else { return -1; } return 0; } <commit_msg>Verbose if errors to check gso.json consistency.<commit_after>/* Copyright (C) 2016 Martin Albrecht This file is part of fplll. fplll is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. fplll is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with fplll. If not, see <http://www.gnu.org/licenses/>. */ #include "io/json.hpp" #include <cstring> #include <fplll.h> using json = nlohmann::json; #ifndef TESTDATADIR #define TESTDATADIR ".." #endif using namespace std; using namespace fplll; template <class ZT> void read_matrix(ZZ_mat<ZT> &A, const char *input_filename) { istream *is = new ifstream(input_filename); *is >> A; delete is; } /** @brief Test BKZ reduction. @param A test matrix @param block_size block size @param float_type floating point type to test @param flags flags to use @param prec precision if mpfr is used @return zero on success. */ template <class ZT> int test_bkz(ZZ_mat<ZT> &A, const int block_size, FloatType float_type, int flags = BKZ_DEFAULT, int prec = 0) { int status = 0; // zero on success status = bkz_reduction(A, block_size, flags, float_type, prec); if (status != RED_SUCCESS) { cerr << "BKZ reduction failed with error '" << get_red_status_str(status); cerr << " for float type " << FLOAT_TYPE_STR[float_type] << endl; } return status; } /** @brief Test BKZ strategy interface. @param A test matrix @param block_size block size @return zero on success. */ template <class ZT> int test_bkz_param(ZZ_mat<ZT> &A, const int block_size, int flags = BKZ_DEFAULT) { int status = 0; vector<Strategy> strategies; for (long b = 0; b <= block_size; b++) { Strategy strategy = Strategy::EmptyStrategy(b); if (b == 10) { strategy.preprocessing_block_sizes.emplace_back(5); } else if (b == 20) { strategy.preprocessing_block_sizes.emplace_back(10); } else if (b == 30) { strategy.preprocessing_block_sizes.emplace_back(15); } strategies.emplace_back(std::move(strategy)); } BKZParam params(block_size, strategies); params.flags = flags; // zero on success status = bkz_reduction(&A, NULL, params, FT_DEFAULT, 53); if (status != RED_SUCCESS) { cerr << "BKZ parameter test failed with error '" << get_red_status_str(status) << "'" << endl; } return status; } /** @brief Test BKZ with pruning. @param A test matrix @param block_size block size @return zero on success. */ template <class ZT> int test_bkz_param_linear_pruning(ZZ_mat<ZT> &A, const int block_size, int flags = BKZ_DEFAULT) { int status = 0; vector<Strategy> strategies; for (long b = 0; b < block_size; b++) { Strategy strategy = Strategy::EmptyStrategy(b); if (b == 10) { strategy.preprocessing_block_sizes.emplace_back(5); } else if (b == 20) { strategy.preprocessing_block_sizes.emplace_back(10); } else if (b == 30) { strategy.preprocessing_block_sizes.emplace_back(15); } strategies.emplace_back(std::move(strategy)); } Strategy strategy; strategy.pruning_parameters.emplace_back(Pruning::LinearPruning(block_size, block_size / 2)); strategies.emplace_back(std::move(strategy)); BKZParam params(block_size, strategies); params.flags = flags; // zero on success status = bkz_reduction(&A, NULL, params, FT_DEFAULT, 53); if (status != RED_SUCCESS) { cerr << "BKZ parameter test failed with error '" << get_red_status_str(status) << "'" << endl; } return status; } template <class ZT> int test_bkz_param_pruning(ZZ_mat<ZT> &A, const int block_size, int flags = BKZ_DEFAULT) { int status = 0; vector<Strategy> strategies = load_strategies_json(TESTDATADIR "/strategies/default.json"); BKZParam params(block_size, strategies); params.flags = flags; // zero on success status = bkz_reduction(&A, NULL, params, FT_DEFAULT, 53); if (status != RED_SUCCESS) { cerr << "BKZ parameter test failed with error '" << get_red_status_str(status) << "'" << endl; } return status; } /** @brief Test BKZ for matrix stored in file pointed to by `input_filename`. @param input_filename a path */ int test_filename_bkz_dump_gso(const char *input_filename) { ZZ_mat<mpz_t> A; read_matrix(A, input_filename); json js; std::ifstream fs("gso.json"); if (fs.fail()) { cerr << "File cannot be loaded." << endl; return 1; } fs >> js; int loop = -1; double time = 0.0; for (auto i : js) { // Verify if there are as much norms as there are rows in A if (A.get_rows() != (int)i["norms"].size()) { cerr << "Array norms does not contains enough value." << endl; return 1; } // Extract data from json file const string step_js = i["step"]; const int loop_js = i["loop"]; const double time_js = i["time"]; // Verify if loop of Input and Output have loop = -1 if (step_js.compare("Input") == 0 || step_js.compare("Output") == 0) { if (loop_js != -1) { cerr << "Steps Input or Output are not with \"loop\" = -1." << endl; return 1; } } else { // Verify that loop increases loop++; if (loop_js != loop) { cerr << "Loop does not increase." << endl; return 1; } // Verify that time increases if (time > time_js) { cerr << "Time does not increase." << endl; return 1; } time = time_js; } } return 0; } /** @brief Test BKZ for matrix stored in file pointed to by `input_filename`. @param input_filename a path @param block_size block size @param float_type floating point type to test @param flags flags to use @param prec precision if mpfr is used @return zero on success */ template <class ZT> int test_filename(const char *input_filename, const int block_size, FloatType float_type = FT_DEFAULT, int flags = BKZ_DEFAULT, int prec = 0) { ZZ_mat<ZT> A, B; read_matrix(A, input_filename); B = A; int status = 0; status |= test_bkz<ZT>(A, block_size, float_type, flags, prec); status |= test_bkz_param<ZT>(B, block_size); return status; } /** @brief Construct d × (d+1) integer relations matrix with bit size b and test BKZ. @param d dimension @param b bit size @param block_size block size @param float_type floating point type to test @param flags flags to use @param prec precision if mpfr is used @return zero on success */ template <class ZT> int test_int_rel(int d, int b, const int block_size, FloatType float_type = FT_DEFAULT, int flags = BKZ_DEFAULT, int prec = 0) { ZZ_mat<ZT> A, B; A.resize(d, d + 1); A.gen_intrel(b); B = A; int status = 0; status |= test_bkz<ZT>(A, block_size, float_type, flags | BKZ_VERBOSE, prec); status |= test_bkz_param<ZT>(B, block_size); status |= test_bkz_param_linear_pruning<ZT>(B, block_size); status |= test_bkz_param_pruning<ZT>(B, block_size); return status; } int test_linear_dep() { ZZ_mat<mpz_t> A; std::stringstream("[[1 2 3]\n [4 5 6]\n [7 8 9]]\n") >> A; return test_bkz_param<mpz_t>(A, 3); } int main(int /*argc*/, char ** /*argv*/) { int status = 0; status |= test_linear_dep(); status |= test_filename<mpz_t>("lattices/dim55_in", 10, FT_DEFAULT, BKZ_DEFAULT | BKZ_AUTO_ABORT); #ifdef FPLLL_HAVE_QD status |= test_filename<mpz_t>("lattices/dim55_in", 10, FT_DD, BKZ_SD_VARIANT | BKZ_AUTO_ABORT); #endif status |= test_filename<mpz_t>("lattices/dim55_in", 10, FT_DEFAULT, BKZ_SLD_RED); status |= test_filename<mpz_t>("lattices/dim55_in", 20, FT_MPFR, BKZ_DEFAULT | BKZ_AUTO_ABORT, 128); status |= test_filename<mpz_t>("lattices/dim55_in", 20, FT_MPFR, BKZ_SD_VARIANT | BKZ_AUTO_ABORT, 128); status |= test_filename<mpz_t>("lattices/dim55_in", 20, FT_MPFR, BKZ_SLD_RED, 128); status |= test_int_rel<mpz_t>(50, 1000, 10, FT_DOUBLE, BKZ_DEFAULT | BKZ_AUTO_ABORT); status |= test_int_rel<mpz_t>(50, 1000, 10, FT_DOUBLE, BKZ_SD_VARIANT | BKZ_AUTO_ABORT); status |= test_int_rel<mpz_t>(50, 1000, 10, FT_DOUBLE, BKZ_SLD_RED); status |= test_int_rel<mpz_t>(50, 1000, 15, FT_MPFR, BKZ_DEFAULT | BKZ_AUTO_ABORT, 100); status |= test_int_rel<mpz_t>(50, 1000, 15, FT_MPFR, BKZ_SD_VARIANT | BKZ_AUTO_ABORT, 100); status |= test_int_rel<mpz_t>(50, 1000, 15, FT_MPFR, BKZ_SLD_RED, 100); status |= test_int_rel<mpz_t>(30, 2000, 10, FT_DPE, BKZ_DEFAULT | BKZ_AUTO_ABORT); status |= test_int_rel<mpz_t>(30, 2000, 10, FT_DPE, BKZ_SD_VARIANT | BKZ_AUTO_ABORT); status |= test_int_rel<mpz_t>(30, 2000, 10, FT_DPE, BKZ_SLD_RED); status |= test_int_rel<mpz_t>(30, 2000, 10, FT_MPFR, BKZ_DEFAULT | BKZ_AUTO_ABORT, 53); status |= test_int_rel<mpz_t>(30, 2000, 10, FT_MPFR, BKZ_SD_VARIANT | BKZ_AUTO_ABORT, 53); status |= test_int_rel<mpz_t>(30, 2000, 10, FT_MPFR, BKZ_SLD_RED, 53); status |= test_filename<mpz_t>("lattices/example_in", 10); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_DEFAULT, BKZ_SD_VARIANT); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_DEFAULT, BKZ_SLD_RED); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_DOUBLE); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_DOUBLE, BKZ_SD_VARIANT); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_DOUBLE, BKZ_SLD_RED); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_MPFR, BKZ_AUTO_ABORT, 212); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_MPFR, BKZ_SD_VARIANT | BKZ_AUTO_ABORT, 212); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_MPFR, BKZ_SLD_RED | BKZ_AUTO_ABORT, 212); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_DOUBLE); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_DOUBLE, BKZ_SD_VARIANT); status |= test_filename<mpz_t>("lattices/example_in", 10, FT_DOUBLE, BKZ_SLD_RED); // Test BKZ_DUMP_GSO status |= test_filename<mpz_t>("lattices/dim55_in", 10, FT_DEFAULT, BKZ_DEFAULT | BKZ_DUMP_GSO); // Use the produced gso.json of the previous call of test_filename<mpz_t> status |= test_filename_bkz_dump_gso("lattices/dim55_in"); if (status == 0) { cerr << "All tests passed." << endl; return 0; } else { return -1; } return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include "map.h" #include "../common/grid_iterator.h" namespace game { Terrain make_flat_terrain(int alt, int w, int h) { auto terrain = Terrain{}; for(int i = 0; i < h; ++i) { terrain.altitude.emplace_back(); for(int j = 0; j < w; ++j) { terrain.altitude.back().push_back(alt); } } terrain.w = w; terrain.h = h; return terrain; } Terrain make_terrain_from_heightmap(Software_Texture const& tex, int add) { auto ret = Terrain{}; ret.w = tex.allocated_extents().x; ret.h = tex.allocated_extents().y; for(int i = 0; i < ret.h; ++i) { ret.altitude.emplace_back(); for(int j = 0; j < ret.w; ++j) { // Just use the red color. auto col = tex.get_pt({i, j}); ret.altitude.back().push_back((int) col.r + add); } } return ret; } Mesh_Data make_terrain_mesh(Terrain const& t, double scale_fac, double flat_fac) noexcept { std::array<Vertex, 4> vertices; std::vector<unsigned int> faces { 1, 3, 2, 0, 1, 2 }; vertices[0].position = {0.0, 0.0, 1.0}; vertices[1].position = {0.0, 0.0, 0.0}; vertices[2].position = {1.0, 0.0, 1.0}; vertices[3].position = {1.0, 0.0, 0.0}; vertices[0].uv = {0.0, 1.0}; vertices[1].uv = {0.0, 0.0}; vertices[2].uv = {1.0, 1.0}; vertices[3].uv = {1.0, 0.0}; auto mesh = Mesh_Data{}; // Add some amount of rectangles, then adjust their height. // Doesn't work when t.h or t.w == 1 or 0 auto iteration = 0; for(int i = 0; i < t.h - 1; ++i) { for(int j = 0; j < t.w - 1; ++j) { std::array<Vertex, 4> mod_verts = vertices; for(auto& vertex : mod_verts) { // Scale the width and depth by flat_fac and the height by scale_fac. // We also translate the squares based on their position on the grid. vertex.position.x = (vertex.position.x + j) * flat_fac; vertex.position.y = t.altitude[i][j] * scale_fac; vertex.position.z = (vertex.position.z + i) * flat_fac; } using std::end; // Insert the vertices. mesh.vertices.insert(end(mesh.vertices), begin(mod_verts), end(mod_verts)); for(auto face : faces) { // Adjust the face by our current iteration. mesh.elements.push_back(face + vertices.size() * iteration); } ++iteration; } } // Change the mesh defaults, of course the user can just switch these as // soon as they get ahold of the mesh. mesh.usage_hint = Usage_Hint::Draw; mesh.upload_hint = Upload_Hint::Static; mesh.primitive = Primitive_Type::Triangle; return mesh; } Structure_Instance:: Structure_Instance(IStructure& s, Orient o) noexcept : structure_type(&s), obj(structure_type->make_obj()), orientation(o) {} Structure_Instance::Structure_Instance(Structure_Instance const& s) noexcept : structure_type(s.structure_type), obj(share_object_keep_ownership(s.obj)), orientation(s.orientation) {} Structure_Instance& Structure_Instance:: operator=(Structure_Instance const& i) noexcept { structure_type = i.structure_type; obj = share_object_keep_ownership(i.obj); orientation = i.orientation; return *this; } } <commit_msg>Much improved terrain -> mesh code.<commit_after>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include "map.h" #include "../common/grid_iterator.h" namespace game { Terrain make_flat_terrain(int alt, int w, int h) { auto terrain = Terrain{}; for(int i = 0; i < h; ++i) { terrain.altitude.emplace_back(); for(int j = 0; j < w; ++j) { terrain.altitude.back().push_back(alt); } } terrain.w = w; terrain.h = h; return terrain; } Terrain make_terrain_from_heightmap(Software_Texture const& tex, int add) { auto ret = Terrain{}; ret.w = tex.allocated_extents().x; ret.h = tex.allocated_extents().y; for(int i = 0; i < ret.h; ++i) { ret.altitude.emplace_back(); for(int j = 0; j < ret.w; ++j) { // Just use the red color. auto col = tex.get_pt({i, j}); ret.altitude.back().push_back((int) col.r + add); } } return ret; } Mesh_Data make_terrain_mesh(Terrain const& t, double scale_fac, double flat_fac) noexcept { auto mesh = Mesh_Data{}; // Add a vertex with a given height for each altitude given. for(int i = 0; i < t.h; ++i) { for(int j = 0; j < t.w; ++j) { Vertex v; v.normal = glm::vec3(0.0f, 1.0f, 0.0f); v.uv = glm::vec2(0.0f, 0.0f); v.position.x = j * flat_fac; v.position.y = t.altitude[i][j] * scale_fac; v.position.z = i * flat_fac; mesh.vertices.push_back(v); } } // Add faces. std::array<unsigned int, 6> face_indices{ 0, 3, 2, 0, 1, 2 }; // For the amount of rectangles. int num_rects = (t.w - 1) * (t.h - 1); for(int i = 0; i < num_rects; ++i) { int x = i % t.w; int y = i / t.w; if(x == t.w - 1 || y == t.h - 1) { // If we are at the last vertex, just bail out. Trying to make a face // here will make one across the mesh which would be terrible. continue; } mesh.elements.push_back(x + 0 + y * t.w); mesh.elements.push_back(x + 1 + (y + 1) * t.w); mesh.elements.push_back(x + 1 + y * t.w); mesh.elements.push_back(x + 0 + y * t.w); mesh.elements.push_back(x + 0 + (y + 1) * t.w); mesh.elements.push_back(x + 1 + (y + 1) * t.w); } // Set the uv coordinates over the whole mesh. for(int i = 0; i < t.h; ++i) { for(int j = 0; j < t.w; ++j) { mesh.vertices[i * t.w + j].uv = glm::vec2((float) j / t.w, (float) i / t.h); } } // Change the mesh defaults, of course the user can just switch these as // soon as they get ahold of the mesh. mesh.usage_hint = Usage_Hint::Draw; mesh.upload_hint = Upload_Hint::Static; mesh.primitive = Primitive_Type::Triangle; return mesh; } Structure_Instance:: Structure_Instance(IStructure& s, Orient o) noexcept : structure_type(&s), obj(structure_type->make_obj()), orientation(o) {} Structure_Instance::Structure_Instance(Structure_Instance const& s) noexcept : structure_type(s.structure_type), obj(share_object_keep_ownership(s.obj)), orientation(s.orientation) {} Structure_Instance& Structure_Instance:: operator=(Structure_Instance const& i) noexcept { structure_type = i.structure_type; obj = share_object_keep_ownership(i.obj); orientation = i.orientation; return *this; } } <|endoftext|>
<commit_before>#include "functions.hpp" ///data base #include <Socket/client/Client.hpp> #include <Socket/server/Server.hpp> #include <Socket/FuncWrapper.hpp> #include <Salamandre-daemon/GuiFunctions.hpp> #include <iostream> #include <list> #define SERVER_PORT 4321 #define PRINT_ERROR std::cout<<"Aucune action corespond à la demmande \""<<c<<"\""<<std::endl #define BACK std::cout<<"Retour au menu précédant" <<std::endl; void run(ntw::cli::Client& cli); int check_status(ntw::cli::Client& cli);///< return 0 if ok, -1 if srv down, 1 on other errors (and print it) int notification_dispatch(int id,ntw::SocketSerialized& request);///< dispatch function for notifier int main(int argc,char* argv[]) { if(argc < 2) { std::cout<<"Usage are: "<<argv[0]<<" <server-port>"<<std::endl; return 1; } ntw::Socket::init(); ntw::cli::Client client; if(client.connect("127.0.0.1",atoi(argv[1])) != NTW_ERROR_CONNEXION) { //init notification listener ntw::srv::Server notification_srv(SERVER_PORT,"127.0.0.1",notification_dispatch,1,1); //notification_srv.on_new_client = void (*)(ntw::srv::Server& self,ntw::srv::Client& client); //notification_srv.on_delete_client = void (*)(ntw::srv::Server& self,ntw::srv::Client& client); notification_srv.start(); //set the connect port on daémon side client.call<void>(salamandre::gui::func::setGuiNotificationPort,SERVER_PORT); if(check_status(client) < 0) { std::cout<<"Error on init notification server"<<std::endl; exit(1); } //start run(client); //wait for end notification_srv.stop(); notification_srv.wait(); } ntw::Socket::close(); return 0; } void run(ntw::cli::Client& client) { int id_medecin, id_patient; std::cout<<"Id medecin:\n>"; std::cin>>id_medecin; std::cout<<"Id patient:\n>"; std::cin>>id_patient; std::vector<std::string> file_paths; std::vector<std::string> file_to_signal; std::string daemon_path = client.call<std::string>(salamandre::gui::func::getMyPath); char c = 0; while(c!= 'Q' and c != 'q') { std::cout<< "==========================\n" "=== Choisir une action ===\n" "==========================\n" "\t[1] Créer les fiches client\n" "\t[2] Déplacer des fiches vers le dossier de sauvgarde\n" "\t[3] Signaler la présence de nouveaux fichiers\n" "\t[4] Demmander une récupération de ficher\n" "\t[5] Verifier si une update est en cour\n" "\t[6] Voir la liste des fichier à sauver\n" "\t[7] Voir le path du server\n" "\t[Q/q] Quitter\n>"; std::cin>>c; std::cout<<std::endl; switch(c) { case '1' ://créer fiches { while(c != 'q' and c != 'Q') { std::cout<< "---------------------\n" "--- Fiche à créer ---\n" "---------------------\n" "\t[1] test1\n" "\t[2] test2\n" "\t[3] test3\n" "\t[4] test4\n" "\t[5] test[1~4]\n" "\t[6] Autre nom\n" "\t[Q/q] Retour\n>"; std::cin>>c; std::cout<<std::endl; switch(c) { case '1'://test1 { test::createFile(id_medecin,id_patient,"test1",file_paths); }break; case '2'://test2 { test::createFile(id_medecin,id_patient,"test2",file_paths); }break; case '3'://test3 { test::createFile(id_medecin,id_patient,"test3",file_paths); }break; case '4'://test4 { test::createFile(id_medecin,id_patient,"test4",file_paths); }break; case '5'://test[1~4] { test::createFile(id_medecin,id_patient,"test1",file_paths); test::createFile(id_medecin,id_patient,"test2",file_paths); test::createFile(id_medecin,id_patient,"test3",file_paths); test::createFile(id_medecin,id_patient,"test4",file_paths); }break; case '6'://autre { std::cout<<"Nom du fichier à créer\n>"; std::string s; std::cin>>s; test::createFile(id_medecin,id_patient,s,file_paths); }break; case 'q'://quitter case 'Q': { BACK; }break; default: { PRINT_ERROR; }break; } } c=0; }break; case '2': //déplacer vers save for(auto& file : file_paths) test::moveForSave(id_medecin,id_patient,file,file_to_signal); file_paths.clear(); { }break; case '3': //signaler nouveau fichiers { for(auto& file : file_to_signal) { client.call<void>(salamandre::gui::func::newFile,id_medecin,id_patient,file); if(check_status(client) < 0) { std::cout<<"ERROR on send new file info("<<file<<")"<<std::endl; exit(2); } client.request_sock.clear(); } file_to_signal.clear(); }break; case '4'://recupération { while(c != 'q' and c != 'Q') { std::cout<< "----------------------------\n" "--- Fichiers à récupérer ---\n" "----------------------------\n" "\t[1] test1\n" "\t[2] test2\n" "\t[3] test3\n" "\t[4] test4\n" "\t[5] test[1~4]\n" "\t[6] Autre nom\n" "\t[7] Tous ceux du patient\n" "\t[8] Tous ceux du medecin\n" "\t[Q/q] Retour\n>"; std::cin>>c; std::cout<<std::endl; std::list<std::string> files; switch(c) { case '1'://test1 { files.push_back("test1"); }break; case '2'://test2 { files.push_back("test2"); }break; case '3'://test3 { files.push_back("test3"); }break; case '4'://test4 { files.push_back("test4"); }break; case '5'://test[1~4] { files.push_back("test1"); files.push_back("test2"); files.push_back("test3"); files.push_back("test4"); }break; case '6'://autre { std::cout<<"Nom du fichier à créer\n>"; std::string s; std::cin>>s; files.push_back(s); }break; case '7': //Tous ceux du patient { client.call<void>(salamandre::gui::func::sync,id_medecin,id_patient,""); if(check_status(client) < 0) { std::cout<<"ERROR on ask for an sync on all file of the patient ("<<id_patient<<")"<<std::endl; exit(3); } client.request_sock.clear(); }break; case '8':/// Tous ceux du medecin { client.call<void>(salamandre::gui::func::sync,id_medecin,-1,""); if(check_status(client) < 0) { std::cout<<"ERROR on ask for an sync on all file of the medecin ("<<id_medecin<<")"<<std::endl; exit(4); } client.request_sock.clear(); }break; case 'q'://quitter case 'Q': { BACK; }break; default: { PRINT_ERROR; }break; } //ask for sync on files for(auto& file : files) { client.call<void>(salamandre::gui::func::sync,id_medecin,id_patient,file); if(check_status(client) < 0) { std::cout<<"ERROR on ask for an sync on file("<<file<<")"<<std::endl; exit(5); } client.request_sock.clear(); } } }break; case '5': ///update en cour { while(c != 'q' and c != 'Q') { std::cout<< "----------------------\n" "--- Update en cour ---\n" "----------------------\n" "\t[1] test1\n" "\t[2] test2\n" "\t[3] test3\n" "\t[4] test4\n" "\t[5] Autre nom\n" "\t[6] Tous ceux du patient\n" "\t[7] Tous ceux du medecin\n" "\t[Q/q] Retour\n>"; std::cin>>c; std::cout<<std::endl; std::list<std::string> files; bool up = false; switch(c) { case '1'://test1 { up = client.call<bool>(salamandre::gui::func::sync,id_medecin,id_patient,"test1"); }break; case '2'://test2 { up = client.call<bool>(salamandre::gui::func::sync,id_medecin,id_patient,"test2"); }break; case '3'://test3 { up = client.call<bool>(salamandre::gui::func::sync,id_medecin,id_patient,"test3"); }break; case '4'://test4 { up = client.call<bool>(salamandre::gui::func::sync,id_medecin,id_patient,"test4"); }break; case '5'://autre { std::cout<<"Nom du fichier à créer\n>"; std::string s; std::cin>>s; up = client.call<bool>(salamandre::gui::func::sync,id_medecin,id_patient,s); }break; case '6': //Tous ceux du patient { up = client.call<bool>(salamandre::gui::func::sync,id_medecin,id_patient,""); }break; case '7':/// Tous ceux du medecin { up = client.call<bool>(salamandre::gui::func::sync,id_medecin-1,""); }break; case 'q'://quitter case 'Q': { BACK; }break; default: { PRINT_ERROR; }break; } if(c>=1 and c <=6) { if(check_status(client) < 0) { std::cout<<"ERROR on ask for is_update"<<std::endl; exit(2); } else std::cout<<"Update: "<<(up?"Oui":"Non")<<std::endl; client.request_sock.clear(); } } }break; case '6': //print file list { for(auto& file : file_paths) std::cout<<"-\""<<ROOT_DIR<<id_medecin<<"/"<<id_patient<<"/"<<file<<"\""<<std::endl; }break; case '7': //print daemon_path { std::cout<<"Daemon path : \""<<daemon_path<<"\""<<std::endl; }break; case 'q': //quitter case 'Q': { std::cout<<"Exit"<<std::endl; }break; default: { PRINT_ERROR; }break; } } } int check_status(ntw::cli::Client& client) { int status = client.request_sock.getStatus(); switch(status) { case salamandre::gui::status::STOP : { std::cerr<<"[ERROR] The server is probably down."<<std::endl; std::cout<<"[Recv] Stop"<<std::endl <<"The programme will now stop"<<std::endl; return -1; }break; case ntw::FuncWrapper::Status::st::ok : { return 0; } default : { std::cout<<"[ERROR] Recv server code <"<<status<<"> whene sending file : "<<salamandre::gui::statusToString(status)<<std::endl; /// server error??? return 1; }break; } } int notification_dispatch(int id,ntw::SocketSerialized& request) { int res= ntw::FuncWrapper::Status::st::wrong_id; std::cout<<"[notification_dispatch] id:"<<id<<std::endl<<std::flush; switch(id) { case salamandre::gui::func::fileIsSend : { res = ntw::FuncWrapper::srv::exec(salamandre::gui::funcFileIsSend,request); }break; case salamandre::gui::func::fileIsRecv : { res = ntw::FuncWrapper::srv::exec(salamandre::gui::funcFileIsRecv,request); }break; default: { std::cout<<"[notification_dispatch] Function id not found"<<std::endl; }break; } return res; } ///\todo TODO namespace salamandre { namespace gui { void funcFileIsSend(ntw::SocketSerialized& sock,int id_medecin, int id_patient, std::string filename) { std::cout<<"File send:"<<id_medecin<<"/"<<id_patient<<"/"<<filename<<std::endl; } void funcFileIsRecv(ntw::SocketSerialized& sock,int id_medecin, int id_patient, std::string filename) { std::cout<<"File recv:"<<id_medecin<<"/"<<id_patient<<"/"<<filename<<std::endl; } } } <commit_msg>update exemple with utils::log<commit_after>#include "functions.hpp" ///data base #include <Socket/client/Client.hpp> #include <Socket/server/Server.hpp> #include <Socket/FuncWrapper.hpp> #include <Salamandre-daemon/GuiFunctions.hpp> #include <utils/log.hpp> #include <iostream> #include <list> #define SERVER_PORT 4321 #define PRINT_ERROR utils::log::error(std::to_string(c),"Aucune action corespond à la demmande"); #define BACK utils::log::info("Retour au menu précédant"); #define COLOR_TITLE utils::log::colors::light_blue #define COLOR_ASK utils::log::colors::light_yellow #define COLOR_RESET utils::log::colors::reset void run(ntw::cli::Client& cli); int check_status(ntw::cli::Client& cli);///< return 0 if ok, -1 if srv down, 1 on other errors (and print it) int notification_dispatch(int id,ntw::SocketSerialized& request);///< dispatch function for notifier int main(int argc,char* argv[]) { if(argc < 2) { std::cout<<"Usage are: "<<argv[0]<<" <server-port>"<<std::endl; return 1; } ntw::Socket::init(); ntw::cli::Client client; if(client.connect("127.0.0.1",atoi(argv[1])) != NTW_ERROR_CONNEXION) { //init notification listener ntw::srv::Server notification_srv(SERVER_PORT,"127.0.0.1",notification_dispatch,1,1); //notification_srv.on_new_client = void (*)(ntw::srv::Server& self,ntw::srv::Client& client); //notification_srv.on_delete_client = void (*)(ntw::srv::Server& self,ntw::srv::Client& client); notification_srv.start(); //set the connect port on daémon side client.call<void>(salamandre::gui::func::setGuiNotificationPort,SERVER_PORT); if(check_status(client) < 0) { utils::log::critical("Error on init notification server",1); } //start run(client); //wait for end notification_srv.stop(); notification_srv.wait(); } ntw::Socket::close(); return 0; } void run(ntw::cli::Client& client) { int id_medecin, id_patient; std::cout<<COLOR_ASK<<"Id medecin:\n>"<<COLOR_RESET; std::cin>>id_medecin; std::cout<<COLOR_ASK<<"Id patient:\n>"<<COLOR_RESET; std::cin>>id_patient; std::vector<std::string> file_paths; std::vector<std::string> file_to_signal; std::string daemon_path = client.call<std::string>(salamandre::gui::func::getMyPath); char c = 0; while(c!= 'Q' and c != 'q') { std::cout<<COLOR_TITLE<< "==========================\n" "=== Choisir une action ===\n" "==========================\n" "\t[1] Créer les fiches client\n" "\t[2] Déplacer des fiches vers le dossier de sauvgarde\n" "\t[3] Signaler la présence de nouveaux fichiers\n" "\t[4] Demmander une récupération de ficher\n" "\t[5] Verifier si une update est en cour\n" "\t[6] Voir la liste des fichier à sauver\n" "\t[7] Voir le path du server\n" "\t[Q/q] Quitter\n>" <<COLOR_RESET; std::cin>>c; std::cout<<std::endl; switch(c) { case '1' ://créer fiches { while(c != 'q' and c != 'Q') { std::cout<<COLOR_TITLE<< "---------------------\n" "--- Fiche à créer ---\n" "---------------------\n" "\t[1] test1\n" "\t[2] test2\n" "\t[3] test3\n" "\t[4] test4\n" "\t[5] test[1~4]\n" "\t[6] Autre nom\n" "\t[Q/q] Retour\n>" <<COLOR_RESET; std::cin>>c; std::cout<<std::endl; switch(c) { case '1'://test1 { test::createFile(id_medecin,id_patient,"test1",file_paths); }break; case '2'://test2 { test::createFile(id_medecin,id_patient,"test2",file_paths); }break; case '3'://test3 { test::createFile(id_medecin,id_patient,"test3",file_paths); }break; case '4'://test4 { test::createFile(id_medecin,id_patient,"test4",file_paths); }break; case '5'://test[1~4] { test::createFile(id_medecin,id_patient,"test1",file_paths); test::createFile(id_medecin,id_patient,"test2",file_paths); test::createFile(id_medecin,id_patient,"test3",file_paths); test::createFile(id_medecin,id_patient,"test4",file_paths); }break; case '6'://autre { std::cout<<COLOR_ASK<<"Nom du fichier à créer\n>"<<COLOR_RESET; std::string s; std::cin>>s; test::createFile(id_medecin,id_patient,s,file_paths); }break; case 'q'://quitter case 'Q': { BACK; }break; default: { PRINT_ERROR; }break; } } c=0; }break; case '2': //déplacer vers save for(auto& file : file_paths) test::moveForSave(id_medecin,id_patient,file,file_to_signal); file_paths.clear(); { }break; case '3': //signaler nouveau fichiers { for(auto& file : file_to_signal) { client.call<void>(salamandre::gui::func::newFile,id_medecin,id_patient,file); if(check_status(client) < 0) { utils::log::critical(file,"ERROR on send new file info",2); } client.request_sock.clear(); } file_to_signal.clear(); }break; case '4'://recupération { while(c != 'q' and c != 'Q') { std::cout<<COLOR_TITLE<< "----------------------------\n" "--- Fichiers à récupérer ---\n" "----------------------------\n" "\t[1] test1\n" "\t[2] test2\n" "\t[3] test3\n" "\t[4] test4\n" "\t[5] test[1~4]\n" "\t[6] Autre nom\n" "\t[7] Tous ceux du patient\n" "\t[8] Tous ceux du medecin\n" "\t[Q/q] Retour\n>" <<COLOR_RESET; std::cin>>c; std::cout<<std::endl; std::list<std::string> files; switch(c) { case '1'://test1 { files.push_back("test1"); }break; case '2'://test2 { files.push_back("test2"); }break; case '3'://test3 { files.push_back("test3"); }break; case '4'://test4 { files.push_back("test4"); }break; case '5'://test[1~4] { files.push_back("test1"); files.push_back("test2"); files.push_back("test3"); files.push_back("test4"); }break; case '6'://autre { std::cout<<COLOR_ASK<<"Nom du fichier à créer\n>"<<COLOR_RESET; std::string s; std::cin>>s; files.push_back(s); }break; case '7': //Tous ceux du patient { client.call<void>(salamandre::gui::func::sync,id_medecin,id_patient,""); if(check_status(client) < 0) { utils::log::critical(std::to_string(id_patient),"ERROR on ask for an sync on all file of the patient",3); } client.request_sock.clear(); }break; case '8':/// Tous ceux du medecin { client.call<void>(salamandre::gui::func::sync,id_medecin,-1,""); if(check_status(client) < 0) { utils::log::critical(std::to_string(id_medecin),"ERROR on ask for an sync on all file of the medecin",4); } client.request_sock.clear(); }break; case 'q'://quitter case 'Q': { BACK; }break; default: { PRINT_ERROR; }break; } //ask for sync on files for(auto& file : files) { client.call<void>(salamandre::gui::func::sync,id_medecin,id_patient,file); if(check_status(client) < 0) { utils::log::critical(file,"ERROR on ask for an sync on file",5); } client.request_sock.clear(); } } }break; case '5': ///update en cour { while(c != 'q' and c != 'Q') { std::cout<<COLOR_TITLE<< "----------------------\n" "--- Update en cour ---\n" "----------------------\n" "\t[1] test1\n" "\t[2] test2\n" "\t[3] test3\n" "\t[4] test4\n" "\t[5] Autre nom\n" "\t[6] Tous ceux du patient\n" "\t[7] Tous ceux du medecin\n" "\t[Q/q] Retour\n>" <<COLOR_RESET; std::cin>>c; std::cout<<std::endl; std::list<std::string> files; bool up = false; switch(c) { case '1'://test1 { up = client.call<bool>(salamandre::gui::func::sync,id_medecin,id_patient,"test1"); }break; case '2'://test2 { up = client.call<bool>(salamandre::gui::func::sync,id_medecin,id_patient,"test2"); }break; case '3'://test3 { up = client.call<bool>(salamandre::gui::func::sync,id_medecin,id_patient,"test3"); }break; case '4'://test4 { up = client.call<bool>(salamandre::gui::func::sync,id_medecin,id_patient,"test4"); }break; case '5'://autre { std::cout<<COLOR_ASK<<"Nom du fichier à créer\n>"<<COLOR_RESET; std::string s; std::cin>>s; up = client.call<bool>(salamandre::gui::func::sync,id_medecin,id_patient,s); }break; case '6': //Tous ceux du patient { up = client.call<bool>(salamandre::gui::func::sync,id_medecin,id_patient,""); }break; case '7':/// Tous ceux du medecin { up = client.call<bool>(salamandre::gui::func::sync,id_medecin-1,""); }break; case 'q'://quitter case 'Q': { BACK; }break; default: { PRINT_ERROR; }break; } if(c>=1 and c <=6) { if(check_status(client) < 0) { utils::log::critical("ERROR on ask for is_update",2); } else std::cout<<"Update: "<<(up?"Oui":"Non")<<std::endl; client.request_sock.clear(); } } }break; case '6': //print file list { for(auto& file : file_paths) std::cout<<"-\""<<ROOT_DIR<<id_medecin<<"/"<<id_patient<<"/"<<file<<"\""<<std::endl; }break; case '7': //print daemon_path { std::cout<<"Daemon path : \""<<daemon_path<<"\""<<std::endl; }break; case 'q': //quitter case 'Q': { std::cout<<"Exit"<<std::endl; }break; default: { PRINT_ERROR; }break; } } } int check_status(ntw::cli::Client& client) { int status = client.request_sock.getStatus(); switch(status) { case salamandre::gui::status::STOP : { std::cerr<<"[ERROR] The server is probably down."<<std::endl; std::cout<<"[Recv] Stop"<<std::endl <<"The programme will now stop"<<std::endl; return -1; }break; case ntw::FuncWrapper::Status::st::ok : { return 0; } default : { std::cout<<"[ERROR] Recv server code <"<<status<<"> whene sending file : "<<salamandre::gui::statusToString(status)<<std::endl; /// server error??? return 1; }break; } } int notification_dispatch(int id,ntw::SocketSerialized& request) { int res= ntw::FuncWrapper::Status::st::wrong_id; std::cout<<"[notification_dispatch] id:"<<id<<std::endl<<std::flush; switch(id) { case salamandre::gui::func::fileIsSend : { res = ntw::FuncWrapper::srv::exec(salamandre::gui::funcFileIsSend,request); }break; case salamandre::gui::func::fileIsRecv : { res = ntw::FuncWrapper::srv::exec(salamandre::gui::funcFileIsRecv,request); }break; default: { std::cout<<"[notification_dispatch] Function id not found"<<std::endl; }break; } return res; } ///\todo TODO namespace salamandre { namespace gui { void funcFileIsSend(ntw::SocketSerialized& sock,int id_medecin, int id_patient, std::string filename) { std::cout<<"File send:"<<id_medecin<<"/"<<id_patient<<"/"<<filename<<std::endl; } void funcFileIsRecv(ntw::SocketSerialized& sock,int id_medecin, int id_patient, std::string filename) { std::cout<<"File recv:"<<id_medecin<<"/"<<id_patient<<"/"<<filename<<std::endl; } } } <|endoftext|>
<commit_before>/* * MIT License * * Copyright (c) 2016 xiongziliang <[email protected]> * * 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 "SSLBox.h" #if defined(ENABLE_OPENSSL) #include <string.h> #include <openssl/ssl.h> #include <openssl/rand.h> #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/conf.h> #include "Util/util.h" #define SSL_BUF_SIZE 1024*4 namespace ZL { namespace Util { mutex *SSL_Initor::_mutexes; SSL_Initor::SSL_Initor() { SSL_library_init(); SSL_load_error_strings(); OpenSSL_add_all_digests(); OpenSSL_add_all_ciphers(); OpenSSL_add_all_algorithms(); _mutexes = new mutex[CRYPTO_num_locks()]; CRYPTO_set_locking_callback([](int mode,int n, const char *file,int line) { if (mode & CRYPTO_LOCK) _mutexes[n].lock(); else _mutexes[n].unlock(); }); CRYPTO_set_id_callback([]() ->unsigned long { #if !defined(_WIN32) return (unsigned long)pthread_self(); #else return (unsigned long)GetCurrentThreadId(); #endif }); ssl_client = SSL_CTX_new(TLSv1_client_method()); ssl_server = SSL_CTX_new(TLSv1_server_method()); setCtx(ssl_client); setCtx(ssl_server); } void SSL_Initor::loadServerPem(const char *keyAndCA_pem, const char *import_pwd){ loadPem(ssl_server,keyAndCA_pem,import_pwd); } void SSL_Initor::loadClientPem(const char *keyAndCA_pem, const char *import_pwd){ loadPem(ssl_client,keyAndCA_pem,import_pwd); } void SSL_Initor::loadPem(SSL_CTX *ctx, const char *keyAndCA_pem,const char *import_pwd) { int errCode = SSL_CTX_use_PrivateKey_file(ctx, keyAndCA_pem,SSL_FILETYPE_PEM); if (errCode != 1) { throw std::runtime_error(std::string("SSL_CTX_use_PrivateKey_file: ") + getLastError()); } errCode = SSL_CTX_use_certificate_file(ctx, keyAndCA_pem,SSL_FILETYPE_PEM); if (errCode != 1) { throw std::runtime_error(std::string("SSL_CTX_use_certificate_chain_file: ")+ getLastError()); } SSL_CTX_set_default_passwd_cb_userdata(ctx, (void *) import_pwd); SSL_CTX_set_default_passwd_cb(ctx,[](char *buf, int size, int rwflag, void *userdata)->int { const char *privateKeyPwd=(const char *)userdata; size_t privateKeyPwd_len=strlen(privateKeyPwd); strncpy(buf, privateKeyPwd, size); buf[size - 1] = '\0'; if (size > (int)privateKeyPwd_len) size = privateKeyPwd_len; return size; }); errCode = SSL_CTX_check_private_key(ctx); if (errCode != 1) { throw std::runtime_error(std::string("SSL_CTX_check_private_key: ") + getLastError()); } } SSL_Initor::~SSL_Initor() { SSL_CTX_free(ssl_client); SSL_CTX_free(ssl_server); EVP_cleanup(); ERR_free_strings(); ERR_clear_error(); ERR_remove_state(0); CRYPTO_set_locking_callback(NULL); //sk_SSL_COMP_free(SSL_COMP_get_compression_methods()); CRYPTO_cleanup_all_ex_data(); CONF_modules_unload(1); CONF_modules_free(); delete[] _mutexes; } void SSL_Initor::setCtx(SSL_CTX *ctx) { SSL_CTX_set_cipher_list(ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); SSL_CTX_set_verify_depth(ctx, 9); SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY); SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF); SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE,[](int ok, X509_STORE_CTX *pStore) { if (!ok) { int depth = X509_STORE_CTX_get_error_depth(pStore); int err = X509_STORE_CTX_get_error(pStore); std::string error(X509_verify_cert_error_string(err)); ErrorL<<depth<<" "<<error<<endl; ok = 1; } return ok; }); } inline std::string SSL_Initor::getLastError(){ unsigned long errCode = ERR_get_error(); if (errCode != 0) { char buffer[256]; ERR_error_string_n(errCode, buffer, sizeof(buffer)); return std::string(buffer); } else return "No error"; } SSL_Box::SSL_Box(bool isServer, bool enable) : _ssl(nullptr), _read_bio(nullptr), _write_bio(nullptr) { _isServer = isServer; _enable = enable; _ssl = SSL_new(_isServer ?SSL_Initor::Instance().ssl_server :SSL_Initor::Instance().ssl_client); _read_bio = BIO_new(BIO_s_mem()); _write_bio = BIO_new(BIO_s_mem()); SSL_set_bio(_ssl, _read_bio, _write_bio); _isServer ? SSL_set_accept_state(_ssl) : SSL_set_connect_state(_ssl); _sendHandshake = false; } SSL_Box::~SSL_Box() { if (_ssl) { SSL_free(_ssl); _ssl = nullptr; } ERR_clear_error(); ERR_remove_state(0); } void SSL_Box::shutdown() { int ret = SSL_shutdown(_ssl); if (ret != 1) { ErrorL << "SSL shutdown failed:"<< ERR_reason_error_string(ERR_get_error()) << endl; } else { flush(); } } void SSL_Box::onRecv(const char* data, uint32_t data_len) { if (!_enable) { if (_onDec) { _onDec(data, data_len); } return; } BIO_write(_read_bio, data, data_len); flush(); } void SSL_Box::onSend(const char* data, uint32_t data_len) { if (!_enable) { if (_onEnc) { _onEnc(data, data_len); } return; } if (!_isServer && !_sendHandshake) { _sendHandshake = true; SSL_do_handshake(_ssl); } _bufferOut.append(data, data_len); flush(); } void SSL_Box::flushWriteBio(char *buf, int bufsize) { int nread = 0; //write to socket while ((nread = BIO_read(_write_bio, buf, bufsize)) > 0) { if (_onEnc) { //send _onEnc(buf, nread); } } } void SSL_Box::flushReadBio(char *buf, int bufsize) { int nread = 0; //recv from bio while ((nread = SSL_read(_ssl, buf, bufsize)) > 0) { if (_onDec) { //recv _onDec(buf, nread); } } } void SSL_Box::flush() { int nread = 0; char buffer[SSL_BUF_SIZE]; // optimize! flushReadBio(buffer, sizeof(buffer)); flushWriteBio(buffer, sizeof(buffer)); //write to bio if (SSL_is_init_finished(_ssl) && _bufferOut.size()) { nread = SSL_write(_ssl, _bufferOut.data(), _bufferOut.size()); if (nread >= 0) { //success _bufferOut.clear(); flushWriteBio(buffer, sizeof(buffer)); } else { int error = SSL_get_error(_ssl, nread); ErrorL << "ssl error:" << error << endl; } } } } /* namespace Util */ } /* namespace ZL */ #endif //ENABLE_OPENSSL namespace ZL { namespace Util { SSL_Initor &SSL_Initor::Instance() { static SSL_Initor obj; return obj; } } /* namespace Util */ } /* namespace ZL */<commit_msg>确保最后一个字节为0<commit_after>/* * MIT License * * Copyright (c) 2016 xiongziliang <[email protected]> * * 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 "SSLBox.h" #if defined(ENABLE_OPENSSL) #include <string.h> #include <openssl/ssl.h> #include <openssl/rand.h> #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/conf.h> #include "Util/util.h" #define SSL_BUF_SIZE 1024*4 namespace ZL { namespace Util { mutex *SSL_Initor::_mutexes; SSL_Initor::SSL_Initor() { SSL_library_init(); SSL_load_error_strings(); OpenSSL_add_all_digests(); OpenSSL_add_all_ciphers(); OpenSSL_add_all_algorithms(); _mutexes = new mutex[CRYPTO_num_locks()]; CRYPTO_set_locking_callback([](int mode,int n, const char *file,int line) { if (mode & CRYPTO_LOCK) _mutexes[n].lock(); else _mutexes[n].unlock(); }); CRYPTO_set_id_callback([]() ->unsigned long { #if !defined(_WIN32) return (unsigned long)pthread_self(); #else return (unsigned long)GetCurrentThreadId(); #endif }); ssl_client = SSL_CTX_new(TLSv1_client_method()); ssl_server = SSL_CTX_new(TLSv1_server_method()); setCtx(ssl_client); setCtx(ssl_server); } void SSL_Initor::loadServerPem(const char *keyAndCA_pem, const char *import_pwd){ loadPem(ssl_server,keyAndCA_pem,import_pwd); } void SSL_Initor::loadClientPem(const char *keyAndCA_pem, const char *import_pwd){ loadPem(ssl_client,keyAndCA_pem,import_pwd); } void SSL_Initor::loadPem(SSL_CTX *ctx, const char *keyAndCA_pem,const char *import_pwd) { int errCode = SSL_CTX_use_PrivateKey_file(ctx, keyAndCA_pem,SSL_FILETYPE_PEM); if (errCode != 1) { throw std::runtime_error(std::string("SSL_CTX_use_PrivateKey_file: ") + getLastError()); } errCode = SSL_CTX_use_certificate_file(ctx, keyAndCA_pem,SSL_FILETYPE_PEM); if (errCode != 1) { throw std::runtime_error(std::string("SSL_CTX_use_certificate_chain_file: ")+ getLastError()); } SSL_CTX_set_default_passwd_cb_userdata(ctx, (void *) import_pwd); SSL_CTX_set_default_passwd_cb(ctx,[](char *buf, int size, int rwflag, void *userdata)->int { const char *privateKeyPwd=(const char *)userdata; size_t privateKeyPwd_len=strlen(privateKeyPwd); strncpy(buf, privateKeyPwd, size); buf[size - 1] = '\0'; if (size > (int)privateKeyPwd_len) size = privateKeyPwd_len; return size; }); errCode = SSL_CTX_check_private_key(ctx); if (errCode != 1) { throw std::runtime_error(std::string("SSL_CTX_check_private_key: ") + getLastError()); } } SSL_Initor::~SSL_Initor() { SSL_CTX_free(ssl_client); SSL_CTX_free(ssl_server); EVP_cleanup(); ERR_free_strings(); ERR_clear_error(); ERR_remove_state(0); CRYPTO_set_locking_callback(NULL); //sk_SSL_COMP_free(SSL_COMP_get_compression_methods()); CRYPTO_cleanup_all_ex_data(); CONF_modules_unload(1); CONF_modules_free(); delete[] _mutexes; } void SSL_Initor::setCtx(SSL_CTX *ctx) { SSL_CTX_set_cipher_list(ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); SSL_CTX_set_verify_depth(ctx, 9); SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY); SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF); SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE,[](int ok, X509_STORE_CTX *pStore) { if (!ok) { int depth = X509_STORE_CTX_get_error_depth(pStore); int err = X509_STORE_CTX_get_error(pStore); std::string error(X509_verify_cert_error_string(err)); ErrorL<<depth<<" "<<error<<endl; ok = 1; } return ok; }); } inline std::string SSL_Initor::getLastError(){ unsigned long errCode = ERR_get_error(); if (errCode != 0) { char buffer[256]; ERR_error_string_n(errCode, buffer, sizeof(buffer)); return std::string(buffer); } else return "No error"; } SSL_Box::SSL_Box(bool isServer, bool enable) : _ssl(nullptr), _read_bio(nullptr), _write_bio(nullptr) { _isServer = isServer; _enable = enable; _ssl = SSL_new(_isServer ?SSL_Initor::Instance().ssl_server :SSL_Initor::Instance().ssl_client); _read_bio = BIO_new(BIO_s_mem()); _write_bio = BIO_new(BIO_s_mem()); SSL_set_bio(_ssl, _read_bio, _write_bio); _isServer ? SSL_set_accept_state(_ssl) : SSL_set_connect_state(_ssl); _sendHandshake = false; } SSL_Box::~SSL_Box() { if (_ssl) { SSL_free(_ssl); _ssl = nullptr; } ERR_clear_error(); ERR_remove_state(0); } void SSL_Box::shutdown() { int ret = SSL_shutdown(_ssl); if (ret != 1) { ErrorL << "SSL shutdown failed:"<< ERR_reason_error_string(ERR_get_error()) << endl; } else { flush(); } } void SSL_Box::onRecv(const char* data, uint32_t data_len) { if (!_enable) { if (_onDec) { _onDec(data, data_len); } return; } BIO_write(_read_bio, data, data_len); flush(); } void SSL_Box::onSend(const char* data, uint32_t data_len) { if (!_enable) { if (_onEnc) { _onEnc(data, data_len); } return; } if (!_isServer && !_sendHandshake) { _sendHandshake = true; SSL_do_handshake(_ssl); } _bufferOut.append(data, data_len); flush(); } void SSL_Box::flushWriteBio(char *buf, int bufsize) { int nread = 0; //write to socket while ((nread = BIO_read(_write_bio, buf, bufsize)) > 0) { if (_onEnc) { //send buf[nread] = '\0'; _onEnc(buf, nread); } } } void SSL_Box::flushReadBio(char *buf, int bufsize) { int nread = 0; //recv from bio while ((nread = SSL_read(_ssl, buf, bufsize)) > 0) { if (_onDec) { //recv buf[nread] = '\0'; _onDec(buf, nread); } } } void SSL_Box::flush() { int nread = 0; char buffer[SSL_BUF_SIZE + 1]; // optimize! flushReadBio(buffer, SSL_BUF_SIZE); flushWriteBio(buffer, SSL_BUF_SIZE); //write to bio if (SSL_is_init_finished(_ssl) && _bufferOut.size()) { nread = SSL_write(_ssl, _bufferOut.data(), _bufferOut.size()); if (nread >= 0) { //success _bufferOut.clear(); flushWriteBio(buffer, sizeof(buffer)); } else { int error = SSL_get_error(_ssl, nread); ErrorL << "ssl error:" << error << endl; } } } } /* namespace Util */ } /* namespace ZL */ #endif //ENABLE_OPENSSL namespace ZL { namespace Util { SSL_Initor &SSL_Initor::Instance() { static SSL_Initor obj; return obj; } } /* namespace Util */ } /* namespace ZL */<|endoftext|>
<commit_before>/* * A wrapper for an async_operation which closes an istream on abort. * * author: Max Kellermann <[email protected]> */ #include "abort_close.hxx" #include "async.hxx" #include "pool.hxx" #include "istream.h" #include "util/Cast.hxx" struct CloseOnAbort { struct istream *istream; struct async_operation operation; struct async_operation_ref ref; void Abort() { ref.Abort(); istream_close_unused(istream); } }; /* * constructor * */ struct async_operation_ref * async_close_on_abort(struct pool *pool, struct istream *istream, struct async_operation_ref *async_ref) { auto coa = NewFromPool<struct CloseOnAbort>(*pool); assert(istream != nullptr); assert(!istream_has_handler(istream)); assert(async_ref != nullptr); coa->istream = istream; coa->operation.Init2<CloseOnAbort>(); async_ref->Set(coa->operation); return &coa->ref; } struct async_operation_ref * async_optional_close_on_abort(struct pool *pool, struct istream *istream, struct async_operation_ref *async_ref) { return istream != nullptr ? async_close_on_abort(pool, istream, async_ref) : async_ref; } <commit_msg>abort_close: add constructor<commit_after>/* * A wrapper for an async_operation which closes an istream on abort. * * author: Max Kellermann <[email protected]> */ #include "abort_close.hxx" #include "async.hxx" #include "pool.hxx" #include "istream.h" #include "util/Cast.hxx" struct CloseOnAbort { struct istream *istream; struct async_operation operation; struct async_operation_ref ref; CloseOnAbort(struct istream &_istream, struct async_operation_ref &async_ref) :istream(&_istream) { operation.Init2<CloseOnAbort>(); async_ref.Set(operation); } void Abort() { ref.Abort(); istream_close_unused(istream); } }; /* * constructor * */ struct async_operation_ref * async_close_on_abort(struct pool *pool, struct istream *istream, struct async_operation_ref *async_ref) { assert(istream != nullptr); assert(!istream_has_handler(istream)); assert(async_ref != nullptr); auto coa = NewFromPool<struct CloseOnAbort>(*pool, *istream, *async_ref); return &coa->ref; } struct async_operation_ref * async_optional_close_on_abort(struct pool *pool, struct istream *istream, struct async_operation_ref *async_ref) { return istream != nullptr ? async_close_on_abort(pool, istream, async_ref) : async_ref; } <|endoftext|>
<commit_before>#include <ace/Runtime.hpp> #include <stdio.h> #if defined(__unix__) || defined(__APPLE__) || defined(__linux__) #include <dlfcn.h> #define OPEN_LIB(path) dlopen((path), RTLD_LAZY) #define CLOSE_LIB(handle) dlclose((handle)) #define LOAD_LIB_FUNC(handle, func) dlsym((handle), (func)) #elif _WIN32 #include <windows.h> #define OPEN_LIB(path) LoadLibrary((path)) #define CLOSE_LIB(handle) #define LOAD_LIB_FUNC(handle, func) (void*)(GetProcAddress((HMODULE)handle, func)) #endif namespace ace { const int Runtime::VERSION_MAJOR = 0; const int Runtime::VERSION_MINOR = 1; const int Runtime::VERSION_PATCH = 1; const char *Runtime::OS_NAME = #ifdef _WIN32 "Windows"; #elif __APPLE__ "Mac"; #elif __linux__ "Linux"; #else "Unknown"; #endif std::vector<Library> Runtime::libs = {}; vm::NativeFunctionPtr_t Library::GetFunction(const char *name) { if (void *ptr = LOAD_LIB_FUNC(handle, name)) { return (vm::NativeFunctionPtr_t)ptr; } return nullptr; } Library Runtime::Load(const char *path) { Library lib; lib.handle = OPEN_LIB(path); if (lib.handle) { libs.push_back(lib); } return lib; } void Runtime::UnloadLibraries() { for (auto it = libs.rbegin(); it != libs.rend(); it++) { if ((*it).handle) { CLOSE_LIB((*it).handle); } } libs.clear(); } } // namespace ace <commit_msg>Delete runtime.cpp<commit_after><|endoftext|>
<commit_before>#ifndef __CALCULATE_SYMBOL_HPP__ #define __CALCULATE_SYMBOL_HPP__ #include "wrapper.hpp" namespace calculate { template<typename Expression> class Symbol { friend struct std::hash<Symbol>; public: using Type = typename Expression::Type; enum class SymbolType : int { LEFT=0, RIGHT, SEPARATOR, CONSTANT, FUNCTION, OPERATOR }; private: using WrapperConcept = WrapperConcept<Type, Expression>; using Wrapper = Wrapper<Type, Expression>; template<typename Callable> struct Inspect { static constexpr bool not_me = detail::NotSame<Callable, Symbol>::value; static constexpr bool is_model = std::is_base_of<WrapperConcept, Callable>::value; }; Wrapper _wrapper; protected: virtual bool _equal(const Symbol&) const noexcept { return true; } std::size_t _hash() const noexcept { if (symbol() == SymbolType::CONSTANT) return std::hash<Type>()(_wrapper()); return std::hash<Wrapper>()(_wrapper); } public: template< typename Callable, std::enable_if_t<Inspect<Callable>::not_me>* = nullptr, std::enable_if_t<!Inspect<Callable>::is_model>* = nullptr > Symbol(Callable&& callable) : _wrapper{std::forward<Callable>(callable), &Expression::evaluate} {} template< typename Callable, std::enable_if_t<Inspect<Callable>::is_model>* = nullptr > Symbol(Callable&& callable) : _wrapper{std::forward<Callable>(callable)} {} template<typename Class> bool operator==(const Class& other) const noexcept { if (symbol() != other.symbol()) return false; if (symbol() == SymbolType::CONSTANT) return _wrapper() == other._wrapper(); return _wrapper == other._wrapper && this->_equal(other); } Type evaluate(const std::vector<Expression>& nodes) const { return const_cast<const Wrapper*>(&_wrapper)->operator()(nodes); } Type evaluate(const std::vector<Expression>& nodes) { return _wrapper(nodes); } std::size_t arguments() const noexcept { return _wrapper.argc(); } virtual SymbolType symbol() const noexcept = 0; virtual ~Symbol() {} }; template<typename Expression> class Constant final : public Symbol<Expression> { using Symbol = Symbol<Expression>; using SymbolType = typename Symbol::SymbolType; public: using Type = typename Expression::Type; Constant(Type value) : Symbol{[value]() noexcept { return value; }} {} SymbolType symbol() const noexcept override { return SymbolType::CONSTANT; } operator Type() const { return Symbol::evaluate({}); } }; template<typename Expression> class Variable final : public Symbol<Expression> { using Symbol = Symbol<Expression>; using SymbolType = typename Symbol::SymbolType; public: using Type = typename Expression::Type; Variable(Type& variable) : Symbol{[&variable]() noexcept { return variable; }} {} SymbolType symbol() const noexcept override { return SymbolType::CONSTANT; } }; template<typename Expression> class Function final : public Symbol<Expression> { using Symbol = Symbol<Expression>; using SymbolType = typename Symbol::SymbolType; public: using Type = typename Expression::Type; template<typename Callable> Function(Callable&& callable) : Symbol{std::forward<Callable>(callable)} {} SymbolType symbol() const noexcept override { return SymbolType::FUNCTION; } }; template<typename Expression> class Operator final : public Symbol<Expression> { using Symbol = Symbol<Expression>; using SymbolType = typename Symbol::SymbolType; public: using Type = typename Expression::Type; enum class Associativity : int {LEFT=0, RIGHT, BOTH}; private: std::string _alias; std::size_t _precedence; Associativity _associativity; bool _equal(const Symbol& other) const noexcept { return _alias == static_cast<Operator&>(other)._alias && _precedence == static_cast<Operator&>(other)._precedence && _associativity == static_cast<Operator&>(other)._associativity; } public: template<typename Callable> Operator( Callable&& callable, const std::string& alias, std::size_t precedence, Associativity associativity ) : Symbol{std::forward<Callable>(callable)}, _alias{alias}, _precedence{precedence}, _associativity{associativity} {} SymbolType symbol() const noexcept override { return SymbolType::OPERATOR; } const std::string& alias() const noexcept { return _alias; } std::size_t precedence() const noexcept { return _precedence; } Associativity associativity() const noexcept { return _associativity; } }; } namespace std { template<typename Expression> struct hash<calculate::Symbol<Expression>> { size_t operator()(const calculate::Symbol<Expression>& symbol) const { return symbol._hash(); } }; } #endif <commit_msg>Added operator() to functions and operators<commit_after>#ifndef __CALCULATE_SYMBOL_HPP__ #define __CALCULATE_SYMBOL_HPP__ #include "wrapper.hpp" namespace calculate { template<typename Expression> class Symbol { friend struct std::hash<Symbol>; public: using Type = typename Expression::Type; enum class SymbolType : int { LEFT=0, RIGHT, SEPARATOR, CONSTANT, FUNCTION, OPERATOR }; private: using WrapperConcept = WrapperConcept<Type, Expression>; using Wrapper = Wrapper<Type, Expression>; template<typename Callable> struct Inspect { static constexpr bool not_me = detail::NotSame<Callable, Symbol>::value; static constexpr bool is_model = std::is_base_of<WrapperConcept, Callable>::value; }; Wrapper _wrapper; protected: virtual bool _equal(const Symbol&) const noexcept { return true; } std::size_t _hash() const noexcept { if (symbol() == SymbolType::CONSTANT) return std::hash<Type>()(_wrapper()); return std::hash<Wrapper>()(_wrapper); } public: template< typename Callable, std::enable_if_t<Inspect<Callable>::not_me>* = nullptr, std::enable_if_t<!Inspect<Callable>::is_model>* = nullptr > Symbol(Callable&& callable) : _wrapper{std::forward<Callable>(callable), &Expression::evaluate} {} template< typename Callable, std::enable_if_t<Inspect<Callable>::is_model>* = nullptr > Symbol(Callable&& callable) : _wrapper{std::forward<Callable>(callable)} {} template<typename Class> bool operator==(const Class& other) const noexcept { if (symbol() != other.symbol()) return false; if (symbol() == SymbolType::CONSTANT) return _wrapper() == other._wrapper(); return _wrapper == other._wrapper && this->_equal(other); } template<typename... Args> Type call(Args&&... args) const { return const_cast<const Wrapper&>(_wrapper) .call(std::forward<Args>(args)...); } template<typename... Args> Type call(Args&&... args) { return _wrapper.call(std::forward<Args>(args)...); } Type evaluate(const std::vector<Expression>& nodes) const { return const_cast<const Wrapper&>(_wrapper)(nodes); } Type evaluate(const std::vector<Expression>& nodes) { return _wrapper(nodes); } std::size_t arguments() const noexcept { return _wrapper.argc(); } virtual SymbolType symbol() const noexcept = 0; virtual ~Symbol() {} }; template<typename Expression> class Constant final : public Symbol<Expression> { using Symbol = Symbol<Expression>; using SymbolType = typename Symbol::SymbolType; public: using Type = typename Expression::Type; Constant(Type value) : Symbol{[value]() noexcept { return value; }} {} SymbolType symbol() const noexcept override { return SymbolType::CONSTANT; } operator Type() const { return this->call(); } operator Type() { return this->call(); } }; template<typename Expression> class Variable final : public Symbol<Expression> { using Symbol = Symbol<Expression>; using SymbolType = typename Symbol::SymbolType; public: using Type = typename Expression::Type; Variable(Type& variable) : Symbol{[&variable]() noexcept { return variable; }} {} SymbolType symbol() const noexcept override { return SymbolType::CONSTANT; } }; template<typename Expression> class Function final : public Symbol<Expression> { using Symbol = Symbol<Expression>; using SymbolType = typename Symbol::SymbolType; public: using Type = typename Expression::Type; template<typename Callable> Function(Callable&& callable) : Symbol{std::forward<Callable>(callable)} {} SymbolType symbol() const noexcept override { return SymbolType::FUNCTION; } template<typename... Args> Type operator()(Args&&... args) const { return const_cast<const Symbol*>(this) ->call(std::forward<Args>(args)...); } template<typename... Args> Type operator()(Args&&... args) { return this->call(std::forward<Args>(args)...); } }; template<typename Expression> class Operator final : public Symbol<Expression> { using Symbol = Symbol<Expression>; using SymbolType = typename Symbol::SymbolType; public: using Type = typename Expression::Type; enum class Associativity : int {LEFT=0, RIGHT, BOTH}; private: std::string _alias; std::size_t _precedence; Associativity _associativity; bool _equal(const Symbol& other) const noexcept { return _alias == static_cast<Operator&>(other)._alias && _precedence == static_cast<Operator&>(other)._precedence && _associativity == static_cast<Operator&>(other)._associativity; } public: template<typename Callable> Operator( Callable&& callable, const std::string& alias, std::size_t precedence, Associativity associativity ) : Symbol{std::forward<Callable>(callable)}, _alias{alias}, _precedence{precedence}, _associativity{associativity} {} SymbolType symbol() const noexcept override { return SymbolType::OPERATOR; } template<typename... Args> Type operator()(Args&&... args) const { return const_cast<const Symbol*>(this) ->call(std::forward<Args>(args)...); } template<typename... Args> Type operator()(Args&&... args) { return this->call(std::forward<Args>(args)...); } const std::string& alias() const noexcept { return _alias; } std::size_t precedence() const noexcept { return _precedence; } Associativity associativity() const noexcept { return _associativity; } }; } namespace std { template<typename Expression> struct hash<calculate::Symbol<Expression>> { size_t operator()(const calculate::Symbol<Expression>& symbol) const { return symbol._hash(); } }; } #endif <|endoftext|>
<commit_before>#pragma once /** @file @brief succinct vector @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause */ #include <assert.h> #include <vector> #include <cybozu/exception.hpp> #include <cybozu/bit_operation.hpp> #include <cybozu/select8.hpp> #include <iosfwd> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4127) #endif namespace cybozu { const uint64_t NotFound = ~uint64_t(0); namespace sucvector_util { inline uint32_t rank64(uint64_t v, size_t i) { return cybozu::popcnt<uint64_t>(v & cybozu::makeBitMask64(i)); } inline uint32_t select64(uint64_t v, size_t r) { assert(r <= 64); if (r > popcnt(v)) return 64; uint32_t pos = 0; uint32_t c = popcnt(uint32_t(v)); if (r > c) { r -= c; pos = 32; v >>= 32; } c = popcnt<uint32_t>(uint16_t(v)); if (r > c) { r -= c; pos += 16; v >>= 16; } c = popcnt<uint32_t>(uint8_t(v)); if (r > c) { r -= c; pos += 8; v >>= 8; } if (r == 8 && uint8_t(v) == 0xff) return pos + 7; assert(r <= 8); c = cybozu::select8_util::select8(uint8_t(v), r); return pos + c; } union ci { uint64_t i; char c[8]; }; inline uint64_t load64bit(std::istream& is, const char *msg) { ci ci; if (is.read(ci.c, sizeof(ci.c)) && is.gcount() == sizeof(ci.c)) { return ci.i; } throw cybozu::Exception("sucvector_util:load64bit") << msg; } inline void save64bit(std::ostream& os, uint64_t val, const char *msg) { ci ci; ci.i = val; if (!os.write(ci.c, sizeof(ci.c))) { throw cybozu::Exception("sucvector_util:save64bit") << msg; } } template<class V> void loadVec(V& v, std::istream& is, const char *msg) { const uint64_t size64 = sucvector_util::load64bit(is, msg); assert(size64 <= ~size_t(0)); const size_t size = size_t(size64); v.resize(size); if (is.read(cybozu::cast<char*>(&v[0]), size * sizeof(v[0]))) return; throw cybozu::Exception("sucvector_util:loadVec") << msg; } template<class V> void saveVec(std::ostream& os, const V& v, const char *msg) { save64bit(os, v.size(), msg); const size_t size = v.size() * sizeof(v[0]); if (os.write(cybozu::cast<const char*>(&v[0]), size) && os.flush()) return; throw cybozu::Exception("sucvector_util:saveVec") << msg; } } // cybozu::sucvector_util /* extra memory (32 + 8 * 4) / 256 = 1/4 bit per bit */ struct SucVector { static const uint64_t maxBitSize = uint64_t(1) << 40; struct B { uint64_t org[4]; union { uint64_t a64; struct { uint32_t a; uint8_t b[4]; // b[0] is used for (b[0] << 32) | a } ab; }; }; uint64_t bitSize_; uint64_t num_[2]; std::vector<B> blk_; template<int b> uint64_t rank_a(size_t i) const { assert(i < blk_.size()); uint64_t ret = blk_[i].a64 % maxBitSize; if (!b) ret = i * uint64_t(256) - ret; return ret; } template<bool b> size_t get_b(size_t L, size_t i) const { assert(i > 0); size_t r = blk_[L].ab.b[i]; if (!b) r = 64 * i - r; return r; } public: SucVector() : bitSize_(0) { num_[0] = num_[1] = 0; } /* data format(endian is depend on CPU:eg. little endian for x86/x64) bitSize : 8 num_[0] : 8 num_[1] : 8 blkSize : 8 blk data : blkSize * sizeof(B) */ void save(std::ostream& os) const { sucvector_util::save64bit(os, bitSize_, "bitSize"); sucvector_util::save64bit(os, num_[0], "num0"); sucvector_util::save64bit(os, num_[1], "num1"); sucvector_util::saveVec(os, blk_, "blk"); } void load(std::istream& is) { bitSize_ = sucvector_util::load64bit(is, "bitSize"); num_[0] = sucvector_util::load64bit(is, "num0"); num_[1] = sucvector_util::load64bit(is, "num1"); sucvector_util::loadVec(blk_, is, "blk"); } /* @param blk [in] bit pattern block @param bitSize [in] bitSize ; blk size = (bitSize + 63) / 64 @note max bitSize is 1<<40 */ SucVector(const uint64_t *blk, uint64_t bitSize) { if (bitSize > maxBitSize) throw cybozu::Exception("SucVector:too large") << bitSize; init(blk, bitSize); } void init(const uint64_t *blk, uint64_t bitSize) { bitSize_ = bitSize; const uint64_t v = (bitSize + 63) / 64; assert(v <= ~size_t(0)); const size_t blkNum = size_t(v); size_t tblNum = (blkNum + 3) / 4; blk_.resize(tblNum + 1); uint64_t av = 0; size_t pos = 0; for (size_t i = 0; i < tblNum; i++) { B& b = blk_[i]; b.a64 = av % maxBitSize; uint32_t bv = 0; for (size_t j = 0; j < 4; j++) { uint64_t v = pos < blkNum ? blk[pos++] : 0; b.org[j] = v; uint32_t c = cybozu::popcnt(v); av += c; if (j > 0) { b.ab.b[j] = (uint8_t)bv; } bv += c; } } blk_[tblNum].a64 = av; num_[0] = blkNum * 64 - av; num_[1] = av; } uint64_t getNum(bool b) const { return num_[b ? 1 : 0]; } uint64_t rank1(uint64_t i) const { assert(i / 256 <= ~size_t(0)); size_t q = size_t(i / 256); size_t r = size_t((i / 64) & 3); assert(q < blk_.size()); const B& b = blk_[q]; uint64_t ret = b.a64 % maxBitSize; if (r > 0) { // ret += b.ab.b[r]; ret += uint8_t(b.a64 >> (32 + r * 8)); } ret += cybozu::popcnt<uint64_t>(b.org[r] & cybozu::makeBitMask64(i & 63)); return ret; } uint64_t size() const { return bitSize_; } uint64_t rank0(uint64_t i) const { return i - rank1(i); } uint64_t rank(bool b, uint64_t i) const { if (b) return rank1(i); return rank0(i); } bool get(uint64_t i) const { assert(i / 256 <= ~size_t(0)); size_t q = size_t(i / 256); size_t r = size_t((i / 64) & 3); assert(q < blk_.size()); const B& b = blk_[q]; return (b.org[r] & (1ULL << (i & 63))) != 0; } uint64_t select0(uint64_t rank) const { return selectSub<false>(rank); } uint64_t select1(uint64_t rank) const { return selectSub<true>(rank); } uint64_t select(bool b, uint64_t rank) const { if (b) return select1(rank); return select0(rank); } /* 0123456789 0100101101 ^ ^ ^^ 0 1 23 select(v, r) = min { i - 1 | rank(v, i) = r + 1 } select(3) = 7 */ template<bool b> uint64_t selectSub(uint64_t rank) const { if (rank >= num_[b]) return NotFound; rank++; size_t L = 0; size_t R = blk_.size(); while (L < R) { size_t M = (L + R) / 2; // (R - L) / 2 + L; if (rank_a<b>(M) < rank) { L = M + 1; } else { R = M; } } if (L > 0) L--; rank -= rank_a<b>(L); size_t i = 0; #if 0 { const uint8_t *p = blk_[L].ab.b; if (b) { if (p[2] >= rank) { if (p[1] >= rank) { i = 0; } else { i = 1; rank -= p[1]; } } else { if (p[3] >= rank) { i = 2; rank -= p[2]; } else { i = 3; rank -= p[3]; } } } else { size_t r = 128 - p[2]; if (r >= rank) { r = 64 - p[1]; if (r >= rank) { i = 0; } else { i = 1; rank -= r; } } else { size_t r2 = 192 - p[3]; if (r2 >= rank) { i = 2; rank -= r; } else { i = 3; rank -= r2; } } } } #else while (i < 3) { size_t r = get_b<b>(L, i + 1); if (r >= rank) { break; } i++; } if (i > 0) { size_t r = get_b<b>(L, i); rank -= r; } #endif uint64_t v = blk_[L].org[i]; if (!b) v = ~v; assert(rank <= 64); uint64_t ret = cybozu::sucvector_util::select64(v, size_t(rank)); ret += L * 256 + i * 64; return ret; } }; } // cybozu #ifdef _WIN32 #pragma warning(pop) #endif <commit_msg>remove test code<commit_after>#pragma once /** @file @brief succinct vector @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause */ #include <assert.h> #include <vector> #include <cybozu/exception.hpp> #include <cybozu/bit_operation.hpp> #include <cybozu/select8.hpp> #include <iosfwd> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4127) #endif namespace cybozu { const uint64_t NotFound = ~uint64_t(0); namespace sucvector_util { inline uint32_t rank64(uint64_t v, size_t i) { return cybozu::popcnt<uint64_t>(v & cybozu::makeBitMask64(i)); } inline uint32_t select64(uint64_t v, size_t r) { assert(r <= 64); if (r > popcnt(v)) return 64; uint32_t pos = 0; uint32_t c = popcnt(uint32_t(v)); if (r > c) { r -= c; pos = 32; v >>= 32; } c = popcnt<uint32_t>(uint16_t(v)); if (r > c) { r -= c; pos += 16; v >>= 16; } c = popcnt<uint32_t>(uint8_t(v)); if (r > c) { r -= c; pos += 8; v >>= 8; } if (r == 8 && uint8_t(v) == 0xff) return pos + 7; assert(r <= 8); c = cybozu::select8_util::select8(uint8_t(v), r); return pos + c; } union ci { uint64_t i; char c[8]; }; inline uint64_t load64bit(std::istream& is, const char *msg) { ci ci; if (is.read(ci.c, sizeof(ci.c)) && is.gcount() == sizeof(ci.c)) { return ci.i; } throw cybozu::Exception("sucvector_util:load64bit") << msg; } inline void save64bit(std::ostream& os, uint64_t val, const char *msg) { ci ci; ci.i = val; if (!os.write(ci.c, sizeof(ci.c))) { throw cybozu::Exception("sucvector_util:save64bit") << msg; } } template<class V> void loadVec(V& v, std::istream& is, const char *msg) { const uint64_t size64 = sucvector_util::load64bit(is, msg); assert(size64 <= ~size_t(0)); const size_t size = size_t(size64); v.resize(size); if (is.read(cybozu::cast<char*>(&v[0]), size * sizeof(v[0]))) return; throw cybozu::Exception("sucvector_util:loadVec") << msg; } template<class V> void saveVec(std::ostream& os, const V& v, const char *msg) { save64bit(os, v.size(), msg); const size_t size = v.size() * sizeof(v[0]); if (os.write(cybozu::cast<const char*>(&v[0]), size) && os.flush()) return; throw cybozu::Exception("sucvector_util:saveVec") << msg; } } // cybozu::sucvector_util /* extra memory (32 + 8 * 4) / 256 = 1/4 bit per bit */ struct SucVector { static const uint64_t maxBitSize = uint64_t(1) << 40; struct B { uint64_t org[4]; union { uint64_t a64; struct { uint32_t a; uint8_t b[4]; // b[0] is used for (b[0] << 32) | a } ab; }; }; uint64_t bitSize_; uint64_t num_[2]; std::vector<B> blk_; template<int b> uint64_t rank_a(size_t i) const { assert(i < blk_.size()); uint64_t ret = blk_[i].a64 % maxBitSize; if (!b) ret = i * uint64_t(256) - ret; return ret; } template<bool b> size_t get_b(size_t L, size_t i) const { assert(i > 0); size_t r = blk_[L].ab.b[i]; if (!b) r = 64 * i - r; return r; } public: SucVector() : bitSize_(0) { num_[0] = num_[1] = 0; } /* data format(endian is depend on CPU:eg. little endian for x86/x64) bitSize : 8 num_[0] : 8 num_[1] : 8 blkSize : 8 blk data : blkSize * sizeof(B) */ void save(std::ostream& os) const { sucvector_util::save64bit(os, bitSize_, "bitSize"); sucvector_util::save64bit(os, num_[0], "num0"); sucvector_util::save64bit(os, num_[1], "num1"); sucvector_util::saveVec(os, blk_, "blk"); } void load(std::istream& is) { bitSize_ = sucvector_util::load64bit(is, "bitSize"); num_[0] = sucvector_util::load64bit(is, "num0"); num_[1] = sucvector_util::load64bit(is, "num1"); sucvector_util::loadVec(blk_, is, "blk"); } /* @param blk [in] bit pattern block @param bitSize [in] bitSize ; blk size = (bitSize + 63) / 64 @note max bitSize is 1<<40 */ SucVector(const uint64_t *blk, uint64_t bitSize) { if (bitSize > maxBitSize) throw cybozu::Exception("SucVector:too large") << bitSize; init(blk, bitSize); } void init(const uint64_t *blk, uint64_t bitSize) { bitSize_ = bitSize; const uint64_t v = (bitSize + 63) / 64; assert(v <= ~size_t(0)); const size_t blkNum = size_t(v); size_t tblNum = (blkNum + 3) / 4; blk_.resize(tblNum + 1); uint64_t av = 0; size_t pos = 0; for (size_t i = 0; i < tblNum; i++) { B& b = blk_[i]; b.a64 = av % maxBitSize; uint32_t bv = 0; for (size_t j = 0; j < 4; j++) { uint64_t v = pos < blkNum ? blk[pos++] : 0; b.org[j] = v; uint32_t c = cybozu::popcnt(v); av += c; if (j > 0) { b.ab.b[j] = (uint8_t)bv; } bv += c; } } blk_[tblNum].a64 = av; num_[0] = blkNum * 64 - av; num_[1] = av; } uint64_t getNum(bool b) const { return num_[b ? 1 : 0]; } uint64_t rank1(uint64_t i) const { assert(i / 256 <= ~size_t(0)); size_t q = size_t(i / 256); size_t r = size_t((i / 64) & 3); assert(q < blk_.size()); const B& b = blk_[q]; uint64_t ret = b.a64 % maxBitSize; if (r > 0) { // ret += b.ab.b[r]; ret += uint8_t(b.a64 >> (32 + r * 8)); } ret += cybozu::popcnt<uint64_t>(b.org[r] & cybozu::makeBitMask64(i & 63)); return ret; } uint64_t size() const { return bitSize_; } uint64_t rank0(uint64_t i) const { return i - rank1(i); } uint64_t rank(bool b, uint64_t i) const { if (b) return rank1(i); return rank0(i); } bool get(uint64_t i) const { assert(i / 256 <= ~size_t(0)); size_t q = size_t(i / 256); size_t r = size_t((i / 64) & 3); assert(q < blk_.size()); const B& b = blk_[q]; return (b.org[r] & (1ULL << (i & 63))) != 0; } uint64_t select0(uint64_t rank) const { return selectSub<false>(rank); } uint64_t select1(uint64_t rank) const { return selectSub<true>(rank); } uint64_t select(bool b, uint64_t rank) const { if (b) return select1(rank); return select0(rank); } /* 0123456789 0100101101 ^ ^ ^^ 0 1 23 select(v, r) = min { i - 1 | rank(v, i) = r + 1 } select(3) = 7 */ template<bool b> uint64_t selectSub(uint64_t rank) const { if (rank >= num_[b]) return NotFound; rank++; size_t L = 0; size_t R = blk_.size(); while (L < R) { size_t M = (L + R) / 2; // (R - L) / 2 + L; if (rank_a<b>(M) < rank) { L = M + 1; } else { R = M; } } if (L > 0) L--; rank -= rank_a<b>(L); size_t i = 0; while (i < 3) { size_t r = get_b<b>(L, i + 1); if (r >= rank) { break; } i++; } if (i > 0) { size_t r = get_b<b>(L, i); rank -= r; } uint64_t v = blk_[L].org[i]; if (!b) v = ~v; assert(rank <= 64); uint64_t ret = cybozu::sucvector_util::select64(v, size_t(rank)); ret += L * 256 + i * 64; return ret; } }; } // cybozu #ifdef _WIN32 #pragma warning(pop) #endif <|endoftext|>
<commit_before>#pragma once /** @file @brief succinct vector @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause */ #include <assert.h> #include <vector> #include <cybozu/exception.hpp> #include <cybozu/bit_operation.hpp> #include <cybozu/select8.hpp> #include <iosfwd> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4127) #endif namespace cybozu { const uint64_t NotFound = ~uint64_t(0); namespace sucvector_util { inline uint32_t rank64(uint64_t v, size_t i) { return cybozu::popcnt<uint64_t>(v & cybozu::makeBitMask64(i)); } inline uint32_t select64(uint64_t v, size_t r) { assert(r <= 64); if (r > popcnt(v)) return 64; uint32_t pos = 0; uint32_t c = popcnt(uint32_t(v)); if (r > c) { r -= c; pos = 32; v >>= 32; } c = popcnt<uint32_t>(uint16_t(v)); if (r > c) { r -= c; pos += 16; v >>= 16; } c = popcnt<uint32_t>(uint8_t(v)); if (r > c) { r -= c; pos += 8; v >>= 8; } if (r == 8 && uint8_t(v) == 0xff) return pos + 7; assert(r <= 8); c = cybozu::select8_util::select8(uint8_t(v), r); return pos + c; } union ci { uint64_t i; char c[8]; }; inline uint64_t load64bit(std::istream& is, const char *msg) { ci ci; if (is.read(ci.c, sizeof(ci.c)) && is.gcount() == sizeof(ci.c)) { return ci.i; } throw cybozu::Exception("SucVector:load64bit") << msg; } inline void save64bit(std::ostream& os, uint64_t val, const char *msg) { ci ci; ci.i = val; if (!os.write(ci.c, sizeof(ci.c))) { throw cybozu::Exception("SucVector:save64bit") << msg; } } } // cybozu::sucvector_util /* extra memory (32 + 8 * 4) / 256 = 1/4 bit per bit */ struct SucVector { static const uint64_t maxBitSize = uint64_t(1) << 40; struct B { uint64_t org[4]; union { uint64_t a64; struct { uint32_t a; uint8_t b[4]; // b[0] is used for (b[0] << 32) | a } ab; }; }; uint64_t bitSize_; uint64_t num_[2]; std::vector<B> blk_; template<int b> uint64_t rank_a(size_t i) const { assert(i < blk_.size()); uint64_t ret = blk_[i].a64 % maxBitSize; if (!b) ret = i * uint64_t(256) - ret; return ret; } template<bool b> size_t get_b(size_t L, size_t i) const { assert(i > 0); size_t r = blk_[L].ab.b[i]; if (!b) r = 64 * i - r; return r; } public: SucVector() : bitSize_(0) { num_[0] = num_[1] = 0; } /* data format(little endian for x86/x64) bitSize : 8 num_[0] : 8 num_[1] : 8 blkSize : 8 blk data : blkSize * sizeof(B) */ void save(std::ostream& os) const { sucvector_util::save64bit(os, bitSize_, "bitSize"); sucvector_util::save64bit(os, num_[0], "num0"); sucvector_util::save64bit(os, num_[1], "num1"); sucvector_util::save64bit(os, blk_.size(), "blkSize"); const size_t size = blk_.size() * sizeof(blk_[0]); if (os.write(cybozu::cast<const char*>(&blk_[0]), size) && os.flush()) return; throw cybozu::Exception("SucVector:save"); } void load(std::istream& is) { bitSize_ = sucvector_util::load64bit(is, "bitSize"); num_[0] = sucvector_util::load64bit(is, "num0"); num_[1] = sucvector_util::load64bit(is, "num1"); const uint64_t v = sucvector_util::load64bit(is, "blkSize"); assert(v <= ~size_t(0)); const size_t blkSize = size_t(v); blk_.resize(blkSize); const size_t size = blkSize * sizeof(blk_[0]); if (is.read(cybozu::cast<char*>(&blk_[0]), size)) return; throw cybozu::Exception("SucVector:load"); } /* @param blk [in] bit pattern block @param bitSize [in] bitSize ; blk size = (bitSize + 63) / 64 @note max bitSize is 1<<40 */ SucVector(const uint64_t *blk, uint64_t bitSize) { if (bitSize > maxBitSize) throw cybozu::Exception("SucVector:too large") << bitSize; init(blk, bitSize); } void init(const uint64_t *blk, uint64_t bitSize) { bitSize_ = bitSize; const uint64_t v = (bitSize + 63) / 64; assert(v <= ~size_t(0)); const size_t blkNum = size_t(v); size_t tblNum = (blkNum + 3) / 4; blk_.resize(tblNum + 1); uint64_t av = 0; size_t pos = 0; for (size_t i = 0; i < tblNum; i++) { B& b = blk_[i]; b.a64 = av % maxBitSize; uint32_t bv = 0; for (size_t j = 0; j < 4; j++) { uint64_t v = pos < blkNum ? blk[pos++] : 0; b.org[j] = v; uint32_t c = cybozu::popcnt(v); av += c; if (j > 0) { b.ab.b[j] = (uint8_t)bv; } bv += c; } } blk_[tblNum].a64 = av; num_[0] = blkNum * 64 - av; num_[1] = av; } uint64_t getNum(bool b) const { return num_[b ? 1 : 0]; } uint64_t rank1(uint64_t i) const { assert(i / 256 <= ~size_t(0)); size_t q = size_t(i / 256); size_t r = size_t((i / 64) & 3); assert(q < blk_.size()); const B& b = blk_[q]; uint64_t ret = b.a64 % maxBitSize; if (r > 0) { // ret += b.ab.b[r]; ret += uint8_t(b.a64 >> (32 + r * 8)); } ret += cybozu::popcnt<uint64_t>(b.org[r] & cybozu::makeBitMask64(i & 63)); return ret; } uint64_t size() const { return bitSize_; } uint64_t rank0(uint64_t i) const { return i - rank1(i); } uint64_t rank(bool b, uint64_t i) const { if (b) return rank1(i); return rank0(i); } bool get(uint64_t i) const { assert(i / 256 <= ~size_t(0)); size_t q = size_t(i / 256); size_t r = size_t((i / 64) & 3); assert(q < blk_.size()); const B& b = blk_[q]; return (b.org[r] & (1ULL << (i & 63))) != 0; } uint64_t select0(uint64_t rank) const { return selectSub<false>(rank); } uint64_t select1(uint64_t rank) const { return selectSub<true>(rank); } uint64_t select(bool b, uint64_t rank) const { if (b) return select1(rank); return select0(rank); } /* 0123456789 0100101101 ^ ^ ^^ 0 1 23 select(v, r) = min { i - 1 | rank(v, i) = r + 1 } select(3) = 7 */ template<bool b> uint64_t selectSub(uint64_t rank) const { if (rank >= num_[b]) return NotFound; rank++; size_t L = 0; size_t R = blk_.size(); while (L < R) { size_t M = (L + R) / 2; // (R - L) / 2 + L; if (rank_a<b>(M) < rank) { L = M + 1; } else { R = M; } } if (L > 0) L--; rank -= rank_a<b>(L); size_t i = 0; while (i < 3) { size_t r = get_b<b>(L, i + 1); if (r >= rank) { break; } i++; } if (i > 0) { size_t r = get_b<b>(L, i); rank -= r; } uint64_t v = blk_[L].org[i]; if (!b) v = ~v; assert(rank <= 64); uint64_t ret = cybozu::sucvector_util::select64(v, size_t(rank)); ret += L * 256 + i * 64; return ret; } }; } // cybozu #ifdef _WIN32 #pragma warning(pop) #endif <commit_msg>separate loadVec/saveVec from SucVector<commit_after>#pragma once /** @file @brief succinct vector @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause */ #include <assert.h> #include <vector> #include <cybozu/exception.hpp> #include <cybozu/bit_operation.hpp> #include <cybozu/select8.hpp> #include <iosfwd> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4127) #endif namespace cybozu { const uint64_t NotFound = ~uint64_t(0); namespace sucvector_util { inline uint32_t rank64(uint64_t v, size_t i) { return cybozu::popcnt<uint64_t>(v & cybozu::makeBitMask64(i)); } inline uint32_t select64(uint64_t v, size_t r) { assert(r <= 64); if (r > popcnt(v)) return 64; uint32_t pos = 0; uint32_t c = popcnt(uint32_t(v)); if (r > c) { r -= c; pos = 32; v >>= 32; } c = popcnt<uint32_t>(uint16_t(v)); if (r > c) { r -= c; pos += 16; v >>= 16; } c = popcnt<uint32_t>(uint8_t(v)); if (r > c) { r -= c; pos += 8; v >>= 8; } if (r == 8 && uint8_t(v) == 0xff) return pos + 7; assert(r <= 8); c = cybozu::select8_util::select8(uint8_t(v), r); return pos + c; } union ci { uint64_t i; char c[8]; }; inline uint64_t load64bit(std::istream& is, const char *msg) { ci ci; if (is.read(ci.c, sizeof(ci.c)) && is.gcount() == sizeof(ci.c)) { return ci.i; } throw cybozu::Exception("sucvector_util:load64bit") << msg; } inline void save64bit(std::ostream& os, uint64_t val, const char *msg) { ci ci; ci.i = val; if (!os.write(ci.c, sizeof(ci.c))) { throw cybozu::Exception("sucvector_util:save64bit") << msg; } } template<class V> void loadVec(V& v, std::istream& is, const char *msg) { const uint64_t size64 = sucvector_util::load64bit(is, msg); assert(size64 <= ~size_t(0)); const size_t size = size_t(size64); v.resize(size); if (is.read(cybozu::cast<char*>(&v[0]), size * sizeof(v[0]))) return; throw cybozu::Exception("sucvector_util:loadVec") << msg; } template<class V> void saveVec(std::ostream& os, const V& v, const char *msg) { save64bit(os, v.size(), msg); const size_t size = v.size() * sizeof(v[0]); if (os.write(cybozu::cast<const char*>(&v[0]), size) && os.flush()) return; throw cybozu::Exception("sucvector_util:saveVec") << msg; } } // cybozu::sucvector_util /* extra memory (32 + 8 * 4) / 256 = 1/4 bit per bit */ struct SucVector { static const uint64_t maxBitSize = uint64_t(1) << 40; struct B { uint64_t org[4]; union { uint64_t a64; struct { uint32_t a; uint8_t b[4]; // b[0] is used for (b[0] << 32) | a } ab; }; }; uint64_t bitSize_; uint64_t num_[2]; std::vector<B> blk_; template<int b> uint64_t rank_a(size_t i) const { assert(i < blk_.size()); uint64_t ret = blk_[i].a64 % maxBitSize; if (!b) ret = i * uint64_t(256) - ret; return ret; } template<bool b> size_t get_b(size_t L, size_t i) const { assert(i > 0); size_t r = blk_[L].ab.b[i]; if (!b) r = 64 * i - r; return r; } public: SucVector() : bitSize_(0) { num_[0] = num_[1] = 0; } /* data format(endian is depend on CPU:eg. little endian for x86/x64) bitSize : 8 num_[0] : 8 num_[1] : 8 blkSize : 8 blk data : blkSize * sizeof(B) */ void save(std::ostream& os) const { sucvector_util::save64bit(os, bitSize_, "bitSize"); sucvector_util::save64bit(os, num_[0], "num0"); sucvector_util::save64bit(os, num_[1], "num1"); sucvector_util::saveVec(os, blk_, "blk"); } void load(std::istream& is) { bitSize_ = sucvector_util::load64bit(is, "bitSize"); num_[0] = sucvector_util::load64bit(is, "num0"); num_[1] = sucvector_util::load64bit(is, "num1"); sucvector_util::loadVec(blk_, is, "blk"); } /* @param blk [in] bit pattern block @param bitSize [in] bitSize ; blk size = (bitSize + 63) / 64 @note max bitSize is 1<<40 */ SucVector(const uint64_t *blk, uint64_t bitSize) { if (bitSize > maxBitSize) throw cybozu::Exception("SucVector:too large") << bitSize; init(blk, bitSize); } void init(const uint64_t *blk, uint64_t bitSize) { bitSize_ = bitSize; const uint64_t v = (bitSize + 63) / 64; assert(v <= ~size_t(0)); const size_t blkNum = size_t(v); size_t tblNum = (blkNum + 3) / 4; blk_.resize(tblNum + 1); uint64_t av = 0; size_t pos = 0; for (size_t i = 0; i < tblNum; i++) { B& b = blk_[i]; b.a64 = av % maxBitSize; uint32_t bv = 0; for (size_t j = 0; j < 4; j++) { uint64_t v = pos < blkNum ? blk[pos++] : 0; b.org[j] = v; uint32_t c = cybozu::popcnt(v); av += c; if (j > 0) { b.ab.b[j] = (uint8_t)bv; } bv += c; } } blk_[tblNum].a64 = av; num_[0] = blkNum * 64 - av; num_[1] = av; } uint64_t getNum(bool b) const { return num_[b ? 1 : 0]; } uint64_t rank1(uint64_t i) const { assert(i / 256 <= ~size_t(0)); size_t q = size_t(i / 256); size_t r = size_t((i / 64) & 3); assert(q < blk_.size()); const B& b = blk_[q]; uint64_t ret = b.a64 % maxBitSize; if (r > 0) { // ret += b.ab.b[r]; ret += uint8_t(b.a64 >> (32 + r * 8)); } ret += cybozu::popcnt<uint64_t>(b.org[r] & cybozu::makeBitMask64(i & 63)); return ret; } uint64_t size() const { return bitSize_; } uint64_t rank0(uint64_t i) const { return i - rank1(i); } uint64_t rank(bool b, uint64_t i) const { if (b) return rank1(i); return rank0(i); } bool get(uint64_t i) const { assert(i / 256 <= ~size_t(0)); size_t q = size_t(i / 256); size_t r = size_t((i / 64) & 3); assert(q < blk_.size()); const B& b = blk_[q]; return (b.org[r] & (1ULL << (i & 63))) != 0; } uint64_t select0(uint64_t rank) const { return selectSub<false>(rank); } uint64_t select1(uint64_t rank) const { return selectSub<true>(rank); } uint64_t select(bool b, uint64_t rank) const { if (b) return select1(rank); return select0(rank); } /* 0123456789 0100101101 ^ ^ ^^ 0 1 23 select(v, r) = min { i - 1 | rank(v, i) = r + 1 } select(3) = 7 */ template<bool b> uint64_t selectSub(uint64_t rank) const { if (rank >= num_[b]) return NotFound; rank++; size_t L = 0; size_t R = blk_.size(); while (L < R) { size_t M = (L + R) / 2; // (R - L) / 2 + L; if (rank_a<b>(M) < rank) { L = M + 1; } else { R = M; } } if (L > 0) L--; rank -= rank_a<b>(L); size_t i = 0; while (i < 3) { size_t r = get_b<b>(L, i + 1); if (r >= rank) { break; } i++; } if (i > 0) { size_t r = get_b<b>(L, i); rank -= r; } uint64_t v = blk_[L].org[i]; if (!b) v = ~v; assert(rank <= 64); uint64_t ret = cybozu::sucvector_util::select64(v, size_t(rank)); ret += L * 256 + i * 64; return ret; } }; } // cybozu #ifdef _WIN32 #pragma warning(pop) #endif <|endoftext|>
<commit_before>#include "catch.hh" #include "lib/file.h" TEST_CASE("Reading and writing from files works", "[file]") { const std::string testContent = "test"; { auto f = File::fromFileName("test.txt", File::Mode::Write); f->write(testContent.data(), testContent.size()); } { auto f = File::fromFileName("test.txt", File::Mode::Read); REQUIRE(f->getSize() == testContent.size()); REQUIRE(f->tell() == 0); std::unique_ptr<char[]> buffer(new char[testContent.size()]); f->read(buffer.get(), testContent.size()); REQUIRE(std::string(buffer.get(), testContent.size()) == testContent); } std::remove("test.txt"); } TEST_CASE("Support for big file sizes works", "[file]") { File::OffsetType test; REQUIRE(sizeof(File::OffsetType) > sizeof(uint32_t)); } <commit_msg>tests: drop unused variable<commit_after>#include "catch.hh" #include "lib/file.h" TEST_CASE("Reading and writing from files works", "[file]") { const std::string testContent = "test"; { auto f = File::fromFileName("test.txt", File::Mode::Write); f->write(testContent.data(), testContent.size()); } { auto f = File::fromFileName("test.txt", File::Mode::Read); REQUIRE(f->getSize() == testContent.size()); REQUIRE(f->tell() == 0); std::unique_ptr<char[]> buffer(new char[testContent.size()]); f->read(buffer.get(), testContent.size()); REQUIRE(std::string(buffer.get(), testContent.size()) == testContent); } std::remove("test.txt"); } TEST_CASE("Support for big file sizes works", "[file]") { REQUIRE(sizeof(File::OffsetType) > sizeof(uint32_t)); } <|endoftext|>
<commit_before>/** * \file * \brief Thread class header * * \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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 INCLUDE_DISTORTOS_THREAD_HPP_ #define INCLUDE_DISTORTOS_THREAD_HPP_ #include "distortos/distortosConfiguration.h" #include "distortos/SchedulingPolicy.hpp" #include "distortos/SignalSet.hpp" #include "distortos/ThreadState.hpp" #include <csignal> namespace distortos { /** * \brief Thread class is a pure abstract interface for threads * * \ingroup threads */ class Thread { public: /** * \brief Thread's destructor */ virtual ~Thread() = 0; #ifdef CONFIG_THREAD_DETACH_ENABLE /** * \brief Detaches the thread. * * Similar to std::thread::detach() - http://en.cppreference.com/w/cpp/thread/thread/detach * Similar to POSIX pthread_detach() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_detach.html * * Detaches the executing thread from the Thread object, allowing execution to continue independently. All resources * allocated for the thread will be deallocated when the thread terminates. * * \return 0 on success, error code otherwise: * - EINVAL - this thread is already detached; * - ENOTSUP - this thread cannot be detached; */ virtual int detach() = 0; #endif // def CONFIG_THREAD_DETACH_ENABLE /** * \brief Generates signal for thread. * * Similar to pthread_kill() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_kill.html * * Adds the signalNumber to set of pending signals. If this thread is currently waiting for this signal, it will be * unblocked. * * \param [in] signalNumber is the signal that will be generated, [0; 31] * * \return 0 on success, error code otherwise: * - EINVAL - \a signalNumber value is invalid; * - ENOTSUP - reception of signals is disabled for this thread; * * \ingroup signals */ virtual int generateSignal(uint8_t signalNumber) = 0; /** * \return effective priority of thread */ virtual uint8_t getEffectivePriority() const = 0; /** * \brief Gets set of currently pending signals. * * Similar to sigpending() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigpending.html * * This function shall return the set of signals that are blocked from delivery and are pending on the thread. * * \return set of currently pending signals * * \ingroup signals */ virtual SignalSet getPendingSignalSet() const = 0; /** * \return priority of thread */ virtual uint8_t getPriority() const = 0; /** * \return scheduling policy of the thread */ virtual SchedulingPolicy getSchedulingPolicy() const = 0; /** * \return current state of thread */ virtual ThreadState getState() const = 0; /** * \brief Waits for thread termination. * * Similar to std::thread::join() - http://en.cppreference.com/w/cpp/thread/thread/join * Similar to POSIX pthread_join() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_join.html * * Blocks current thread until this thread finishes its execution. The results of multiple simultaneous calls to * join() on the same target thread are undefined. * * \return 0 on success, error code otherwise: * - EDEADLK - deadlock condition was detected, * - EINVAL - this thread is not joinable, * - ... * * \ingroup synchronization */ virtual int join() = 0; /** * \brief Queues signal for thread. * * Similar to sigqueue() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigqueue.html * * Adds the signalNumber and signal value (sigval union) to queue of SignalInformation objects. If this thread is * currently waiting for this signal, it will be unblocked. * * \param [in] signalNumber is the signal that will be queued, [0; 31] * \param [in] value is the signal value * * \return 0 on success, error code otherwise: * - EAGAIN - no resources are available to queue the signal, maximal number of signals is already queued in * associated queue of SignalInformation objects; * - EINVAL - \a signalNumber value is invalid; * - ENOTSUP - reception or queuing of signals are disabled for this thread; * * \ingroup signals */ virtual int queueSignal(uint8_t signalNumber, sigval value) = 0; /** * \brief Changes priority of thread. * * If the priority really changes, the position in the thread list is adjusted and context switch may be requested. * * \param [in] priority is the new priority of thread * \param [in] alwaysBehind selects the method of ordering when lowering the priority * - false - the thread is moved to the head of the group of threads with the new priority (default), * - true - the thread is moved to the tail of the group of threads with the new priority. */ virtual void setPriority(uint8_t priority, bool alwaysBehind = {}) = 0; /** * param [in] schedulingPolicy is the new scheduling policy of the thread */ virtual void setSchedulingPolicy(SchedulingPolicy schedulingPolicy) = 0; /** * \brief Starts the thread. * * This operation can be performed on threads in "New" state only. * * \return 0 on success, error code otherwise: * - EINVAL - thread is already started; * - error codes returned by scheduler::Scheduler::add(); */ virtual int start() = 0; }; } // namespace distortos #endif // INCLUDE_DISTORTOS_THREAD_HPP_ <commit_msg>Add comment about use in interrupt context to Thread::join()<commit_after>/** * \file * \brief Thread class header * * \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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 INCLUDE_DISTORTOS_THREAD_HPP_ #define INCLUDE_DISTORTOS_THREAD_HPP_ #include "distortos/distortosConfiguration.h" #include "distortos/SchedulingPolicy.hpp" #include "distortos/SignalSet.hpp" #include "distortos/ThreadState.hpp" #include <csignal> namespace distortos { /** * \brief Thread class is a pure abstract interface for threads * * \ingroup threads */ class Thread { public: /** * \brief Thread's destructor */ virtual ~Thread() = 0; #ifdef CONFIG_THREAD_DETACH_ENABLE /** * \brief Detaches the thread. * * Similar to std::thread::detach() - http://en.cppreference.com/w/cpp/thread/thread/detach * Similar to POSIX pthread_detach() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_detach.html * * Detaches the executing thread from the Thread object, allowing execution to continue independently. All resources * allocated for the thread will be deallocated when the thread terminates. * * \return 0 on success, error code otherwise: * - EINVAL - this thread is already detached; * - ENOTSUP - this thread cannot be detached; */ virtual int detach() = 0; #endif // def CONFIG_THREAD_DETACH_ENABLE /** * \brief Generates signal for thread. * * Similar to pthread_kill() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_kill.html * * Adds the signalNumber to set of pending signals. If this thread is currently waiting for this signal, it will be * unblocked. * * \param [in] signalNumber is the signal that will be generated, [0; 31] * * \return 0 on success, error code otherwise: * - EINVAL - \a signalNumber value is invalid; * - ENOTSUP - reception of signals is disabled for this thread; * * \ingroup signals */ virtual int generateSignal(uint8_t signalNumber) = 0; /** * \return effective priority of thread */ virtual uint8_t getEffectivePriority() const = 0; /** * \brief Gets set of currently pending signals. * * Similar to sigpending() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigpending.html * * This function shall return the set of signals that are blocked from delivery and are pending on the thread. * * \return set of currently pending signals * * \ingroup signals */ virtual SignalSet getPendingSignalSet() const = 0; /** * \return priority of thread */ virtual uint8_t getPriority() const = 0; /** * \return scheduling policy of the thread */ virtual SchedulingPolicy getSchedulingPolicy() const = 0; /** * \return current state of thread */ virtual ThreadState getState() const = 0; /** * \brief Waits for thread termination. * * Similar to std::thread::join() - http://en.cppreference.com/w/cpp/thread/thread/join * Similar to POSIX pthread_join() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_join.html * * Blocks current thread until this thread finishes its execution. The results of multiple simultaneous calls to * join() on the same target thread are undefined. * * \warning This function must not be called from interrupt context! * * \return 0 on success, error code otherwise: * - EDEADLK - deadlock condition was detected, * - EINVAL - this thread is not joinable, * - ... * * \ingroup synchronization */ virtual int join() = 0; /** * \brief Queues signal for thread. * * Similar to sigqueue() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigqueue.html * * Adds the signalNumber and signal value (sigval union) to queue of SignalInformation objects. If this thread is * currently waiting for this signal, it will be unblocked. * * \param [in] signalNumber is the signal that will be queued, [0; 31] * \param [in] value is the signal value * * \return 0 on success, error code otherwise: * - EAGAIN - no resources are available to queue the signal, maximal number of signals is already queued in * associated queue of SignalInformation objects; * - EINVAL - \a signalNumber value is invalid; * - ENOTSUP - reception or queuing of signals are disabled for this thread; * * \ingroup signals */ virtual int queueSignal(uint8_t signalNumber, sigval value) = 0; /** * \brief Changes priority of thread. * * If the priority really changes, the position in the thread list is adjusted and context switch may be requested. * * \param [in] priority is the new priority of thread * \param [in] alwaysBehind selects the method of ordering when lowering the priority * - false - the thread is moved to the head of the group of threads with the new priority (default), * - true - the thread is moved to the tail of the group of threads with the new priority. */ virtual void setPriority(uint8_t priority, bool alwaysBehind = {}) = 0; /** * param [in] schedulingPolicy is the new scheduling policy of the thread */ virtual void setSchedulingPolicy(SchedulingPolicy schedulingPolicy) = 0; /** * \brief Starts the thread. * * This operation can be performed on threads in "New" state only. * * \return 0 on success, error code otherwise: * - EINVAL - thread is already started; * - error codes returned by scheduler::Scheduler::add(); */ virtual int start() = 0; }; } // namespace distortos #endif // INCLUDE_DISTORTOS_THREAD_HPP_ <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef _EDITSTAT_HXX #define _EDITSTAT_HXX #include <tools/string.hxx> #include <i18nlangtag/lang.h> #define EE_CNTRL_USECHARATTRIBS 0x00000001 // Use of hard character attributes #define EE_CNTRL_USEPARAATTRIBS 0x00000002 // Using paragraph attributes. #define EE_CNTRL_CRSRLEFTPARA 0x00000004 // Cursor is moved to another paragraph #define EE_CNTRL_DOIDLEFORMAT 0x00000008 // Formatting idle #define EE_CNTRL_PASTESPECIAL 0x00000010 // Allow PasteSpecial #define EE_CNTRL_AUTOINDENTING 0x00000020 // Automatic indenting #define EE_CNTRL_UNDOATTRIBS 0x00000040 // Undo for Attributes.... #define EE_CNTRL_ONECHARPERLINE 0x00000080 // One character per line #define EE_CNTRL_NOCOLORS 0x00000100 // Engine: No Color #define EE_CNTRL_OUTLINER 0x00000200 // Special treatment Outliner/Outline mode #define EE_CNTRL_OUTLINER2 0x00000400 // Special treatment Outliner/Page #define EE_CNTRL_ALLOWBIGOBJS 0x00000800 // Portion info in text object #define EE_CNTRL_ONLINESPELLING 0x00001000 // During the edit Spelling #define EE_CNTRL_STRETCHING 0x00002000 // Stretch mode #define EE_CNTRL_MARKFIELDS 0x00004000 // Mark Fields with color #define EE_CNTRL_URLSFXEXECUTE 0x00008000 // !!!OLD!!!: SFX-URL-Execute. #define EE_CNTRL_RESTOREFONT 0x00010000 // Restore Font in OutDev #define EE_CNTRL_RTFSTYLESHEETS 0x00020000 // Use Stylesheets when imported //#define EE_CNTRL_NOREDLINES 0x00040000 // No RedLines when OnlineSpellError /* removed #i91949 */ #define EE_CNTRL_AUTOCORRECT 0x00080000 // AutoCorrect #define EE_CNTRL_AUTOCOMPLETE 0x00100000 // AutoComplete #define EE_CNTRL_AUTOPAGESIZEX 0x00200000 // Adjust paper width to Text #define EE_CNTRL_AUTOPAGESIZEY 0x00400000 // Adjust paper height to Text #define EE_CNTRL_AUTOPAGESIZE (EE_CNTRL_AUTOPAGESIZEX|EE_CNTRL_AUTOPAGESIZEY) #define EE_CNTRL_TABINDENTING 0x00800000 // Indent with tab #define EE_CNTRL_FORMAT100 0x01000000 // Always format to 100% #define EE_CNTRL_ULSPACESUMMATION 0x02000000 // MS Compat: sum SA and SB, not maximum value #define EE_CNTRL_ULSPACEFIRSTPARA 0x04000000 // MS Compat: evaluate also at the first paragraph #define EV_CNTRL_AUTOSCROLL 0x00000001 // Auto scrolling horizontally #define EV_CNTRL_BIGSCROLL 0x00000002 // Scroll further to the cursor #define EV_CNTRL_ENABLEPASTE 0x00000004 // Enable Paste #define EV_CNTRL_SINGLELINEPASTE 0x00000008 // View: Paste in input line ... #define EV_CNTRL_OVERWRITE 0x00000010 // Overwrite mode #define EV_CNTRL_INVONEMORE 0x00000020 // Invalidate one pixel more #define EV_CNTRL_AUTOSIZEX 0x00000040 // Automatically adapt to text width #define EV_CNTRL_AUTOSIZEY 0x00000080 // Automatically adapt to Text width #define EV_CNTRL_AUTOSIZE (EV_CNTRL_AUTOSIZEX|EV_CNTRL_AUTOSIZEY) #define EE_STAT_HSCROLL 0x00000001 #define EE_STAT_VSCROLL 0x00000002 #define EE_STAT_CURSOROUT 0x00000004 #define EE_STAT_CRSRMOVEFAIL 0x00000008 #define EE_STAT_CRSRLEFTPARA 0x00000010 #define EE_STAT_TEXTWIDTHCHANGED 0x00000020 #define EE_STAT_TEXTHEIGHTCHANGED 0x00000040 #define EE_STAT_WRONGWORDCHANGED 0x00000080 // #define EE_STAT_MODIFIED 0x00000100 /* EE_STAT_CRSRLEFTPARA at the time cursor movement and the enter. */ inline void SetFlags( sal_uLong& rBits, const sal_uInt32 nMask, bool bOn ) { if ( bOn ) rBits |= nMask; else rBits &= ~nMask; } class EditStatus { protected: sal_uLong nStatusBits; sal_uLong nControlBits; sal_uInt16 nPrevPara; // for EE_STAT_CRSRLEFTPARA public: EditStatus() { nStatusBits = 0; nControlBits = 0; nPrevPara = 0xFFFF; } void Clear() { nStatusBits = 0; } void SetControlBits( sal_uLong nMask, bool bOn ) { SetFlags( nControlBits, nMask, bOn ); } sal_uLong GetStatusWord() const { return nStatusBits; } sal_uLong& GetStatusWord() { return nStatusBits; } sal_uLong GetControlWord() const { return nControlBits; } sal_uLong& GetControlWord() { return nControlBits; } sal_uInt16 GetPrevParagraph() const { return nPrevPara; } sal_uInt16& GetPrevParagraph() { return nPrevPara; } }; #define SPELLCMD_IGNOREWORD 0x0001 #define SPELLCMD_STARTSPELLDLG 0x0002 #define SPELLCMD_ADDTODICTIONARY 0x0003 #define SPELLCMD_WORDLANGUAGE 0x0004 #define SPELLCMD_PARALANGUAGE 0x0005 struct SpellCallbackInfo { sal_uInt16 nCommand; String aWord; LanguageType eLanguage; SpellCallbackInfo( sal_uInt16 nCMD, const String& rWord ) : aWord( rWord ) { nCommand = nCMD; eLanguage = LANGUAGE_DONTKNOW; } SpellCallbackInfo( sal_uInt16 nCMD, LanguageType eLang ) { nCommand = nCMD; eLanguage = eLang; } }; #endif // _EDITSTAT_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>convert include/editeng/editstate.hxx from String to OUString<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef _EDITSTAT_HXX #define _EDITSTAT_HXX #include <tools/string.hxx> #include <i18nlangtag/lang.h> #define EE_CNTRL_USECHARATTRIBS 0x00000001 // Use of hard character attributes #define EE_CNTRL_USEPARAATTRIBS 0x00000002 // Using paragraph attributes. #define EE_CNTRL_CRSRLEFTPARA 0x00000004 // Cursor is moved to another paragraph #define EE_CNTRL_DOIDLEFORMAT 0x00000008 // Formatting idle #define EE_CNTRL_PASTESPECIAL 0x00000010 // Allow PasteSpecial #define EE_CNTRL_AUTOINDENTING 0x00000020 // Automatic indenting #define EE_CNTRL_UNDOATTRIBS 0x00000040 // Undo for Attributes.... #define EE_CNTRL_ONECHARPERLINE 0x00000080 // One character per line #define EE_CNTRL_NOCOLORS 0x00000100 // Engine: No Color #define EE_CNTRL_OUTLINER 0x00000200 // Special treatment Outliner/Outline mode #define EE_CNTRL_OUTLINER2 0x00000400 // Special treatment Outliner/Page #define EE_CNTRL_ALLOWBIGOBJS 0x00000800 // Portion info in text object #define EE_CNTRL_ONLINESPELLING 0x00001000 // During the edit Spelling #define EE_CNTRL_STRETCHING 0x00002000 // Stretch mode #define EE_CNTRL_MARKFIELDS 0x00004000 // Mark Fields with color #define EE_CNTRL_URLSFXEXECUTE 0x00008000 // !!!OLD!!!: SFX-URL-Execute. #define EE_CNTRL_RESTOREFONT 0x00010000 // Restore Font in OutDev #define EE_CNTRL_RTFSTYLESHEETS 0x00020000 // Use Stylesheets when imported //#define EE_CNTRL_NOREDLINES 0x00040000 // No RedLines when OnlineSpellError /* removed #i91949 */ #define EE_CNTRL_AUTOCORRECT 0x00080000 // AutoCorrect #define EE_CNTRL_AUTOCOMPLETE 0x00100000 // AutoComplete #define EE_CNTRL_AUTOPAGESIZEX 0x00200000 // Adjust paper width to Text #define EE_CNTRL_AUTOPAGESIZEY 0x00400000 // Adjust paper height to Text #define EE_CNTRL_AUTOPAGESIZE (EE_CNTRL_AUTOPAGESIZEX|EE_CNTRL_AUTOPAGESIZEY) #define EE_CNTRL_TABINDENTING 0x00800000 // Indent with tab #define EE_CNTRL_FORMAT100 0x01000000 // Always format to 100% #define EE_CNTRL_ULSPACESUMMATION 0x02000000 // MS Compat: sum SA and SB, not maximum value #define EE_CNTRL_ULSPACEFIRSTPARA 0x04000000 // MS Compat: evaluate also at the first paragraph #define EV_CNTRL_AUTOSCROLL 0x00000001 // Auto scrolling horizontally #define EV_CNTRL_BIGSCROLL 0x00000002 // Scroll further to the cursor #define EV_CNTRL_ENABLEPASTE 0x00000004 // Enable Paste #define EV_CNTRL_SINGLELINEPASTE 0x00000008 // View: Paste in input line ... #define EV_CNTRL_OVERWRITE 0x00000010 // Overwrite mode #define EV_CNTRL_INVONEMORE 0x00000020 // Invalidate one pixel more #define EV_CNTRL_AUTOSIZEX 0x00000040 // Automatically adapt to text width #define EV_CNTRL_AUTOSIZEY 0x00000080 // Automatically adapt to Text width #define EV_CNTRL_AUTOSIZE (EV_CNTRL_AUTOSIZEX|EV_CNTRL_AUTOSIZEY) #define EE_STAT_HSCROLL 0x00000001 #define EE_STAT_VSCROLL 0x00000002 #define EE_STAT_CURSOROUT 0x00000004 #define EE_STAT_CRSRMOVEFAIL 0x00000008 #define EE_STAT_CRSRLEFTPARA 0x00000010 #define EE_STAT_TEXTWIDTHCHANGED 0x00000020 #define EE_STAT_TEXTHEIGHTCHANGED 0x00000040 #define EE_STAT_WRONGWORDCHANGED 0x00000080 // #define EE_STAT_MODIFIED 0x00000100 /* EE_STAT_CRSRLEFTPARA at the time cursor movement and the enter. */ inline void SetFlags( sal_uLong& rBits, const sal_uInt32 nMask, bool bOn ) { if ( bOn ) rBits |= nMask; else rBits &= ~nMask; } class EditStatus { protected: sal_uLong nStatusBits; sal_uLong nControlBits; sal_uInt16 nPrevPara; // for EE_STAT_CRSRLEFTPARA public: EditStatus() { nStatusBits = 0; nControlBits = 0; nPrevPara = 0xFFFF; } void Clear() { nStatusBits = 0; } void SetControlBits( sal_uLong nMask, bool bOn ) { SetFlags( nControlBits, nMask, bOn ); } sal_uLong GetStatusWord() const { return nStatusBits; } sal_uLong& GetStatusWord() { return nStatusBits; } sal_uLong GetControlWord() const { return nControlBits; } sal_uLong& GetControlWord() { return nControlBits; } sal_uInt16 GetPrevParagraph() const { return nPrevPara; } sal_uInt16& GetPrevParagraph() { return nPrevPara; } }; #define SPELLCMD_IGNOREWORD 0x0001 #define SPELLCMD_STARTSPELLDLG 0x0002 #define SPELLCMD_ADDTODICTIONARY 0x0003 #define SPELLCMD_WORDLANGUAGE 0x0004 #define SPELLCMD_PARALANGUAGE 0x0005 struct SpellCallbackInfo { sal_uInt16 nCommand; OUString aWord; LanguageType eLanguage; SpellCallbackInfo( sal_uInt16 nCMD, const OUString& rWord ) : aWord( rWord ) { nCommand = nCMD; eLanguage = LANGUAGE_DONTKNOW; } SpellCallbackInfo( sal_uInt16 nCMD, LanguageType eLang ) { nCommand = nCMD; eLanguage = eLang; } }; #endif // _EDITSTAT_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************ * flatten_iterator.hpp * ESA++ * * Copyright (c) 2014, Chi-En Wu * Distributed under The BSD 3-Clause License ************************************************/ #ifndef ESAPP_FLATTEN_ITERATOR_HPP_ #define ESAPP_FLATTEN_ITERATOR_HPP_ #include <memory> #include <type_traits> #include <utility> #include "generator.hpp" namespace esapp { template <typename I> class flatten_iterator; /************************************************ * Inline Helper Function(s) ************************************************/ template <typename Iterable> inline auto make_flatten_iterator(Iterable const &iterable) -> flatten_iterator<decltype(iterable.begin())> { typedef decltype(make_flatten_iterator(iterable)) it_t; return it_t(iterable.begin(), iterable.end()); } /************************************************ * Declaration: class flatten_iterator ************************************************/ template <typename Iterator> class flatten_iterator : public generator< flatten_iterator<Iterator>, Iterator, typename std::remove_const< typename std::remove_reference< decltype(*(std::declval<Iterator>()->begin())) >::type >::type > { private: // Private Type(s) typedef generator< flatten_iterator, Iterator, typename std::remove_const< typename std::remove_reference< decltype(*(std::declval<Iterator>()->begin())) >::type >::type > supercls_t; public: // Public Type(s) typedef typename supercls_t::iterator_category iterator_category; typedef typename supercls_t::value_type value_type; typedef typename supercls_t::reference reference; typedef typename supercls_t::pointer pointer; typedef typename supercls_t::difference_type difference_type; typedef typename supercls_t::input_iterator input_iterator; typedef decltype(std::declval<Iterator>()->begin()) value_iterator; public: // Public Method(s) flatten_iterator(void) = default; flatten_iterator(input_iterator const &begin, input_iterator const &end); flatten_iterator(flatten_iterator const &it); flatten_iterator end(void) const; void next(void); reference dereference(void) const; bool equal(flatten_iterator const &it) const; private: // Private Method(s) flatten_iterator(input_iterator const &begin, input_iterator const &end, std::unique_ptr<value_iterator> &&val_it_ptr); private: // Private Property(ies) std::unique_ptr<value_iterator> val_it_ptr_; }; // class flatten_iterator /************************************************ * Implementation: class flatten_iterator ************************************************/ template <typename I> inline flatten_iterator<I>::flatten_iterator(input_iterator const &begin, input_iterator const &end) : supercls_t(begin, end), val_it_ptr_(nullptr) { if (this->it_ != this->end_) { val_it_ptr_.reset(new value_iterator(this->it_->begin())); } } template <typename I> inline flatten_iterator<I>::flatten_iterator(flatten_iterator const &it) : supercls_t(it.it_, it.end_) { if (it.val_it_ptr_.get() != nullptr) { val_it_ptr_.reset(new value_iterator(*(it.val_it_ptr_))); } else { val_it_ptr_.reset(); } } template <typename I> inline flatten_iterator<I>::flatten_iterator(input_iterator const &begin, input_iterator const &end, std::unique_ptr<value_iterator> &&val_it_ptr) : supercls_t(begin, end), val_it_ptr_(std::move(val_it_ptr)) { // do nothing } template <typename I> inline flatten_iterator<I> flatten_iterator<I>::end(void) const { return flatten_iterator(this->end_, this->end_, decltype(val_it_ptr_)(nullptr)); } template <typename I> inline void flatten_iterator<I>::next(void) { if (++(*val_it_ptr_) == this->it_->end()) { if (++this->it_ == this->end_) { val_it_ptr_.reset(); } else { *val_it_ptr_ = this->it_->begin(); } } } template <typename I> inline typename flatten_iterator<I>::reference flatten_iterator<I>::dereference(void) const { return **val_it_ptr_; } template <typename I> inline bool flatten_iterator<I>::equal(flatten_iterator const &it) const { if (val_it_ptr_) { return (bool) it.val_it_ptr_; } else if (it.val_it_ptr_) { return false; } return *val_it_ptr_ == *(it.val_it_ptr_); } } // namespace esapp #endif // ESAPP_FLATTEN_ITERATOR_HPP_ <commit_msg>Correct indentations<commit_after>/************************************************ * flatten_iterator.hpp * ESA++ * * Copyright (c) 2014, Chi-En Wu * Distributed under The BSD 3-Clause License ************************************************/ #ifndef ESAPP_FLATTEN_ITERATOR_HPP_ #define ESAPP_FLATTEN_ITERATOR_HPP_ #include <memory> #include <type_traits> #include <utility> #include "generator.hpp" namespace esapp { template <typename I> class flatten_iterator; /************************************************ * Inline Helper Function(s) ************************************************/ template <typename Iterable> inline auto make_flatten_iterator(Iterable const &iterable) -> flatten_iterator<decltype(iterable.begin())> { typedef decltype(make_flatten_iterator(iterable)) it_t; return it_t(iterable.begin(), iterable.end()); } /************************************************ * Declaration: class flatten_iterator ************************************************/ template <typename Iterator> class flatten_iterator : public generator< flatten_iterator<Iterator>, Iterator, typename std::remove_const< typename std::remove_reference< decltype(*(std::declval<Iterator>()->begin())) >::type >::type > { private: // Private Type(s) typedef generator< flatten_iterator, Iterator, typename std::remove_const< typename std::remove_reference< decltype(*(std::declval<Iterator>()->begin())) >::type >::type > supercls_t; public: // Public Type(s) typedef typename supercls_t::iterator_category iterator_category; typedef typename supercls_t::value_type value_type; typedef typename supercls_t::reference reference; typedef typename supercls_t::pointer pointer; typedef typename supercls_t::difference_type difference_type; typedef typename supercls_t::input_iterator input_iterator; typedef decltype(std::declval<Iterator>()->begin()) value_iterator; public: // Public Method(s) flatten_iterator(void) = default; flatten_iterator(input_iterator const &begin, input_iterator const &end); flatten_iterator(flatten_iterator const &it); flatten_iterator end(void) const; void next(void); reference dereference(void) const; bool equal(flatten_iterator const &it) const; private: // Private Method(s) flatten_iterator(input_iterator const &begin, input_iterator const &end, std::unique_ptr<value_iterator> &&val_it_ptr); private: // Private Property(ies) std::unique_ptr<value_iterator> val_it_ptr_; }; // class flatten_iterator /************************************************ * Implementation: class flatten_iterator ************************************************/ template <typename I> inline flatten_iterator<I>::flatten_iterator(input_iterator const &begin, input_iterator const &end) : supercls_t(begin, end), val_it_ptr_(nullptr) { if (this->it_ != this->end_) { val_it_ptr_.reset(new value_iterator(this->it_->begin())); } } template <typename I> inline flatten_iterator<I>::flatten_iterator(flatten_iterator const &it) : supercls_t(it.it_, it.end_) { if (it.val_it_ptr_.get() != nullptr) { val_it_ptr_.reset(new value_iterator(*(it.val_it_ptr_))); } else { val_it_ptr_.reset(); } } template <typename I> inline flatten_iterator<I>::flatten_iterator( input_iterator const &begin, input_iterator const &end, std::unique_ptr<value_iterator> &&val_it_ptr) : supercls_t(begin, end), val_it_ptr_(std::move(val_it_ptr)) { // do nothing } template <typename I> inline flatten_iterator<I> flatten_iterator<I>::end(void) const { return flatten_iterator(this->end_, this->end_, decltype(val_it_ptr_)(nullptr)); } template <typename I> inline void flatten_iterator<I>::next(void) { if (++(*val_it_ptr_) == this->it_->end()) { if (++this->it_ == this->end_) { val_it_ptr_.reset(); } else { *val_it_ptr_ = this->it_->begin(); } } } template <typename I> inline typename flatten_iterator<I>::reference flatten_iterator<I>::dereference(void) const { return **val_it_ptr_; } template <typename I> inline bool flatten_iterator<I>::equal(flatten_iterator const &it) const { if (val_it_ptr_) { return (bool) it.val_it_ptr_; } else if (it.val_it_ptr_) { return false; } return *val_it_ptr_ == *(it.val_it_ptr_); } } // namespace esapp #endif // ESAPP_FLATTEN_ITERATOR_HPP_ <|endoftext|>
<commit_before>/* * Agent.cpp * * The reinforcement learning agent: the core of the project */ #include <vector> #include <chrono> #include <math.h> #include <stdio.h> #include <fstream> #include <string> #include <sstream> #include <algorithm> #include <iostream> #include <Box2D/Box2D.h> #include "Agent.h" #include "../PinballBot.h" #include "State.h" #include "../action/Action.h" const int Agent::STATES_TO_BACKPORT = 35; const float Agent::VALUE_ADJUST_FRACTION = 0.4f; const float Agent::EPSILON = 0.2f; const std::string Agent::POLICIES_HEADER_POSITION_X = "POSITION_X"; const std::string Agent::POLICIES_HEADER_POSITION_Y = "POSITION_Y"; const std::string Agent::POLICIES_HEADER_VELOCITY_X = "VELOCITY_X"; const std::string Agent::POLICIES_HEADER_VELOCITY_Y = "VELOCITY_Y"; const int Agent::POLICIES_HEADER_ACTIONS_OFFSET = 4; const std::string Agent::POLICIES_HEADER_ACTION_PREFIX = "ACTION_"; Agent::Agent(std::vector<Action*> availableActions): availableActions(availableActions), generator(seed()){ //causes an std::bad_alloc on some systems //states.reserve(std::pow(2, 20));//reserves a lot a space, enough space for 2^20 = 1'048'576 elements loadPolicyFromFile(); } void Agent::think(State state, std::vector<float> collectedRewards){ int currentStateIndex = 0; float lastValue; //first check whether this state already occurred or not and retrieve the iterator std::vector<State>::iterator it = std::lower_bound(states.begin(), states.end(), state); currentStateIndex = (it - states.begin()); if(currentStateIndex >= states.size() || states[currentStateIndex] != state){ //If its a new state, add it at the *right* position to prevent a sort it = states.insert(it, state); //As we inserted an element we need to increase the index of all after the new one for(int i=0;i<lastActions.size();i++){ if(lastActions[i].first >= currentStateIndex){ lastActions[i].first++; } } } /* * Maybe (actually most of the time in a pinball game) the good/bad reward isn't simply caused by the last action taken * A series of actions and events have lead to this specific situation, so we need to apply the reward received for the last action * to the last state in general, in other words to every possible action * * Example: * State 0: Action: EnableFlipperLeft Reward: 0.0f Cause: Ball leaves the CF in the direction of a pin * State 10: Action: DisableFlipperRight Reward: 0.0f Cause: Nothing, ball is still travelling in the direction of the pin * State 15: Action: DisableFlipperRight Reward: 1.0f Cause: Nothing BUT the ball kicked in state 0 hits the pin and causes a reward of 1.0f * * Now we want to series of actions taken from the last few states to occur more often because we know it was "good" * We now want to apply the reward received in state 15 to the actions taken in the last few steps */ //"strange" syntax because it should be more efficient this way if(collectedRewards.size() == 0){ for(int i=1;i<lastActions.size();i++){ lastValue = states[lastActions[i].first].getValue(lastActions[i].second); /* * If there was no reward we want to port the average value of the current state back * in order to ensure it will occur more or less often. To do that, we simply converge all * values of the previous to the average of one before */ //printf("No rewards; %f is adjusted by %f. Current value for %s: %f\n", lastValue, ((VALUE_ADJUST_FRACTION) * (states[lastActions[i-1].first].getAverageValue() - lastValue)), lastActions[i].second->getUID(), lastValue + ((VALUE_ADJUST_FRACTION) * (states[lastActions[i-1].first].getAverageValue() - lastValue))); lastValue = lastValue + ((VALUE_ADJUST_FRACTION) * (states[lastActions[i-1].first].getAverageValue() - lastValue)); states[lastActions[i].first].setValue(lastActions[i].second, lastValue); } }else{ for(int i=0;i<lastActions.size();i++){ lastValue = states[lastActions[i].first].getValue(lastActions[i].second); //printf("%lu rewards were collected:\n", collectedRewards.size()); //Apply all collected rewards, they can't be simply added up because then values greater than 1.0f would be possible for(int j=0;j<collectedRewards.size();j++){ /* As currently we don't know more than that what we did in the last state and what the result is, we create a "connection" between the action and the reward * If we receive a good reward (1.0f) the epsilonGreedy() function is more likely to select this action in exactly this state again */ //printf(" %f adjusts the value by %f. Current value: %f\n", collectedRewards[j], ((VALUE_ADJUST_FRACTION) * (collectedRewards[j] - lastValue)), lastValue + ((VALUE_ADJUST_FRACTION) * (collectedRewards[j] - lastValue))); lastValue = lastValue + ((VALUE_ADJUST_FRACTION) * (collectedRewards[j] - lastValue)); } states[lastActions[i].first].setValue(lastActions[i].second, lastValue); //printf("The current value for %s is %f.\n", lastActions[i].second->getUID(), lastValue); } } //then decide what action to take next Action* actionToTake = this->epsilonGreedy(states[currentStateIndex], EPSILON); //and the JUST DO IT actionToTake->run(); lastActions.push_back(std::make_pair(currentStateIndex, actionToTake)); if(lastActions.size() > STATES_TO_BACKPORT){ for(int i=0;i<(lastActions.size() - STATES_TO_BACKPORT);i++){ lastActions.pop_front(); } } } unsigned Agent::seed(){ return (unsigned) std::chrono::system_clock::now().time_since_epoch().count(); } float Agent::randomFloatInRange(const float &min, const float &max){ std::uniform_real_distribution<float> distribution = std::uniform_real_distribution<float>(min, max); return distribution(generator); } int Agent::randomIntInRange(const int &min, const int &max){ std::uniform_int_distribution<int> distribution = std::uniform_int_distribution<int>(min, max); return distribution(generator); } /*Action Agent::softmax(State state, unsigned long temperature){ std::vector<double> probabilities(states.size()); float numerator, denominator; for(int i = 0;i<availableActions.size();i++){ } for(int i=0;i<states.size();i++){ probabilities[i] = 0; } }*/ Action* Agent::epsilonGreedy(State state, const float &epsilon){ if(epsilon < randomFloatInRange(0.0f, 1.0f)){ //pick a greedy state return greedy(state); }else{ //pick a random state return random(availableActions); } } Action* Agent::greedy(State state){ float maxValue = 0; float tmpValue; std::vector<Action*> maxActions; for(int i=0;i<availableActions.size();i++){ tmpValue = state.getValue(availableActions[i]); if(tmpValue > maxValue){ maxValue = tmpValue; maxActions.clear(); maxActions.push_back(availableActions[i]); }else if(tmpValue == maxValue){ maxActions.push_back(availableActions[i]); } } if(maxActions.size() == 1){ return maxActions[0]; }else{ return random(maxActions); } } Action* Agent::random(std::vector<Action*> availableActions){ return availableActions[randomIntInRange(0, availableActions.size()-1)]; } void Agent::savePoliciesToFile(){ if(states.size() != 0){ std::ofstream policies; policies.open(PinballBot::POLICIES_FILE); //Generate header policies << POLICIES_HEADER_POSITION_X << ";" << POLICIES_HEADER_POSITION_Y << ";" << POLICIES_HEADER_VELOCITY_X << ";" << POLICIES_HEADER_VELOCITY_Y; for(int i=0;i<availableActions.size();i++){ policies << ";" << POLICIES_HEADER_ACTION_PREFIX << availableActions[i]->getUID(); } policies << std::endl; //and the content in the same order for(int i=0;i<states.size();i++){ policies << states[i].ballPosition.x << ";" << states[i].ballPosition.y << ";" << states[i].ballVelocity.x << ";" << states[i].ballVelocity.y; for(int j=0;j<availableActions.size();j++){ if(states[i].values.find(availableActions[j]) == states[i].values.end()){ policies << ";" << Action::DEFAULT_REWARD; //printf("DEFAULT Value: %f\n", Action::DEFAULT_REWARD); }else{ policies << ";" << (states[i].getValue(availableActions[j])); //printf("Value: %f\n", (states[i].getValue(availableActions[j]))); } } policies << std::endl; } } } void Agent::loadPolicyFromFile(){ std::string line, header; std::ifstream policies; std::vector<std::string> partials, headerPartials; states.clear(); printf("Reading and parsing %s....\n", PinballBot::POLICIES_FILE.c_str()); policies.open(PinballBot::POLICIES_FILE); if(std::getline(policies, header)){ split(header, ';', headerPartials); while (std::getline(policies, line)){ b2Vec2 ballPosition; b2Vec2 ballVelocity; bool posX = false, posY = false, velX = false, velY = false, stateInit = false; State state; split(line, ';', partials); if(partials.size() != headerPartials.size()){ printf("ERROR: Line %lu of %s doesn't have the same amount of columns as the header!\n", (states.size() + 1), PinballBot::POLICIES_FILE.c_str()); break; } for(int i=0;i<partials.size();i++){ //init state with values as soon as all the necessary values are loaded if((posX && posY && velX && velY) && !stateInit){ state = State(ballPosition, ballVelocity, availableActions); stateInit = true; } if(headerPartials[i] == POLICIES_HEADER_POSITION_X){ ballPosition.x = stof(partials[i]); posX = true; }else if(headerPartials[i] == POLICIES_HEADER_POSITION_Y){ ballPosition.y = stof(partials[i]); posY = true; }else if(headerPartials[i] == POLICIES_HEADER_VELOCITY_X){ ballVelocity.x = stof(partials[i]); velX = true; }else if(headerPartials[i] == POLICIES_HEADER_VELOCITY_Y){ ballVelocity.y = stof(partials[i]); velY = true; }else if(stateInit){ for(int j=0; j<availableActions.size(); j++){ if(headerPartials[i] == (POLICIES_HEADER_ACTION_PREFIX + std::string(availableActions[j]->getUID()))){ state.values[availableActions[j]] = stof(partials[POLICIES_HEADER_ACTIONS_OFFSET + j]); } } } } // push new state to states if all values are loaded if(posX && posY && velX && velY && stateInit){ states.push_back(state); } partials.clear(); } } printf("Read and parsed %s, %lu states were imported.\n", PinballBot::POLICIES_FILE.c_str(), states.size()); return; } std::vector<std::string> Agent::split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } <commit_msg>*typos ^^<commit_after>/* * Agent.cpp * * The reinforcement learning agent: the core of the project */ #include <vector> #include <chrono> #include <math.h> #include <stdio.h> #include <fstream> #include <string> #include <sstream> #include <algorithm> #include <iostream> #include <Box2D/Box2D.h> #include "Agent.h" #include "../PinballBot.h" #include "State.h" #include "../action/Action.h" const int Agent::STATES_TO_BACKPORT = 35; const float Agent::VALUE_ADJUST_FRACTION = 0.4f; const float Agent::EPSILON = 0.2f; const std::string Agent::POLICIES_HEADER_POSITION_X = "POSITION_X"; const std::string Agent::POLICIES_HEADER_POSITION_Y = "POSITION_Y"; const std::string Agent::POLICIES_HEADER_VELOCITY_X = "VELOCITY_X"; const std::string Agent::POLICIES_HEADER_VELOCITY_Y = "VELOCITY_Y"; const int Agent::POLICIES_HEADER_ACTIONS_OFFSET = 4; const std::string Agent::POLICIES_HEADER_ACTION_PREFIX = "ACTION_"; Agent::Agent(std::vector<Action*> availableActions): availableActions(availableActions), generator(seed()){ //causes an std::bad_alloc on some systems //states.reserve(std::pow(2, 20));//reserves a lot a space, enough space for 2^20 = 1'048'576 elements loadPolicyFromFile(); } void Agent::think(State state, std::vector<float> collectedRewards){ int currentStateIndex = 0; float lastValue; //first check whether this state already occurred or not and retrieve the iterator std::vector<State>::iterator it = std::lower_bound(states.begin(), states.end(), state); currentStateIndex = (it - states.begin()); if(currentStateIndex >= states.size() || states[currentStateIndex] != state){ //If its a new state, add it at the *right* position to prevent a sort it = states.insert(it, state); //As we inserted an element we need to increase the index of all after the new one for(int i=0;i<lastActions.size();i++){ if(lastActions[i].first >= currentStateIndex){ lastActions[i].first++; } } } /* * Maybe (actually most of the time in a pinball game) the good/bad reward isn't simply caused by the last action taken * A series of actions and events have lead to this specific situation, so we need to apply the reward received for the last action * to the last state in general, in other words to every possible action * * Example: * State 0: Action: EnableFlipperLeft Reward: 0.0f Cause: Ball leaves the CF in the direction of a pin * State 10: Action: DisableFlipperRight Reward: 0.0f Cause: Nothing, ball is still traveling in the direction of the pin * State 15: Action: DisableFlipperRight Reward: 1.0f Cause: Nothing BUT the ball kicked in state 0 hits the pin and causes a reward of 1.0f * * Now we want to series of actions taken from the last few states to occur more often because we know it was "good" * We now want to apply the reward received in state 15 to the actions taken in the last few steps */ //"strange" syntax because it should be more efficient this way if(collectedRewards.size() == 0){ for(int i=1;i<lastActions.size();i++){ lastValue = states[lastActions[i].first].getValue(lastActions[i].second); /* * If there was no reward we want to port the average value of the current state back * in order to ensure it will occur more or less often. To do that, we simply converge all * values of the previous to the average of one before */ //printf("No rewards; %f is adjusted by %f. Current value for %s: %f\n", lastValue, ((VALUE_ADJUST_FRACTION) * (states[lastActions[i-1].first].getAverageValue() - lastValue)), lastActions[i].second->getUID(), lastValue + ((VALUE_ADJUST_FRACTION) * (states[lastActions[i-1].first].getAverageValue() - lastValue))); lastValue = lastValue + ((VALUE_ADJUST_FRACTION) * (states[lastActions[i-1].first].getAverageValue() - lastValue)); states[lastActions[i].first].setValue(lastActions[i].second, lastValue); } }else{ for(int i=0;i<lastActions.size();i++){ lastValue = states[lastActions[i].first].getValue(lastActions[i].second); //printf("%lu rewards were collected:\n", collectedRewards.size()); //Apply all collected rewards, they can't be simply added up because then values greater than 1.0f would be possible for(int j=0;j<collectedRewards.size();j++){ /* As currently we don't know more than that what we did in the last state and what the result is, we create a "connection" between the action and the reward * If we receive a good reward (1.0f) the epsilonGreedy() function is more likely to select this action in exactly this state again */ //printf(" %f adjusts the value by %f. Current value: %f\n", collectedRewards[j], ((VALUE_ADJUST_FRACTION) * (collectedRewards[j] - lastValue)), lastValue + ((VALUE_ADJUST_FRACTION) * (collectedRewards[j] - lastValue))); lastValue = lastValue + ((VALUE_ADJUST_FRACTION) * (collectedRewards[j] - lastValue)); } states[lastActions[i].first].setValue(lastActions[i].second, lastValue); //printf("The current value for %s is %f.\n", lastActions[i].second->getUID(), lastValue); } } //then decide what action to take next Action* actionToTake = this->epsilonGreedy(states[currentStateIndex], EPSILON); //and the JUST DO IT actionToTake->run(); lastActions.push_back(std::make_pair(currentStateIndex, actionToTake)); if(lastActions.size() > STATES_TO_BACKPORT){ for(int i=0;i<(lastActions.size() - STATES_TO_BACKPORT);i++){ lastActions.pop_front(); } } } unsigned Agent::seed(){ return (unsigned) std::chrono::system_clock::now().time_since_epoch().count(); } float Agent::randomFloatInRange(const float &min, const float &max){ std::uniform_real_distribution<float> distribution = std::uniform_real_distribution<float>(min, max); return distribution(generator); } int Agent::randomIntInRange(const int &min, const int &max){ std::uniform_int_distribution<int> distribution = std::uniform_int_distribution<int>(min, max); return distribution(generator); } /*Action Agent::softmax(State state, unsigned long temperature){ std::vector<double> probabilities(states.size()); float numerator, denominator; for(int i = 0;i<availableActions.size();i++){ } for(int i=0;i<states.size();i++){ probabilities[i] = 0; } }*/ Action* Agent::epsilonGreedy(State state, const float &epsilon){ if(epsilon < randomFloatInRange(0.0f, 1.0f)){ //pick a greedy state return greedy(state); }else{ //pick a random state return random(availableActions); } } Action* Agent::greedy(State state){ float maxValue = 0; float tmpValue; std::vector<Action*> maxActions; for(int i=0;i<availableActions.size();i++){ tmpValue = state.getValue(availableActions[i]); if(tmpValue > maxValue){ maxValue = tmpValue; maxActions.clear(); maxActions.push_back(availableActions[i]); }else if(tmpValue == maxValue){ maxActions.push_back(availableActions[i]); } } if(maxActions.size() == 1){ return maxActions[0]; }else{ return random(maxActions); } } Action* Agent::random(std::vector<Action*> availableActions){ return availableActions[randomIntInRange(0, availableActions.size()-1)]; } void Agent::savePoliciesToFile(){ if(states.size() != 0){ std::ofstream policies; policies.open(PinballBot::POLICIES_FILE); //Generate header policies << POLICIES_HEADER_POSITION_X << ";" << POLICIES_HEADER_POSITION_Y << ";" << POLICIES_HEADER_VELOCITY_X << ";" << POLICIES_HEADER_VELOCITY_Y; for(int i=0;i<availableActions.size();i++){ policies << ";" << POLICIES_HEADER_ACTION_PREFIX << availableActions[i]->getUID(); } policies << std::endl; //and the content in the same order for(int i=0;i<states.size();i++){ policies << states[i].ballPosition.x << ";" << states[i].ballPosition.y << ";" << states[i].ballVelocity.x << ";" << states[i].ballVelocity.y; for(int j=0;j<availableActions.size();j++){ if(states[i].values.find(availableActions[j]) == states[i].values.end()){ policies << ";" << Action::DEFAULT_REWARD; //printf("DEFAULT Value: %f\n", Action::DEFAULT_REWARD); }else{ policies << ";" << (states[i].getValue(availableActions[j])); //printf("Value: %f\n", (states[i].getValue(availableActions[j]))); } } policies << std::endl; } } } void Agent::loadPolicyFromFile(){ std::string line, header; std::ifstream policies; std::vector<std::string> partials, headerPartials; states.clear(); printf("Reading and parsing %s....\n", PinballBot::POLICIES_FILE.c_str()); policies.open(PinballBot::POLICIES_FILE); if(std::getline(policies, header)){ split(header, ';', headerPartials); while (std::getline(policies, line)){ b2Vec2 ballPosition; b2Vec2 ballVelocity; bool posX = false, posY = false, velX = false, velY = false, stateInit = false; State state; split(line, ';', partials); if(partials.size() != headerPartials.size()){ printf("ERROR: Line %lu of %s doesn't have the same amount of columns as the header!\n", (states.size() + 1), PinballBot::POLICIES_FILE.c_str()); break; } for(int i=0;i<partials.size();i++){ //init state with values as soon as all the necessary values are loaded if((posX && posY && velX && velY) && !stateInit){ state = State(ballPosition, ballVelocity, availableActions); stateInit = true; } if(headerPartials[i] == POLICIES_HEADER_POSITION_X){ ballPosition.x = stof(partials[i]); posX = true; }else if(headerPartials[i] == POLICIES_HEADER_POSITION_Y){ ballPosition.y = stof(partials[i]); posY = true; }else if(headerPartials[i] == POLICIES_HEADER_VELOCITY_X){ ballVelocity.x = stof(partials[i]); velX = true; }else if(headerPartials[i] == POLICIES_HEADER_VELOCITY_Y){ ballVelocity.y = stof(partials[i]); velY = true; }else if(stateInit){ for(int j=0; j<availableActions.size(); j++){ if(headerPartials[i] == (POLICIES_HEADER_ACTION_PREFIX + std::string(availableActions[j]->getUID()))){ state.values[availableActions[j]] = stof(partials[POLICIES_HEADER_ACTIONS_OFFSET + j]); } } } } // push new state to states if all values are loaded if(posX && posY && velX && velY && stateInit){ states.push_back(state); } partials.clear(); } } printf("Read and parsed %s, %lu states were imported.\n", PinballBot::POLICIES_FILE.c_str(), states.size()); return; } std::vector<std::string> Agent::split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg, Daniel Wallin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_ALERT_HPP_INCLUDED #define TORRENT_ALERT_HPP_INCLUDED #include <memory> #include <queue> #include <string> #include <typeinfo> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/thread/mutex.hpp> #include <boost/thread/condition.hpp> #include <boost/preprocessor/repetition/enum_params_with_a_default.hpp> #include <boost/preprocessor/repetition/enum.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_shifted_params.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/time.hpp" #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" #ifndef TORRENT_MAX_ALERT_TYPES #define TORRENT_MAX_ALERT_TYPES 15 #endif namespace libtorrent { class TORRENT_EXPORT alert { public: // only here for backwards compatibility enum severity_t { debug, info, warning, critical, fatal, none }; enum category_t { error_notification = 0x1, peer_notification = 0x2, port_mapping_notification = 0x4, storage_notification = 0x8, tracker_notification = 0x10, debug_notification = 0x20, status_notification = 0x40, progress_notification = 0x80, ip_block_notification = 0x100, performance_warning = 0x200, dht_notification = 0x400, all_categories = 0xffffffff }; alert(); virtual ~alert(); // a timestamp is automatically created in the constructor ptime timestamp() const; virtual char const* what() const = 0; virtual std::string message() const = 0; virtual int category() const = 0; #ifndef TORRENT_NO_DEPRECATE severity_t severity() const TORRENT_DEPRECATED { return warning; } #endif virtual std::auto_ptr<alert> clone() const = 0; private: ptime m_timestamp; }; class TORRENT_EXPORT alert_manager { public: enum { queue_size_limit_default = 1000 }; alert_manager(); ~alert_manager(); void post_alert(const alert& alert_); bool pending() const; std::auto_ptr<alert> get(); template <class T> bool should_post() const { return (m_alert_mask & T::static_category) != 0; } alert const* wait_for_alert(time_duration max_wait); void set_alert_mask(int m) { m_alert_mask = m; } size_t alert_queue_size_limit() const { return m_queue_size_limit; } size_t set_alert_queue_size_limit(size_t queue_size_limit_); void set_dispatch_function(boost::function<void(alert const&)> const&); private: std::queue<alert*> m_alerts; mutable boost::mutex m_mutex; boost::condition m_condition; int m_alert_mask; size_t m_queue_size_limit; boost::function<void(alert const&)> m_dispatch; }; struct TORRENT_EXPORT unhandled_alert : std::exception { unhandled_alert() {} }; namespace detail { struct void_; template<class Handler , BOOST_PP_ENUM_PARAMS(TORRENT_MAX_ALERT_TYPES, class T)> void handle_alert_dispatch( const std::auto_ptr<alert>& alert_, const Handler& handler , const std::type_info& typeid_ , BOOST_PP_ENUM_BINARY_PARAMS(TORRENT_MAX_ALERT_TYPES, T, *p)) { if (typeid_ == typeid(T0)) handler(*static_cast<T0*>(alert_.get())); else handle_alert_dispatch(alert_, handler, typeid_ , BOOST_PP_ENUM_SHIFTED_PARAMS( TORRENT_MAX_ALERT_TYPES, p), (void_*)0); } template<class Handler> void handle_alert_dispatch( const std::auto_ptr<alert>& alert_ , const Handler& handler , const std::type_info& typeid_ , BOOST_PP_ENUM_PARAMS(TORRENT_MAX_ALERT_TYPES, void_* BOOST_PP_INTERCEPT)) { throw unhandled_alert(); } } // namespace detail template<BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT( TORRENT_MAX_ALERT_TYPES, class T, detail::void_)> struct TORRENT_EXPORT handle_alert { template<class Handler> handle_alert(const std::auto_ptr<alert>& alert_ , const Handler& handler) { #define ALERT_POINTER_TYPE(z, n, text) (BOOST_PP_CAT(T, n)*)0 detail::handle_alert_dispatch(alert_, handler, typeid(*alert_) , BOOST_PP_ENUM(TORRENT_MAX_ALERT_TYPES, ALERT_POINTER_TYPE, _)); #undef ALERT_POINTER_TYPE } }; } // namespace libtorrent #endif // TORRENT_ALERT_HPP_INCLUDED <commit_msg>added missing include directive<commit_after>/* Copyright (c) 2003, Arvid Norberg, Daniel Wallin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_ALERT_HPP_INCLUDED #define TORRENT_ALERT_HPP_INCLUDED #include <memory> #include <queue> #include <string> #include <typeinfo> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/thread/mutex.hpp> #include <boost/thread/condition.hpp> #include <boost/function.hpp> #include <boost/preprocessor/repetition/enum_params_with_a_default.hpp> #include <boost/preprocessor/repetition/enum.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_shifted_params.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/time.hpp" #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" #ifndef TORRENT_MAX_ALERT_TYPES #define TORRENT_MAX_ALERT_TYPES 15 #endif namespace libtorrent { class TORRENT_EXPORT alert { public: // only here for backwards compatibility enum severity_t { debug, info, warning, critical, fatal, none }; enum category_t { error_notification = 0x1, peer_notification = 0x2, port_mapping_notification = 0x4, storage_notification = 0x8, tracker_notification = 0x10, debug_notification = 0x20, status_notification = 0x40, progress_notification = 0x80, ip_block_notification = 0x100, performance_warning = 0x200, dht_notification = 0x400, all_categories = 0xffffffff }; alert(); virtual ~alert(); // a timestamp is automatically created in the constructor ptime timestamp() const; virtual char const* what() const = 0; virtual std::string message() const = 0; virtual int category() const = 0; #ifndef TORRENT_NO_DEPRECATE severity_t severity() const TORRENT_DEPRECATED { return warning; } #endif virtual std::auto_ptr<alert> clone() const = 0; private: ptime m_timestamp; }; class TORRENT_EXPORT alert_manager { public: enum { queue_size_limit_default = 1000 }; alert_manager(); ~alert_manager(); void post_alert(const alert& alert_); bool pending() const; std::auto_ptr<alert> get(); template <class T> bool should_post() const { return (m_alert_mask & T::static_category) != 0; } alert const* wait_for_alert(time_duration max_wait); void set_alert_mask(int m) { m_alert_mask = m; } size_t alert_queue_size_limit() const { return m_queue_size_limit; } size_t set_alert_queue_size_limit(size_t queue_size_limit_); void set_dispatch_function(boost::function<void(alert const&)> const&); private: std::queue<alert*> m_alerts; mutable boost::mutex m_mutex; boost::condition m_condition; int m_alert_mask; size_t m_queue_size_limit; boost::function<void(alert const&)> m_dispatch; }; struct TORRENT_EXPORT unhandled_alert : std::exception { unhandled_alert() {} }; namespace detail { struct void_; template<class Handler , BOOST_PP_ENUM_PARAMS(TORRENT_MAX_ALERT_TYPES, class T)> void handle_alert_dispatch( const std::auto_ptr<alert>& alert_, const Handler& handler , const std::type_info& typeid_ , BOOST_PP_ENUM_BINARY_PARAMS(TORRENT_MAX_ALERT_TYPES, T, *p)) { if (typeid_ == typeid(T0)) handler(*static_cast<T0*>(alert_.get())); else handle_alert_dispatch(alert_, handler, typeid_ , BOOST_PP_ENUM_SHIFTED_PARAMS( TORRENT_MAX_ALERT_TYPES, p), (void_*)0); } template<class Handler> void handle_alert_dispatch( const std::auto_ptr<alert>& alert_ , const Handler& handler , const std::type_info& typeid_ , BOOST_PP_ENUM_PARAMS(TORRENT_MAX_ALERT_TYPES, void_* BOOST_PP_INTERCEPT)) { throw unhandled_alert(); } } // namespace detail template<BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT( TORRENT_MAX_ALERT_TYPES, class T, detail::void_)> struct TORRENT_EXPORT handle_alert { template<class Handler> handle_alert(const std::auto_ptr<alert>& alert_ , const Handler& handler) { #define ALERT_POINTER_TYPE(z, n, text) (BOOST_PP_CAT(T, n)*)0 detail::handle_alert_dispatch(alert_, handler, typeid(*alert_) , BOOST_PP_ENUM(TORRENT_MAX_ALERT_TYPES, ALERT_POINTER_TYPE, _)); #undef ALERT_POINTER_TYPE } }; } // namespace libtorrent #endif // TORRENT_ALERT_HPP_INCLUDED <|endoftext|>
<commit_before>#include "SkBenchmark.h" #include "SkColorPriv.h" #include "SkMatrix.h" #include "SkRandom.h" #include "SkString.h" #include "SkPaint.h" static float sk_fsel(float pred, float result_ge, float result_lt) { return pred >= 0 ? result_ge : result_lt; } static float fast_floor(float x) { float big = sk_fsel(x, 0x1.0p+23, -0x1.0p+23); return (x + big) - big; } class MathBench : public SkBenchmark { enum { kBuffer = 100, kLoop = 10000 }; SkString fName; float fSrc[kBuffer], fDst[kBuffer]; public: MathBench(void* param, const char name[]) : INHERITED(param) { fName.printf("math_%s", name); SkRandom rand; for (int i = 0; i < kBuffer; ++i) { fSrc[i] = rand.nextSScalar1(); } } virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) = 0; protected: virtual int mulLoopCount() const { return 1; } virtual const char* onGetName() { return fName.c_str(); } virtual void onDraw(SkCanvas* canvas) { int n = SkBENCHLOOP(kLoop * this->mulLoopCount()); for (int i = 0; i < n; i++) { this->performTest(fDst, fSrc, kBuffer); } } private: typedef SkBenchmark INHERITED; }; class MathBenchU32 : public MathBench { public: MathBenchU32(void* param, const char name[]) : INHERITED(param, name) {} protected: virtual void performITest(uint32_t* SK_RESTRICT dst, const uint32_t* SK_RESTRICT src, int count) = 0; virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) SK_OVERRIDE { uint32_t* d = SkTCast<uint32_t*>(dst); const uint32_t* s = SkTCast<const uint32_t*>(src); this->performITest(d, s, count); } private: typedef MathBench INHERITED; }; /////////////////////////////////////////////////////////////////////////////// class NoOpMathBench : public MathBench { public: NoOpMathBench(void* param) : INHERITED(param, "noOp") {} protected: virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) { for (int i = 0; i < count; ++i) { dst[i] = src[i] + 1; } } private: typedef MathBench INHERITED; }; class SlowISqrtMathBench : public MathBench { public: SlowISqrtMathBench(void* param) : INHERITED(param, "slowIsqrt") {} protected: virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) { for (int i = 0; i < count; ++i) { dst[i] = 1.0f / sk_float_sqrt(src[i]); } } private: typedef MathBench INHERITED; }; static inline float SkFastInvSqrt(float x) { float xhalf = 0.5f*x; int i = *(int*)&x; i = 0x5f3759df - (i>>1); x = *(float*)&i; x = x*(1.5f-xhalf*x*x); // x = x*(1.5f-xhalf*x*x); // this line takes err from 10^-3 to 10^-6 return x; } class FastISqrtMathBench : public MathBench { public: FastISqrtMathBench(void* param) : INHERITED(param, "fastIsqrt") {} protected: virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) { for (int i = 0; i < count; ++i) { dst[i] = SkFastInvSqrt(src[i]); } } private: typedef MathBench INHERITED; }; static inline uint32_t QMul64(uint32_t value, U8CPU alpha) { SkASSERT((uint8_t)alpha == alpha); const uint32_t mask = 0xFF00FF; uint64_t tmp = value; tmp = (tmp & mask) | ((tmp & ~mask) << 24); tmp *= alpha; return ((tmp >> 8) & mask) | ((tmp >> 32) & ~mask); } class QMul64Bench : public MathBenchU32 { public: QMul64Bench(void* param) : INHERITED(param, "qmul64") {} protected: virtual void performITest(uint32_t* SK_RESTRICT dst, const uint32_t* SK_RESTRICT src, int count) SK_OVERRIDE { for (int i = 0; i < count; ++i) { dst[i] = QMul64(src[i], (uint8_t)i); } } private: typedef MathBenchU32 INHERITED; }; class QMul32Bench : public MathBenchU32 { public: QMul32Bench(void* param) : INHERITED(param, "qmul32") {} protected: virtual void performITest(uint32_t* SK_RESTRICT dst, const uint32_t* SK_RESTRICT src, int count) SK_OVERRIDE { for (int i = 0; i < count; ++i) { dst[i] = SkAlphaMulQ(src[i], (uint8_t)i); } } private: typedef MathBenchU32 INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static bool isFinite_int(float x) { uint32_t bits = SkFloat2Bits(x); // need unsigned for our shifts int exponent = bits << 1 >> 24; return exponent != 0xFF; } static bool isFinite_float(float x) { return SkToBool(sk_float_isfinite(x)); } static bool isFinite_mulzero(float x) { float y = x * 0; return y == y; } static bool isfinite_and_int(const float data[4]) { return isFinite_int(data[0]) && isFinite_int(data[1]) && isFinite_int(data[2]) && isFinite_int(data[3]); } static bool isfinite_and_float(const float data[4]) { return isFinite_float(data[0]) && isFinite_float(data[1]) && isFinite_float(data[2]) && isFinite_float(data[3]); } static bool isfinite_and_mulzero(const float data[4]) { return isFinite_mulzero(data[0]) && isFinite_mulzero(data[1]) && isFinite_mulzero(data[2]) && isFinite_mulzero(data[3]); } #define mulzeroadd(data) (data[0]*0 + data[1]*0 + data[2]*0 + data[3]*0) static bool isfinite_plus_int(const float data[4]) { return isFinite_int(mulzeroadd(data)); } static bool isfinite_plus_float(const float data[4]) { return !sk_float_isnan(mulzeroadd(data)); } static bool isfinite_plus_mulzero(const float data[4]) { float x = mulzeroadd(data); return x == x; } typedef bool (*IsFiniteProc)(const float[]); #define MAKEREC(name) { name, #name } static const struct { IsFiniteProc fProc; const char* fName; } gRec[] = { MAKEREC(isfinite_and_int), MAKEREC(isfinite_and_float), MAKEREC(isfinite_and_mulzero), MAKEREC(isfinite_plus_int), MAKEREC(isfinite_plus_float), MAKEREC(isfinite_plus_mulzero), }; #undef MAKEREC static bool isFinite(const SkRect& r) { // x * 0 will be NaN iff x is infinity or NaN. // a + b will be NaN iff either a or b is NaN. float value = r.fLeft * 0 + r.fTop * 0 + r.fRight * 0 + r.fBottom * 0; // value is either NaN or it is finite (zero). // value==value will be true iff value is not NaN return value == value; } class IsFiniteBench : public SkBenchmark { enum { N = SkBENCHLOOP(1000), NN = SkBENCHLOOP(1000), }; float fData[N]; public: IsFiniteBench(void* param, int index) : INHERITED(param) { SkRandom rand; for (int i = 0; i < N; ++i) { fData[i] = rand.nextSScalar1(); } if (index < 0) { fProc = NULL; fName = "isfinite_rect"; } else { fProc = gRec[index].fProc; fName = gRec[index].fName; } } protected: virtual void onDraw(SkCanvas* canvas) { IsFiniteProc proc = fProc; const float* data = fData; // do this so the compiler won't throw away the function call int counter = 0; if (proc) { for (int j = 0; j < NN; ++j) { for (int i = 0; i < N - 4; ++i) { counter += proc(&data[i]); } } } else { for (int j = 0; j < NN; ++j) { for (int i = 0; i < N - 4; ++i) { const SkRect* r = reinterpret_cast<const SkRect*>(&data[i]); counter += r->isFinite(); } } } SkPaint paint; if (paint.getAlpha() == 0) { SkDebugf("%d\n", counter); } } virtual const char* onGetName() { return fName; } private: IsFiniteProc fProc; const char* fName; typedef SkBenchmark INHERITED; }; class FloorBench : public SkBenchmark { enum { ARRAY = SkBENCHLOOP(1000), LOOP = SkBENCHLOOP(1000), }; float fData[ARRAY]; bool fFast; public: FloorBench(void* param, bool fast) : INHERITED(param), fFast(fast) { SkRandom rand; for (int i = 0; i < ARRAY; ++i) { fData[i] = rand.nextSScalar1(); } if (fast) { fName = "floor_fast"; } else { fName = "floor_std"; } } virtual void process(float) {} protected: virtual void onDraw(SkCanvas* canvas) { SkRandom rand; float accum = 0; const float* data = fData; float tmp[ARRAY] = {}; if (fFast) { for (int j = 0; j < LOOP; ++j) { for (int i = 0; i < ARRAY; ++i) { accum += fast_floor(data[i]); } this->process(accum); } } else { for (int j = 0; j < LOOP; ++j) { for (int i = 0; i < ARRAY; ++i) { accum += sk_float_floor(data[i]); } this->process(accum); } } } virtual const char* onGetName() { return fName; } private: const char* fName; typedef SkBenchmark INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static SkBenchmark* M0(void* p) { return new NoOpMathBench(p); } static SkBenchmark* M1(void* p) { return new SlowISqrtMathBench(p); } static SkBenchmark* M2(void* p) { return new FastISqrtMathBench(p); } static SkBenchmark* M3(void* p) { return new QMul64Bench(p); } static SkBenchmark* M4(void* p) { return new QMul32Bench(p); } static SkBenchmark* M5neg1(void* p) { return new IsFiniteBench(p, -1); } static SkBenchmark* M50(void* p) { return new IsFiniteBench(p, 0); } static SkBenchmark* M51(void* p) { return new IsFiniteBench(p, 1); } static SkBenchmark* M52(void* p) { return new IsFiniteBench(p, 2); } static SkBenchmark* M53(void* p) { return new IsFiniteBench(p, 3); } static SkBenchmark* M54(void* p) { return new IsFiniteBench(p, 4); } static SkBenchmark* M55(void* p) { return new IsFiniteBench(p, 5); } static SkBenchmark* F0(void* p) { return new FloorBench(p, false); } static SkBenchmark* F1(void* p) { return new FloorBench(p, true); } static BenchRegistry gReg0(M0); static BenchRegistry gReg1(M1); static BenchRegistry gReg2(M2); static BenchRegistry gReg3(M3); static BenchRegistry gReg4(M4); static BenchRegistry gReg5neg1(M5neg1); static BenchRegistry gReg50(M50); static BenchRegistry gReg51(M51); static BenchRegistry gReg52(M52); static BenchRegistry gReg53(M53); static BenchRegistry gReg54(M54); static BenchRegistry gReg55(M55); static BenchRegistry gRF0(F0); static BenchRegistry gRF1(F1); <commit_msg>apply 10.p+32 -> (float)(1 << 23) fix from MathTest here as well windows can't eat the former syntax<commit_after>#include "SkBenchmark.h" #include "SkColorPriv.h" #include "SkMatrix.h" #include "SkRandom.h" #include "SkString.h" #include "SkPaint.h" static float sk_fsel(float pred, float result_ge, float result_lt) { return pred >= 0 ? result_ge : result_lt; } static float fast_floor(float x) { // float big = sk_fsel(x, 0x1.0p+23, -0x1.0p+23); float big = sk_fsel(x, (float)(1 << 23), -(float)(1 << 23)); return (x + big) - big; } class MathBench : public SkBenchmark { enum { kBuffer = 100, kLoop = 10000 }; SkString fName; float fSrc[kBuffer], fDst[kBuffer]; public: MathBench(void* param, const char name[]) : INHERITED(param) { fName.printf("math_%s", name); SkRandom rand; for (int i = 0; i < kBuffer; ++i) { fSrc[i] = rand.nextSScalar1(); } } virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) = 0; protected: virtual int mulLoopCount() const { return 1; } virtual const char* onGetName() { return fName.c_str(); } virtual void onDraw(SkCanvas* canvas) { int n = SkBENCHLOOP(kLoop * this->mulLoopCount()); for (int i = 0; i < n; i++) { this->performTest(fDst, fSrc, kBuffer); } } private: typedef SkBenchmark INHERITED; }; class MathBenchU32 : public MathBench { public: MathBenchU32(void* param, const char name[]) : INHERITED(param, name) {} protected: virtual void performITest(uint32_t* SK_RESTRICT dst, const uint32_t* SK_RESTRICT src, int count) = 0; virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) SK_OVERRIDE { uint32_t* d = SkTCast<uint32_t*>(dst); const uint32_t* s = SkTCast<const uint32_t*>(src); this->performITest(d, s, count); } private: typedef MathBench INHERITED; }; /////////////////////////////////////////////////////////////////////////////// class NoOpMathBench : public MathBench { public: NoOpMathBench(void* param) : INHERITED(param, "noOp") {} protected: virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) { for (int i = 0; i < count; ++i) { dst[i] = src[i] + 1; } } private: typedef MathBench INHERITED; }; class SlowISqrtMathBench : public MathBench { public: SlowISqrtMathBench(void* param) : INHERITED(param, "slowIsqrt") {} protected: virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) { for (int i = 0; i < count; ++i) { dst[i] = 1.0f / sk_float_sqrt(src[i]); } } private: typedef MathBench INHERITED; }; static inline float SkFastInvSqrt(float x) { float xhalf = 0.5f*x; int i = *(int*)&x; i = 0x5f3759df - (i>>1); x = *(float*)&i; x = x*(1.5f-xhalf*x*x); // x = x*(1.5f-xhalf*x*x); // this line takes err from 10^-3 to 10^-6 return x; } class FastISqrtMathBench : public MathBench { public: FastISqrtMathBench(void* param) : INHERITED(param, "fastIsqrt") {} protected: virtual void performTest(float* SK_RESTRICT dst, const float* SK_RESTRICT src, int count) { for (int i = 0; i < count; ++i) { dst[i] = SkFastInvSqrt(src[i]); } } private: typedef MathBench INHERITED; }; static inline uint32_t QMul64(uint32_t value, U8CPU alpha) { SkASSERT((uint8_t)alpha == alpha); const uint32_t mask = 0xFF00FF; uint64_t tmp = value; tmp = (tmp & mask) | ((tmp & ~mask) << 24); tmp *= alpha; return ((tmp >> 8) & mask) | ((tmp >> 32) & ~mask); } class QMul64Bench : public MathBenchU32 { public: QMul64Bench(void* param) : INHERITED(param, "qmul64") {} protected: virtual void performITest(uint32_t* SK_RESTRICT dst, const uint32_t* SK_RESTRICT src, int count) SK_OVERRIDE { for (int i = 0; i < count; ++i) { dst[i] = QMul64(src[i], (uint8_t)i); } } private: typedef MathBenchU32 INHERITED; }; class QMul32Bench : public MathBenchU32 { public: QMul32Bench(void* param) : INHERITED(param, "qmul32") {} protected: virtual void performITest(uint32_t* SK_RESTRICT dst, const uint32_t* SK_RESTRICT src, int count) SK_OVERRIDE { for (int i = 0; i < count; ++i) { dst[i] = SkAlphaMulQ(src[i], (uint8_t)i); } } private: typedef MathBenchU32 INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static bool isFinite_int(float x) { uint32_t bits = SkFloat2Bits(x); // need unsigned for our shifts int exponent = bits << 1 >> 24; return exponent != 0xFF; } static bool isFinite_float(float x) { return SkToBool(sk_float_isfinite(x)); } static bool isFinite_mulzero(float x) { float y = x * 0; return y == y; } static bool isfinite_and_int(const float data[4]) { return isFinite_int(data[0]) && isFinite_int(data[1]) && isFinite_int(data[2]) && isFinite_int(data[3]); } static bool isfinite_and_float(const float data[4]) { return isFinite_float(data[0]) && isFinite_float(data[1]) && isFinite_float(data[2]) && isFinite_float(data[3]); } static bool isfinite_and_mulzero(const float data[4]) { return isFinite_mulzero(data[0]) && isFinite_mulzero(data[1]) && isFinite_mulzero(data[2]) && isFinite_mulzero(data[3]); } #define mulzeroadd(data) (data[0]*0 + data[1]*0 + data[2]*0 + data[3]*0) static bool isfinite_plus_int(const float data[4]) { return isFinite_int(mulzeroadd(data)); } static bool isfinite_plus_float(const float data[4]) { return !sk_float_isnan(mulzeroadd(data)); } static bool isfinite_plus_mulzero(const float data[4]) { float x = mulzeroadd(data); return x == x; } typedef bool (*IsFiniteProc)(const float[]); #define MAKEREC(name) { name, #name } static const struct { IsFiniteProc fProc; const char* fName; } gRec[] = { MAKEREC(isfinite_and_int), MAKEREC(isfinite_and_float), MAKEREC(isfinite_and_mulzero), MAKEREC(isfinite_plus_int), MAKEREC(isfinite_plus_float), MAKEREC(isfinite_plus_mulzero), }; #undef MAKEREC static bool isFinite(const SkRect& r) { // x * 0 will be NaN iff x is infinity or NaN. // a + b will be NaN iff either a or b is NaN. float value = r.fLeft * 0 + r.fTop * 0 + r.fRight * 0 + r.fBottom * 0; // value is either NaN or it is finite (zero). // value==value will be true iff value is not NaN return value == value; } class IsFiniteBench : public SkBenchmark { enum { N = SkBENCHLOOP(1000), NN = SkBENCHLOOP(1000), }; float fData[N]; public: IsFiniteBench(void* param, int index) : INHERITED(param) { SkRandom rand; for (int i = 0; i < N; ++i) { fData[i] = rand.nextSScalar1(); } if (index < 0) { fProc = NULL; fName = "isfinite_rect"; } else { fProc = gRec[index].fProc; fName = gRec[index].fName; } } protected: virtual void onDraw(SkCanvas* canvas) { IsFiniteProc proc = fProc; const float* data = fData; // do this so the compiler won't throw away the function call int counter = 0; if (proc) { for (int j = 0; j < NN; ++j) { for (int i = 0; i < N - 4; ++i) { counter += proc(&data[i]); } } } else { for (int j = 0; j < NN; ++j) { for (int i = 0; i < N - 4; ++i) { const SkRect* r = reinterpret_cast<const SkRect*>(&data[i]); counter += r->isFinite(); } } } SkPaint paint; if (paint.getAlpha() == 0) { SkDebugf("%d\n", counter); } } virtual const char* onGetName() { return fName; } private: IsFiniteProc fProc; const char* fName; typedef SkBenchmark INHERITED; }; class FloorBench : public SkBenchmark { enum { ARRAY = SkBENCHLOOP(1000), LOOP = SkBENCHLOOP(1000), }; float fData[ARRAY]; bool fFast; public: FloorBench(void* param, bool fast) : INHERITED(param), fFast(fast) { SkRandom rand; for (int i = 0; i < ARRAY; ++i) { fData[i] = rand.nextSScalar1(); } if (fast) { fName = "floor_fast"; } else { fName = "floor_std"; } } virtual void process(float) {} protected: virtual void onDraw(SkCanvas* canvas) { SkRandom rand; float accum = 0; const float* data = fData; float tmp[ARRAY] = {}; if (fFast) { for (int j = 0; j < LOOP; ++j) { for (int i = 0; i < ARRAY; ++i) { accum += fast_floor(data[i]); } this->process(accum); } } else { for (int j = 0; j < LOOP; ++j) { for (int i = 0; i < ARRAY; ++i) { accum += sk_float_floor(data[i]); } this->process(accum); } } } virtual const char* onGetName() { return fName; } private: const char* fName; typedef SkBenchmark INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static SkBenchmark* M0(void* p) { return new NoOpMathBench(p); } static SkBenchmark* M1(void* p) { return new SlowISqrtMathBench(p); } static SkBenchmark* M2(void* p) { return new FastISqrtMathBench(p); } static SkBenchmark* M3(void* p) { return new QMul64Bench(p); } static SkBenchmark* M4(void* p) { return new QMul32Bench(p); } static SkBenchmark* M5neg1(void* p) { return new IsFiniteBench(p, -1); } static SkBenchmark* M50(void* p) { return new IsFiniteBench(p, 0); } static SkBenchmark* M51(void* p) { return new IsFiniteBench(p, 1); } static SkBenchmark* M52(void* p) { return new IsFiniteBench(p, 2); } static SkBenchmark* M53(void* p) { return new IsFiniteBench(p, 3); } static SkBenchmark* M54(void* p) { return new IsFiniteBench(p, 4); } static SkBenchmark* M55(void* p) { return new IsFiniteBench(p, 5); } static SkBenchmark* F0(void* p) { return new FloorBench(p, false); } static SkBenchmark* F1(void* p) { return new FloorBench(p, true); } static BenchRegistry gReg0(M0); static BenchRegistry gReg1(M1); static BenchRegistry gReg2(M2); static BenchRegistry gReg3(M3); static BenchRegistry gReg4(M4); static BenchRegistry gReg5neg1(M5neg1); static BenchRegistry gReg50(M50); static BenchRegistry gReg51(M51); static BenchRegistry gReg52(M52); static BenchRegistry gReg53(M53); static BenchRegistry gReg54(M54); static BenchRegistry gReg55(M55); static BenchRegistry gRF0(F0); static BenchRegistry gRF1(F1); <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_ATTRIBUTE_HPP #define MAPNIK_ATTRIBUTE_HPP // mapnik #include <mapnik/value.hpp> // stl #include <string> namespace mapnik { static mapnik::value _null_value; struct attribute { std::string name_; explicit attribute(std::string const& name) : name_(name) {} template <typename V ,typename F> V const& value(F const& f) const { typedef typename F::const_iterator const_iterator; const_iterator itr = f.find(name_); if (itr != f.end()) { return itr->second; } return _null_value; } std::string const& name() const { return name_;} }; } #endif // MAPNIK_ATTRIBUTE_HPP <commit_msg>return by value<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_ATTRIBUTE_HPP #define MAPNIK_ATTRIBUTE_HPP // mapnik #include <mapnik/value.hpp> // stl #include <string> namespace mapnik { static mapnik::value _null_value; struct attribute { std::string name_; explicit attribute(std::string const& name) : name_(name) {} template <typename V ,typename F> V value(F const& f) const { typedef typename F::const_iterator const_iterator; const_iterator itr = f.find(name_); if (itr != f.end()) { return itr->second; } return _null_value; } std::string const& name() const { return name_;} }; } #endif // MAPNIK_ATTRIBUTE_HPP <|endoftext|>
<commit_before>/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBenchmark.h" #include "SkRandom.h" #include "SkTSort.h" #include "SkString.h" static const int N = 1000; static void rand_proc(int array[], int count) { SkRandom rand; for (int i = 0; i < count; ++i) { array[i] = rand.nextS(); } } static void randN_proc(int array[], int count) { SkRandom rand; int mod = N / 10; for (int i = 0; i < count; ++i) { array[i] = rand.nextU() % mod; } } static void forward_proc(int array[], int count) { for (int i = 0; i < count; ++i) { array[i] = i; } } static void backward_proc(int array[], int count) { for (int i = 0; i < count; ++i) { array[i] = -i; } } static void same_proc(int array[], int count) { for (int i = 0; i < count; ++i) { array[i] = count; } } typedef void (*SortProc)(int array[], int count); enum Type { kRand, kRandN, kFore, kBack, kSame }; static const struct { const char* fName; SortProc fProc; } gRec[] = { { "rand", rand_proc }, { "rand10", randN_proc }, { "forward", forward_proc }, { "backward", backward_proc }, { "repeated", same_proc }, }; static void skqsort_sort(int array[], int count) { SkTQSort<int>(array, array + count); } static void skheap_sort(int array[], int count) { SkTHeapSort<int>(array, count); } extern "C" { static int int_compare(const void* a, const void* b) { const int ai = *(const int*)a; const int bi = *(const int*)b; return ai < bi ? -1 : (ai > bi); } } static void qsort_sort(int array[], int count) { qsort(array, count, sizeof(int), int_compare); } enum SortType { kSKQSort, kSKHeap, kQSort }; static const struct { const char* fName; SortProc fProc; } gSorts[] = { { "skqsort", skqsort_sort }, { "skheap", skheap_sort }, { "qsort", qsort_sort }, }; class SortBench : public SkBenchmark { SkString fName; enum { MAX = 100000 }; int fUnsorted[MAX]; int fSorted[MAX]; int fCount; SortProc fSortProc; public: SortBench(void* param, Type t, int n, SortType s) : INHERITED(param) { if (n > MAX) { n = MAX; } fName.printf("sort_%s_%s", gSorts[s].fName, gRec[t].fName); fCount = n; gRec[t].fProc(fUnsorted, n); fSortProc = gSorts[s].fProc; fIsRendering = false; } protected: virtual const char* onGetName() SK_OVERRIDE { return fName.c_str(); } virtual void onDraw(SkCanvas* canvas) { int n = SkBENCHLOOP(200); for (int i = 0; i < n; i++) { memcpy(fSorted, fUnsorted, fCount * sizeof(int)); fSortProc(fSorted, fCount); #ifdef SK_DEBUG for (int j = 1; j < fCount; ++j) { SkASSERT(fSorted[j - 1] <= fSorted[j]); } #endif } } private: typedef SkBenchmark INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static SkBenchmark* NewSkQSort(void* param, Type t) { return new SortBench(param, t, N, kSKQSort); } static SkBenchmark* NewSkHeap(void* param, Type t) { return new SortBench(param, t, N, kSKHeap); } static SkBenchmark* NewQSort(void* param, Type t) { return new SortBench(param, t, N, kQSort); } DEF_BENCH( return NewSkQSort(p, kRand); ) DEF_BENCH( return NewSkHeap(p, kRand); ) DEF_BENCH( return NewQSort(p, kRand); ) DEF_BENCH( return NewSkQSort(p, kRandN); ) DEF_BENCH( return NewSkHeap(p, kRandN); ) DEF_BENCH( return NewQSort(p, kRandN); ) DEF_BENCH( return NewSkQSort(p, kFore); ) DEF_BENCH( return NewSkHeap(p, kFore); ) DEF_BENCH( return NewQSort(p, kFore); ) DEF_BENCH( return NewSkQSort(p, kBack); ) DEF_BENCH( return NewSkHeap(p, kBack); ) DEF_BENCH( return NewQSort(p, kBack); ) DEF_BENCH( return NewSkQSort(p, kSame); ) DEF_BENCH( return NewSkHeap(p, kSame); ) DEF_BENCH( return NewQSort(p, kSame); ) <commit_msg>reduce array size in debug builds for sortbench. This avoids a stack-overflow due to (1) SkTQSort's bad behavior on repeated-keys, and (2) windows-debug doesn't implement tail-recursion.<commit_after>/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBenchmark.h" #include "SkRandom.h" #include "SkTSort.h" #include "SkString.h" #ifdef SK_DEBUG // Windows-debug builds (at least) don't implement tail-recursion, and we have // a bench that triggers a worst-case behavior in SkTQSort (w/ repeated keys) // which can overflow the stack if N is too big. So we reduce it for debug // builds (for which we don't care about sorting performance anyways). static const int N = 100; #else static const int N = 1000; #endif static void rand_proc(int array[], int count) { SkRandom rand; for (int i = 0; i < count; ++i) { array[i] = rand.nextS(); } } static void randN_proc(int array[], int count) { SkRandom rand; int mod = N / 10; for (int i = 0; i < count; ++i) { array[i] = rand.nextU() % mod; } } static void forward_proc(int array[], int count) { for (int i = 0; i < count; ++i) { array[i] = i; } } static void backward_proc(int array[], int count) { for (int i = 0; i < count; ++i) { array[i] = -i; } } static void same_proc(int array[], int count) { for (int i = 0; i < count; ++i) { array[i] = count; } } typedef void (*SortProc)(int array[], int count); enum Type { kRand, kRandN, kFore, kBack, kSame }; static const struct { const char* fName; SortProc fProc; } gRec[] = { { "rand", rand_proc }, { "rand10", randN_proc }, { "forward", forward_proc }, { "backward", backward_proc }, { "repeated", same_proc }, }; static void skqsort_sort(int array[], int count) { SkTQSort<int>(array, array + count); } static void skheap_sort(int array[], int count) { SkTHeapSort<int>(array, count); } extern "C" { static int int_compare(const void* a, const void* b) { const int ai = *(const int*)a; const int bi = *(const int*)b; return ai < bi ? -1 : (ai > bi); } } static void qsort_sort(int array[], int count) { qsort(array, count, sizeof(int), int_compare); } enum SortType { kSKQSort, kSKHeap, kQSort }; static const struct { const char* fName; SortProc fProc; } gSorts[] = { { "skqsort", skqsort_sort }, { "skheap", skheap_sort }, { "qsort", qsort_sort }, }; class SortBench : public SkBenchmark { SkString fName; enum { MAX = 100000 }; int fUnsorted[MAX]; int fSorted[MAX]; int fCount; SortProc fSortProc; public: SortBench(void* param, Type t, int n, SortType s) : INHERITED(param) { if (n > MAX) { n = MAX; } fName.printf("sort_%s_%s", gSorts[s].fName, gRec[t].fName); fCount = n; gRec[t].fProc(fUnsorted, n); fSortProc = gSorts[s].fProc; fIsRendering = false; } protected: virtual const char* onGetName() SK_OVERRIDE { return fName.c_str(); } virtual void onDraw(SkCanvas* canvas) { int n = SkBENCHLOOP(200); for (int i = 0; i < n; i++) { memcpy(fSorted, fUnsorted, fCount * sizeof(int)); fSortProc(fSorted, fCount); #ifdef SK_DEBUG for (int j = 1; j < fCount; ++j) { SkASSERT(fSorted[j - 1] <= fSorted[j]); } #endif } } private: typedef SkBenchmark INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static SkBenchmark* NewSkQSort(void* param, Type t) { return new SortBench(param, t, N, kSKQSort); } static SkBenchmark* NewSkHeap(void* param, Type t) { return new SortBench(param, t, N, kSKHeap); } static SkBenchmark* NewQSort(void* param, Type t) { return new SortBench(param, t, N, kQSort); } DEF_BENCH( return NewSkQSort(p, kRand); ) DEF_BENCH( return NewSkHeap(p, kRand); ) DEF_BENCH( return NewQSort(p, kRand); ) DEF_BENCH( return NewSkQSort(p, kRandN); ) DEF_BENCH( return NewSkHeap(p, kRandN); ) DEF_BENCH( return NewQSort(p, kRandN); ) DEF_BENCH( return NewSkQSort(p, kFore); ) DEF_BENCH( return NewSkHeap(p, kFore); ) DEF_BENCH( return NewQSort(p, kFore); ) DEF_BENCH( return NewSkQSort(p, kBack); ) DEF_BENCH( return NewSkHeap(p, kBack); ) DEF_BENCH( return NewQSort(p, kBack); ) DEF_BENCH( return NewSkQSort(p, kSame); ) DEF_BENCH( return NewSkHeap(p, kSame); ) DEF_BENCH( return NewQSort(p, kSame); ) <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2012 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_TRIM_HPP #define MAPNIK_TRIM_HPP // boost //#include <boost/algorithm/string/trim.hpp> // stl #include <string> #include <iostream> namespace mapnik { namespace util { /* faster trim (than boost::trim) that intentionally does not respect std::locale to avoid overhead in cases where the locale is not critical */ static inline bool not_whitespace(int ch) { if (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t') return false; return true; } // trim from start static inline std::string & ltrim(std::string & s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), not_whitespace)); return s; } // trim from end static inline std::string & rtrim(std::string & s) { s.erase(std::find_if(s.rbegin(), s.rend(), not_whitespace).base(), s.end()); return s; } // trim from both ends static inline void trim(std::string & s) { ltrim(rtrim(s)); } static inline std::string trim_copy(std::string s) { return ltrim(rtrim(s)); } }} // end of namespace mapnik #endif // MAPNIK_TRIM_HPP <commit_msg>fix includes in new trim header to allow linux compile<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2012 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_TRIM_HPP #define MAPNIK_TRIM_HPP // stl #include <string> #include <algorithm> namespace mapnik { namespace util { /* https://github.com/mapnik/mapnik/issues/1633 faster trim (than boost::trim) that intentionally does not respect std::locale to avoid overhead in cases where the locale is not critical */ static inline bool not_whitespace(int ch) { if (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t') return false; return true; } // trim from start static inline std::string & ltrim(std::string & s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), not_whitespace)); return s; } // trim from end static inline std::string & rtrim(std::string & s) { s.erase(std::find_if(s.rbegin(), s.rend(), not_whitespace).base(), s.end()); return s; } // trim from both ends static inline void trim(std::string & s) { ltrim(rtrim(s)); } static inline std::string trim_copy(std::string s) { return ltrim(rtrim(s)); } }} // end of namespace mapnik #endif // MAPNIK_TRIM_HPP <|endoftext|>
<commit_before>#include "dsa_common.h" #include "responder.h" #include "module/security_manager.h" #include "core/session.h" #include "message/request/invoke_request_message.h" #include "message/request/list_request_message.h" #include "message/request/set_request_message.h" #include "message/request/subscribe_request_message.h" #include "stream/responder/outgoing_invoke_stream.h" #include "stream/responder/outgoing_list_stream.h" #include "stream/responder/outgoing_set_stream.h" #include "stream/responder/outgoing_subscribe_stream.h" #include "stream/simple_stream.h" namespace dsa { Responder::Responder(Session &session) : _session(session) {} void Responder::destroy_impl() { for (auto &it : _outgoing_streams) { it.second->destroy(); } _outgoing_streams.clear(); } void Responder::connection_changed() { for (auto it = _outgoing_streams.begin(); it != _outgoing_streams.end();) { if (it->second->connection_changed()) { it = _outgoing_streams.erase(it); } else { ++it; } } } inline ref_<OutgoingSubscribeStream> Responder::on_subscribe_request( ref_<SubscribeRequestMessage> &&message) { return make_ref_<OutgoingSubscribeStream>( _session.get_ref(), message->get_target_path(), message->get_rid(), message->get_subscribe_options()); } inline ref_<OutgoingListStream> Responder::on_list_request( ref_<ListRequestMessage> &&message) { return make_ref_<OutgoingListStream>( _session.get_ref(), message->get_target_path(), message->get_rid(), message->get_list_options()); } inline ref_<OutgoingInvokeStream> Responder::on_invoke_request( ref_<InvokeRequestMessage> &&message) { return make_ref_<OutgoingInvokeStream>( _session.get_ref(), message->get_target_path(), message->get_rid(), std::move(message)); } inline ref_<OutgoingSetStream> Responder::on_set_request( ref_<SetRequestMessage> &&message) { return make_ref_<OutgoingSetStream>(_session.get_ref(), message->get_target_path(), message->get_rid(), std::move(message)); } void Responder::receive_message(ref_<Message> &&message) { auto find_stream = _outgoing_streams.find(message->get_rid()); if (find_stream != _outgoing_streams.end()) { if (message->type() == MessageType::CLOSE_REQUEST) { find_stream->second->destroy(); _outgoing_streams.erase(find_stream); } else { find_stream->second->receive_message(std::move(message)); } return; } if (message->type() == MessageType::CLOSE_REQUEST) { // no need to close a stream that doesn't exist return; } auto request = DOWN_CAST<RequestMessage *>(message.get()); if (request->get_target_path().is_invalid()) { MessageType response_type = Message::get_response_type(request->type()); if (response_type != MessageType::INVALID) { _session.write_stream(make_ref_<SimpleStream>( request->get_rid(), response_type, MessageStatus::INVALID_MESSAGE)); } return; } std::function<void(PermissionLevel)> callback; switch (message->type()) { case MessageType::INVOKE_REQUEST: { auto stream = on_invoke_request(ref_<InvokeRequestMessage>(std::move(message))); callback = [stream, this](PermissionLevel permission_level) mutable { // it's possible stream is closed before permission check if (stream->is_destroyed()) return; stream->allowed_permission = permission_level; if (permission_level < PermissionLevel::READ) { auto response = make_ref_<InvokeResponseMessage>(); response->set_status(MessageStatus::PERMISSION_DENIED); stream->send_response(std::move(response)); return; } else { _session._strand->stream_acceptor().add(std::move(stream)); } }; _outgoing_streams[stream->rid] = std::move(stream); break; } case MessageType::SUBSCRIBE_REQUEST: { auto stream = on_subscribe_request( ref_<SubscribeRequestMessage>(std::move(message))); callback = [stream, this](PermissionLevel permission_level) mutable { // it's possible stream is closed before permission check if (stream->is_destroyed()) return; stream->allowed_permission = permission_level; if (permission_level < PermissionLevel::READ) { auto response = make_ref_<SubscribeResponseMessage>(); response->set_status(MessageStatus::PERMISSION_DENIED); stream->send_subscribe_response(std::move(response)); return; } else { _session._strand->stream_acceptor().add(std::move(stream)); } }; _outgoing_streams[stream->rid] = std::move(stream); break; } case MessageType::LIST_REQUEST: { auto stream = on_list_request(ref_<ListRequestMessage>(std::move(message))); callback = [stream, this](PermissionLevel permission_level) mutable { // it's possible stream is closed before permission check if (stream->is_destroyed()) return; stream->allowed_permission = permission_level; if (permission_level < PermissionLevel::LIST) { stream->update_response_status(MessageStatus::PERMISSION_DENIED); return; } else { _session._strand->stream_acceptor().add(std::move(stream)); } }; _outgoing_streams[stream->rid] = std::move(stream); break; } case MessageType::SET_REQUEST: { auto stream = on_set_request(ref_<SetRequestMessage>(std::move(message))); callback = [stream, this](PermissionLevel permission_level) mutable { // it's possible stream is closed before permission check if (stream->is_destroyed()) return; stream->allowed_permission = permission_level; if (permission_level < PermissionLevel::WRITE) { auto response = make_ref_<SetResponseMessage>(); response->set_status(MessageStatus::PERMISSION_DENIED); stream->send_response(std::move(response)); return; } else { _session._strand->stream_acceptor().add(std::move(stream)); } }; _outgoing_streams[stream->rid] = std::move(stream); break; } default: return; } _session._strand->security_manager().check_permission( _session.dsid(), request->get_permission_token(), request->type(), request->get_target_path(), std::move(callback)); } bool Responder::destroy_stream(int32_t rid) { auto search = _outgoing_streams.find(rid); if (search != _outgoing_streams.end()) { auto &stream = search->second; stream->destroy(); _outgoing_streams.erase(search); return true; } return false; } } // namespace dsa <commit_msg>fix the error that data used after std::move<commit_after>#include "dsa_common.h" #include "responder.h" #include "module/security_manager.h" #include "core/session.h" #include "message/request/invoke_request_message.h" #include "message/request/list_request_message.h" #include "message/request/set_request_message.h" #include "message/request/subscribe_request_message.h" #include "stream/responder/outgoing_invoke_stream.h" #include "stream/responder/outgoing_list_stream.h" #include "stream/responder/outgoing_set_stream.h" #include "stream/responder/outgoing_subscribe_stream.h" #include "stream/simple_stream.h" namespace dsa { Responder::Responder(Session &session) : _session(session) {} void Responder::destroy_impl() { for (auto &it : _outgoing_streams) { it.second->destroy(); } _outgoing_streams.clear(); } void Responder::connection_changed() { for (auto it = _outgoing_streams.begin(); it != _outgoing_streams.end();) { if (it->second->connection_changed()) { it = _outgoing_streams.erase(it); } else { ++it; } } } inline ref_<OutgoingSubscribeStream> Responder::on_subscribe_request( ref_<SubscribeRequestMessage> &&message) { return make_ref_<OutgoingSubscribeStream>( _session.get_ref(), message->get_target_path(), message->get_rid(), message->get_subscribe_options()); } inline ref_<OutgoingListStream> Responder::on_list_request( ref_<ListRequestMessage> &&message) { return make_ref_<OutgoingListStream>( _session.get_ref(), message->get_target_path(), message->get_rid(), message->get_list_options()); } inline ref_<OutgoingInvokeStream> Responder::on_invoke_request( ref_<InvokeRequestMessage> &&message) { return make_ref_<OutgoingInvokeStream>( _session.get_ref(), message->get_target_path(), message->get_rid(), std::move(message)); } inline ref_<OutgoingSetStream> Responder::on_set_request( ref_<SetRequestMessage> &&message) { return make_ref_<OutgoingSetStream>(_session.get_ref(), message->get_target_path(), message->get_rid(), std::move(message)); } void Responder::receive_message(ref_<Message> &&message) { auto find_stream = _outgoing_streams.find(message->get_rid()); if (find_stream != _outgoing_streams.end()) { if (message->type() == MessageType::CLOSE_REQUEST) { find_stream->second->destroy(); _outgoing_streams.erase(find_stream); } else { find_stream->second->receive_message(std::move(message)); } return; } if (message->type() == MessageType::CLOSE_REQUEST) { // no need to close a stream that doesn't exist return; } auto request = DOWN_CAST<RequestMessage *>(message.get()); if (request->get_target_path().is_invalid()) { MessageType response_type = Message::get_response_type(request->type()); if (response_type != MessageType::INVALID) { _session.write_stream(make_ref_<SimpleStream>( request->get_rid(), response_type, MessageStatus::INVALID_MESSAGE)); } return; } std::function<void(PermissionLevel)> callback; switch (message->type()) { case MessageType::INVOKE_REQUEST: { auto stream = on_invoke_request(ref_<InvokeRequestMessage>(message->get_ref())); callback = [stream, this](PermissionLevel permission_level) mutable { // it's possible stream is closed before permission check if (stream->is_destroyed()) return; stream->allowed_permission = permission_level; if (permission_level < PermissionLevel::READ) { auto response = make_ref_<InvokeResponseMessage>(); response->set_status(MessageStatus::PERMISSION_DENIED); stream->send_response(std::move(response)); return; } else { _session._strand->stream_acceptor().add(std::move(stream)); } }; _outgoing_streams[stream->rid] = std::move(stream); break; } case MessageType::SUBSCRIBE_REQUEST: { auto stream = on_subscribe_request( ref_<SubscribeRequestMessage>(message->get_ref())); callback = [stream, this](PermissionLevel permission_level) mutable { // it's possible stream is closed before permission check if (stream->is_destroyed()) return; stream->allowed_permission = permission_level; if (permission_level < PermissionLevel::READ) { auto response = make_ref_<SubscribeResponseMessage>(); response->set_status(MessageStatus::PERMISSION_DENIED); stream->send_subscribe_response(std::move(response)); return; } else { _session._strand->stream_acceptor().add(std::move(stream)); } }; _outgoing_streams[stream->rid] = std::move(stream); break; } case MessageType::LIST_REQUEST: { auto stream = on_list_request(ref_<ListRequestMessage>(message->get_ref())); callback = [stream, this](PermissionLevel permission_level) mutable { // it's possible stream is closed before permission check if (stream->is_destroyed()) return; stream->allowed_permission = permission_level; if (permission_level < PermissionLevel::LIST) { stream->update_response_status(MessageStatus::PERMISSION_DENIED); return; } else { _session._strand->stream_acceptor().add(std::move(stream)); } }; _outgoing_streams[stream->rid] = std::move(stream); break; } case MessageType::SET_REQUEST: { auto stream = on_set_request(ref_<SetRequestMessage>(message->get_ref())); callback = [stream, this](PermissionLevel permission_level) mutable { // it's possible stream is closed before permission check if (stream->is_destroyed()) return; stream->allowed_permission = permission_level; if (permission_level < PermissionLevel::WRITE) { auto response = make_ref_<SetResponseMessage>(); response->set_status(MessageStatus::PERMISSION_DENIED); stream->send_response(std::move(response)); return; } else { _session._strand->stream_acceptor().add(std::move(stream)); } }; _outgoing_streams[stream->rid] = std::move(stream); break; } default: return; } _session._strand->security_manager().check_permission( _session.dsid(), request->get_permission_token(), request->type(), request->get_target_path(), std::move(callback)); } bool Responder::destroy_stream(int32_t rid) { auto search = _outgoing_streams.find(rid); if (search != _outgoing_streams.end()) { auto &stream = search->second; stream->destroy(); _outgoing_streams.erase(search); return true; } return false; } } // namespace dsa <|endoftext|>
<commit_before>#include <assert.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include "test_lib.h" static char TMP_BUFFER[2048]; unsigned int assertions = 0; std::vector<_test_case *> __tests; std::vector<_test_case *> __failed_tests; _test_case *current_test_case(void) { return __tests.back(); } void free_test_case(_test_case *tc) { if (tc) { free(tc->name); if (tc->message) free(tc->message); if (tc->failed_pos) free(tc->failed_pos); free(tc); } } static char DESCRIP_BUFFER[2048]; const char * describe_stack(std::vector<const char *> &stack) { strcpy(DESCRIP_BUFFER, ""); for (int i=0, iLen=stack.size(); i<iLen; ++i) { if (i > 0) strcat(DESCRIP_BUFFER, " "); strcat(DESCRIP_BUFFER, stack.at(i)); } // .back()->description return DESCRIP_BUFFER; } _test_case * __run_test(const char *description, std::vector<const char *> &stack) { _test_case *tc = (_test_case *)malloc(sizeof(_test_case)); memset(tc, 0, sizeof(_test_case)); char buf[1024]; sprintf(buf, "\"%s %s\"", describe_stack(stack), description); tc->name = strdup(buf); __tests.push_back(tc); return tc; } void __end_test() { printf("%c", __tests.back()->failed ? 'F' : '.'); } int run_test_suite(test_suite *suite_methods, int suite_count) { for (unsigned int i=0; i<suite_count; ++i) suite_methods[i](); printf("\n"); for (std::vector<_test_case *>::iterator it=__failed_tests.begin(); it!=__failed_tests.end(); ++it) { printf("\n%s\n%s\n%s\n", (*it)->name, (*it)->message, (*it)->failed_pos); } printf("\n%u tests, %u assertions, %u failures\n", (unsigned int)__tests.size(), assertions, (unsigned int)__failed_tests.size()); while (!__tests.empty()) { free_test_case(__tests.back()); __tests.pop_back(); } return __failed_tests.size() > 0 ? -1 : 0; } static void fail_test(const char *file, int line, const char *message) { _test_case *tc = current_test_case(); char buf[1024]; const char *last_error = NULL; snprintf(buf, 1024, "%s:%d", file, line); tc->failed = 1; tc->message = strdup(message); tc->failed_pos = strdup(buf); __failed_tests.push_back(tc); longjmp(tc->jump, 0); } void __test_assert_true(const char *file, int line, bool value, const char *message) { ++assertions; if (!value) { if (!message) { message = &TMP_BUFFER[0]; sprintf(TMP_BUFFER, "expected: TRUE"); } fail_test(file, line, message); } } void __test_assert_equal(const char *file, int line, int expected, int value, const char *message) { ++assertions; if (expected != value) { if (!message) { message = &TMP_BUFFER[0]; sprintf(TMP_BUFFER, "expected: %i but was %i", expected, value); } fail_test(file, line, message); } } void __test_assert_equal(const char *file, int line, const char *expected, const char *value, const char *message) { ++assertions; if (strcmp(expected, value) != 0) { if (!message) { message = &TMP_BUFFER[0]; sprintf(TMP_BUFFER, "expected: '%s' but was '%s'", expected, value); } fail_test(file, line, message); } } /* void __run_test_suite() { printf("\n"); std::vector<const char *> context_stack; _test_case *current_test_case; // describe("backwards compat") context_stack.push_back("backwards compat"); // describe("join") context_stack.push_back("join"); // it("noops on nil") current_test_case = __run_test("noops on nil", context_stack); if (setjmp(current_test_case->jump) == 0) { current_test_case->failed = 1; longjmp(current_test_case->jump, 0); // Table relation = c_arel::Table("users"); // SelectManager sm = relation.skip(2); // assert_equal(sm.to_sql(), "SELECT FROM users OFFSET 2", "DESCRP"); } __end_test(); context_stack.pop_back(); // it("noops on nil") current_test_case = __run_test("noops on nil", context_stack); if (setjmp(current_test_case->jump) == 0) { longjmp(current_test_case->jump, 0); // Table relation = c_arel::Table("users"); // SelectManager sm = relation.skip(2); // assert_equal(sm.to_sql(), "SELECT FROM users OFFSET 2", "DESCRP"); } __end_test(); printf("\n%u tests, %u assertions, %u failures\n", (unsigned int)__tests.size(), 0, 0); while (!__tests.empty()) { free_test_case(__tests.back()); __tests.pop_back(); } } */ /* #define DO_ALLOC(TYPE) ((TYPE*) malloc(sizeof(TYPE))) #define GIT_MAX_TEST_CASES 64 struct test { char *name; char *message; char *failed_pos; char *description; char *error_message; unsigned char asserts; testfunc function; unsigned failed:1, ran:1; jmp_buf *jump; }; struct testsuite { char *name; int count, fail_count; int asserts; test *list[GIT_MAX_TEST_CASES]; }; static void test_free(test *t) { if (t) { free(t->name); free(t->description); free(t->failed_pos); free(t->message); free(t->error_message); free(t); } } static void test_run(test *tc) { jmp_buf buf; tc->jump = &buf; if (setjmp(buf) == 0) { tc->ran = 1; (tc->function)(tc); } tc->jump = 0; } static test *create_test(testfunc function) { test *t = DO_ALLOC(test); memset(t, 0x0, sizeof(test)); t->function = function; return t; } void test__init(test *t, const char *name, const char *description) { t->name = strdup(name); t->description = strdup(description); } static void fail_test(test *tc, const char *file, int line, const char *message) { char buf[1024]; const char *last_error = NULL; snprintf(buf, 1024, "%s:%d", file, line); tc->failed = 1; tc->message = strdup(message); tc->failed_pos = strdup(buf); if (last_error) tc->error_message = strdup(last_error); if (tc->jump != 0) longjmp(*(tc->jump), 0); } void __test_assert_true(test *tc, const char *file, int line, bool value, const char *message) { tc->asserts++; if (!value) { if (!message) { message = &TMP_BUFFER[0]; sprintf(TMP_BUFFER, "expected: TRUE\n"); } fail_test(tc, file, line, message); } } // void __test_assert_equal(test *tc, const char *file, int line, const char *expected, const char *value, const char *message) { void __test_assert_equal(_test_case *tc, const char *file, int line, const char *expected, const char *value, const char *message) { // tc->asserts++; if (strcmp(expected, value) != 0) { if (!message) { message = &TMP_BUFFER[0]; sprintf(TMP_BUFFER, "expected: '%s' but was '%s'", expected, value); } // fail_test(tc, file, line, message); } } void __test_assert_equal(test *tc, const char *file, int line, int expected, int value, const char *message) { tc->asserts++; if (expected != value) { if (!message) { message = &TMP_BUFFER[0]; sprintf(TMP_BUFFER, "expected: %i but was %i\n", expected, value); } fail_test(tc, file, line, message); } } static void testsuite_init(testsuite *ts) { ts->count = 0; ts->fail_count = 0; ts->asserts = 0; memset(ts->list, 0, sizeof(ts->list)); } testsuite *testsuite_new(const char *name) { testsuite *ts = DO_ALLOC(testsuite); testsuite_init(ts); ts->name = strdup(name); return ts; } static void free_suite(testsuite *ts) { unsigned int n; for (n = 0; n < GIT_MAX_TEST_CASES; n++) if (ts->list[n]) test_free(ts->list[n]); free(ts->name); free(ts); } void testsuite_add(testsuite *ts, testfunc test) { assert(ts->count < GIT_MAX_TEST_CASES); ts->list[ts->count++] = create_test(test); } static void print_details(testsuite *ts) { int i; int failCount = 0; if (ts->fail_count == 0) { const char *testWord = ts->count == 1 ? "test" : "tests"; printf("OK (%d %s - %d assertions)\n", ts->count, testWord, ts->asserts); } else { printf("Failed (%d failures):\n", ts->fail_count); for (i = 0 ; i < ts->count ; ++i) { test *tc = ts->list[i]; if (tc->failed) { failCount++; printf(" %d) \"%s\" [test %s @ %s]\n\t%s\n", failCount, tc->description, tc->name, tc->failed_pos, tc->message); if (tc->error_message) printf("\tError: %s\n", tc->error_message); } } } } int testsuite_run(testsuite *ts) { int i, fail_count; printf("Suite \"%s\": ", ts->name); for (i = 0 ; i < ts->count ; ++i) { test *tc = ts->list[i]; test_run(tc); ts->asserts += tc->asserts; if (tc->failed) { ts->fail_count++; putchar('F'); } else putchar('.'); fflush(stdout); } printf("\n "); print_details(ts); fail_count = ts->fail_count; free_suite(ts); return fail_count; } */ <commit_msg>test suite cleanup<commit_after>#include <assert.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include "test_lib.h" static char TMP_BUFFER[2048]; unsigned int assertions = 0; std::vector<_test_case *> __tests; std::vector<_test_case *> __failed_tests; _test_case *current_test_case(void) { return __tests.back(); } void free_test_case(_test_case *tc) { if (tc) { free(tc->name); if (tc->message) free(tc->message); if (tc->failed_pos) free(tc->failed_pos); free(tc); } } static char DESCRIP_BUFFER[2048]; const char * describe_stack(std::vector<const char *> &stack) { strcpy(DESCRIP_BUFFER, ""); for (int i=0, iLen=stack.size(); i<iLen; ++i) { if (i > 0) strcat(DESCRIP_BUFFER, " "); strcat(DESCRIP_BUFFER, stack.at(i)); } // .back()->description return DESCRIP_BUFFER; } _test_case * __run_test(const char *description, std::vector<const char *> &stack) { _test_case *tc = (_test_case *)malloc(sizeof(_test_case)); memset(tc, 0, sizeof(_test_case)); char buf[1024]; sprintf(buf, "\"%s %s\"", describe_stack(stack), description); tc->name = strdup(buf); __tests.push_back(tc); return tc; } void __end_test() { printf("%c", __tests.back()->failed ? 'F' : '.'); } int run_test_suite(test_suite *suite_methods, int suite_count) { for (unsigned int i=0; i<suite_count; ++i) suite_methods[i](); printf("\n"); for (std::vector<_test_case *>::iterator it=__failed_tests.begin(); it!=__failed_tests.end(); ++it) { printf("\n%s\n%s\n%s\n", (*it)->name, (*it)->message, (*it)->failed_pos); } printf("\n%u tests, %u assertions, %u failures\n", (unsigned int)__tests.size(), assertions, (unsigned int)__failed_tests.size()); while (!__tests.empty()) { free_test_case(__tests.back()); __tests.pop_back(); } return __failed_tests.size() > 0 ? -1 : 0; } static void fail_test(const char *file, int line, const char *message) { _test_case *tc = current_test_case(); char buf[1024]; const char *last_error = NULL; snprintf(buf, 1024, "%s:%d", file, line); tc->failed = 1; tc->message = strdup(message); tc->failed_pos = strdup(buf); __failed_tests.push_back(tc); longjmp(tc->jump, 0); } void __test_assert_true(const char *file, int line, bool value, const char *message) { ++assertions; if (!value) { if (!message) { message = &TMP_BUFFER[0]; sprintf(TMP_BUFFER, "expected: TRUE"); } fail_test(file, line, message); } } void __test_assert_equal(const char *file, int line, int expected, int value, const char *message) { ++assertions; if (expected != value) { if (!message) { message = &TMP_BUFFER[0]; sprintf(TMP_BUFFER, "expected: %i but was %i", expected, value); } fail_test(file, line, message); } } void __test_assert_equal(const char *file, int line, const char *expected, const char *value, const char *message) { ++assertions; if (strcmp(expected, value) != 0) { if (!message) { message = &TMP_BUFFER[0]; sprintf(TMP_BUFFER, "expected: '%s' but was '%s'", expected, value); } fail_test(file, line, message); } }<|endoftext|>
<commit_before>// Copyright (C) 2016 Jonathan Müller <[email protected]> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #ifndef TYPE_SAFE_CONFIG_HPP_INCLUDED #define TYPE_SAFE_CONFIG_HPP_INCLUDED #include <cstddef> #include <cstdlib> #ifndef TYPE_SAFE_ENABLE_ASSERTIONS #define TYPE_SAFE_ENABLE_ASSERTIONS 1 #endif #ifndef TYPE_SAFE_ENABLE_WRAPPER #define TYPE_SAFE_ENABLE_WRAPPER 1 #endif #ifndef TYPE_SAFE_ARITHMETIC_UB #define TYPE_SAFE_ARITHMETIC_UB 1 #endif #ifndef TYPE_SAFE_USE_REF_QUALIFIERS #if defined(__cpp_ref_qualifiers) && __cpp_ref_qualifiers >= 200710 #define TYPE_SAFE_USE_REF_QUALIFIERS 1 #elif defined(_MSC_VER) && _MSC_VER >= 1900 #define TYPE_SAFE_USE_REF_QUALIFIERS 1 #else #define TYPE_SAFE_USE_REF_QUALIFIERS 0 #endif #endif #if TYPE_SAFE_USE_REF_QUALIFIERS #define TYPE_SAFE_LVALUE_REF & #define TYPE_SAFE_RVALUE_REF && #else #define TYPE_SAFE_LVALUE_REF #define TYPE_SAFE_RVALUE_REF #endif #ifndef TYPE_SAFE_USE_EXCEPTIONS #if __cpp_exceptions #define TYPE_SAFE_USE_EXCEPTIONS 1 #elif defined(__GNUC__) && defined(__EXCEPTIONS) #define TYPE_SAFE_USE_EXCEPTIONS 1 #elif defined(_MSC_VER) && defined(__CPPUNWIND) #define TYPE_SAFE_USE_EXCEPTIONS 1 #else #define TYPE_SAFE_USE_EXCEPTIONS 0 #endif #endif #if TYPE_SAFE_USE_EXCEPTIONS #define TYPE_SAFE_THROW(Ex) throw Ex #else #define TYPE_SAFE_THROW(Ex) (Ex, std::abort()) #endif /// \entity type_safe /// \unique_name ts #endif // TYPE_SAFE_CONFIG_HPP_INCLUDED <commit_msg>Add try/catch/rethrow macros<commit_after>// Copyright (C) 2016 Jonathan Müller <[email protected]> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #ifndef TYPE_SAFE_CONFIG_HPP_INCLUDED #define TYPE_SAFE_CONFIG_HPP_INCLUDED #include <cstddef> #include <cstdlib> #ifndef TYPE_SAFE_ENABLE_ASSERTIONS #define TYPE_SAFE_ENABLE_ASSERTIONS 1 #endif #ifndef TYPE_SAFE_ENABLE_WRAPPER #define TYPE_SAFE_ENABLE_WRAPPER 1 #endif #ifndef TYPE_SAFE_ARITHMETIC_UB #define TYPE_SAFE_ARITHMETIC_UB 1 #endif #ifndef TYPE_SAFE_USE_REF_QUALIFIERS #if defined(__cpp_ref_qualifiers) && __cpp_ref_qualifiers >= 200710 #define TYPE_SAFE_USE_REF_QUALIFIERS 1 #elif defined(_MSC_VER) && _MSC_VER >= 1900 #define TYPE_SAFE_USE_REF_QUALIFIERS 1 #else #define TYPE_SAFE_USE_REF_QUALIFIERS 0 #endif #endif #if TYPE_SAFE_USE_REF_QUALIFIERS #define TYPE_SAFE_LVALUE_REF & #define TYPE_SAFE_RVALUE_REF && #else #define TYPE_SAFE_LVALUE_REF #define TYPE_SAFE_RVALUE_REF #endif #ifndef TYPE_SAFE_USE_EXCEPTIONS #if __cpp_exceptions #define TYPE_SAFE_USE_EXCEPTIONS 1 #elif defined(__GNUC__) && defined(__EXCEPTIONS) #define TYPE_SAFE_USE_EXCEPTIONS 1 #elif defined(_MSC_VER) && defined(__CPPUNWIND) #define TYPE_SAFE_USE_EXCEPTIONS 1 #else #define TYPE_SAFE_USE_EXCEPTIONS 0 #endif #endif #if TYPE_SAFE_USE_EXCEPTIONS #define TYPE_SAFE_THROW(Ex) throw Ex #define TYPE_SAFE_TRY try #define TYPE_SAFE_CATCH_ALL catch (...) #define TYPE_SAFE_RETHROW throw #else #define TYPE_SAFE_THROW(Ex) (Ex, std::abort()) #define TYPE_SAFE_TRY if (true) #define TYPE_SAFE_CATCH_ALL if (false) #define TYPE_SAFE_RETHROW std::abort() #endif /// \entity type_safe /// \unique_name ts #endif // TYPE_SAFE_CONFIG_HPP_INCLUDED <|endoftext|>
<commit_before>#include "basicopenglview.h" // this version demonstrates using the mouse to inout some points and draw lines between them BasicOpenGLView::BasicOpenGLView(QWidget *parent) : QGLWidget(parent), polygons(QVector< QVector<QVector3D> >()) { clearon = false; mousedown = false; lastpt = -1; csv = NULL; // represents an unselected vertex //polygons = QVector< QVector<QVector3D> >(); srand (time(NULL)); newPoly(); } void BasicOpenGLView::initializeGL() { glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // white glShadeModel( GL_FLAT ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glPointSize(5); } void BasicOpenGLView::resizeGL(int width, int height) { glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0,GLdouble(width),0,GLdouble(height),-10.0,10.0); //glOrtho(-(GLdouble)width/2.0, (GLdouble)width/2.0, -(GLdouble)height/2.0, (GLdouble)height/2.0, -10.0,10.0); glMatrixMode(GL_MODELVIEW); // qDebug()<< "resize\n"; } void BasicOpenGLView::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); drawFigure(); //QGLWidget::swapBuffers(); } void BasicOpenGLView::mousePressEvent(QMouseEvent *e) { if (mousedown) return; mousedown = true; csv = NULL; if (e->button() == Qt::RightButton) addPoint( e->x(), height()-e->y() ); if (e->button() == Qt::LeftButton) movePoint(e->x(), height()-e->y() ); update(); } void BasicOpenGLView::mouseMoveEvent(QMouseEvent *e) { if (mousedown) movePoint(e->x(), height()-e->y()); update(); } void BasicOpenGLView::mouseReleaseEvent(QMouseEvent *e) { // finished move point movePoint(e->x(), height()-e->y()); mousedown = false; update(); } void BasicOpenGLView::movePoint(int x, int y) { if (mousedown) { if (csv == NULL) // If no vertex selected select(x, y); // Look for vertex selected if (csv != NULL) { // If vertex selected csv->setX(x); csv->setY(y); } } } void BasicOpenGLView::addPoint(int x, int y) { int i; for (i = 0; i < polygons.size(); i++) { if ( polygons.at(i).size() > 0 && ( (polygons.at(i).at(0).x()-RADIUS) < x && (polygons.at(i).at(0).x()+RADIUS) > x ) && ( (polygons.at(i).at(0).y()-RADIUS) < y && (polygons.at(i).at(0).y()+RADIUS) > y ) ) { newPoly(); return; } } polygons.last().append(QVector3D(x, y, 1)); } void BasicOpenGLView::select(int x, int y) { int i, j; for (i = 0; i < polygons.size(); i++) { for (j = 0; j < polygons.at(i).size(); j++) { if ( ( (polygons.at(i).at(j).x()-RADIUS) < x && (polygons.at(i).at(j).x()+RADIUS) > x ) && ( (polygons.at(i).at(j).y()-RADIUS) < y && (polygons.at(i).at(j).y()+RADIUS) > y ) ) { csv = &(polygons[i][j]); } } } } void BasicOpenGLView::clearme() { //for (int i = 0; i < polygons.size(); i++) // polygons.at(i).clear(); // THIS IS NOT A DEEP CLEAR, FIX THIS polygons.clear(); polyColors.clear(); newPoly(); update(); } void BasicOpenGLView::drawCircle(double radius, double xcen, double ycen, bool line) { GLint i; static GLfloat circcoords[100][2]; // qDebug()<<"drawing circle "<< radius SEP xcen SEP ycen NL; for(i=0;i<100;i++) { circcoords[i][0]=radius*cos(i*2*M_PI/100.0)+xcen; circcoords[i][1]=radius*sin(i*2*M_PI/100.0)+ycen; } if (line) glBegin(GL_LINES); else glBegin(GL_POLYGON); for(i=0;i<100;i++) glVertex2fv(&circcoords[i][0]); glEnd(); } void BasicOpenGLView::drawLine(double x0, double y0, double x1, double y1 ) { glBegin(GL_LINES); glVertex2f(x0, y0); glVertex2f(x1, y1); glEnd(); } void BasicOpenGLView::drawFigure() { // draw a line between each pair of points int x0,x1,y0,y1,i,j, firstX, firstY; int numPolys = polygons.size(); for (i = 0; i < numPolys; i++) { if (polygons.at(i).size() <= 1) ; else { firstX = polygons.at(i).at(0).x(); firstY = polygons.at(i).at(0).y(); x0 = firstX; y0 = firstY; glColor3f(polyColors[i][0], polyColors[i][1], polyColors[i][2]); for (j = 1; j < polygons.at(i).size(); j++) { x1 = polygons.at(i).at(j).x(); y1 = polygons.at(i).at(j).y(); drawLine(x0, y0, x1, y1); x0 = x1; y0 = y1; } // If this is a closed polygon, draw the last line if (i != (numPolys - 1)) drawLine(x1, y1, firstX, firstY); } glColor3f(polyColors[i][0], polyColors[i][1], polyColors[i][2]); for (j = 0; j < polygons.at(i).size(); j++) drawCircle( (double)RADIUS, polygons.at(i).at(j).x(), polygons.at(i).at(j).y(), false); } } void BasicOpenGLView::newPoly() { polygons.append(QVector<QVector3D>()); polyColors.append(QVector<double>(3)); polyColors.last()[0] = ((double) rand() / (RAND_MAX)); polyColors.last()[1] = ((double) rand() / (RAND_MAX)); polyColors.last()[2] = ((double) rand() / (RAND_MAX)); update(); } <commit_msg>no message<commit_after>#include "basicopenglview.h" // this version demonstrates using the mouse to inout some points and draw lines between them BasicOpenGLView::BasicOpenGLView(QWidget *parent) : QGLWidget(parent), polygons(QVector< QVector<QVector3D> >()) { clearon = false; mousedown = false; lastpt = -1; csv = NULL; // represents an unselected vertex //polygons = QVector< QVector<QVector3D> >(); srand (time(NULL)); newPoly(); } void BasicOpenGLView::initializeGL() { glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // white glShadeModel( GL_FLAT ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glPointSize(5); } void BasicOpenGLView::resizeGL(int width, int height) { glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0,GLdouble(width),0,GLdouble(height),-10.0,10.0); //glOrtho(-(GLdouble)width/2.0, (GLdouble)width/2.0, -(GLdouble)height/2.0, (GLdouble)height/2.0, -10.0,10.0); glMatrixMode(GL_MODELVIEW); // qDebug()<< "resize\n"; } void BasicOpenGLView::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); drawFigure(); //QGLWidget::swapBuffers(); } void BasicOpenGLView::mousePressEvent(QMouseEvent *e) { if (mousedown) return; mousedown = true; csv = NULL; if (e->button() == Qt::RightButton) addPoint( e->x(), height()-e->y() ); if (e->button() == Qt::LeftButton) movePoint(e->x(), height()-e->y() ); update(); } void BasicOpenGLView::mouseMoveEvent(QMouseEvent *e) { if (mousedown) movePoint(e->x(), height()-e->y()); update(); } void BasicOpenGLView::mouseReleaseEvent(QMouseEvent *e) { // finished move point movePoint(e->x(), height()-e->y()); mousedown = false; update(); } void BasicOpenGLView::movePoint(int x, int y) { if (mousedown) { if (csv == NULL) // If no vertex selected select(x, y); // Look for vertex selected if (csv != NULL) { // If vertex selected csv->setX(x); csv->setY(y); } } } void BasicOpenGLView::addPoint(int x, int y) { int i; for (i = 0; i < polygons.size(); i++) { if ( polygons.at(i).size() > 0 && ( (polygons.at(i).at(0).x()-RADIUS) < x && (polygons.at(i).at(0).x()+RADIUS) > x ) && ( (polygons.at(i).at(0).y()-RADIUS) < y && (polygons.at(i).at(0).y()+RADIUS) > y ) ) { newPoly(); return; } } polygons.last().append(QVector3D(x, y, 1)); } void BasicOpenGLView::select(int x, int y) { int i, j; for (i = 0; i < polygons.size(); i++) { for (j = 0; j < polygons.at(i).size(); j++) { if ( ( (polygons.at(i).at(j).x()-RADIUS) < x && (polygons.at(i).at(j).x()+RADIUS) > x ) && ( (polygons.at(i).at(j).y()-RADIUS) < y && (polygons.at(i).at(j).y()+RADIUS) > y ) ) { csv = &(polygons[i][j]); } } } } void BasicOpenGLView::clearme() { //for (int i = 0; i < polygons.size(); i++) // polygons.at(i).clear(); // THIS IS NOT A DEEP CLEAR, FIX THIS polygons.clear(); polyColors.clear(); newPoly(); update(); } void BasicOpenGLView::drawCircle(double radius, double xcen, double ycen, bool line) { GLint i; static GLfloat circcoords[100][2]; // qDebug()<<"drawing circle "<< radius SEP xcen SEP ycen NL; for(i=0;i<100;i++) { circcoords[i][0]=radius*cos(i*2*M_PI/100.0)+xcen; circcoords[i][1]=radius*sin(i*2*M_PI/100.0)+ycen; } if (line) glBegin(GL_LINES); else glBegin(GL_POLYGON); for(i=0;i<100;i++) glVertex2fv(&circcoords[i][0]); glEnd(); } void BasicOpenGLView::drawLine(double x0, double y0, double x1, double y1 ) { glBegin(GL_LINES); glVertex2f(x0, y0); glVertex2f(x1, y1); glEnd(); } void BasicOpenGLView::drawFigure() { // draw a line between each pair of points int x0,x1,y0,y1,i,j, firstX, firstY; int numPolys = polygons.size(); for (i = 0; i < numPolys; i++) { if (polygons.at(i).size() <= 1) ; else { firstX = polygons.at(i).at(0).x(); firstY = polygons.at(i).at(0).y(); x0 = firstX; y0 = firstY; glColor3f(polyColors[i][0], polyColors[i][1], polyColors[i][2]); for (j = 1; j < polygons.at(i).size(); j++) { x1 = polygons.at(i).at(j).x(); y1 = polygons.at(i).at(j).y(); drawLine(x0, y0, x1, y1); x0 = x1; y0 = y1; } // If this is a closed polygon, draw the last line if (i != (numPolys - 1)) drawLine(x1, y1, firstX, firstY); } glColor3f(polyColors[i][0], polyColors[i][1], polyColors[i][2]); for (j = 0; j < polygons.at(i).size(); j++) drawCircle( (double)RADIUS, polygons.at(i).at(j).x(), polygons.at(i).at(j).y(), false); } } void BasicOpenGLView::newPoly() { polygons.append(QVector<QVector3D>()); polyColors.append(QVector<double>(3)); polyColors.last()[0] = ((double) rand() / (RAND_MAX)); polyColors.last()[1] = ((double) rand() / (RAND_MAX)); polyColors.last()[2] = ((double) rand() / (RAND_MAX)); update(); } <|endoftext|>
<commit_before>#include <iostream> #include <opencv2/opencv.hpp> #include <stdio.h> using namespace std; using namespace cv; int main() { Mat frame; VideoCapture cap("frame_%06d.jpg"); VideoWriter writer("created.avi", CV_FOURCC('M','J','P','G'), 30, Size(640, 360)); int i = 0; while(1) { cout << i << endl; i++; cap >> frame; if (frame.empty()) break; writer.write(frame); } return 0; } <commit_msg>Added code to create videos from images<commit_after>#include <iostream> #include <opencv2/opencv.hpp> #include <stdio.h> using namespace std; using namespace cv; int main() { Mat frame; VideoCapture cap("webframe%06d.jpg"); VideoWriter writer("webcam_created.avi", CV_FOURCC('M','J','P','G'), 30, Size(640, 480)); int i = 0; while(1) { cout << i << endl; i++; cap >> frame; if (frame.empty()) break; writer.write(frame); } return 0; } <|endoftext|>
<commit_before>#include "arch/address.hpp" #include "arch/arch.hpp" #include <netdb.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <limits.h> #include <unistd.h> #include "errors.hpp" #include <boost/bind.hpp> ip_address_t::ip_address_t(const char *host) { /* Use hint to make sure we get a IPv4 address that we can use with TCP */ struct addrinfo hint; hint.ai_flags = 0; hint.ai_family = AF_INET; hint.ai_socktype = SOCK_STREAM; hint.ai_protocol = 0; hint.ai_addrlen = 0; // These last four must be 0/NULL hint.ai_addr = NULL; hint.ai_canonname = NULL; hint.ai_next = NULL; struct addrinfo *addr_possibilities; // Because getaddrinfo may block, send it to a blocker thread and give up execution in the meantime boost::function<int()> fn = boost::bind(getaddrinfo, host, reinterpret_cast<const char*>(NULL), &hint, &addr_possibilities); int res = thread_pool_t::run_in_blocker_pool(fn); guarantee_err(res == 0, "getaddrinfo() failed"); struct sockaddr_in *addr_in = reinterpret_cast<struct sockaddr_in *>(addr_possibilities->ai_addr); addr = addr_in->sin_addr; freeaddrinfo(addr_possibilities); } ip_address_t::ip_address_t(uint32_t a) { addr.s_addr = a; } bool ip_address_t::operator==(const ip_address_t &x) { return !memcmp(&addr, &x.addr, sizeof(struct in_addr)); } bool ip_address_t::operator!=(const ip_address_t &x) { return memcmp(&addr, &x.addr, sizeof(struct in_addr)); } ip_address_t ip_address_t::us() { char name[HOST_NAME_MAX+1]; int res = gethostname(name, sizeof(name)); guarantee(res == 0, "gethostname() failed: %s\n", strerror(errno)); return ip_address_t(name); } uint32_t ip_address_t::ip_as_uint32() { return addr.s_addr; } <commit_msg>Changing reinterpret_cast to static_cast as per comment<commit_after>#include "arch/address.hpp" #include "arch/arch.hpp" #include <netdb.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <limits.h> #include <unistd.h> #include "errors.hpp" #include <boost/bind.hpp> ip_address_t::ip_address_t(const char *host) { /* Use hint to make sure we get a IPv4 address that we can use with TCP */ struct addrinfo hint; hint.ai_flags = 0; hint.ai_family = AF_INET; hint.ai_socktype = SOCK_STREAM; hint.ai_protocol = 0; hint.ai_addrlen = 0; // These last four must be 0/NULL hint.ai_addr = NULL; hint.ai_canonname = NULL; hint.ai_next = NULL; struct addrinfo *addr_possibilities; // Because getaddrinfo may block, send it to a blocker thread and give up execution in the meantime boost::function<int()> fn = boost::bind(getaddrinfo, host, static_cast<const char*>(NULL), &hint, &addr_possibilities); int res = thread_pool_t::run_in_blocker_pool(fn); guarantee_err(res == 0, "getaddrinfo() failed"); struct sockaddr_in *addr_in = reinterpret_cast<struct sockaddr_in *>(addr_possibilities->ai_addr); addr = addr_in->sin_addr; freeaddrinfo(addr_possibilities); } ip_address_t::ip_address_t(uint32_t a) { addr.s_addr = a; } bool ip_address_t::operator==(const ip_address_t &x) { return !memcmp(&addr, &x.addr, sizeof(struct in_addr)); } bool ip_address_t::operator!=(const ip_address_t &x) { return memcmp(&addr, &x.addr, sizeof(struct in_addr)); } ip_address_t ip_address_t::us() { char name[HOST_NAME_MAX+1]; int res = gethostname(name, sizeof(name)); guarantee(res == 0, "gethostname() failed: %s\n", strerror(errno)); return ip_address_t(name); } uint32_t ip_address_t::ip_as_uint32() { return addr.s_addr; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm 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. // //////////////////////////////////////////////////////////////////////////// #ifndef REALM_COORDINATOR_HPP #define REALM_COORDINATOR_HPP #include "shared_realm.hpp" #include <realm/version_id.hpp> #include <condition_variable> #include <mutex> namespace realm { class Replication; class Schema; class SharedGroup; class StringData; class SyncSession; namespace _impl { class CollectionNotifier; class ExternalCommitHelper; class WeakRealmNotifier; // RealmCoordinator manages the weak cache of Realm instances and communication // between per-thread Realm instances for a given file class RealmCoordinator : public std::enable_shared_from_this<RealmCoordinator> { public: // Get the coordinator for the given path, creating it if neccesary static std::shared_ptr<RealmCoordinator> get_coordinator(StringData path); // Get the coordinator for the given config, creating it if neccesary static std::shared_ptr<RealmCoordinator> get_coordinator(const Realm::Config&); // Get the coordinator for the given path, or null if there is none static std::shared_ptr<RealmCoordinator> get_existing_coordinator(StringData path); // Get a thread-local shared Realm with the given configuration // If the Realm is already open on another thread, validates that the given // configuration is compatible with the existing one std::shared_ptr<Realm> get_realm(Realm::Config config); std::shared_ptr<Realm> get_realm(); Realm::Config get_config() const { return m_config; } uint64_t get_schema_version() const noexcept { return m_schema_version; } const std::string& get_path() const noexcept { return m_config.path; } const std::vector<char>& get_encryption_key() const noexcept { return m_config.encryption_key; } bool is_in_memory() const noexcept { return m_config.in_memory; } // To avoid having to re-read and validate the file's schema every time a // new read transaction is begun, RealmCoordinator maintains a cache of the // most recently seen file schema and the range of transaction versions // which it applies to. Note that this schema may not be identical to that // of any Realm instances managed by this coordinator, as individual Realms // may only be using a subset of it. // Get the latest cached schema and the transaction version which is applies // to. Returns false if there is no cached schema. bool get_cached_schema(Schema& schema, uint64_t& schema_version, uint64_t& transaction) const noexcept; // Cache the state of the schema at the given transaction version void cache_schema(Schema const& new_schema, uint64_t new_schema_version, uint64_t transaction_version); // If there is a schema cached for transaction version `previous`, report // that it is still valid at transaction version `next` void advance_schema_cache(uint64_t previous, uint64_t next); void clear_schema_cache_and_set_schema_version(uint64_t new_schema_version); // Asynchronously call notify() on every Realm instance for this coordinator's // path, including those in other processes void send_commit_notifications(Realm&); void wake_up_notifier_worker(); // Clear the weak Realm cache for all paths // Should only be called in test code, as continuing to use the previously // cached instances will have odd results static void clear_cache(); // Clears all caches on existing coordinators static void clear_all_caches(); // Verify that there are no Realms open for any paths static void assert_no_open_realms() noexcept; // Explicit constructor/destructor needed for the unique_ptrs to forward-declared types RealmCoordinator(); ~RealmCoordinator(); // Called by Realm's destructor to ensure the cache is cleaned up promptly // Do not call directly void unregister_realm(Realm* realm); // Called by m_notifier when there's a new commit to send notifications for void on_change(); static void register_notifier(std::shared_ptr<CollectionNotifier> notifier); // Advance the Realm to the most recent transaction version which all async // work is complete for void advance_to_ready(Realm& realm); // Advance the Realm to the most recent transaction version, blocking if // async notifiers are not yet ready for that version // returns whether it actually changed the version bool advance_to_latest(Realm& realm); // Deliver any notifications which are ready for the Realm's version void process_available_async(Realm& realm); // Register a function which is called whenever sync makes a write to the Realm void set_transaction_callback(std::function<void(VersionID, VersionID)>); // Deliver notifications for the Realm, blocking if some aren't ready yet // The calling Realm must be in a write transaction void promote_to_write(Realm& realm); // Commit a Realm's current write transaction and send notifications to all // other Realm instances for that path, including in other processes void commit_write(Realm& realm); template<typename Pred> std::unique_lock<std::mutex> wait_for_notifiers(Pred&& wait_predicate); private: Realm::Config m_config; mutable std::mutex m_schema_cache_mutex; util::Optional<Schema> m_cached_schema; uint64_t m_schema_version = -1; uint64_t m_schema_transaction_version_min = 0; uint64_t m_schema_transaction_version_max = 0; std::mutex m_realm_mutex; std::vector<WeakRealmNotifier> m_weak_realm_notifiers; std::mutex m_notifier_mutex; std::condition_variable m_notifier_cv; std::vector<std::shared_ptr<_impl::CollectionNotifier>> m_new_notifiers; std::vector<std::shared_ptr<_impl::CollectionNotifier>> m_notifiers; VersionID m_notifier_skip_version = {0, 0}; // SharedGroup used for actually running async notifiers // Will have a read transaction iff m_notifiers is non-empty std::unique_ptr<Replication> m_notifier_history; std::unique_ptr<SharedGroup> m_notifier_sg; // SharedGroup used to advance notifiers in m_new_notifiers to the main shared // group's transaction version // Will have a read transaction iff m_new_notifiers is non-empty std::unique_ptr<Replication> m_advancer_history; std::unique_ptr<SharedGroup> m_advancer_sg; std::exception_ptr m_async_error; std::unique_ptr<_impl::ExternalCommitHelper> m_notifier; std::function<void(VersionID, VersionID)> m_transaction_callback; std::shared_ptr<SyncSession> m_sync_session; // must be called with m_notifier_mutex locked void pin_version(VersionID version); void set_config(const Realm::Config&); void create_sync_session(); void run_async_notifiers(); void open_helper_shared_group(); void advance_helper_shared_group_to_latest(); void clean_up_dead_notifiers(); std::vector<std::shared_ptr<_impl::CollectionNotifier>> notifiers_for_realm(Realm&); }; template<typename Pred> std::unique_lock<std::mutex> RealmCoordinator::wait_for_notifiers(Pred&& wait_predicate) { std::unique_lock<std::mutex> lock(m_notifier_mutex); bool first = true; m_notifier_cv.wait(lock, [&] { if (wait_predicate()) return true; if (first) { wake_up_notifier_worker(); first = false; } return false; }); return lock; } } // namespace _impl } // namespace realm #endif /* REALM_COORDINATOR_HPP */ <commit_msg>Fix a typo<commit_after>//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm 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. // //////////////////////////////////////////////////////////////////////////// #ifndef REALM_COORDINATOR_HPP #define REALM_COORDINATOR_HPP #include "shared_realm.hpp" #include <realm/version_id.hpp> #include <condition_variable> #include <mutex> namespace realm { class Replication; class Schema; class SharedGroup; class StringData; class SyncSession; namespace _impl { class CollectionNotifier; class ExternalCommitHelper; class WeakRealmNotifier; // RealmCoordinator manages the weak cache of Realm instances and communication // between per-thread Realm instances for a given file class RealmCoordinator : public std::enable_shared_from_this<RealmCoordinator> { public: // Get the coordinator for the given path, creating it if neccesary static std::shared_ptr<RealmCoordinator> get_coordinator(StringData path); // Get the coordinator for the given config, creating it if neccesary static std::shared_ptr<RealmCoordinator> get_coordinator(const Realm::Config&); // Get the coordinator for the given path, or null if there is none static std::shared_ptr<RealmCoordinator> get_existing_coordinator(StringData path); // Get a thread-local shared Realm with the given configuration // If the Realm is already open on another thread, validates that the given // configuration is compatible with the existing one std::shared_ptr<Realm> get_realm(Realm::Config config); std::shared_ptr<Realm> get_realm(); Realm::Config get_config() const { return m_config; } uint64_t get_schema_version() const noexcept { return m_schema_version; } const std::string& get_path() const noexcept { return m_config.path; } const std::vector<char>& get_encryption_key() const noexcept { return m_config.encryption_key; } bool is_in_memory() const noexcept { return m_config.in_memory; } // To avoid having to re-read and validate the file's schema every time a // new read transaction is begun, RealmCoordinator maintains a cache of the // most recently seen file schema and the range of transaction versions // which it applies to. Note that this schema may not be identical to that // of any Realm instances managed by this coordinator, as individual Realms // may only be using a subset of it. // Get the latest cached schema and the transaction version which it applies // to. Returns false if there is no cached schema. bool get_cached_schema(Schema& schema, uint64_t& schema_version, uint64_t& transaction) const noexcept; // Cache the state of the schema at the given transaction version void cache_schema(Schema const& new_schema, uint64_t new_schema_version, uint64_t transaction_version); // If there is a schema cached for transaction version `previous`, report // that it is still valid at transaction version `next` void advance_schema_cache(uint64_t previous, uint64_t next); void clear_schema_cache_and_set_schema_version(uint64_t new_schema_version); // Asynchronously call notify() on every Realm instance for this coordinator's // path, including those in other processes void send_commit_notifications(Realm&); void wake_up_notifier_worker(); // Clear the weak Realm cache for all paths // Should only be called in test code, as continuing to use the previously // cached instances will have odd results static void clear_cache(); // Clears all caches on existing coordinators static void clear_all_caches(); // Verify that there are no Realms open for any paths static void assert_no_open_realms() noexcept; // Explicit constructor/destructor needed for the unique_ptrs to forward-declared types RealmCoordinator(); ~RealmCoordinator(); // Called by Realm's destructor to ensure the cache is cleaned up promptly // Do not call directly void unregister_realm(Realm* realm); // Called by m_notifier when there's a new commit to send notifications for void on_change(); static void register_notifier(std::shared_ptr<CollectionNotifier> notifier); // Advance the Realm to the most recent transaction version which all async // work is complete for void advance_to_ready(Realm& realm); // Advance the Realm to the most recent transaction version, blocking if // async notifiers are not yet ready for that version // returns whether it actually changed the version bool advance_to_latest(Realm& realm); // Deliver any notifications which are ready for the Realm's version void process_available_async(Realm& realm); // Register a function which is called whenever sync makes a write to the Realm void set_transaction_callback(std::function<void(VersionID, VersionID)>); // Deliver notifications for the Realm, blocking if some aren't ready yet // The calling Realm must be in a write transaction void promote_to_write(Realm& realm); // Commit a Realm's current write transaction and send notifications to all // other Realm instances for that path, including in other processes void commit_write(Realm& realm); template<typename Pred> std::unique_lock<std::mutex> wait_for_notifiers(Pred&& wait_predicate); private: Realm::Config m_config; mutable std::mutex m_schema_cache_mutex; util::Optional<Schema> m_cached_schema; uint64_t m_schema_version = -1; uint64_t m_schema_transaction_version_min = 0; uint64_t m_schema_transaction_version_max = 0; std::mutex m_realm_mutex; std::vector<WeakRealmNotifier> m_weak_realm_notifiers; std::mutex m_notifier_mutex; std::condition_variable m_notifier_cv; std::vector<std::shared_ptr<_impl::CollectionNotifier>> m_new_notifiers; std::vector<std::shared_ptr<_impl::CollectionNotifier>> m_notifiers; VersionID m_notifier_skip_version = {0, 0}; // SharedGroup used for actually running async notifiers // Will have a read transaction iff m_notifiers is non-empty std::unique_ptr<Replication> m_notifier_history; std::unique_ptr<SharedGroup> m_notifier_sg; // SharedGroup used to advance notifiers in m_new_notifiers to the main shared // group's transaction version // Will have a read transaction iff m_new_notifiers is non-empty std::unique_ptr<Replication> m_advancer_history; std::unique_ptr<SharedGroup> m_advancer_sg; std::exception_ptr m_async_error; std::unique_ptr<_impl::ExternalCommitHelper> m_notifier; std::function<void(VersionID, VersionID)> m_transaction_callback; std::shared_ptr<SyncSession> m_sync_session; // must be called with m_notifier_mutex locked void pin_version(VersionID version); void set_config(const Realm::Config&); void create_sync_session(); void run_async_notifiers(); void open_helper_shared_group(); void advance_helper_shared_group_to_latest(); void clean_up_dead_notifiers(); std::vector<std::shared_ptr<_impl::CollectionNotifier>> notifiers_for_realm(Realm&); }; template<typename Pred> std::unique_lock<std::mutex> RealmCoordinator::wait_for_notifiers(Pred&& wait_predicate) { std::unique_lock<std::mutex> lock(m_notifier_mutex); bool first = true; m_notifier_cv.wait(lock, [&] { if (wait_predicate()) return true; if (first) { wake_up_notifier_worker(); first = false; } return false; }); return lock; } } // namespace _impl } // namespace realm #endif /* REALM_COORDINATOR_HPP */ <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/socket/unix_domain_socket_posix.h" #include <cstring> #include <string> #include <errno.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/un.h> #include <unistd.h> #include "base/bind.h" #include "base/callback.h" #include "base/posix/eintr_wrapper.h" #include "base/threading/platform_thread.h" #include "build/build_config.h" #include "net/base/net_errors.h" #include "net/base/net_util.h" namespace net { namespace { bool NoAuthenticationCallback(uid_t, gid_t) { return true; } bool GetPeerIds(int socket, uid_t* user_id, gid_t* group_id) { #if defined(OS_LINUX) || defined(OS_ANDROID) struct ucred user_cred; socklen_t len = sizeof(user_cred); if (getsockopt(socket, SOL_SOCKET, SO_PEERCRED, &user_cred, &len) == -1) return false; *user_id = user_cred.uid; *group_id = user_cred.gid; #else if (getpeereid(socket, user_id, group_id) == -1) return false; #endif return true; } } // namespace // static UnixDomainSocket::AuthCallback NoAuthentication() { return base::Bind(NoAuthenticationCallback); } // static UnixDomainSocket* UnixDomainSocket::CreateAndListenInternal( const std::string& path, const std::string& fallback_path, StreamListenSocket::Delegate* del, const AuthCallback& auth_callback, bool use_abstract_namespace) { SocketDescriptor s = CreateAndBind(path, use_abstract_namespace); if (s == kInvalidSocket && !fallback_path.empty()) s = CreateAndBind(fallback_path, use_abstract_namespace); if (s == kInvalidSocket) return NULL; UnixDomainSocket* sock = new UnixDomainSocket(s, del, auth_callback); sock->Listen(); return sock; } // static scoped_refptr<UnixDomainSocket> UnixDomainSocket::CreateAndListen( const std::string& path, StreamListenSocket::Delegate* del, const AuthCallback& auth_callback) { return CreateAndListenInternal(path, "", del, auth_callback, false); } #if defined(SOCKET_ABSTRACT_NAMESPACE_SUPPORTED) // static scoped_refptr<UnixDomainSocket> UnixDomainSocket::CreateAndListenWithAbstractNamespace( const std::string& path, const std::string& fallback_path, StreamListenSocket::Delegate* del, const AuthCallback& auth_callback) { return make_scoped_refptr( CreateAndListenInternal(path, fallback_path, del, auth_callback, true)); } #endif UnixDomainSocket::UnixDomainSocket( SocketDescriptor s, StreamListenSocket::Delegate* del, const AuthCallback& auth_callback) : StreamListenSocket(s, del), auth_callback_(auth_callback) {} UnixDomainSocket::~UnixDomainSocket() {} // static SocketDescriptor UnixDomainSocket::CreateAndBind(const std::string& path, bool use_abstract_namespace) { sockaddr_un addr; static const size_t kPathMax = sizeof(addr.sun_path); if (use_abstract_namespace + path.size() + 1 /* '\0' */ > kPathMax) return kInvalidSocket; const SocketDescriptor s = socket(PF_UNIX, SOCK_STREAM, 0); if (s == kInvalidSocket) return kInvalidSocket; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; socklen_t addr_len; if (use_abstract_namespace) { // Convert the path given into abstract socket name. It must start with // the '\0' character, so we are adding it. |addr_len| must specify the // length of the structure exactly, as potentially the socket name may // have '\0' characters embedded (although we don't support this). // Note that addr.sun_path is already zero initialized. memcpy(addr.sun_path + 1, path.c_str(), path.size()); addr_len = path.size() + offsetof(struct sockaddr_un, sun_path) + 1; } else { memcpy(addr.sun_path, path.c_str(), path.size()); addr_len = sizeof(sockaddr_un); } if (bind(s, reinterpret_cast<sockaddr*>(&addr), addr_len)) { LOG(ERROR) << "Could not bind unix domain socket to " << path; if (use_abstract_namespace) LOG(ERROR) << " (with abstract namespace enabled)"; if (HANDLE_EINTR(close(s)) < 0) LOG(ERROR) << "close() error"; return kInvalidSocket; } return s; } void UnixDomainSocket::Accept() { SocketDescriptor conn = StreamListenSocket::AcceptSocket(); if (conn == kInvalidSocket) return; uid_t user_id; gid_t group_id; if (!GetPeerIds(conn, &user_id, &group_id) || !auth_callback_.Run(user_id, group_id)) { if (HANDLE_EINTR(close(conn)) < 0) LOG(ERROR) << "close() error"; return; } scoped_refptr<UnixDomainSocket> sock( new UnixDomainSocket(conn, socket_delegate_, auth_callback_)); // It's up to the delegate to AddRef if it wants to keep it around. sock->WatchSocket(WAITING_READ); socket_delegate_->DidAccept(this, sock.get()); } UnixDomainSocketFactory::UnixDomainSocketFactory( const std::string& path, const UnixDomainSocket::AuthCallback& auth_callback) : path_(path), auth_callback_(auth_callback) {} UnixDomainSocketFactory::~UnixDomainSocketFactory() {} scoped_refptr<StreamListenSocket> UnixDomainSocketFactory::CreateAndListen( StreamListenSocket::Delegate* delegate) const { return UnixDomainSocket::CreateAndListen( path_, delegate, auth_callback_); } #if defined(SOCKET_ABSTRACT_NAMESPACE_SUPPORTED) UnixDomainSocketWithAbstractNamespaceFactory:: UnixDomainSocketWithAbstractNamespaceFactory( const std::string& path, const std::string& fallback_path, const UnixDomainSocket::AuthCallback& auth_callback) : UnixDomainSocketFactory(path, auth_callback), fallback_path_(fallback_path) {} UnixDomainSocketWithAbstractNamespaceFactory:: ~UnixDomainSocketWithAbstractNamespaceFactory() {} scoped_refptr<StreamListenSocket> UnixDomainSocketWithAbstractNamespaceFactory::CreateAndListen( StreamListenSocket::Delegate* delegate) const { return UnixDomainSocket::CreateAndListenWithAbstractNamespace( path_, fallback_path_, delegate, auth_callback_); } #endif } // namespace net <commit_msg>Fix a typo causing UnixDomainSocket::NoAuthentication to be undefined.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/socket/unix_domain_socket_posix.h" #include <cstring> #include <string> #include <errno.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/un.h> #include <unistd.h> #include "base/bind.h" #include "base/callback.h" #include "base/posix/eintr_wrapper.h" #include "base/threading/platform_thread.h" #include "build/build_config.h" #include "net/base/net_errors.h" #include "net/base/net_util.h" namespace net { namespace { bool NoAuthenticationCallback(uid_t, gid_t) { return true; } bool GetPeerIds(int socket, uid_t* user_id, gid_t* group_id) { #if defined(OS_LINUX) || defined(OS_ANDROID) struct ucred user_cred; socklen_t len = sizeof(user_cred); if (getsockopt(socket, SOL_SOCKET, SO_PEERCRED, &user_cred, &len) == -1) return false; *user_id = user_cred.uid; *group_id = user_cred.gid; #else if (getpeereid(socket, user_id, group_id) == -1) return false; #endif return true; } } // namespace // static UnixDomainSocket::AuthCallback UnixDomainSocket::NoAuthentication() { return base::Bind(NoAuthenticationCallback); } // static UnixDomainSocket* UnixDomainSocket::CreateAndListenInternal( const std::string& path, const std::string& fallback_path, StreamListenSocket::Delegate* del, const AuthCallback& auth_callback, bool use_abstract_namespace) { SocketDescriptor s = CreateAndBind(path, use_abstract_namespace); if (s == kInvalidSocket && !fallback_path.empty()) s = CreateAndBind(fallback_path, use_abstract_namespace); if (s == kInvalidSocket) return NULL; UnixDomainSocket* sock = new UnixDomainSocket(s, del, auth_callback); sock->Listen(); return sock; } // static scoped_refptr<UnixDomainSocket> UnixDomainSocket::CreateAndListen( const std::string& path, StreamListenSocket::Delegate* del, const AuthCallback& auth_callback) { return CreateAndListenInternal(path, "", del, auth_callback, false); } #if defined(SOCKET_ABSTRACT_NAMESPACE_SUPPORTED) // static scoped_refptr<UnixDomainSocket> UnixDomainSocket::CreateAndListenWithAbstractNamespace( const std::string& path, const std::string& fallback_path, StreamListenSocket::Delegate* del, const AuthCallback& auth_callback) { return make_scoped_refptr( CreateAndListenInternal(path, fallback_path, del, auth_callback, true)); } #endif UnixDomainSocket::UnixDomainSocket( SocketDescriptor s, StreamListenSocket::Delegate* del, const AuthCallback& auth_callback) : StreamListenSocket(s, del), auth_callback_(auth_callback) {} UnixDomainSocket::~UnixDomainSocket() {} // static SocketDescriptor UnixDomainSocket::CreateAndBind(const std::string& path, bool use_abstract_namespace) { sockaddr_un addr; static const size_t kPathMax = sizeof(addr.sun_path); if (use_abstract_namespace + path.size() + 1 /* '\0' */ > kPathMax) return kInvalidSocket; const SocketDescriptor s = socket(PF_UNIX, SOCK_STREAM, 0); if (s == kInvalidSocket) return kInvalidSocket; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; socklen_t addr_len; if (use_abstract_namespace) { // Convert the path given into abstract socket name. It must start with // the '\0' character, so we are adding it. |addr_len| must specify the // length of the structure exactly, as potentially the socket name may // have '\0' characters embedded (although we don't support this). // Note that addr.sun_path is already zero initialized. memcpy(addr.sun_path + 1, path.c_str(), path.size()); addr_len = path.size() + offsetof(struct sockaddr_un, sun_path) + 1; } else { memcpy(addr.sun_path, path.c_str(), path.size()); addr_len = sizeof(sockaddr_un); } if (bind(s, reinterpret_cast<sockaddr*>(&addr), addr_len)) { LOG(ERROR) << "Could not bind unix domain socket to " << path; if (use_abstract_namespace) LOG(ERROR) << " (with abstract namespace enabled)"; if (HANDLE_EINTR(close(s)) < 0) LOG(ERROR) << "close() error"; return kInvalidSocket; } return s; } void UnixDomainSocket::Accept() { SocketDescriptor conn = StreamListenSocket::AcceptSocket(); if (conn == kInvalidSocket) return; uid_t user_id; gid_t group_id; if (!GetPeerIds(conn, &user_id, &group_id) || !auth_callback_.Run(user_id, group_id)) { if (HANDLE_EINTR(close(conn)) < 0) LOG(ERROR) << "close() error"; return; } scoped_refptr<UnixDomainSocket> sock( new UnixDomainSocket(conn, socket_delegate_, auth_callback_)); // It's up to the delegate to AddRef if it wants to keep it around. sock->WatchSocket(WAITING_READ); socket_delegate_->DidAccept(this, sock.get()); } UnixDomainSocketFactory::UnixDomainSocketFactory( const std::string& path, const UnixDomainSocket::AuthCallback& auth_callback) : path_(path), auth_callback_(auth_callback) {} UnixDomainSocketFactory::~UnixDomainSocketFactory() {} scoped_refptr<StreamListenSocket> UnixDomainSocketFactory::CreateAndListen( StreamListenSocket::Delegate* delegate) const { return UnixDomainSocket::CreateAndListen( path_, delegate, auth_callback_); } #if defined(SOCKET_ABSTRACT_NAMESPACE_SUPPORTED) UnixDomainSocketWithAbstractNamespaceFactory:: UnixDomainSocketWithAbstractNamespaceFactory( const std::string& path, const std::string& fallback_path, const UnixDomainSocket::AuthCallback& auth_callback) : UnixDomainSocketFactory(path, auth_callback), fallback_path_(fallback_path) {} UnixDomainSocketWithAbstractNamespaceFactory:: ~UnixDomainSocketWithAbstractNamespaceFactory() {} scoped_refptr<StreamListenSocket> UnixDomainSocketWithAbstractNamespaceFactory::CreateAndListen( StreamListenSocket::Delegate* delegate) const { return UnixDomainSocket::CreateAndListenWithAbstractNamespace( path_, fallback_path_, delegate, auth_callback_); } #endif } // namespace net <|endoftext|>
<commit_before>/* * 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/. * * This file is part of zmqpp. * Copyright (c) 2011-2015 Contributors as noted in the AUTHORS file. */ #pragma once #include <tuple> #include <vector> #include <list> #include <chrono> #include <functional> #include <memory> #include "compatibility.hpp" #include "poller.hpp" namespace zmqpp { class socket; typedef socket socket_t; /** * Loop object that helps to manage multiple socket by calling a user-defined handler for each socket * when a watched event occurs. * Calls assigned user-defined handler for timed events - repeaded and one-shot. * * It uses zmq::poller as the underlying polling mechanism. */ class loop { public: /** * Type used to identify created timers withing loop */ typedef void * timer_id_t; typedef std::function<bool (void) > Callable; /** * Construct an empty polling model. */ ZMQPP_EXPORT loop(); /** * Cleanup reactor. * * Any sockets will need to be closed separately. */ ZMQPP_EXPORT virtual ~loop(); /** * Add a socket to the loop, providing a handler that will be called when the monitored events occur. * * \param socket the socket to monitor. * \param callable the function that will be called by the loop when a registered event occurs on socket. * \param event the event flags to monitor on the socket. */ ZMQPP_EXPORT void add(socket_t& socket, Callable callable, short const event = poller::poll_in); /*! * Add a standard socket to the loop, providing a handler that will be called when the monitored events occur. * * \param descriptor the standard socket to monitor (SOCKET under Windows, a file descriptor otherwise). * \param callable the function that will be called by the loop when a registered event occurs on fd. * \param event the event flags to monitor. */ ZMQPP_EXPORT void add(raw_socket_t const descriptor, Callable callable, short const event = poller::poll_in | poller::poll_error); /** * Add a timed event to the loop, providing a handler that will be called when timer fires. * * \param delay time after which handler will be executed. * \param times how many times should timer be reneved - 0 for infinte ammount. * \param callable the function that will be called by the loop after delay. */ ZMQPP_EXPORT timer_id_t add(std::chrono::milliseconds delay, size_t times, Callable callable); /** * Reset timer in the loop, it will start counting delay time again. Times argument is preserved. * * \param timer identifier in the loop. */ ZMQPP_EXPORT void reset(timer_id_t const timer); /** * Remove timer event from the loop. * * \param timer identifier in the loop. */ ZMQPP_EXPORT void remove(timer_id_t const timer); /** * Stop monitoring a socket. * * \param socket the socket to stop monitoring. */ ZMQPP_EXPORT void remove(socket_t const& socket); /** * Stop monitoring a standard socket. * * \param descriptor the standard socket to stop monitoring. */ ZMQPP_EXPORT void remove(raw_socket_t const descriptor); /** * Starts loop. It will block until one of handlers returns false. */ ZMQPP_EXPORT void start(); private: struct timer_t { size_t times; std::chrono::milliseconds delay; std::chrono::steady_clock::time_point when; timer_t(size_t times, std::chrono::milliseconds delay); void reset(); void update(); }; typedef std::pair<zmq_pollitem_t, Callable> PollItemCallablePair; typedef std::pair<std::unique_ptr<timer_t>, Callable> TimerItemCallablePair; static bool TimerItemCallablePairComp(const TimerItemCallablePair &lhs, const TimerItemCallablePair &rhs); std::vector<PollItemCallablePair> items_; std::list<TimerItemCallablePair> timers_; std::vector<const socket_t *> sockRemoveLater_; std::vector<raw_socket_t> fdRemoveLater_; std::vector<timer_id_t> timerRemoveLater_; void add(const zmq_pollitem_t &item, Callable callable); void add(std::unique_ptr<timer_t>, Callable callable); bool start_handle_timers(); bool start_handle_poller(); /** * Flush the fdRemoveLater_ and sockRemoveLater_ vector, effectively removing * the item for the reactor and poller. */ void flush_remove_later(); /** * Calculate min time to wait in poller. */ long tickless(); poller poller_; bool dispatching_; bool rebuild_poller_; }; } <commit_msg>matching whitespace to surrounding file<commit_after>/* * 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/. * * This file is part of zmqpp. * Copyright (c) 2011-2015 Contributors as noted in the AUTHORS file. */ #pragma once #include <tuple> #include <vector> #include <list> #include <chrono> #include <functional> #include <memory> #include "compatibility.hpp" #include "poller.hpp" namespace zmqpp { class socket; typedef socket socket_t; /** * Loop object that helps to manage multiple socket by calling a user-defined handler for each socket * when a watched event occurs. * Calls assigned user-defined handler for timed events - repeaded and one-shot. * * It uses zmq::poller as the underlying polling mechanism. */ class loop { public: /** * Type used to identify created timers withing loop */ typedef void * timer_id_t; typedef std::function<bool (void) > Callable; /** * Construct an empty polling model. */ ZMQPP_EXPORT loop(); /** * Cleanup reactor. * * Any sockets will need to be closed separately. */ ZMQPP_EXPORT virtual ~loop(); /** * Add a socket to the loop, providing a handler that will be called when the monitored events occur. * * \param socket the socket to monitor. * \param callable the function that will be called by the loop when a registered event occurs on socket. * \param event the event flags to monitor on the socket. */ ZMQPP_EXPORT void add(socket_t& socket, Callable callable, short const event = poller::poll_in); /*! * Add a standard socket to the loop, providing a handler that will be called when the monitored events occur. * * \param descriptor the standard socket to monitor (SOCKET under Windows, a file descriptor otherwise). * \param callable the function that will be called by the loop when a registered event occurs on fd. * \param event the event flags to monitor. */ ZMQPP_EXPORT void add(raw_socket_t const descriptor, Callable callable, short const event = poller::poll_in | poller::poll_error); /** * Add a timed event to the loop, providing a handler that will be called when timer fires. * * \param delay time after which handler will be executed. * \param times how many times should timer be reneved - 0 for infinte ammount. * \param callable the function that will be called by the loop after delay. */ ZMQPP_EXPORT timer_id_t add(std::chrono::milliseconds delay, size_t times, Callable callable); /** * Reset timer in the loop, it will start counting delay time again. Times argument is preserved. * * \param timer identifier in the loop. */ ZMQPP_EXPORT void reset(timer_id_t const timer); /** * Remove timer event from the loop. * * \param timer identifier in the loop. */ ZMQPP_EXPORT void remove(timer_id_t const timer); /** * Stop monitoring a socket. * * \param socket the socket to stop monitoring. */ ZMQPP_EXPORT void remove(socket_t const& socket); /** * Stop monitoring a standard socket. * * \param descriptor the standard socket to stop monitoring. */ ZMQPP_EXPORT void remove(raw_socket_t const descriptor); /** * Starts loop. It will block until one of handlers returns false. */ ZMQPP_EXPORT void start(); private: struct timer_t { size_t times; std::chrono::milliseconds delay; std::chrono::steady_clock::time_point when; timer_t(size_t times, std::chrono::milliseconds delay); void reset(); void update(); }; typedef std::pair<zmq_pollitem_t, Callable> PollItemCallablePair; typedef std::pair<std::unique_ptr<timer_t>, Callable> TimerItemCallablePair; static bool TimerItemCallablePairComp(const TimerItemCallablePair &lhs, const TimerItemCallablePair &rhs); std::vector<PollItemCallablePair> items_; std::list<TimerItemCallablePair> timers_; std::vector<const socket_t *> sockRemoveLater_; std::vector<raw_socket_t> fdRemoveLater_; std::vector<timer_id_t> timerRemoveLater_; void add(const zmq_pollitem_t &item, Callable callable); void add(std::unique_ptr<timer_t>, Callable callable); bool start_handle_timers(); bool start_handle_poller(); /** * Flush the fdRemoveLater_ and sockRemoveLater_ vector, effectively removing * the item for the reactor and poller. */ void flush_remove_later(); /** * Calculate min time to wait in poller. */ long tickless(); poller poller_; bool dispatching_; bool rebuild_poller_; }; } <|endoftext|>
<commit_before>/* * security-manager, database access * * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved * * Contact: Rafal Krypa <[email protected]> * * 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 privilege_db.cpp * @author Krzysztof Sasiak <[email protected]> * @version 0.1 * @brief This file contains declaration of the API to privileges database. */ #include <cstdio> #include <set> #include <list> #include <string> #include <iostream> #include <dpl/log/log.h> #include "privilege_db.h" #define SET_CONTAINS(set,value) set.find(value)!=set.end() #define CATCH_STANDARD_EXCEPTIONS \ catch (DB::SqlConnection::Exception::SyntaxError &e) { \ LogDebug("Syntax error in command: " << e.DumpToString()); \ ThrowMsg(PrivilegeDb::Exception::InternalError, \ "Syntax error in command: " << e.DumpToString()); \ } catch (DB::SqlConnection::Exception::InternalError &e) { \ LogDebug("Mysterious internal error in SqlConnection class" << e.DumpToString()); \ ThrowMsg(PrivilegeDb::Exception::InternalError, \ "Mysterious internal error in SqlConnection class: " << e.DumpToString()); \ } namespace SecurityManager { PrivilegeDb::PrivilegeDb(const std::string &path) { try { mSqlConnection = new DB::SqlConnection(path, DB::SqlConnection::Flag::None, DB::SqlConnection::Flag::RW); } catch (DB::SqlConnection::Exception::Base &e) { LogError("Database initialization error: " << e.DumpToString()); ThrowMsg(PrivilegeDb::Exception::IOError, "Database initialization error:" << e.DumpToString()); }; } PrivilegeDb::~PrivilegeDb() { delete mSqlConnection; } ; void PrivilegeDb::BeginTransaction(void) { try { mSqlConnection->BeginTransaction(); }CATCH_STANDARD_EXCEPTIONS; } void PrivilegeDb::CommitTransaction(void) { try { mSqlConnection->CommitTransaction(); }CATCH_STANDARD_EXCEPTIONS; } void PrivilegeDb::RollbackTransaction(void) { try { mSqlConnection->RollbackTransaction(); }CATCH_STANDARD_EXCEPTIONS; } bool PrivilegeDb::PkgIdExists(const std::string &pkgId) { try { DB::SqlConnection::DataCommandAutoPtr command = mSqlConnection->PrepareDataCommand( Queries.at(QueryType::EPkgIdExists)); command->BindString(1, pkgId.c_str()); if (command->Step()) { LogPedantic("PkgId: " << pkgId << " found in database"); command->Reset(); return true; }; }CATCH_STANDARD_EXCEPTIONS; return false; } bool PrivilegeDb::AddApplication(const std::string &appId, const std::string &pkgId, bool &pkgIdIsNew) { pkgIdIsNew = !(this->PkgIdExists(pkgId)); try { DB::SqlConnection::DataCommandAutoPtr command = mSqlConnection->PrepareDataCommand( Queries.at(QueryType::EAddApplication)); command->BindString(1, appId.c_str()); command->BindString(2, pkgId.c_str()); if (command->Step()) { LogPedantic("Unexpected SQLITE_ROW answer to query: " << Queries.at(QueryType::EAddApplication)); }; command->Reset(); LogPedantic( "Added appId: " << appId << ", pkgId: " << pkgId); return true; }CATCH_STANDARD_EXCEPTIONS; return false; } bool PrivilegeDb::RemoveApplication(const std::string &appId, const std::string &pkgId, bool &pkgIdIsNoMore) { try { DB::SqlConnection::DataCommandAutoPtr command = mSqlConnection->PrepareDataCommand( Queries.at(QueryType::ERemoveApplication)); command->BindString(1, appId.c_str()); command->BindString(2, pkgId.c_str()); if (command->Step()) { LogPedantic("Unexpected SQLITE_ROW answer to query: " << Queries.at(QueryType::ERemoveApplication)); }; command->Reset(); LogPedantic( "Removed appId: " << appId << ", pkgId: " << pkgId); pkgIdIsNoMore = !(this->PkgIdExists(pkgId)); return true; }CATCH_STANDARD_EXCEPTIONS; return false; } bool PrivilegeDb::GetPkgPermissions(const std::string &pkgId, TPermissionsList &currentPermissions) { try { DB::SqlConnection::DataCommandAutoPtr command = mSqlConnection->PrepareDataCommand( Queries.at(QueryType::EGetPkgPermissions)); command->BindString(1, pkgId.c_str()); while (command->Step()) { std::string permission = command->GetColumnString(0); LogPedantic ("Got permission: "<< permission); currentPermissions.push_back(permission); }; return true; }CATCH_STANDARD_EXCEPTIONS; return false; } bool PrivilegeDb::UpdatePermissions(const std::string &appId, const std::string &pkgId, const TPermissionsList &permissions, TPermissionsList &addedPermissions, TPermissionsList &removedPermissions) { DB::SqlConnection::DataCommandAutoPtr command; TPermissionsList curPermissions = TPermissionsList(); if (!this->GetPkgPermissions(pkgId, curPermissions)) return false; try { //Data compilation std::set<std::string> permissionsSet = std::set< std::string>(permissions.begin(), permissions.end()); std::set<std::string> curPermissionsSet = std::set< std::string>(curPermissions.begin(), curPermissions.end()); std::list < std::string > tmpPermissions = std::list < std::string > (permissions.begin(), permissions.end()); tmpPermissions.merge (std::list < std::string >(curPermissions.begin(), curPermissions.end())); tmpPermissions.unique (); for (auto permission : tmpPermissions) { if ((SET_CONTAINS(permissionsSet, permission)) && !(SET_CONTAINS(curPermissionsSet, permission))) { addedPermissions.push_back(permission); } if (!(SET_CONTAINS(permissionsSet, permission)) && (SET_CONTAINS(curPermissionsSet, permission))) { removedPermissions.push_back(permission); } } //adding missing permissions for (auto addedPermission : addedPermissions) { command = mSqlConnection->PrepareDataCommand( Queries.at(QueryType::EAddAppPermissions)); command->BindString(1, appId.c_str()); command->BindString(2, pkgId.c_str()); command->BindString(3, addedPermission.c_str()); if (command->Step()) LogPedantic("Unexpected SQLITE_ROW answer to query: " << Queries.at(QueryType::EAddAppPermissions)); command->Reset(); LogPedantic( "Added appId: " << appId << ", pkgId: " << pkgId << ", permission: " << addedPermission); } //removing unwanted permissions for (auto removedPermission : removedPermissions) { command = mSqlConnection->PrepareDataCommand( Queries.at(QueryType::ERemoveAppPermissions)); command->BindString(1, appId.c_str()); command->BindString(2, pkgId.c_str()); command->BindString(3, removedPermission.c_str()); if (command->Step()) LogPedantic("Unexpected SQLITE_ROW answer to query: " << Queries.at(QueryType::EAddAppPermissions)); LogPedantic( "Removed appId: " << appId << ", pkgId: " << pkgId << ", permission: " << removedPermission); } return true; }CATCH_STANDARD_EXCEPTIONS; return false; } } //namespace SecurityManager <commit_msg>Adjust code formatting in privilege_db.cpp<commit_after>/* * security-manager, database access * * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved * * Contact: Rafal Krypa <[email protected]> * * 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 privilege_db.cpp * @author Krzysztof Sasiak <[email protected]> * @author Rafal Krypa <[email protected]> * @version 0.1 * @brief This file contains declaration of the API to privileges database. */ #include <cstdio> #include <set> #include <list> #include <string> #include <iostream> #include <dpl/log/log.h> #include "privilege_db.h" #define SET_CONTAINS(set,value) set.find(value)!=set.end() #define CATCH_STANDARD_EXCEPTIONS \ catch (DB::SqlConnection::Exception::SyntaxError &e) { \ LogDebug("Syntax error in command: " << e.DumpToString()); \ ThrowMsg(PrivilegeDb::Exception::InternalError, \ "Syntax error in command: " << e.DumpToString()); \ } catch (DB::SqlConnection::Exception::InternalError &e) { \ LogDebug("Mysterious internal error in SqlConnection class" << e.DumpToString()); \ ThrowMsg(PrivilegeDb::Exception::InternalError, \ "Mysterious internal error in SqlConnection class: " << e.DumpToString()); \ } namespace SecurityManager { PrivilegeDb::PrivilegeDb(const std::string &path) { try { mSqlConnection = new DB::SqlConnection(path, DB::SqlConnection::Flag::None, DB::SqlConnection::Flag::RW); } catch (DB::SqlConnection::Exception::Base &e) { LogError("Database initialization error: " << e.DumpToString()); ThrowMsg(PrivilegeDb::Exception::IOError, "Database initialization error:" << e.DumpToString()); }; } PrivilegeDb::~PrivilegeDb() { delete mSqlConnection; } void PrivilegeDb::BeginTransaction(void) { try { mSqlConnection->BeginTransaction(); }CATCH_STANDARD_EXCEPTIONS; } void PrivilegeDb::CommitTransaction(void) { try { mSqlConnection->CommitTransaction(); }CATCH_STANDARD_EXCEPTIONS; } void PrivilegeDb::RollbackTransaction(void) { try { mSqlConnection->RollbackTransaction(); }CATCH_STANDARD_EXCEPTIONS; } bool PrivilegeDb::PkgIdExists(const std::string &pkgId) { try { DB::SqlConnection::DataCommandAutoPtr command = mSqlConnection->PrepareDataCommand( Queries.at(QueryType::EPkgIdExists)); command->BindString(1, pkgId.c_str()); if (command->Step()) { LogPedantic("PkgId: " << pkgId << " found in database"); command->Reset(); return true; }; }CATCH_STANDARD_EXCEPTIONS; return false; } bool PrivilegeDb::AddApplication(const std::string &appId, const std::string &pkgId, bool &pkgIdIsNew) { pkgIdIsNew = !(this->PkgIdExists(pkgId)); try { DB::SqlConnection::DataCommandAutoPtr command = mSqlConnection->PrepareDataCommand( Queries.at(QueryType::EAddApplication)); command->BindString(1, appId.c_str()); command->BindString(2, pkgId.c_str()); if (command->Step()) { LogPedantic("Unexpected SQLITE_ROW answer to query: " << Queries.at(QueryType::EAddApplication)); }; command->Reset(); LogPedantic( "Added appId: " << appId << ", pkgId: " << pkgId); return true; }CATCH_STANDARD_EXCEPTIONS; return false; } bool PrivilegeDb::RemoveApplication(const std::string &appId, const std::string &pkgId, bool &pkgIdIsNoMore) { try { DB::SqlConnection::DataCommandAutoPtr command = mSqlConnection->PrepareDataCommand( Queries.at(QueryType::ERemoveApplication)); command->BindString(1, appId.c_str()); command->BindString(2, pkgId.c_str()); if (command->Step()) { LogPedantic("Unexpected SQLITE_ROW answer to query: " << Queries.at(QueryType::ERemoveApplication)); }; command->Reset(); LogPedantic( "Removed appId: " << appId << ", pkgId: " << pkgId); pkgIdIsNoMore = !(this->PkgIdExists(pkgId)); return true; }CATCH_STANDARD_EXCEPTIONS; return false; } bool PrivilegeDb::GetPkgPermissions(const std::string &pkgId, TPermissionsList &currentPermissions) { try { DB::SqlConnection::DataCommandAutoPtr command = mSqlConnection->PrepareDataCommand( Queries.at(QueryType::EGetPkgPermissions)); command->BindString(1, pkgId.c_str()); while (command->Step()) { std::string permission = command->GetColumnString(0); LogPedantic ("Got permission: "<< permission); currentPermissions.push_back(permission); }; return true; }CATCH_STANDARD_EXCEPTIONS; return false; } bool PrivilegeDb::UpdatePermissions(const std::string &appId, const std::string &pkgId, const TPermissionsList &permissions, TPermissionsList &addedPermissions, TPermissionsList &removedPermissions) { DB::SqlConnection::DataCommandAutoPtr command; TPermissionsList curPermissions = TPermissionsList(); if (!this->GetPkgPermissions(pkgId, curPermissions)) return false; try { //Data compilation std::set<std::string> permissionsSet = std::set< std::string>(permissions.begin(), permissions.end()); std::set<std::string> curPermissionsSet = std::set< std::string>(curPermissions.begin(), curPermissions.end()); std::list < std::string > tmpPermissions = std::list < std::string > (permissions.begin(), permissions.end()); tmpPermissions.merge (std::list < std::string >(curPermissions.begin(), curPermissions.end())); tmpPermissions.unique (); for (auto permission : tmpPermissions) { if ((SET_CONTAINS(permissionsSet, permission)) && !(SET_CONTAINS(curPermissionsSet, permission))) { addedPermissions.push_back(permission); } if (!(SET_CONTAINS(permissionsSet, permission)) && (SET_CONTAINS(curPermissionsSet, permission))) { removedPermissions.push_back(permission); } } //adding missing permissions for (auto addedPermission : addedPermissions) { command = mSqlConnection->PrepareDataCommand( Queries.at(QueryType::EAddAppPermissions)); command->BindString(1, appId.c_str()); command->BindString(2, pkgId.c_str()); command->BindString(3, addedPermission.c_str()); if (command->Step()) LogPedantic("Unexpected SQLITE_ROW answer to query: " << Queries.at(QueryType::EAddAppPermissions)); command->Reset(); LogPedantic( "Added appId: " << appId << ", pkgId: " << pkgId << ", permission: " << addedPermission); } //removing unwanted permissions for (auto removedPermission : removedPermissions) { command = mSqlConnection->PrepareDataCommand( Queries.at(QueryType::ERemoveAppPermissions)); command->BindString(1, appId.c_str()); command->BindString(2, pkgId.c_str()); command->BindString(3, removedPermission.c_str()); if (command->Step()) LogPedantic("Unexpected SQLITE_ROW answer to query: " << Queries.at(QueryType::EAddAppPermissions)); LogPedantic( "Removed appId: " << appId << ", pkgId: " << pkgId << ", permission: " << removedPermission); } return true; }CATCH_STANDARD_EXCEPTIONS; return false; } } //namespace SecurityManager <|endoftext|>
<commit_before>#ifndef NETSTAT_HPP #define NETSTAT_HPP #include <string> #include <vector> struct netstat_t { std::string proto; std::string local_address; std::string foreign_address; uint16_t local_port; uint16_t foreign_port; std::string state; std::string pid; }; typedef std::vector<netstat_t> netstat_list_t; netstat_list_t netstat(); #endif<commit_msg>Fixed missing include for linux in netstat.hpp.<commit_after>#ifndef NETSTAT_HPP #define NETSTAT_HPP #include <stdint.h> #include <string> #include <vector> struct netstat_t { std::string proto; std::string local_address; std::string foreign_address; uint16_t local_port; uint16_t foreign_port; std::string state; std::string pid; }; typedef std::vector<netstat_t> netstat_list_t; netstat_list_t netstat(); #endif<|endoftext|>
<commit_before>#include <cassert> #include <iostream> #include "state.h" #include "global.h" #include "partition/partition_table.h" #include "partition/partition_db.h" #include "util/hash.h" #include "util/utilization.h" #include "server_internal.h" static const float kMaximumUtilizationToAcceptDonation = 0.6; static const size_t kMinBytesFreeToAcceptDonation = 512 * 1024 * 1024; // 512mb std::list<partition_t> HandleJoinRequest(MessageId mesg_id, std::string &new_node) { assert (g_current_node_id != mesg_id.node_id); node_t node_id = hostToNodeId(new_node); assert (node_id == mesg_id.node_id); g_current_node_state->cluster_members_lock.acquireWRLock(); // 1 // handle already joined case if (g_current_node_state->cluster_members.find(node_id) == g_current_node_state->cluster_members.end()) { std::cout << new_node << " " << node_id << " already joined!" << std::endl; } else // allow new node to join the cluster { g_current_node_state->cluster_members[node_id] = new_node; g_current_node_state->saveClusterMemberList(g_cluster_member_list_filename); std::cout << new_node << " " << node_id << " added to cluster" << std::endl; } // send back the partitions owned by this node g_current_node_state->partitions_owned_map_lock.acquireRDLock(); // 2 std::list<partition_t> partitions_owned; for (auto &kv : g_current_node_state->partitions_owned_map) { if (kv.second.state == PartitionState::STABLE) { partitions_owned.push_back(kv.first); } } g_current_node_state->partitions_owned_map_lock.acquireRDLock(); // 2 g_current_node_state->cluster_members_lock.releaseWRLock(); // 1 return partitions_owned; } bool HandleLeaveRequest(MessageId mesg_id) { assert (g_current_node_id != mesg_id.node_id); g_current_node_state->cluster_members_lock.acquireWRLock(); // 1 // handle already left case if (g_current_node_state->cluster_members.find(mesg_id.node_id) == g_current_node_state->cluster_members.end()) { std::cout << mesg_id.node_id << " already left!" << std::endl; } else // remove the node from the cluster { g_current_node_state->cluster_members.erase(mesg_id.node_id); g_current_node_state->saveClusterMemberList(g_cluster_member_list_filename); std::cout << mesg_id.node_id << " left cluster!" << std::endl; } g_current_node_state->cluster_members_lock.releaseWRLock(); // 1 return true; } GetPartitionTableResult HandleGetPartitionTableRequest() { GetPartitionTableResult ret; g_current_node_state->state_lock.acquireRDLock(); // 1 if (g_current_node_state->state == NodeState::JOINING) { ret.success = false; g_current_node_state->state_lock.releaseRDLock(); // 1 } else { g_current_node_state->state_lock.releaseRDLock(); // 1 } // don't need partition table read lock since the table request // is a hint for the Monitor ret.num_partitions = g_cached_partition_table->getNumPartitions(); ret.num_replicas = g_cached_partition_table->getNumReplicas(); ret.partition_table = g_cached_partition_table->getPartitionTable(); ret.success = true; return ret; } PutResult Server::handlePutRequest(node_t sender, transaction_t tid, device_t deviceId, time_t timestamp, time_t expiry, blob data) { assert (g_current_node_id != sender); std::cout << "Received put request from " << sender << " : " << deviceId << " (device) " << timestamp << " (timestamp) " << expiry << " (expiry) " << std::endl; PutResult ret; partition_t partition_to_put_into = g_cached_partition_table->getPartition(hash_integer(deviceId)); PartitionMetadata partition_state; g_current_node_state->partitions_owned_map_lock.acquireRDLock(); // 1 try { partition_state = g_current_node_state->partitions_owned_map.at(partition_to_put_into); } catch (const std::out_of_range &e) // this range is not owned by current node! { std::cout << "received put on unowned range!" << std::endl; ret.status = DATA_NOT_OWNED; g_current_node_state->partitions_owned_map_lock.releaseRDLock(); // 1 return ret; } if (partition_state.state == PartitionState::STABLE || partition_state.state == PartitionState::RECEIVED) { std::cout << "putting into db" << std::endl; PartitionDB *db = partition_state.db; bool success = db->put(deviceId, timestamp, expiry, &data[0], data.size()); if (!success) ret.status = DB_ERROR; else success = ret.status = SUCCESS; } else if (partition_state.state == PartitionState::RECEIVING) // not ready to handle put request yet { std::cout << "currently receiving" << std::endl; ret.status = DATA_MOVING; } else // (partition_state.state == PartitionState::DONATING) { std::cout << "donating the partition" << std::endl; ret.status = DATA_MOVED; ret.moved_to = partition_state.other_node; } g_current_node_state->partitions_owned_map_lock.releaseRDLock(); // 1 std::cout << "Success: " << (ret.status == SUCCESS) << std::endl; return ret; } std::list<std::string> *Server::handleLocateRequest(device_t deviceId) { std::list<std::string> *owners = new std::list<std::string>(); partition_t partition_to_get_from = g_cached_partition_table->getPartition(hash_integer(deviceId)); int num_replicas = g_cached_partition_table->getNumReplicas(); g_cached_partition_table->lock.acquireRDLock(); // 1 g_current_node_state->cluster_members_lock.acquireRDLock(); // 2 node_t *owner_node_ids = g_cached_partition_table->getPartitionOwners(partition_to_get_from); // translate node_ids to actual hostnames for (int i = 0; i < num_replicas; i++) { owners->push_back(g_current_node_state->cluster_members[owner_node_ids[i]]); } g_current_node_state->cluster_members_lock.releaseRDLock(); g_cached_partition_table->lock.releaseRDLock(); return owners; } GetResult Server::handleGetRequest(transaction_t tid, device_t deviceId, time_t begin, time_t end) { GetResult ret; partition_t partition_to_get_from = g_cached_partition_table->getPartition(hash_integer(deviceId)); PartitionMetadata partition_state; g_current_node_state->partitions_owned_map_lock.acquireRDLock(); // 1 try { partition_state = g_current_node_state->partitions_owned_map.at(partition_to_get_from); } catch (const std::out_of_range &e) // this range is not owned by current node! { std::cout << "received get on unowned range!" << std::endl; ret.status = DATA_NOT_OWNED; g_current_node_state->partitions_owned_map_lock.releaseRDLock(); // 1 return ret; } if (partition_state.state == PartitionState::STABLE || partition_state.state == PartitionState::RECEIVED) { PartitionDB *db = partition_state.db; ret.values = db->get(deviceId, begin, end); ret.status = SUCCESS; } else if (partition_state.state == PartitionState::RECEIVING) { ret.status = DATA_MOVING; // not ready to service reads yet } else // DONATING: data no longer at this node { ret.status = DATA_MOVED; ret.moved_to = partition_state.other_node; } g_current_node_state->partitions_owned_map_lock.releaseRDLock(); // 1 return ret; } bool Server::handleUpdatePartitionOwner(node_t sender, transaction_t tid, node_t newOwner, partition_t partition) { assert (g_current_node_id != sender); bool success; g_cached_partition_table->lock.acquireWRLock(); // 1 success = g_cached_partition_table->updatePartitionOwner(sender, newOwner, partition); g_cached_partition_table->lock.releaseWRLock(); // 1 return success; } CanReceiveResult Server::handleCanReceiveRequest(node_t sender, transaction_t tid, partition_t partition_id) { assert (g_current_node_id != sender); CanReceiveResult ret; size_t used = ComputeNodeUtilization(); ret.free = g_local_disk_limit_in_bytes - used; ret.util = ret.free / (float) g_local_disk_limit_in_bytes; if (ret.util > kMaximumUtilizationToAcceptDonation || ret.free < kMinBytesFreeToAcceptDonation) { ret.can_recv = false; return ret; } // don't need the state lock since it is a hint if (g_current_node_state->state != NodeState::STABLE) // can only accept if stable { ret.can_recv = false; return ret; } g_current_node_state->partitions_owned_map_lock.acquireRDLock(); // 1 if (g_current_node_state->partitions_owned_map.find(partition_id) != g_current_node_state->partitions_owned_map.end()) // check if storing partition already { ret.can_recv = false; g_current_node_state->partitions_owned_map_lock.releaseRDLock(); // 1 return ret; } else { g_current_node_state->partitions_owned_map_lock.releaseRDLock(); // 1 } ret.can_recv = true; return ret; } bool Server::handleCommitReceiveRequest(node_t sender, transaction_t tid, partition_t partition_id) { assert (g_current_node_id != sender); size_t used = ComputeNodeUtilization(); // TODO what if we over commit? size_t free_space = g_local_disk_limit_in_bytes - used; float util = free_space / (float) g_local_disk_limit_in_bytes; if (util > kMaximumUtilizationToAcceptDonation || free_space < kMinBytesFreeToAcceptDonation) { return false; } g_current_node_state->state_lock.acquireRDLock(); // 1 if (g_current_node_state->state != NodeState::STABLE) // can only accept if stable { g_current_node_state->state_lock.releaseRDLock(); // 1 return false; } g_current_node_state->partitions_owned_map_lock.acquireWRLock(); // 2 if (g_current_node_state->partitions_owned_map.find(partition_id) != g_current_node_state->partitions_owned_map.end()) // check if storing partition already { PartitionMetadata pm = g_current_node_state->partitions_owned_map[partition_id]; if (pm.state == PartitionState::RECEIVING && pm.other_node == sender) // retransmission of comfirm receive { // reply true } else // already own or receiving the partition from another source { g_current_node_state->partitions_owned_map_lock.releaseWRLock(); // 2 g_current_node_state->state_lock.releaseRDLock(); // 1 return false; } } else // add to partition map { PartitionMetadata pm; pm.db = NULL; // get partition db filename pm.state = PartitionState::RECEIVING; pm.other_node = sender; g_current_node_state->partitions_owned_map[partition_id] = pm; g_current_node_state->savePartitionState(g_owned_partition_state_filename); } g_current_node_state->partitions_owned_map_lock.releaseWRLock(); // 2 g_current_node_state->state_lock.releaseRDLock(); // 1 // update cached partition to node mapping g_cached_partition_table->lock.acquireWRLock(); g_cached_partition_table->updatePartitionOwner(sender, g_current_node_id, partition_id); g_cached_partition_table->lock.releaseWRLock(); return true; } bool Server::handleCommitAsStableRequest(node_t sender, transaction_t tid, partition_t partition_id) { assert (g_current_node_id != sender); g_current_node_state->partitions_owned_map_lock.acquireWRLock(); // 1 // Cannot commit as stable if (g_current_node_state->partitions_owned_map.find(partition_id) == g_current_node_state->partitions_owned_map.end() || (g_current_node_state->partitions_owned_map[partition_id].state != PartitionState::RECEIVED && g_current_node_state->partitions_owned_map[partition_id].state != PartitionState::STABLE)) { g_current_node_state->partitions_owned_map_lock.releaseWRLock(); // 1 return false; } g_current_node_state->partitions_owned_map[partition_id].state = PartitionState::STABLE; g_current_node_state->savePartitionState(g_owned_partition_state_filename); g_current_node_state->partitions_owned_map_lock.releaseWRLock(); // 1 return true; } <commit_msg>updated override<commit_after>#include <cassert> #include <iostream> #include "state.h" #include "global.h" #include "partition/partition_table.h" #include "partition/partition_db.h" #include "util/hash.h" #include "util/utilization.h" #include "server_internal.h" static const float kMaximumUtilizationToAcceptDonation = 0.6; static const size_t kMinBytesFreeToAcceptDonation = 512 * 1024 * 1024; // 512mb std::list<partition_t> HandleJoinRequest(MessageId mesg_id, std::string &new_node) { assert (g_current_node_id != mesg_id.node_id); node_t node_id = hostToNodeId(new_node); assert (node_id == mesg_id.node_id); g_current_node_state->cluster_members_lock.acquireWRLock(); // 1 // handle already joined case if (g_current_node_state->cluster_members.find(node_id) == g_current_node_state->cluster_members.end()) { std::cout << new_node << " " << node_id << " already joined!" << std::endl; } else // allow new node to join the cluster { g_current_node_state->cluster_members[node_id] = new_node; g_current_node_state->saveClusterMemberList(g_cluster_member_list_filename); std::cout << new_node << " " << node_id << " added to cluster" << std::endl; } // send back the partitions owned by this node g_current_node_state->partitions_owned_map_lock.acquireRDLock(); // 2 std::list<partition_t> partitions_owned; for (auto &kv : g_current_node_state->partitions_owned_map) { if (kv.second.state == PartitionState::STABLE) { partitions_owned.push_back(kv.first); } } g_current_node_state->partitions_owned_map_lock.acquireRDLock(); // 2 g_current_node_state->cluster_members_lock.releaseWRLock(); // 1 return partitions_owned; } bool HandleLeaveRequest(MessageId mesg_id) { assert (g_current_node_id != mesg_id.node_id); g_current_node_state->cluster_members_lock.acquireWRLock(); // 1 // handle already left case if (g_current_node_state->cluster_members.find(mesg_id.node_id) == g_current_node_state->cluster_members.end()) { std::cout << mesg_id.node_id << " already left!" << std::endl; } else // remove the node from the cluster { g_current_node_state->cluster_members.erase(mesg_id.node_id); g_current_node_state->saveClusterMemberList(g_cluster_member_list_filename); std::cout << mesg_id.node_id << " left cluster!" << std::endl; } g_current_node_state->cluster_members_lock.releaseWRLock(); // 1 return true; } GetPartitionTableResult HandleGetPartitionTableRequest() { GetPartitionTableResult ret; g_current_node_state->state_lock.acquireRDLock(); // 1 if (g_current_node_state->state == NodeState::JOINING) { ret.success = false; g_current_node_state->state_lock.releaseRDLock(); // 1 } else { g_current_node_state->state_lock.releaseRDLock(); // 1 } // don't need partition table read lock since the table request // is a hint for the Monitor ret.num_partitions = g_cached_partition_table->getNumPartitions(); ret.num_replicas = g_cached_partition_table->getNumReplicas(); ret.partition_table = g_cached_partition_table->getPartitionTable(); ret.success = true; return ret; } PutResult Server::handlePutRequest(node_t sender, transaction_t tid, device_t deviceId, time_t timestamp, time_t expiry, blob data) { assert (g_current_node_id != sender); std::cout << "Received put request from " << sender << " : " << deviceId << " (device) " << timestamp << " (timestamp) " << expiry << " (expiry) " << std::endl; PutResult ret; partition_t partition_to_put_into = g_cached_partition_table->getPartition(hash_integer(deviceId)); PartitionMetadata partition_state; g_current_node_state->partitions_owned_map_lock.acquireRDLock(); // 1 try { partition_state = g_current_node_state->partitions_owned_map.at(partition_to_put_into); } catch (const std::out_of_range &e) // this range is not owned by current node! { std::cout << "received put on unowned range!" << std::endl; ret.status = DATA_NOT_OWNED; g_current_node_state->partitions_owned_map_lock.releaseRDLock(); // 1 return ret; } if (partition_state.state == PartitionState::STABLE || partition_state.state == PartitionState::RECEIVED) { std::cout << "putting into db" << std::endl; PartitionDB *db = partition_state.db; bool success = db->put(deviceId, timestamp, expiry, &data[0], data.size()); if (!success) ret.status = DB_ERROR; else success = ret.status = SUCCESS; } else if (partition_state.state == PartitionState::RECEIVING) // not ready to handle put request yet { std::cout << "currently receiving" << std::endl; ret.status = DATA_MOVING; } else // (partition_state.state == PartitionState::DONATING) { std::cout << "donating the partition" << std::endl; ret.status = DATA_MOVED; ret.moved_to = partition_state.other_node; } g_current_node_state->partitions_owned_map_lock.releaseRDLock(); // 1 std::cout << "Success: " << (ret.status == SUCCESS) << std::endl; return ret; } std::list<std::string> *Server::handleLocateRequest(device_t deviceId) { std::list<std::string> *owners = new std::list<std::string>(); partition_t partition_to_get_from = g_cached_partition_table->getPartition(hash_integer(deviceId)); int num_replicas = g_cached_partition_table->getNumReplicas(); g_cached_partition_table->lock.acquireRDLock(); // 1 g_current_node_state->cluster_members_lock.acquireRDLock(); // 2 node_t *owner_node_ids = g_cached_partition_table->getPartitionOwners(partition_to_get_from); // translate node_ids to actual hostnames for (int i = 0; i < num_replicas; i++) { owners->push_back(g_current_node_state->cluster_members[owner_node_ids[i]]); } g_current_node_state->cluster_members_lock.releaseRDLock(); g_cached_partition_table->lock.releaseRDLock(); return owners; } GetResult Server::handleGetRequest(transaction_t tid, device_t deviceId, time_t begin, time_t end) { GetResult ret; partition_t partition_to_get_from = g_cached_partition_table->getPartition(hash_integer(deviceId)); PartitionMetadata partition_state; g_current_node_state->partitions_owned_map_lock.acquireRDLock(); // 1 try { partition_state = g_current_node_state->partitions_owned_map.at(partition_to_get_from); } catch (const std::out_of_range &e) // this range is not owned by current node! { std::cout << "received get on unowned range!" << std::endl; ret.status = DATA_NOT_OWNED; g_current_node_state->partitions_owned_map_lock.releaseRDLock(); // 1 return ret; } if (partition_state.state == PartitionState::STABLE || partition_state.state == PartitionState::RECEIVED) { PartitionDB *db = partition_state.db; ret.values = db->get(deviceId, begin, end); ret.status = SUCCESS; } else if (partition_state.state == PartitionState::RECEIVING) { ret.status = DATA_MOVING; // not ready to service reads yet } else // DONATING: data no longer at this node { ret.status = DATA_MOVED; ret.moved_to = partition_state.other_node; } g_current_node_state->partitions_owned_map_lock.releaseRDLock(); // 1 return ret; } bool Server::handleUpdatePartitionOwner(node_t sender, transaction_t tid, node_t newOwner, partition_t partition) { assert (g_current_node_id != sender); bool success; g_cached_partition_table->lock.acquireWRLock(); // 1 success = g_cached_partition_table->updatePartitionOwner(sender, newOwner, partition); g_cached_partition_table->lock.releaseWRLock(); // 1 return success; } CanReceiveResult Server::handleCanReceiveRequest(node_t sender, transaction_t tid, partition_t partition_id) { assert (g_current_node_id != sender); CanReceiveResult ret; size_t used = ComputeNodeUtilization(); ret.free = g_local_disk_limit_in_bytes - used; ret.util = ret.free / (float) g_local_disk_limit_in_bytes; if (ret.util > kMaximumUtilizationToAcceptDonation || ret.free < kMinBytesFreeToAcceptDonation) { ret.can_recv = false; return ret; } // don't need the state lock since it is a hint if (g_current_node_state->state != NodeState::STABLE) // can only accept if stable { ret.can_recv = false; return ret; } g_current_node_state->partitions_owned_map_lock.acquireRDLock(); // 1 if (g_current_node_state->partitions_owned_map.find(partition_id) != g_current_node_state->partitions_owned_map.end()) // check if storing partition already { ret.can_recv = false; g_current_node_state->partitions_owned_map_lock.releaseRDLock(); // 1 return ret; } else { g_current_node_state->partitions_owned_map_lock.releaseRDLock(); // 1 } ret.can_recv = true; return ret; } bool Server::handleCommitReceiveRequest(node_t sender, transaction_t tid, partition_t partition_id) { assert (g_current_node_id != sender); size_t used = ComputeNodeUtilization(); // TODO what if we over commit? size_t free_space = g_local_disk_limit_in_bytes - used; float util = free_space / (float) g_local_disk_limit_in_bytes; if (util > kMaximumUtilizationToAcceptDonation || free_space < kMinBytesFreeToAcceptDonation) { return false; } g_current_node_state->state_lock.acquireRDLock(); // 1 if (g_current_node_state->state != NodeState::STABLE) // can only accept if stable { g_current_node_state->state_lock.releaseRDLock(); // 1 return false; } g_current_node_state->partitions_owned_map_lock.acquireWRLock(); // 2 if (g_current_node_state->partitions_owned_map.find(partition_id) != g_current_node_state->partitions_owned_map.end()) // check if storing partition already { PartitionMetadata pm = g_current_node_state->partitions_owned_map[partition_id]; if (pm.state == PartitionState::RECEIVING && pm.other_node == sender) // retransmission of comfirm receive { // reply true } else // already own or receiving the partition from another source { g_current_node_state->partitions_owned_map_lock.releaseWRLock(); // 2 g_current_node_state->state_lock.releaseRDLock(); // 1 return false; } } else // add to partition map { PartitionMetadata pm; pm.db = NULL; // get partition db filename pm.state = PartitionState::RECEIVING; pm.other_node = sender; g_current_node_state->partitions_owned_map[partition_id] = pm; g_current_node_state->savePartitionState(g_owned_partition_state_filename); } g_current_node_state->partitions_owned_map_lock.releaseWRLock(); // 2 g_current_node_state->state_lock.releaseRDLock(); // 1 // update cached partition to node mapping g_cached_partition_table->lock.acquireWRLock(); g_cached_partition_table->updatePartitionOwner(sender, g_current_node_id, partition_id); g_cached_partition_table->lock.releaseWRLock(); return true; } bool Server::handleCommitAsStableRequest(node_t sender, transaction_t tid, partition_t partition_id) { assert (g_current_node_id != sender); g_current_node_state->partitions_owned_map_lock.acquireWRLock(); // 1 // Cannot commit as stable if (g_current_node_state->partitions_owned_map.find(partition_id) == g_current_node_state->partitions_owned_map.end() || (g_current_node_state->partitions_owned_map[partition_id].state != PartitionState::RECEIVED && g_current_node_state->partitions_owned_map[partition_id].state != PartitionState::STABLE)) { g_current_node_state->partitions_owned_map_lock.releaseWRLock(); // 1 return false; } g_current_node_state->partitions_owned_map[partition_id].state = PartitionState::STABLE; g_current_node_state->savePartitionState(g_owned_partition_state_filename); g_current_node_state->partitions_owned_map_lock.releaseWRLock(); // 1 return true; } <|endoftext|>
<commit_before>/* * Copyright 2015 Cloudius Systems */ #pragma once #include "core/iostream.hh" #include "core/fstream.hh" #include "types.hh" #include "compress.hh" namespace sstables { class file_writer { output_stream<char> _out; size_t _offset = 0; public: file_writer(file f, size_t buffer_size = 8192) : _out(make_file_output_stream(std::move(f), buffer_size)) {} file_writer(output_stream<char>&& out) : _out(std::move(out)) {} virtual ~file_writer() = default; file_writer(file_writer&&) = default; virtual future<> write(const char* buf, size_t n) { _offset += n; return _out.write(buf, n); } virtual future<> write(const bytes& s) { _offset += s.size(); return _out.write(s); } future<> flush() { return _out.flush(); } future<> close() { return _out.close(); } size_t offset() { return _offset; } friend class checksummed_file_writer; }; output_stream<char> make_checksummed_file_output_stream(file f, size_t buffer_size, struct checksum& cinfo, uint32_t& full_file_checksum, bool checksum_file); class checksummed_file_writer : public file_writer { checksum _c; uint32_t _full_checksum; bool _checksum_file; public: checksummed_file_writer(file f, size_t buffer_size = 8192, bool checksum_file = false) : file_writer(make_checksummed_file_output_stream(std::move(f), buffer_size, _c, _full_checksum, checksum_file)) { _checksum_file = checksum_file; _c.chunk_size = std::min(size_t(DEFAULT_CHUNK_SIZE), buffer_size); _full_checksum = init_checksum_adler32(); } // Since we are exposing a reference to _full_checksum, we delete the move // constructor. If it is moved, the reference will refer to the old // location. checksummed_file_writer(checksummed_file_writer&&) = delete; checksummed_file_writer(const checksummed_file_writer&) = default; checksum& finalize_checksum() { return _c; } uint32_t full_checksum() { return _full_checksum; } }; class checksummed_file_data_sink_impl : public data_sink_impl { output_stream<char> _out; struct checksum& _c; uint32_t& _full_checksum; bool _checksum_file; public: checksummed_file_data_sink_impl(file f, size_t buffer_size, struct checksum& c, uint32_t& full_file_checksum, bool checksum_file) : _out(make_file_output_stream(std::move(f), buffer_size)) , _c(c) , _full_checksum(full_file_checksum) , _checksum_file(checksum_file) {} future<> put(net::packet data) { abort(); } virtual future<> put(temporary_buffer<char> buf) override { // bufs will usually be a multiple of chunk size, but this won't be the case for // the last buffer being flushed. if (!_checksum_file) { _full_checksum = checksum_adler32(_full_checksum, buf.begin(), buf.size()); } else { for (size_t offset = 0; offset < buf.size(); offset += _c.chunk_size) { size_t size = std::min(size_t(_c.chunk_size), buf.size() - offset); uint32_t per_chunk_checksum = init_checksum_adler32(); per_chunk_checksum = checksum_adler32(per_chunk_checksum, buf.begin() + offset, size); _full_checksum = checksum_adler32_combine(_full_checksum, per_chunk_checksum, size); _c.checksums.push_back(per_chunk_checksum); } } return _out.write(buf.begin(), buf.size()); } virtual future<> close() { // Nothing to do, because close at the file_stream level will call flush on us. return _out.close(); } }; class checksummed_file_data_sink : public data_sink { public: checksummed_file_data_sink(file f, size_t buffer_size, struct checksum& cinfo, uint32_t& full_file_checksum, bool checksum_file) : data_sink(std::make_unique<checksummed_file_data_sink_impl>(std::move(f), buffer_size, cinfo, full_file_checksum, checksum_file)) {} }; inline output_stream<char> make_checksummed_file_output_stream(file f, size_t buffer_size, struct checksum& cinfo, uint32_t& full_file_checksum, bool checksum_file) { return output_stream<char>(checksummed_file_data_sink(std::move(f), buffer_size, cinfo, full_file_checksum, checksum_file), buffer_size, true); } // compressed_file_data_sink_impl works as a filter for a file output stream, // where the buffer flushed will be compressed and its checksum computed, then // the result passed to a regular output stream. class compressed_file_data_sink_impl : public data_sink_impl { output_stream<char> _out; sstables::compression* _compression_metadata; size_t _pos = 0; public: compressed_file_data_sink_impl(file f, sstables::compression* cm, file_output_stream_options options) : _out(make_file_output_stream(std::move(f), options)) , _compression_metadata(cm) {} future<> put(net::packet data) { abort(); } virtual future<> put(temporary_buffer<char> buf) override { auto output_len = _compression_metadata->compress_max_size(buf.size()); // account space for checksum that goes after compressed data. temporary_buffer<char> compressed(output_len + 4); // compress flushed data. auto len = _compression_metadata->compress(buf.get(), buf.size(), compressed.get_write(), output_len); if (len > output_len) { throw std::runtime_error("possible overflow during compression"); } _compression_metadata->offsets.elements.push_back(_pos); // account compressed data + 32-bit checksum. _pos += len + 4; _compression_metadata->set_compressed_file_length(_pos); // total length of the uncompressed data. _compression_metadata->data_len += buf.size(); // compute 32-bit checksum for compressed data. uint32_t per_chunk_checksum = checksum_adler32(compressed.get(), len); _compression_metadata->update_full_checksum(per_chunk_checksum, len); // write checksum into buffer after compressed data. *unaligned_cast<uint32_t*>(compressed.get_write() + len) = htonl(per_chunk_checksum); compressed.trim(len + 4); auto f = _out.write(compressed.get(), compressed.size()); return f.then([compressed = std::move(compressed)] {}); } virtual future<> close() { return _out.close(); } }; class compressed_file_data_sink : public data_sink { public: compressed_file_data_sink(file f, sstables::compression* cm, file_output_stream_options options) : data_sink(std::make_unique<compressed_file_data_sink_impl>( std::move(f), cm, options)) {} }; static inline output_stream<char> make_compressed_file_output_stream(file f, sstables::compression* cm) { file_output_stream_options options; // buffer of output stream is set to chunk length, because flush must // happen every time a chunk was filled up. options.buffer_size = cm->uncompressed_chunk_length(); return output_stream<char>(compressed_file_data_sink(std::move(f), cm, options), options.buffer_size, true); } } <commit_msg>checksummed file writer: some cleanups<commit_after>/* * Copyright 2015 Cloudius Systems */ #pragma once #include "core/iostream.hh" #include "core/fstream.hh" #include "types.hh" #include "compress.hh" namespace sstables { class file_writer { output_stream<char> _out; size_t _offset = 0; public: file_writer(file f, size_t buffer_size = 8192) : _out(make_file_output_stream(std::move(f), buffer_size)) {} file_writer(output_stream<char>&& out) : _out(std::move(out)) {} virtual ~file_writer() = default; file_writer(file_writer&&) = default; virtual future<> write(const char* buf, size_t n) { _offset += n; return _out.write(buf, n); } virtual future<> write(const bytes& s) { _offset += s.size(); return _out.write(s); } future<> flush() { return _out.flush(); } future<> close() { return _out.close(); } size_t offset() { return _offset; } }; output_stream<char> make_checksummed_file_output_stream(file f, size_t buffer_size, struct checksum& cinfo, uint32_t& full_file_checksum, bool checksum_file); class checksummed_file_writer : public file_writer { checksum _c; uint32_t _full_checksum; public: checksummed_file_writer(file f, size_t buffer_size = 8192, bool checksum_file = false) : file_writer(make_checksummed_file_output_stream(std::move(f), buffer_size, _c, _full_checksum, checksum_file)) , _c({uint32_t(std::min(size_t(DEFAULT_CHUNK_SIZE), buffer_size))}) , _full_checksum(init_checksum_adler32()) {} // Since we are exposing a reference to _full_checksum, we delete the move // constructor. If it is moved, the reference will refer to the old // location. checksummed_file_writer(checksummed_file_writer&&) = delete; checksummed_file_writer(const checksummed_file_writer&) = default; checksum& finalize_checksum() { return _c; } uint32_t full_checksum() { return _full_checksum; } }; class checksummed_file_data_sink_impl : public data_sink_impl { output_stream<char> _out; struct checksum& _c; uint32_t& _full_checksum; bool _checksum_file; public: checksummed_file_data_sink_impl(file f, size_t buffer_size, struct checksum& c, uint32_t& full_file_checksum, bool checksum_file) : _out(make_file_output_stream(std::move(f), buffer_size)) , _c(c) , _full_checksum(full_file_checksum) , _checksum_file(checksum_file) {} future<> put(net::packet data) { abort(); } virtual future<> put(temporary_buffer<char> buf) override { // bufs will usually be a multiple of chunk size, but this won't be the case for // the last buffer being flushed. if (!_checksum_file) { _full_checksum = checksum_adler32(_full_checksum, buf.begin(), buf.size()); } else { for (size_t offset = 0; offset < buf.size(); offset += _c.chunk_size) { size_t size = std::min(size_t(_c.chunk_size), buf.size() - offset); uint32_t per_chunk_checksum = init_checksum_adler32(); per_chunk_checksum = checksum_adler32(per_chunk_checksum, buf.begin() + offset, size); _full_checksum = checksum_adler32_combine(_full_checksum, per_chunk_checksum, size); _c.checksums.push_back(per_chunk_checksum); } } return _out.write(buf.begin(), buf.size()); } virtual future<> close() { // Nothing to do, because close at the file_stream level will call flush on us. return _out.close(); } }; class checksummed_file_data_sink : public data_sink { public: checksummed_file_data_sink(file f, size_t buffer_size, struct checksum& cinfo, uint32_t& full_file_checksum, bool checksum_file) : data_sink(std::make_unique<checksummed_file_data_sink_impl>(std::move(f), buffer_size, cinfo, full_file_checksum, checksum_file)) {} }; inline output_stream<char> make_checksummed_file_output_stream(file f, size_t buffer_size, struct checksum& cinfo, uint32_t& full_file_checksum, bool checksum_file) { return output_stream<char>(checksummed_file_data_sink(std::move(f), buffer_size, cinfo, full_file_checksum, checksum_file), buffer_size, true); } // compressed_file_data_sink_impl works as a filter for a file output stream, // where the buffer flushed will be compressed and its checksum computed, then // the result passed to a regular output stream. class compressed_file_data_sink_impl : public data_sink_impl { output_stream<char> _out; sstables::compression* _compression_metadata; size_t _pos = 0; public: compressed_file_data_sink_impl(file f, sstables::compression* cm, file_output_stream_options options) : _out(make_file_output_stream(std::move(f), options)) , _compression_metadata(cm) {} future<> put(net::packet data) { abort(); } virtual future<> put(temporary_buffer<char> buf) override { auto output_len = _compression_metadata->compress_max_size(buf.size()); // account space for checksum that goes after compressed data. temporary_buffer<char> compressed(output_len + 4); // compress flushed data. auto len = _compression_metadata->compress(buf.get(), buf.size(), compressed.get_write(), output_len); if (len > output_len) { throw std::runtime_error("possible overflow during compression"); } _compression_metadata->offsets.elements.push_back(_pos); // account compressed data + 32-bit checksum. _pos += len + 4; _compression_metadata->set_compressed_file_length(_pos); // total length of the uncompressed data. _compression_metadata->data_len += buf.size(); // compute 32-bit checksum for compressed data. uint32_t per_chunk_checksum = checksum_adler32(compressed.get(), len); _compression_metadata->update_full_checksum(per_chunk_checksum, len); // write checksum into buffer after compressed data. *unaligned_cast<uint32_t*>(compressed.get_write() + len) = htonl(per_chunk_checksum); compressed.trim(len + 4); auto f = _out.write(compressed.get(), compressed.size()); return f.then([compressed = std::move(compressed)] {}); } virtual future<> close() { return _out.close(); } }; class compressed_file_data_sink : public data_sink { public: compressed_file_data_sink(file f, sstables::compression* cm, file_output_stream_options options) : data_sink(std::make_unique<compressed_file_data_sink_impl>( std::move(f), cm, options)) {} }; static inline output_stream<char> make_compressed_file_output_stream(file f, sstables::compression* cm) { file_output_stream_options options; // buffer of output stream is set to chunk length, because flush must // happen every time a chunk was filled up. options.buffer_size = cm->uncompressed_chunk_length(); return output_stream<char>(compressed_file_data_sink(std::move(f), cm, options), options.buffer_size, true); } } <|endoftext|>
<commit_before>/* Copyright 2008 Larry Gritz and the other authors and contributors. All Rights Reserved. Based on BSD-licensed software Copyright 2004 NVIDIA Corp. 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 software's owners nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (This is the Modified BSD License) */ #include <cassert> #include <cstdio> extern "C" { #include "jpeglib.h" } #include "imageio.h" #include "fmath.h" #include "jpeg_pvt.h" OIIO_PLUGIN_NAMESPACE_BEGIN using namespace OpenImageIO; using namespace Jpeg_imageio_pvt; // See JPEG library documentation in /usr/share/doc/libjpeg-devel-6b // N.B. The class definition for JpgInput is in jpeg_pvt.h. // Export version number and create function symbols OIIO_PLUGIN_EXPORTS_BEGIN DLLEXPORT int jpeg_imageio_version = OPENIMAGEIO_PLUGIN_VERSION; DLLEXPORT ImageInput *jpeg_input_imageio_create () { return new JpgInput; } DLLEXPORT const char *jpeg_input_extensions[] = { "jpg", "jpe", "jpeg", NULL }; OIIO_PLUGIN_EXPORTS_END bool JpgInput::open (const std::string &name, ImageSpec &newspec, const ImageSpec &config) { const ImageIOParameter *p = config.find_attribute ("_jpeg:raw", TypeDesc::TypeInt); m_raw = p && *(int *)p->data(); return open (name, newspec); } bool JpgInput::open (const std::string &name, ImageSpec &newspec) { // Check that file exists and can be opened m_filename = name; m_fd = fopen (name.c_str(), "rb"); if (m_fd == NULL) { error ("Could not open file \"%s\"", name.c_str()); return false; } // Check magic number to assure this is a JPEG file int magic = 0; if (fread (&magic, 4, 1, m_fd) != 1) { error ("Empty file"); return false; } rewind (m_fd); const int JPEG_MAGIC = 0xffd8ffe0, JPEG_MAGIC_OTHER_ENDIAN = 0xe0ffd8ff; const int JPEG_MAGIC2 = 0xffd8ffe1, JPEG_MAGIC2_OTHER_ENDIAN = 0xe1ffd8ff; if (magic != JPEG_MAGIC && magic != JPEG_MAGIC_OTHER_ENDIAN && magic != JPEG_MAGIC2 && magic != JPEG_MAGIC2_OTHER_ENDIAN) { fclose (m_fd); m_fd = NULL; error ("\"%s\" is a JPEG file, magic number doesn't match", name.c_str()); return false; } m_cinfo.err = jpeg_std_error (&m_jerr); jpeg_create_decompress (&m_cinfo); // initialize decompressor jpeg_stdio_src (&m_cinfo, m_fd); // specify the data source // Request saving of EXIF and other special tags for later spelunking for (int mark = 0; mark < 16; ++mark) jpeg_save_markers (&m_cinfo, JPEG_APP0+mark, 0xffff); jpeg_save_markers (&m_cinfo, JPEG_COM, 0xffff); // comment marker jpeg_read_header (&m_cinfo, FALSE); // read the file parameters if (m_raw) m_coeffs = jpeg_read_coefficients (&m_cinfo); else jpeg_start_decompress (&m_cinfo); // start working m_next_scanline = 0; // next scanline we'll read m_spec = ImageSpec (m_cinfo.output_width, m_cinfo.output_height, m_cinfo.output_components, TypeDesc::UINT8); for (jpeg_saved_marker_ptr m = m_cinfo.marker_list; m; m = m->next) { if (m->marker == (JPEG_APP0+1) && ! strcmp ((const char *)m->data, "Exif")) decode_exif ((unsigned char *)m->data, m->data_length, m_spec); else if (m->marker == (JPEG_APP0+1) && ! strcmp ((const char *)m->data, "http://ns.adobe.com/xap/1.0/")) { #ifdef DEBUG std::cerr << "Found APP1 XMP! length " << m->data_length << "\n"; #endif std::string xml ((const char *)m->data, m->data_length); OpenImageIO::decode_xmp (xml, m_spec); } else if (m->marker == (JPEG_APP0+13) && ! strcmp ((const char *)m->data, "Photoshop 3.0")) jpeg_decode_iptc ((unsigned char *)m->data); else if (m->marker == JPEG_COM) { if (! m_spec.find_attribute ("ImageDescription", TypeDesc::STRING)) m_spec.attribute ("ImageDescription", std::string ((const char *)m->data)); } } newspec = m_spec; return true; } bool JpgInput::read_native_scanline (int y, int z, void *data) { if (m_raw) return false; if (y < 0 || y >= (int)m_cinfo.output_height) // out of range scanline return false; if (m_next_scanline > y) { // User is trying to read an earlier scanline than the one we're // up to. Easy fix: close the file and re-open. ImageSpec dummyspec; int subimage = current_subimage(); if (! close () || ! open (m_filename, dummyspec) || ! seek_subimage (subimage, dummyspec)) return false; // Somehow, the re-open failed assert (m_next_scanline == 0 && current_subimage() == subimage); } while (m_next_scanline <= y) { // Keep reading until we're read the scanline we really need jpeg_read_scanlines (&m_cinfo, (JSAMPLE **)&data, 1); // read one scanline ++m_next_scanline; } return true; } bool JpgInput::close () { if (m_fd != NULL) { // N.B. don't call finish_decompress if we never read anything if (m_next_scanline > 0) { // But if we've only read some scanlines, read the rest to avoid // errors std::vector<char> buf (spec().scanline_bytes()); char *data = &buf[0]; while (m_next_scanline < spec().height) { jpeg_read_scanlines (&m_cinfo, (JSAMPLE **)&data, 1); ++m_next_scanline; } } if (m_next_scanline > 0 || m_raw) jpeg_finish_decompress (&m_cinfo); jpeg_destroy_decompress (&m_cinfo); fclose (m_fd); m_fd = NULL; } init (); // Reset to initial state return true; } void JpgInput::jpeg_decode_iptc (const unsigned char *buf) { // APP13 blob doesn't have to be IPTC info. Look for the IPTC marker, // which is the string "Photoshop 3.0" followed by a null character. if (strcmp ((const char *)buf, "Photoshop 3.0")) return; buf += strlen("Photoshop 3.0") + 1; // Next are the 4 bytes "8BIM" if (strncmp ((const char *)buf, "8BIM", 4)) return; buf += 4; // Next two bytes are the segment type, in big endian. // We expect 1028 to indicate IPTC data block. if (((buf[0] << 8) + buf[1]) != 1028) return; buf += 2; // Next are 4 bytes of 0 padding, just skip it. buf += 4; // Next is 2 byte (big endian) giving the size of the segment int segmentsize = (buf[0] << 8) + buf[1]; buf += 2; OpenImageIO::decode_iptc_iim (buf, segmentsize, m_spec); } OIIO_PLUGIN_NAMESPACE_END <commit_msg>Assume JPEG is always sRGB unless the EXIF tag says otherwise.<commit_after>/* Copyright 2008 Larry Gritz and the other authors and contributors. All Rights Reserved. Based on BSD-licensed software Copyright 2004 NVIDIA Corp. 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 software's owners nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (This is the Modified BSD License) */ #include <cassert> #include <cstdio> extern "C" { #include "jpeglib.h" } #include "imageio.h" #include "fmath.h" #include "jpeg_pvt.h" OIIO_PLUGIN_NAMESPACE_BEGIN using namespace OpenImageIO; using namespace Jpeg_imageio_pvt; // See JPEG library documentation in /usr/share/doc/libjpeg-devel-6b // N.B. The class definition for JpgInput is in jpeg_pvt.h. // Export version number and create function symbols OIIO_PLUGIN_EXPORTS_BEGIN DLLEXPORT int jpeg_imageio_version = OPENIMAGEIO_PLUGIN_VERSION; DLLEXPORT ImageInput *jpeg_input_imageio_create () { return new JpgInput; } DLLEXPORT const char *jpeg_input_extensions[] = { "jpg", "jpe", "jpeg", NULL }; OIIO_PLUGIN_EXPORTS_END bool JpgInput::open (const std::string &name, ImageSpec &newspec, const ImageSpec &config) { const ImageIOParameter *p = config.find_attribute ("_jpeg:raw", TypeDesc::TypeInt); m_raw = p && *(int *)p->data(); return open (name, newspec); } bool JpgInput::open (const std::string &name, ImageSpec &newspec) { // Check that file exists and can be opened m_filename = name; m_fd = fopen (name.c_str(), "rb"); if (m_fd == NULL) { error ("Could not open file \"%s\"", name.c_str()); return false; } // Check magic number to assure this is a JPEG file int magic = 0; if (fread (&magic, 4, 1, m_fd) != 1) { error ("Empty file"); return false; } rewind (m_fd); const int JPEG_MAGIC = 0xffd8ffe0, JPEG_MAGIC_OTHER_ENDIAN = 0xe0ffd8ff; const int JPEG_MAGIC2 = 0xffd8ffe1, JPEG_MAGIC2_OTHER_ENDIAN = 0xe1ffd8ff; if (magic != JPEG_MAGIC && magic != JPEG_MAGIC_OTHER_ENDIAN && magic != JPEG_MAGIC2 && magic != JPEG_MAGIC2_OTHER_ENDIAN) { fclose (m_fd); m_fd = NULL; error ("\"%s\" is a JPEG file, magic number doesn't match", name.c_str()); return false; } m_cinfo.err = jpeg_std_error (&m_jerr); jpeg_create_decompress (&m_cinfo); // initialize decompressor jpeg_stdio_src (&m_cinfo, m_fd); // specify the data source // Request saving of EXIF and other special tags for later spelunking for (int mark = 0; mark < 16; ++mark) jpeg_save_markers (&m_cinfo, JPEG_APP0+mark, 0xffff); jpeg_save_markers (&m_cinfo, JPEG_COM, 0xffff); // comment marker jpeg_read_header (&m_cinfo, FALSE); // read the file parameters if (m_raw) m_coeffs = jpeg_read_coefficients (&m_cinfo); else jpeg_start_decompress (&m_cinfo); // start working m_next_scanline = 0; // next scanline we'll read m_spec = ImageSpec (m_cinfo.output_width, m_cinfo.output_height, m_cinfo.output_components, TypeDesc::UINT8); // Assume JPEG is in sRGB unless the Exif or XMP tags say otherwise. m_spec.linearity = ImageSpec::sRGB; for (jpeg_saved_marker_ptr m = m_cinfo.marker_list; m; m = m->next) { if (m->marker == (JPEG_APP0+1) && ! strcmp ((const char *)m->data, "Exif")) decode_exif ((unsigned char *)m->data, m->data_length, m_spec); else if (m->marker == (JPEG_APP0+1) && ! strcmp ((const char *)m->data, "http://ns.adobe.com/xap/1.0/")) { #ifdef DEBUG std::cerr << "Found APP1 XMP! length " << m->data_length << "\n"; #endif std::string xml ((const char *)m->data, m->data_length); OpenImageIO::decode_xmp (xml, m_spec); } else if (m->marker == (JPEG_APP0+13) && ! strcmp ((const char *)m->data, "Photoshop 3.0")) jpeg_decode_iptc ((unsigned char *)m->data); else if (m->marker == JPEG_COM) { if (! m_spec.find_attribute ("ImageDescription", TypeDesc::STRING)) m_spec.attribute ("ImageDescription", std::string ((const char *)m->data)); } } newspec = m_spec; return true; } bool JpgInput::read_native_scanline (int y, int z, void *data) { if (m_raw) return false; if (y < 0 || y >= (int)m_cinfo.output_height) // out of range scanline return false; if (m_next_scanline > y) { // User is trying to read an earlier scanline than the one we're // up to. Easy fix: close the file and re-open. ImageSpec dummyspec; int subimage = current_subimage(); if (! close () || ! open (m_filename, dummyspec) || ! seek_subimage (subimage, dummyspec)) return false; // Somehow, the re-open failed assert (m_next_scanline == 0 && current_subimage() == subimage); } while (m_next_scanline <= y) { // Keep reading until we're read the scanline we really need jpeg_read_scanlines (&m_cinfo, (JSAMPLE **)&data, 1); // read one scanline ++m_next_scanline; } return true; } bool JpgInput::close () { if (m_fd != NULL) { // N.B. don't call finish_decompress if we never read anything if (m_next_scanline > 0) { // But if we've only read some scanlines, read the rest to avoid // errors std::vector<char> buf (spec().scanline_bytes()); char *data = &buf[0]; while (m_next_scanline < spec().height) { jpeg_read_scanlines (&m_cinfo, (JSAMPLE **)&data, 1); ++m_next_scanline; } } if (m_next_scanline > 0 || m_raw) jpeg_finish_decompress (&m_cinfo); jpeg_destroy_decompress (&m_cinfo); fclose (m_fd); m_fd = NULL; } init (); // Reset to initial state return true; } void JpgInput::jpeg_decode_iptc (const unsigned char *buf) { // APP13 blob doesn't have to be IPTC info. Look for the IPTC marker, // which is the string "Photoshop 3.0" followed by a null character. if (strcmp ((const char *)buf, "Photoshop 3.0")) return; buf += strlen("Photoshop 3.0") + 1; // Next are the 4 bytes "8BIM" if (strncmp ((const char *)buf, "8BIM", 4)) return; buf += 4; // Next two bytes are the segment type, in big endian. // We expect 1028 to indicate IPTC data block. if (((buf[0] << 8) + buf[1]) != 1028) return; buf += 2; // Next are 4 bytes of 0 padding, just skip it. buf += 4; // Next is 2 byte (big endian) giving the size of the segment int segmentsize = (buf[0] << 8) + buf[1]; buf += 2; OpenImageIO::decode_iptc_iim (buf, segmentsize, m_spec); } OIIO_PLUGIN_NAMESPACE_END <|endoftext|>
<commit_before>// Time: O(|V|+|E|) = O(26 + 26^2) = O(1) // Space: O(|E|) = O(26^2) = O(1) class Solution { public: // Construct the graph. void findEdges(const string &word1, const string &word2, unordered_map<char, vector<char>> *ancestors) { int len = min(word1.length(), word2.length()); for (int i = 0; i < len; ++i) { if (word1[i] != word2[i]) { (*ancestors)[word2[i]].emplace_back(word1[i]); break; } } } // Topological sort, return whether there is a cycle. bool topSortDFS(const char& root, const char& node, unordered_map<char, vector<char>> *ancestors, unordered_map<char, char> *visited, string *result) { if (visited->emplace(make_pair(node, root)).second) { for (auto& ancestor: (*ancestors)[node]) { if (topSortDFS(root, ancestor, ancestors, visited, result)) { return true; } } result->push_back(node); return false; } else if ((*visited)[node] == root) { // Visited from the same root in the DFS path. // So it is cyclic. return true; } } string alienOrder(vector<string>& words) { // Find ancestors of each node by DFS unordered_set<char> nodes; unordered_map<char, vector<char>> ancestors; for (int i = 0; i < words.size(); ++i) { for (char c : words[i]) { nodes.emplace(c); } if (i > 0) { findEdges(words[i - 1], words[i], &ancestors); } } // Output topological order by DFS string result; unordered_map<char, char> visited; for (auto& node : nodes) { if (topSortDFS(node, node, &ancestors, &visited, &result)) { return ""; } } return result; } }; // Adjacency matrix method. class Solution2 { public: void findEdges(const string &word1, const string &word2, vector<vector<bool>> *graph) { int len = min(word1.length(), word2.length()); for (int i = 0; i < len; ++i) { if (word1[i] != word2[i]) { (*graph)[word1[i] - 'a'][word2[i] - 'a'] = true; break; } } } // Construct the graph. void findDependency(const vector<string>& words, vector<vector<bool>> *graph) { for (const auto& c : words[0]) { (*graph)[c - 'a'][c - 'a'] = true; } for (int i = 1; i < words.size(); ++i) { for (const auto& c : words[i]) { (*graph)[c - 'a'] [c - 'a'] = true; } findEdges(words[i - 1], words[i], graph); } } // Topological sort, return whether there is a cycle. bool topSortDFS(string *result, vector<bool> *visited, vector<vector<bool>> *graph, const int root) { if ((*visited)[root]) { result->clear(); return true; } (*visited)[root] = true; for (int i = 0; i < 26; ++i) { if (i != root && (*graph)[root][i]) { if (topSortDFS(result, visited, graph, i)) { return true; } } } (*graph)[root][root] = false; result->push_back(root + 'a'); return false; } void findOrder(vector<vector<bool>> *graph, string *result) { for (int i = 0; i < 26; ++i) { // Find a root node. bool root_node = (*graph)[i][i]; if ((*graph)[i][i]) { for (int j = 0; j < 26; ++j) { if (j != i && (*graph)[j][i]) { root_node = false; break; } } } if (root_node) { string reversed_order = ""; vector<bool> visited(26, false); if (topSortDFS(&reversed_order, &visited, graph, i)) { result->clear(); return; } else { result->append(reversed_order); } } } // If there is any unvisited node, return "". for (int i = 0; i < 26; ++i) { if ((*graph)[i][i]) { result->clear(); return; } } // The order should be reversed. reverse(result->begin(), result->end()); } string alienOrder(vector<string>& words) { string result; vector<vector<bool>> graph(26, vector<bool>(26)); findDependency(words, &graph); findOrder(&graph, &result); return result; } }; <commit_msg>Update alien-dictionary.cpp<commit_after>// Time: O(|V|+|E|) = O(26 + 26^2) = O(1) // Space: O(|E|) = O(26^2) = O(1) class Solution { public: // Construct the graph. void findEdges(const string &word1, const string &word2, unordered_map<char, vector<char>> *ancestors) { int len = min(word1.length(), word2.length()); for (int i = 0; i < len; ++i) { if (word1[i] != word2[i]) { (*ancestors)[word2[i]].emplace_back(word1[i]); break; } } } // Topological sort, return whether there is a cycle. bool topSortDFS(const char& root, const char& node, unordered_map<char, vector<char>> *ancestors, unordered_map<char, char> *visited, string *result) { if (visited->emplace(make_pair(node, root)).second) { for (auto& ancestor: (*ancestors)[node]) { if (topSortDFS(root, ancestor, ancestors, visited, result)) { return true; } } result->push_back(node); } else if ((*visited)[node] == root) { // Visited from the same root in the DFS path. // So it is cyclic. return true; } return false; } string alienOrder(vector<string>& words) { // Find ancestors of each node by DFS unordered_set<char> nodes; unordered_map<char, vector<char>> ancestors; for (int i = 0; i < words.size(); ++i) { for (char c : words[i]) { nodes.emplace(c); } if (i > 0) { findEdges(words[i - 1], words[i], &ancestors); } } // Output topological order by DFS string result; unordered_map<char, char> visited; for (auto& node : nodes) { if (topSortDFS(node, node, &ancestors, &visited, &result)) { return ""; } } return result; } }; // Adjacency matrix method. class Solution2 { public: void findEdges(const string &word1, const string &word2, vector<vector<bool>> *graph) { int len = min(word1.length(), word2.length()); for (int i = 0; i < len; ++i) { if (word1[i] != word2[i]) { (*graph)[word1[i] - 'a'][word2[i] - 'a'] = true; break; } } } // Construct the graph. void findDependency(const vector<string>& words, vector<vector<bool>> *graph) { for (const auto& c : words[0]) { (*graph)[c - 'a'][c - 'a'] = true; } for (int i = 1; i < words.size(); ++i) { for (const auto& c : words[i]) { (*graph)[c - 'a'] [c - 'a'] = true; } findEdges(words[i - 1], words[i], graph); } } // Topological sort, return whether there is a cycle. bool topSortDFS(string *result, vector<bool> *visited, vector<vector<bool>> *graph, const int root) { if ((*visited)[root]) { result->clear(); return true; } (*visited)[root] = true; for (int i = 0; i < 26; ++i) { if (i != root && (*graph)[root][i]) { if (topSortDFS(result, visited, graph, i)) { return true; } } } (*graph)[root][root] = false; result->push_back(root + 'a'); return false; } void findOrder(vector<vector<bool>> *graph, string *result) { for (int i = 0; i < 26; ++i) { // Find a root node. bool root_node = (*graph)[i][i]; if ((*graph)[i][i]) { for (int j = 0; j < 26; ++j) { if (j != i && (*graph)[j][i]) { root_node = false; break; } } } if (root_node) { string reversed_order = ""; vector<bool> visited(26, false); if (topSortDFS(&reversed_order, &visited, graph, i)) { result->clear(); return; } else { result->append(reversed_order); } } } // If there is any unvisited node, return "". for (int i = 0; i < 26; ++i) { if ((*graph)[i][i]) { result->clear(); return; } } // The order should be reversed. reverse(result->begin(), result->end()); } string alienOrder(vector<string>& words) { string result; vector<vector<bool>> graph(26, vector<bool>(26)); findDependency(words, &graph); findOrder(&graph, &result); return result; } }; <|endoftext|>
<commit_before><commit_msg>added<commit_after><|endoftext|>
<commit_before>#include "powerup.hpp" int Powerup::vertex_type( Vertex& v ) { int num_neighbors = map->getNumActors(); for ( int i = 0; i < num_neighbors; i++ ) { int a, b; map->getActorPosition( i, a, b ); Vertex temp( a, b ); if( temp == v ) { return map->getActorType( i ); } } return 0; } Powerup::Powerup( int type ): Actor( type ) {} Powerup* Powerup::duplicate() { return new Powerup( getType() ); } const char* Powerup::getActorId() { return "simplehero"; } const char* Powerup::getNetId() { return "hammesa"; } bool Powerup::visited( const Vertex& v ) const { return v_set.find( v ) != v_set.end(); } int& Powerup::dist( const Vertex& v) { return distances[v]; } int Powerup::selectNeighbor( GraphMap* map, int cur_x, int cur_y ) { this->map = map; v_set.clear(); rank_nodes( cur_x, cur_y ); return 0; } void Powerup::rank_nodes( int x, int y ) { queue< Vertex > q; q.push( Vertex( x, y ) ); vector< Vertex > enemies; vector< Vertex > eatables; while( !q.empty() && enemies.size() < 5 ) { Vertex popped = q.front(); q.pop(); v_set.insert( popped ); } } <commit_msg>removed dist()<commit_after>#include "powerup.hpp" int Powerup::vertex_type( Vertex& v ) { int num_neighbors = map->getNumActors(); for ( int i = 0; i < num_neighbors; i++ ) { int a, b; map->getActorPosition( i, a, b ); Vertex temp( a, b ); if( temp == v ) { return map->getActorType( i ); } } return 0; } Powerup::Powerup( int type ): Actor( type ) {} Powerup* Powerup::duplicate() { return new Powerup( getType() ); } const char* Powerup::getActorId() { return "simplehero"; } const char* Powerup::getNetId() { return "hammesa"; } bool Powerup::visited( const Vertex& v ) const { return v_set.find( v ) != v_set.end(); } int Powerup::selectNeighbor( GraphMap* map, int cur_x, int cur_y ) { this->map = map; v_set.clear(); rank_nodes( cur_x, cur_y ); return 0; } void Powerup::rank_nodes( int x, int y ) { queue< Vertex > q; Vertex temp( x, y ); q.push( Vertex( x, y ) ); vector< Vertex > enemies; vector< Vertex > eatables; while( !q.empty() && enemies.size() < 5 ) { Vertex popped = q.front(); q.pop(); v_set.insert( popped ); if( vertex_type( popped ) & ACTOR_ENEMY ) { enemies.push_back( popped ); } if( vertex_type( popped ) & ACTOR_EATABLE ) { eatables.push_back( popped ); } int num_neighbors = map->getNumNeighbors( popped.x, popped. y ) for ( int i = 0; i < num_neighbors; i++ ) { int a, b; map->getNeighbor( popped.x, popped.y, i, a, b ); Vertex temp( a, b ); if( ! visited( temp ) ) { q.push( temp ); } } } } <|endoftext|>
<commit_before>#include "MacroLex.h" #include "CmdInputFactor.h" #include <gtest/gtest.h> #include "IncludeHandler.h" #include "JZLogger.h" //cover case: include TEST(MacroLex, macroInclude1){ int argc = 2; char argv0[128] = {0},argv1[128] = {0}; strcpy(argv0,"tester"); strcpy(argv1,"./test/TestSet/macro_include_test_1"); char* argv[2] = {argv0,argv1}; JZSetLoggerLevel(JZ_LOG_TEST); //analyze command line input CmdInputFactor::getInstance()->analyze(argc, argv); //now begin to analyze the files input from command line string toCompileFile = CmdInputFactor::getInstance()->getNextFile(); MacroLex lex; lex.analyzeAFile(toCompileFile); LexRecList recList = lex.getRecList(); ASSERT_GT(recList.size(), 10); } //cover case: include and once TEST(MacroLex, macroInclude2){ int argc = 2; char argv0[128] = {0},argv1[128] = {0}; strcpy(argv0,"tester"); strcpy(argv1,"./test/TestSet/macro_include_test_2"); char* argv[2] = {argv0,argv1}; JZSetLoggerLevel(JZ_LOG_TEST); //analyze command line input CmdInputFactor::getInstance()->analyze(argc, argv); //now begin to analyze the files input from command line string toCompileFile = CmdInputFactor::getInstance()->getNextFile(); MacroLex lex; IncludeHandler::getInstance()->addUserHeaderSearchPath("./test/TestSet"); lex.analyzeAFile(toCompileFile); LexRecList recList = lex.getRecList(); ASSERT_EQ(recList.size(), 3); ASSERT_STREQ("int", recList[0].word.c_str()); ASSERT_STREQ("hello", recList[1].word.c_str()); ASSERT_STREQ(";", recList[2].word.c_str()); } //cover test: can not match a word TEST(MacroLex, unmatch_word_test){ //this is really a strong test, so don't do it for more than one file every time int argc = 2; char argv0[128] = {0},argv1[128] = {0}; strcpy(argv0,"tester"); strcpy(argv1,"./test/TestSet/unmatch_word_test"); char* argv[2] = {argv0,argv1}; //analyze command line input CmdInputFactor::getInstance()->analyze(argc, argv); //now begin to analyze the files input from command line string toCompileFile = CmdInputFactor::getInstance()->getNextFile(); MacroLex lex; uint32 ret = lex.analyzeAFile(toCompileFile); ASSERT_NE(LexBase::eLexReachLineEnd, ret); } <commit_msg>update test<commit_after>#include "MacroLex.h" #include "CmdInputFactor.h" #include <gtest/gtest.h> #include "IncludeHandler.h" #include "JZLogger.h" //cover case: include TEST(MacroLex, macroInclude1){ int argc = 2; char argv0[128] = {0},argv1[128] = {0}; strcpy(argv0,"tester"); strcpy(argv1,"./test/TestSet/macro_include_test_1"); char* argv[2] = {argv0,argv1}; JZSetLoggerLevel(JZ_LOG_TEST); //analyze command line input CmdInputFactor::getInstance()->analyze(argc, argv); //now begin to analyze the files input from command line string toCompileFile = CmdInputFactor::getInstance()->getNextFile(); MacroLex lex; lex.analyzeAFile(toCompileFile); LexRecList recList = lex.getRecList(); // ASSERT_GT(recList.size(), 10); } //cover case: include and once TEST(MacroLex, macroInclude2){ int argc = 2; char argv0[128] = {0},argv1[128] = {0}; strcpy(argv0,"tester"); strcpy(argv1,"./test/TestSet/macro_include_test_2"); char* argv[2] = {argv0,argv1}; JZSetLoggerLevel(JZ_LOG_TEST); //analyze command line input CmdInputFactor::getInstance()->analyze(argc, argv); //now begin to analyze the files input from command line string toCompileFile = CmdInputFactor::getInstance()->getNextFile(); MacroLex lex; IncludeHandler::getInstance()->addUserHeaderSearchPath("./test/TestSet"); lex.analyzeAFile(toCompileFile); LexRecList recList = lex.getRecList(); ASSERT_EQ(recList.size(), 3); ASSERT_STREQ("int", recList[0].word.c_str()); ASSERT_STREQ("hello", recList[1].word.c_str()); ASSERT_STREQ(";", recList[2].word.c_str()); } //cover test: can not match a word TEST(MacroLex, unmatch_word_test){ //this is really a strong test, so don't do it for more than one file every time int argc = 2; char argv0[128] = {0},argv1[128] = {0}; strcpy(argv0,"tester"); strcpy(argv1,"./test/TestSet/unmatch_word_test"); char* argv[2] = {argv0,argv1}; //analyze command line input CmdInputFactor::getInstance()->analyze(argc, argv); //now begin to analyze the files input from command line string toCompileFile = CmdInputFactor::getInstance()->getNextFile(); MacroLex lex; uint32 ret = lex.analyzeAFile(toCompileFile); ASSERT_NE(LexBase::eLexReachLineEnd, ret); } <|endoftext|>
<commit_before>#include "WebView.h" namespace CefSharp { namespace Wpf { void WebView::Initialize(String^ address, BrowserSettings^ settings) { if (!CEF::IsInitialized && !CEF::Initialize(gcnew Settings)) { throw gcnew InvalidOperationException("CEF::Initialize() failed"); } Focusable = true; FocusVisualStyle = nullptr; IsTabStop = true; _settings = settings; _browserCore = gcnew BrowserCore(address); _browserCore->PropertyChanged += gcnew PropertyChangedEventHandler(this, &WebView::BrowserCore_PropertyChanged); _scriptCore = new ScriptCore(); _paintDelegate = gcnew ActionHandler(this, &WebView::SetBitmap); ToolTip = _toolTip = gcnew System::Windows::Controls::ToolTip(); _toolTip->StaysOpen = true; _timer = gcnew DispatcherTimer(DispatcherPriority::Render); _timer->Interval = TimeSpan::FromSeconds(0.5); _timer->Tick += gcnew EventHandler(this, &WebView::Timer_Tick); } void WebView::SetCursor(SafeFileHandle^ handle) { Cursor = CursorInteropHelper::Create(handle); } void WebView::BrowserCore_PropertyChanged(Object^ sender, PropertyChangedEventArgs^ e) { if (e->PropertyName == "TooltipText") { _timer->Stop(); if (String::IsNullOrEmpty(_browserCore->TooltipText)) { Dispatcher->BeginInvoke(DispatcherPriority::Render, gcnew Action<String^>(this, &WebView::SetTooltipText), nullptr); } else { _timer->Start(); } } } void WebView::Timer_Tick(Object^ sender, EventArgs^ e) { _timer->Stop(); SetTooltipText(_browserCore->TooltipText); } IntPtr WebView::SourceHook(IntPtr hWnd, int message, IntPtr wParam, IntPtr lParam, bool% handled) { handled = false; switch(message) { case WM_KEYDOWN: case WM_KEYUP: case WM_SYSKEYDOWN: case WM_SYSKEYUP: case WM_CHAR: case WM_SYSCHAR: case WM_IME_CHAR: if (!IsFocused) { break; } CefBrowser::KeyType type; if (message == WM_CHAR) type = KT_CHAR; else if (message == WM_KEYDOWN || message == WM_SYSKEYDOWN) type = KT_KEYDOWN; else if (message == WM_KEYUP || message == WM_SYSKEYUP) type = KT_KEYUP; bool sysChar = message == WM_SYSKEYDOWN || message == WM_SYSKEYUP || message == WM_SYSCHAR; bool imeChar = message == WM_IME_CHAR; _clientAdapter->GetCefBrowser()->SendKeyEvent(type, wParam.ToInt32(), lParam.ToInt32(), sysChar, imeChar); handled = true; } return IntPtr::Zero; } void WebView::SetBitmap() { InteropBitmap^ bitmap = _ibitmap; if(bitmap == nullptr) { _image->Source = nullptr; GC::Collect(1); int stride = _width * PixelFormats::Bgr32.BitsPerPixel / 8; bitmap = (InteropBitmap^)Interop::Imaging::CreateBitmapSourceFromMemorySection( (IntPtr)_fileMappingHandle, _width, _height, PixelFormats::Bgr32, stride, 0); _image->Source = bitmap; _ibitmap = bitmap; } bitmap->Invalidate(); } void WebView::OnPreviewKey(KeyEventArgs^ e) { if (e->Key == Key::Tab || e->Key >= Key::Left && e->Key <= Key::Down) { CefBrowser::KeyType type = e->IsDown ? KT_KEYDOWN : KT_KEYUP; int key = KeyInterop::VirtualKeyFromKey(e->Key); _clientAdapter->GetCefBrowser()->SendKeyEvent(type, key, 0, false, false); e->Handled = true; } } void WebView::OnMouseButton(MouseButtonEventArgs^ e) { Point point = e->GetPosition(this); CefBrowser::MouseButtonType type; if (e->ChangedButton == MouseButton::Left) type = CefBrowser::MouseButtonType::MBT_LEFT; else if (e->ChangedButton == MouseButton::Middle) type = CefBrowser::MouseButtonType::MBT_MIDDLE; else type = CefBrowser::MouseButtonType::MBT_RIGHT; bool mouseUp = e->ButtonState == MouseButtonState::Released; _clientAdapter->GetCefBrowser()->SendMouseClickEvent((int)point.X, (int)point.Y, type, mouseUp, e->ClickCount); } Size WebView::ArrangeOverride(Size size) { if(_clientAdapter->GetIsInitialized()) { _clientAdapter->GetCefBrowser()->SetSize(PET_VIEW, (int)size.Width, (int)size.Height); } else { Dispatcher->BeginInvoke(DispatcherPriority::Loaded, gcnew ActionHandler(this, &WebView::InvalidateArrange)); } return ContentControl::ArrangeOverride(size); } void WebView::OnGotFocus(RoutedEventArgs^ e) { _clientAdapter->GetCefBrowser()->SendFocusEvent(true); ContentControl::OnGotFocus(e); } void WebView::OnLostFocus(RoutedEventArgs^ e) { _clientAdapter->GetCefBrowser()->SendFocusEvent(false); ContentControl::OnLostFocus(e); } void WebView::OnPreviewKeyDown(KeyEventArgs^ e) { OnPreviewKey(e); } void WebView::OnPreviewKeyUp(KeyEventArgs^ e) { OnPreviewKey(e); } void WebView::OnMouseMove(MouseEventArgs^ e) { Point point = e->GetPosition(this); _clientAdapter->GetCefBrowser()->SendMouseMoveEvent((int)point.X, (int)point.Y, false); } void WebView::OnMouseWheel(MouseWheelEventArgs^ e) { Point point = e->GetPosition(this); _clientAdapter->GetCefBrowser()->SendMouseWheelEvent((int)point.X, (int)point.Y, e->Delta); } void WebView::OnMouseDown(MouseButtonEventArgs^ e) { Focus(); OnMouseButton(e); Mouse::Capture(this); } void WebView::OnMouseUp(MouseButtonEventArgs^ e) { OnMouseButton(e); Mouse::Capture(nullptr); } void WebView::OnMouseLeave(MouseEventArgs^ e) { _clientAdapter->GetCefBrowser()->SendMouseMoveEvent(0, 0, true); } void WebView::OnInitialized() { _browserCore->OnInitialized(); } void WebView::Load(String^ url) { _browserCore->CheckBrowserInitialization(); _browserCore->OnLoad(); _clientAdapter->GetCefBrowser()->GetMainFrame()->LoadURL(toNative(url)); } void WebView::Stop() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->StopLoad(); } void WebView::Back() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GoBack(); } void WebView::Forward() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GoForward(); } void WebView::Reload() { Reload(false); } void WebView::Reload(bool ignoreCache) { _browserCore->CheckBrowserInitialization(); if (ignoreCache) { _clientAdapter->GetCefBrowser()->ReloadIgnoreCache(); } else { _clientAdapter->GetCefBrowser()->Reload(); } } void WebView::ClearHistory() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->ClearHistory(); } void WebView::ShowDevTools() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->ShowDevTools(); } void WebView::CloseDevTools() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->CloseDevTools(); } void WebView::Undo() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GetMainFrame()->Undo(); } void WebView::Redo() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GetMainFrame()->Redo(); } void WebView::Cut() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GetMainFrame()->Cut(); } void WebView::Copy() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GetMainFrame()->Copy(); } void WebView::Paste() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GetMainFrame()->Paste(); } void WebView::Delete() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GetMainFrame()->Delete(); } void WebView::SelectAll() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GetMainFrame()->SelectAll(); } void WebView::Print() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GetMainFrame()->Print(); } void WebView::ExecuteScript(String^ script) { _browserCore->CheckBrowserInitialization(); CefRefPtr<CefBrowser> browser = _clientAdapter->GetCefBrowser(); CefRefPtr<CefFrame> frame = browser->GetMainFrame(); _scriptCore->Execute(frame, toNative(script)); } Object^ WebView::EvaluateScript(String^ script) { return EvaluateScript(script, TimeSpan::MaxValue); } Object^ WebView::EvaluateScript(String^ script, TimeSpan timeout) { _browserCore->CheckBrowserInitialization(); CefRefPtr<CefBrowser> browser = _clientAdapter->GetCefBrowser(); CefRefPtr<CefFrame> frame = browser->GetMainFrame(); return _scriptCore->Evaluate(frame, toNative(script), timeout.TotalMilliseconds); } void WebView::SetNavState(bool isLoading, bool canGoBack, bool canGoForward) { _browserCore->SetNavState(isLoading, canGoBack, canGoForward); } void WebView::OnConsoleMessage(String^ message, String^ source, int line) { ConsoleMessage(this, gcnew ConsoleMessageEventArgs(message, source, line)); } void WebView::OnFrameLoadStart() { _browserCore->OnFrameLoadStart(); } void WebView::OnFrameLoadEnd() { _browserCore->OnFrameLoadEnd(); } void WebView::OnTakeFocus(bool next) { FocusNavigationDirection direction = next ? FocusNavigationDirection::Next : FocusNavigationDirection::Previous; TraversalRequest^ request = gcnew TraversalRequest(direction); Dispatcher->BeginInvoke(DispatcherPriority::Input, gcnew MoveFocusHandler(this, &WebView::MoveFocus), request); } void WebView::OnApplyTemplate() { ContentControl::OnApplyTemplate(); _clientAdapter = new RenderClientAdapter(this); Visual^ parent = (Visual^)VisualTreeHelper::GetParent(this); HwndSource^ source = (HwndSource^)PresentationSource::FromVisual(parent); HWND hwnd = static_cast<HWND>(source->Handle.ToPointer()); CefWindowInfo window; window.SetAsOffScreen(hwnd); CefRefPtr<RenderClientAdapter> ptr = _clientAdapter.get(); CefString url = toNative(_browserCore->Address); CefBrowser::CreateBrowser(window, static_cast<CefRefPtr<CefClient>>(ptr), url, *_settings->_browserSettings); source->AddHook(gcnew Interop::HwndSourceHook(this, &WebView::SourceHook)); _image = (Image^)GetTemplateChild("PART_Image"); Content = _image = gcnew Image(); _image->Stretch = Stretch::None; _image->HorizontalAlignment = ::HorizontalAlignment::Left; _image->VerticalAlignment = ::VerticalAlignment::Top; } void WebView::SetCursor(CefCursorHandle cursor) { SafeFileHandle^ handle = gcnew SafeFileHandle((IntPtr)cursor, false); Dispatcher->BeginInvoke(DispatcherPriority::Render, gcnew Action<SafeFileHandle^>(this, &WebView::SetCursor), handle); } void WebView::SetTooltipText(String^ text) { if (String::IsNullOrEmpty(text)) { _toolTip->IsOpen = false; } else { _toolTip->Content = text; _toolTip->IsOpen = true; } } void WebView::SetBuffer(int width, int height, const void* buffer) { if (!_backBufferHandle || _width != width || _height != height) { _ibitmap = nullptr; if (_backBufferHandle) { UnmapViewOfFile(_backBufferHandle); _backBufferHandle = NULL; } if (_fileMappingHandle) { CloseHandle(_fileMappingHandle); _fileMappingHandle = NULL; } int pixels = width * height; int bytes = pixels * PixelFormats::Bgr32.BitsPerPixel / 8; _fileMappingHandle = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, bytes, NULL); if(!_fileMappingHandle) { return; } _backBufferHandle = MapViewOfFile(_fileMappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, bytes); if(!_backBufferHandle) { return; } _width = width; _height = height; } int stride = width * PixelFormats::Bgr32.BitsPerPixel / 8; CopyMemory(_backBufferHandle, (void*) buffer, height * stride); if(!Dispatcher->HasShutdownStarted) { Dispatcher->BeginInvoke(DispatcherPriority::Render, _paintDelegate); } } }}<commit_msg>Wpf.WebView: set/unsent ToolTip property to prevent stale tooltips from appearing at incorrect locations<commit_after>#include "WebView.h" namespace CefSharp { namespace Wpf { void WebView::Initialize(String^ address, BrowserSettings^ settings) { if (!CEF::IsInitialized && !CEF::Initialize(gcnew Settings)) { throw gcnew InvalidOperationException("CEF::Initialize() failed"); } Focusable = true; FocusVisualStyle = nullptr; IsTabStop = true; _settings = settings; _browserCore = gcnew BrowserCore(address); _browserCore->PropertyChanged += gcnew PropertyChangedEventHandler(this, &WebView::BrowserCore_PropertyChanged); _scriptCore = new ScriptCore(); _paintDelegate = gcnew ActionHandler(this, &WebView::SetBitmap); ToolTip = _toolTip = gcnew System::Windows::Controls::ToolTip(); _toolTip->StaysOpen = true; _timer = gcnew DispatcherTimer(DispatcherPriority::Render); _timer->Interval = TimeSpan::FromSeconds(0.5); _timer->Tick += gcnew EventHandler(this, &WebView::Timer_Tick); } void WebView::SetCursor(SafeFileHandle^ handle) { Cursor = CursorInteropHelper::Create(handle); } void WebView::BrowserCore_PropertyChanged(Object^ sender, PropertyChangedEventArgs^ e) { if (e->PropertyName == "TooltipText") { _timer->Stop(); if (String::IsNullOrEmpty(_browserCore->TooltipText)) { Dispatcher->BeginInvoke(DispatcherPriority::Render, gcnew Action<String^>(this, &WebView::SetTooltipText), nullptr); } else { _timer->Start(); } } } void WebView::Timer_Tick(Object^ sender, EventArgs^ e) { _timer->Stop(); SetTooltipText(_browserCore->TooltipText); } IntPtr WebView::SourceHook(IntPtr hWnd, int message, IntPtr wParam, IntPtr lParam, bool% handled) { handled = false; switch(message) { case WM_KEYDOWN: case WM_KEYUP: case WM_SYSKEYDOWN: case WM_SYSKEYUP: case WM_CHAR: case WM_SYSCHAR: case WM_IME_CHAR: if (!IsFocused) { break; } CefBrowser::KeyType type; if (message == WM_CHAR) type = KT_CHAR; else if (message == WM_KEYDOWN || message == WM_SYSKEYDOWN) type = KT_KEYDOWN; else if (message == WM_KEYUP || message == WM_SYSKEYUP) type = KT_KEYUP; bool sysChar = message == WM_SYSKEYDOWN || message == WM_SYSKEYUP || message == WM_SYSCHAR; bool imeChar = message == WM_IME_CHAR; _clientAdapter->GetCefBrowser()->SendKeyEvent(type, wParam.ToInt32(), lParam.ToInt32(), sysChar, imeChar); handled = true; } return IntPtr::Zero; } void WebView::SetBitmap() { InteropBitmap^ bitmap = _ibitmap; if(bitmap == nullptr) { _image->Source = nullptr; GC::Collect(1); int stride = _width * PixelFormats::Bgr32.BitsPerPixel / 8; bitmap = (InteropBitmap^)Interop::Imaging::CreateBitmapSourceFromMemorySection( (IntPtr)_fileMappingHandle, _width, _height, PixelFormats::Bgr32, stride, 0); _image->Source = bitmap; _ibitmap = bitmap; } bitmap->Invalidate(); } void WebView::OnPreviewKey(KeyEventArgs^ e) { if (e->Key == Key::Tab || e->Key >= Key::Left && e->Key <= Key::Down) { CefBrowser::KeyType type = e->IsDown ? KT_KEYDOWN : KT_KEYUP; int key = KeyInterop::VirtualKeyFromKey(e->Key); _clientAdapter->GetCefBrowser()->SendKeyEvent(type, key, 0, false, false); e->Handled = true; } } void WebView::OnMouseButton(MouseButtonEventArgs^ e) { Point point = e->GetPosition(this); CefBrowser::MouseButtonType type; if (e->ChangedButton == MouseButton::Left) type = CefBrowser::MouseButtonType::MBT_LEFT; else if (e->ChangedButton == MouseButton::Middle) type = CefBrowser::MouseButtonType::MBT_MIDDLE; else type = CefBrowser::MouseButtonType::MBT_RIGHT; bool mouseUp = e->ButtonState == MouseButtonState::Released; _clientAdapter->GetCefBrowser()->SendMouseClickEvent((int)point.X, (int)point.Y, type, mouseUp, e->ClickCount); } Size WebView::ArrangeOverride(Size size) { if(_clientAdapter->GetIsInitialized()) { _clientAdapter->GetCefBrowser()->SetSize(PET_VIEW, (int)size.Width, (int)size.Height); } else { Dispatcher->BeginInvoke(DispatcherPriority::Loaded, gcnew ActionHandler(this, &WebView::InvalidateArrange)); } return ContentControl::ArrangeOverride(size); } void WebView::OnGotFocus(RoutedEventArgs^ e) { _clientAdapter->GetCefBrowser()->SendFocusEvent(true); ContentControl::OnGotFocus(e); } void WebView::OnLostFocus(RoutedEventArgs^ e) { _clientAdapter->GetCefBrowser()->SendFocusEvent(false); ContentControl::OnLostFocus(e); } void WebView::OnPreviewKeyDown(KeyEventArgs^ e) { OnPreviewKey(e); } void WebView::OnPreviewKeyUp(KeyEventArgs^ e) { OnPreviewKey(e); } void WebView::OnMouseMove(MouseEventArgs^ e) { Point point = e->GetPosition(this); _clientAdapter->GetCefBrowser()->SendMouseMoveEvent((int)point.X, (int)point.Y, false); } void WebView::OnMouseWheel(MouseWheelEventArgs^ e) { Point point = e->GetPosition(this); _clientAdapter->GetCefBrowser()->SendMouseWheelEvent((int)point.X, (int)point.Y, e->Delta); } void WebView::OnMouseDown(MouseButtonEventArgs^ e) { Focus(); OnMouseButton(e); Mouse::Capture(this); } void WebView::OnMouseUp(MouseButtonEventArgs^ e) { OnMouseButton(e); Mouse::Capture(nullptr); } void WebView::OnMouseLeave(MouseEventArgs^ e) { _clientAdapter->GetCefBrowser()->SendMouseMoveEvent(0, 0, true); } void WebView::OnInitialized() { _browserCore->OnInitialized(); } void WebView::Load(String^ url) { _browserCore->CheckBrowserInitialization(); _browserCore->OnLoad(); _clientAdapter->GetCefBrowser()->GetMainFrame()->LoadURL(toNative(url)); } void WebView::Stop() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->StopLoad(); } void WebView::Back() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GoBack(); } void WebView::Forward() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GoForward(); } void WebView::Reload() { Reload(false); } void WebView::Reload(bool ignoreCache) { _browserCore->CheckBrowserInitialization(); if (ignoreCache) { _clientAdapter->GetCefBrowser()->ReloadIgnoreCache(); } else { _clientAdapter->GetCefBrowser()->Reload(); } } void WebView::ClearHistory() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->ClearHistory(); } void WebView::ShowDevTools() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->ShowDevTools(); } void WebView::CloseDevTools() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->CloseDevTools(); } void WebView::Undo() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GetMainFrame()->Undo(); } void WebView::Redo() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GetMainFrame()->Redo(); } void WebView::Cut() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GetMainFrame()->Cut(); } void WebView::Copy() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GetMainFrame()->Copy(); } void WebView::Paste() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GetMainFrame()->Paste(); } void WebView::Delete() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GetMainFrame()->Delete(); } void WebView::SelectAll() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GetMainFrame()->SelectAll(); } void WebView::Print() { _browserCore->CheckBrowserInitialization(); _clientAdapter->GetCefBrowser()->GetMainFrame()->Print(); } void WebView::ExecuteScript(String^ script) { _browserCore->CheckBrowserInitialization(); CefRefPtr<CefBrowser> browser = _clientAdapter->GetCefBrowser(); CefRefPtr<CefFrame> frame = browser->GetMainFrame(); _scriptCore->Execute(frame, toNative(script)); } Object^ WebView::EvaluateScript(String^ script) { return EvaluateScript(script, TimeSpan::MaxValue); } Object^ WebView::EvaluateScript(String^ script, TimeSpan timeout) { _browserCore->CheckBrowserInitialization(); CefRefPtr<CefBrowser> browser = _clientAdapter->GetCefBrowser(); CefRefPtr<CefFrame> frame = browser->GetMainFrame(); return _scriptCore->Evaluate(frame, toNative(script), timeout.TotalMilliseconds); } void WebView::SetNavState(bool isLoading, bool canGoBack, bool canGoForward) { _browserCore->SetNavState(isLoading, canGoBack, canGoForward); } void WebView::OnConsoleMessage(String^ message, String^ source, int line) { ConsoleMessage(this, gcnew ConsoleMessageEventArgs(message, source, line)); } void WebView::OnFrameLoadStart() { _browserCore->OnFrameLoadStart(); } void WebView::OnFrameLoadEnd() { _browserCore->OnFrameLoadEnd(); } void WebView::OnTakeFocus(bool next) { FocusNavigationDirection direction = next ? FocusNavigationDirection::Next : FocusNavigationDirection::Previous; TraversalRequest^ request = gcnew TraversalRequest(direction); Dispatcher->BeginInvoke(DispatcherPriority::Input, gcnew MoveFocusHandler(this, &WebView::MoveFocus), request); } void WebView::OnApplyTemplate() { ContentControl::OnApplyTemplate(); _clientAdapter = new RenderClientAdapter(this); Visual^ parent = (Visual^)VisualTreeHelper::GetParent(this); HwndSource^ source = (HwndSource^)PresentationSource::FromVisual(parent); HWND hwnd = static_cast<HWND>(source->Handle.ToPointer()); CefWindowInfo window; window.SetAsOffScreen(hwnd); CefRefPtr<RenderClientAdapter> ptr = _clientAdapter.get(); CefString url = toNative(_browserCore->Address); CefBrowser::CreateBrowser(window, static_cast<CefRefPtr<CefClient>>(ptr), url, *_settings->_browserSettings); source->AddHook(gcnew Interop::HwndSourceHook(this, &WebView::SourceHook)); _image = (Image^)GetTemplateChild("PART_Image"); Content = _image = gcnew Image(); _image->Stretch = Stretch::None; _image->HorizontalAlignment = ::HorizontalAlignment::Left; _image->VerticalAlignment = ::VerticalAlignment::Top; } void WebView::SetCursor(CefCursorHandle cursor) { SafeFileHandle^ handle = gcnew SafeFileHandle((IntPtr)cursor, false); Dispatcher->BeginInvoke(DispatcherPriority::Render, gcnew Action<SafeFileHandle^>(this, &WebView::SetCursor), handle); } void WebView::SetTooltipText(String^ text) { if (String::IsNullOrEmpty(text)) { ToolTip = nullptr; _toolTip->IsOpen = false; } else { ToolTip = _toolTip; _toolTip->Content = text; _toolTip->IsOpen = true; } } void WebView::SetBuffer(int width, int height, const void* buffer) { if (!_backBufferHandle || _width != width || _height != height) { _ibitmap = nullptr; if (_backBufferHandle) { UnmapViewOfFile(_backBufferHandle); _backBufferHandle = NULL; } if (_fileMappingHandle) { CloseHandle(_fileMappingHandle); _fileMappingHandle = NULL; } int pixels = width * height; int bytes = pixels * PixelFormats::Bgr32.BitsPerPixel / 8; _fileMappingHandle = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, bytes, NULL); if(!_fileMappingHandle) { return; } _backBufferHandle = MapViewOfFile(_fileMappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, bytes); if(!_backBufferHandle) { return; } _width = width; _height = height; } int stride = width * PixelFormats::Bgr32.BitsPerPixel / 8; CopyMemory(_backBufferHandle, (void*) buffer, height * stride); if(!Dispatcher->HasShutdownStarted) { Dispatcher->BeginInvoke(DispatcherPriority::Render, _paintDelegate); } } }}<|endoftext|>
<commit_before>#include "PluginManager.h" #include <filesystem> #include <fstream> #include <sstream> #include <Logger/Logger.h> #include <Tools.h> #include "../Helpers.h" #include "../IBaseApi.h" namespace API { PluginManager::PluginManager() { ArkApi::GetCommands().AddOnTimerCallback(L"PluginManager.DetectPluginChangesTimerCallback", &DetectPluginChangesTimerCallback); } PluginManager& PluginManager::Get() { static PluginManager instance; return instance; } nlohmann::json PluginManager::GetAllPDBConfigs() { namespace fs = std::filesystem; const std::string dir_path = Tools::GetCurrentDir() + "/" + game_api->GetApiName() + "/Plugins"; auto result = nlohmann::json({}); for (const auto& dir_name : fs::directory_iterator(dir_path)) { const auto& path = dir_name.path(); const auto filename = path.filename().stem().generic_string(); try { const auto plugin_pdb_config = ReadPluginPDBConfig(filename); MergePdbConfig(result, plugin_pdb_config); } catch (const std::exception& error) { Log::GetLog()->warn("({}) {}", __FUNCTION__, error.what()); } } return result; } nlohmann::json PluginManager::ReadPluginPDBConfig(const std::string& plugin_name) { namespace fs = std::filesystem; auto plugin_pdb_config = nlohmann::json({}); const std::string dir_path = Tools::GetCurrentDir() + "/" + game_api->GetApiName() + "/Plugins/" + plugin_name; const std::string config_path = dir_path + "/PdbConfig.json"; if (!fs::exists(config_path)) { return plugin_pdb_config; } std::ifstream file{config_path}; if (file.is_open()) { file >> plugin_pdb_config; file.close(); } return plugin_pdb_config; } nlohmann::json PluginManager::ReadSettingsConfig() { nlohmann::json config = nlohmann::json::object({}); const std::string config_path = Tools::GetCurrentDir() + "/config.json"; std::ifstream file{config_path}; if (!file.is_open()) { return config; } file >> config; file.close(); return config; } void PluginManager::LoadAllPlugins() { namespace fs = std::filesystem; const std::string dir_path = Tools::GetCurrentDir() + "/" + game_api->GetApiName() + "/Plugins"; for (const auto& dir_name : fs::directory_iterator(dir_path)) { const auto& path = dir_name.path(); if (!is_directory(path)) { continue; } const auto filename = path.filename().stem().generic_string(); const std::string dir_file_path = Tools::GetCurrentDir() + "/" + game_api->GetApiName() + "/Plugins/" + filename; const std::string full_dll_path = dir_file_path + "/" + filename + ".dll"; const std::string new_full_dll_path = dir_file_path + "/" + filename + ".dll.ArkApi"; try { // Loads the new .dll.ArkApi if it exists on startup as well if (fs::exists(new_full_dll_path)) { copy_file(new_full_dll_path, full_dll_path, fs::copy_options::overwrite_existing); fs::remove(new_full_dll_path); } std::stringstream stream; std::shared_ptr<Plugin>& plugin = LoadPlugin(filename); stream << "Loaded plugin " << (plugin->full_name.empty() ? plugin->name : plugin->full_name) << " V" << plugin->version << " (" << plugin->description << ")"; Log::GetLog()->info(stream.str()); } catch (const std::exception& error) { Log::GetLog()->warn("({}) {}", __FUNCTION__, error.what()); } } CheckPluginsDependencies(); // Set auto plugins reloading auto settings = ReadSettingsConfig(); enable_plugin_reload_ = settings["settings"].value("AutomaticPluginReloading", false); if (enable_plugin_reload_) { reload_sleep_seconds_ = settings["settings"].value("AutomaticPluginReloadSeconds", 5); save_world_before_reload_ = settings["settings"].value("SaveWorldBeforePluginReload", true); } Log::GetLog()->info("Loaded all plugins\n"); } std::shared_ptr<Plugin>& PluginManager::LoadPlugin(const std::string& plugin_name) noexcept(false) { namespace fs = std::filesystem; const std::string dir_path = Tools::GetCurrentDir() + "/" + game_api->GetApiName() + "/Plugins/" + plugin_name; const std::string full_dll_path = dir_path + "/" + plugin_name + ".dll"; if (!fs::exists(full_dll_path)) { throw std::runtime_error("Plugin " + plugin_name + " does not exist"); } if (IsPluginLoaded(plugin_name)) { throw std::runtime_error("Plugin " + plugin_name + " was already loaded"); } auto plugin_info = ReadPluginInfo(plugin_name); // Check version const auto required_version = static_cast<float>(plugin_info["MinApiVersion"]); if (required_version != .0f && game_api->GetVersion() < required_version) { throw std::runtime_error("Plugin " + plugin_name + " requires newer API version!"); } HINSTANCE h_module = LoadLibraryA(full_dll_path.c_str()); if (h_module == nullptr) { throw std::runtime_error( "Failed to load plugin - " + plugin_name + "\nError code: " + std::to_string(GetLastError())); } // Calls Plugin_Init (if found) after loading DLL // Note: DllMain callbacks during LoadLibrary is load-locked so we cannot do things like WaitForMultipleObjects on threads using pfnPluginInit = void(__fastcall*)(); const auto pfn_init = reinterpret_cast<pfnPluginInit>(GetProcAddress(h_module, "Plugin_Init")); if (pfn_init != nullptr) { pfn_init(); } return loaded_plugins_.emplace_back(std::make_shared<Plugin>(h_module, plugin_name, plugin_info["FullName"], plugin_info["Description"], plugin_info["Version"], plugin_info["MinApiVersion"], plugin_info["Dependencies"])); } void PluginManager::UnloadPlugin(const std::string& plugin_name) noexcept(false) { namespace fs = std::filesystem; const auto iter = FindPlugin(plugin_name); if (iter == loaded_plugins_.end()) { throw std::runtime_error("Plugin " + plugin_name + " is not loaded"); } const std::string dir_path = Tools::GetCurrentDir() + "/" + game_api->GetApiName() + "/Plugins/" + plugin_name; const std::string full_dll_path = dir_path + "/" + plugin_name + ".dll"; if (!fs::exists(full_dll_path.c_str())) { throw std::runtime_error("Plugin " + plugin_name + " does not exist"); } // Calls Plugin_Unload (if found) just before unloading DLL to let DLL gracefully clean up // Note: DllMain callbacks during FreeLibrary is load-locked so we cannot do things like WaitForMultipleObjects on threads using pfnPluginUnload = void(__fastcall*)(); const auto pfn_unload = reinterpret_cast<pfnPluginUnload>(GetProcAddress((*iter)->h_module, "Plugin_Unload")); if (pfn_unload != nullptr) { pfn_unload(); } const BOOL result = FreeLibrary((*iter)->h_module); if (result == 0) { throw std::runtime_error( "Failed to unload plugin - " + plugin_name + "\nError code: " + std::to_string(GetLastError())); } loaded_plugins_.erase(remove(loaded_plugins_.begin(), loaded_plugins_.end(), *iter), loaded_plugins_.end()); } nlohmann::json PluginManager::ReadPluginInfo(const std::string& plugin_name) { nlohmann::json plugin_info_result({}); nlohmann::json plugin_info({}); const std::string dir_path = Tools::GetCurrentDir() + "/" + game_api->GetApiName() + "/Plugins/" + plugin_name; const std::string config_path = dir_path + "/PluginInfo.json"; std::ifstream file{config_path}; if (file.is_open()) { file >> plugin_info; file.close(); } try { plugin_info_result["FullName"] = plugin_info.value("FullName", ""); plugin_info_result["Description"] = plugin_info.value("Description", "No description"); plugin_info_result["Version"] = plugin_info.value("Version", 1.00f); plugin_info_result["MinApiVersion"] = plugin_info.value("MinApiVersion", .0f); plugin_info_result["Dependencies"] = plugin_info.value("Dependencies", std::vector<std::string>{}); } catch (const std::exception& error) { Log::GetLog()->warn("({}) {}", __FUNCTION__, error.what()); } return plugin_info_result; } void PluginManager::CheckPluginsDependencies() { for (const auto& plugin : loaded_plugins_) { if (plugin->dependencies.empty()) { continue; } for (const std::string& dependency : plugin->dependencies) { if (!IsPluginLoaded(dependency)) { Log::GetLog()->error("Plugin {} is missing! {} might not work correctly", dependency, plugin->name); } } } } std::vector<std::shared_ptr<Plugin>>::const_iterator PluginManager::FindPlugin(const std::string& plugin_name) { const auto iter = std::find_if(loaded_plugins_.begin(), loaded_plugins_.end(), [plugin_name](const std::shared_ptr<Plugin>& plugin) -> bool { return plugin->name == plugin_name; }); return iter; } bool PluginManager::IsPluginLoaded(const std::string& plugin_name) { return FindPlugin(plugin_name) != loaded_plugins_.end(); } void PluginManager::DetectPluginChangesTimerCallback() { auto& pluginManager = Get(); const time_t now = time(nullptr); if (now < pluginManager.next_reload_check_) { return; } pluginManager.next_reload_check_ = now + pluginManager.reload_sleep_seconds_; pluginManager.DetectPluginChanges(); } void PluginManager::DetectPluginChanges() { namespace fs = std::filesystem; // Prevents saving world multiple times if multiple plugins are queued to be reloaded bool save_world = save_world_before_reload_; for (const auto& dir_name : fs::directory_iterator( Tools::GetCurrentDir() + "/" + game_api->GetApiName() + "/Plugins")) { const auto& path = dir_name.path(); if (!is_directory(path)) { continue; } const auto filename = path.filename().stem().generic_string(); const std::string plugin_folder = path.generic_string() + "/"; const std::string plugin_file_path = plugin_folder + filename + ".dll"; const std::string new_plugin_file_path = plugin_folder + filename + ".dll.ArkApi"; if (fs::exists(new_plugin_file_path) && FindPlugin(filename) != loaded_plugins_.end()) { // Save the world in case the unload/load procedure causes crash if (save_world) { //Log::GetLog()->info("Saving world before reloading plugins ..."); //ArkApi::GetApiUtils().GetShooterGameMode()->SaveWorld(); //Log::GetLog()->info("World saved."); save_world = false; // do not save again if multiple plugins are reloaded in this loop } try { UnloadPlugin(filename); copy_file(new_plugin_file_path, plugin_file_path, fs::copy_options::overwrite_existing); fs::remove(new_plugin_file_path); LoadPlugin(filename); } catch (const std::exception& error) { Log::GetLog()->warn("({}) {}", __FUNCTION__, error.what()); continue; } Log::GetLog()->info("Reloaded plugin - {}", filename); } } } } // namespace API<commit_msg>Fixed automatic plugin reload config reading<commit_after>#include "PluginManager.h" #include <filesystem> #include <fstream> #include <sstream> #include <Logger/Logger.h> #include <Tools.h> #include "../Helpers.h" #include "../IBaseApi.h" namespace API { PluginManager::PluginManager() { ArkApi::GetCommands().AddOnTimerCallback(L"PluginManager.DetectPluginChangesTimerCallback", &DetectPluginChangesTimerCallback); } PluginManager& PluginManager::Get() { static PluginManager instance; return instance; } nlohmann::json PluginManager::GetAllPDBConfigs() { namespace fs = std::filesystem; const std::string dir_path = Tools::GetCurrentDir() + "/" + game_api->GetApiName() + "/Plugins"; auto result = nlohmann::json({}); for (const auto& dir_name : fs::directory_iterator(dir_path)) { const auto& path = dir_name.path(); const auto filename = path.filename().stem().generic_string(); try { const auto plugin_pdb_config = ReadPluginPDBConfig(filename); MergePdbConfig(result, plugin_pdb_config); } catch (const std::exception& error) { Log::GetLog()->warn("({}) {}", __FUNCTION__, error.what()); } } return result; } nlohmann::json PluginManager::ReadPluginPDBConfig(const std::string& plugin_name) { namespace fs = std::filesystem; auto plugin_pdb_config = nlohmann::json({}); const std::string dir_path = Tools::GetCurrentDir() + "/" + game_api->GetApiName() + "/Plugins/" + plugin_name; const std::string config_path = dir_path + "/PdbConfig.json"; if (!fs::exists(config_path)) { return plugin_pdb_config; } std::ifstream file{config_path}; if (file.is_open()) { file >> plugin_pdb_config; file.close(); } return plugin_pdb_config; } nlohmann::json PluginManager::ReadSettingsConfig() { nlohmann::json config = nlohmann::json::object({}); const std::string config_path = Tools::GetCurrentDir() + "/config.json"; std::ifstream file{config_path}; if (!file.is_open()) { return config; } file >> config; file.close(); return config; } void PluginManager::LoadAllPlugins() { namespace fs = std::filesystem; const std::string dir_path = Tools::GetCurrentDir() + "/" + game_api->GetApiName() + "/Plugins"; for (const auto& dir_name : fs::directory_iterator(dir_path)) { const auto& path = dir_name.path(); if (!is_directory(path)) { continue; } const auto filename = path.filename().stem().generic_string(); const std::string dir_file_path = Tools::GetCurrentDir() + "/" + game_api->GetApiName() + "/Plugins/" + filename; const std::string full_dll_path = dir_file_path + "/" + filename + ".dll"; const std::string new_full_dll_path = dir_file_path + "/" + filename + ".dll.ArkApi"; try { // Loads the new .dll.ArkApi if it exists on startup as well if (fs::exists(new_full_dll_path)) { copy_file(new_full_dll_path, full_dll_path, fs::copy_options::overwrite_existing); fs::remove(new_full_dll_path); } std::stringstream stream; std::shared_ptr<Plugin>& plugin = LoadPlugin(filename); stream << "Loaded plugin " << (plugin->full_name.empty() ? plugin->name : plugin->full_name) << " V" << plugin->version << " (" << plugin->description << ")"; Log::GetLog()->info(stream.str()); } catch (const std::exception& error) { Log::GetLog()->warn("({}) {}", __FUNCTION__, error.what()); } } CheckPluginsDependencies(); // Set auto plugins reloading auto settings = ReadSettingsConfig(); enable_plugin_reload_ = settings["settings"].value("AutomaticPluginReloading", false); if (enable_plugin_reload_) { reload_sleep_seconds_ = settings["settings"].value("AutomaticPluginReloadSeconds", 5); save_world_before_reload_ = settings["settings"].value("SaveWorldBeforePluginReload", true); } Log::GetLog()->info("Loaded all plugins\n"); } std::shared_ptr<Plugin>& PluginManager::LoadPlugin(const std::string& plugin_name) noexcept(false) { namespace fs = std::filesystem; const std::string dir_path = Tools::GetCurrentDir() + "/" + game_api->GetApiName() + "/Plugins/" + plugin_name; const std::string full_dll_path = dir_path + "/" + plugin_name + ".dll"; if (!fs::exists(full_dll_path)) { throw std::runtime_error("Plugin " + plugin_name + " does not exist"); } if (IsPluginLoaded(plugin_name)) { throw std::runtime_error("Plugin " + plugin_name + " was already loaded"); } auto plugin_info = ReadPluginInfo(plugin_name); // Check version const auto required_version = static_cast<float>(plugin_info["MinApiVersion"]); if (required_version != .0f && game_api->GetVersion() < required_version) { throw std::runtime_error("Plugin " + plugin_name + " requires newer API version!"); } HINSTANCE h_module = LoadLibraryA(full_dll_path.c_str()); if (h_module == nullptr) { throw std::runtime_error( "Failed to load plugin - " + plugin_name + "\nError code: " + std::to_string(GetLastError())); } // Calls Plugin_Init (if found) after loading DLL // Note: DllMain callbacks during LoadLibrary is load-locked so we cannot do things like WaitForMultipleObjects on threads using pfnPluginInit = void(__fastcall*)(); const auto pfn_init = reinterpret_cast<pfnPluginInit>(GetProcAddress(h_module, "Plugin_Init")); if (pfn_init != nullptr) { pfn_init(); } return loaded_plugins_.emplace_back(std::make_shared<Plugin>(h_module, plugin_name, plugin_info["FullName"], plugin_info["Description"], plugin_info["Version"], plugin_info["MinApiVersion"], plugin_info["Dependencies"])); } void PluginManager::UnloadPlugin(const std::string& plugin_name) noexcept(false) { namespace fs = std::filesystem; const auto iter = FindPlugin(plugin_name); if (iter == loaded_plugins_.end()) { throw std::runtime_error("Plugin " + plugin_name + " is not loaded"); } const std::string dir_path = Tools::GetCurrentDir() + "/" + game_api->GetApiName() + "/Plugins/" + plugin_name; const std::string full_dll_path = dir_path + "/" + plugin_name + ".dll"; if (!fs::exists(full_dll_path.c_str())) { throw std::runtime_error("Plugin " + plugin_name + " does not exist"); } // Calls Plugin_Unload (if found) just before unloading DLL to let DLL gracefully clean up // Note: DllMain callbacks during FreeLibrary is load-locked so we cannot do things like WaitForMultipleObjects on threads using pfnPluginUnload = void(__fastcall*)(); const auto pfn_unload = reinterpret_cast<pfnPluginUnload>(GetProcAddress((*iter)->h_module, "Plugin_Unload")); if (pfn_unload != nullptr) { pfn_unload(); } const BOOL result = FreeLibrary((*iter)->h_module); if (result == 0) { throw std::runtime_error( "Failed to unload plugin - " + plugin_name + "\nError code: " + std::to_string(GetLastError())); } loaded_plugins_.erase(remove(loaded_plugins_.begin(), loaded_plugins_.end(), *iter), loaded_plugins_.end()); } nlohmann::json PluginManager::ReadPluginInfo(const std::string& plugin_name) { nlohmann::json plugin_info_result({}); nlohmann::json plugin_info({}); const std::string dir_path = Tools::GetCurrentDir() + "/" + game_api->GetApiName() + "/Plugins/" + plugin_name; const std::string config_path = dir_path + "/PluginInfo.json"; std::ifstream file{config_path}; if (file.is_open()) { file >> plugin_info; file.close(); } try { plugin_info_result["FullName"] = plugin_info.value("FullName", ""); plugin_info_result["Description"] = plugin_info.value("Description", "No description"); plugin_info_result["Version"] = plugin_info.value("Version", 1.00f); plugin_info_result["MinApiVersion"] = plugin_info.value("MinApiVersion", .0f); plugin_info_result["Dependencies"] = plugin_info.value("Dependencies", std::vector<std::string>{}); } catch (const std::exception& error) { Log::GetLog()->warn("({}) {}", __FUNCTION__, error.what()); } return plugin_info_result; } void PluginManager::CheckPluginsDependencies() { for (const auto& plugin : loaded_plugins_) { if (plugin->dependencies.empty()) { continue; } for (const std::string& dependency : plugin->dependencies) { if (!IsPluginLoaded(dependency)) { Log::GetLog()->error("Plugin {} is missing! {} might not work correctly", dependency, plugin->name); } } } } std::vector<std::shared_ptr<Plugin>>::const_iterator PluginManager::FindPlugin(const std::string& plugin_name) { const auto iter = std::find_if(loaded_plugins_.begin(), loaded_plugins_.end(), [plugin_name](const std::shared_ptr<Plugin>& plugin) -> bool { return plugin->name == plugin_name; }); return iter; } bool PluginManager::IsPluginLoaded(const std::string& plugin_name) { return FindPlugin(plugin_name) != loaded_plugins_.end(); } void PluginManager::DetectPluginChangesTimerCallback() { auto& pluginManager = Get(); const time_t now = time(nullptr); if (now < pluginManager.next_reload_check_ || !pluginManager.enable_plugin_reload_) { return; } pluginManager.next_reload_check_ = now + pluginManager.reload_sleep_seconds_; pluginManager.DetectPluginChanges(); } void PluginManager::DetectPluginChanges() { namespace fs = std::filesystem; // Prevents saving world multiple times if multiple plugins are queued to be reloaded bool save_world = save_world_before_reload_; for (const auto& dir_name : fs::directory_iterator( Tools::GetCurrentDir() + "/" + game_api->GetApiName() + "/Plugins")) { const auto& path = dir_name.path(); if (!is_directory(path)) { continue; } const auto filename = path.filename().stem().generic_string(); const std::string plugin_folder = path.generic_string() + "/"; const std::string plugin_file_path = plugin_folder + filename + ".dll"; const std::string new_plugin_file_path = plugin_folder + filename + ".dll.ArkApi"; if (fs::exists(new_plugin_file_path) && FindPlugin(filename) != loaded_plugins_.end()) { // Save the world in case the unload/load procedure causes crash if (save_world) { //Log::GetLog()->info("Saving world before reloading plugins ..."); //ArkApi::GetApiUtils().GetShooterGameMode()->SaveWorld(); //Log::GetLog()->info("World saved."); save_world = false; // do not save again if multiple plugins are reloaded in this loop } try { UnloadPlugin(filename); copy_file(new_plugin_file_path, plugin_file_path, fs::copy_options::overwrite_existing); fs::remove(new_plugin_file_path); LoadPlugin(filename); } catch (const std::exception& error) { Log::GetLog()->warn("({}) {}", __FUNCTION__, error.what()); continue; } Log::GetLog()->info("Reloaded plugin - {}", filename); } } } } // namespace API<|endoftext|>
<commit_before>#include "catch.hpp" #include <iostream> #include <exception> // std::bad_function_call, std::runtime_error #include <thread> // std::thread, std::this_thread::yield #include <mutex> // std::mutex, std::unique_lock #include <condition_variable> // std::condition_variable #include <functional> // std::function class EventThreader { public: std::condition_variable event_waiter; std::condition_variable calling_waiter; std::unique_lock<std::mutex>* event_lock = nullptr; std::unique_lock<std::mutex>* calling_lock = nullptr; std::mutex mtx; std::mutex allocation_mtx; std::thread event_thread; void switchToCallingThread(); bool require_switch_from_event = false; std::function<void(void)> event_cleanup; std::runtime_error* exception_from_the_event_thread = nullptr; std::function<void (std::function<void (void)>)> event_function; void deallocate(); public: EventThreader(std::function<void (std::function<void (void)>)> func); ~EventThreader(); void switchToEventThread(); void join(); void setEventCleanup(std::function<void(void)>); }; EventThreader::EventThreader(std::function<void (std::function<void (void)>)> func) { allocation_mtx.lock(); calling_lock = new std::unique_lock<std::mutex>(mtx); allocation_mtx.unlock(); event_cleanup = [](){}; // empty function event_function = func; auto event = [&](){ /* mtx force switch to calling - blocked by the mutex */ this->allocation_mtx.lock(); this->event_lock = new std::unique_lock<std::mutex>(this->mtx); this->allocation_mtx.unlock(); this->calling_waiter.notify_one(); this->event_waiter.wait(*(this->event_lock)); std::this_thread::yield(); try { this->event_function([&](){this->switchToCallingThread();}); if (this->require_switch_from_event) { // the event has ended, but not ready to join // rejoin the calling thread after dealing with this exception throw std::runtime_error("switch to event not matched with a switch to calling"); } } catch (const std::runtime_error &e) { /* report the exception to the calling thread */ this->allocation_mtx.lock(); this->exception_from_the_event_thread = new std::runtime_error(e); this->allocation_mtx.unlock(); this->calling_waiter.notify_one(); std::this_thread::yield(); } this->allocation_mtx.lock(); delete this->event_lock; this->event_lock = nullptr; this->allocation_mtx.unlock(); this->event_cleanup(); }; event_thread = std::thread(event); } EventThreader::~EventThreader() { deallocate(); } void EventThreader::deallocate() { allocation_mtx.lock(); if (exception_from_the_event_thread != nullptr) { delete exception_from_the_event_thread; exception_from_the_event_thread = nullptr; } if (calling_lock != nullptr) { delete calling_lock; calling_lock = nullptr; } if (event_lock != nullptr) { delete event_lock; event_lock = nullptr; } allocation_mtx.unlock(); } void EventThreader::switchToCallingThread() { if (!require_switch_from_event) { throw std::runtime_error("switch to calling not matched with a switch to event"); } require_switch_from_event = false; /* switch to calling */ calling_waiter.notify_one(); std::this_thread::yield(); event_waiter.wait(*(event_lock)); std::this_thread::yield(); /* back from calling */ } void EventThreader::switchToEventThread() { } void EventThreader::join() { allocation_mtx.lock(); delete calling_lock; // remove lock on this thread, allow event to run calling_lock = nullptr; allocation_mtx.unlock(); if (event_lock != nullptr) { event_waiter.notify_one(); std::this_thread::yield(); } event_thread.join(); if (exception_from_the_event_thread != nullptr) { /* an exception occured */ std::runtime_error e_copy(exception_from_the_event_thread->what()); allocation_mtx.lock(); delete exception_from_the_event_thread; exception_from_the_event_thread = nullptr; allocation_mtx.unlock(); throw e_copy; } deallocate(); } void EventThreader::setEventCleanup(std::function<void(void)> cleanup) { event_cleanup = cleanup; } TEST_CASE( "EventThreader", "[EventThreader]" ) { std::stringstream ss; SECTION("Finding the error") { /* Example of most basic use */ auto f = [&ss](std::function<void(void)> switchToMainThread){ for(int i = 0; i < 100; i++) { ss << "*"; } switchToMainThread(); for(int i = 0; i < 50; i++) { ss << "*"; } switchToMainThread(); }; EventThreader et(f); // class functions auto switchToEventThread= [&]() { if (et.require_switch_from_event) { throw std::runtime_error("switch to event not matched with a switch to calling"); } et.require_switch_from_event = true; /* switch to event */ et.event_waiter.notify_one(); std::this_thread::yield(); et.calling_waiter.wait(*et.calling_lock); std::this_thread::yield(); /* back from event */ if (et.require_switch_from_event) { /* this exception is thrown if switchToCallingThread() was not used, which means the thread ended */ et.join(); } }; std::function<void (std::function<void (void)>)> func = f; // Start construction std::this_thread::yield(); et.calling_waiter.wait(*(et.calling_lock)); std::this_thread::yield(); // End constuction //EventThreader et(f); switchToEventThread(); for(int i = 0; i < 75; i++) { ss << "$"; } switchToEventThread(); for(int i = 0; i < 25; i++) { ss << "$"; } et.join(); /* Generate what the result should look like */ std::string requirement; for(int i = 0; i < 100; i++) { requirement += "*"; } for(int i = 0; i < 75; i++) { requirement += "$"; } for(int i = 0; i < 50; i++) { requirement += "*"; } for(int i = 0; i < 25; i++) { requirement += "$"; } REQUIRE( requirement == ss.str()); } /* SECTION("Abitrary use") { // Example of most basic use auto f = [&ss](std::function<void(void)> switchToMainThread){ for(int i = 0; i < 100; i++) { ss << "*"; } switchToMainThread(); for(int i = 0; i < 50; i++) { ss << "*"; } switchToMainThread(); }; EventThreader et(f); switchToEventThread(); for(int i = 0; i < 75; i++) { ss << "$"; } switchToEventThread(); for(int i = 0; i < 25; i++) { ss << "$"; } join(); // Generate what the result should look like std::string requirement; for(int i = 0; i < 100; i++) { requirement += "*"; } for(int i = 0; i < 75; i++) { requirement += "$"; } for(int i = 0; i < 50; i++) { requirement += "*"; } for(int i = 0; i < 25; i++) { requirement += "$"; } REQUIRE( requirement == ss.str()); } */ } <commit_msg>remove other reference to f<commit_after>#include "catch.hpp" #include <iostream> #include <exception> // std::bad_function_call, std::runtime_error #include <thread> // std::thread, std::this_thread::yield #include <mutex> // std::mutex, std::unique_lock #include <condition_variable> // std::condition_variable #include <functional> // std::function class EventThreader { public: std::condition_variable event_waiter; std::condition_variable calling_waiter; std::unique_lock<std::mutex>* event_lock = nullptr; std::unique_lock<std::mutex>* calling_lock = nullptr; std::mutex mtx; std::mutex allocation_mtx; std::thread event_thread; void switchToCallingThread(); bool require_switch_from_event = false; std::function<void(void)> event_cleanup; std::runtime_error* exception_from_the_event_thread = nullptr; std::function<void (std::function<void (void)>)> event_function; void deallocate(); public: EventThreader(std::function<void (std::function<void (void)>)> func); ~EventThreader(); void switchToEventThread(); void join(); void setEventCleanup(std::function<void(void)>); }; EventThreader::EventThreader(std::function<void (std::function<void (void)>)> func) { allocation_mtx.lock(); calling_lock = new std::unique_lock<std::mutex>(mtx); allocation_mtx.unlock(); event_cleanup = [](){}; // empty function event_function = func; auto event = [&](){ /* mtx force switch to calling - blocked by the mutex */ this->allocation_mtx.lock(); this->event_lock = new std::unique_lock<std::mutex>(this->mtx); this->allocation_mtx.unlock(); this->calling_waiter.notify_one(); this->event_waiter.wait(*(this->event_lock)); std::this_thread::yield(); try { this->event_function([&](){this->switchToCallingThread();}); if (this->require_switch_from_event) { // the event has ended, but not ready to join // rejoin the calling thread after dealing with this exception throw std::runtime_error("switch to event not matched with a switch to calling"); } } catch (const std::runtime_error &e) { /* report the exception to the calling thread */ this->allocation_mtx.lock(); this->exception_from_the_event_thread = new std::runtime_error(e); this->allocation_mtx.unlock(); this->calling_waiter.notify_one(); std::this_thread::yield(); } this->allocation_mtx.lock(); delete this->event_lock; this->event_lock = nullptr; this->allocation_mtx.unlock(); this->event_cleanup(); }; event_thread = std::thread(event); } EventThreader::~EventThreader() { deallocate(); } void EventThreader::deallocate() { allocation_mtx.lock(); if (exception_from_the_event_thread != nullptr) { delete exception_from_the_event_thread; exception_from_the_event_thread = nullptr; } if (calling_lock != nullptr) { delete calling_lock; calling_lock = nullptr; } if (event_lock != nullptr) { delete event_lock; event_lock = nullptr; } allocation_mtx.unlock(); } void EventThreader::switchToCallingThread() { if (!require_switch_from_event) { throw std::runtime_error("switch to calling not matched with a switch to event"); } require_switch_from_event = false; /* switch to calling */ calling_waiter.notify_one(); std::this_thread::yield(); event_waiter.wait(*(event_lock)); std::this_thread::yield(); /* back from calling */ } void EventThreader::switchToEventThread() { } void EventThreader::join() { allocation_mtx.lock(); delete calling_lock; // remove lock on this thread, allow event to run calling_lock = nullptr; allocation_mtx.unlock(); if (event_lock != nullptr) { event_waiter.notify_one(); std::this_thread::yield(); } event_thread.join(); if (exception_from_the_event_thread != nullptr) { /* an exception occured */ std::runtime_error e_copy(exception_from_the_event_thread->what()); allocation_mtx.lock(); delete exception_from_the_event_thread; exception_from_the_event_thread = nullptr; allocation_mtx.unlock(); throw e_copy; } deallocate(); } void EventThreader::setEventCleanup(std::function<void(void)> cleanup) { event_cleanup = cleanup; } TEST_CASE( "EventThreader", "[EventThreader]" ) { std::stringstream ss; SECTION("Finding the error") { /* Example of most basic use */ auto f = [&ss](std::function<void(void)> switchToMainThread){ for(int i = 0; i < 100; i++) { ss << "*"; } switchToMainThread(); for(int i = 0; i < 50; i++) { ss << "*"; } switchToMainThread(); }; EventThreader et(f); // class functions auto switchToEventThread= [&]() { if (et.require_switch_from_event) { throw std::runtime_error("switch to event not matched with a switch to calling"); } et.require_switch_from_event = true; /* switch to event */ et.event_waiter.notify_one(); std::this_thread::yield(); et.calling_waiter.wait(*et.calling_lock); std::this_thread::yield(); /* back from event */ if (et.require_switch_from_event) { /* this exception is thrown if switchToCallingThread() was not used, which means the thread ended */ et.join(); } }; // Start construction std::this_thread::yield(); et.calling_waiter.wait(*(et.calling_lock)); std::this_thread::yield(); // End constuction //EventThreader et(f); switchToEventThread(); for(int i = 0; i < 75; i++) { ss << "$"; } switchToEventThread(); for(int i = 0; i < 25; i++) { ss << "$"; } et.join(); /* Generate what the result should look like */ std::string requirement; for(int i = 0; i < 100; i++) { requirement += "*"; } for(int i = 0; i < 75; i++) { requirement += "$"; } for(int i = 0; i < 50; i++) { requirement += "*"; } for(int i = 0; i < 25; i++) { requirement += "$"; } REQUIRE( requirement == ss.str()); } /* SECTION("Abitrary use") { // Example of most basic use auto f = [&ss](std::function<void(void)> switchToMainThread){ for(int i = 0; i < 100; i++) { ss << "*"; } switchToMainThread(); for(int i = 0; i < 50; i++) { ss << "*"; } switchToMainThread(); }; EventThreader et(f); switchToEventThread(); for(int i = 0; i < 75; i++) { ss << "$"; } switchToEventThread(); for(int i = 0; i < 25; i++) { ss << "$"; } join(); // Generate what the result should look like std::string requirement; for(int i = 0; i < 100; i++) { requirement += "*"; } for(int i = 0; i < 75; i++) { requirement += "$"; } for(int i = 0; i < 50; i++) { requirement += "*"; } for(int i = 0; i < 25; i++) { requirement += "$"; } REQUIRE( requirement == ss.str()); } */ } <|endoftext|>
<commit_before>#ifndef _options_hpp_INCLUDED #define _options_hpp_INCLUDED /*------------------------------------------------------------------------*/ // The 'check' option has by default '0' in optimized compilation, but for // debugging and testing we want to set it to '1', by default. Setting // 'check' to '1' for instance triggers saving all the original clauses for // checking witnesses and also learned clauses if a solution is provided. #ifndef NDEBUG #define DEBUG 1 #else #define DEBUG 0 #endif /*------------------------------------------------------------------------*/ // Some of the 'OPTION' macros below should only be included if certain // compile time options are enabled. This has the effect, that for instance // if 'LOGGING' is defined, and thus logging code is included, then also the // 'log' option is defined. Otherwise the 'log' option is not included. #ifdef LOGGING #define LOGOPT OPTION #else #define LOGOPT(ARGS...) /**/ #endif #ifdef QUIET #define QUTOPT(ARGS...) /**/ #else #define QUTOPT OPTION #endif /*------------------------------------------------------------------------*/ // In order to add new option, simply add a new line below. #define OPTIONS \ \ /* NAME TYPE, VAL, LO, HI, USAGE */ \ \ OPTION(arena, int, 3, 0, 3, "1=clause,2=var,3=queue") \ OPTION(arenacompact, bool, 1, 0, 1, "keep clauses compact") \ OPTION(arenasort, int, 1, 0, 1, "sort clauses after arenaing") \ OPTION(binary, bool, 1, 0, 1, "use binary proof format") \ OPTION(check, bool,DEBUG, 0, 1, "save & check original CNF") \ OPTION(clim, int, -1, 0,1e9, "conflict limit (-1=none)") \ OPTION(compact, bool, 1, 0, 1, "enable compactification") \ OPTION(compactint, int, 1e3, 1,1e9, "compactification conflic tlimit") \ OPTION(compactlim, double, 0.1, 0, 1, "inactive variable limit") \ OPTION(compactmin, int, 100, 1,1e9, "inactive variable limit") \ OPTION(dlim, int, -1, 0,1e9, "decision limit (-1=none)") \ OPTION(elim, bool, 1, 0, 1, "bounded variable elimination") \ OPTION(elimclslim, int, 1e3, 0,1e9, "ignore clauses of this size") \ OPTION(eliminit, int, 1e3, 0,1e9, "initial conflict limit") \ OPTION(elimint, int, 1e4, 1,1e9, "initial conflict interval") \ OPTION(elimocclim, int, 100, 0,1e9, "one sided occurrence limit") \ OPTION(elimroundsinit, int, 5, 1,1e9, "initial number of rounds") \ OPTION(elimrounds, int, 2, 1,1e9, "usual number of rounds") \ OPTION(emagluefast, double, 3e-2, 0, 1, "alpha fast glue") \ OPTION(emaglueslow, double, 1e-5, 0, 1, "alpha slow glue") \ OPTION(emajump, double, 1e-5, 0, 1, "alpha jump level") \ OPTION(emasize, double, 1e-5, 0, 1, "alpha learned clause size") \ OPTION(decompose, bool, 1, 0, 1, "SCC decompose BIG and ELS") \ OPTION(decomposerounds, int, 1, 1,1e9, "number of decompose rounds") \ OPTION(force, bool, 0, 0, 1, "force to read broken header") \ OPTION(hbr, bool, 1, 0, 1, "learn hyper binary clauses") \ OPTION(hbrsizelim, int, 1e9, 3, 1e9, "max size HBR base clause") \ OPTION(keepglue, int, 3, 1,1e9, "glue kept learned clauses") \ OPTION(keepsize, int, 3, 2,1e9, "size kept learned clauses") \ OPTION(leak, bool, 1, 0, 1, "leak solver memory") \ LOGOPT(log, bool, 0, 0, 1, "enable logging") \ LOGOPT(logsort, bool, 0, 0, 1, "sort logged clauses") \ OPTION(minimize, bool, 1, 0, 1, "minimize learned clauses") \ OPTION(minimizedepth, int, 1e3, 0,1e9, "minimization depth") \ OPTION(phase, int, 1, 0, 1, "initial phase: 0=neg,1=pos") \ OPTION(posize, int, 4, 4,1e9, "size for saving position") \ OPTION(prefetch, bool, 1, 0, 1, "prefetch watches") \ OPTION(probe, bool, 1, 0, 1, "failed literal probing" ) \ OPTION(probeinit, int, 500, 0,1e9, "initial probing interval" ) \ OPTION(probeint, int, 1e4, 1,1e9, "probing interval increment" ) \ OPTION(probereleff, double, 0.02, 0, 1, "relative probing efficiency") \ OPTION(probemaxeff, double, 1e7, 0, 1, "maximum probing efficiency") \ OPTION(probemineff, double, 1e5, 0, 1, "minimum probing efficiency") \ OPTION(profile, int, 2, 0, 4, "profiling level") \ QUTOPT(quiet, bool, 0, 0, 1, "disable all messages") \ OPTION(reduceinc, int, 300, 1,1e6, "reduce limit increment") \ OPTION(reduceinit, int, 2000, 0,1e6, "initial reduce limit") \ OPTION(rephase, bool, 0, 0, 1, "enable rephasing") \ OPTION(rephaseint, int, 1e5, 1,1e9, "rephasing interval") \ OPTION(restart, bool, 1, 0, 1, "enable restarting") \ OPTION(restartint, int, 400, 1,1e9, "restart base interval") \ OPTION(restartmargin, double, 1.1, 0, 10, "restart slow fast margin") \ OPTION(reusetrail, bool, 1, 0, 1, "enable trail reuse") \ OPTION(simplify, bool, 1, 0, 1, "enable simplifier") \ OPTION(strengthen, bool, 1, 0, 1, "strengthen during subsume") \ OPTION(subsume, bool, 1, 0, 1, "enable clause subsumption") \ OPTION(subsumebinlim, int, 1e4, 0,1e9, "watch list length limit") \ OPTION(subsumeclslim, int, 1e3, 0,1e9, "clause length limit") \ OPTION(subsumeinc, int, 1e4, 1,1e9, "interval in conflicts") \ OPTION(subsumeinit, int, 1e4, 0,1e9, "initial subsume limit") \ OPTION(subsumeocclim, int, 100, 0,1e9, "watch list length limit") \ OPTION(transred, bool, 1, 0, 1, "transitive reduction of BIG") \ OPTION(transredreleff,double, 0.10, 0, 1, "relative efficiency") \ OPTION(transredmaxeff,double, 1e7, 0, 1, "maximum efficiency") \ OPTION(transredmineff,double, 1e5, 0, 1, "minimum efficiency") \ QUTOPT(verbose, int, 0, 0, 2, "more verbose messages") \ OPTION(vivify, bool, 1, 0, 1, "vivification") \ OPTION(vivifyreleff, double, 0.03, 0, 1, "relative efficiency") \ OPTION(vivifymaxeff, double, 1e7, 0, 1, "maximum efficiency") \ OPTION(vivifymineff, double, 1e5, 0, 1, "minimum efficiency") \ OPTION(witness, bool, 1, 0, 1, "print witness") \ /*------------------------------------------------------------------------*/ namespace CaDiCaL { class Internal; class Options { Internal * internal; bool set ( int &, const char *, const char *, const int, const int); bool set ( bool &, const char *, const char *, const bool, const bool); bool set (double &, const char *, const char *, const double, const double); const char * match (const char *, const char *); public: // Makes options directly accessible, e.g., for instance declares the // member 'bool Options.restart' here. This will give fast and type save // access to option values (internally). In principle one could make all // options simply 'double' though, but that requires double conversions // during accessing options at run-time and disregards the intended types, // e.g., one would need to allow fractional values for actual integer // or boolean options. Keeping the different types makes the output of // 'print' and 'usage' also more appealing (since correctly typed values // are printed). #define OPTION(N,T,V,L,H,D) \ T N; OPTIONS #undef OPTION Options (Internal *); // This sets the value of an option assuming a 'long' command line // argument form. The argument 'arg' thus should look like // // "--<NAME>=<VAL>", "--<NAME>" or "--no-<NAME>" // // where 'NAME' is one of the option names above. Returns 'true' if the // option was parsed and set correctly. For boolean values we strictly // only allow "true", "false", "0" and "1" as "<VAL>" string. For 'int' // type options we parse "<VAL>" with 'atoi' and force the resulting 'int' // value to the 'LO' and 'HI' range and similarly for 'double' type // options using 'atof'. If the string is not a valid 'int' for 'int' // options or a 'double' value for 'double' options, then the function // returns 'false'. // bool set (const char * arg); // Interface to options using in a certain sense non-type-safe 'double' // values even for 'int' and 'bool'. However, 'double' can hold a 'bool' // as well an 'int' value precisely, e.g., if the result of 'get' is cast // down again by the client. This would only fail for 64 byte 'long', // which we currently do not support as option type. // bool has (const char * name); double get (const char * name); bool set (const char * name, double); void print (); // print current values in command line form static void usage (); // print usage message for all options }; }; #endif <commit_msg>back to sc17 tag<commit_after>#ifndef _options_hpp_INCLUDED #define _options_hpp_INCLUDED /*------------------------------------------------------------------------*/ // The 'check' option has by default '0' in optimized compilation, but for // debugging and testing we want to set it to '1', by default. Setting // 'check' to '1' for instance triggers saving all the original clauses for // checking witnesses and also learned clauses if a solution is provided. #ifndef NDEBUG #define DEBUG 1 #else #define DEBUG 0 #endif /*------------------------------------------------------------------------*/ // Some of the 'OPTION' macros below should only be included if certain // compile time options are enabled. This has the effect, that for instance // if 'LOGGING' is defined, and thus logging code is included, then also the // 'log' option is defined. Otherwise the 'log' option is not included. #ifdef LOGGING #define LOGOPT OPTION #else #define LOGOPT(ARGS...) /**/ #endif #ifdef QUIET #define QUTOPT(ARGS...) /**/ #else #define QUTOPT OPTION #endif /*------------------------------------------------------------------------*/ // In order to add new option, simply add a new line below. #define OPTIONS \ \ /* NAME TYPE, VAL, LO, HI, USAGE */ \ \ OPTION(arena, int, 3, 0, 3, "1=clause,2=var,3=queue") \ OPTION(arenacompact, bool, 1, 0, 1, "keep clauses compact") \ OPTION(arenasort, int, 1, 0, 1, "sort clauses after arenaing") \ OPTION(binary, bool, 1, 0, 1, "use binary proof format") \ OPTION(check, bool,DEBUG, 0, 1, "save & check original CNF") \ OPTION(clim, int, -1, 0,1e9, "conflict limit (-1=none)") \ OPTION(compact, bool, 1, 0, 1, "enable compactification") \ OPTION(compactint, int, 1e3, 1,1e9, "compactification conflic tlimit") \ OPTION(compactlim, double, 0.1, 0, 1, "inactive variable limit") \ OPTION(compactmin, int, 100, 1,1e9, "inactive variable limit") \ OPTION(dlim, int, -1, 0,1e9, "decision limit (-1=none)") \ OPTION(elim, bool, 1, 0, 1, "bounded variable elimination") \ OPTION(elimclslim, int, 1e3, 0,1e9, "ignore clauses of this size") \ OPTION(eliminit, int, 1e3, 0,1e9, "initial conflict limit") \ OPTION(elimint, int, 1e4, 1,1e9, "initial conflict interval") \ OPTION(elimocclim, int, 100, 0,1e9, "one sided occurrence limit") \ OPTION(elimroundsinit, int, 5, 1,1e9, "initial number of rounds") \ OPTION(elimrounds, int, 2, 1,1e9, "usual number of rounds") \ OPTION(emagluefast, double, 3e-2, 0, 1, "alpha fast glue") \ OPTION(emaglueslow, double, 1e-5, 0, 1, "alpha slow glue") \ OPTION(emajump, double, 1e-5, 0, 1, "alpha jump level") \ OPTION(emasize, double, 1e-5, 0, 1, "alpha learned clause size") \ OPTION(decompose, bool, 1, 0, 1, "SCC decompose BIG and ELS") \ OPTION(decomposerounds, int, 1, 1,1e9, "number of decompose rounds") \ OPTION(force, bool, 0, 0, 1, "force to read broken header") \ OPTION(hbr, bool, 1, 0, 1, "learn hyper binary clauses") \ OPTION(hbrsizelim, int, 1e9, 3, 1e9, "max size HBR base clause") \ OPTION(keepglue, int, 3, 1,1e9, "glue kept learned clauses") \ OPTION(keepsize, int, 3, 2,1e9, "size kept learned clauses") \ OPTION(leak, bool, 1, 0, 1, "leak solver memory") \ LOGOPT(log, bool, 0, 0, 1, "enable logging") \ LOGOPT(logsort, bool, 0, 0, 1, "sort logged clauses") \ OPTION(minimize, bool, 1, 0, 1, "minimize learned clauses") \ OPTION(minimizedepth, int, 1e3, 0,1e9, "minimization depth") \ OPTION(phase, int, 1, 0, 1, "initial phase: 0=neg,1=pos") \ OPTION(posize, int, 4, 4,1e9, "size for saving position") \ OPTION(prefetch, bool, 1, 0, 1, "prefetch watches") \ OPTION(probe, bool, 1, 0, 1, "failed literal probing" ) \ OPTION(probeinit, int, 500, 0,1e9, "initial probing interval" ) \ OPTION(probeint, int, 1e4, 1,1e9, "probing interval increment" ) \ OPTION(probereleff, double, 0.02, 0, 1, "relative probing efficiency") \ OPTION(probemaxeff, double, 1e7, 0, 1, "maximum probing efficiency") \ OPTION(probemineff, double, 1e5, 0, 1, "minimum probing efficiency") \ OPTION(profile, int, 2, 0, 4, "profiling level") \ QUTOPT(quiet, bool, 0, 0, 1, "disable all messages") \ OPTION(reduceinc, int, 300, 1,1e6, "reduce limit increment") \ OPTION(reduceinit, int, 2000, 0,1e6, "initial reduce limit") \ OPTION(rephase, bool, 1, 0, 1, "enable rephasing") \ OPTION(rephaseint, int, 1e5, 1,1e9, "rephasing interval") \ OPTION(restart, bool, 1, 0, 1, "enable restarting") \ OPTION(restartint, int, 6, 1,1e9, "restart base interval") \ OPTION(restartmargin, double, 1.1, 0, 10, "restart slow fast margin") \ OPTION(reusetrail, bool, 1, 0, 1, "enable trail reuse") \ OPTION(simplify, bool, 1, 0, 1, "enable simplifier") \ OPTION(strengthen, bool, 1, 0, 1, "strengthen during subsume") \ OPTION(subsume, bool, 1, 0, 1, "enable clause subsumption") \ OPTION(subsumebinlim, int, 1e4, 0,1e9, "watch list length limit") \ OPTION(subsumeclslim, int, 1e3, 0,1e9, "clause length limit") \ OPTION(subsumeinc, int, 1e4, 1,1e9, "interval in conflicts") \ OPTION(subsumeinit, int, 1e4, 0,1e9, "initial subsume limit") \ OPTION(subsumeocclim, int, 100, 0,1e9, "watch list length limit") \ OPTION(transred, bool, 1, 0, 1, "transitive reduction of BIG") \ OPTION(transredreleff,double, 0.10, 0, 1, "relative efficiency") \ OPTION(transredmaxeff,double, 1e7, 0, 1, "maximum efficiency") \ OPTION(transredmineff,double, 1e5, 0, 1, "minimum efficiency") \ QUTOPT(verbose, int, 0, 0, 2, "more verbose messages") \ OPTION(vivify, bool, 1, 0, 1, "vivification") \ OPTION(vivifyreleff, double, 0.03, 0, 1, "relative efficiency") \ OPTION(vivifymaxeff, double, 1e7, 0, 1, "maximum efficiency") \ OPTION(vivifymineff, double, 1e5, 0, 1, "minimum efficiency") \ OPTION(witness, bool, 1, 0, 1, "print witness") \ /*------------------------------------------------------------------------*/ namespace CaDiCaL { class Internal; class Options { Internal * internal; bool set ( int &, const char *, const char *, const int, const int); bool set ( bool &, const char *, const char *, const bool, const bool); bool set (double &, const char *, const char *, const double, const double); const char * match (const char *, const char *); public: // Makes options directly accessible, e.g., for instance declares the // member 'bool Options.restart' here. This will give fast and type save // access to option values (internally). In principle one could make all // options simply 'double' though, but that requires double conversions // during accessing options at run-time and disregards the intended types, // e.g., one would need to allow fractional values for actual integer // or boolean options. Keeping the different types makes the output of // 'print' and 'usage' also more appealing (since correctly typed values // are printed). #define OPTION(N,T,V,L,H,D) \ T N; OPTIONS #undef OPTION Options (Internal *); // This sets the value of an option assuming a 'long' command line // argument form. The argument 'arg' thus should look like // // "--<NAME>=<VAL>", "--<NAME>" or "--no-<NAME>" // // where 'NAME' is one of the option names above. Returns 'true' if the // option was parsed and set correctly. For boolean values we strictly // only allow "true", "false", "0" and "1" as "<VAL>" string. For 'int' // type options we parse "<VAL>" with 'atoi' and force the resulting 'int' // value to the 'LO' and 'HI' range and similarly for 'double' type // options using 'atof'. If the string is not a valid 'int' for 'int' // options or a 'double' value for 'double' options, then the function // returns 'false'. // bool set (const char * arg); // Interface to options using in a certain sense non-type-safe 'double' // values even for 'int' and 'bool'. However, 'double' can hold a 'bool' // as well an 'int' value precisely, e.g., if the result of 'get' is cast // down again by the client. This would only fail for 64 byte 'long', // which we currently do not support as option type. // bool has (const char * name); double get (const char * name); bool set (const char * name, double); void print (); // print current values in command line form static void usage (); // print usage message for all options }; }; #endif <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/controls/tabbed_pane/native_tabbed_pane_win.h" #include <vssym32.h> #include "app/l10n_util_win.h" #include "app/resource_bundle.h" #include "base/logging.h" #include "base/stl_util-inl.h" #include "gfx/canvas.h" #include "gfx/font.h" #include "gfx/native_theme_win.h" #include "views/controls/tabbed_pane/tabbed_pane.h" #include "views/fill_layout.h" #include "views/widget/root_view.h" #include "views/widget/widget_win.h" namespace views { // A background object that paints the tab panel background which may be // rendered by the system visual styles system. class TabBackground : public Background { public: explicit TabBackground() { // TMT_FILLCOLORHINT returns a color value that supposedly // approximates the texture drawn by PaintTabPanelBackground. SkColor tab_page_color = gfx::NativeTheme::instance()->GetThemeColorWithDefault( gfx::NativeTheme::TAB, TABP_BODY, 0, TMT_FILLCOLORHINT, COLOR_3DFACE); SetNativeControlColor(tab_page_color); } virtual ~TabBackground() {} virtual void Paint(gfx::Canvas* canvas, View* view) const { HDC dc = canvas->beginPlatformPaint(); RECT r = {0, 0, view->width(), view->height()}; gfx::NativeTheme::instance()->PaintTabPanelBackground(dc, &r); canvas->endPlatformPaint(); } private: DISALLOW_COPY_AND_ASSIGN(TabBackground); }; //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWin, public: NativeTabbedPaneWin::NativeTabbedPaneWin(TabbedPane* tabbed_pane) : NativeControlWin(), tabbed_pane_(tabbed_pane), content_window_(NULL), selected_index_(-1) { // Associates the actual HWND with the tabbed-pane so the tabbed-pane is // the one considered as having the focus (not the wrapper) when the HWND is // focused directly (with a click for example). set_focus_view(tabbed_pane); } NativeTabbedPaneWin::~NativeTabbedPaneWin() { // We own the tab views, let's delete them. STLDeleteContainerPointers(tab_views_.begin(), tab_views_.end()); } //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWin, NativeTabbedPaneWrapper implementation: void NativeTabbedPaneWin::AddTab(const std::wstring& title, View* contents) { AddTabAtIndex(static_cast<int>(tab_views_.size()), title, contents, true); } void NativeTabbedPaneWin::AddTabAtIndex(int index, const std::wstring& title, View* contents, bool select_if_first_tab) { DCHECK(index <= static_cast<int>(tab_views_.size())); contents->set_parent_owned(false); tab_views_.insert(tab_views_.begin() + index, contents); tab_titles_.insert(tab_titles_.begin() + index, title); if (!contents->background()) contents->set_background(new TabBackground); if (tab_views_.size() == 1 && select_if_first_tab) { // If this is the only tab displayed, make sure the contents is set. selected_index_ = 0; if (content_window_) content_window_->GetRootView()->AddChildView(contents); } // Add native tab only if the native control is alreay created. if (content_window_) { AddNativeTab(index, title, contents); // The newly added tab may have made the contents window smaller. ResizeContents(); } } void NativeTabbedPaneWin::AddNativeTab(int index, const std::wstring &title, views::View* contents) { TCITEM tcitem; tcitem.mask = TCIF_TEXT; // If the locale is RTL, we set the TCIF_RTLREADING so that BiDi text is // rendered properly on the tabs. if (UILayoutIsRightToLeft()) { tcitem.mask |= TCIF_RTLREADING; } tcitem.pszText = const_cast<wchar_t*>(title.c_str()); int result = TabCtrl_InsertItem(native_view(), index, &tcitem); DCHECK(result != -1); } View* NativeTabbedPaneWin::RemoveTabAtIndex(int index) { int tab_count = static_cast<int>(tab_views_.size()); DCHECK(index >= 0 && index < tab_count); if (index < (tab_count - 1)) { // Select the next tab. SelectTabAt(index + 1); } else { // We are the last tab, select the previous one. if (index > 0) { SelectTabAt(index - 1); } else if (content_window_) { // That was the last tab. Remove the contents. content_window_->GetRootView()->RemoveAllChildViews(false); } } TabCtrl_DeleteItem(native_view(), index); // The removed tab may have made the contents window bigger. if (content_window_) ResizeContents(); std::vector<View*>::iterator iter = tab_views_.begin() + index; View* removed_tab = *iter; tab_views_.erase(iter); tab_titles_.erase(tab_titles_.begin() + index); return removed_tab; } void NativeTabbedPaneWin::SelectTabAt(int index) { DCHECK((index >= 0) && (index < static_cast<int>(tab_views_.size()))); if (native_view()) TabCtrl_SetCurSel(native_view(), index); DoSelectTabAt(index, true); } int NativeTabbedPaneWin::GetTabCount() { return TabCtrl_GetItemCount(native_view()); } int NativeTabbedPaneWin::GetSelectedTabIndex() { return TabCtrl_GetCurSel(native_view()); } View* NativeTabbedPaneWin::GetSelectedTab() { if (selected_index_ < 0) return NULL; return tab_views_[selected_index_]; } View* NativeTabbedPaneWin::GetView() { return this; } void NativeTabbedPaneWin::SetFocus() { // Focus the associated HWND. Focus(); } gfx::NativeView NativeTabbedPaneWin::GetTestingHandle() const { return native_view(); } //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWin, NativeControlWin override: void NativeTabbedPaneWin::CreateNativeControl() { // Create the tab control. // // Note that we don't follow the common convention for NativeControl // subclasses and we don't pass the value returned from // NativeControl::GetAdditionalExStyle() as the dwExStyle parameter. Here is // why: on RTL locales, if we pass NativeControl::GetAdditionalExStyle() when // we basically tell Windows to create our HWND with the WS_EX_LAYOUTRTL. If // we do that, then the HWND we create for |content_window_| below will // inherit the WS_EX_LAYOUTRTL property and this will result in the contents // being flipped, which is not what we want (because we handle mirroring in // views without the use of Windows' support for mirroring). Therefore, // we initially create our HWND without the aforementioned property and we // explicitly set this property our child is created. This way, on RTL // locales, our tabs will be nicely rendered from right to left (by virtue of // Windows doing the right thing with the TabbedPane HWND) and each tab // contents will use an RTL layout correctly (by virtue of the mirroring // infrastructure in views doing the right thing with each View we put // in the tab). HWND tab_control = ::CreateWindowEx(0, WC_TABCONTROL, L"", WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE, 0, 0, width(), height(), GetWidget()->GetNativeView(), NULL, NULL, NULL); HFONT font = ResourceBundle::GetSharedInstance(). GetFont(ResourceBundle::BaseFont).hfont(); SendMessage(tab_control, WM_SETFONT, reinterpret_cast<WPARAM>(font), FALSE); // Create the view container which is a child of the TabControl. content_window_ = new WidgetWin(); content_window_->Init(tab_control, gfx::Rect()); // Explicitly setting the WS_EX_LAYOUTRTL property for the HWND (see above // for a thorough explanation regarding why we waited until |content_window_| // if created before we set this property for the tabbed pane's HWND). if (UILayoutIsRightToLeft()) l10n_util::HWNDSetRTLLayout(tab_control); RootView* root_view = content_window_->GetRootView(); root_view->SetLayoutManager(new FillLayout()); DWORD sys_color = ::GetSysColor(COLOR_3DHILIGHT); SkColor color = SkColorSetRGB(GetRValue(sys_color), GetGValue(sys_color), GetBValue(sys_color)); root_view->set_background(Background::CreateSolidBackground(color)); content_window_->SetFocusTraversableParentView(this); NativeControlCreated(tab_control); // Add tabs that are already added if any. if (tab_views_.size() > 0) { InitializeTabs(); if (selected_index_ >= 0) DoSelectTabAt(selected_index_, false); } ResizeContents(); } bool NativeTabbedPaneWin::ProcessMessage(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { if (message == WM_NOTIFY && reinterpret_cast<LPNMHDR>(l_param)->code == TCN_SELCHANGE) { int selected_tab = TabCtrl_GetCurSel(native_view()); DCHECK(selected_tab != -1); DoSelectTabAt(selected_tab, true); return TRUE; } return NativeControlWin::ProcessMessage(message, w_param, l_param, result); } //////////////////////////////////////////////////////////////////////////////// // View override: void NativeTabbedPaneWin::Layout() { NativeControlWin::Layout(); ResizeContents(); } FocusTraversable* NativeTabbedPaneWin::GetFocusTraversable() { return content_window_; } void NativeTabbedPaneWin::ViewHierarchyChanged(bool is_add, View *parent, View *child) { NativeControlWin::ViewHierarchyChanged(is_add, parent, child); if (is_add && (child == this) && content_window_) { // We have been added to a view hierarchy, update the FocusTraversable // parent. content_window_->SetFocusTraversableParent(GetRootView()); } } //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWin, private: void NativeTabbedPaneWin::InitializeTabs() { for (size_t i = 0; i < tab_views_.size(); ++i) { AddNativeTab(i, tab_titles_[i], tab_views_[i]); } } void NativeTabbedPaneWin::DoSelectTabAt(int index, boolean invoke_listener) { selected_index_ = index; if (content_window_) { RootView* content_root = content_window_->GetRootView(); // Clear the focus if the focused view was on the tab. FocusManager* focus_manager = GetFocusManager(); DCHECK(focus_manager); View* focused_view = focus_manager->GetFocusedView(); if (focused_view && content_root->IsParentOf(focused_view)) focus_manager->ClearFocus(); content_root->RemoveAllChildViews(false); content_root->AddChildView(tab_views_[index]); content_root->Layout(); } if (invoke_listener && tabbed_pane_->listener()) tabbed_pane_->listener()->TabSelectedAt(index); } void NativeTabbedPaneWin::ResizeContents() { CRect content_bounds; if (!GetClientRect(native_view(), &content_bounds)) return; TabCtrl_AdjustRect(native_view(), FALSE, &content_bounds); content_window_->MoveWindow(content_bounds.left, content_bounds.top, content_bounds.Width(), content_bounds.Height(), TRUE); } //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWrapper, public: // static NativeTabbedPaneWrapper* NativeTabbedPaneWrapper::CreateNativeWrapper( TabbedPane* tabbed_pane) { return new NativeTabbedPaneWin(tabbed_pane); } } // namespace views <commit_msg>Add style to clip children which reduces flashing when the tab control is resized. The tab control still flashes a little bit but it is only the outer area and not the large content area/child controls. Fixing that probably requires drawing the tab control on our own which is perhaps overkill. BUG=28383 TEST=follow steps given in the bug and resize password manager window, tab should not flicker as much as it did earlier. <commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/controls/tabbed_pane/native_tabbed_pane_win.h" #include <vssym32.h> #include "app/l10n_util_win.h" #include "app/resource_bundle.h" #include "base/logging.h" #include "base/stl_util-inl.h" #include "gfx/canvas.h" #include "gfx/font.h" #include "gfx/native_theme_win.h" #include "views/controls/tabbed_pane/tabbed_pane.h" #include "views/fill_layout.h" #include "views/widget/root_view.h" #include "views/widget/widget_win.h" namespace views { // A background object that paints the tab panel background which may be // rendered by the system visual styles system. class TabBackground : public Background { public: explicit TabBackground() { // TMT_FILLCOLORHINT returns a color value that supposedly // approximates the texture drawn by PaintTabPanelBackground. SkColor tab_page_color = gfx::NativeTheme::instance()->GetThemeColorWithDefault( gfx::NativeTheme::TAB, TABP_BODY, 0, TMT_FILLCOLORHINT, COLOR_3DFACE); SetNativeControlColor(tab_page_color); } virtual ~TabBackground() {} virtual void Paint(gfx::Canvas* canvas, View* view) const { HDC dc = canvas->beginPlatformPaint(); RECT r = {0, 0, view->width(), view->height()}; gfx::NativeTheme::instance()->PaintTabPanelBackground(dc, &r); canvas->endPlatformPaint(); } private: DISALLOW_COPY_AND_ASSIGN(TabBackground); }; //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWin, public: NativeTabbedPaneWin::NativeTabbedPaneWin(TabbedPane* tabbed_pane) : NativeControlWin(), tabbed_pane_(tabbed_pane), content_window_(NULL), selected_index_(-1) { // Associates the actual HWND with the tabbed-pane so the tabbed-pane is // the one considered as having the focus (not the wrapper) when the HWND is // focused directly (with a click for example). set_focus_view(tabbed_pane); } NativeTabbedPaneWin::~NativeTabbedPaneWin() { // We own the tab views, let's delete them. STLDeleteContainerPointers(tab_views_.begin(), tab_views_.end()); } //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWin, NativeTabbedPaneWrapper implementation: void NativeTabbedPaneWin::AddTab(const std::wstring& title, View* contents) { AddTabAtIndex(static_cast<int>(tab_views_.size()), title, contents, true); } void NativeTabbedPaneWin::AddTabAtIndex(int index, const std::wstring& title, View* contents, bool select_if_first_tab) { DCHECK(index <= static_cast<int>(tab_views_.size())); contents->set_parent_owned(false); tab_views_.insert(tab_views_.begin() + index, contents); tab_titles_.insert(tab_titles_.begin() + index, title); if (!contents->background()) contents->set_background(new TabBackground); if (tab_views_.size() == 1 && select_if_first_tab) { // If this is the only tab displayed, make sure the contents is set. selected_index_ = 0; if (content_window_) content_window_->GetRootView()->AddChildView(contents); } // Add native tab only if the native control is alreay created. if (content_window_) { AddNativeTab(index, title, contents); // The newly added tab may have made the contents window smaller. ResizeContents(); } } void NativeTabbedPaneWin::AddNativeTab(int index, const std::wstring &title, views::View* contents) { TCITEM tcitem; tcitem.mask = TCIF_TEXT; // If the locale is RTL, we set the TCIF_RTLREADING so that BiDi text is // rendered properly on the tabs. if (UILayoutIsRightToLeft()) { tcitem.mask |= TCIF_RTLREADING; } tcitem.pszText = const_cast<wchar_t*>(title.c_str()); int result = TabCtrl_InsertItem(native_view(), index, &tcitem); DCHECK(result != -1); } View* NativeTabbedPaneWin::RemoveTabAtIndex(int index) { int tab_count = static_cast<int>(tab_views_.size()); DCHECK(index >= 0 && index < tab_count); if (index < (tab_count - 1)) { // Select the next tab. SelectTabAt(index + 1); } else { // We are the last tab, select the previous one. if (index > 0) { SelectTabAt(index - 1); } else if (content_window_) { // That was the last tab. Remove the contents. content_window_->GetRootView()->RemoveAllChildViews(false); } } TabCtrl_DeleteItem(native_view(), index); // The removed tab may have made the contents window bigger. if (content_window_) ResizeContents(); std::vector<View*>::iterator iter = tab_views_.begin() + index; View* removed_tab = *iter; tab_views_.erase(iter); tab_titles_.erase(tab_titles_.begin() + index); return removed_tab; } void NativeTabbedPaneWin::SelectTabAt(int index) { DCHECK((index >= 0) && (index < static_cast<int>(tab_views_.size()))); if (native_view()) TabCtrl_SetCurSel(native_view(), index); DoSelectTabAt(index, true); } int NativeTabbedPaneWin::GetTabCount() { return TabCtrl_GetItemCount(native_view()); } int NativeTabbedPaneWin::GetSelectedTabIndex() { return TabCtrl_GetCurSel(native_view()); } View* NativeTabbedPaneWin::GetSelectedTab() { if (selected_index_ < 0) return NULL; return tab_views_[selected_index_]; } View* NativeTabbedPaneWin::GetView() { return this; } void NativeTabbedPaneWin::SetFocus() { // Focus the associated HWND. Focus(); } gfx::NativeView NativeTabbedPaneWin::GetTestingHandle() const { return native_view(); } //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWin, NativeControlWin override: void NativeTabbedPaneWin::CreateNativeControl() { // Create the tab control. // // Note that we don't follow the common convention for NativeControl // subclasses and we don't pass the value returned from // NativeControl::GetAdditionalExStyle() as the dwExStyle parameter. Here is // why: on RTL locales, if we pass NativeControl::GetAdditionalExStyle() when // we basically tell Windows to create our HWND with the WS_EX_LAYOUTRTL. If // we do that, then the HWND we create for |content_window_| below will // inherit the WS_EX_LAYOUTRTL property and this will result in the contents // being flipped, which is not what we want (because we handle mirroring in // views without the use of Windows' support for mirroring). Therefore, // we initially create our HWND without the aforementioned property and we // explicitly set this property our child is created. This way, on RTL // locales, our tabs will be nicely rendered from right to left (by virtue of // Windows doing the right thing with the TabbedPane HWND) and each tab // contents will use an RTL layout correctly (by virtue of the mirroring // infrastructure in views doing the right thing with each View we put // in the tab). DWORD style = WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE | WS_CLIPCHILDREN; HWND tab_control = ::CreateWindowEx(0, WC_TABCONTROL, L"", style, 0, 0, width(), height(), GetWidget()->GetNativeView(), NULL, NULL, NULL); HFONT font = ResourceBundle::GetSharedInstance(). GetFont(ResourceBundle::BaseFont).hfont(); SendMessage(tab_control, WM_SETFONT, reinterpret_cast<WPARAM>(font), FALSE); // Create the view container which is a child of the TabControl. content_window_ = new WidgetWin(); content_window_->Init(tab_control, gfx::Rect()); // Explicitly setting the WS_EX_LAYOUTRTL property for the HWND (see above // for a thorough explanation regarding why we waited until |content_window_| // if created before we set this property for the tabbed pane's HWND). if (UILayoutIsRightToLeft()) l10n_util::HWNDSetRTLLayout(tab_control); RootView* root_view = content_window_->GetRootView(); root_view->SetLayoutManager(new FillLayout()); DWORD sys_color = ::GetSysColor(COLOR_3DHILIGHT); SkColor color = SkColorSetRGB(GetRValue(sys_color), GetGValue(sys_color), GetBValue(sys_color)); root_view->set_background(Background::CreateSolidBackground(color)); content_window_->SetFocusTraversableParentView(this); NativeControlCreated(tab_control); // Add tabs that are already added if any. if (tab_views_.size() > 0) { InitializeTabs(); if (selected_index_ >= 0) DoSelectTabAt(selected_index_, false); } ResizeContents(); } bool NativeTabbedPaneWin::ProcessMessage(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { if (message == WM_NOTIFY && reinterpret_cast<LPNMHDR>(l_param)->code == TCN_SELCHANGE) { int selected_tab = TabCtrl_GetCurSel(native_view()); DCHECK(selected_tab != -1); DoSelectTabAt(selected_tab, true); return TRUE; } return NativeControlWin::ProcessMessage(message, w_param, l_param, result); } //////////////////////////////////////////////////////////////////////////////// // View override: void NativeTabbedPaneWin::Layout() { NativeControlWin::Layout(); ResizeContents(); } FocusTraversable* NativeTabbedPaneWin::GetFocusTraversable() { return content_window_; } void NativeTabbedPaneWin::ViewHierarchyChanged(bool is_add, View *parent, View *child) { NativeControlWin::ViewHierarchyChanged(is_add, parent, child); if (is_add && (child == this) && content_window_) { // We have been added to a view hierarchy, update the FocusTraversable // parent. content_window_->SetFocusTraversableParent(GetRootView()); } } //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWin, private: void NativeTabbedPaneWin::InitializeTabs() { for (size_t i = 0; i < tab_views_.size(); ++i) { AddNativeTab(i, tab_titles_[i], tab_views_[i]); } } void NativeTabbedPaneWin::DoSelectTabAt(int index, boolean invoke_listener) { selected_index_ = index; if (content_window_) { RootView* content_root = content_window_->GetRootView(); // Clear the focus if the focused view was on the tab. FocusManager* focus_manager = GetFocusManager(); DCHECK(focus_manager); View* focused_view = focus_manager->GetFocusedView(); if (focused_view && content_root->IsParentOf(focused_view)) focus_manager->ClearFocus(); content_root->RemoveAllChildViews(false); content_root->AddChildView(tab_views_[index]); content_root->Layout(); } if (invoke_listener && tabbed_pane_->listener()) tabbed_pane_->listener()->TabSelectedAt(index); } void NativeTabbedPaneWin::ResizeContents() { CRect content_bounds; if (!GetClientRect(native_view(), &content_bounds)) return; TabCtrl_AdjustRect(native_view(), FALSE, &content_bounds); content_window_->MoveWindow(content_bounds.left, content_bounds.top, content_bounds.Width(), content_bounds.Height(), TRUE); } //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWrapper, public: // static NativeTabbedPaneWrapper* NativeTabbedPaneWrapper::CreateNativeWrapper( TabbedPane* tabbed_pane) { return new NativeTabbedPaneWin(tabbed_pane); } } // namespace views <|endoftext|>
<commit_before>/**************************************************************************/ /** ** C H I L D ** ** CHANNEL-HILLSLOPE INTEGRATED LANDSCAPE DEVELOPMENT MODEL ** ** OXFORD VERSION 2003 ** ** Designed and created by Gregory E. Tucker, Stephen T. Lancaster, ** Nicole M. Gasparini, and Rafael L. Bras ** ** ** @file childmain.cpp ** @brief This file contains the main() routine that handles ** top-level initialization and implements the main ** time-loop. ** ** NOTE: This source code is copyrighted material. It is distributed ** solely for noncommercial research and educational purposes ** only. Use in whole or in part for commercial purposes without ** a written license from the copyright holder(s) is expressly ** prohibited. Copies of this source code or any of its components ** may not be transferred to any other individuals or organizations ** without written consent. Copyright (C) Massachusetts Institute ** of Technology, 1997-2000. All rights reserved. ** ** For information regarding this program, please contact Greg Tucker at: ** ** School of Geography and the Environment ** University of Oxford ** Mansfield Road ** Oxford OX1 3TB United Kingdom ** ** $Id: childmain.cpp,v 1.26 2004-06-16 13:37:24 childcvs Exp $ */ /**************************************************************************/ /* set traps for some floating point exceptions on Linux */ #include "trapfpe.h" #include "Inclusions.h" #include "tFloodplain/tFloodplain.h" #include "tStratGrid/tStratGrid.h" #include "tEolian/tEolian.h" #include "tOption/tOption.h" Predicates predicate; int main( int argc, char **argv ) { bool optDetachLim, // Option for detachment-limited erosion only optFloodplainDep, // Option for floodplain (overbank) deposition optLoessDep, // Option for eolian deposition optVegetation, // Option for dynamic vegetation cover optMeander, // Option for stream meandering optDiffuseDepo, // Option for deposition / no deposition by diff'n optStratGrid; // Option to enable stratigraphy grid tVegetation *vegetation(0); // -> vegetation object tFloodplain *floodplain(0); // -> floodplain object tStratGrid *stratGrid(0); // -> Stratigraphy Grid object tEolian *loess(0); // -> eolian deposition object tStreamMeander *strmMeander(0); // -> stream meander object /****************** INITIALIZATION *************************************\ ** ALGORITHM ** Get command-line arguments (name of input file + any other opts) ** Set silent_mode flag ** Open main input file ** Create and initialize objects for... ** Mesh ** Output files ** Storm ** Stream network ** Erosion ** Uplift (or baselevel change) ** Run timer ** Write output for initial state ** Get options for erosion type, meandering, etc. \**********************************************************************/ // Check command-line arguments tOption option( argc, argv ); // Say hello option.version(); // Open main input file tInputFile inputFile( option.inputFile ); // Create a random number generator for the simulation itself tRand rand( inputFile ); // Create and initialize objects: std::cout << "Creating mesh...\n"; tMesh<tLNode> mesh( inputFile, option.checkMeshConsistency ); std::cout << "Creating output files...\n"; tLOutput<tLNode> output( &mesh, inputFile, &rand ); tStorm storm( inputFile, &rand ); std::cout << "Creating stream network...\n"; tStreamNet strmNet( mesh, storm, inputFile ); tErosion erosion( &mesh, inputFile ); tUplift uplift( inputFile ); // Get various options optDetachLim = inputFile.ReadBool( "OPTDETACHLIM" ); optDiffuseDepo = inputFile.ReadBool( "OPTDIFFDEP" ); optVegetation = inputFile.ReadBool( "OPTVEG" ); optFloodplainDep = inputFile.ReadBool( "OPTFLOODPLAIN" ); optLoessDep = inputFile.ReadBool( "OPTLOESSDEP" ); optMeander = inputFile.ReadBool( "OPTMEANDER" ); optStratGrid = inputFile.ReadBool( "OPTSTRATGRID" ,false); // If applicable, create Vegetation object if( optVegetation ) vegetation = new tVegetation( &mesh, inputFile ); // If applicable, create floodplain object if( optFloodplainDep ) floodplain = new tFloodplain( inputFile, &mesh ); // If applicable, create eolian deposition object if( optLoessDep ) loess = new tEolian( inputFile ); // If applicable, create Stream Meander object if( optMeander ) strmMeander = new tStreamMeander( strmNet, mesh, inputFile, &rand ); // If applicable, create Stratigraphy Grid object // and pass it to output if( optStratGrid ) { if (!optFloodplainDep) ReportFatalError("OPTFLOODPLAIN must be enabled."); stratGrid = new tStratGrid (inputFile, &mesh); output.SetStratGrid( stratGrid, &strmNet ); } std::cout << "Writing data for time zero...\n"; tRunTimer time( inputFile, !option.silent_mode ); output.WriteOutput( 0. ); std::cout << "Initialization done.\n"; // Option for time series output (IN PROGRESS) /* switch( optTSOutput ){ case 1: // Volume output each N years. if( time.CheckTSOutputTime() ) output.WriteVolOutput(); break; case 2: // Volume and vegetation cover output each N years. std::cout << "here" << std::endl; if( time.CheckTSOutputTime() ){ std::cout << "there" << std::endl; output.WriteVolVegOutput();} break; case 3: // All data at each storm. output.WriteTSOutput(); break; case 0: // No additional timeseries output. break; default: // Invalid option. ReportFatalError( "The input file contains an invalid value for OptTSOutput." ); } */ /**************** MAIN LOOP ******************************************\ ** ALGORITHM ** Generate storm ** Do storm... ** Update network (flow directions, drainage area, runoff) ** Water erosion/deposition (vertical) ** Meandering (if applicable) ** Floodplain deposition (if applicable) ** Do interstorm... ** Hillslope transport ** Vegetation (if applicable) ** Exposure history ** Mesh densification (if applicable) ** Eolian (loess) deposition (if applicable) ** Uplift (or baselevel change) **********************************************************************/ while( !time.IsFinished() ) { std::cout << " " << std::endl; time.ReportTimeStatus(); // Do storm... storm.GenerateStorm( time.getCurrentTime(), strmNet.getInfilt(), strmNet.getSoilStore() ); /*std::cout << "Storm: " << storm.getRainrate() << " " << storm.getStormDuration() << " " << storm.interstormDur() << std::endl;*/ strmNet.UpdateNet( time.getCurrentTime(), storm ); if(0) //DEBUG std::cout << "UpdateNet::Done.." << std::endl; // Link tLNodes to StratNodes, adjust elevation StratNode to surrounding tLNodes if( optStratGrid ) stratGrid->UpdateStratGrid(tStratGrid::k0, time.getCurrentTime()); if( optDetachLim ) erosion.ErodeDetachLim( storm.getStormDuration(), &strmNet, vegetation ); else erosion.DetachErode( storm.getStormDuration(), &strmNet, time.getCurrentTime(), vegetation ); if(0) //DEBUG std::cout << "Erosion::Done.." << std::endl; // Link tLNodes to StratNodes, adjust elevation StratNode to surrounding tLNodes if( optStratGrid ) stratGrid->UpdateStratGrid(tStratGrid::k1,time.getCurrentTime() ); if( optMeander ) strmMeander->Migrate( time.getCurrentTime() ); if(0) //DEBUG std::cout << "Meander-Migrate::Done..\n"; // Link tLNodes to StratNodes, adjust elevation StratNode to surrounding tLNodes if( optStratGrid ) stratGrid->UpdateStratGrid(tStratGrid::k2,time.getCurrentTime()); //----------------FLOODPLAIN--------------------------------- if( optFloodplainDep ) { if( floodplain->OptControlMainChan() ) floodplain->UpdateMainChannelHeight( time.getCurrentTime(), strmNet.getInletNodePtrNC() ); std::cout << "UpdateChannelHeight::Done..\n"; if( optStratGrid ){ stratGrid->UpdateStratGrid(tStratGrid::k3,time.getCurrentTime()); } floodplain->DepositOverbank( storm.getRainrate(), storm.getStormDuration(), time.getCurrentTime() ); std::cout << "tFloodplain::Done..\n"; if( optStratGrid ){ stratGrid->UpdateStratGrid(tStratGrid::k4,time.getCurrentTime()); } } // end of floodplain stuff #define NEWVEG 1 if( optVegetation ) { if( NEWVEG ) vegetation->GrowVegetation( &mesh, storm.interstormDur() ); else vegetation->UpdateVegetation( &mesh, storm.getStormDuration(), storm.interstormDur() ); } #undef NEWVEG // Do interstorm... erosion.Diffuse( storm.getStormDuration() + storm.interstormDur(), optDiffuseDepo ); erosion.UpdateExposureTime( storm.getStormDuration() + storm.interstormDur() ); if( optLoessDep ) loess->DepositLoess( &mesh, storm.getStormDuration()+storm.interstormDur(), time.getCurrentTime() ); if( time.getCurrentTime() < uplift.getDuration() ) uplift.DoUplift( &mesh, storm.getStormDuration() + storm.interstormDur(), time.getCurrentTime() ); time.Advance( storm.getStormDuration() + storm.interstormDur() ); if( time.CheckOutputTime() ) output.WriteOutput( time.getCurrentTime() ); if( output.OptTSOutput() ) output.WriteTSOutput(); /* IN PROGRESS switch( optTSOutput ){ case 1: // Volume output each N years. if( time.CheckTSOutputTime() ) output.WriteVolOutput(); break; case 2: // Volume and vegetation cover output each N years. if( time.CheckTSOutputTime() ) output.WriteVolVegOutput(); break; case 3: // All data at each storm. output.WriteTSOutput(); break; case 0: // No additional timeseries output. break; default: // Invalid option. ReportFatalError( "The input file contains an invalid value for OptTSOutput." */ /*tMesh< tLNode >::nodeListIter_t ni( mesh.getNodeList() ); tLNode *cn; for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() ) { if( cn->getY()<25 && cn->getX()>250 && cn->getDrArea()>1000 ) cn->TellAll(); }*/ } // end of main loop delete vegetation; delete floodplain; delete loess; delete strmMeander; delete stratGrid; return 0; } <commit_msg>general commit Oct 04 of work done mainly by QC spring-summer 04<commit_after>/**************************************************************************/ /** ** C H I L D ** ** CHANNEL-HILLSLOPE INTEGRATED LANDSCAPE DEVELOPMENT MODEL ** ** OXFORD VERSION 2003 ** ** Designed and created by Gregory E. Tucker, Stephen T. Lancaster, ** Nicole M. Gasparini, and Rafael L. Bras ** ** ** @file childmain.cpp ** @brief This file contains the main() routine that handles ** top-level initialization and implements the main ** time-loop. ** ** NOTE: This source code is copyrighted material. It is distributed ** solely for noncommercial research and educational purposes ** only. Use in whole or in part for commercial purposes without ** a written license from the copyright holder(s) is expressly ** prohibited. Copies of this source code or any of its components ** may not be transferred to any other individuals or organizations ** without written consent. Copyright (C) Massachusetts Institute ** of Technology, 1997-2000. All rights reserved. ** ** For information regarding this program, please contact Greg Tucker at: ** ** School of Geography and the Environment ** University of Oxford ** Mansfield Road ** Oxford OX1 3TB United Kingdom ** ** $Id: childmain.cpp,v 1.27 2004-10-05 14:24:27 childcvs Exp $ */ /**************************************************************************/ /* set traps for some floating point exceptions on Linux */ #include "trapfpe.h" #include "Inclusions.h" #include "tFloodplain/tFloodplain.h" #include "tStratGrid/tStratGrid.h" #include "tEolian/tEolian.h" #include "tOption/tOption.h" Predicates predicate; int main( int argc, char **argv ) { bool optDetachLim, // Option for detachment-limited erosion only optFloodplainDep, // Option for floodplain (overbank) deposition optLoessDep, // Option for eolian deposition optVegetation, // Option for dynamic vegetation cover optMeander, // Option for stream meandering optDiffuseDepo, // Option for deposition / no deposition by diff'n optStratGrid; // Option to enable stratigraphy grid tVegetation *vegetation(0); // -> vegetation object tFloodplain *floodplain(0); // -> floodplain object tStratGrid *stratGrid(0); // -> Stratigraphy Grid object tEolian *loess(0); // -> eolian deposition object tStreamMeander *strmMeander(0); // -> stream meander object /****************** INITIALIZATION *************************************\ ** ALGORITHM ** Get command-line arguments (name of input file + any other opts) ** Set silent_mode flag ** Open main input file ** Create and initialize objects for... ** Mesh ** Output files ** Storm ** Stream network ** Erosion ** Uplift (or baselevel change) ** Run timer ** Write output for initial state ** Get options for erosion type, meandering, etc. \**********************************************************************/ // Check command-line arguments tOption option( argc, argv ); // Say hello option.version(); // Open main input file tInputFile inputFile( option.inputFile ); // Create a random number generator for the simulation itself tRand rand( inputFile ); // Create and initialize objects: std::cout << "Creating mesh...\n"; tMesh<tLNode> mesh( inputFile, option.checkMeshConsistency ); std::cout << "Creating output files...\n"; tLOutput<tLNode> output( &mesh, inputFile, &rand ); tStorm storm( inputFile, &rand ); std::cout << "Creating stream network...\n"; tStreamNet strmNet( mesh, storm, inputFile ); tErosion erosion( &mesh, inputFile ); tUplift uplift( inputFile ); // Get various options optDetachLim = inputFile.ReadBool( "OPTDETACHLIM" ); optDiffuseDepo = inputFile.ReadBool( "OPTDIFFDEP" ); optVegetation = inputFile.ReadBool( "OPTVEG" ); optFloodplainDep = inputFile.ReadBool( "OPTFLOODPLAIN" ); optLoessDep = inputFile.ReadBool( "OPTLOESSDEP" ); optMeander = inputFile.ReadBool( "OPTMEANDER" ); optStratGrid = inputFile.ReadBool( "OPTSTRATGRID" ,false); // If applicable, create Vegetation object if( optVegetation ) vegetation = new tVegetation( &mesh, inputFile ); // If applicable, create floodplain object if( optFloodplainDep ) floodplain = new tFloodplain( inputFile, &mesh ); // If applicable, create eolian deposition object if( optLoessDep ) loess = new tEolian( inputFile ); // If applicable, create Stream Meander object if( optMeander ) strmMeander = new tStreamMeander( strmNet, mesh, inputFile, &rand ); // If applicable, create Stratigraphy Grid object // and pass it to output if( optStratGrid ) { if (!optFloodplainDep) ReportFatalError("OPTFLOODPLAIN must be enabled."); stratGrid = new tStratGrid (inputFile, &mesh); output.SetStratGrid( stratGrid, &strmNet ); } std::cout << "Writing data for time zero...\n"; tRunTimer time( inputFile, !option.silent_mode ); output.WriteOutput( 0. ); std::cout << "Initialization done.\n"; // Option for time series output (IN PROGRESS) /* switch( optTSOutput ){ case 1: // Volume output each N years. if( time.CheckTSOutputTime() ) output.WriteVolOutput(); break; case 2: // Volume and vegetation cover output each N years. std::cout << "here" << std::endl; if( time.CheckTSOutputTime() ){ std::cout << "there" << std::endl; output.WriteVolVegOutput();} break; case 3: // All data at each storm. output.WriteTSOutput(); break; case 0: // No additional timeseries output. break; default: // Invalid option. ReportFatalError( "The input file contains an invalid value for OptTSOutput." ); } */ /**************** MAIN LOOP ******************************************\ ** ALGORITHM ** Generate storm ** Do storm... ** Update network (flow directions, drainage area, runoff) ** Water erosion/deposition (vertical) ** Meandering (if applicable) ** Floodplain deposition (if applicable) ** Do interstorm... ** Hillslope transport ** Vegetation (if applicable) ** Exposure history ** Mesh densification (if applicable) ** Eolian (loess) deposition (if applicable) ** Uplift (or baselevel change) **********************************************************************/ while( !time.IsFinished() ) { if(0) //debug std::cout << " " << std::endl; time.ReportTimeStatus(); // Do storm... storm.GenerateStorm( time.getCurrentTime(), strmNet.getInfilt(), strmNet.getSoilStore() ); /*std::cout << "Storm: " << storm.getRainrate() << " " << storm.getStormDuration() << " " << storm.interstormDur() << std::endl;*/ strmNet.UpdateNet( time.getCurrentTime(), storm ); if(0) //DEBUG std::cout << "UpdateNet::Done.." << std::endl; // Link tLNodes to StratNodes, adjust elevation StratNode to surrounding tLNodes if( optStratGrid ) stratGrid->UpdateStratGrid(tStratGrid::k0, time.getCurrentTime()); if( optDetachLim ) erosion.ErodeDetachLim( storm.getStormDuration(), &strmNet, vegetation ); else erosion.DetachErode( storm.getStormDuration(), &strmNet, time.getCurrentTime(), vegetation ); if(0) //DEBUG std::cout << "Erosion::Done.." << std::endl; // Link tLNodes to StratNodes, adjust elevation StratNode to surrounding tLNodes if( optStratGrid ) stratGrid->UpdateStratGrid(tStratGrid::k1,time.getCurrentTime() ); if( optMeander ) strmMeander->Migrate( time.getCurrentTime() ); if(0) //DEBUG std::cout << "Meander-Migrate::Done..\n"; // Link tLNodes to StratNodes, adjust elevation StratNode to surrounding tLNodes if( optStratGrid ) stratGrid->UpdateStratGrid(tStratGrid::k2,time.getCurrentTime()); //----------------FLOODPLAIN--------------------------------- if( optFloodplainDep ) { if( floodplain->OptControlMainChan() ) floodplain->UpdateMainChannelHeight( time.getCurrentTime(), strmNet.getInletNodePtrNC() ); std::cout << "UpdateChannelHeight::Done..\n"; if( optStratGrid ){ stratGrid->UpdateStratGrid(tStratGrid::k3,time.getCurrentTime()); } floodplain->DepositOverbank( storm.getRainrate(), storm.getStormDuration(), time.getCurrentTime() ); std::cout << "tFloodplain::Done..\n"; if( optStratGrid ){ stratGrid->UpdateStratGrid(tStratGrid::k4,time.getCurrentTime()); } } // end of floodplain stuff #define NEWVEG 1 if( optVegetation ) { if( NEWVEG ) vegetation->GrowVegetation( &mesh, storm.interstormDur() ); else vegetation->UpdateVegetation( &mesh, storm.getStormDuration(), storm.interstormDur() ); } #undef NEWVEG // Do interstorm... erosion.Diffuse( storm.getStormDuration() + storm.interstormDur(), optDiffuseDepo ); erosion.UpdateExposureTime( storm.getStormDuration() + storm.interstormDur() ); if( optLoessDep ) loess->DepositLoess( &mesh, storm.getStormDuration()+storm.interstormDur(), time.getCurrentTime() ); if( time.getCurrentTime() < uplift.getDuration() ) uplift.DoUplift( &mesh, storm.getStormDuration() + storm.interstormDur(), time.getCurrentTime() ); time.Advance( storm.getStormDuration() + storm.interstormDur() ); if( time.CheckOutputTime() ) output.WriteOutput( time.getCurrentTime() ); if( output.OptTSOutput() ) output.WriteTSOutput(); /* IN PROGRESS switch( optTSOutput ){ case 1: // Volume output each N years. if( time.CheckTSOutputTime() ) output.WriteVolOutput(); break; case 2: // Volume and vegetation cover output each N years. if( time.CheckTSOutputTime() ) output.WriteVolVegOutput(); break; case 3: // All data at each storm. output.WriteTSOutput(); break; case 0: // No additional timeseries output. break; default: // Invalid option. ReportFatalError( "The input file contains an invalid value for OptTSOutput." */ /*tMesh< tLNode >::nodeListIter_t ni( mesh.getNodeList() ); tLNode *cn; for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() ) { if( cn->getY()<25 && cn->getX()>250 && cn->getDrArea()>1000 ) cn->TellAll(); }*/ } // end of main loop delete vegetation; delete floodplain; delete loess; delete strmMeander; delete stratGrid; return 0; } <|endoftext|>
<commit_before>// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <signal.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <time.h> #include <atomic> #include <functional> #include <iostream> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "test/util/file_descriptor.h" #include "test/util/logging.h" #include "test/util/multiprocess_util.h" #include "test/util/posix_error.h" #include "test/util/signal_util.h" #include "test/util/test_util.h" #include "test/util/thread_util.h" #include "test/util/timer_util.h" namespace gvisor { namespace testing { namespace { constexpr char kSIGALRMToMainThread[] = "--itimer_sigarlm_to_main_thread"; constexpr char kSIGPROFFairnessActive[] = "--itimer_sigprof_fairness_active"; constexpr char kSIGPROFFairnessIdle[] = "--itimer_sigprof_fairness_idle"; // Time period to be set for the itimers. constexpr absl::Duration kPeriod = absl::Milliseconds(25); // Total amount of time to spend per thread. constexpr absl::Duration kTestDuration = absl::Seconds(20); // Amount of spin iterations to perform as the minimum work item per thread. // Chosen to be sub-millisecond range. constexpr int kIterations = 10000000; // Allow deviation in the number of samples. constexpr double kNumSamplesDeviationRatio = 0.2; TEST(ItimerTest, ItimervalUpdatedBeforeExpiration) { constexpr int kSleepSecs = 10; constexpr int kAlarmSecs = 15; static_assert( kSleepSecs < kAlarmSecs, "kSleepSecs must be less than kAlarmSecs for the test to be meaningful"); constexpr int kMaxRemainingSecs = kAlarmSecs - kSleepSecs; // Install a no-op handler for SIGALRM. struct sigaction sa = {}; sigfillset(&sa.sa_mask); sa.sa_handler = +[](int signo) {}; auto const cleanup_sa = ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGALRM, sa)); // Set an itimer-based alarm for kAlarmSecs from now. struct itimerval itv = {}; itv.it_value.tv_sec = kAlarmSecs; auto const cleanup_itimer = ASSERT_NO_ERRNO_AND_VALUE(ScopedItimer(ITIMER_REAL, itv)); // After sleeping for kSleepSecs, the itimer value should reflect the elapsed // time even if it hasn't expired. absl::SleepFor(absl::Seconds(kSleepSecs)); ASSERT_THAT(getitimer(ITIMER_REAL, &itv), SyscallSucceeds()); EXPECT_TRUE( itv.it_value.tv_sec < kMaxRemainingSecs || (itv.it_value.tv_sec == kMaxRemainingSecs && itv.it_value.tv_usec == 0)) << "Remaining time: " << itv.it_value.tv_sec << " seconds + " << itv.it_value.tv_usec << " microseconds"; } ABSL_CONST_INIT static thread_local std::atomic_int signal_test_num_samples = ATOMIC_VAR_INIT(0); void SignalTestSignalHandler(int /*signum*/) { signal_test_num_samples++; } struct SignalTestResult { int expected_total; int main_thread_samples; std::vector<int> worker_samples; }; std::ostream& operator<<(std::ostream& os, const SignalTestResult& r) { os << "{expected_total: " << r.expected_total << ", main_thread_samples: " << r.main_thread_samples << ", worker_samples: ["; bool first = true; for (int sample : r.worker_samples) { if (!first) { os << ", "; } os << sample; first = false; } os << "]}"; return os; } // Starts two worker threads and itimer id and measures the number of signal // delivered to each thread. SignalTestResult ItimerSignalTest(int id, clock_t main_clock, clock_t worker_clock, int signal, absl::Duration sleep) { signal_test_num_samples = 0; struct sigaction sa = {}; sa.sa_handler = &SignalTestSignalHandler; sa.sa_flags = SA_RESTART; sigemptyset(&sa.sa_mask); auto sigaction_cleanup = ScopedSigaction(signal, sa).ValueOrDie(); int socketfds[2]; TEST_PCHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, socketfds) == 0); // Do the spinning in the workers. std::function<void*(int)> work = [&](int socket_fd) { FileDescriptor fd(socket_fd); absl::Time finish = Now(worker_clock) + kTestDuration; while (Now(worker_clock) < finish) { // Blocked on read. char c; RetryEINTR(read)(fd.get(), &c, 1); for (int i = 0; i < kIterations; i++) { // Ensure compiler won't optimize this loop away. asm(""); } if (sleep != absl::ZeroDuration()) { // Sleep so that the entire process is idle for a while. absl::SleepFor(sleep); } // Unblock the other thread. RetryEINTR(write)(fd.get(), &c, 1); } return reinterpret_cast<void*>(signal_test_num_samples.load()); }; ScopedThread th1( static_cast<std::function<void*()>>(std::bind(work, socketfds[0]))); ScopedThread th2( static_cast<std::function<void*()>>(std::bind(work, socketfds[1]))); absl::Time start = Now(main_clock); // Start the timer. struct itimerval timer = {}; timer.it_value = absl::ToTimeval(kPeriod); timer.it_interval = absl::ToTimeval(kPeriod); auto cleanup_itimer = ScopedItimer(id, timer).ValueOrDie(); // Unblock th1. // // N.B. th2 owns socketfds[1] but can't close it until it unblocks. char c = 0; TEST_CHECK(write(socketfds[1], &c, 1) == 1); SignalTestResult result; // Wait for the workers to be done and collect their sample counts. result.worker_samples.push_back(reinterpret_cast<int64_t>(th1.Join())); result.worker_samples.push_back(reinterpret_cast<int64_t>(th2.Join())); cleanup_itimer.Release()(); result.expected_total = (Now(main_clock) - start) / kPeriod; result.main_thread_samples = signal_test_num_samples.load(); return result; } int TestSIGALRMToMainThread() { SignalTestResult result = ItimerSignalTest(ITIMER_REAL, CLOCK_REALTIME, CLOCK_REALTIME, SIGALRM, absl::ZeroDuration()); std::cerr << "result: " << result << std::endl; // ITIMER_REAL-generated SIGALRMs prefer to deliver to the thread group leader // (but don't guarantee it), so we expect to see most samples on the main // thread. // // The number of SIGALRMs delivered to a worker should not exceed 20% // of the number of total signals expected (this is somewhat arbitrary). const int worker_threshold = result.expected_total / 5; // // Linux only guarantees timers will never expire before the requested time. // Thus, we only check the upper bound and also it at least have one sample. TEST_CHECK(result.main_thread_samples <= result.expected_total); TEST_CHECK(result.main_thread_samples > 0); for (int num : result.worker_samples) { TEST_CHECK_MSG(num <= worker_threshold, "worker received too many samples"); } return 0; } // Random save/restore is disabled as it introduces additional latency and // unpredictable distribution patterns. TEST(ItimerTest, DeliversSIGALRMToMainThread_NoRandomSave) { pid_t child; int execve_errno; auto kill = ASSERT_NO_ERRNO_AND_VALUE( ForkAndExec("/proc/self/exe", {"/proc/self/exe", kSIGALRMToMainThread}, {}, &child, &execve_errno)); EXPECT_EQ(0, execve_errno); int status; EXPECT_THAT(RetryEINTR(waitpid)(child, &status, 0), SyscallSucceedsWithValue(child)); // Not required anymore. kill.Release(); EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0) << status; } // Signals are delivered to threads fairly. // // sleep indicates how long to sleep worker threads each iteration to make the // entire process idle. int TestSIGPROFFairness(absl::Duration sleep) { SignalTestResult result = ItimerSignalTest(ITIMER_PROF, CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID, SIGPROF, sleep); std::cerr << "result: " << result << std::endl; // The number of samples on the main thread should be very low as it did // nothing. TEST_CHECK(result.main_thread_samples < 60); // Both workers should get roughly equal number of samples. TEST_CHECK(result.worker_samples.size() == 2); TEST_CHECK(result.expected_total > 0); // In an ideal world each thread would get exactly 50% of the signals, // but since that's unlikely to happen we allow for them to get no less than // kNumSamplesDeviationRatio of the total observed samples. TEST_CHECK_MSG(std::abs(result.worker_samples[0] - result.worker_samples[1]) < ((result.worker_samples[0] + result.worker_samples[1]) * kNumSamplesDeviationRatio), "one worker received disproportionate share of samples"); return 0; } // Random save/restore is disabled as it introduces additional latency and // unpredictable distribution patterns. TEST(ItimerTest, DeliversSIGPROFToThreadsRoughlyFairlyActive_NoRandomSave) { // TODO(b/143247272): CPU time accounting is inaccurate for the KVM platform. SKIP_IF(GvisorPlatform() == Platform::kKVM); pid_t child; int execve_errno; auto kill = ASSERT_NO_ERRNO_AND_VALUE( ForkAndExec("/proc/self/exe", {"/proc/self/exe", kSIGPROFFairnessActive}, {}, &child, &execve_errno)); EXPECT_EQ(0, execve_errno); int status; EXPECT_THAT(RetryEINTR(waitpid)(child, &status, 0), SyscallSucceedsWithValue(child)); // Not required anymore. kill.Release(); EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0) << "Exited with code: " << status; } // Random save/restore is disabled as it introduces additional latency and // unpredictable distribution patterns. TEST(ItimerTest, DeliversSIGPROFToThreadsRoughlyFairlyIdle_NoRandomSave) { // TODO(b/143247272): CPU time accounting is inaccurate for the KVM platform. SKIP_IF(GvisorPlatform() == Platform::kKVM); pid_t child; int execve_errno; auto kill = ASSERT_NO_ERRNO_AND_VALUE( ForkAndExec("/proc/self/exe", {"/proc/self/exe", kSIGPROFFairnessIdle}, {}, &child, &execve_errno)); EXPECT_EQ(0, execve_errno); int status; EXPECT_THAT(RetryEINTR(waitpid)(child, &status, 0), SyscallSucceedsWithValue(child)); // Not required anymore. kill.Release(); EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0) << "Exited with code: " << status; } } // namespace } // namespace testing } // namespace gvisor namespace { void MaskSIGPIPE() { // Always mask SIGPIPE as it's common and tests aren't expected to handle it. // We don't take the TestInit() path so we must do this manually. struct sigaction sa = {}; sa.sa_handler = SIG_IGN; TEST_CHECK(sigaction(SIGPIPE, &sa, nullptr) == 0); } } // namespace int main(int argc, char** argv) { // These tests require no background threads, so check for them before // TestInit. for (int i = 0; i < argc; i++) { absl::string_view arg(argv[i]); if (arg == gvisor::testing::kSIGALRMToMainThread) { MaskSIGPIPE(); return gvisor::testing::TestSIGALRMToMainThread(); } if (arg == gvisor::testing::kSIGPROFFairnessActive) { MaskSIGPIPE(); return gvisor::testing::TestSIGPROFFairness(absl::ZeroDuration()); } if (arg == gvisor::testing::kSIGPROFFairnessIdle) { MaskSIGPIPE(); // Sleep time > ClockTick (10ms) exercises sleeping gVisor's // kernel.cpuClockTicker. return gvisor::testing::TestSIGPROFFairness(absl::Milliseconds(25)); } } gvisor::testing::TestInit(&argc, &argv); return gvisor::testing::RunAllTests(); } <commit_msg>Bump up acceptable sample count for flaky itimer test.<commit_after>// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <signal.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <time.h> #include <atomic> #include <functional> #include <iostream> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "test/util/file_descriptor.h" #include "test/util/logging.h" #include "test/util/multiprocess_util.h" #include "test/util/posix_error.h" #include "test/util/signal_util.h" #include "test/util/test_util.h" #include "test/util/thread_util.h" #include "test/util/timer_util.h" namespace gvisor { namespace testing { namespace { constexpr char kSIGALRMToMainThread[] = "--itimer_sigarlm_to_main_thread"; constexpr char kSIGPROFFairnessActive[] = "--itimer_sigprof_fairness_active"; constexpr char kSIGPROFFairnessIdle[] = "--itimer_sigprof_fairness_idle"; // Time period to be set for the itimers. constexpr absl::Duration kPeriod = absl::Milliseconds(25); // Total amount of time to spend per thread. constexpr absl::Duration kTestDuration = absl::Seconds(20); // Amount of spin iterations to perform as the minimum work item per thread. // Chosen to be sub-millisecond range. constexpr int kIterations = 10000000; // Allow deviation in the number of samples. constexpr double kNumSamplesDeviationRatio = 0.2; TEST(ItimerTest, ItimervalUpdatedBeforeExpiration) { constexpr int kSleepSecs = 10; constexpr int kAlarmSecs = 15; static_assert( kSleepSecs < kAlarmSecs, "kSleepSecs must be less than kAlarmSecs for the test to be meaningful"); constexpr int kMaxRemainingSecs = kAlarmSecs - kSleepSecs; // Install a no-op handler for SIGALRM. struct sigaction sa = {}; sigfillset(&sa.sa_mask); sa.sa_handler = +[](int signo) {}; auto const cleanup_sa = ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGALRM, sa)); // Set an itimer-based alarm for kAlarmSecs from now. struct itimerval itv = {}; itv.it_value.tv_sec = kAlarmSecs; auto const cleanup_itimer = ASSERT_NO_ERRNO_AND_VALUE(ScopedItimer(ITIMER_REAL, itv)); // After sleeping for kSleepSecs, the itimer value should reflect the elapsed // time even if it hasn't expired. absl::SleepFor(absl::Seconds(kSleepSecs)); ASSERT_THAT(getitimer(ITIMER_REAL, &itv), SyscallSucceeds()); EXPECT_TRUE( itv.it_value.tv_sec < kMaxRemainingSecs || (itv.it_value.tv_sec == kMaxRemainingSecs && itv.it_value.tv_usec == 0)) << "Remaining time: " << itv.it_value.tv_sec << " seconds + " << itv.it_value.tv_usec << " microseconds"; } ABSL_CONST_INIT static thread_local std::atomic_int signal_test_num_samples = ATOMIC_VAR_INIT(0); void SignalTestSignalHandler(int /*signum*/) { signal_test_num_samples++; } struct SignalTestResult { int expected_total; int main_thread_samples; std::vector<int> worker_samples; }; std::ostream& operator<<(std::ostream& os, const SignalTestResult& r) { os << "{expected_total: " << r.expected_total << ", main_thread_samples: " << r.main_thread_samples << ", worker_samples: ["; bool first = true; for (int sample : r.worker_samples) { if (!first) { os << ", "; } os << sample; first = false; } os << "]}"; return os; } // Starts two worker threads and itimer id and measures the number of signal // delivered to each thread. SignalTestResult ItimerSignalTest(int id, clock_t main_clock, clock_t worker_clock, int signal, absl::Duration sleep) { signal_test_num_samples = 0; struct sigaction sa = {}; sa.sa_handler = &SignalTestSignalHandler; sa.sa_flags = SA_RESTART; sigemptyset(&sa.sa_mask); auto sigaction_cleanup = ScopedSigaction(signal, sa).ValueOrDie(); int socketfds[2]; TEST_PCHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, socketfds) == 0); // Do the spinning in the workers. std::function<void*(int)> work = [&](int socket_fd) { FileDescriptor fd(socket_fd); absl::Time finish = Now(worker_clock) + kTestDuration; while (Now(worker_clock) < finish) { // Blocked on read. char c; RetryEINTR(read)(fd.get(), &c, 1); for (int i = 0; i < kIterations; i++) { // Ensure compiler won't optimize this loop away. asm(""); } if (sleep != absl::ZeroDuration()) { // Sleep so that the entire process is idle for a while. absl::SleepFor(sleep); } // Unblock the other thread. RetryEINTR(write)(fd.get(), &c, 1); } return reinterpret_cast<void*>(signal_test_num_samples.load()); }; ScopedThread th1( static_cast<std::function<void*()>>(std::bind(work, socketfds[0]))); ScopedThread th2( static_cast<std::function<void*()>>(std::bind(work, socketfds[1]))); absl::Time start = Now(main_clock); // Start the timer. struct itimerval timer = {}; timer.it_value = absl::ToTimeval(kPeriod); timer.it_interval = absl::ToTimeval(kPeriod); auto cleanup_itimer = ScopedItimer(id, timer).ValueOrDie(); // Unblock th1. // // N.B. th2 owns socketfds[1] but can't close it until it unblocks. char c = 0; TEST_CHECK(write(socketfds[1], &c, 1) == 1); SignalTestResult result; // Wait for the workers to be done and collect their sample counts. result.worker_samples.push_back(reinterpret_cast<int64_t>(th1.Join())); result.worker_samples.push_back(reinterpret_cast<int64_t>(th2.Join())); cleanup_itimer.Release()(); result.expected_total = (Now(main_clock) - start) / kPeriod; result.main_thread_samples = signal_test_num_samples.load(); return result; } int TestSIGALRMToMainThread() { SignalTestResult result = ItimerSignalTest(ITIMER_REAL, CLOCK_REALTIME, CLOCK_REALTIME, SIGALRM, absl::ZeroDuration()); std::cerr << "result: " << result << std::endl; // ITIMER_REAL-generated SIGALRMs prefer to deliver to the thread group leader // (but don't guarantee it), so we expect to see most samples on the main // thread. // // The number of SIGALRMs delivered to a worker should not exceed 20% // of the number of total signals expected (this is somewhat arbitrary). const int worker_threshold = result.expected_total / 5; // // Linux only guarantees timers will never expire before the requested time. // Thus, we only check the upper bound and also it at least have one sample. TEST_CHECK(result.main_thread_samples <= result.expected_total); TEST_CHECK(result.main_thread_samples > 0); for (int num : result.worker_samples) { TEST_CHECK_MSG(num <= worker_threshold, "worker received too many samples"); } return 0; } // Random save/restore is disabled as it introduces additional latency and // unpredictable distribution patterns. TEST(ItimerTest, DeliversSIGALRMToMainThread_NoRandomSave) { pid_t child; int execve_errno; auto kill = ASSERT_NO_ERRNO_AND_VALUE( ForkAndExec("/proc/self/exe", {"/proc/self/exe", kSIGALRMToMainThread}, {}, &child, &execve_errno)); EXPECT_EQ(0, execve_errno); int status; EXPECT_THAT(RetryEINTR(waitpid)(child, &status, 0), SyscallSucceedsWithValue(child)); // Not required anymore. kill.Release(); EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0) << status; } // Signals are delivered to threads fairly. // // sleep indicates how long to sleep worker threads each iteration to make the // entire process idle. int TestSIGPROFFairness(absl::Duration sleep) { SignalTestResult result = ItimerSignalTest(ITIMER_PROF, CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID, SIGPROF, sleep); std::cerr << "result: " << result << std::endl; // The number of samples on the main thread should be very low as it did // nothing. TEST_CHECK(result.main_thread_samples < 80); // Both workers should get roughly equal number of samples. TEST_CHECK(result.worker_samples.size() == 2); TEST_CHECK(result.expected_total > 0); // In an ideal world each thread would get exactly 50% of the signals, // but since that's unlikely to happen we allow for them to get no less than // kNumSamplesDeviationRatio of the total observed samples. TEST_CHECK_MSG(std::abs(result.worker_samples[0] - result.worker_samples[1]) < ((result.worker_samples[0] + result.worker_samples[1]) * kNumSamplesDeviationRatio), "one worker received disproportionate share of samples"); return 0; } // Random save/restore is disabled as it introduces additional latency and // unpredictable distribution patterns. TEST(ItimerTest, DeliversSIGPROFToThreadsRoughlyFairlyActive_NoRandomSave) { // TODO(b/143247272): CPU time accounting is inaccurate for the KVM platform. SKIP_IF(GvisorPlatform() == Platform::kKVM); pid_t child; int execve_errno; auto kill = ASSERT_NO_ERRNO_AND_VALUE( ForkAndExec("/proc/self/exe", {"/proc/self/exe", kSIGPROFFairnessActive}, {}, &child, &execve_errno)); EXPECT_EQ(0, execve_errno); int status; EXPECT_THAT(RetryEINTR(waitpid)(child, &status, 0), SyscallSucceedsWithValue(child)); // Not required anymore. kill.Release(); EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0) << "Exited with code: " << status; } // Random save/restore is disabled as it introduces additional latency and // unpredictable distribution patterns. TEST(ItimerTest, DeliversSIGPROFToThreadsRoughlyFairlyIdle_NoRandomSave) { // TODO(b/143247272): CPU time accounting is inaccurate for the KVM platform. SKIP_IF(GvisorPlatform() == Platform::kKVM); pid_t child; int execve_errno; auto kill = ASSERT_NO_ERRNO_AND_VALUE( ForkAndExec("/proc/self/exe", {"/proc/self/exe", kSIGPROFFairnessIdle}, {}, &child, &execve_errno)); EXPECT_EQ(0, execve_errno); int status; EXPECT_THAT(RetryEINTR(waitpid)(child, &status, 0), SyscallSucceedsWithValue(child)); // Not required anymore. kill.Release(); EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0) << "Exited with code: " << status; } } // namespace } // namespace testing } // namespace gvisor namespace { void MaskSIGPIPE() { // Always mask SIGPIPE as it's common and tests aren't expected to handle it. // We don't take the TestInit() path so we must do this manually. struct sigaction sa = {}; sa.sa_handler = SIG_IGN; TEST_CHECK(sigaction(SIGPIPE, &sa, nullptr) == 0); } } // namespace int main(int argc, char** argv) { // These tests require no background threads, so check for them before // TestInit. for (int i = 0; i < argc; i++) { absl::string_view arg(argv[i]); if (arg == gvisor::testing::kSIGALRMToMainThread) { MaskSIGPIPE(); return gvisor::testing::TestSIGALRMToMainThread(); } if (arg == gvisor::testing::kSIGPROFFairnessActive) { MaskSIGPIPE(); return gvisor::testing::TestSIGPROFFairness(absl::ZeroDuration()); } if (arg == gvisor::testing::kSIGPROFFairnessIdle) { MaskSIGPIPE(); // Sleep time > ClockTick (10ms) exercises sleeping gVisor's // kernel.cpuClockTicker. return gvisor::testing::TestSIGPROFFairness(absl::Milliseconds(25)); } } gvisor::testing::TestInit(&argc, &argv); return gvisor::testing::RunAllTests(); } <|endoftext|>
<commit_before>#ifndef __STAN__AGRAD__REV__AS_BOOL_HPP__ #define __STAN__AGRAD__REV__AS_BOOL_HPP__ #include <stan/agrad/rev/var.hpp> namespace stan { namespace agrad { /** * Return 1 if the argument is unequal to zero and 0 otherwise. * * @param x Value. * @return 1 if argument is equal to zero and 0 otherwise. */ inline int as_bool(const agrad::var& v) { return 0.0 != v.vi_->val_; } } } #endif <commit_msg>Changed documentation to match code<commit_after>#ifndef __STAN__AGRAD__REV__AS_BOOL_HPP__ #define __STAN__AGRAD__REV__AS_BOOL_HPP__ #include <stan/agrad/rev/var.hpp> namespace stan { namespace agrad { /** * Return 1 if the argument is unequal to zero and 0 otherwise. * * @param v Value. * @return 1 if argument is equal to zero and 0 otherwise. */ inline int as_bool(const agrad::var& v) { return 0.0 != v.vi_->val_; } } } #endif <|endoftext|>