text
stringlengths
54
60.6k
<commit_before>/* Copyright (c) 2012-2013 LevelDOWN contributors * See list at <https://github.com/rvagg/node-leveldown#contributing> * MIT +no-false-attribs License <https://github.com/rvagg/node-leveldown/blob/master/LICENSE> */ #include <node.h> #include <node_buffer.h> #include "database.h" #include "leveldown.h" #include "async.h" #include "iterator_async.h" namespace leveldown { /** NEXT-MULTI WORKER **/ NextWorker::NextWorker ( Iterator* iterator , NanCallback *callback , void (*localCallback)(Iterator*) ) : AsyncWorker(NULL, callback) , iterator(iterator) , localCallback(localCallback) {}; NextWorker::~NextWorker () {} void NextWorker::Execute () { ok = iterator->IteratorNext(result); if (!ok) SetStatus(iterator->IteratorStatus()); } void NextWorker::HandleOKCallback () { size_t idx = 0; v8::Local<v8::Array> returnArray; if (ok) returnArray = NanNew<v8::Array>(result.size()); else { // make room and add for a null-value at the end, // signaling that we're at the end returnArray = NanNew<v8::Array>(result.size() + 1); returnArray->Set( NanNew<v8::Integer>(static_cast<int>(result.size())) w(NanNull() ); } for(idx = 0; idx < result.size(); ++idx) { std::pair<std::string, std::string> row = result[idx]; std::string key = row.first; std::string value = row.second; v8::Local<v8::Value> returnKey; if (iterator->keyAsBuffer) { returnKey = NanNewBufferHandle((char*)key.data(), key.size()); } else { returnKey = NanNew<v8::String>((char*)key.data(), key.size()); } v8::Local<v8::Value> returnValue; if (iterator->valueAsBuffer) { returnValue = NanNewBufferHandle((char*)value.data(), value.size()); } else { returnValue = NanNew<v8::String>((char*)value.data(), value.size()); } v8::Local<v8::Object> returnObject = NanNew<v8::Object>(); returnObject->Set(NanNew("key"), returnKey); returnObject->Set(NanNew("value"), returnValue); returnArray->Set(NanNew<v8::Integer>(static_cast<int>(idx)), returnObject); } // clean up & handle the next/end state see iterator.cc/checkEndCallback localCallback(iterator); v8::Local<v8::Value> argv[] = { NanNull() , returnArray }; callback->Call(2, argv); } /** END WORKER **/ EndWorker::EndWorker ( Iterator* iterator , NanCallback *callback ) : AsyncWorker(NULL, callback) , iterator(iterator) {}; EndWorker::~EndWorker () {} void EndWorker::Execute () { iterator->IteratorEnd(); } void EndWorker::HandleOKCallback () { iterator->Release(); callback->Call(0, NULL); } } // namespace leveldown <commit_msg>omg, embarrassing fumble (pressed ⌘+z before ⌘+s, lolz)<commit_after>/* Copyright (c) 2012-2013 LevelDOWN contributors * See list at <https://github.com/rvagg/node-leveldown#contributing> * MIT +no-false-attribs License <https://github.com/rvagg/node-leveldown/blob/master/LICENSE> */ #include <node.h> #include <node_buffer.h> #include "database.h" #include "leveldown.h" #include "async.h" #include "iterator_async.h" namespace leveldown { /** NEXT-MULTI WORKER **/ NextWorker::NextWorker ( Iterator* iterator , NanCallback *callback , void (*localCallback)(Iterator*) ) : AsyncWorker(NULL, callback) , iterator(iterator) , localCallback(localCallback) {}; NextWorker::~NextWorker () {} void NextWorker::Execute () { ok = iterator->IteratorNext(result); if (!ok) SetStatus(iterator->IteratorStatus()); } void NextWorker::HandleOKCallback () { size_t idx = 0; v8::Local<v8::Array> returnArray; if (ok) returnArray = NanNew<v8::Array>(result.size()); else { // make room and add for a null-value at the end, // signaling that we're at the end returnArray = NanNew<v8::Array>(result.size() + 1); returnArray->Set( NanNew<v8::Integer>(static_cast<int>(result.size())) , NanNull() ); } for(idx = 0; idx < result.size(); ++idx) { std::pair<std::string, std::string> row = result[idx]; std::string key = row.first; std::string value = row.second; v8::Local<v8::Value> returnKey; if (iterator->keyAsBuffer) { returnKey = NanNewBufferHandle((char*)key.data(), key.size()); } else { returnKey = NanNew<v8::String>((char*)key.data(), key.size()); } v8::Local<v8::Value> returnValue; if (iterator->valueAsBuffer) { returnValue = NanNewBufferHandle((char*)value.data(), value.size()); } else { returnValue = NanNew<v8::String>((char*)value.data(), value.size()); } v8::Local<v8::Object> returnObject = NanNew<v8::Object>(); returnObject->Set(NanNew("key"), returnKey); returnObject->Set(NanNew("value"), returnValue); returnArray->Set(NanNew<v8::Integer>(static_cast<int>(idx)), returnObject); } // clean up & handle the next/end state see iterator.cc/checkEndCallback localCallback(iterator); v8::Local<v8::Value> argv[] = { NanNull() , returnArray }; callback->Call(2, argv); } /** END WORKER **/ EndWorker::EndWorker ( Iterator* iterator , NanCallback *callback ) : AsyncWorker(NULL, callback) , iterator(iterator) {}; EndWorker::~EndWorker () {} void EndWorker::Execute () { iterator->IteratorEnd(); } void EndWorker::HandleOKCallback () { iterator->Release(); callback->Call(0, NULL); } } // namespace leveldown <|endoftext|>
<commit_before>#include "eventbackend.h" #define MAX_EVENTS 1024 // PDTK #include <cxxutils/vterm.h> lockable<std::unordered_multimap<posix::fd_t, EventBackend::callback_info_t>> EventBackend::queue; std::list<std::pair<posix::fd_t, native_flags_t>> EventBackend::results; #if defined(__linux__) // epoll needs kernel 2.5.44 // Linux #include <sys/epoll.h> struct EventBackend::platform_dependant // poll notification (epoll) { posix::fd_t fd; struct epoll_event output[MAX_EVENTS]; platform_dependant(void) noexcept : fd(posix::invalid_descriptor) { fd = ::epoll_create(MAX_EVENTS); flaw(fd == posix::invalid_descriptor, terminal::critical, std::exit(errno),, "Unable to create an instance of epoll! %s", std::strerror(errno)) } ~platform_dependant(void) noexcept { posix::close(fd); fd = posix::invalid_descriptor; } bool add(posix::fd_t wd, native_flags_t flags) noexcept { struct epoll_event native_event; native_event.data.fd = wd; native_event.events = flags; // be sure to convert to native events return ::epoll_ctl(fd, EPOLL_CTL_ADD, wd, &native_event) == posix::success_response || // add new event OR (errno == EEXIST && ::epoll_ctl(fd, EPOLL_CTL_MOD, wd, &native_event) == posix::success_response); // modify existing event } bool remove(posix::fd_t wd) noexcept { struct epoll_event event; return ::epoll_ctl(fd, EPOLL_CTL_DEL, wd, &event) == posix::success_response; // try to delete entry } } EventBackend::s_platform; const native_flags_t EventBackend::SimplePollReadFlags = EPOLLIN; bool EventBackend::poll(int timeout) noexcept { int count = ::epoll_wait(s_platform.fd, s_platform.output, MAX_EVENTS, timeout); // wait for new results results.clear(); // clear old results if(count == posix::error_response) // if error/timeout occurred return false; //fail const epoll_event* end = s_platform.output + count; for(epoll_event* pos = s_platform.output; pos != end; ++pos) // iterate through results results.emplace_back(std::make_pair(posix::fd_t(pos->data.fd), native_flags_t(pos->events))); // save result (in native format) return true; } #elif defined(__APPLE__) /* Darwin 7+ */ || \ defined(__FreeBSD__) /* FreeBSD 4.1+ */ || \ defined(__DragonFly__) /* DragonFly BSD */ || \ defined(__OpenBSD__) /* OpenBSD 2.9+ */ || \ defined(__NetBSD__) /* NetBSD 2+ */ // BSD #include <sys/time.h> #include <sys/event.h> // POSIX #include <sys/socket.h> #include <unistd.h> // POSIX++ #include <cstdlib> #include <cstdio> #include <climits> #include <cstring> // STL #include <vector> #include <algorithm> #include <iterator> // PDTK #include <cxxutils/vterm.h> #include <cxxutils/error_helpers.h> struct EventBackend::platform_dependant // poll notification (epoll) { posix::fd_t kq; std::vector<struct kevent> koutput; // events that were triggered static constexpr native_flags_t composite_flag(uint16_t actions, int16_t filters, uint32_t flags) noexcept { return native_flags_t(actions) | (uint16_t(filters) << 16) | (flags << 32); } static constexpr short extract_actions(native_flags_t flags) noexcept { return flags & 0xFFFF; } static constexpr ushort extract_filter(native_flags_t flags) noexcept { return (flags >> 16) & 0xFFFF; } static constexpr ushort extract_flags(native_flags_t flags) noexcept { return flags >> 32; } platform_dependant(void) { kq = posix::ignore_interruption(::kqueue); flaw(kq == posix::error_response, terminal::critical, std::exit(errno),, "Unable to create a new kqueue: %s", std::strerror(errno)) koutput.resize(1024); } ~platform_dependant(void) { posix::close(kq); } bool add(posix::fd_t fd, native_flags_t flags) noexcept { struct kevent ev; EV_SET(&ev, fd, extract_filter(flags), EV_ADD | extract_actions(flags), extract_flags(flags), 0, nullptr); return kevent(kq, &ev, 1, nullptr, 0, nullptr) == posix::success_response; } bool remove(posix::fd_t fd) noexcept { struct kevent ev; EV_SET(&ev, fd, 0, EV_DELETE, 0, 0, nullptr); return kevent(kq, &ev, 1, nullptr, 0, nullptr) == posix::success_response; } } EventBackend::s_platform; const native_flags_t EventBackend::SimplePollReadFlags = platform_dependant::composite_flag(0, EVFILT_READ, 0); bool EventBackend::poll(int timeout) noexcept { uint32_t data; timespec tout; tout.tv_sec = timeout / 1000; tout.tv_nsec = (timeout % 1000) * 1000; int count = kevent(s_platform.kq, nullptr, 0, s_platform.koutput.data(), s_platform.koutput.size(), &tout); if(count <= 0) return false; struct kevent* end = s_platform.koutput.data() + count; for(struct kevent* pos = s_platform.koutput.data(); pos != end; ++pos) // iterate through results results.emplace_back(std::make_pair(posix::fd_t(pos->ident), platform_dependant::composite_flag(pos->filter, pos->flags))); return true; } #elif defined(__sun) && defined(__SVR4) // Solaris / OpenSolaris / OpenIndiana / illumos #pragma message Not implemented, yet! #pragma message See: http://docs.oracle.com/cd/E19253-01/816-5168/port-get-3c/index.html #error The backend code in PDTK for Solaris / OpenSolaris / OpenIndiana / illumos is non-functional! Please submit a patch! // Solaris #include <port.h> // POSIX #include <sys/socket.h> #include <unistd.h> // POSIX++ #include <cstdlib> #include <cstdio> #include <climits> #include <cstring> // STL #include <vector> // PDTK #include <cxxutils/vterm.h> #include <cxxutils/error_helpers.h> struct platform_dependant { posix::fd_t port; std::vector<port_event_t> pinput; // events we want to monitor std::vector<port_event_t> poutput; // events that were triggered platform_dependant(void) { port = ::port_create(); flaw(port == posix::error_response, terminal::critical, std::exit(errno),, "Unable to create a new kqueue: %s", std::strerror(errno)) pinput .reserve(1024); poutput.reserve(1024); } ~platform_dependant(void) { posix::close(port); } } EventBackend::s_platform; bool EventBackend::add(posix::fd_t fd, native_flags_t flags, callback_t function) noexcept { port_event_t pev; s_platform.pinput.push_back(pev); queue.emplace(fd, (callback_info_t){flags, function}); return true; } bool EventBackend::remove(posix::fd_t fd) noexcept { return false; } bool EventBackend::poll(int timeout) noexcept { native_flags_t flags; uint_t count = 0; timespec tout; tout.tv_sec = timeout / 1000; tout.tv_nsec = (timeout % 1000) * 1000; if(::port_getn(s_platform.port, &s_platform.pinput.data(), s_platform.pinput.size(), s_platform.poutput, MAX_EVENTS, &count &tout) == posix::error_response) return false; port_event_t* end = s_platform.poutput + count; for(port_event_t* pos = s_platform.poutput; pos != end; ++pos) // iterate through results { //flags = from_kevent(*pos); results.emplace(posix::fd_t(pos->ident), flags); } return true; } #elif defined(__minix) // MINIX #error No event backend code exists in PDTK for MINIX! Please submit a patch! #elif defined(__QNX__) // QNX // QNX docs: http://www.qnx.com/developers/docs/7.0.0/index.html#com.qnx.doc.neutrino.devctl/topic/about.html #error No event backend code exists in PDTK for QNX! Please submit a patch! #elif defined(__hpux) // HP-UX // see http://nixdoc.net/man-pages/HP-UX/man7/poll.7.html // and https://www.freebsd.org/cgi/man.cgi?query=poll&sektion=7&apropos=0&manpath=HP-UX+11.22 // uses /dev/poll #error No event backend code exists in PDTK for HP-UX! Please submit a patch! #include <sys/devpoll.h> #elif defined(_AIX) // IBM AIX // see https://www.ibm.com/support/knowledgecenter/ssw_aix_61/com.ibm.aix.basetrf1/pollset.htm // uses pollset_* functions #include <sys/poll.h> #include <sys/pollset.h> pollset_t n; n = pollset_create(-1); pollset_destroy(n); #error No event backend code exists in PDTK for IBM AIX! Please submit a patch! #elif defined(BSD) #error Unrecognized BSD derivative! #elif defined(__unix__) #error Unrecognized UNIX variant! #else #error This platform is not supported. #endif bool EventBackend::add(posix::fd_t fd, native_flags_t flags, callback_t function) noexcept { native_flags_t total_flags = flags; bool found = false; auto entries = queue.equal_range(fd); // find modified entry! for(auto& pos = entries.first; pos != entries.second; ++pos) { total_flags |= pos->second.flags; found |= &(pos->second.function) == &function; // save if function was ever found if(&(pos->second.function) == &function) // if the FD is in the queue and it's callback function matches pos->second.flags |= flags; // simply modify the flags to include the current } if(!found) // function wasn't found queue.emplace(fd, (callback_info_t){flags, function}); // make a new entry for this FD return s_platform.add(fd, total_flags); } bool EventBackend::remove(posix::fd_t fd, native_flags_t flags) noexcept { native_flags_t remaining_flags = 0; auto entries = queue.equal_range(fd); // find modified entry! for(auto& pos = entries.first; pos != entries.second; ++pos) { if((pos->second.flags & flags) == pos->second.flags) // if all flags match queue.erase(pos); else if(pos->second.flags & flags) // if only some flags match { pos->second.flags ^= pos->second.flags & flags; // remove flags remaining_flags |= pos->second.flags; // accumulate remaining flags } } return remaining_flags ? s_platform.add(fd, remaining_flags) : s_platform.remove(fd); } <commit_msg>fix flag compiter<commit_after>#include "eventbackend.h" #define MAX_EVENTS 1024 // PDTK #include <cxxutils/vterm.h> lockable<std::unordered_multimap<posix::fd_t, EventBackend::callback_info_t>> EventBackend::queue; std::list<std::pair<posix::fd_t, native_flags_t>> EventBackend::results; #if defined(__linux__) // epoll needs kernel 2.5.44 // Linux #include <sys/epoll.h> struct EventBackend::platform_dependant // poll notification (epoll) { posix::fd_t fd; struct epoll_event output[MAX_EVENTS]; platform_dependant(void) noexcept : fd(posix::invalid_descriptor) { fd = ::epoll_create(MAX_EVENTS); flaw(fd == posix::invalid_descriptor, terminal::critical, std::exit(errno),, "Unable to create an instance of epoll! %s", std::strerror(errno)) } ~platform_dependant(void) noexcept { posix::close(fd); fd = posix::invalid_descriptor; } bool add(posix::fd_t wd, native_flags_t flags) noexcept { struct epoll_event native_event; native_event.data.fd = wd; native_event.events = flags; // be sure to convert to native events return ::epoll_ctl(fd, EPOLL_CTL_ADD, wd, &native_event) == posix::success_response || // add new event OR (errno == EEXIST && ::epoll_ctl(fd, EPOLL_CTL_MOD, wd, &native_event) == posix::success_response); // modify existing event } bool remove(posix::fd_t wd) noexcept { struct epoll_event event; return ::epoll_ctl(fd, EPOLL_CTL_DEL, wd, &event) == posix::success_response; // try to delete entry } } EventBackend::s_platform; const native_flags_t EventBackend::SimplePollReadFlags = EPOLLIN; bool EventBackend::poll(int timeout) noexcept { int count = ::epoll_wait(s_platform.fd, s_platform.output, MAX_EVENTS, timeout); // wait for new results results.clear(); // clear old results if(count == posix::error_response) // if error/timeout occurred return false; //fail const epoll_event* end = s_platform.output + count; for(epoll_event* pos = s_platform.output; pos != end; ++pos) // iterate through results results.emplace_back(std::make_pair(posix::fd_t(pos->data.fd), native_flags_t(pos->events))); // save result (in native format) return true; } #elif defined(__APPLE__) /* Darwin 7+ */ || \ defined(__FreeBSD__) /* FreeBSD 4.1+ */ || \ defined(__DragonFly__) /* DragonFly BSD */ || \ defined(__OpenBSD__) /* OpenBSD 2.9+ */ || \ defined(__NetBSD__) /* NetBSD 2+ */ // BSD #include <sys/time.h> #include <sys/event.h> // POSIX #include <sys/socket.h> #include <unistd.h> // POSIX++ #include <cstdlib> #include <cstdio> #include <climits> #include <cstring> // STL #include <vector> #include <algorithm> #include <iterator> // PDTK #include <cxxutils/vterm.h> #include <cxxutils/error_helpers.h> struct EventBackend::platform_dependant // poll notification (epoll) { posix::fd_t kq; std::vector<struct kevent> koutput; // events that were triggered static constexpr native_flags_t composite_flag(uint16_t actions, int16_t filters, uint32_t flags) noexcept { return native_flags_t(actions) | (uint16_t(filters) << 16) | (flags << 32); } static constexpr short extract_actions(native_flags_t flags) noexcept { return flags & 0xFFFF; } static constexpr ushort extract_filter(native_flags_t flags) noexcept { return (flags >> 16) & 0xFFFF; } static constexpr ushort extract_flags(native_flags_t flags) noexcept { return flags >> 32; } platform_dependant(void) { kq = posix::ignore_interruption(::kqueue); flaw(kq == posix::error_response, terminal::critical, std::exit(errno),, "Unable to create a new kqueue: %s", std::strerror(errno)) koutput.resize(1024); } ~platform_dependant(void) { posix::close(kq); } bool add(posix::fd_t fd, native_flags_t flags) noexcept { struct kevent ev; EV_SET(&ev, fd, extract_filter(flags), EV_ADD | extract_actions(flags), extract_flags(flags), 0, nullptr); return kevent(kq, &ev, 1, nullptr, 0, nullptr) == posix::success_response; } bool remove(posix::fd_t fd) noexcept { struct kevent ev; EV_SET(&ev, fd, 0, EV_DELETE, 0, 0, nullptr); return kevent(kq, &ev, 1, nullptr, 0, nullptr) == posix::success_response; } } EventBackend::s_platform; const native_flags_t EventBackend::SimplePollReadFlags = platform_dependant::composite_flag(0, EVFILT_READ, 0); bool EventBackend::poll(int timeout) noexcept { uint32_t data; timespec tout; tout.tv_sec = timeout / 1000; tout.tv_nsec = (timeout % 1000) * 1000; int count = kevent(s_platform.kq, nullptr, 0, s_platform.koutput.data(), s_platform.koutput.size(), &tout); if(count <= 0) return false; struct kevent* end = s_platform.koutput.data() + count; for(struct kevent* pos = s_platform.koutput.data(); pos != end; ++pos) // iterate through results results.emplace_back(std::make_pair(posix::fd_t(pos->ident), platform_dependant::composite_flag(pos->flags, pos->filter, pos->fflags))); return true; } #elif defined(__sun) && defined(__SVR4) // Solaris / OpenSolaris / OpenIndiana / illumos #pragma message Not implemented, yet! #pragma message See: http://docs.oracle.com/cd/E19253-01/816-5168/port-get-3c/index.html #error The backend code in PDTK for Solaris / OpenSolaris / OpenIndiana / illumos is non-functional! Please submit a patch! // Solaris #include <port.h> // POSIX #include <sys/socket.h> #include <unistd.h> // POSIX++ #include <cstdlib> #include <cstdio> #include <climits> #include <cstring> // STL #include <vector> // PDTK #include <cxxutils/vterm.h> #include <cxxutils/error_helpers.h> struct platform_dependant { posix::fd_t port; std::vector<port_event_t> pinput; // events we want to monitor std::vector<port_event_t> poutput; // events that were triggered platform_dependant(void) { port = ::port_create(); flaw(port == posix::error_response, terminal::critical, std::exit(errno),, "Unable to create a new kqueue: %s", std::strerror(errno)) pinput .reserve(1024); poutput.reserve(1024); } ~platform_dependant(void) { posix::close(port); } } EventBackend::s_platform; bool EventBackend::add(posix::fd_t fd, native_flags_t flags, callback_t function) noexcept { port_event_t pev; s_platform.pinput.push_back(pev); queue.emplace(fd, (callback_info_t){flags, function}); return true; } bool EventBackend::remove(posix::fd_t fd) noexcept { return false; } bool EventBackend::poll(int timeout) noexcept { native_flags_t flags; uint_t count = 0; timespec tout; tout.tv_sec = timeout / 1000; tout.tv_nsec = (timeout % 1000) * 1000; if(::port_getn(s_platform.port, &s_platform.pinput.data(), s_platform.pinput.size(), s_platform.poutput, MAX_EVENTS, &count &tout) == posix::error_response) return false; port_event_t* end = s_platform.poutput + count; for(port_event_t* pos = s_platform.poutput; pos != end; ++pos) // iterate through results { //flags = from_kevent(*pos); results.emplace(posix::fd_t(pos->ident), flags); } return true; } #elif defined(__minix) // MINIX #error No event backend code exists in PDTK for MINIX! Please submit a patch! #elif defined(__QNX__) // QNX // QNX docs: http://www.qnx.com/developers/docs/7.0.0/index.html#com.qnx.doc.neutrino.devctl/topic/about.html #error No event backend code exists in PDTK for QNX! Please submit a patch! #elif defined(__hpux) // HP-UX // see http://nixdoc.net/man-pages/HP-UX/man7/poll.7.html // and https://www.freebsd.org/cgi/man.cgi?query=poll&sektion=7&apropos=0&manpath=HP-UX+11.22 // uses /dev/poll #error No event backend code exists in PDTK for HP-UX! Please submit a patch! #include <sys/devpoll.h> #elif defined(_AIX) // IBM AIX // see https://www.ibm.com/support/knowledgecenter/ssw_aix_61/com.ibm.aix.basetrf1/pollset.htm // uses pollset_* functions #include <sys/poll.h> #include <sys/pollset.h> pollset_t n; n = pollset_create(-1); pollset_destroy(n); #error No event backend code exists in PDTK for IBM AIX! Please submit a patch! #elif defined(BSD) #error Unrecognized BSD derivative! #elif defined(__unix__) #error Unrecognized UNIX variant! #else #error This platform is not supported. #endif bool EventBackend::add(posix::fd_t fd, native_flags_t flags, callback_t function) noexcept { native_flags_t total_flags = flags; bool found = false; auto entries = queue.equal_range(fd); // find modified entry! for(auto& pos = entries.first; pos != entries.second; ++pos) { total_flags |= pos->second.flags; found |= &(pos->second.function) == &function; // save if function was ever found if(&(pos->second.function) == &function) // if the FD is in the queue and it's callback function matches pos->second.flags |= flags; // simply modify the flags to include the current } if(!found) // function wasn't found queue.emplace(fd, (callback_info_t){flags, function}); // make a new entry for this FD return s_platform.add(fd, total_flags); } bool EventBackend::remove(posix::fd_t fd, native_flags_t flags) noexcept { native_flags_t remaining_flags = 0; auto entries = queue.equal_range(fd); // find modified entry! for(auto& pos = entries.first; pos != entries.second; ++pos) { if((pos->second.flags & flags) == pos->second.flags) // if all flags match queue.erase(pos); else if(pos->second.flags & flags) // if only some flags match { pos->second.flags ^= pos->second.flags & flags; // remove flags remaining_flags |= pos->second.flags; // accumulate remaining flags } } return remaining_flags ? s_platform.add(fd, remaining_flags) : s_platform.remove(fd); } <|endoftext|>
<commit_before>#include <bits/stdc++.h> using namespace std; long long horner(int n, int c[], int x) { long long res = c[0]; for(int i=0; i<n; i++) res = res*x + c[i+1]; return res; } int main() { unsigned k, cases = 0; int n, x, coe[1001]; ios_base::sync_with_stdio(0); // polynomial while(cin >> n) { if(n == -1) break; cout << "Case " << ++cases << ":\n"; for(int i=0; i<=n; i++) cin >> coe[i]; // points cin >> k; while(k--) { cin >> x; cout << horner(n, coe, x) << "\n"; } } return 0; }<commit_msg>spoj/00-classical/POLEVAL.cc<commit_after>#include <bits/stdc++.h> using namespace std; long long horner(int n, int c[], int x) { long long res = c[0]; for(int i=0; i<n; i++) res = res*x + c[i+1]; return res; } int main() { int n, x, coe[1001]; unsigned k, cases = 0; cin.tie(NULL); ios_base::sync_with_stdio(0); // polynomial while(cin >> n) { if(n == -1) break; cout << "Case " << ++cases << ":\n"; for(int i=0; i<=n; i++) cin >> coe[i]; // points cin >> k; while(k--) { cin >> x; cout << horner(n, coe, x) << "\n"; } } return 0; }<|endoftext|>
<commit_before>/* ndhs.c - DHCPv4/DHCPv6 and IPv6 router advertisement server * * Copyright 2014-2017 Nicholas J. Kain <njkain at gmail dot com> * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #define NDHS_VERSION "2.0" #define LEASEFILE_PATH "/store/dynlease.txt" #include <memory> #include <string> #include <vector> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/stat.h> #include <fcntl.h> #include <ctype.h> #include <pwd.h> #include <grp.h> #include <signal.h> #include <errno.h> #include <asio.hpp> #include <fmt/format.h> #include <nk/optionarg.hpp> #include <nk/from_string.hpp> #include <nk/prng.hpp> extern "C" { #include "nk/log.h" #include "nk/privs.h" } #include "nlsocket.hpp" #include "dhcp6.hpp" #include "dhcp4.hpp" #include "dhcp_state.hpp" #include "dynlease.hpp" #include "duid.hpp" static asio::io_service io_service; static asio::signal_set asio_signal_set(io_service); static std::string configfile{"/etc/ndhs.conf"}; static std::string chroot_path; static uid_t ndhs_uid; static gid_t ndhs_gid; std::unique_ptr<NLSocket> nl_socket; static std::vector<std::unique_ptr<D6Listener>> v6_listeners; static std::vector<std::unique_ptr<D4Listener>> v4_listeners; extern void parse_config(const std::string &path); static void init_listeners() { auto v6l = &v6_listeners; auto v4l = &v4_listeners; bound_interfaces_foreach([v6l, v4l](const std::string &i, bool use_v4, bool use_v6, uint8_t preference) { if (use_v6) { v6l->emplace_back(std::make_unique<D6Listener>()); if (!v6l->back()->init(i, preference)) { v6l->pop_back(); fmt::print(stderr, "Can't bind to v6 interface: {}\n", i); } } if (use_v4) { v4l->emplace_back(std::make_unique<D4Listener>()); if (!v4l->back()->init(i)) { v4l->pop_back(); fmt::print(stderr, "Can't bind to v4 interface: {}\n", i); } } }); } int64_t get_current_ts() { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) suicide("clock_gettime failed"); return ts.tv_sec; } void set_user_runas(size_t /* linenum */, std::string &&username) { if (nk_uidgidbyname(username.c_str(), &ndhs_uid, &ndhs_gid)) { fmt::print(stderr, "invalid user '{}' specified\n", username); std::exit(EXIT_FAILURE); } } void set_chroot_path(size_t /* linenum */, std::string &&path) { chroot_path = std::move(path); } static void process_signals() { sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGCHLD); sigaddset(&mask, SIGPIPE); sigaddset(&mask, SIGUSR1); sigaddset(&mask, SIGUSR2); sigaddset(&mask, SIGTSTP); sigaddset(&mask, SIGTTIN); sigaddset(&mask, SIGHUP); if (sigprocmask(SIG_BLOCK, &mask, nullptr) < 0) { fmt::print(stderr, "sigprocmask failed\n"); std::exit(EXIT_FAILURE); } asio_signal_set.add(SIGINT); asio_signal_set.add(SIGTERM); asio_signal_set.async_wait([](const std::error_code &, int) { io_service.stop(); }); } static void print_version(void) { fmt::print(stderr, "ndhs " NDHS_VERSION ", ipv6 router advertisment and dhcp server.\n" "Copyright 2014-2017 Nicholas J. Kain\n" "All rights reserved.\n\n" "Redistribution and use in source and binary forms, with or without\n" "modification, are permitted provided that the following conditions are met:\n\n" "- Redistributions of source code must retain the above copyright notice,\n" " this list of conditions and the following disclaimer.\n" "- Redistributions in binary form must reproduce the above copyright notice,\n" " this list of conditions and the following disclaimer in the documentation\n" " and/or other materials provided with the distribution.\n\n" "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n" "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n" "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n" "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n" "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n" "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n" "CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n" "ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n" "POSSIBILITY OF SUCH DAMAGE.\n"); } enum OpIdx { OPT_UNKNOWN, OPT_HELP, OPT_VERSION, OPT_CONFIG, OPT_QUIET }; static const option::Descriptor usage[] = { { OPT_UNKNOWN, 0, "", "", Arg::Unknown, "ndhs " NDHS_VERSION ", DHCPv4/DHCPv6 and IPv6 Router Advertisement server.\n" "Copyright 2014-2017 Nicholas J. Kain\n" "ndhs [options] [configfile]...\n\nOptions:" }, { OPT_HELP, 0, "h", "help", Arg::None, "\t-h, \t--help \tPrint usage and exit." }, { OPT_VERSION, 0, "v", "version", Arg::None, "\t-v, \t--version \tPrint version and exit." }, { OPT_CONFIG, 0, "c", "config", Arg::String, "\t-c, \t--config \tPath to configuration file (default: /etc/ndhs.conf)."}, { OPT_QUIET, 0, "q", "quiet", Arg::None, "\t-q, \t--quiet \tDon't log to std(out|err) or syslog." }, {0,0,0,0,0,0} }; static void process_options(int ac, char *av[]) { ac-=ac>0; av+=ac>0; option::Stats stats(usage, ac, av); #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wvla" option::Option options[stats.options_max], buffer[stats.buffer_max]; #pragma GCC diagnostic pop option::Parser parse(usage, ac, av, options, buffer); #else auto options = std::make_unique<option::Option[]>(stats.options_max); auto buffer = std::make_unique<option::Option[]>(stats.buffer_max); option::Parser parse(usage, ac, av, options.get(), buffer.get()); #endif if (parse.error()) std::exit(EXIT_FAILURE); if (options[OPT_HELP]) { uint16_t col{80}; if (const auto cols = getenv("COLUMNS")) { if (auto t = nk::from_string<uint16_t>(cols)) col = *t; } option::printUsage(fwrite, stdout, usage, col); std::exit(EXIT_FAILURE); } if (options[OPT_VERSION]) { print_version(); std::exit(EXIT_FAILURE); } std::vector<std::string> addrlist; for (int i = 0; i < parse.optionsCount(); ++i) { option::Option &opt = buffer[i]; switch (opt.index()) { case OPT_CONFIG: configfile = std::string(opt.arg); break; case OPT_QUIET: gflags_quiet = 1; break; } } if (configfile.size()) parse_config(configfile); for (int i = 0; i < parse.nonOptionsCount(); ++i) parse_config(parse.nonOption(i)); if (!bound_interfaces_count()) { fmt::print(stderr, "No interfaces have been bound\n"); std::exit(EXIT_FAILURE); } if (!ndhs_uid || !ndhs_gid) { fmt::print(stderr, "No non-root user account is specified.\n"); std::exit(EXIT_FAILURE); } if (chroot_path.empty()) { fmt::print(stderr, "No chroot path is specified.\n"); std::exit(EXIT_FAILURE); } nl_socket = std::make_unique<NLSocket>(); init_listeners(); umask(077); process_signals(); nk_set_chroot(chroot_path.c_str()); duid_load_from_file(); dynlease_deserialize(LEASEFILE_PATH); nk_set_uidgid(ndhs_uid, ndhs_gid, nullptr, 0); } int main(int ac, char *av[]) { gflags_log_name = const_cast<char *>("ndhs"); process_options(ac, av); io_service.run(); dynlease_serialize(LEASEFILE_PATH); std::exit(EXIT_SUCCESS); } <commit_msg>ndhs: Remove asio::io_service and just use poll and posix signal api.<commit_after>/* ndhs.c - DHCPv4/DHCPv6 and IPv6 router advertisement server * * Copyright 2014-2020 Nicholas J. Kain <njkain at gmail dot com> * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #define NDHS_VERSION "2.0" #define LEASEFILE_PATH "/store/dynlease.txt" #include <memory> #include <string> #include <vector> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <fcntl.h> #include <ctype.h> #include <pwd.h> #include <grp.h> #include <signal.h> #include <poll.h> #include <errno.h> #include <fmt/format.h> #include <nk/optionarg.hpp> #include <nk/from_string.hpp> extern "C" { #include "nk/log.h" #include "nk/privs.h" } #include "nlsocket.hpp" #include "dhcp6.hpp" #include "dhcp4.hpp" #include "dhcp_state.hpp" #include "dynlease.hpp" #include "duid.hpp" static std::string configfile{"/etc/ndhs.conf"}; static std::string chroot_path; static uid_t ndhs_uid; static gid_t ndhs_gid; std::unique_ptr<NLSocket> nl_socket; static std::vector<std::unique_ptr<D6Listener>> v6_listeners; static std::vector<std::unique_ptr<D4Listener>> v4_listeners; extern void parse_config(const std::string &path); static void init_listeners() { auto v6l = &v6_listeners; auto v4l = &v4_listeners; bound_interfaces_foreach([v6l, v4l](const std::string &i, bool use_v4, bool use_v6, uint8_t preference) { if (use_v6) { v6l->emplace_back(std::make_unique<D6Listener>()); if (!v6l->back()->init(i, preference)) { v6l->pop_back(); fmt::print(stderr, "Can't bind to v6 interface: {}\n", i); } } if (use_v4) { v4l->emplace_back(std::make_unique<D4Listener>()); if (!v4l->back()->init(i)) { v4l->pop_back(); fmt::print(stderr, "Can't bind to v4 interface: {}\n", i); } } }); } int64_t get_current_ts() { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) suicide("clock_gettime failed"); return ts.tv_sec; } void set_user_runas(size_t /* linenum */, std::string &&username) { if (nk_uidgidbyname(username.c_str(), &ndhs_uid, &ndhs_gid)) { fmt::print(stderr, "invalid user '{}' specified\n", username); std::exit(EXIT_FAILURE); } } void set_chroot_path(size_t /* linenum */, std::string &&path) { chroot_path = std::move(path); } static volatile sig_atomic_t l_signal_exit; static void signal_handler(int signo) { switch (signo) { case SIGCHLD: { while (waitpid(-1, nullptr, WNOHANG) > -1); break; } case SIGINT: case SIGTERM: l_signal_exit = 1; break; default: break; } } static void setup_signals_ndhs() { static const int ss[] = { SIGCHLD, SIGINT, SIGTERM, SIGKILL }; sigset_t mask; if (sigprocmask(0, 0, &mask) < 0) suicide("sigprocmask failed"); for (int i = 0; ss[i] != SIGKILL; ++i) if (sigdelset(&mask, ss[i])) suicide("sigdelset failed"); if (sigaddset(&mask, SIGPIPE)) suicide("sigaddset failed"); if (sigprocmask(SIG_SETMASK, &mask, static_cast<sigset_t *>(nullptr)) < 0) suicide("sigprocmask failed"); struct sigaction sa; memset(&sa, 0, sizeof sa); sa.sa_handler = signal_handler; sa.sa_flags = SA_RESTART; if (sigemptyset(&sa.sa_mask)) suicide("sigemptyset failed"); for (int i = 0; ss[i] != SIGKILL; ++i) if (sigaction(ss[i], &sa, NULL)) suicide("sigaction failed"); } static void print_version(void) { fmt::print(stderr, "ndhs " NDHS_VERSION ", ipv6 router advertisment and dhcp server.\n" "Copyright 2014-2017 Nicholas J. Kain\n" "All rights reserved.\n\n" "Redistribution and use in source and binary forms, with or without\n" "modification, are permitted provided that the following conditions are met:\n\n" "- Redistributions of source code must retain the above copyright notice,\n" " this list of conditions and the following disclaimer.\n" "- Redistributions in binary form must reproduce the above copyright notice,\n" " this list of conditions and the following disclaimer in the documentation\n" " and/or other materials provided with the distribution.\n\n" "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n" "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n" "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n" "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n" "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n" "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n" "CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n" "ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n" "POSSIBILITY OF SUCH DAMAGE.\n"); } enum OpIdx { OPT_UNKNOWN, OPT_HELP, OPT_VERSION, OPT_CONFIG, OPT_QUIET }; static const option::Descriptor usage[] = { { OPT_UNKNOWN, 0, "", "", Arg::Unknown, "ndhs " NDHS_VERSION ", DHCPv4/DHCPv6 and IPv6 Router Advertisement server.\n" "Copyright 2014-2017 Nicholas J. Kain\n" "ndhs [options] [configfile]...\n\nOptions:" }, { OPT_HELP, 0, "h", "help", Arg::None, "\t-h, \t--help \tPrint usage and exit." }, { OPT_VERSION, 0, "v", "version", Arg::None, "\t-v, \t--version \tPrint version and exit." }, { OPT_CONFIG, 0, "c", "config", Arg::String, "\t-c, \t--config \tPath to configuration file (default: /etc/ndhs.conf)."}, { OPT_QUIET, 0, "q", "quiet", Arg::None, "\t-q, \t--quiet \tDon't log to std(out|err) or syslog." }, {0,0,0,0,0,0} }; static void process_options(int ac, char *av[]) { ac-=ac>0; av+=ac>0; option::Stats stats(usage, ac, av); #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wvla" option::Option options[stats.options_max], buffer[stats.buffer_max]; #pragma GCC diagnostic pop option::Parser parse(usage, ac, av, options, buffer); #else auto options = std::make_unique<option::Option[]>(stats.options_max); auto buffer = std::make_unique<option::Option[]>(stats.buffer_max); option::Parser parse(usage, ac, av, options.get(), buffer.get()); #endif if (parse.error()) std::exit(EXIT_FAILURE); if (options[OPT_HELP]) { uint16_t col{80}; if (const auto cols = getenv("COLUMNS")) { if (auto t = nk::from_string<uint16_t>(cols)) col = *t; } option::printUsage(fwrite, stdout, usage, col); std::exit(EXIT_FAILURE); } if (options[OPT_VERSION]) { print_version(); std::exit(EXIT_FAILURE); } std::vector<std::string> addrlist; for (int i = 0; i < parse.optionsCount(); ++i) { option::Option &opt = buffer[i]; switch (opt.index()) { case OPT_CONFIG: configfile = std::string(opt.arg); break; case OPT_QUIET: gflags_quiet = 1; break; } } if (configfile.size()) parse_config(configfile); for (int i = 0; i < parse.nonOptionsCount(); ++i) parse_config(parse.nonOption(i)); if (!bound_interfaces_count()) { fmt::print(stderr, "No interfaces have been bound\n"); std::exit(EXIT_FAILURE); } if (!ndhs_uid || !ndhs_gid) { fmt::print(stderr, "No non-root user account is specified.\n"); std::exit(EXIT_FAILURE); } if (chroot_path.empty()) { fmt::print(stderr, "No chroot path is specified.\n"); std::exit(EXIT_FAILURE); } nl_socket = std::make_unique<NLSocket>(); init_listeners(); umask(077); setup_signals_ndhs(); nk_set_chroot(chroot_path.c_str()); duid_load_from_file(); dynlease_deserialize(LEASEFILE_PATH); nk_set_uidgid(ndhs_uid, ndhs_gid, nullptr, 0); } int main(int ac, char *av[]) { gflags_log_name = const_cast<char *>("ndhs"); process_options(ac, av); struct pollfd pfds[1]; memset(pfds, 0, sizeof pfds); pfds[0].fd = -1; pfds[0].events = POLLIN|POLLHUP|POLLERR|POLLRDHUP; for (;;) { if (poll(pfds, 1, -1) < 0) { if (errno != EINTR) suicide("poll failed"); } if (l_signal_exit) break; } dynlease_serialize(LEASEFILE_PATH); std::exit(EXIT_SUCCESS); } <|endoftext|>
<commit_before>#include "plot.h" #include "curvedata.h" #include "signaldata.h" #include <qwt_plot_grid.h> #include <qwt_plot_layout.h> #include <qwt_plot_canvas.h> #include <qwt_plot_marker.h> #include <qwt_plot_curve.h> #include <qwt_plot_directpainter.h> #include <qwt_curve_fitter.h> #include <qwt_painter.h> #include <qwt_scale_engine.h> #include <qwt_scale_draw.h> #include <qwt_plot_zoomer.h> #include <qwt_plot_panner.h> #include <qwt_plot_magnifier.h> #include <qwt_text.h> #include <qevent.h> #include <cassert> #define DEFAULT_CURVE_STYLE QwtPlotCurve::Dots class MyPanner : public QObject { public: QPoint mInitialPos; bool mEnabled; int mMouseButton; int mKeyboardButton; Plot* mPlot; MyPanner(Plot* plot) : QObject(plot) { mEnabled = false; mMouseButton = Qt::LeftButton; mKeyboardButton = Qt::NoButton; mPlot = plot; mPlot->canvas()->installEventFilter(this); } bool eventFilter( QObject *object, QEvent *event ) { switch ( event->type() ) { case QEvent::MouseButtonPress: { widgetMousePressEvent( ( QMouseEvent * )event ); break; } case QEvent::MouseMove: { widgetMouseMoveEvent( ( QMouseEvent * )event ); break; } case QEvent::MouseButtonRelease: { widgetMouseReleaseEvent( ( QMouseEvent * )event ); break; } } return false; } void moveCanvas( int dx, int dy ) { if ( dx == 0 && dy == 0 ) return; if (!mPlot->isStopped()) dx = 0; for ( int axis = 0; axis < QwtPlot::axisCnt; axis++ ) { const QwtScaleMap map = mPlot->canvasMap( axis ); const double p1 = map.transform( mPlot->axisScaleDiv( axis )->lowerBound() ); const double p2 = map.transform( mPlot->axisScaleDiv( axis )->upperBound() ); double d1, d2; if ( axis == QwtPlot::xBottom || axis == QwtPlot::xTop ) { d1 = map.invTransform( p1 - dx ); d2 = map.invTransform( p2 - dx ); } else { d1 = map.invTransform( p1 - dy ); d2 = map.invTransform( p2 - dy ); } mPlot->setAxisScale( axis, d1, d2 ); } mPlot->flagAxisSyncRequired(); mPlot->replot(); } void widgetMousePressEvent( QMouseEvent *mouseEvent ) { if (mouseEvent->button() != mMouseButton) { return; } if ((mouseEvent->modifiers() & Qt::KeyboardModifierMask) != (mKeyboardButton & Qt::KeyboardModifierMask)) { return; } mInitialPos = mouseEvent->pos(); mEnabled = true; } void widgetMouseMoveEvent( QMouseEvent *mouseEvent ) { if (!mEnabled) return; QPoint pos = mouseEvent->pos(); if (pos != mInitialPos) { moveCanvas(pos.x() - mInitialPos.x(), pos.y() - mInitialPos.y()); mInitialPos = mouseEvent->pos(); } } void widgetMouseReleaseEvent( QMouseEvent *mouseEvent ) { mEnabled = false; } }; class MyScaleDraw : public QwtScaleDraw { virtual QwtText label(double value) const { return QString::number(value, 'f', 2); } }; class MyZoomer: public QwtPlotZoomer { public: Plot* mPlot; MyZoomer(Plot *plot) : QwtPlotZoomer(plot->canvas()) { mPlot = plot; setTrackerMode(AlwaysOn); } virtual QwtText trackerTextF(const QPointF &pos) const { QColor bg(Qt::white); bg.setAlpha(200); QwtText text = QwtPlotZoomer::trackerTextF(pos); text.setBackgroundBrush( QBrush( bg )); return text; } protected: virtual void rescale() { mPlot->flagAxisSyncRequired(); QwtPlotZoomer::rescale(); } }; class MyMagnifier: public QwtPlotMagnifier { public: Plot* mPlot; MyMagnifier(Plot* plot) : QwtPlotMagnifier(plot->canvas()) { mPlot = plot; } protected: // Normally, a value < 1.0 zooms in, a value > 1.0 zooms out. // This function is overloaded to invert the magnification direction. virtual void rescale( double factor ) { factor = qAbs( factor ); factor = (1-factor) + 1; mPlot->flagAxisSyncRequired(); this->QwtPlotMagnifier::rescale(factor); } }; Plot::Plot(QWidget *parent): QwtPlot(parent), d_origin(0), d_grid(0), mStopped(true), mAxisSyncRequired(false), mColorMode(0), mTimeWindow(10.0) { setAutoReplot(false); // The backing store is important, when working with widget // overlays ( f.e rubberbands for zooming ). // Here we don't have them and the internal // backing store of QWidget is good enough. canvas()->setPaintAttribute(QwtPlotCanvas::BackingStore, false); #if defined(Q_WS_X11) // Even if not recommended by TrollTech, Qt::WA_PaintOutsidePaintEvent // works on X11. This has a nice effect on the performance. canvas()->setAttribute(Qt::WA_PaintOutsidePaintEvent, true); // Disabling the backing store of Qt improves the performance // for the direct painter even more, but the canvas becomes // a native window of the window system, receiving paint events // for resize and expose operations. Those might be expensive // when there are many points and the backing store of // the canvas is disabled. So in this application // we better don't both backing stores. if ( canvas()->testPaintAttribute( QwtPlotCanvas::BackingStore ) ) { canvas()->setAttribute(Qt::WA_PaintOnScreen, true); canvas()->setAttribute(Qt::WA_NoSystemBackground, true); } #endif plotLayout()->setAlignCanvasToScales(true); setAxisAutoScale(QwtPlot::xBottom, false); setAxisAutoScale(QwtPlot::yLeft, false); setAxisTitle(QwtPlot::xBottom, "Time [s]"); setAxisScale(QwtPlot::xBottom, 0, 10); setAxisScale(QwtPlot::yLeft, -4.0, 4.0); setAxisScaleDraw(QwtPlot::xBottom, new MyScaleDraw); initBackground(); QwtPlotZoomer* zoomer = new MyZoomer(this); zoomer->setMousePattern(QwtEventPattern::QwtEventPattern::MouseSelect1, Qt::LeftButton, Qt::ShiftModifier); // disable MouseSelect3 action of the zoomer zoomer->setMousePattern(QwtEventPattern::MouseSelect3, 0); MyPanner *panner = new MyPanner(this); // zoom in/out with the wheel mMagnifier = new MyMagnifier(this); mMagnifier->setMouseButton(Qt::MiddleButton); const QColor c(Qt::darkBlue); zoomer->setRubberBandPen(c); zoomer->setTrackerPen(c); this->setMinimumHeight(200); } Plot::~Plot() { } void Plot::addSignal(SignalData* signalData, QColor color) { QwtPlotCurve* d_curve = new QwtPlotCurve(); d_curve->setStyle(DEFAULT_CURVE_STYLE); QPen curvePen(color); curvePen.setWidth(0); d_curve->setPen(curvePen); #if 1 d_curve->setRenderHint(QwtPlotItem::RenderAntialiased, true); #endif #if 1 d_curve->setPaintAttribute(QwtPlotCurve::ClipPolygons, false); #endif d_curve->setData(new CurveData(signalData)); d_curve->attach(this); mSignals[signalData] = d_curve; } void Plot::removeSignal(SignalData* signalData) { if (!signalData) { return; } QwtPlotCurve* curve = mSignals.value(signalData); assert(curve); curve->detach(); delete curve; mSignals.remove(signalData); } void Plot::setSignalVisible(SignalData* signalData, bool visible) { if (!signalData) { return; } QwtPlotCurve* curve = mSignals.value(signalData); assert(curve); if (visible) { curve->attach(this); } else { curve->detach(); } this->replot(); } void Plot::setSignalColor(SignalData* signalData, QColor color) { if (!signalData) { return; } QwtPlotCurve* curve = mSignals.value(signalData); assert(curve); curve->setPen(QPen(color)); } void Plot::setPointSize(double pointSize) { foreach (QwtPlotCurve* curve, mSignals.values()) { QPen curvePen = curve->pen(); curvePen.setWidth(pointSize); curve->setPen(curvePen); } } void Plot::setCurveStyle(QwtPlotCurve::CurveStyle style) { foreach (QwtPlotCurve* curve, mSignals.values()) { curve->setStyle(style); } } void Plot::setBackgroundColor(QString color) { if (color == "White") { mColorMode = 0; } else if (color == "Black") { mColorMode = 1; } this->initBackground(); } void Plot::initBackground() { if (!d_grid) { d_grid = new QwtPlotGrid(); d_grid->enableX(false); d_grid->enableXMin(false); d_grid->enableY(true); d_grid->enableYMin(false); d_grid->attach(this); } if (!d_origin) { d_origin = new QwtPlotMarker(); d_origin->setLineStyle(QwtPlotMarker::HLine); d_origin->setValue(0.0, 0.0); d_origin->attach(this); } QColor backgroundColor = Qt::white; QColor gridColor = Qt::gray; if (mColorMode == 1) { backgroundColor = Qt::black; gridColor = QColor(100, 100, 100); } QPalette pal = canvas()->palette(); pal.setBrush(QPalette::Window, QBrush(backgroundColor)); canvas()->setPalette(pal); d_grid->setPen(QPen(gridColor, 0.0, Qt::DotLine)); d_origin->setLinePen(QPen(gridColor, 0.0, Qt::DashLine)); } void Plot::start() { mStopped = false; mMagnifier->setAxisEnabled(QwtPlot::xBottom, mStopped); } void Plot::stop() { mStopped = true; mMagnifier->setAxisEnabled(QwtPlot::xBottom, mStopped); } bool Plot::isStopped() { return mStopped; } void Plot::replot() { this->updateTicks(); // Lock the signal data objects, then plot the data and unlock. QList<SignalData*> signalDataList = mSignals.keys(); foreach (SignalData* signalData, signalDataList) { signalData->lock(); } QwtPlot::replot(); foreach (SignalData* signalData, signalDataList) { signalData->unlock(); } } void Plot::flagAxisSyncRequired() { mAxisSyncRequired = true; } double Plot::timeWindow() { return mTimeWindow; } void Plot::setTimeWindow(double interval) { if ( interval > 0.0 && interval != mTimeWindow) { mTimeWindow = interval; QwtInterval xinterval = this->axisInterval(QwtPlot::xBottom); xinterval.setMinValue(xinterval.maxValue() - interval); this->setAxisScale(QwtPlot::xBottom, xinterval.minValue(), xinterval.maxValue()); this->replot(); } } void Plot::setYScale(double scale) { setAxisScale(QwtPlot::yLeft, -scale, scale); this->replot(); } void Plot::setEndTime(double endTime) { QwtInterval xinterval = this->axisInterval(QwtPlot::xBottom); if (xinterval.maxValue() == endTime) { return; } xinterval = QwtInterval(endTime - xinterval.width(), endTime); this->setAxisScale(QwtPlot::xBottom, xinterval.minValue(), xinterval.maxValue()); } void Plot::updateTicks() { this->updateAxes(); QwtInterval xinterval = this->axisInterval(QwtPlot::xBottom); // when playing, always use the requested time window // when paused, the user may zoom in/out, changing the time window if (!this->isStopped()) { xinterval.setMinValue(xinterval.maxValue() - mTimeWindow); } QwtScaleEngine* engine = axisScaleEngine(QwtPlot::xBottom); QwtScaleDiv scaleDiv = engine->divideScale(xinterval.minValue(), xinterval.maxValue(), 0, 0); QList<double> majorTicks; double majorStep = scaleDiv.range() / 5.0; for (int i = 0; i <= 5; ++i) { majorTicks << scaleDiv.lowerBound() + i*majorStep; } majorTicks.back() = scaleDiv.upperBound(); QList<double> minorTicks; double minorStep = scaleDiv.range() / 25.0; for (int i = 0; i <= 25; ++i) { minorTicks << scaleDiv.lowerBound() + i*minorStep; } minorTicks.back() = scaleDiv.upperBound(); scaleDiv.setTicks(QwtScaleDiv::MajorTick, majorTicks); scaleDiv.setTicks(QwtScaleDiv::MinorTick, minorTicks); setAxisScaleDiv(QwtPlot::xBottom, scaleDiv); if (mAxisSyncRequired) { emit this->syncXAxisScale(xinterval.minValue(), xinterval.maxValue()); mAxisSyncRequired = false; } } <commit_msg>call replot after changing point size or curve style<commit_after>#include "plot.h" #include "curvedata.h" #include "signaldata.h" #include <qwt_plot_grid.h> #include <qwt_plot_layout.h> #include <qwt_plot_canvas.h> #include <qwt_plot_marker.h> #include <qwt_plot_curve.h> #include <qwt_plot_directpainter.h> #include <qwt_curve_fitter.h> #include <qwt_painter.h> #include <qwt_scale_engine.h> #include <qwt_scale_draw.h> #include <qwt_plot_zoomer.h> #include <qwt_plot_panner.h> #include <qwt_plot_magnifier.h> #include <qwt_text.h> #include <qevent.h> #include <cassert> #define DEFAULT_CURVE_STYLE QwtPlotCurve::Dots class MyPanner : public QObject { public: QPoint mInitialPos; bool mEnabled; int mMouseButton; int mKeyboardButton; Plot* mPlot; MyPanner(Plot* plot) : QObject(plot) { mEnabled = false; mMouseButton = Qt::LeftButton; mKeyboardButton = Qt::NoButton; mPlot = plot; mPlot->canvas()->installEventFilter(this); } bool eventFilter( QObject *object, QEvent *event ) { switch ( event->type() ) { case QEvent::MouseButtonPress: { widgetMousePressEvent( ( QMouseEvent * )event ); break; } case QEvent::MouseMove: { widgetMouseMoveEvent( ( QMouseEvent * )event ); break; } case QEvent::MouseButtonRelease: { widgetMouseReleaseEvent( ( QMouseEvent * )event ); break; } } return false; } void moveCanvas( int dx, int dy ) { if ( dx == 0 && dy == 0 ) return; if (!mPlot->isStopped()) dx = 0; for ( int axis = 0; axis < QwtPlot::axisCnt; axis++ ) { const QwtScaleMap map = mPlot->canvasMap( axis ); const double p1 = map.transform( mPlot->axisScaleDiv( axis )->lowerBound() ); const double p2 = map.transform( mPlot->axisScaleDiv( axis )->upperBound() ); double d1, d2; if ( axis == QwtPlot::xBottom || axis == QwtPlot::xTop ) { d1 = map.invTransform( p1 - dx ); d2 = map.invTransform( p2 - dx ); } else { d1 = map.invTransform( p1 - dy ); d2 = map.invTransform( p2 - dy ); } mPlot->setAxisScale( axis, d1, d2 ); } mPlot->flagAxisSyncRequired(); mPlot->replot(); } void widgetMousePressEvent( QMouseEvent *mouseEvent ) { if (mouseEvent->button() != mMouseButton) { return; } if ((mouseEvent->modifiers() & Qt::KeyboardModifierMask) != (mKeyboardButton & Qt::KeyboardModifierMask)) { return; } mInitialPos = mouseEvent->pos(); mEnabled = true; } void widgetMouseMoveEvent( QMouseEvent *mouseEvent ) { if (!mEnabled) return; QPoint pos = mouseEvent->pos(); if (pos != mInitialPos) { moveCanvas(pos.x() - mInitialPos.x(), pos.y() - mInitialPos.y()); mInitialPos = mouseEvent->pos(); } } void widgetMouseReleaseEvent( QMouseEvent *mouseEvent ) { mEnabled = false; } }; class MyScaleDraw : public QwtScaleDraw { virtual QwtText label(double value) const { return QString::number(value, 'f', 2); } }; class MyZoomer: public QwtPlotZoomer { public: Plot* mPlot; MyZoomer(Plot *plot) : QwtPlotZoomer(plot->canvas()) { mPlot = plot; setTrackerMode(AlwaysOn); } virtual QwtText trackerTextF(const QPointF &pos) const { QColor bg(Qt::white); bg.setAlpha(200); QwtText text = QwtPlotZoomer::trackerTextF(pos); text.setBackgroundBrush( QBrush( bg )); return text; } protected: virtual void rescale() { mPlot->flagAxisSyncRequired(); QwtPlotZoomer::rescale(); } }; class MyMagnifier: public QwtPlotMagnifier { public: Plot* mPlot; MyMagnifier(Plot* plot) : QwtPlotMagnifier(plot->canvas()) { mPlot = plot; } protected: // Normally, a value < 1.0 zooms in, a value > 1.0 zooms out. // This function is overloaded to invert the magnification direction. virtual void rescale( double factor ) { factor = qAbs( factor ); factor = (1-factor) + 1; mPlot->flagAxisSyncRequired(); this->QwtPlotMagnifier::rescale(factor); } }; Plot::Plot(QWidget *parent): QwtPlot(parent), d_origin(0), d_grid(0), mStopped(true), mAxisSyncRequired(false), mColorMode(0), mTimeWindow(10.0) { setAutoReplot(false); // The backing store is important, when working with widget // overlays ( f.e rubberbands for zooming ). // Here we don't have them and the internal // backing store of QWidget is good enough. canvas()->setPaintAttribute(QwtPlotCanvas::BackingStore, false); #if defined(Q_WS_X11) // Even if not recommended by TrollTech, Qt::WA_PaintOutsidePaintEvent // works on X11. This has a nice effect on the performance. canvas()->setAttribute(Qt::WA_PaintOutsidePaintEvent, true); // Disabling the backing store of Qt improves the performance // for the direct painter even more, but the canvas becomes // a native window of the window system, receiving paint events // for resize and expose operations. Those might be expensive // when there are many points and the backing store of // the canvas is disabled. So in this application // we better don't both backing stores. if ( canvas()->testPaintAttribute( QwtPlotCanvas::BackingStore ) ) { canvas()->setAttribute(Qt::WA_PaintOnScreen, true); canvas()->setAttribute(Qt::WA_NoSystemBackground, true); } #endif plotLayout()->setAlignCanvasToScales(true); setAxisAutoScale(QwtPlot::xBottom, false); setAxisAutoScale(QwtPlot::yLeft, false); setAxisTitle(QwtPlot::xBottom, "Time [s]"); setAxisScale(QwtPlot::xBottom, 0, 10); setAxisScale(QwtPlot::yLeft, -4.0, 4.0); setAxisScaleDraw(QwtPlot::xBottom, new MyScaleDraw); initBackground(); QwtPlotZoomer* zoomer = new MyZoomer(this); zoomer->setMousePattern(QwtEventPattern::QwtEventPattern::MouseSelect1, Qt::LeftButton, Qt::ShiftModifier); // disable MouseSelect3 action of the zoomer zoomer->setMousePattern(QwtEventPattern::MouseSelect3, 0); MyPanner *panner = new MyPanner(this); // zoom in/out with the wheel mMagnifier = new MyMagnifier(this); mMagnifier->setMouseButton(Qt::MiddleButton); const QColor c(Qt::darkBlue); zoomer->setRubberBandPen(c); zoomer->setTrackerPen(c); this->setMinimumHeight(200); } Plot::~Plot() { } void Plot::addSignal(SignalData* signalData, QColor color) { QwtPlotCurve* d_curve = new QwtPlotCurve(); d_curve->setStyle(DEFAULT_CURVE_STYLE); QPen curvePen(color); curvePen.setWidth(0); d_curve->setPen(curvePen); #if 1 d_curve->setRenderHint(QwtPlotItem::RenderAntialiased, true); #endif #if 1 d_curve->setPaintAttribute(QwtPlotCurve::ClipPolygons, false); #endif d_curve->setData(new CurveData(signalData)); d_curve->attach(this); mSignals[signalData] = d_curve; } void Plot::removeSignal(SignalData* signalData) { if (!signalData) { return; } QwtPlotCurve* curve = mSignals.value(signalData); assert(curve); curve->detach(); delete curve; mSignals.remove(signalData); } void Plot::setSignalVisible(SignalData* signalData, bool visible) { if (!signalData) { return; } QwtPlotCurve* curve = mSignals.value(signalData); assert(curve); if (visible) { curve->attach(this); } else { curve->detach(); } this->replot(); } void Plot::setSignalColor(SignalData* signalData, QColor color) { if (!signalData) { return; } QwtPlotCurve* curve = mSignals.value(signalData); assert(curve); curve->setPen(QPen(color)); } void Plot::setPointSize(double pointSize) { foreach (QwtPlotCurve* curve, mSignals.values()) { QPen curvePen = curve->pen(); curvePen.setWidth(pointSize); curve->setPen(curvePen); } this->replot(); } void Plot::setCurveStyle(QwtPlotCurve::CurveStyle style) { foreach (QwtPlotCurve* curve, mSignals.values()) { curve->setStyle(style); } this->replot(); } void Plot::setBackgroundColor(QString color) { if (color == "White") { mColorMode = 0; } else if (color == "Black") { mColorMode = 1; } this->initBackground(); } void Plot::initBackground() { if (!d_grid) { d_grid = new QwtPlotGrid(); d_grid->enableX(false); d_grid->enableXMin(false); d_grid->enableY(true); d_grid->enableYMin(false); d_grid->attach(this); } if (!d_origin) { d_origin = new QwtPlotMarker(); d_origin->setLineStyle(QwtPlotMarker::HLine); d_origin->setValue(0.0, 0.0); d_origin->attach(this); } QColor backgroundColor = Qt::white; QColor gridColor = Qt::gray; if (mColorMode == 1) { backgroundColor = Qt::black; gridColor = QColor(100, 100, 100); } QPalette pal = canvas()->palette(); pal.setBrush(QPalette::Window, QBrush(backgroundColor)); canvas()->setPalette(pal); d_grid->setPen(QPen(gridColor, 0.0, Qt::DotLine)); d_origin->setLinePen(QPen(gridColor, 0.0, Qt::DashLine)); } void Plot::start() { mStopped = false; mMagnifier->setAxisEnabled(QwtPlot::xBottom, mStopped); } void Plot::stop() { mStopped = true; mMagnifier->setAxisEnabled(QwtPlot::xBottom, mStopped); } bool Plot::isStopped() { return mStopped; } void Plot::replot() { this->updateTicks(); // Lock the signal data objects, then plot the data and unlock. QList<SignalData*> signalDataList = mSignals.keys(); foreach (SignalData* signalData, signalDataList) { signalData->lock(); } QwtPlot::replot(); foreach (SignalData* signalData, signalDataList) { signalData->unlock(); } } void Plot::flagAxisSyncRequired() { mAxisSyncRequired = true; } double Plot::timeWindow() { return mTimeWindow; } void Plot::setTimeWindow(double interval) { if ( interval > 0.0 && interval != mTimeWindow) { mTimeWindow = interval; QwtInterval xinterval = this->axisInterval(QwtPlot::xBottom); xinterval.setMinValue(xinterval.maxValue() - interval); this->setAxisScale(QwtPlot::xBottom, xinterval.minValue(), xinterval.maxValue()); this->replot(); } } void Plot::setYScale(double scale) { setAxisScale(QwtPlot::yLeft, -scale, scale); this->replot(); } void Plot::setEndTime(double endTime) { QwtInterval xinterval = this->axisInterval(QwtPlot::xBottom); if (xinterval.maxValue() == endTime) { return; } xinterval = QwtInterval(endTime - xinterval.width(), endTime); this->setAxisScale(QwtPlot::xBottom, xinterval.minValue(), xinterval.maxValue()); } void Plot::updateTicks() { this->updateAxes(); QwtInterval xinterval = this->axisInterval(QwtPlot::xBottom); // when playing, always use the requested time window // when paused, the user may zoom in/out, changing the time window if (!this->isStopped()) { xinterval.setMinValue(xinterval.maxValue() - mTimeWindow); } QwtScaleEngine* engine = axisScaleEngine(QwtPlot::xBottom); QwtScaleDiv scaleDiv = engine->divideScale(xinterval.minValue(), xinterval.maxValue(), 0, 0); QList<double> majorTicks; double majorStep = scaleDiv.range() / 5.0; for (int i = 0; i <= 5; ++i) { majorTicks << scaleDiv.lowerBound() + i*majorStep; } majorTicks.back() = scaleDiv.upperBound(); QList<double> minorTicks; double minorStep = scaleDiv.range() / 25.0; for (int i = 0; i <= 25; ++i) { minorTicks << scaleDiv.lowerBound() + i*minorStep; } minorTicks.back() = scaleDiv.upperBound(); scaleDiv.setTicks(QwtScaleDiv::MajorTick, majorTicks); scaleDiv.setTicks(QwtScaleDiv::MinorTick, minorTicks); setAxisScaleDiv(QwtPlot::xBottom, scaleDiv); if (mAxisSyncRequired) { emit this->syncXAxisScale(xinterval.minValue(), xinterval.maxValue()); mAxisSyncRequired = false; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2012-2013 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * 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 copyright holders 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. * * Authors: Andreas Hansson */ /** * @file * ClockedObject declaration and implementation. */ #ifndef __SIM_CLOCKED_OBJECT_HH__ #define __SIM_CLOCKED_OBJECT_HH__ #include "base/intmath.hh" #include "base/misc.hh" #include "params/ClockedObject.hh" #include "sim/core.hh" #include "sim/clock_domain.hh" #include "sim/sim_object.hh" /** * The ClockedObject class extends the SimObject with a clock and * accessor functions to relate ticks to the cycles of the object. */ class ClockedObject : public SimObject { private: // the tick value of the next clock edge (>= curTick()) at the // time of the last call to update() mutable Tick tick; // The cycle counter value corresponding to the current value of // 'tick' mutable Cycles cycle; /** * Prevent inadvertent use of the copy constructor and assignment * operator by making them private. */ ClockedObject(ClockedObject&); ClockedObject& operator=(ClockedObject&); /** * Align cycle and tick to the next clock edge if not already done. */ void update() const { // both tick and cycle are up-to-date and we are done, note // that the >= is important as it captures cases where tick // has already passed curTick() if (tick >= curTick()) return; // optimise for the common case and see if the tick should be // advanced by a single clock period tick += clockPeriod(); ++cycle; // see if we are done at this point if (tick >= curTick()) return; // if not, we have to recalculate the cycle and tick, we // perform the calculations in terms of relative cycles to // allow changes to the clock period in the future Cycles elapsedCycles(divCeil(curTick() - tick, clockPeriod())); cycle += elapsedCycles; tick += elapsedCycles * clockPeriod(); } /** * The clock domain this clocked object belongs to */ ClockDomain &clockDomain; protected: /** * Create a clocked object and set the clock domain based on the * parameters. */ ClockedObject(const ClockedObjectParams* p) : SimObject(p), tick(0), cycle(0), clockDomain(*p->clk_domain) { } /** * Virtual destructor due to inheritance. */ virtual ~ClockedObject() { } /** * Reset the object's clock using the current global tick value. Likely * to be used only when the global clock is reset. Currently, this done * only when Ruby is done warming up the memory system. */ void resetClock() const { Cycles elapsedCycles(divCeil(curTick(), clockPeriod())); cycle = elapsedCycles; tick = elapsedCycles * clockPeriod(); } public: /** * Determine the tick when a cycle begins, by default the current * one, but the argument also enables the caller to determine a * future cycle. * * @param cycles The number of cycles into the future * * @return The tick when the clock edge occurs */ inline Tick clockEdge(Cycles cycles = Cycles(0)) const { // align tick to the next clock edge update(); // figure out when this future cycle is return tick + clockPeriod() * cycles; } /** * Determine the current cycle, corresponding to a tick aligned to * a clock edge. * * @return The current cycle count */ inline Cycles curCycle() const { // align cycle to the next clock edge. update(); return cycle; } /** * Based on the clock of the object, determine the tick when the next * cycle begins, in other words, return the next clock edge. * (This can never be the current tick.) * * @return The tick when the next cycle starts */ Tick nextCycle() const { return clockEdge(Cycles(1)); } inline uint64_t frequency() const { return SimClock::Frequency / clockPeriod(); } inline Tick clockPeriod() const { return clockDomain.clockPeriod(); } inline Cycles ticksToCycles(Tick t) const { return Cycles(t / clockPeriod()); } }; #endif //__SIM_CLOCKED_OBJECT_HH__ <commit_msg>sim: correct ticksToCycles() function.<commit_after>/* * Copyright (c) 2012-2013 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * 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 copyright holders 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. * * Authors: Andreas Hansson */ /** * @file * ClockedObject declaration and implementation. */ #ifndef __SIM_CLOCKED_OBJECT_HH__ #define __SIM_CLOCKED_OBJECT_HH__ #include "base/intmath.hh" #include "base/misc.hh" #include "params/ClockedObject.hh" #include "sim/core.hh" #include "sim/clock_domain.hh" #include "sim/sim_object.hh" /** * The ClockedObject class extends the SimObject with a clock and * accessor functions to relate ticks to the cycles of the object. */ class ClockedObject : public SimObject { private: // the tick value of the next clock edge (>= curTick()) at the // time of the last call to update() mutable Tick tick; // The cycle counter value corresponding to the current value of // 'tick' mutable Cycles cycle; /** * Prevent inadvertent use of the copy constructor and assignment * operator by making them private. */ ClockedObject(ClockedObject&); ClockedObject& operator=(ClockedObject&); /** * Align cycle and tick to the next clock edge if not already done. */ void update() const { // both tick and cycle are up-to-date and we are done, note // that the >= is important as it captures cases where tick // has already passed curTick() if (tick >= curTick()) return; // optimise for the common case and see if the tick should be // advanced by a single clock period tick += clockPeriod(); ++cycle; // see if we are done at this point if (tick >= curTick()) return; // if not, we have to recalculate the cycle and tick, we // perform the calculations in terms of relative cycles to // allow changes to the clock period in the future Cycles elapsedCycles(divCeil(curTick() - tick, clockPeriod())); cycle += elapsedCycles; tick += elapsedCycles * clockPeriod(); } /** * The clock domain this clocked object belongs to */ ClockDomain &clockDomain; protected: /** * Create a clocked object and set the clock domain based on the * parameters. */ ClockedObject(const ClockedObjectParams* p) : SimObject(p), tick(0), cycle(0), clockDomain(*p->clk_domain) { } /** * Virtual destructor due to inheritance. */ virtual ~ClockedObject() { } /** * Reset the object's clock using the current global tick value. Likely * to be used only when the global clock is reset. Currently, this done * only when Ruby is done warming up the memory system. */ void resetClock() const { Cycles elapsedCycles(divCeil(curTick(), clockPeriod())); cycle = elapsedCycles; tick = elapsedCycles * clockPeriod(); } public: /** * Determine the tick when a cycle begins, by default the current * one, but the argument also enables the caller to determine a * future cycle. * * @param cycles The number of cycles into the future * * @return The tick when the clock edge occurs */ inline Tick clockEdge(Cycles cycles = Cycles(0)) const { // align tick to the next clock edge update(); // figure out when this future cycle is return tick + clockPeriod() * cycles; } /** * Determine the current cycle, corresponding to a tick aligned to * a clock edge. * * @return The current cycle count */ inline Cycles curCycle() const { // align cycle to the next clock edge. update(); return cycle; } /** * Based on the clock of the object, determine the tick when the next * cycle begins, in other words, return the next clock edge. * (This can never be the current tick.) * * @return The tick when the next cycle starts */ Tick nextCycle() const { return clockEdge(Cycles(1)); } inline uint64_t frequency() const { return SimClock::Frequency / clockPeriod(); } inline Tick clockPeriod() const { return clockDomain.clockPeriod(); } inline Cycles ticksToCycles(Tick t) const { return Cycles(divCeil(t, clockPeriod())); } }; #endif //__SIM_CLOCKED_OBJECT_HH__ <|endoftext|>
<commit_before> #include <cublas_v2.h> #include <cuda_runtime.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <numeric> using namespace std; static void CheckCudaErrorAux(const char* file, unsigned line, const char* statement, cudaError_t err) { if (err == cudaSuccess) return; std::cerr << statement << " returned " << cudaGetErrorString(err) << "(" << err << ") at " << file << ":" << line << std::endl; exit(1); } #define CUDA_CHECK_RETURN(value) CheckCudaErrorAux(__FILE__, __LINE__, #value, value) __global__ void calcZ_v4(const int *dimensions, const int dim_product, const int maxDataPerRow, const signed char *laplace_matrix, const float *p, float *z) { extern __shared__ int diagonalOffsets[]; // Build diagonalOffsets on the first thread of each block and write it to shared memory if(threadIdx.x == 0) { const int diagonal = maxDataPerRow / 2; diagonalOffsets[diagonal] = 0; int factor = 1; for(int i = 0, offset = 1; i < diagonal; i++, offset++) { diagonalOffsets[diagonal - offset] = -factor; diagonalOffsets[diagonal + offset] = factor; factor *= dimensions[i]; } } __syncthreads(); const int row = blockIdx.x * blockDim.x + threadIdx.x; if (row < dim_product) { const int diagonal = row * maxDataPerRow; float tmp = 0; for(int i = diagonal; i < diagonal + maxDataPerRow; i++) { // when accessing out of bound memory in p, laplace_matrix[i] is always zero. So no illegal mem-access will be made. // If this causes problems add : // if(row + offsets[i - diagonalOffsets] >= 0 && row + offsets[i - diagonalOffsets] < dim_product) tmp += (signed char)laplace_matrix[i] * p[row + diagonalOffsets[i - diagonal]]; // No modulo here (as the general way in the thesis suggests) } z[row] = tmp; } } __global__ void checkResiduum(const int dim_product, const float* r, const float threshold, bool *threshold_reached) { for (int row = blockIdx.x * blockDim.x + threadIdx.x; row < dim_product; row += blockDim.x * gridDim.x) { if (r[row] >= threshold) { *threshold_reached = false; break; } } } __global__ void initVariablesWithGuess(const int dim_product, const float *divergence, float* A_times_x_0, float *p, float *r, bool *threshold_reached) { const int row = blockIdx.x * blockDim.x + threadIdx.x; if (row < dim_product) { float tmp = divergence[row] - A_times_x_0[row]; p[row] = tmp; r[row] = tmp; } if(row == 0) *threshold_reached = false; } // global blas handle, initialize only once (warning - currently not free'd!) bool initBlasHandle = true; cublasHandle_t blasHandle; void LaunchPressureKernel(const int* dimensions, const int dim_product, const int dim_size, const signed char *laplace_matrix, float* p, float* z, float* r, float* divergence, float* x, const float *oneVector, bool* threshold_reached, const float accuracy, const int max_iterations, const int batch_size, int* iterations_gpu) { // printf("Address of laplace_matrix is %p\n", (void *)laplace_matrix); // printf("Address of oneVector is %p\n", (void *)oneVector); // printf("Address of x is %p\n", (void *)x); // printf("Address of p is %p\n", (void *)p); // printf("Address of z is %p\n", (void *)z); // printf("Address of r is %p\n", (void *)r); // printf("Address of divergence is %p\n", (void *)divergence); if(initBlasHandle) { cublasCreate_v2(&blasHandle); cublasSetPointerMode_v2(blasHandle, CUBLAS_POINTER_MODE_HOST); initBlasHandle = false; } // CG helper variables variables init float *alpha = new float[batch_size], *beta = new float[batch_size]; const float oneScalar = 1.0f; bool *threshold_reached_cpu = new bool[batch_size]; float *p_r = new float[batch_size], *p_z = new float[batch_size], *r_z = new float[batch_size]; // get block and gridSize to theoretically get best occupancy int blockSize; int minGridSize; int gridSize; // Initialize the helper variables cudaOccupancyMaxPotentialBlockSize( &minGridSize, &blockSize, calcZ_v4, 0, 0); gridSize = (dim_product + blockSize - 1) / blockSize; // First calc A * x_0, save result to z: for(int i = 0; i < batch_size; i++) { calcZ_v4<<<gridSize, blockSize, dim_size * 2 + 1>>>(dimensions, dim_product, dim_size * 2 + 1, laplace_matrix, x + i * dim_product, z + i * dim_product); } CUDA_CHECK_RETURN(cudaDeviceSynchronize()); cudaOccupancyMaxPotentialBlockSize( &minGridSize, &blockSize, initVariablesWithGuess, 0, 0); gridSize = (dim_product + blockSize - 1) / blockSize; // Second apply result to the helper variables for(int i = 0; i < batch_size; i++) { int offset = i * dim_product; initVariablesWithGuess<<<gridSize, blockSize>>>(dim_product, divergence + offset, z + offset, p + offset, r + offset, threshold_reached + i); } CUDA_CHECK_RETURN(cudaDeviceSynchronize()); // Init residuum checker variables CUDA_CHECK_RETURN(cudaMemcpy(threshold_reached_cpu, threshold_reached, sizeof(bool) * batch_size, cudaMemcpyDeviceToHost)); CUDA_CHECK_RETURN(cudaDeviceSynchronize()); cudaOccupancyMaxPotentialBlockSize( &minGridSize, &blockSize, calcZ_v4, 0, 0); gridSize = (dim_product + blockSize - 1) / blockSize; // Do CG-Solve int checker = 1; int iterations = 0; for (; iterations < max_iterations; iterations++) { for(int i = 0; i < batch_size; i++) { if(threshold_reached_cpu[i]) continue; calcZ_v4<<<gridSize, blockSize, dim_size * 2 + 1>>>(dimensions, dim_product, dim_size * 2 + 1, laplace_matrix, p + i * dim_product, z + i * dim_product); } CUDA_CHECK_RETURN(cudaDeviceSynchronize()); for(int i = 0; i < batch_size; i++) { if(threshold_reached_cpu[i]) continue; cublasSdot_v2(blasHandle, dim_product, p + i * dim_product, 1, r + i * dim_product, 1, p_r + i); cublasSdot_v2(blasHandle, dim_product, p + i * dim_product, 1, z + i * dim_product, 1, p_z + i); } CUDA_CHECK_RETURN(cudaDeviceSynchronize()); for(int i = 0; i < batch_size; i++) { if(threshold_reached_cpu[i]) continue; alpha[i] = p_r[i] / p_z[i]; cublasSaxpy_v2(blasHandle, dim_product, alpha + i, p + i * dim_product, 1, x + i * dim_product, 1); alpha[i] = -alpha[i]; cublasSaxpy_v2(blasHandle, dim_product, alpha + i, z + i * dim_product, 1, r + i * dim_product, 1); } CUDA_CHECK_RETURN(cudaDeviceSynchronize()); // Check the residuum every 5 steps to keep memcopys between H&D low // Tests have shown, that 5 is a good avg trade-of between memcopys and extra computation and increases the performance if (checker % 5 == 0) { for(int i = 0; i < batch_size; i++) { if(threshold_reached_cpu[i]) continue; // Use fewer occupancy here, because in most cases residual will be to high and therefore checkResiduum<<<8, blockSize>>>(dim_product, r + i * dim_product, accuracy, threshold_reached + i); } CUDA_CHECK_RETURN(cudaDeviceSynchronize()); CUDA_CHECK_RETURN(cudaMemcpy(threshold_reached_cpu, threshold_reached, sizeof(bool) * batch_size, cudaMemcpyDeviceToHost)); CUDA_CHECK_RETURN(cudaDeviceSynchronize()); bool done = true; for(int i = 0; i < batch_size; i++) { if (!threshold_reached_cpu[i]) { done = false; break; } } if(done){ iterations++; break; } CUDA_CHECK_RETURN(cudaMemset(threshold_reached, 1, sizeof(bool) * batch_size)); } checker++; for(int i = 0; i < batch_size; i++) { if(threshold_reached_cpu[i]) continue; cublasSdot_v2(blasHandle, dim_product, r + i * dim_product, 1, z + i * dim_product, 1, r_z + i); } CUDA_CHECK_RETURN(cudaDeviceSynchronize()); for(int i = 0; i < batch_size; i++) { if(threshold_reached_cpu[i]) continue; beta[i] = -r_z[i] / p_z[i]; cublasSscal_v2(blasHandle, dim_product, beta + i, p + i * dim_product, 1); cublasSaxpy_v2(blasHandle, dim_product, &oneScalar, r + i * dim_product, 1, p + i * dim_product, 1); } CUDA_CHECK_RETURN(cudaDeviceSynchronize()); } delete[] alpha, beta, threshold_reached_cpu, p_r, p_z, r_z; // printf("I: %i\n", iterations); CUDA_CHECK_RETURN(cudaMemcpy(iterations_gpu, &iterations, sizeof(int), cudaMemcpyHostToDevice)); CUDA_CHECK_RETURN(cudaDeviceSynchronize()); } <commit_msg>added safe divide for alpha calculation in CUDA CG solver<commit_after> #include <cublas_v2.h> #include <cuda_runtime.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <numeric> using namespace std; static void CheckCudaErrorAux(const char* file, unsigned line, const char* statement, cudaError_t err) { if (err == cudaSuccess) return; std::cerr << statement << " returned " << cudaGetErrorString(err) << "(" << err << ") at " << file << ":" << line << std::endl; exit(1); } #define CUDA_CHECK_RETURN(value) CheckCudaErrorAux(__FILE__, __LINE__, #value, value) __global__ void calcZ_v4(const int *dimensions, const int dim_product, const int maxDataPerRow, const signed char *laplace_matrix, const float *p, float *z) { extern __shared__ int diagonalOffsets[]; // Build diagonalOffsets on the first thread of each block and write it to shared memory if(threadIdx.x == 0) { const int diagonal = maxDataPerRow / 2; diagonalOffsets[diagonal] = 0; int factor = 1; for(int i = 0, offset = 1; i < diagonal; i++, offset++) { diagonalOffsets[diagonal - offset] = -factor; diagonalOffsets[diagonal + offset] = factor; factor *= dimensions[i]; } } __syncthreads(); const int row = blockIdx.x * blockDim.x + threadIdx.x; if (row < dim_product) { const int diagonal = row * maxDataPerRow; float tmp = 0; for(int i = diagonal; i < diagonal + maxDataPerRow; i++) { // when accessing out of bound memory in p, laplace_matrix[i] is always zero. So no illegal mem-access will be made. // If this causes problems add : // if(row + offsets[i - diagonalOffsets] >= 0 && row + offsets[i - diagonalOffsets] < dim_product) tmp += (signed char)laplace_matrix[i] * p[row + diagonalOffsets[i - diagonal]]; // No modulo here (as the general way in the thesis suggests) } z[row] = tmp; } } __global__ void checkResiduum(const int dim_product, const float* r, const float threshold, bool *threshold_reached) { for (int row = blockIdx.x * blockDim.x + threadIdx.x; row < dim_product; row += blockDim.x * gridDim.x) { if (r[row] >= threshold) { *threshold_reached = false; break; } } } __global__ void initVariablesWithGuess(const int dim_product, const float *divergence, float* A_times_x_0, float *p, float *r, bool *threshold_reached) { const int row = blockIdx.x * blockDim.x + threadIdx.x; if (row < dim_product) { float tmp = divergence[row] - A_times_x_0[row]; p[row] = tmp; r[row] = tmp; } if(row == 0) *threshold_reached = false; } // global blas handle, initialize only once (warning - currently not free'd!) bool initBlasHandle = true; cublasHandle_t blasHandle; void LaunchPressureKernel(const int* dimensions, const int dim_product, const int dim_size, const signed char *laplace_matrix, float* p, float* z, float* r, float* divergence, float* x, const float *oneVector, bool* threshold_reached, const float accuracy, const int max_iterations, const int batch_size, int* iterations_gpu) { // printf("Address of laplace_matrix is %p\n", (void *)laplace_matrix); // printf("Address of oneVector is %p\n", (void *)oneVector); // printf("Address of x is %p\n", (void *)x); // printf("Address of p is %p\n", (void *)p); // printf("Address of z is %p\n", (void *)z); // printf("Address of r is %p\n", (void *)r); // printf("Address of divergence is %p\n", (void *)divergence); if(initBlasHandle) { cublasCreate_v2(&blasHandle); cublasSetPointerMode_v2(blasHandle, CUBLAS_POINTER_MODE_HOST); initBlasHandle = false; } // CG helper variables variables init float *alpha = new float[batch_size], *beta = new float[batch_size]; const float oneScalar = 1.0f; bool *threshold_reached_cpu = new bool[batch_size]; float *p_r = new float[batch_size], *p_z = new float[batch_size], *r_z = new float[batch_size]; // get block and gridSize to theoretically get best occupancy int blockSize; int minGridSize; int gridSize; // Initialize the helper variables cudaOccupancyMaxPotentialBlockSize( &minGridSize, &blockSize, calcZ_v4, 0, 0); gridSize = (dim_product + blockSize - 1) / blockSize; // First calc A * x_0, save result to z: for(int i = 0; i < batch_size; i++) { calcZ_v4<<<gridSize, blockSize, dim_size * 2 + 1>>>(dimensions, dim_product, dim_size * 2 + 1, laplace_matrix, x + i * dim_product, z + i * dim_product); } CUDA_CHECK_RETURN(cudaDeviceSynchronize()); cudaOccupancyMaxPotentialBlockSize( &minGridSize, &blockSize, initVariablesWithGuess, 0, 0); gridSize = (dim_product + blockSize - 1) / blockSize; // Second apply result to the helper variables for(int i = 0; i < batch_size; i++) { int offset = i * dim_product; initVariablesWithGuess<<<gridSize, blockSize>>>(dim_product, divergence + offset, z + offset, p + offset, r + offset, threshold_reached + i); } CUDA_CHECK_RETURN(cudaDeviceSynchronize()); // Init residuum checker variables CUDA_CHECK_RETURN(cudaMemcpy(threshold_reached_cpu, threshold_reached, sizeof(bool) * batch_size, cudaMemcpyDeviceToHost)); CUDA_CHECK_RETURN(cudaDeviceSynchronize()); cudaOccupancyMaxPotentialBlockSize( &minGridSize, &blockSize, calcZ_v4, 0, 0); gridSize = (dim_product + blockSize - 1) / blockSize; // Do CG-Solve int checker = 1; int iterations = 0; for (; iterations < max_iterations; iterations++) { for(int i = 0; i < batch_size; i++) { if(threshold_reached_cpu[i]) continue; calcZ_v4<<<gridSize, blockSize, dim_size * 2 + 1>>>(dimensions, dim_product, dim_size * 2 + 1, laplace_matrix, p + i * dim_product, z + i * dim_product); } CUDA_CHECK_RETURN(cudaDeviceSynchronize()); for(int i = 0; i < batch_size; i++) { if(threshold_reached_cpu[i]) continue; cublasSdot_v2(blasHandle, dim_product, p + i * dim_product, 1, r + i * dim_product, 1, p_r + i); cublasSdot_v2(blasHandle, dim_product, p + i * dim_product, 1, z + i * dim_product, 1, p_z + i); } CUDA_CHECK_RETURN(cudaDeviceSynchronize()); for(int i = 0; i < batch_size; i++) { if(threshold_reached_cpu[i]) continue; alpha[i] = 0.; if(fabs(p_z[i])>0.) alpha[i] = p_r[i] / p_z[i]; cublasSaxpy_v2(blasHandle, dim_product, alpha + i, p + i * dim_product, 1, x + i * dim_product, 1); alpha[i] = -alpha[i]; cublasSaxpy_v2(blasHandle, dim_product, alpha + i, z + i * dim_product, 1, r + i * dim_product, 1); } CUDA_CHECK_RETURN(cudaDeviceSynchronize()); // Check the residuum every 5 steps to keep memcopys between H&D low // Tests have shown, that 5 is a good avg trade-of between memcopys and extra computation and increases the performance if (checker % 5 == 0) { for(int i = 0; i < batch_size; i++) { if(threshold_reached_cpu[i]) continue; // Use fewer occupancy here, because in most cases residual will be to high and therefore checkResiduum<<<8, blockSize>>>(dim_product, r + i * dim_product, accuracy, threshold_reached + i); } CUDA_CHECK_RETURN(cudaDeviceSynchronize()); CUDA_CHECK_RETURN(cudaMemcpy(threshold_reached_cpu, threshold_reached, sizeof(bool) * batch_size, cudaMemcpyDeviceToHost)); CUDA_CHECK_RETURN(cudaDeviceSynchronize()); bool done = true; for(int i = 0; i < batch_size; i++) { if (!threshold_reached_cpu[i]) { done = false; break; } } if(done){ iterations++; break; } CUDA_CHECK_RETURN(cudaMemset(threshold_reached, 1, sizeof(bool) * batch_size)); } checker++; for(int i = 0; i < batch_size; i++) { if(threshold_reached_cpu[i]) continue; cublasSdot_v2(blasHandle, dim_product, r + i * dim_product, 1, z + i * dim_product, 1, r_z + i); } CUDA_CHECK_RETURN(cudaDeviceSynchronize()); for(int i = 0; i < batch_size; i++) { if(threshold_reached_cpu[i]) continue; beta[i] = -r_z[i] / p_z[i]; cublasSscal_v2(blasHandle, dim_product, beta + i, p + i * dim_product, 1); cublasSaxpy_v2(blasHandle, dim_product, &oneScalar, r + i * dim_product, 1, p + i * dim_product, 1); } CUDA_CHECK_RETURN(cudaDeviceSynchronize()); } delete[] alpha, beta, threshold_reached_cpu, p_r, p_z, r_z; // printf("I: %i\n", iterations); CUDA_CHECK_RETURN(cudaMemcpy(iterations_gpu, &iterations, sizeof(int), cudaMemcpyHostToDevice)); CUDA_CHECK_RETURN(cudaDeviceSynchronize()); } <|endoftext|>
<commit_before>#define _BSD_SOURCE #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <signal.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/wait.h> #include <unistd.h> #include <sys/ptrace.h> #include "ptbox.h" pt_process *pt_alloc_process(pt_debugger *debugger) { return new pt_process(debugger); } void pt_free_process(pt_process *process) { delete process; } pt_process::pt_process(pt_debugger *debugger) : pid(0), callback(NULL), context(NULL), debugger(debugger), event_proc(NULL), event_context(NULL), _trace_syscalls(true), _initialized(false) { memset(&exec_time, 0, sizeof exec_time); memset(handler, 0, sizeof handler); debugger->set_process(this); } void pt_process::set_callback(pt_handler_callback callback, void *context) { this->callback = callback; this->context = context; } void pt_process::set_event_proc(pt_event_callback callback, void *context) { this->event_proc = callback; this->event_context = context; } int pt_process::set_handler(int syscall, int handler) { if (syscall >= MAX_SYSCALL || syscall < 0) return 1; this->handler[syscall] = handler; return 0; } int pt_process::dispatch(int event, unsigned long param) { if (event_proc != NULL) return event_proc(event_context, event, param); return -1; } int pt_process::spawn(pt_fork_handler child, void *context) { pid_t pid = fork(); if (pid == -1) return 1; if (pid == 0) { setpgid(0, 0); _exit(child(context)); } this->pid = pid; debugger->new_process(); return 0; } int pt_process::protection_fault(int syscall) { dispatch(PTBOX_EVENT_PROTECTION, syscall); dispatch(PTBOX_EVENT_EXITING, PTBOX_EXIT_PROTECTION); kill(pid, SIGKILL); return PTBOX_EXIT_PROTECTION; } int pt_process::monitor() { bool in_syscall = false, first = true, spawned = false; struct timespec start, end, delta; int status, exit_reason = PTBOX_EXIT_NORMAL; siginfo_t si; // Set pgid to -this->pid such that -pgid becomes pid, resulting // in the initial wait be on the main thread. This allows it a chance // of creating a new process group. pid_t pid, pgid = -this->pid; while (true) { clock_gettime(CLOCK_MONOTONIC, &start); pid = wait4(-pgid, &status, __WALL, &_rusage); clock_gettime(CLOCK_MONOTONIC, &end); timespec_sub(&end, &start, &delta); timespec_add(&exec_time, &delta, &exec_time); int signal = 0; //printf("pid: %d (%d)\n", pid, this->pid); if (WIFEXITED(status) || WIFSIGNALED(status)) { if (first || pid == pgid) break; //else printf("Thread exit: %d\n", pid); } if (first) { dispatch(PTBOX_EVENT_ATTACH, 0); // This is right after SIGSTOP is received: ptrace(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXIT | PTRACE_O_TRACECLONE); // We now set the process group to the actual pgid. pgid = pid; } if (WIFSTOPPED(status)) { if (WSTOPSIG(status) == (0x80 | SIGTRAP)) { debugger->settid(pid); int syscall = debugger->syscall(); in_syscall ^= true; //printf("%d: %s syscall %d\n", pid, in_syscall ? "Enter" : "Exit", syscall); if (!spawned) { // Does execve not return if the process hits an rlimit and gets SIGKILLed? // // It doesn't. See the strace below. // $ ulimit -Sv50000 // $ strace ./a.out // execve("./a.out", ["./a.out"], [/* 17 vars */] <unfinished ...> // +++ killed by SIGKILL +++ // Killed // // From this we can see that execve doesn't return (<unfinished ...>) if the process fails to // initialize, so we don't need to wait until the next non-execve syscall to set // _initialized to true - if it exited execve, it's good to go. if (!in_syscall && syscall == debugger->execve_syscall()) spawned = this->_initialized = true; } else if (in_syscall) { if (syscall < MAX_SYSCALL) { switch (handler[syscall]) { case PTBOX_HANDLER_ALLOW: break; case PTBOX_HANDLER_STDOUTERR: { int arg0 = debugger->arg0(); if (arg0 != 1 && arg0 != 2) exit_reason = protection_fault(syscall); break; } case PTBOX_HANDLER_CALLBACK: if (callback(context, syscall)) break; //printf("Killed by callback: %d\n", syscall); exit_reason = protection_fault(syscall); continue; default: // Default is to kill, safety first. //printf("Killed by DISALLOW or None: %d\n", syscall); exit_reason = protection_fault(syscall); continue; } } } else if (debugger->on_return_callback) { debugger->on_return_callback(debugger->on_return_context, syscall); debugger->on_return_callback = NULL; debugger->on_return_context = NULL; } } else { switch (WSTOPSIG(status)) { case SIGTRAP: switch (status >> 16) { case PTRACE_EVENT_EXIT: if (exit_reason != PTBOX_EXIT_NORMAL) dispatch(PTBOX_EVENT_EXITING, PTBOX_EXIT_NORMAL); case PTRACE_EVENT_CLONE: { unsigned long tid; ptrace(PTRACE_GETEVENTMSG, pid, NULL, &tid); //printf("Created thread: %d\n", tid); break; } } break; default: signal = WSTOPSIG(status); } if (!first) // *** Don't set _signal to SIGSTOP if this is the /first/ SIGSTOP dispatch(PTBOX_EVENT_SIGNAL, WSTOPSIG(status)); } } // Pass NULL as signal in case of our first SIGSTOP because the runtime tends to resend it, making all our // work for naught. Like abort(), it catches the signal, prints something (^Z?) and then resends it. // Doing this prevents a second SIGSTOP from being dispatched to our event handler above. *** #if defined(__FreeBSD__) ptrace(_trace_syscalls ? PT_SYSCALL : PT_CONTINUE, pid, (caddr_t) 1, first ? 0 : signal); #else ptrace(_trace_syscalls ? PTRACE_SYSCALL : PTRACE_CONT, pid, NULL, first ? NULL : (void*) signal); #endif first = false; } dispatch(PTBOX_EVENT_EXITED, exit_reason); return WIFEXITED(status) ? WEXITSTATUS(status) : -WTERMSIG(status); } <commit_msg>Correct some nonexistent ptrace logic; #192<commit_after>#define _BSD_SOURCE #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <signal.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/wait.h> #include <unistd.h> #include <sys/ptrace.h> #include "ptbox.h" pt_process *pt_alloc_process(pt_debugger *debugger) { return new pt_process(debugger); } void pt_free_process(pt_process *process) { delete process; } pt_process::pt_process(pt_debugger *debugger) : pid(0), callback(NULL), context(NULL), debugger(debugger), event_proc(NULL), event_context(NULL), _trace_syscalls(true), _initialized(false) { memset(&exec_time, 0, sizeof exec_time); memset(handler, 0, sizeof handler); debugger->set_process(this); } void pt_process::set_callback(pt_handler_callback callback, void *context) { this->callback = callback; this->context = context; } void pt_process::set_event_proc(pt_event_callback callback, void *context) { this->event_proc = callback; this->event_context = context; } int pt_process::set_handler(int syscall, int handler) { if (syscall >= MAX_SYSCALL || syscall < 0) return 1; this->handler[syscall] = handler; return 0; } int pt_process::dispatch(int event, unsigned long param) { if (event_proc != NULL) return event_proc(event_context, event, param); return -1; } int pt_process::spawn(pt_fork_handler child, void *context) { pid_t pid = fork(); if (pid == -1) return 1; if (pid == 0) { setpgid(0, 0); _exit(child(context)); } this->pid = pid; debugger->new_process(); return 0; } int pt_process::protection_fault(int syscall) { dispatch(PTBOX_EVENT_PROTECTION, syscall); dispatch(PTBOX_EVENT_EXITING, PTBOX_EXIT_PROTECTION); kill(pid, SIGKILL); return PTBOX_EXIT_PROTECTION; } int pt_process::monitor() { bool in_syscall = false, first = true, spawned = false; struct timespec start, end, delta; int status, exit_reason = PTBOX_EXIT_NORMAL; siginfo_t si; // Set pgid to -this->pid such that -pgid becomes pid, resulting // in the initial wait be on the main thread. This allows it a chance // of creating a new process group. pid_t pid, pgid = -this->pid; while (true) { clock_gettime(CLOCK_MONOTONIC, &start); pid = wait4(-pgid, &status, __WALL, &_rusage); clock_gettime(CLOCK_MONOTONIC, &end); timespec_sub(&end, &start, &delta); timespec_add(&exec_time, &delta, &exec_time); int signal = 0; //printf("pid: %d (%d)\n", pid, this->pid); if (WIFEXITED(status) || WIFSIGNALED(status)) { if (first || pid == pgid) break; //else printf("Thread exit: %d\n", pid); } if (first) { dispatch(PTBOX_EVENT_ATTACH, 0); #if defined(__FreeBSD__) // No FreeBSD equivalent that I know of // * TRACESYSGOOD is only for bit 7 of SIGTRAP, we can do without // * TRACECLONE makes no sense since FreeBSD has no clone(2) // * TRACEEXIT... I'm not sure about #else // This is right after SIGSTOP is received: ptrace(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXIT | PTRACE_O_TRACECLONE); #endif // We now set the process group to the actual pgid. pgid = pid; } if (WIFSTOPPED(status)) { #if defined(__FreeBSD__) // FreeBSD has no PTRACE_O_TRACESYSGOOD equivalent if (WSTOPSIG(status) == SIGTRAP) { else if (WSTOPSIG(status) == (0x80 | SIGTRAP)) { #endif debugger->settid(pid); int syscall = debugger->syscall(); in_syscall ^= true; //printf("%d: %s syscall %d\n", pid, in_syscall ? "Enter" : "Exit", syscall); if (!spawned) { // Does execve not return if the process hits an rlimit and gets SIGKILLed? // // It doesn't. See the strace below. // $ ulimit -Sv50000 // $ strace ./a.out // execve("./a.out", ["./a.out"], [/* 17 vars */] <unfinished ...> // +++ killed by SIGKILL +++ // Killed // // From this we can see that execve doesn't return (<unfinished ...>) if the process fails to // initialize, so we don't need to wait until the next non-execve syscall to set // _initialized to true - if it exited execve, it's good to go. if (!in_syscall && syscall == debugger->execve_syscall()) spawned = this->_initialized = true; } else if (in_syscall) { if (syscall < MAX_SYSCALL) { switch (handler[syscall]) { case PTBOX_HANDLER_ALLOW: break; case PTBOX_HANDLER_STDOUTERR: { int arg0 = debugger->arg0(); if (arg0 != 1 && arg0 != 2) exit_reason = protection_fault(syscall); break; } case PTBOX_HANDLER_CALLBACK: if (callback(context, syscall)) break; //printf("Killed by callback: %d\n", syscall); exit_reason = protection_fault(syscall); continue; default: // Default is to kill, safety first. //printf("Killed by DISALLOW or None: %d\n", syscall); exit_reason = protection_fault(syscall); continue; } } } else if (debugger->on_return_callback) { debugger->on_return_callback(debugger->on_return_context, syscall); debugger->on_return_callback = NULL; debugger->on_return_context = NULL; } } else { #if defined(__FreeBSD__) // No events aside from signal event on FreeBSD // (TODO: maybe check for PL_SIGNAL instead of both PL_SIGNAL and PL_NONE?) signal = WSTOPSIG(status); #else switch (WSTOPSIG(status)) { case SIGTRAP: switch (status >> 16) { case PTRACE_EVENT_EXIT: if (exit_reason != PTBOX_EXIT_NORMAL) dispatch(PTBOX_EVENT_EXITING, PTBOX_EXIT_NORMAL); case PTRACE_EVENT_CLONE: { unsigned long tid; ptrace(PTRACE_GETEVENTMSG, pid, NULL, &tid); //printf("Created thread: %d\n", tid); break; } } break; default: signal = WSTOPSIG(status); } #endif if (!first) // *** Don't set _signal to SIGSTOP if this is the /first/ SIGSTOP dispatch(PTBOX_EVENT_SIGNAL, WSTOPSIG(status)); } } // Pass NULL as signal in case of our first SIGSTOP because the runtime tends to resend it, making all our // work for naught. Like abort(), it catches the signal, prints something (^Z?) and then resends it. // Doing this prevents a second SIGSTOP from being dispatched to our event handler above. *** #if defined(__FreeBSD__) ptrace(_trace_syscalls ? PT_SYSCALL : PT_CONTINUE, pid, (caddr_t) 1, first ? 0 : signal); #else ptrace(_trace_syscalls ? PTRACE_SYSCALL : PTRACE_CONT, pid, NULL, first ? NULL : (void*) signal); #endif first = false; } dispatch(PTBOX_EVENT_EXITED, exit_reason); return WIFEXITED(status) ? WEXITSTATUS(status) : -WTERMSIG(status); } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2006 by FThauer FHammer * * [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. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "joinnetworkgamedialogimpl.h" #include "session.h" #include "configfile.h" #include "tinyxml.h" using namespace std; joinNetworkGameDialogImpl::joinNetworkGameDialogImpl(QWidget *parent, ConfigFile *c) : QDialog(parent), myConfig(c) { setupUi(this); // QShortcut *connectKey = new QShortcut(QKeySequence(Qt::Key_Enter), this); // connect( connectKey, SIGNAL(activated() ), pushButton_connect, SLOT( click() ) ); if (myConfig->readConfigInt("CLA_NoWriteAccess")) { pushButton_save->setDisabled(TRUE); pushButton_delete->setDisabled(TRUE); treeWidget->setDisabled(TRUE); } connect( pushButton_connect, SIGNAL( clicked() ), this, SLOT( startClient() ) ); connect( pushButton_save, SIGNAL( clicked() ), this, SLOT( saveServerProfile() ) ); connect( pushButton_delete, SIGNAL( clicked() ), this, SLOT( deleteServerProfile() ) ); connect( treeWidget, SIGNAL( itemClicked ( QTreeWidgetItem*, int) ), this, SLOT( itemFillForm (QTreeWidgetItem*, int) ) ); } void joinNetworkGameDialogImpl::exec() { bool toIntTrue; spinBox_port->setValue(QString::fromUtf8(myConfig->readConfigString("ServerPort").c_str()).toInt(&toIntTrue, 10)); //Profile Name darf nicht mit einer Zahl beginnen --> XML konform QRegExp rx("[A-Z|a-z]+[A-Z|a-z|\\d]*"); QValidator *validator = new QRegExpValidator(rx, this); lineEdit_profileName->setValidator(validator); pushButton_delete->setDisabled(TRUE); lineEdit_ipAddress->setFocus(); if (myConfig->readConfigInt("CLA_NoWriteAccess") == 0 ) { //if discwrite-access myServerProfilesFile = myConfig->readConfigString("DataDir")+"serverprofiles.xml"; //Anlegen wenn noch nicht existiert! QFile serverProfilesfile(QString::fromUtf8(myServerProfilesFile.c_str())); if(!serverProfilesfile.exists()) { TiXmlDocument doc; TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "UTF-8", ""); doc.LinkEndChild( decl ); TiXmlElement * root = new TiXmlElement( "PokerTH" ); doc.LinkEndChild( root ); TiXmlElement * profiles = new TiXmlElement( "ServerProfiles" ); root->LinkEndChild( profiles ); doc.SaveFile(QString::fromUtf8(myServerProfilesFile.c_str()).toStdString()); } //Liste Füllen fillServerProfileList(); } QDialog::exec(); } void joinNetworkGameDialogImpl::startClient() { // TODO: Check input values! } void joinNetworkGameDialogImpl::fillServerProfileList() { treeWidget->clear(); TiXmlDocument doc(QString::fromUtf8(myServerProfilesFile.c_str()).toStdString()); if(!doc.LoadFile()) { QMessageBox::warning(this, tr("Load Server-Profile-File Error"), tr("Could not load server-profiles-file:\n"+QString::fromUtf8(myServerProfilesFile.c_str()).toAscii()), QMessageBox::Close); } TiXmlHandle docHandle( &doc ); TiXmlElement* profile = docHandle.FirstChild( "PokerTH" ).FirstChild( "ServerProfiles" ).FirstChild().ToElement(); if ( profile ) { for( profile; profile; profile = profile->NextSiblingElement()) { QTreeWidgetItem *item = new QTreeWidgetItem(treeWidget,0); item->setData(0, 0, profile->Attribute("Name")); item->setData(1, 0, profile->Attribute("Address")); item->setData(2, 0, profile->Attribute("Port")); string isIpv6 = "no"; int tempInt = 0; profile->QueryIntAttribute("IsIpv6", &tempInt ); if( tempInt == 1 ) { isIpv6 = "yes"; } item->setData(3, 0, QString::fromUtf8(isIpv6.c_str())); treeWidget->addTopLevelItem(item); } } else { cout << "No Profiles Found \n"; } treeWidget->resizeColumnToContents ( 0 ); treeWidget->resizeColumnToContents ( 1 ); treeWidget->resizeColumnToContents ( 2 ); treeWidget->resizeColumnToContents ( 3 ); } void joinNetworkGameDialogImpl::itemFillForm (QTreeWidgetItem* item, int column) { bool toIntTrue; TiXmlDocument doc(QString::fromUtf8(myServerProfilesFile.c_str()).toStdString()); if(!doc.LoadFile()) { QMessageBox::warning(this, tr("Load Server-Profile-File Error"), tr("Could not load server-profiles-file:\n"+QString::fromUtf8(myServerProfilesFile.c_str()).toAscii()), QMessageBox::Close); } TiXmlHandle docHandle( &doc ); TiXmlElement* profile = docHandle.FirstChild( "PokerTH" ).FirstChild( "ServerProfiles" ).FirstChild( item->data(0,0).toString().toStdString() ).ToElement(); if ( profile ) { lineEdit_profileName->setText(QString::fromUtf8(profile->Attribute("Name"))); lineEdit_ipAddress->setText(QString::fromUtf8(profile->Attribute("Address"))); lineEdit_password->setText(QString::fromUtf8(profile->Attribute("Password"))); spinBox_port->setValue(QString::fromUtf8(profile->Attribute("Port")).toInt(&toIntTrue, 10)); checkBox_ipv6->setChecked(QString::fromUtf8(profile->Attribute("IsIpv6")).toInt(&toIntTrue, 10)); } pushButton_delete->setEnabled(TRUE); } void joinNetworkGameDialogImpl::saveServerProfile() { // bool toIntTrue; TiXmlDocument doc(QString::fromUtf8(myServerProfilesFile.c_str()).toStdString()); if(!doc.LoadFile()) { QMessageBox::warning(this, tr("Load Server-Profile-File Error"), tr("Could not load server-profiles-file:\n"+QString::fromUtf8(myServerProfilesFile.c_str()).toAscii()), QMessageBox::Close); } TiXmlHandle docHandle( &doc ); TiXmlElement* profiles = docHandle.FirstChild( "PokerTH" ).FirstChild( "ServerProfiles" ).ToElement(); if ( profiles ) { TiXmlElement * testProfile = docHandle.FirstChild( "PokerTH" ).FirstChild( "ServerProfiles" ).FirstChild( lineEdit_profileName->text().toStdString() ).ToElement(); if( testProfile ) { // Wenn der Name schon existiert --> Überschreiben? QMessageBox msgBox(QMessageBox::Warning, tr("Save Server Profile Error"), tr("A profile with the name: \""+lineEdit_profileName->text().toAscii()+"\" already exists.\nWould you like to overwrite ?"), QMessageBox::Yes | QMessageBox::No, this); switch (msgBox.exec()) { case QMessageBox::Yes: { // yes was clicked // remove the old testProfile->Parent()->RemoveChild(testProfile); // write the new TiXmlElement * profile1 = new TiXmlElement( lineEdit_profileName->text().toStdString() ); profiles->LinkEndChild( profile1 ); profile1->SetAttribute("Name", lineEdit_profileName->text().toStdString()); profile1->SetAttribute("Address", lineEdit_ipAddress->text().toStdString()); profile1->SetAttribute("Password", lineEdit_password->text().toStdString()); profile1->SetAttribute("Port", spinBox_port->value()); profile1->SetAttribute("IsIpv6", checkBox_ipv6->isChecked()); } break; case QMessageBox::No: // no was clicked break; default: // should never be reached break; } } else { // Wenn der Name nicht existiert --> speichern TiXmlElement * profile2 = new TiXmlElement( lineEdit_profileName->text().toStdString() ); profiles->LinkEndChild( profile2 ); profile2->SetAttribute("Name", lineEdit_profileName->text().toStdString()); profile2->SetAttribute("Address", lineEdit_ipAddress->text().toStdString()); profile2->SetAttribute("Password", lineEdit_password->text().toStdString()); profile2->SetAttribute("Port", spinBox_port->value()); profile2->SetAttribute("IsIpv6", checkBox_ipv6->isChecked()); } } else { QMessageBox::warning(this, tr("Read Server-Profile List Error"), tr("Could not read server-profiles list"), QMessageBox::Close); } if(!doc.SaveFile()) { QMessageBox::warning(this, tr("Save Server-Profile-File Error"), tr("Could not save server-profiles-file:\n"+QString::fromUtf8(myServerProfilesFile.c_str()).toAscii()), QMessageBox::Close); } fillServerProfileList(); } void joinNetworkGameDialogImpl::deleteServerProfile() { TiXmlDocument doc(QString::fromUtf8(myServerProfilesFile.c_str()).toStdString()); if(!doc.LoadFile()) { QMessageBox::warning(this, tr("Load Server-Profile-File Error"), tr("Could not load server-profiles-file:\n"+QString::fromUtf8(myServerProfilesFile.c_str()).toAscii()), QMessageBox::Close); } else { TiXmlHandle docHandle( &doc ); TiXmlElement* profile = docHandle.FirstChild( "PokerTH" ).FirstChild( "ServerProfiles" ).FirstChild( treeWidget->currentItem()->data(0,0).toString().toStdString() ).ToElement(); if ( profile ) { profile->Parent()->RemoveChild(profile); } if(!doc.SaveFile()) { QMessageBox::warning(this, tr("Save Server-Profile-File Error"), tr("Could not save server-profiles-file:\n"+QString::fromUtf8(myServerProfilesFile.c_str()).toAscii()), QMessageBox::Close); } //Liste Füllen fillServerProfileList(); } pushButton_delete->setDisabled(TRUE); } void joinNetworkGameDialogImpl::keyPressEvent ( QKeyEvent * event ) { // std::cout << "key" << event->key(); if (event->key() == 16777220) { pushButton_connect->click(); } //ENTER } <commit_msg>utf8 serverprofiles fix<commit_after>/*************************************************************************** * Copyright (C) 2006 by FThauer FHammer * * [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. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "joinnetworkgamedialogimpl.h" #include "session.h" #include "configfile.h" #include "tinyxml.h" using namespace std; joinNetworkGameDialogImpl::joinNetworkGameDialogImpl(QWidget *parent, ConfigFile *c) : QDialog(parent), myConfig(c) { setupUi(this); // QShortcut *connectKey = new QShortcut(QKeySequence(Qt::Key_Enter), this); // connect( connectKey, SIGNAL(activated() ), pushButton_connect, SLOT( click() ) ); if (myConfig->readConfigInt("CLA_NoWriteAccess")) { pushButton_save->setDisabled(TRUE); pushButton_delete->setDisabled(TRUE); treeWidget->setDisabled(TRUE); } connect( pushButton_connect, SIGNAL( clicked() ), this, SLOT( startClient() ) ); connect( pushButton_save, SIGNAL( clicked() ), this, SLOT( saveServerProfile() ) ); connect( pushButton_delete, SIGNAL( clicked() ), this, SLOT( deleteServerProfile() ) ); connect( treeWidget, SIGNAL( itemClicked ( QTreeWidgetItem*, int) ), this, SLOT( itemFillForm (QTreeWidgetItem*, int) ) ); } void joinNetworkGameDialogImpl::exec() { bool toIntTrue; spinBox_port->setValue(QString::fromUtf8(myConfig->readConfigString("ServerPort").c_str()).toInt(&toIntTrue, 10)); //Profile Name darf nicht mit einer Zahl beginnen --> XML konform QRegExp rx("[A-Z|a-z]+[A-Z|a-z|\\d]*"); QValidator *validator = new QRegExpValidator(rx, this); lineEdit_profileName->setValidator(validator); pushButton_delete->setDisabled(TRUE); lineEdit_ipAddress->setFocus(); if (myConfig->readConfigInt("CLA_NoWriteAccess") == 0 ) { //if discwrite-access myServerProfilesFile = myConfig->readConfigString("DataDir")+"serverprofiles.xml"; //Anlegen wenn noch nicht existiert! QFile serverProfilesfile(QString::fromUtf8(myServerProfilesFile.c_str())); if(!serverProfilesfile.exists()) { TiXmlDocument doc; TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "UTF-8", ""); doc.LinkEndChild( decl ); TiXmlElement * root = new TiXmlElement( "PokerTH" ); doc.LinkEndChild( root ); TiXmlElement * profiles = new TiXmlElement( "ServerProfiles" ); root->LinkEndChild( profiles ); doc.SaveFile(QString::fromUtf8(myServerProfilesFile.c_str()).toStdString()); } //Liste Füllen fillServerProfileList(); } QDialog::exec(); } void joinNetworkGameDialogImpl::startClient() { // TODO: Check input values! } void joinNetworkGameDialogImpl::fillServerProfileList() { treeWidget->clear(); TiXmlDocument doc(QString::fromUtf8(myServerProfilesFile.c_str()).toStdString()); if(!doc.LoadFile()) { QMessageBox::warning(this, tr("Load Server-Profile-File Error"), tr("Could not load server-profiles-file:\n"+QString::fromUtf8(myServerProfilesFile.c_str()).toAscii()), QMessageBox::Close); } TiXmlHandle docHandle( &doc ); TiXmlElement* profile = docHandle.FirstChild( "PokerTH" ).FirstChild( "ServerProfiles" ).FirstChild().ToElement(); if ( profile ) { for( profile; profile; profile = profile->NextSiblingElement()) { QTreeWidgetItem *item = new QTreeWidgetItem(treeWidget,0); item->setData(0, 0, QString::fromUtf8(profile->Attribute("Name"))); item->setData(1, 0, QString::fromUtf8(profile->Attribute("Address"))); item->setData(2, 0, profile->Attribute("Port")); string isIpv6 = "no"; int tempInt = 0; profile->QueryIntAttribute("IsIpv6", &tempInt ); if( tempInt == 1 ) { isIpv6 = "yes"; } item->setData(3, 0, QString::fromUtf8(isIpv6.c_str())); treeWidget->addTopLevelItem(item); } } else { cout << "No Profiles Found \n"; } treeWidget->resizeColumnToContents ( 0 ); treeWidget->resizeColumnToContents ( 1 ); treeWidget->resizeColumnToContents ( 2 ); treeWidget->resizeColumnToContents ( 3 ); } void joinNetworkGameDialogImpl::itemFillForm (QTreeWidgetItem* item, int column) { bool toIntTrue; TiXmlDocument doc(QString::fromUtf8(myServerProfilesFile.c_str()).toStdString()); if(!doc.LoadFile()) { QMessageBox::warning(this, tr("Load Server-Profile-File Error"), tr("Could not load server-profiles-file:\n"+QString::fromUtf8(myServerProfilesFile.c_str()).toAscii()), QMessageBox::Close); } TiXmlHandle docHandle( &doc ); TiXmlElement* profile = docHandle.FirstChild( "PokerTH" ).FirstChild( "ServerProfiles" ).FirstChild( item->data(0,0).toString().toStdString() ).ToElement(); if ( profile ) { lineEdit_profileName->setText(QString::fromUtf8(profile->Attribute("Name"))); lineEdit_ipAddress->setText(QString::fromUtf8(profile->Attribute("Address"))); lineEdit_password->setText(QString::fromUtf8(profile->Attribute("Password"))); spinBox_port->setValue(QString::fromUtf8(profile->Attribute("Port")).toInt(&toIntTrue, 10)); checkBox_ipv6->setChecked(QString::fromUtf8(profile->Attribute("IsIpv6")).toInt(&toIntTrue, 10)); } pushButton_delete->setEnabled(TRUE); } void joinNetworkGameDialogImpl::saveServerProfile() { // bool toIntTrue; TiXmlDocument doc(QString::fromUtf8(myServerProfilesFile.c_str()).toStdString()); if(!doc.LoadFile()) { QMessageBox::warning(this, tr("Load Server-Profile-File Error"), tr("Could not load server-profiles-file:\n"+QString::fromUtf8(myServerProfilesFile.c_str()).toAscii()), QMessageBox::Close); } TiXmlHandle docHandle( &doc ); TiXmlElement* profiles = docHandle.FirstChild( "PokerTH" ).FirstChild( "ServerProfiles" ).ToElement(); if ( profiles ) { TiXmlElement * testProfile = docHandle.FirstChild( "PokerTH" ).FirstChild( "ServerProfiles" ).FirstChild( lineEdit_profileName->text().toStdString() ).ToElement(); if( testProfile ) { // Wenn der Name schon existiert --> Überschreiben? QMessageBox msgBox(QMessageBox::Warning, tr("Save Server Profile Error"), tr("A profile with the name: \""+lineEdit_profileName->text().toAscii()+"\" already exists.\nWould you like to overwrite ?"), QMessageBox::Yes | QMessageBox::No, this); switch (msgBox.exec()) { case QMessageBox::Yes: { // yes was clicked // remove the old testProfile->Parent()->RemoveChild(testProfile); // write the new TiXmlElement * profile1 = new TiXmlElement( lineEdit_profileName->text().toUtf8().constData() ); profiles->LinkEndChild( profile1 ); profile1->SetAttribute("Name", lineEdit_profileName->text().toUtf8().constData()); profile1->SetAttribute("Address", lineEdit_ipAddress->text().toUtf8().constData()); profile1->SetAttribute("Password", lineEdit_password->text().toUtf8().constData()); profile1->SetAttribute("Port", spinBox_port->value()); profile1->SetAttribute("IsIpv6", checkBox_ipv6->isChecked()); } break; case QMessageBox::No: // no was clicked break; default: // should never be reached break; } } else { // Wenn der Name nicht existiert --> speichern TiXmlElement * profile2 = new TiXmlElement( lineEdit_profileName->text().toStdString() ); profiles->LinkEndChild( profile2 ); profile2->SetAttribute("Name", lineEdit_profileName->text().toUtf8().constData()); profile2->SetAttribute("Address", lineEdit_ipAddress->text().toUtf8().constData()); profile2->SetAttribute("Password", lineEdit_password->text().toUtf8().constData()); profile2->SetAttribute("Port", spinBox_port->value()); profile2->SetAttribute("IsIpv6", checkBox_ipv6->isChecked()); } } else { QMessageBox::warning(this, tr("Read Server-Profile List Error"), tr("Could not read server-profiles list"), QMessageBox::Close); } if(!doc.SaveFile()) { QMessageBox::warning(this, tr("Save Server-Profile-File Error"), tr("Could not save server-profiles-file:\n"+QString::fromUtf8(myServerProfilesFile.c_str()).toAscii()), QMessageBox::Close); } fillServerProfileList(); } void joinNetworkGameDialogImpl::deleteServerProfile() { TiXmlDocument doc(QString::fromUtf8(myServerProfilesFile.c_str()).toStdString()); if(!doc.LoadFile()) { QMessageBox::warning(this, tr("Load Server-Profile-File Error"), tr("Could not load server-profiles-file:\n"+QString::fromUtf8(myServerProfilesFile.c_str()).toAscii()), QMessageBox::Close); } else { TiXmlHandle docHandle( &doc ); TiXmlElement* profile = docHandle.FirstChild( "PokerTH" ).FirstChild( "ServerProfiles" ).FirstChild( treeWidget->currentItem()->data(0,0).toString().toUtf8().constData() ).ToElement(); if ( profile ) { profile->Parent()->RemoveChild(profile); } if(!doc.SaveFile()) { QMessageBox::warning(this, tr("Save Server-Profile-File Error"), tr("Could not save server-profiles-file:\n"+QString::fromUtf8(myServerProfilesFile.c_str()).toAscii()), QMessageBox::Close); } //Liste Füllen fillServerProfileList(); } pushButton_delete->setDisabled(TRUE); } void joinNetworkGameDialogImpl::keyPressEvent ( QKeyEvent * event ) { // std::cout << "key" << event->key(); if (event->key() == 16777220) { pushButton_connect->click(); } //ENTER } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_nv_ref_clk_enable.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_nv_ref_clk_enable.C /// @brief Enable NV reference clocks (FAPI2) /// /// @author Joe McGill <[email protected]> /// // // *HWP HWP Owner: Joe McGill <[email protected]> // *HWP FW Owner: Thi Tran <[email protected]> // *HWP Team: Perv // *HWP Level: 2 // *HWP Consumed by: HB // //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <p9_nv_ref_clk_enable.H> #include <p9_perv_scom_addresses.H> #include <p9_perv_scom_addresses_fld.H> //------------------------------------------------------------------------------ // Constant definitions //------------------------------------------------------------------------------ const uint16_t TPFSI_OFFCHIP_REFCLK_EN_NV = 0x7; //------------------------------------------------------------------------------ // Function definitions //------------------------------------------------------------------------------ fapi2::ReturnCode p9_nv_ref_clk_enable(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { FAPI_INF("Start"); fapi2::buffer<uint64_t> l_root_ctrl6; FAPI_TRY(fapi2::getScom(i_target, PERV_ROOT_CTRL6_SCOM, l_root_ctrl6), "Error from getScom (PERV_ROOT_CTRL6_SCOM)"); l_root_ctrl6.insertFromRight<PERV_ROOT_CTRL6_TPFSI_OFFCHIP_REFCLK_EN_DC, PERV_ROOT_CTRL6_TPFSI_OFFCHIP_REFCLK_EN_DC_LEN>(TPFSI_OFFCHIP_REFCLK_EN_NV); FAPI_TRY(fapi2::putScom(i_target, PERV_ROOT_CTRL6_SCOM, l_root_ctrl6), "Error from putScom (PERV_ROOT_CTRL6_SCOM)"); fapi_try_exit: FAPI_INF("End"); return fapi2::current_err; } <commit_msg>p9_nv_ref_clk_enable -- shift NV refclock field programming<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_nv_ref_clk_enable.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_nv_ref_clk_enable.C /// @brief Enable NV reference clocks (FAPI2) /// /// @author Joe McGill <[email protected]> /// // // *HWP HWP Owner: Joe McGill <[email protected]> // *HWP FW Owner: Thi Tran <[email protected]> // *HWP Team: Perv // *HWP Level: 2 // *HWP Consumed by: HB // //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <p9_nv_ref_clk_enable.H> #include <p9_perv_scom_addresses.H> #include <p9_perv_scom_addresses_fld.H> //------------------------------------------------------------------------------ // Constant definitions //------------------------------------------------------------------------------ const uint16_t TPFSI_OFFCHIP_REFCLK_EN_NV = 0xF; //------------------------------------------------------------------------------ // Function definitions //------------------------------------------------------------------------------ fapi2::ReturnCode p9_nv_ref_clk_enable(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { FAPI_INF("Start"); fapi2::buffer<uint64_t> l_root_ctrl6; FAPI_TRY(fapi2::getScom(i_target, PERV_ROOT_CTRL6_SCOM, l_root_ctrl6), "Error from getScom (PERV_ROOT_CTRL6_SCOM)"); l_root_ctrl6.insertFromRight<PERV_ROOT_CTRL6_TSFSI_NV_REFCLK_EN_DC, PERV_ROOT_CTRL6_TSFSI_NV_REFCLK_EN_DC_LEN>(TPFSI_OFFCHIP_REFCLK_EN_NV); FAPI_TRY(fapi2::putScom(i_target, PERV_ROOT_CTRL6_SCOM, l_root_ctrl6), "Error from putScom (PERV_ROOT_CTRL6_SCOM)"); fapi_try_exit: FAPI_INF("End"); return fapi2::current_err; } <|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. // //////////////////////////////////////////////////////////////////////////// #include "impl/external_commit_helper.hpp" #include "impl/realm_coordinator.hpp" #include <realm/commit_log.hpp> #include <realm/replication.hpp> using namespace realm; using namespace realm::_impl; ExternalCommitHelper::ExternalCommitHelper(RealmCoordinator& parent) { } ExternalCommitHelper::~ExternalCommitHelper() { } <commit_msg>Change generic external commit helper to just be commented out for now<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. // //////////////////////////////////////////////////////////////////////////// #include "impl/external_commit_helper.hpp" #include "impl/realm_coordinator.hpp" #include <realm/commit_log.hpp> #include <realm/replication.hpp> using namespace realm; using namespace realm::_impl; ExternalCommitHelper::ExternalCommitHelper(RealmCoordinator& parent) //: m_parent(parent) //, m_history(realm::make_client_history(parent.get_path(), parent.get_encryption_key().data())) //, m_sg(*m_history, parent.is_in_memory() ? SharedGroup::durability_MemOnly : SharedGroup::durability_Full, // parent.get_encryption_key().data()) //, m_thread(std::async(std::launch::async, [=] { // m_sg.begin_read(); // while (m_sg.wait_for_change()) { // m_sg.end_read(); // m_sg.begin_read(); // m_parent.on_change(); // } //})) { } ExternalCommitHelper::~ExternalCommitHelper() { //m_sg.wait_for_change_release(); //m_thread.wait(); // Wait for the thread to exit } <|endoftext|>
<commit_before>/* * Ascent MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "StdAfx.h" #include "EventableObject.h" EventableObject::~EventableObject() { /* decrement event count on all events */ EventMap::iterator itr = m_events.begin(); for(; itr != m_events.end(); ++itr) { itr->second->deleted = true; itr->second->DecRef(); } m_events.clear(); } EventableObject::EventableObject() { /* commented, these will be allocated when the first event is added. */ //m_event_Instanceid = event_GetInstanceID(); //m_holder = sEventMgr.GetEventHolder(m_event_Instanceid); m_holder = 0; m_event_Instanceid = -1; } void EventableObject::event_AddEvent(TimedEvent * ptr) { m_lock.Acquire(); if(!m_holder) { m_event_Instanceid = event_GetInstanceID(); m_holder = sEventMgr.GetEventHolder(m_event_Instanceid); } ptr->IncRef(); ptr->instanceId = m_event_Instanceid; pair<uint32,TimedEvent*> p(ptr->eventType, ptr); m_events.insert( p ); m_lock.Release(); /* Add to event manager */ if(!m_holder) { /* relocate to -1 eventholder :/ */ m_event_Instanceid = -1; m_holder = sEventMgr.GetEventHolder(m_event_Instanceid); ASSERT(m_holder); } m_holder->AddEvent(ptr); } void EventableObject::event_RemoveByPointer(TimedEvent * ev) { m_lock.Acquire(); EventMap::iterator itr = m_events.find(ev->eventType); EventMap::iterator it2; if(itr != m_events.end()) { do { it2 = itr++; if(it2->second == ev) { it2->second->deleted = true; it2->second->DecRef(); m_events.erase(it2); m_lock.Release(); return; } } while(itr != m_events.upper_bound(ev->eventType)); } m_lock.Release(); } void EventableObject::event_RemoveEvents(uint32 EventType) { m_lock.Acquire(); if(!m_events.size()) { m_lock.Release(); return; } if(EventType == EVENT_REMOVAL_FLAG_ALL) { EventMap::iterator itr = m_events.begin(); for(; itr != m_events.end(); ++itr) { itr->second->deleted = true; itr->second->DecRef(); } m_events.clear(); } else { EventMap::iterator itr = m_events.find(EventType); EventMap::iterator it2; if(itr != m_events.end()) { do { it2 = itr++; it2->second->deleted = true; it2->second->DecRef(); m_events.erase(it2); } while(itr != m_events.upper_bound(EventType)); } } m_lock.Release(); } void EventableObject::event_RemoveEvents() { event_RemoveEvents(EVENT_REMOVAL_FLAG_ALL); } void EventableObject::event_ModifyTimeLeft(uint32 EventType, uint32 TimeLeft,bool unconditioned) { m_lock.Acquire(); if(!m_events.size()) { m_lock.Release(); return; } EventMap::iterator itr = m_events.find(EventType); if(itr != m_events.end()) { do { if(unconditioned) itr->second->currTime = TimeLeft; else itr->second->currTime = ((int32)TimeLeft > itr->second->msTime) ? itr->second->msTime : (int32)TimeLeft; ++itr; } while(itr != m_events.upper_bound(EventType)); } m_lock.Release(); } void EventableObject::event_ModifyTime(uint32 EventType, uint32 Time) { m_lock.Acquire(); if(!m_events.size()) { m_lock.Release(); return; } EventMap::iterator itr = m_events.find(EventType); if(itr != m_events.end()) { do { itr->second->msTime = Time; ++itr; } while(itr != m_events.upper_bound(EventType)); } m_lock.Release(); } void EventableObject::event_ModifyTimeAndTimeLeft(uint32 EventType, uint32 Time) { m_lock.Acquire(); if(!m_events.size()) { m_lock.Release(); return; } EventMap::iterator itr = m_events.find(EventType); if(itr != m_events.end()) { do { itr->second->currTime = itr->second->msTime = Time; ++itr; } while(itr != m_events.upper_bound(EventType)); } m_lock.Release(); } bool EventableObject::event_HasEvent(uint32 EventType) { bool ret = false; m_lock.Acquire(); if(!m_events.size()) { m_lock.Release(); return false; } //ret = m_events.find(EventType) == m_events.end() ? false : true; EventMap::iterator itr = m_events.find(EventType); if(itr != m_events.end()) { do { if(!itr->second->deleted) { ret = true; break; } ++itr; } while(itr != m_events.upper_bound(EventType)); } m_lock.Release(); return ret; } EventableObjectHolder::EventableObjectHolder(int32 instance_id) : mInstanceId(instance_id) { sEventMgr.AddEventHolder(this, instance_id); } EventableObjectHolder::~EventableObjectHolder() { sEventMgr.RemoveEventHolder(this); /* decrement events reference count */ m_lock.Acquire(); EventList::iterator itr = m_events.begin(); for(; itr != m_events.end(); ++itr) (*itr)->DecRef(); m_lock.Release(); } void EventableObjectHolder::Update(uint32 time_difference) { m_lock.Acquire(); // <<<< /* Insert any pending objects in the insert pool. */ m_insertPoolLock.Acquire(); InsertableQueue::iterator iqi; InsertableQueue::iterator iq2 = m_insertPool.begin(); while(iq2 != m_insertPool.end()) { iqi = iq2++; if((*iqi)->deleted || (*iqi)->instanceId != mInstanceId) (*iqi)->DecRef(); else m_events.push_back( (*iqi) ); m_insertPool.erase(iqi); } m_insertPoolLock.Release(); /* Now we can proceed normally. */ EventList::iterator itr = m_events.begin(); EventList::iterator it2; TimedEvent * ev; while(itr != m_events.end()) { it2 = itr++; if((*it2)->instanceId != mInstanceId || (*it2)->deleted || ( mInstanceId == WORLD_INSTANCE && (*it2)->eventFlag & EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT)) { // remove from this list. (*it2)->DecRef(); m_events.erase(it2); continue; } // Event Update Procedure ev = *it2; if((uint32)ev->currTime <= time_difference) { // execute the callback ev->cb->execute(); // check if the event is expired now. if(ev->repeats && --ev->repeats == 0) { // Event expired :> /* remove the event from the object */ /*obj = (EventableObject*)ev->obj; obj->event_RemoveByPointer(ev);*/ /* remove the event from here */ ev->deleted = true; ev->DecRef(); m_events.erase(it2); continue; } else if(ev->deleted) { // event is now deleted ev->DecRef(); m_events.erase(it2); continue; } // event has to repeat again, reset the timer ev->currTime = ev->msTime; } else { // event is still "waiting", subtract time difference ev->currTime -= time_difference; } } m_lock.Release(); } void EventableObject::event_Relocate() { /* prevent any new stuff from getting added */ m_lock.Acquire(); EventableObjectHolder * nh = sEventMgr.GetEventHolder(event_GetInstanceID()); if(nh != m_holder) { // whee, we changed event holder :> // doing this will change the instanceid on all the events, as well as add to the new holder. // no need to do this if we don't have any events, though. if(m_events.size()) { /* shitty sanity check. xUdd sucks. */ if(!nh) nh = sEventMgr.GetEventHolder(-1); nh->AddObject(this); } // reset our m_holder pointer and instance id m_event_Instanceid = nh->GetInstanceID(); m_holder = nh; } /* safe again to add */ m_lock.Release(); } uint32 EventableObject::event_GetEventPeriod(uint32 EventType) { uint32 ret = 0; m_lock.Acquire(); EventMap::iterator itr = m_events.find(EventType); if(itr != m_events.end()) ret = (uint32)itr->second->msTime; m_lock.Release(); return ret; } void EventableObjectHolder::AddEvent(TimedEvent * ev) { // m_lock NEEDS TO BE A RECURSIVE MUTEX ev->IncRef(); if(!m_lock.AttemptAcquire()) { m_insertPoolLock.Acquire(); m_insertPool.push_back( ev ); m_insertPoolLock.Release(); } else { m_events.push_back( ev ); m_lock.Release(); } } void EventableObjectHolder::AddObject(EventableObject * obj) { // transfer all of this objects events into our holder if(!m_lock.AttemptAcquire()) { // The other thread is obviously occupied. We have to use an insert pool here, otherwise // if 2 threads relocate at once we'll hit a deadlock situation. m_insertPoolLock.Acquire(); EventMap::iterator it2; for(EventMap::iterator itr = obj->m_events.begin(); itr != obj->m_events.end(); ++itr) { // ignore deleted events (shouldn't be any in here, actually) if(itr->second->deleted) { /*it2 = itr++; itr->second->DecRef(); obj->m_events.erase(it2);*/ continue; } if(mInstanceId == WORLD_INSTANCE && itr->second->eventFlag & EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT) continue; itr->second->IncRef(); itr->second->instanceId = mInstanceId; m_insertPool.push_back(itr->second); } // Release the insert pool. m_insertPoolLock.Release(); // Ignore the rest of this stuff return; } for(EventMap::iterator itr = obj->m_events.begin(); itr != obj->m_events.end(); ++itr) { // ignore deleted events if(itr->second->deleted) continue; if(mInstanceId == WORLD_INSTANCE && itr->second->eventFlag & EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT) continue; itr->second->IncRef(); itr->second->instanceId = mInstanceId; m_events.push_back( itr->second ); } m_lock.Release(); } <commit_msg>* crash fix<commit_after>/* * Ascent MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "StdAfx.h" #include "EventableObject.h" EventableObject::~EventableObject() { /* decrement event count on all events */ EventMap::iterator itr = m_events.begin(); for(; itr != m_events.end(); ++itr) { itr->second->deleted = true; itr->second->DecRef(); } m_events.clear(); } EventableObject::EventableObject() { /* commented, these will be allocated when the first event is added. */ //m_event_Instanceid = event_GetInstanceID(); //m_holder = sEventMgr.GetEventHolder(m_event_Instanceid); m_holder = 0; m_event_Instanceid = -1; } void EventableObject::event_AddEvent(TimedEvent * ptr) { m_lock.Acquire(); if(!m_holder) { m_event_Instanceid = event_GetInstanceID(); m_holder = sEventMgr.GetEventHolder(m_event_Instanceid); } ptr->IncRef(); ptr->instanceId = m_event_Instanceid; pair<uint32,TimedEvent*> p(ptr->eventType, ptr); m_events.insert( p ); m_lock.Release(); /* Add to event manager */ if(!m_holder) { /* relocate to -1 eventholder :/ */ m_event_Instanceid = -1; m_holder = sEventMgr.GetEventHolder(m_event_Instanceid); ASSERT(m_holder); } m_holder->AddEvent(ptr); } void EventableObject::event_RemoveByPointer(TimedEvent * ev) { m_lock.Acquire(); EventMap::iterator itr = m_events.find(ev->eventType); EventMap::iterator it2; if(itr != m_events.end()) { do { it2 = itr++; if(it2->second == ev) { it2->second->deleted = true; it2->second->DecRef(); m_events.erase(it2); m_lock.Release(); return; } } while(itr != m_events.upper_bound(ev->eventType)); } m_lock.Release(); } void EventableObject::event_RemoveEvents(uint32 EventType) { m_lock.Acquire(); if(!m_events.size()) { m_lock.Release(); return; } if(EventType == EVENT_REMOVAL_FLAG_ALL) { EventMap::iterator itr = m_events.begin(); for(; itr != m_events.end(); ++itr) { itr->second->deleted = true; itr->second->DecRef(); } m_events.clear(); } else { EventMap::iterator itr = m_events.find(EventType); EventMap::iterator it2; if(itr != m_events.end()) { do { it2 = itr++; it2->second->deleted = true; it2->second->DecRef(); m_events.erase(it2); } while(itr != m_events.upper_bound(EventType)); } } m_lock.Release(); } void EventableObject::event_RemoveEvents() { event_RemoveEvents(EVENT_REMOVAL_FLAG_ALL); } void EventableObject::event_ModifyTimeLeft(uint32 EventType, uint32 TimeLeft,bool unconditioned) { m_lock.Acquire(); if(!m_events.size()) { m_lock.Release(); return; } EventMap::iterator itr = m_events.find(EventType); if(itr != m_events.end()) { do { if(unconditioned) itr->second->currTime = TimeLeft; else itr->second->currTime = ((int32)TimeLeft > itr->second->msTime) ? itr->second->msTime : (int32)TimeLeft; ++itr; } while(itr != m_events.upper_bound(EventType)); } m_lock.Release(); } void EventableObject::event_ModifyTime(uint32 EventType, uint32 Time) { m_lock.Acquire(); if(!m_events.size()) { m_lock.Release(); return; } EventMap::iterator itr = m_events.find(EventType); if(itr != m_events.end()) { do { itr->second->msTime = Time; ++itr; } while(itr != m_events.upper_bound(EventType)); } m_lock.Release(); } void EventableObject::event_ModifyTimeAndTimeLeft(uint32 EventType, uint32 Time) { m_lock.Acquire(); if(!m_events.size()) { m_lock.Release(); return; } EventMap::iterator itr = m_events.find(EventType); if(itr != m_events.end()) { do { itr->second->currTime = itr->second->msTime = Time; ++itr; } while(itr != m_events.upper_bound(EventType)); } m_lock.Release(); } bool EventableObject::event_HasEvent(uint32 EventType) { bool ret = false; m_lock.Acquire(); if(!m_events.size()) { m_lock.Release(); return false; } //ret = m_events.find(EventType) == m_events.end() ? false : true; EventMap::iterator itr = m_events.find(EventType); if(itr != m_events.end()) { do { if(!itr->second->deleted) { ret = true; break; } ++itr; } while(itr != m_events.upper_bound(EventType)); } m_lock.Release(); return ret; } EventableObjectHolder::EventableObjectHolder(int32 instance_id) : mInstanceId(instance_id) { sEventMgr.AddEventHolder(this, instance_id); } EventableObjectHolder::~EventableObjectHolder() { sEventMgr.RemoveEventHolder(this); /* decrement events reference count */ m_lock.Acquire(); EventList::iterator itr = m_events.begin(); for(; itr != m_events.end(); ++itr) (*itr)->DecRef(); m_lock.Release(); } void EventableObjectHolder::Update(uint32 time_difference) { m_lock.Acquire(); // <<<< /* Insert any pending objects in the insert pool. */ m_insertPoolLock.Acquire(); InsertableQueue::iterator iqi; InsertableQueue::iterator iq2 = m_insertPool.begin(); while(iq2 != m_insertPool.end()) { iqi = iq2++; if((*iqi)->deleted || (*iqi)->instanceId != mInstanceId) (*iqi)->DecRef(); else m_events.push_back( (*iqi) ); m_insertPool.erase(iqi); } m_insertPoolLock.Release(); /* Now we can proceed normally. */ EventList::iterator itr = m_events.begin(); EventList::iterator it2; TimedEvent * ev; while(itr != m_events.end()) { it2 = itr++; if((*it2)->instanceId != mInstanceId || (*it2)->deleted || ( mInstanceId == WORLD_INSTANCE && (*it2)->eventFlag & EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT)) { // remove from this list. (*it2)->DecRef(); m_events.erase(it2); continue; } // Event Update Procedure ev = *it2; if((uint32)ev->currTime <= time_difference) { // execute the callback ev->cb->execute(); // check if the event is expired now. if(ev->repeats && --ev->repeats == 0) { // Event expired :> /* remove the event from the object */ /*obj = (EventableObject*)ev->obj; obj->event_RemoveByPointer(ev);*/ /* remove the event from here */ ev->deleted = true; ev->DecRef(); m_events.erase(it2); continue; } else if(ev->deleted) { // event is now deleted ev->DecRef(); m_events.erase(it2); continue; } // event has to repeat again, reset the timer ev->currTime = ev->msTime; } else { // event is still "waiting", subtract time difference ev->currTime -= time_difference; } } m_lock.Release(); } void EventableObject::event_Relocate() { /* prevent any new stuff from getting added */ m_lock.Acquire(); EventableObjectHolder * nh = sEventMgr.GetEventHolder(event_GetInstanceID()); if(nh != m_holder) { // whee, we changed event holder :> // doing this will change the instanceid on all the events, as well as add to the new holder. // no need to do this if we don't have any events, though. if(!nh) nh = sEventMgr.GetEventHolder(-1); nh->AddObject(this); // reset our m_holder pointer and instance id m_event_Instanceid = nh->GetInstanceID(); m_holder = nh; } /* safe again to add */ m_lock.Release(); } uint32 EventableObject::event_GetEventPeriod(uint32 EventType) { uint32 ret = 0; m_lock.Acquire(); EventMap::iterator itr = m_events.find(EventType); if(itr != m_events.end()) ret = (uint32)itr->second->msTime; m_lock.Release(); return ret; } void EventableObjectHolder::AddEvent(TimedEvent * ev) { // m_lock NEEDS TO BE A RECURSIVE MUTEX ev->IncRef(); if(!m_lock.AttemptAcquire()) { m_insertPoolLock.Acquire(); m_insertPool.push_back( ev ); m_insertPoolLock.Release(); } else { m_events.push_back( ev ); m_lock.Release(); } } void EventableObjectHolder::AddObject(EventableObject * obj) { // transfer all of this objects events into our holder if(!m_lock.AttemptAcquire()) { // The other thread is obviously occupied. We have to use an insert pool here, otherwise // if 2 threads relocate at once we'll hit a deadlock situation. m_insertPoolLock.Acquire(); EventMap::iterator it2; for(EventMap::iterator itr = obj->m_events.begin(); itr != obj->m_events.end(); ++itr) { // ignore deleted events (shouldn't be any in here, actually) if(itr->second->deleted) { /*it2 = itr++; itr->second->DecRef(); obj->m_events.erase(it2);*/ continue; } if(mInstanceId == WORLD_INSTANCE && itr->second->eventFlag & EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT) continue; itr->second->IncRef(); itr->second->instanceId = mInstanceId; m_insertPool.push_back(itr->second); } // Release the insert pool. m_insertPoolLock.Release(); // Ignore the rest of this stuff return; } for(EventMap::iterator itr = obj->m_events.begin(); itr != obj->m_events.end(); ++itr) { // ignore deleted events if(itr->second->deleted) continue; if(mInstanceId == WORLD_INSTANCE && itr->second->eventFlag & EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT) continue; itr->second->IncRef(); itr->second->instanceId = mInstanceId; m_events.push_back( itr->second ); } m_lock.Release(); } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2015, PickNik LLC * 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 PickNik LLC 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. *********************************************************************/ /* Author: Dave Coleman Desc: Helper ros_control hardware interface that loads configurations */ #include <ros_control_boilerplate/generic_hw_interface.h> #include <limits> namespace ros_control_boilerplate { GenericHWInterface::GenericHWInterface(ros::NodeHandle &nh, urdf::Model *urdf_model) : nh_(nh) , use_rosparam_joint_limits_(false) { // Check if the URDF model needs to be loaded if (urdf_model == NULL) loadURDF(nh, "robot_description"); else urdf_model_ = urdf_model; ROS_INFO_NAMED("generic_hw_interface", "GenericHWInterface Ready."); } void GenericHWInterface::init() { ROS_INFO_STREAM_NAMED("generic_hw_interface", "Reading rosparams from namespace: " << nh_.getNamespace()); // Get joint names nh_.getParam("hardware_interface/joints", joint_names_); if (joint_names_.size() == 0) { ROS_FATAL_STREAM_NAMED("generic_hw_interface", "No joints found on parameter server for controller, did you load the proper yaml file?" << " Namespace: " << nh_.getNamespace() << "/hardware_interface/joints"); exit(-1); } num_joints_ = joint_names_.size(); // Status joint_position_.resize(num_joints_, 0.0); joint_velocity_.resize(num_joints_, 0.0); joint_effort_.resize(num_joints_, 0.0); // Command joint_position_command_.resize(num_joints_, 0.0); joint_velocity_command_.resize(num_joints_, 0.0); joint_effort_command_.resize(num_joints_, 0.0); // Limits joint_position_lower_limits_.resize(num_joints_, 0.0); joint_position_upper_limits_.resize(num_joints_, 0.0); joint_velocity_limits_.resize(num_joints_, 0.0); joint_effort_limits_.resize(num_joints_, 0.0); // Initialize interfaces for each joint for (std::size_t joint_id = 0; joint_id < num_joints_; ++joint_id) { ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Loading joint name: " << joint_names_[joint_id]); // Create joint state interface joint_state_interface_.registerHandle(hardware_interface::JointStateHandle( joint_names_[joint_id], &joint_position_[joint_id], &joint_velocity_[joint_id], &joint_effort_[joint_id])); // Add command interfaces to joints // TODO: decide based on transmissions? hardware_interface::JointHandle joint_handle_position = hardware_interface::JointHandle( joint_state_interface_.getHandle(joint_names_[joint_id]), &joint_position_command_[joint_id]); position_joint_interface_.registerHandle(joint_handle_position); hardware_interface::JointHandle joint_handle_velocity = hardware_interface::JointHandle( joint_state_interface_.getHandle(joint_names_[joint_id]), &joint_velocity_command_[joint_id]); velocity_joint_interface_.registerHandle(joint_handle_velocity); hardware_interface::JointHandle joint_handle_effort = hardware_interface::JointHandle( joint_state_interface_.getHandle(joint_names_[joint_id]), &joint_effort_command_[joint_id]); effort_joint_interface_.registerHandle(joint_handle_effort); // Load the joint limits registerJointLimits(joint_handle_position, joint_handle_velocity, joint_handle_effort, joint_id); } // end for each joint registerInterface(&joint_state_interface_); // From RobotHW base class. registerInterface(&position_joint_interface_); // From RobotHW base class. registerInterface(&velocity_joint_interface_); // From RobotHW base class. registerInterface(&effort_joint_interface_); // From RobotHW base class. } void GenericHWInterface::registerJointLimits(const hardware_interface::JointHandle &joint_handle_position, const hardware_interface::JointHandle &joint_handle_velocity, const hardware_interface::JointHandle &joint_handle_effort, std::size_t joint_id) { // Default values joint_position_lower_limits_[joint_id] = -std::numeric_limits<double>::max(); joint_position_upper_limits_[joint_id] = std::numeric_limits<double>::max(); joint_velocity_limits_[joint_id] = std::numeric_limits<double>::max(); joint_effort_limits_[joint_id] = std::numeric_limits<double>::max(); // Limits datastructures joint_limits_interface::JointLimits joint_limits; // Position joint_limits_interface::SoftJointLimits soft_limits; // Soft Position bool has_joint_limits = false; bool has_soft_limits = false; // Get limits from URDF if (urdf_model_ == NULL) { ROS_WARN_STREAM_NAMED("generic_hw_interface", "No URDF model loaded, unable to get joint limits"); return; } // Get limits from URDF const boost::shared_ptr<const urdf::Joint> urdf_joint = urdf_model_->getJoint(joint_names_[joint_id]); // Get main joint limits if (urdf_joint == NULL) { ROS_ERROR_STREAM_NAMED("generic_hw_interface", "URDF joint not found " << joint_names_[joint_id]); return; } // Get limits from URDF if (joint_limits_interface::getJointLimits(urdf_joint, joint_limits)) { has_joint_limits = true; ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Joint " << joint_names_[joint_id] << " has URDF position limits [" << joint_limits.min_position << ", " << joint_limits.max_position << "]"); if (joint_limits.has_velocity_limits) ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Joint " << joint_names_[joint_id] << " has URDF velocity limit [" << joint_limits.max_velocity << "]"); } else { if (urdf_joint->type != urdf::Joint::CONTINUOUS) ROS_WARN_STREAM_NAMED("generic_hw_interface", "Joint " << joint_names_[joint_id] << " does not have a URDF " "position limit"); } // Get limits from ROS param if (use_rosparam_joint_limits_) { if (joint_limits_interface::getJointLimits(joint_names_[joint_id], nh_, joint_limits)) { has_joint_limits = true; ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Joint " << joint_names_[joint_id] << " has rosparam position limits [" << joint_limits.min_position << ", " << joint_limits.max_position << "]"); if (joint_limits.has_velocity_limits) ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Joint " << joint_names_[joint_id] << " has rosparam velocity limit [" << joint_limits.max_velocity << "]"); } // the else debug message provided internally by joint_limits_interface } // Get soft limits from URDF if (joint_limits_interface::getSoftJointLimits(urdf_joint, soft_limits)) { has_soft_limits = true; ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Joint " << joint_names_[joint_id] << " has soft joint limits."); } else { ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Joint " << joint_names_[joint_id] << " does not have soft joint " "limits"); } // Quit we we haven't found any limits in URDF or rosparam server if (!has_joint_limits) { return; } // Copy position limits if available if (joint_limits.has_position_limits) { // Slighly reduce the joint limits to prevent floating point errors joint_limits.min_position += std::numeric_limits<double>::epsilon(); joint_limits.max_position -= std::numeric_limits<double>::epsilon(); joint_position_lower_limits_[joint_id] = joint_limits.min_position; joint_position_upper_limits_[joint_id] = joint_limits.max_position; } // Copy velocity limits if available if (joint_limits.has_velocity_limits) { joint_velocity_limits_[joint_id] = joint_limits.max_velocity; } // Copy effort limits if available if (joint_limits.has_effort_limits) { joint_effort_limits_[joint_id] = joint_limits.max_effort; } if (has_soft_limits) // Use soft limits { ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Using soft saturation limits"); const joint_limits_interface::PositionJointSoftLimitsHandle soft_handle_position(joint_handle_position, joint_limits, soft_limits); pos_jnt_soft_limits_.registerHandle(soft_handle_position); const joint_limits_interface::VelocityJointSoftLimitsHandle soft_handle_velocity(joint_handle_velocity, joint_limits, soft_limits); vel_jnt_soft_limits_.registerHandle(soft_handle_velocity); const joint_limits_interface::EffortJointSoftLimitsHandle soft_handle_effort(joint_handle_effort, joint_limits, soft_limits); eff_jnt_soft_limits_.registerHandle(soft_handle_effort); } else // Use saturation limits { ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Using saturation limits (not soft limits)"); const joint_limits_interface::PositionJointSaturationHandle sat_handle_position(joint_handle_position, joint_limits); pos_jnt_sat_interface_.registerHandle(sat_handle_position); const joint_limits_interface::VelocityJointSaturationHandle sat_handle_velocity(joint_handle_velocity, joint_limits); vel_jnt_sat_interface_.registerHandle(sat_handle_velocity); const joint_limits_interface::EffortJointSaturationHandle sat_handle_effort(joint_handle_effort, joint_limits); eff_jnt_sat_interface_.registerHandle(sat_handle_effort); } } void GenericHWInterface::reset() { // Reset joint limits state, in case of mode switch or e-stop pos_jnt_sat_interface_.reset(); pos_jnt_soft_limits_.reset(); } void GenericHWInterface::printState() { // WARNING: THIS IS NOT REALTIME SAFE // FOR DEBUGGING ONLY, USE AT YOUR OWN ROBOT's RISK! ROS_INFO_STREAM_THROTTLE(1, std::endl << printStateHelper()); } std::string GenericHWInterface::printStateHelper() { std::stringstream ss; std::cout.precision(15); for (std::size_t i = 0; i < num_joints_; ++i) { ss << "j" << i << ": " << std::fixed << joint_position_[i] << "\t "; ss << std::fixed << joint_velocity_[i] << "\t "; ss << std::fixed << joint_effort_[i] << std::endl; } return ss.str(); } std::string GenericHWInterface::printCommandHelper() { std::stringstream ss; std::cout.precision(15); for (std::size_t i = 0; i < num_joints_; ++i) { ss << "j" << i << ": " << std::fixed << joint_position_command_[i] << "\t "; ss << std::fixed << joint_velocity_command_[i] << "\t "; ss << std::fixed << joint_effort_command_[i] << std::endl; } return ss.str(); } void GenericHWInterface::loadURDF(ros::NodeHandle &nh, std::string param_name) { std::string urdf_string; urdf_model_ = new urdf::Model(); // search and wait for robot_description on param server while (urdf_string.empty() && ros::ok()) { std::string search_param_name; if (nh.searchParam(param_name, search_param_name)) { ROS_INFO_STREAM_NAMED("generic_hw_interface", "Waiting for model URDF on the ROS param server at location: " << nh.getNamespace() << search_param_name); nh.getParam(search_param_name, urdf_string); } else { ROS_INFO_STREAM_NAMED("generic_hw_interface", "Waiting for model URDF on the ROS param server at location: " << nh.getNamespace() << param_name); nh.getParam(param_name, urdf_string); } usleep(100000); } if (!urdf_model_->initString(urdf_string)) ROS_ERROR_STREAM_NAMED("generic_hw_interface", "Unable to load URDF model"); else ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Received URDF from param server"); } } // namespace <commit_msg>header to debug output<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2015, PickNik LLC * 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 PickNik LLC 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. *********************************************************************/ /* Author: Dave Coleman Desc: Helper ros_control hardware interface that loads configurations */ #include <ros_control_boilerplate/generic_hw_interface.h> #include <limits> namespace ros_control_boilerplate { GenericHWInterface::GenericHWInterface(ros::NodeHandle &nh, urdf::Model *urdf_model) : nh_(nh) , use_rosparam_joint_limits_(false) { // Check if the URDF model needs to be loaded if (urdf_model == NULL) loadURDF(nh, "robot_description"); else urdf_model_ = urdf_model; ROS_INFO_NAMED("generic_hw_interface", "GenericHWInterface Ready."); } void GenericHWInterface::init() { ROS_INFO_STREAM_NAMED("generic_hw_interface", "Reading rosparams from namespace: " << nh_.getNamespace()); // Get joint names nh_.getParam("hardware_interface/joints", joint_names_); if (joint_names_.size() == 0) { ROS_FATAL_STREAM_NAMED("generic_hw_interface", "No joints found on parameter server for controller, did you load the proper yaml file?" << " Namespace: " << nh_.getNamespace() << "/hardware_interface/joints"); exit(-1); } num_joints_ = joint_names_.size(); // Status joint_position_.resize(num_joints_, 0.0); joint_velocity_.resize(num_joints_, 0.0); joint_effort_.resize(num_joints_, 0.0); // Command joint_position_command_.resize(num_joints_, 0.0); joint_velocity_command_.resize(num_joints_, 0.0); joint_effort_command_.resize(num_joints_, 0.0); // Limits joint_position_lower_limits_.resize(num_joints_, 0.0); joint_position_upper_limits_.resize(num_joints_, 0.0); joint_velocity_limits_.resize(num_joints_, 0.0); joint_effort_limits_.resize(num_joints_, 0.0); // Initialize interfaces for each joint for (std::size_t joint_id = 0; joint_id < num_joints_; ++joint_id) { ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Loading joint name: " << joint_names_[joint_id]); // Create joint state interface joint_state_interface_.registerHandle(hardware_interface::JointStateHandle( joint_names_[joint_id], &joint_position_[joint_id], &joint_velocity_[joint_id], &joint_effort_[joint_id])); // Add command interfaces to joints // TODO: decide based on transmissions? hardware_interface::JointHandle joint_handle_position = hardware_interface::JointHandle( joint_state_interface_.getHandle(joint_names_[joint_id]), &joint_position_command_[joint_id]); position_joint_interface_.registerHandle(joint_handle_position); hardware_interface::JointHandle joint_handle_velocity = hardware_interface::JointHandle( joint_state_interface_.getHandle(joint_names_[joint_id]), &joint_velocity_command_[joint_id]); velocity_joint_interface_.registerHandle(joint_handle_velocity); hardware_interface::JointHandle joint_handle_effort = hardware_interface::JointHandle( joint_state_interface_.getHandle(joint_names_[joint_id]), &joint_effort_command_[joint_id]); effort_joint_interface_.registerHandle(joint_handle_effort); // Load the joint limits registerJointLimits(joint_handle_position, joint_handle_velocity, joint_handle_effort, joint_id); } // end for each joint registerInterface(&joint_state_interface_); // From RobotHW base class. registerInterface(&position_joint_interface_); // From RobotHW base class. registerInterface(&velocity_joint_interface_); // From RobotHW base class. registerInterface(&effort_joint_interface_); // From RobotHW base class. } void GenericHWInterface::registerJointLimits(const hardware_interface::JointHandle &joint_handle_position, const hardware_interface::JointHandle &joint_handle_velocity, const hardware_interface::JointHandle &joint_handle_effort, std::size_t joint_id) { // Default values joint_position_lower_limits_[joint_id] = -std::numeric_limits<double>::max(); joint_position_upper_limits_[joint_id] = std::numeric_limits<double>::max(); joint_velocity_limits_[joint_id] = std::numeric_limits<double>::max(); joint_effort_limits_[joint_id] = std::numeric_limits<double>::max(); // Limits datastructures joint_limits_interface::JointLimits joint_limits; // Position joint_limits_interface::SoftJointLimits soft_limits; // Soft Position bool has_joint_limits = false; bool has_soft_limits = false; // Get limits from URDF if (urdf_model_ == NULL) { ROS_WARN_STREAM_NAMED("generic_hw_interface", "No URDF model loaded, unable to get joint limits"); return; } // Get limits from URDF const boost::shared_ptr<const urdf::Joint> urdf_joint = urdf_model_->getJoint(joint_names_[joint_id]); // Get main joint limits if (urdf_joint == NULL) { ROS_ERROR_STREAM_NAMED("generic_hw_interface", "URDF joint not found " << joint_names_[joint_id]); return; } // Get limits from URDF if (joint_limits_interface::getJointLimits(urdf_joint, joint_limits)) { has_joint_limits = true; ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Joint " << joint_names_[joint_id] << " has URDF position limits [" << joint_limits.min_position << ", " << joint_limits.max_position << "]"); if (joint_limits.has_velocity_limits) ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Joint " << joint_names_[joint_id] << " has URDF velocity limit [" << joint_limits.max_velocity << "]"); } else { if (urdf_joint->type != urdf::Joint::CONTINUOUS) ROS_WARN_STREAM_NAMED("generic_hw_interface", "Joint " << joint_names_[joint_id] << " does not have a URDF " "position limit"); } // Get limits from ROS param if (use_rosparam_joint_limits_) { if (joint_limits_interface::getJointLimits(joint_names_[joint_id], nh_, joint_limits)) { has_joint_limits = true; ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Joint " << joint_names_[joint_id] << " has rosparam position limits [" << joint_limits.min_position << ", " << joint_limits.max_position << "]"); if (joint_limits.has_velocity_limits) ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Joint " << joint_names_[joint_id] << " has rosparam velocity limit [" << joint_limits.max_velocity << "]"); } // the else debug message provided internally by joint_limits_interface } // Get soft limits from URDF if (joint_limits_interface::getSoftJointLimits(urdf_joint, soft_limits)) { has_soft_limits = true; ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Joint " << joint_names_[joint_id] << " has soft joint limits."); } else { ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Joint " << joint_names_[joint_id] << " does not have soft joint " "limits"); } // Quit we we haven't found any limits in URDF or rosparam server if (!has_joint_limits) { return; } // Copy position limits if available if (joint_limits.has_position_limits) { // Slighly reduce the joint limits to prevent floating point errors joint_limits.min_position += std::numeric_limits<double>::epsilon(); joint_limits.max_position -= std::numeric_limits<double>::epsilon(); joint_position_lower_limits_[joint_id] = joint_limits.min_position; joint_position_upper_limits_[joint_id] = joint_limits.max_position; } // Copy velocity limits if available if (joint_limits.has_velocity_limits) { joint_velocity_limits_[joint_id] = joint_limits.max_velocity; } // Copy effort limits if available if (joint_limits.has_effort_limits) { joint_effort_limits_[joint_id] = joint_limits.max_effort; } if (has_soft_limits) // Use soft limits { ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Using soft saturation limits"); const joint_limits_interface::PositionJointSoftLimitsHandle soft_handle_position(joint_handle_position, joint_limits, soft_limits); pos_jnt_soft_limits_.registerHandle(soft_handle_position); const joint_limits_interface::VelocityJointSoftLimitsHandle soft_handle_velocity(joint_handle_velocity, joint_limits, soft_limits); vel_jnt_soft_limits_.registerHandle(soft_handle_velocity); const joint_limits_interface::EffortJointSoftLimitsHandle soft_handle_effort(joint_handle_effort, joint_limits, soft_limits); eff_jnt_soft_limits_.registerHandle(soft_handle_effort); } else // Use saturation limits { ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Using saturation limits (not soft limits)"); const joint_limits_interface::PositionJointSaturationHandle sat_handle_position(joint_handle_position, joint_limits); pos_jnt_sat_interface_.registerHandle(sat_handle_position); const joint_limits_interface::VelocityJointSaturationHandle sat_handle_velocity(joint_handle_velocity, joint_limits); vel_jnt_sat_interface_.registerHandle(sat_handle_velocity); const joint_limits_interface::EffortJointSaturationHandle sat_handle_effort(joint_handle_effort, joint_limits); eff_jnt_sat_interface_.registerHandle(sat_handle_effort); } } void GenericHWInterface::reset() { // Reset joint limits state, in case of mode switch or e-stop pos_jnt_sat_interface_.reset(); pos_jnt_soft_limits_.reset(); } void GenericHWInterface::printState() { // WARNING: THIS IS NOT REALTIME SAFE // FOR DEBUGGING ONLY, USE AT YOUR OWN ROBOT's RISK! ROS_INFO_STREAM_THROTTLE(1, std::endl << printStateHelper()); } std::string GenericHWInterface::printStateHelper() { std::stringstream ss; std::cout.precision(15); for (std::size_t i = 0; i < num_joints_; ++i) { ss << "j" << i << ": " << std::fixed << joint_position_[i] << "\t "; ss << std::fixed << joint_velocity_[i] << "\t "; ss << std::fixed << joint_effort_[i] << std::endl; } return ss.str(); } std::string GenericHWInterface::printCommandHelper() { std::stringstream ss; std::cout.precision(15); ss << " position velocity effort \n"; for (std::size_t i = 0; i < num_joints_; ++i) { ss << "j" << i << ": " << std::fixed << joint_position_command_[i] << "\t "; ss << std::fixed << joint_velocity_command_[i] << "\t "; ss << std::fixed << joint_effort_command_[i] << std::endl; } return ss.str(); } void GenericHWInterface::loadURDF(ros::NodeHandle &nh, std::string param_name) { std::string urdf_string; urdf_model_ = new urdf::Model(); // search and wait for robot_description on param server while (urdf_string.empty() && ros::ok()) { std::string search_param_name; if (nh.searchParam(param_name, search_param_name)) { ROS_INFO_STREAM_NAMED("generic_hw_interface", "Waiting for model URDF on the ROS param server at location: " << nh.getNamespace() << search_param_name); nh.getParam(search_param_name, urdf_string); } else { ROS_INFO_STREAM_NAMED("generic_hw_interface", "Waiting for model URDF on the ROS param server at location: " << nh.getNamespace() << param_name); nh.getParam(param_name, urdf_string); } usleep(100000); } if (!urdf_model_->initString(urdf_string)) ROS_ERROR_STREAM_NAMED("generic_hw_interface", "Unable to load URDF model"); else ROS_DEBUG_STREAM_NAMED("generic_hw_interface", "Received URDF from param server"); } } // namespace <|endoftext|>
<commit_before>#include "demo/system/precompiled.h" #include "engine/system/system.h" DEA_START() #if (DEA_PLATFORM == DEA_PLATFORM_WINDOWS) #include <windows.h> int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE prev_instance, PSTR cmd_line, int cmd_show) { /* Just the get this to compile for now */ (void*)hinstance; (void*)prev_instance; (void*)cmd_line; --cmd_show; const bool fullscreen = false; window windows[2]; create_window(1280, 720, 0.5f, 0.5f, L"Engine", fullscreen, windows[0]); create_window(600, 400, 0.0f, 0.0f, L"Editor", fullscreen, windows[1]); focus_window(windows[0]); run(); destroy_window(windows[0], fullscreen); destroy_window(windows[1], fullscreen); return 0; } #else #error No Main for current platform #endif DEA_END()<commit_msg>Demo: Demo now uses pod_vector to store windows.<commit_after>#include "demo/system/precompiled.h" #include "engine/system/system.h" DEA_START() #if (DEA_PLATFORM == DEA_PLATFORM_WINDOWS) #include <windows.h> int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE prev_instance, PSTR cmd_line, int cmd_show) { /* Just the get this to compile for now */ (void*)hinstance; (void*)prev_instance; (void*)cmd_line; --cmd_show; init_system_data(); const bool fullscreen = false; pod_vector<window> windows; { window temp; windows.resize(2, temp); create_window(1280, 720, 0.5f, 0.5f, L"Engine", fullscreen, windows[0]); create_window(600, 400, 0.0f, 0.0f, L"Editor", fullscreen, windows[1]); } focus_window(windows[0]); run(windows); for (auto it = windows.get_begin(); it != windows.get_end(); ++it) destroy_window(*it, fullscreen); destroy_system_data(); return 0; } #else #error No Main for current platform #endif DEA_END()<|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of mcompositor. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "mtexturepixmapitem.h" #include "mtexturepixmapitem_p.h" #include <QPainterPath> #include <QRect> #include <QGLContext> #include <QX11Info> #include <vector> #include <X11/Xlib.h> #include <X11/extensions/Xcomposite.h> #include <X11/extensions/Xrender.h> #include <X11/extensions/Xfixes.h> //#define GL_GLEXT_PROTOTYPES #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> static PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHR = 0; static PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHR = 0; PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES = 0; static EGLint attribs[] = { EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE }; class EglTextureManager { public: // TODO: this should be dynamic // use QCache instead like Qt's GL backend static const int sz = 20; EglTextureManager() { glGenTextures(sz, tex); for (int i = 0; i < sz; i++) textures.push_back(tex[i]); } ~EglTextureManager() { glDeleteTextures(sz, tex); } GLuint getTexture() { if (textures.empty()) { qWarning("Empty texture stack"); return 0; } GLuint ret = textures.back(); textures.pop_back(); return ret; } void closeTexture(GLuint texture) { // clear this texture glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); textures.push_back(texture); } GLuint tex[sz+1]; std::vector<GLuint> textures; }; class EglResourceManager { public: EglResourceManager() : has_tfp(false) { if (!dpy) dpy = eglGetDisplay(EGLNativeDisplayType(QX11Info::display())); QString exts = QLatin1String(eglQueryString(dpy, EGL_EXTENSIONS)); if ((exts.contains("EGL_KHR_image") && exts.contains("EGL_KHR_image_pixmap") && exts.contains("EGL_KHR_gl_texture_2D_image")) || 1) { has_tfp = true; eglCreateImageKHR = (PFNEGLCREATEIMAGEKHRPROC) eglGetProcAddress("eglCreateImageKHR"); eglDestroyImageKHR = (PFNEGLDESTROYIMAGEKHRPROC) eglGetProcAddress("eglDestroyImageKHR"); glEGLImageTargetTexture2DOES = (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) eglGetProcAddress("glEGLImageTargetTexture2DOES"); } else { qCritical() << "EGL extensions:" << exts; qFatal("no EGL tfp support, aborting\n"); } texman = new EglTextureManager(); } bool texturePixmapSupport() { return has_tfp; } EglTextureManager *texman; static EGLConfig config; static EGLConfig configAlpha; static EGLDisplay dpy; bool has_tfp; }; EglResourceManager *MTexturePixmapPrivate::eglresource = 0; EGLConfig EglResourceManager::config = 0; EGLConfig EglResourceManager::configAlpha = 0; EGLDisplay EglResourceManager::dpy = 0; void MTexturePixmapItem::init() { if (isValid() && (windowAttributes()->map_state != IsViewable)) { qWarning("MTexturePixmapItem::%s(): Failed getting offscreen pixmap", __func__); d->setValid(false); return; } else if (!isValid()) return; if (!d->eglresource) d->eglresource = new EglResourceManager(); d->custom_tfp = !d->eglresource->texturePixmapSupport(); if (d->custom_tfp) { initCustomTfp(); return; } saveBackingStore(); d->ctx->makeCurrent(); d->egl_image = eglCreateImageKHR(d->eglresource->dpy, 0, EGL_NATIVE_PIXMAP_KHR, (EGLClientBuffer)d->windowp, attribs); if (d->egl_image == EGL_NO_IMAGE_KHR) qWarning("MTexturePixmapItem::%s(): Cannot create EGL image: 0x%x", __func__, eglGetError()); d->textureId = d->eglresource->texman->getTexture(); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, d->textureId); if (d->egl_image != EGL_NO_IMAGE_KHR) glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, d->egl_image); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } MTexturePixmapItem::MTexturePixmapItem(Window window, QGLWidget *glwidget, QGraphicsItem *parent) : MCompositeWindow(window, parent), d(new MTexturePixmapPrivate(window, glwidget, this)) { if (!d->ctx) d->ctx = const_cast<QGLContext *>(glwidget->context()); init(); } void MTexturePixmapItem::saveBackingStore(bool renew) { d->saveBackingStore(renew); } void MTexturePixmapItem::rebindPixmap() { if (d->egl_image != EGL_NO_IMAGE_KHR) { eglDestroyImageKHR(d->eglresource->dpy, d->egl_image); glBindTexture(GL_TEXTURE_2D, 0); } if (!d->windowp) { d->egl_image = EGL_NO_IMAGE_KHR; return; } d->ctx->makeCurrent(); d->egl_image = eglCreateImageKHR(d->eglresource->dpy, 0, EGL_NATIVE_PIXMAP_KHR, (EGLClientBuffer)d->windowp, attribs); if (d->egl_image == EGL_NO_IMAGE_KHR) qWarning("MTexturePixmapItem::%s(): Cannot create EGL image: 0x%x", __func__, eglGetError()); glBindTexture(GL_TEXTURE_2D, d->textureId); if (d->egl_image != EGL_NO_IMAGE_KHR) glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, d->egl_image); } void MTexturePixmapItem::enableDirectFbRendering() { d->damageTracking(false); if (d->direct_fb_render && d->egl_image == EGL_NO_IMAGE_KHR) return; d->direct_fb_render = true; glBindTexture(GL_TEXTURE_2D, 0); eglDestroyImageKHR(d->eglresource->dpy, d->egl_image); d->egl_image = EGL_NO_IMAGE_KHR; if (d->windowp) { XFreePixmap(QX11Info::display(), d->windowp); d->windowp = 0; } XCompositeUnredirectWindow(QX11Info::display(), window(), CompositeRedirectManual); } void MTexturePixmapItem::enableRedirectedRendering() { d->damageTracking(true); if (!d->direct_fb_render && d->egl_image != EGL_NO_IMAGE_KHR) return; d->direct_fb_render = false; XCompositeRedirectWindow(QX11Info::display(), window(), CompositeRedirectManual); saveBackingStore(true); updateWindowPixmap(); } bool MTexturePixmapItem::isDirectRendered() const { return d->direct_fb_render; } MTexturePixmapItem::~MTexturePixmapItem() { cleanup(); delete d; } void MTexturePixmapItem::initCustomTfp() { d->ctextureId = d->eglresource->texman->getTexture(); glBindTexture(GL_TEXTURE_2D, d->ctextureId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } void MTexturePixmapItem::cleanup() { eglDestroyImageKHR(d->eglresource->dpy, d->egl_image); d->egl_image = EGL_NO_IMAGE_KHR; XSync(QX11Info::display(), FALSE); if (!d->custom_tfp) d->eglresource->texman->closeTexture(d->textureId); else d->eglresource->texman->closeTexture(d->ctextureId); #if (QT_VERSION < 0x040600) eglMakeCurrent(d->eglresource->dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); #endif XFreePixmap(QX11Info::display(), d->windowp); } void MTexturePixmapItem::updateWindowPixmap(XRectangle *rects, int num) { if (isTransitioning() || d->direct_fb_render || !windowVisible()) return; QRegion r; for (int i = 0; i < num; ++i) r += QRegion(rects[i].x, rects[i].y, rects[i].width, rects[i].height); d->damageRegion = r; // Our very own custom texture from pixmap if (d->custom_tfp) { QPixmap qp = QPixmap::fromX11Pixmap(d->windowp); QImage img = d->glwidget->convertToGLFormat(qp.toImage()); glBindTexture(GL_TEXTURE_2D, d->ctextureId); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img.width(), img.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, img.bits()); update(); } else { if (d->egl_image == EGL_NO_IMAGE_KHR) saveBackingStore(true); d->glwidget->update(); } } void MTexturePixmapItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option) Q_UNUSED(widget) if (d->direct_fb_render) { glBindTexture(GL_TEXTURE_2D, 0); return; } #if QT_VERSION < 0x040600 if (painter->paintEngine()->type() != QPaintEngine::OpenGL) return; #else if (painter->paintEngine()->type() != QPaintEngine::OpenGL2) { return; } #endif QGLWidget *gl = (QGLWidget *) painter->device(); if (!d->ctx) d->ctx = const_cast<QGLContext *>(gl->context()); if (d->has_alpha || opacity() < 1.0f) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } glBindTexture(GL_TEXTURE_2D, d->custom_tfp ? d->ctextureId : d->textureId); if (d->damageRegion.numRects() > 1) { d->drawTexture(painter->combinedTransform(), boundingRect(), opacity()); glEnable(GL_SCISSOR_TEST); for (int i = 0; i < d->damageRegion.numRects(); ++i) { glScissor(d->damageRegion.rects().at(i).x(), d->brect.height() - (d->damageRegion.rects().at(i).y() + d->damageRegion.rects().at(i).height()), d->damageRegion.rects().at(i).width(), d->damageRegion.rects().at(i).height()); d->drawTexture(painter->combinedTransform(), boundingRect(), opacity()); } glDisable(GL_SCISSOR_TEST); } else d->drawTexture(painter->combinedTransform(), boundingRect(), opacity()); // Explicitly disable blending. for some reason, the latest drivers // still has blending left-over even if we call glDisable(GL_BLEND) glBlendFunc(GL_ONE, GL_ZERO); glDisable(GL_BLEND); } void MTexturePixmapItem::windowRaised() { d->windowRaised(); } void MTexturePixmapItem::resize(int w, int h) { d->resize(w, h); } QSizeF MTexturePixmapItem::sizeHint(Qt::SizeHint, const QSizeF &) const { return boundingRect().size(); } QRectF MTexturePixmapItem::boundingRect() const { return d->brect; } QPainterPath MTexturePixmapItem::shape() const { QPainterPath path; path.addRect(boundingRect()); return path; } bool MTexturePixmapItem::hasAlpha() const { return d->has_alpha; } void MTexturePixmapItem::clearTexture() { glBindTexture(GL_TEXTURE_2D, d->custom_tfp ? d->ctextureId : d->textureId); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); } <commit_msg>Changes: Removed scissoring optimizations for now. Think of alternative solution later RevBy: TrustMe<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of mcompositor. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "mtexturepixmapitem.h" #include "mtexturepixmapitem_p.h" #include <QPainterPath> #include <QRect> #include <QGLContext> #include <QX11Info> #include <vector> #include <X11/Xlib.h> #include <X11/extensions/Xcomposite.h> #include <X11/extensions/Xrender.h> #include <X11/extensions/Xfixes.h> //#define GL_GLEXT_PROTOTYPES #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> static PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHR = 0; static PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHR = 0; PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES = 0; static EGLint attribs[] = { EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE }; class EglTextureManager { public: // TODO: this should be dynamic // use QCache instead like Qt's GL backend static const int sz = 20; EglTextureManager() { glGenTextures(sz, tex); for (int i = 0; i < sz; i++) textures.push_back(tex[i]); } ~EglTextureManager() { glDeleteTextures(sz, tex); } GLuint getTexture() { if (textures.empty()) { qWarning("Empty texture stack"); return 0; } GLuint ret = textures.back(); textures.pop_back(); return ret; } void closeTexture(GLuint texture) { // clear this texture glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); textures.push_back(texture); } GLuint tex[sz+1]; std::vector<GLuint> textures; }; class EglResourceManager { public: EglResourceManager() : has_tfp(false) { if (!dpy) dpy = eglGetDisplay(EGLNativeDisplayType(QX11Info::display())); QString exts = QLatin1String(eglQueryString(dpy, EGL_EXTENSIONS)); if ((exts.contains("EGL_KHR_image") && exts.contains("EGL_KHR_image_pixmap") && exts.contains("EGL_KHR_gl_texture_2D_image")) || 1) { has_tfp = true; eglCreateImageKHR = (PFNEGLCREATEIMAGEKHRPROC) eglGetProcAddress("eglCreateImageKHR"); eglDestroyImageKHR = (PFNEGLDESTROYIMAGEKHRPROC) eglGetProcAddress("eglDestroyImageKHR"); glEGLImageTargetTexture2DOES = (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) eglGetProcAddress("glEGLImageTargetTexture2DOES"); } else { qCritical() << "EGL extensions:" << exts; qFatal("no EGL tfp support, aborting\n"); } texman = new EglTextureManager(); } bool texturePixmapSupport() { return has_tfp; } EglTextureManager *texman; static EGLConfig config; static EGLConfig configAlpha; static EGLDisplay dpy; bool has_tfp; }; EglResourceManager *MTexturePixmapPrivate::eglresource = 0; EGLConfig EglResourceManager::config = 0; EGLConfig EglResourceManager::configAlpha = 0; EGLDisplay EglResourceManager::dpy = 0; void MTexturePixmapItem::init() { if (isValid() && (windowAttributes()->map_state != IsViewable)) { qWarning("MTexturePixmapItem::%s(): Failed getting offscreen pixmap", __func__); d->setValid(false); return; } else if (!isValid()) return; if (!d->eglresource) d->eglresource = new EglResourceManager(); d->custom_tfp = !d->eglresource->texturePixmapSupport(); if (d->custom_tfp) { initCustomTfp(); return; } saveBackingStore(); d->ctx->makeCurrent(); d->egl_image = eglCreateImageKHR(d->eglresource->dpy, 0, EGL_NATIVE_PIXMAP_KHR, (EGLClientBuffer)d->windowp, attribs); if (d->egl_image == EGL_NO_IMAGE_KHR) qWarning("MTexturePixmapItem::%s(): Cannot create EGL image: 0x%x", __func__, eglGetError()); d->textureId = d->eglresource->texman->getTexture(); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, d->textureId); if (d->egl_image != EGL_NO_IMAGE_KHR) glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, d->egl_image); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } MTexturePixmapItem::MTexturePixmapItem(Window window, QGLWidget *glwidget, QGraphicsItem *parent) : MCompositeWindow(window, parent), d(new MTexturePixmapPrivate(window, glwidget, this)) { if (!d->ctx) d->ctx = const_cast<QGLContext *>(glwidget->context()); init(); } void MTexturePixmapItem::saveBackingStore(bool renew) { d->saveBackingStore(renew); } void MTexturePixmapItem::rebindPixmap() { if (d->egl_image != EGL_NO_IMAGE_KHR) { eglDestroyImageKHR(d->eglresource->dpy, d->egl_image); glBindTexture(GL_TEXTURE_2D, 0); } if (!d->windowp) { d->egl_image = EGL_NO_IMAGE_KHR; return; } d->ctx->makeCurrent(); d->egl_image = eglCreateImageKHR(d->eglresource->dpy, 0, EGL_NATIVE_PIXMAP_KHR, (EGLClientBuffer)d->windowp, attribs); if (d->egl_image == EGL_NO_IMAGE_KHR) qWarning("MTexturePixmapItem::%s(): Cannot create EGL image: 0x%x", __func__, eglGetError()); glBindTexture(GL_TEXTURE_2D, d->textureId); if (d->egl_image != EGL_NO_IMAGE_KHR) glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, d->egl_image); } void MTexturePixmapItem::enableDirectFbRendering() { d->damageTracking(false); if (d->direct_fb_render && d->egl_image == EGL_NO_IMAGE_KHR) return; d->direct_fb_render = true; glBindTexture(GL_TEXTURE_2D, 0); eglDestroyImageKHR(d->eglresource->dpy, d->egl_image); d->egl_image = EGL_NO_IMAGE_KHR; if (d->windowp) { XFreePixmap(QX11Info::display(), d->windowp); d->windowp = 0; } XCompositeUnredirectWindow(QX11Info::display(), window(), CompositeRedirectManual); } void MTexturePixmapItem::enableRedirectedRendering() { d->damageTracking(true); if (!d->direct_fb_render && d->egl_image != EGL_NO_IMAGE_KHR) return; d->direct_fb_render = false; XCompositeRedirectWindow(QX11Info::display(), window(), CompositeRedirectManual); saveBackingStore(true); updateWindowPixmap(); } bool MTexturePixmapItem::isDirectRendered() const { return d->direct_fb_render; } MTexturePixmapItem::~MTexturePixmapItem() { cleanup(); delete d; } void MTexturePixmapItem::initCustomTfp() { d->ctextureId = d->eglresource->texman->getTexture(); glBindTexture(GL_TEXTURE_2D, d->ctextureId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } void MTexturePixmapItem::cleanup() { eglDestroyImageKHR(d->eglresource->dpy, d->egl_image); d->egl_image = EGL_NO_IMAGE_KHR; XSync(QX11Info::display(), FALSE); if (!d->custom_tfp) d->eglresource->texman->closeTexture(d->textureId); else d->eglresource->texman->closeTexture(d->ctextureId); #if (QT_VERSION < 0x040600) eglMakeCurrent(d->eglresource->dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); #endif XFreePixmap(QX11Info::display(), d->windowp); } void MTexturePixmapItem::updateWindowPixmap(XRectangle *rects, int num) { if (isTransitioning() || d->direct_fb_render || !windowVisible()) return; QRegion r; for (int i = 0; i < num; ++i) r += QRegion(rects[i].x, rects[i].y, rects[i].width, rects[i].height); d->damageRegion = r; // Our very own custom texture from pixmap if (d->custom_tfp) { QPixmap qp = QPixmap::fromX11Pixmap(d->windowp); QImage img = d->glwidget->convertToGLFormat(qp.toImage()); glBindTexture(GL_TEXTURE_2D, d->ctextureId); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img.width(), img.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, img.bits()); update(); } else { if (d->egl_image == EGL_NO_IMAGE_KHR) saveBackingStore(true); d->glwidget->update(); } } void MTexturePixmapItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option) Q_UNUSED(widget) if (d->direct_fb_render) { glBindTexture(GL_TEXTURE_2D, 0); return; } #if QT_VERSION < 0x040600 if (painter->paintEngine()->type() != QPaintEngine::OpenGL) return; #else if (painter->paintEngine()->type() != QPaintEngine::OpenGL2) { return; } #endif QGLWidget *gl = (QGLWidget *) painter->device(); if (!d->ctx) d->ctx = const_cast<QGLContext *>(gl->context()); if (d->has_alpha || opacity() < 1.0f) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } glBindTexture(GL_TEXTURE_2D, d->custom_tfp ? d->ctextureId : d->textureId); // FIXME: not optimal. probably would be better to replace with // eglSwapBuffersRegionNOK() /* if (d->damageRegion.numRects() > 1) { d->drawTexture(painter->combinedTransform(), boundingRect(), opacity()); glEnable(GL_SCISSOR_TEST); for (int i = 0; i < d->damageRegion.numRects(); ++i) { glScissor(d->damageRegion.rects().at(i).x(), d->brect.height() - (d->damageRegion.rects().at(i).y() + d->damageRegion.rects().at(i).height()), d->damageRegion.rects().at(i).width(), d->damageRegion.rects().at(i).height()); d->drawTexture(painter->combinedTransform(), boundingRect(), opacity()); } glDisable(GL_SCISSOR_TEST); } else */ d->drawTexture(painter->combinedTransform(), boundingRect(), opacity()); // Explicitly disable blending. for some reason, the latest drivers // still has blending left-over even if we call glDisable(GL_BLEND) glBlendFunc(GL_ONE, GL_ZERO); glDisable(GL_BLEND); } void MTexturePixmapItem::windowRaised() { d->windowRaised(); } void MTexturePixmapItem::resize(int w, int h) { d->resize(w, h); } QSizeF MTexturePixmapItem::sizeHint(Qt::SizeHint, const QSizeF &) const { return boundingRect().size(); } QRectF MTexturePixmapItem::boundingRect() const { return d->brect; } QPainterPath MTexturePixmapItem::shape() const { QPainterPath path; path.addRect(boundingRect()); return path; } bool MTexturePixmapItem::hasAlpha() const { return d->has_alpha; } void MTexturePixmapItem::clearTexture() { glBindTexture(GL_TEXTURE_2D, d->custom_tfp ? d->ctextureId : d->textureId); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); } <|endoftext|>
<commit_before><commit_msg>PVS: V517 The use of 'if (A) {...} else if (A) {...}' pattern was detected.<commit_after><|endoftext|>
<commit_before>#include "atom_type.h" namespace sirius { void Atom_type::read_input_core(JSON_tree& parser) { std::string core_str; parser["core"] >> core_str; if (int size = (int)core_str.size()) { if (size % 2) { std::string s = std::string("wrong core configuration string : ") + core_str; TERMINATE(s); } int j = 0; while (j < size) { char c1 = core_str[j++]; char c2 = core_str[j++]; int n = -1; int l = -1; std::istringstream iss(std::string(1, c1)); iss >> n; if (n <= 0 || iss.fail()) { std::string s = std::string("wrong principal quantum number : " ) + std::string(1, c1); TERMINATE(s); } switch (c2) { case 's': { l = 0; break; } case 'p': { l = 1; break; } case 'd': { l = 2; break; } case 'f': { l = 3; break; } default: { std::string s = std::string("wrong angular momentum label : " ) + std::string(1, c2); TERMINATE(s); } } atomic_level_descriptor level; level.n = n; level.l = l; level.core = true; for (int ist = 0; ist < 28; ist++) { if ((level.n == atomic_conf[zn_ - 1][ist][0]) && (level.l == atomic_conf[zn_ - 1][ist][1])) { level.k = atomic_conf[zn_ - 1][ist][2]; level.occupancy = double(atomic_conf[zn_ - 1][ist][3]); atomic_levels_.push_back(level); } } } } } void Atom_type::read_input_aw(JSON_tree& parser) { radial_solution_descriptor rsd; radial_solution_descriptor_set rsd_set; // default augmented wave basis rsd.n = -1; rsd.l = -1; for (int order = 0; order < parser["valence"][0]["basis"].size(); order++) { parser["valence"][0]["basis"][order]["enu"] >> rsd.enu; parser["valence"][0]["basis"][order]["dme"] >> rsd.dme; parser["valence"][0]["basis"][order]["auto"] >> rsd.auto_enu; aw_default_l_.push_back(rsd); } for (int j = 1; j < parser["valence"].size(); j++) { parser["valence"][j]["l"] >> rsd.l; parser["valence"][j]["n"] >> rsd.n; rsd_set.clear(); for (int order = 0; order < parser["valence"][j]["basis"].size(); order++) { parser["valence"][j]["basis"][order]["enu"] >> rsd.enu; parser["valence"][j]["basis"][order]["dme"] >> rsd.dme; parser["valence"][j]["basis"][order]["auto"] >> rsd.auto_enu; rsd_set.push_back(rsd); } aw_specific_l_.push_back(rsd_set); } } void Atom_type::read_input_lo(JSON_tree& parser) { radial_solution_descriptor rsd; radial_solution_descriptor_set rsd_set; int l; for (int j = 0; j < parser["lo"].size(); j++) { parser["lo"][j]["l"] >> l; if (parser["lo"][j].exist("basis")) { local_orbital_descriptor lod; lod.l = l; rsd.l = l; rsd_set.clear(); for (int order = 0; order < parser["lo"][j]["basis"].size(); order++) { parser["lo"][j]["basis"][order]["n"] >> rsd.n; parser["lo"][j]["basis"][order]["enu"] >> rsd.enu; parser["lo"][j]["basis"][order]["dme"] >> rsd.dme; parser["lo"][j]["basis"][order]["auto"] >> rsd.auto_enu; rsd_set.push_back(rsd); } lod.rsd_set = rsd_set; lo_descriptors_.push_back(lod); } } } void Atom_type::read_input(const std::string& fname) { JSON_tree parser(fname); if (!parameters_.full_potential()) { parser["pseudo_potential"]["header"]["element"] >> symbol_; double zp; parser["pseudo_potential"]["header"]["z_valence"] >> zp; zn_ = int(zp + 1e-10); int nmesh; parser["pseudo_potential"]["header"]["mesh_size"] >> nmesh; parser["pseudo_potential"]["radial_grid"] >> uspp_.r; parser["pseudo_potential"]["local_potential"] >> uspp_.vloc; uspp_.core_charge_density = parser["pseudo_potential"]["core_charge_density"].get(std::vector<double>(nmesh, 0)); parser["pseudo_potential"]["total_charge_density"] >> uspp_.total_charge_density; if ((int)uspp_.r.size() != nmesh) { TERMINATE("wrong mesh size"); } if ((int)uspp_.vloc.size() != nmesh || (int)uspp_.core_charge_density.size() != nmesh || (int)uspp_.total_charge_density.size() != nmesh) { std::cout << uspp_.vloc.size() << " " << uspp_.core_charge_density.size() << " " << uspp_.total_charge_density.size() << std::endl; TERMINATE("wrong array size"); } num_mt_points_ = nmesh; mt_radius_ = uspp_.r[nmesh - 1]; set_radial_grid(nmesh, &uspp_.r[0]); parser["pseudo_potential"]["header"]["number_of_proj"] >> uspp_.num_beta_radial_functions; uspp_.beta_radial_functions = mdarray<double, 2>(num_mt_points_, uspp_.num_beta_radial_functions); uspp_.beta_radial_functions.zero(); uspp_.num_beta_radial_points.resize(uspp_.num_beta_radial_functions); uspp_.beta_l.resize(uspp_.num_beta_radial_functions); int lmax_beta = 0; local_orbital_descriptor lod; for (int i = 0; i < uspp_.num_beta_radial_functions; i++) { parser["pseudo_potential"]["beta_projectors"][i]["cutoff_radius_index"] >> uspp_.num_beta_radial_points[i]; std::vector<double> beta; parser["pseudo_potential"]["beta_projectors"][i]["radial_function"] >> beta; if ((int)beta.size() != uspp_.num_beta_radial_points[i]) TERMINATE("wrong size of beta function"); std::memcpy(&uspp_.beta_radial_functions(0, i), &beta[0], beta.size() * sizeof(double)); parser["pseudo_potential"]["beta_projectors"][i]["angular_momentum"] >> uspp_.beta_l[i]; lmax_beta = std::max(lmax_beta, uspp_.beta_l[i]); } uspp_.d_mtrx_ion = mdarray<double, 2>(uspp_.num_beta_radial_functions, uspp_.num_beta_radial_functions); uspp_.d_mtrx_ion.zero(); std::vector<double> dion; parser["pseudo_potential"]["D_ion"] >> dion; for (int i = 0; i < uspp_.num_beta_radial_functions; i++) { for (int j = 0; j < uspp_.num_beta_radial_functions; j++) uspp_.d_mtrx_ion(i, j) = dion[j * uspp_.num_beta_radial_functions + i]; } if (parser["pseudo_potential"].exist("augmentation")) { uspp_.q_radial_functions_l = mdarray<double, 3>(num_mt_points_, uspp_.num_beta_radial_functions * (uspp_.num_beta_radial_functions + 1) / 2, 2 * lmax_beta + 1); uspp_.q_radial_functions_l.zero(); for (int k = 0; k < parser["pseudo_potential"]["augmentation"].size(); k++) { int i, j, l; parser["pseudo_potential"]["augmentation"][k]["i"] >> i; parser["pseudo_potential"]["augmentation"][k]["j"] >> j; int idx = j * (j + 1) / 2 + i; parser["pseudo_potential"]["augmentation"][k]["angular_momentum"] >> l; std::vector<double> qij; parser["pseudo_potential"]["augmentation"][k]["radial_function"] >> qij; if ((int)qij.size() != num_mt_points_) TERMINATE("wrong size of qij"); std::memcpy(&uspp_.q_radial_functions_l(0, idx, l), &qij[0], num_mt_points_ * sizeof(double)); } } if (parser["pseudo_potential"].exist("wave_functions")) { int nwf = parser["pseudo_potential"]["wave_functions"].size(); uspp_.wf_pseudo_ = mdarray<double, 2>(num_mt_points_, nwf); uspp_.l_wf_pseudo_ = std::vector<int>(nwf); for (int k = 0; k < nwf; k++) { std::vector<double> f; parser["pseudo_potential"]["wave_functions"][k]["radial_function"] >> f; std::memcpy(&uspp_.wf_pseudo_(0, k), &f[0], num_mt_points_ * sizeof(double)); parser["pseudo_potential"]["wave_functions"][k]["angular_momentum"] >> uspp_.l_wf_pseudo_[k]; } } } if (parameters_.full_potential()) { parser["name"] >> name_; parser["symbol"] >> symbol_; parser["mass"] >> mass_; parser["number"] >> zn_; parser["rmin"] >> radial_grid_origin_; parser["rmt"] >> mt_radius_; parser["nrmt"] >> num_mt_points_; read_input_core(parser); read_input_aw(parser); read_input_lo(parser); } } } <commit_msg>simplify reading of json species file<commit_after>#include "atom_type.h" namespace sirius { void Atom_type::read_input_core(JSON_tree& parser) { std::string core_str; parser["core"] >> core_str; if (int size = (int)core_str.size()) { if (size % 2) { std::string s = std::string("wrong core configuration string : ") + core_str; TERMINATE(s); } int j = 0; while (j < size) { char c1 = core_str[j++]; char c2 = core_str[j++]; int n = -1; int l = -1; std::istringstream iss(std::string(1, c1)); iss >> n; if (n <= 0 || iss.fail()) { std::string s = std::string("wrong principal quantum number : " ) + std::string(1, c1); TERMINATE(s); } switch (c2) { case 's': { l = 0; break; } case 'p': { l = 1; break; } case 'd': { l = 2; break; } case 'f': { l = 3; break; } default: { std::string s = std::string("wrong angular momentum label : " ) + std::string(1, c2); TERMINATE(s); } } atomic_level_descriptor level; level.n = n; level.l = l; level.core = true; for (int ist = 0; ist < 28; ist++) { if ((level.n == atomic_conf[zn_ - 1][ist][0]) && (level.l == atomic_conf[zn_ - 1][ist][1])) { level.k = atomic_conf[zn_ - 1][ist][2]; level.occupancy = double(atomic_conf[zn_ - 1][ist][3]); atomic_levels_.push_back(level); } } } } } void Atom_type::read_input_aw(JSON_tree& parser) { radial_solution_descriptor rsd; radial_solution_descriptor_set rsd_set; // default augmented wave basis rsd.n = -1; rsd.l = -1; for (int order = 0; order < parser["valence"][0]["basis"].size(); order++) { parser["valence"][0]["basis"][order]["enu"] >> rsd.enu; parser["valence"][0]["basis"][order]["dme"] >> rsd.dme; parser["valence"][0]["basis"][order]["auto"] >> rsd.auto_enu; aw_default_l_.push_back(rsd); } for (int j = 1; j < parser["valence"].size(); j++) { parser["valence"][j]["l"] >> rsd.l; parser["valence"][j]["n"] >> rsd.n; rsd_set.clear(); for (int order = 0; order < parser["valence"][j]["basis"].size(); order++) { parser["valence"][j]["basis"][order]["enu"] >> rsd.enu; parser["valence"][j]["basis"][order]["dme"] >> rsd.dme; parser["valence"][j]["basis"][order]["auto"] >> rsd.auto_enu; rsd_set.push_back(rsd); } aw_specific_l_.push_back(rsd_set); } } void Atom_type::read_input_lo(JSON_tree& parser) { radial_solution_descriptor rsd; radial_solution_descriptor_set rsd_set; int l; for (int j = 0; j < parser["lo"].size(); j++) { parser["lo"][j]["l"] >> l; if (parser["lo"][j].exist("basis")) { local_orbital_descriptor lod; lod.l = l; rsd.l = l; rsd_set.clear(); for (int order = 0; order < parser["lo"][j]["basis"].size(); order++) { parser["lo"][j]["basis"][order]["n"] >> rsd.n; parser["lo"][j]["basis"][order]["enu"] >> rsd.enu; parser["lo"][j]["basis"][order]["dme"] >> rsd.dme; parser["lo"][j]["basis"][order]["auto"] >> rsd.auto_enu; rsd_set.push_back(rsd); } lod.rsd_set = rsd_set; lo_descriptors_.push_back(lod); } } } void Atom_type::read_input(const std::string& fname) { JSON_tree parser(fname); if (!parameters_.full_potential()) { parser["pseudo_potential"]["header"]["element"] >> symbol_; double zp; parser["pseudo_potential"]["header"]["z_valence"] >> zp; zn_ = int(zp + 1e-10); int nmesh; parser["pseudo_potential"]["header"]["mesh_size"] >> nmesh; parser["pseudo_potential"]["radial_grid"] >> uspp_.r; parser["pseudo_potential"]["local_potential"] >> uspp_.vloc; uspp_.core_charge_density = parser["pseudo_potential"]["core_charge_density"].get(std::vector<double>(nmesh, 0)); parser["pseudo_potential"]["total_charge_density"] >> uspp_.total_charge_density; if ((int)uspp_.r.size() != nmesh) { TERMINATE("wrong mesh size"); } if ((int)uspp_.vloc.size() != nmesh || (int)uspp_.core_charge_density.size() != nmesh || (int)uspp_.total_charge_density.size() != nmesh) { std::cout << uspp_.vloc.size() << " " << uspp_.core_charge_density.size() << " " << uspp_.total_charge_density.size() << std::endl; TERMINATE("wrong array size"); } num_mt_points_ = nmesh; mt_radius_ = uspp_.r[nmesh - 1]; set_radial_grid(nmesh, &uspp_.r[0]); parser["pseudo_potential"]["header"]["number_of_proj"] >> uspp_.num_beta_radial_functions; uspp_.beta_radial_functions = mdarray<double, 2>(num_mt_points_, uspp_.num_beta_radial_functions); uspp_.beta_radial_functions.zero(); uspp_.num_beta_radial_points.resize(uspp_.num_beta_radial_functions); uspp_.beta_l.resize(uspp_.num_beta_radial_functions); int lmax_beta = 0; local_orbital_descriptor lod; for (int i = 0; i < uspp_.num_beta_radial_functions; i++) { std::vector<double> beta; parser["pseudo_potential"]["beta_projectors"][i]["radial_function"] >> beta; if ((int)beta.size() > num_mt_points_) { std::stringstream s; s << "wrong size of beta functions for atom type " << symbol_ << " (label: " << label_ << ")" << std::endl << "size of beta radial functions in the file: " << beta.size() << std::endl << "radial grid size: " << num_mt_points_; TERMINATE(s); } uspp_.num_beta_radial_points[i] = static_cast<int>(beta.size()); std::memcpy(&uspp_.beta_radial_functions(0, i), &beta[0], uspp_.num_beta_radial_points[i] * sizeof(double)); parser["pseudo_potential"]["beta_projectors"][i]["angular_momentum"] >> uspp_.beta_l[i]; lmax_beta = std::max(lmax_beta, uspp_.beta_l[i]); } uspp_.d_mtrx_ion = mdarray<double, 2>(uspp_.num_beta_radial_functions, uspp_.num_beta_radial_functions); uspp_.d_mtrx_ion.zero(); std::vector<double> dion; parser["pseudo_potential"]["D_ion"] >> dion; for (int i = 0; i < uspp_.num_beta_radial_functions; i++) { for (int j = 0; j < uspp_.num_beta_radial_functions; j++) uspp_.d_mtrx_ion(i, j) = dion[j * uspp_.num_beta_radial_functions + i]; } if (parser["pseudo_potential"].exist("augmentation")) { uspp_.q_radial_functions_l = mdarray<double, 3>(num_mt_points_, uspp_.num_beta_radial_functions * (uspp_.num_beta_radial_functions + 1) / 2, 2 * lmax_beta + 1); uspp_.q_radial_functions_l.zero(); for (int k = 0; k < parser["pseudo_potential"]["augmentation"].size(); k++) { int i, j, l; parser["pseudo_potential"]["augmentation"][k]["i"] >> i; parser["pseudo_potential"]["augmentation"][k]["j"] >> j; int idx = j * (j + 1) / 2 + i; parser["pseudo_potential"]["augmentation"][k]["angular_momentum"] >> l; std::vector<double> qij; parser["pseudo_potential"]["augmentation"][k]["radial_function"] >> qij; if ((int)qij.size() != num_mt_points_) TERMINATE("wrong size of qij"); std::memcpy(&uspp_.q_radial_functions_l(0, idx, l), &qij[0], num_mt_points_ * sizeof(double)); } } if (parser["pseudo_potential"].exist("atomic_wave_functions")) { int nwf = parser["pseudo_potential"]["atomic_wave_functions"].size(); for (int k = 0; k < nwf; k++) { std::pair<int, std::vector<double> > wf; parser["pseudo_potential"]["atomic_wave_functions"][k]["radial_function"] >> wf.second; if ((int)wf.second.size() != num_mt_points_) { std::stringstream s; s << "wrong size of atomic functions for atom type " << symbol_ << " (label: " << label_ << ")" << std::endl << "size of atomic radial functions in the file: " << wf.second.size() << std::endl << "radial grid size: " << num_mt_points_; TERMINATE(s); } parser["pseudo_potential"]["atomic_wave_functions"][k]["angular_momentum"] >> wf.first; uspp_.atomic_pseudo_wfs_.push_back(wf); } } } if (parameters_.full_potential()) { parser["name"] >> name_; parser["symbol"] >> symbol_; parser["mass"] >> mass_; parser["number"] >> zn_; parser["rmin"] >> radial_grid_origin_; parser["rmt"] >> mt_radius_; parser["nrmt"] >> num_mt_points_; read_input_core(parser); read_input_aw(parser); read_input_lo(parser); } } } <|endoftext|>
<commit_before>#include <cstring> #ifdef __clang__ #include <vector> #endif #if defined _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #endif #ifdef _MSC_VER #pragma warning(disable:4127) #endif #define __DYN_GRID_SIZE #include "common.h" #include "metrix.h" #include "aligned_malloc.h" #define as256p(p) (reinterpret_cast<__m256d*>(p)) #define as256pc(p) (reinterpret_cast<const __m256d*>(p)) #ifndef __DEGRID #define GRID_MOD #define VIS_MOD const inline void addGrids( complexd dst[] , const complexd srcs[] , int nthreads , int grid_pitch , int grid_size ) { int siz = grid_size*grid_pitch; #pragma omp parallel for for (unsigned int i = 0; i < siz*sizeof(complexd)/(256/8); i++) { __m256d sum = as256pc(srcs)[i]; // __m256d sum = _mm256_loadu_pd(reinterpret_cast<const double*>(as256pc(srcs)+i)); for (int g = 1; g < nthreads; g ++) sum = _mm256_add_pd(sum, as256pc(srcs + g * siz)[i]); as256p(dst)[i] = sum; } } #else #define GRID_MOD const #define VIS_MOD #endif template < int over , bool is_half_gcf > // grid must be initialized to 0s. void gridKernel_scatter( double scale , double wstep , int baselines , const int gcf_supps[/* baselines */] , GRID_MOD complexd grids[] // We have a [w_planes][over][over]-shaped array of pointers to // variable-sized gcf layers, but we precompute (in pregrid) // exact index into this array, thus we use plain pointer here , const complexd * gcf[] , const Double3 * _uvw[] , VIS_MOD complexd * _vis[] , int ts_ch , int grid_pitch , int grid_size ) { int siz = grid_size*grid_pitch; #pragma omp parallel { GRID_MOD complexd * _grid = grids + omp_get_thread_num() * siz; #ifndef __DEGRID memset(_grid, 0, sizeof(complexd) * siz); #else memset(_vis, 0, sizeof(complexd) * baselines * ts_ch); #endif __ACC(complexd, grid, grid_pitch); #pragma omp for schedule(dynamic) for(int bl = 0; bl < baselines; bl++) { int max_supp_here; max_supp_here = gcf_supps[bl]; const Double3 * uvw; uvw = _uvw[bl]; // VLA requires "--std=gnu..." extension Pregridded pa[ts_ch]; #ifndef __DEGRID // Clang doesn't allow non-POD types in VLAs, // thus we use much more heavyweight vector here. #ifndef __clang__ complexd vis[ts_ch]; #else std::vector<complexd> vis(ts_ch); #endif #endif for(int n=0; n<ts_ch; n++){ #ifndef __DEGRID vis[n] = rotw(_vis[bl][n], uvw[n].w); #endif pregridPoint<over, is_half_gcf>(scale, wstep, uvw[n], pa[n], grid_size); } #ifdef __DEGRID complexd * vis; vis = _vis[bl]; #endif for (int su = 0; su < max_supp_here; su++) { // Moved from 2-levels below according to Romein for (int i = 0; i < ts_ch; i++) { Pregridded p = pa[i]; for (int sv = 0; sv < max_supp_here; sv++) { // Don't forget our u v are already translated by -max_supp_here/2 int gsu, gsv; gsu = p.u + su; gsv = p.v + sv; complexd supportPixel; #define __layeroff su * max_supp_here + sv if (is_half_gcf) { int index; index = p.gcf_layer_index; // Negative index indicates that original w was mirrored // and we shall negate the index to obtain correct // offset *and* conjugate the result. if (index < 0) { supportPixel = conj(gcf[-index][__layeroff]); } else { supportPixel = gcf[index][__layeroff]; } } else { supportPixel = gcf[p.gcf_layer_index][__layeroff]; } #ifndef __DEGRID grid[gsu][gsv] += vis[i] * supportPixel; #else vis[i] += rotw(grid[gsu][gsv] * supportPixel, uvw[i].w); #endif } } } } } } #ifndef __DEGRID template < int over , bool is_half_gcf > // grid must be initialized to 0s. void gridKernel_scatter_full( double scale , double wstep , int baselines , const int gcf_supps[/* baselines */] , complexd grid[] // We have a [w_planes][over][over]-shaped array of pointers to // variable-sized gcf layers, but we precompute (in pregrid) // exact index into this array, thus we use plain pointer here , const complexd * gcf[] , const Double3 * uvw[] , const complexd * vis[] , int ts_ch , int grid_pitch , int grid_size ) { #if defined _OPENMP int siz = grid_size*grid_pitch; int nthreads; #pragma omp parallel #pragma omp single nthreads = omp_get_num_threads(); // Nullify incoming grid, allocate thread-local grids memset(grid, 0, sizeof(complexd) * siz); complexd * tmpgrids = alignedMallocArray<complexd>(siz * nthreads, 32); gridKernel_scatter< over , is_half_gcf >(scale, wstep, baselines, gcf_supps, tmpgrids, gcf, uvw, vis, ts_ch, grid_pitch, grid_size); addGrids(grid, tmpgrids, nthreads, grid_pitch, grid_size); free(tmpgrids); #else gridKernel_scatter< over , is_half_gcf >(scale, wstep, baselines, gcf_supps, grid, gcf, uvw, vis, ts_ch, grid_pitch, grid_size); #endif } #define gridKernelCPU(hgcfSuff, isHgcf) \ extern "C" \ void gridKernelCPU##hgcfSuff( \ double scale \ , double wstep \ , int baselines \ , const int gcf_supps[/* baselines */] \ , complexd grid[] \ , const complexd * gcf[] \ , const Double3 * uvw[] \ , const complexd * vis[] \ , int ts_ch \ , int grid_pitch \ , int grid_size \ ){ \ gridKernel_scatter_full<OVER, isHgcf> \ ( scale, wstep, baselines, gcf_supps \ , grid, gcf, uvw, vis, ts_ch, grid_pitch, grid_size); \ } gridKernelCPU(HalfGCF, true) gridKernelCPU(FullGCF, false) // Normalization is done inplace! extern "C" void normalize( int n , complexd src[] , int grid_pitch , int grid_size ) { int siz = grid_size*grid_pitch; double norm = 1.0/double(siz); #pragma omp parallel for for (int i = 0; i < siz; i++) { src[i] *= norm; } } #else #define deGridKernelCPU(hgcfSuff, isHgcf) \ extern "C" \ void deGridKernelCPU##hgcfSuff( \ double scale \ , double wstep \ , int baselines \ , const int gcf_supps[/* baselines */] \ , const complexd grid[] \ , const complexd * gcf[] \ , const Double3 * uvw[] \ , complexd * vis[] \ , int ts_ch \ , int grid_pitch \ , int grid_size \ ){ \ gridKernel_scatter<OVER, isHgcf> \ ( scale, wstep, baselines, gcf_supps \ , grid, gcf, uvw, vis, ts_ch, grid_pitch, grid_size); \ } deGridKernelCPU(HalfGCF, true) deGridKernelCPU(FullGCF, false) #endif <commit_msg>Fix degridder's vis data zeroing bug.<commit_after>#include <cstring> #ifdef __clang__ #include <vector> #endif #if defined _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #endif #ifdef _MSC_VER #pragma warning(disable:4127) #endif #define __DYN_GRID_SIZE #include "common.h" #include "metrix.h" #include "aligned_malloc.h" #define as256p(p) (reinterpret_cast<__m256d*>(p)) #define as256pc(p) (reinterpret_cast<const __m256d*>(p)) #ifndef __DEGRID #define GRID_MOD #define VIS_MOD const inline void addGrids( complexd dst[] , const complexd srcs[] , int nthreads , int grid_pitch , int grid_size ) { int siz = grid_size*grid_pitch; #pragma omp parallel for for (unsigned int i = 0; i < siz*sizeof(complexd)/(256/8); i++) { __m256d sum = as256pc(srcs)[i]; // __m256d sum = _mm256_loadu_pd(reinterpret_cast<const double*>(as256pc(srcs)+i)); for (int g = 1; g < nthreads; g ++) sum = _mm256_add_pd(sum, as256pc(srcs + g * siz)[i]); as256p(dst)[i] = sum; } } #else #define GRID_MOD const #define VIS_MOD #endif template < int over , bool is_half_gcf > // grid must be initialized to 0s. void gridKernel_scatter( double scale , double wstep , int baselines , const int gcf_supps[/* baselines */] , GRID_MOD complexd grids[] // We have a [w_planes][over][over]-shaped array of pointers to // variable-sized gcf layers, but we precompute (in pregrid) // exact index into this array, thus we use plain pointer here , const complexd * gcf[] , const Double3 * _uvw[] , VIS_MOD complexd * _vis[] , int ts_ch , int grid_pitch , int grid_size ) { int siz = grid_size*grid_pitch; #pragma omp parallel { GRID_MOD complexd * _grid = grids + omp_get_thread_num() * siz; #ifndef __DEGRID memset(_grid, 0, sizeof(complexd) * siz); #endif __ACC(complexd, grid, grid_pitch); #pragma omp for schedule(dynamic) for(int bl = 0; bl < baselines; bl++) { int max_supp_here; max_supp_here = gcf_supps[bl]; const Double3 * uvw; uvw = _uvw[bl]; // VLA requires "--std=gnu..." extension Pregridded pa[ts_ch]; #ifndef __DEGRID // Clang doesn't allow non-POD types in VLAs, // thus we use much more heavyweight vector here. #ifndef __clang__ complexd vis[ts_ch]; #else std::vector<complexd> vis(ts_ch); #endif #else complexd * vis; vis = _vis[bl]; #endif for(int n=0; n<ts_ch; n++){ #ifndef __DEGRID vis[n] = rotw(_vis[bl][n], uvw[n].w); #else vis[n] = {0.0, 0.0}; #endif pregridPoint<over, is_half_gcf>(scale, wstep, uvw[n], pa[n], grid_size); } for (int su = 0; su < max_supp_here; su++) { // Moved from 2-levels below according to Romein for (int i = 0; i < ts_ch; i++) { Pregridded p = pa[i]; for (int sv = 0; sv < max_supp_here; sv++) { // Don't forget our u v are already translated by -max_supp_here/2 int gsu, gsv; gsu = p.u + su; gsv = p.v + sv; complexd supportPixel; #define __layeroff su * max_supp_here + sv if (is_half_gcf) { int index; index = p.gcf_layer_index; // Negative index indicates that original w was mirrored // and we shall negate the index to obtain correct // offset *and* conjugate the result. if (index < 0) { supportPixel = conj(gcf[-index][__layeroff]); } else { supportPixel = gcf[index][__layeroff]; } } else { supportPixel = gcf[p.gcf_layer_index][__layeroff]; } #ifndef __DEGRID grid[gsu][gsv] += vis[i] * supportPixel; #else vis[i] += rotw(grid[gsu][gsv] * supportPixel, uvw[i].w); #endif } } } } } } #ifndef __DEGRID template < int over , bool is_half_gcf > // grid must be initialized to 0s. void gridKernel_scatter_full( double scale , double wstep , int baselines , const int gcf_supps[/* baselines */] , complexd grid[] // We have a [w_planes][over][over]-shaped array of pointers to // variable-sized gcf layers, but we precompute (in pregrid) // exact index into this array, thus we use plain pointer here , const complexd * gcf[] , const Double3 * uvw[] , const complexd * vis[] , int ts_ch , int grid_pitch , int grid_size ) { #if defined _OPENMP int siz = grid_size*grid_pitch; int nthreads; #pragma omp parallel #pragma omp single nthreads = omp_get_num_threads(); // Nullify incoming grid, allocate thread-local grids memset(grid, 0, sizeof(complexd) * siz); complexd * tmpgrids = alignedMallocArray<complexd>(siz * nthreads, 32); gridKernel_scatter< over , is_half_gcf >(scale, wstep, baselines, gcf_supps, tmpgrids, gcf, uvw, vis, ts_ch, grid_pitch, grid_size); addGrids(grid, tmpgrids, nthreads, grid_pitch, grid_size); free(tmpgrids); #else gridKernel_scatter< over , is_half_gcf >(scale, wstep, baselines, gcf_supps, grid, gcf, uvw, vis, ts_ch, grid_pitch, grid_size); #endif } #define gridKernelCPU(hgcfSuff, isHgcf) \ extern "C" \ void gridKernelCPU##hgcfSuff( \ double scale \ , double wstep \ , int baselines \ , const int gcf_supps[/* baselines */] \ , complexd grid[] \ , const complexd * gcf[] \ , const Double3 * uvw[] \ , const complexd * vis[] \ , int ts_ch \ , int grid_pitch \ , int grid_size \ ){ \ gridKernel_scatter_full<OVER, isHgcf> \ ( scale, wstep, baselines, gcf_supps \ , grid, gcf, uvw, vis, ts_ch, grid_pitch, grid_size); \ } gridKernelCPU(HalfGCF, true) gridKernelCPU(FullGCF, false) // Normalization is done inplace! extern "C" void normalize( int n , complexd src[] , int grid_pitch , int grid_size ) { int siz = grid_size*grid_pitch; double norm = 1.0/double(siz); #pragma omp parallel for for (int i = 0; i < siz; i++) { src[i] *= norm; } } #else #define deGridKernelCPU(hgcfSuff, isHgcf) \ extern "C" \ void deGridKernelCPU##hgcfSuff( \ double scale \ , double wstep \ , int baselines \ , const int gcf_supps[/* baselines */] \ , const complexd grid[] \ , const complexd * gcf[] \ , const Double3 * uvw[] \ , complexd * vis[] \ , int ts_ch \ , int grid_pitch \ , int grid_size \ ){ \ gridKernel_scatter<OVER, isHgcf> \ ( scale, wstep, baselines, gcf_supps \ , grid, gcf, uvw, vis, ts_ch, grid_pitch, grid_size); \ } deGridKernelCPU(HalfGCF, true) deGridKernelCPU(FullGCF, false) #endif <|endoftext|>
<commit_before>/*************************************************************************** * * * Copyright (C) 2007-2015 by frePPLe bvba * * * * This library 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 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 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/>. * * * ***************************************************************************/ #define FREPPLE_CORE #include "frepple/solver.h" namespace frepple { DECLARE_EXPORT const MetaClass* SolverMRP::metadata; const Keyword SolverMRP::tag_iterationthreshold("iterationthreshold"); const Keyword SolverMRP::tag_iterationaccuracy("iterationaccuracy"); const Keyword SolverMRP::tag_lazydelay("lazydelay"); const Keyword SolverMRP::tag_allowsplits("allowsplits"); const Keyword SolverMRP::tag_rotateresources("rotateresources"); const Keyword SolverMRP::tag_planSafetyStockFirst("plansafetystockfirst"); const Keyword SolverMRP::tag_iterationmax("iterationmax"); void LibrarySolver::initialize() { // Initialize only once static bool init = false; if (init) { logger << "Warning: Calling frepple::LibrarySolver::initialize() more " << "than once." << endl; return; } init = true; // Register all classes. int nok = 0; nok += SolverMRP::initialize(); nok += OperatorDelete::initialize(); if (nok) throw RuntimeException("Error registering new Python types"); } int SolverMRP::initialize() { // Initialize the metadata metadata = MetaClass::registerClass<SolverMRP>( "solver", "solver_mrp", Object::create<SolverMRP>, true ); registerFields<SolverMRP>(const_cast<MetaClass*>(metadata)); // Initialize the Python class PythonType& x = FreppleClass<SolverMRP, Solver>::getPythonType(); x.setName("solver_mrp"); x.setDoc("frePPLe solver_mrp"); x.supportgetattro(); x.supportsetattro(); x.supportcreate(create); x.addMethod("solve", solve, METH_NOARGS, "run the solver"); x.addMethod("commit", commit, METH_NOARGS, "commit the plan changes"); x.addMethod("rollback", rollback, METH_NOARGS, "rollback the plan changes"); const_cast<MetaClass*>(metadata)->pythonClass = x.type_object(); return x.typeReady(); } PyObject* SolverMRP::create(PyTypeObject* pytype, PyObject* args, PyObject* kwds) { try { // Create the solver SolverMRP *s = new SolverMRP(); // Iterate over extra keywords, and set attributes. @todo move this responsibility to the readers... if (kwds) { PyObject *key, *value; Py_ssize_t pos = 0; while (PyDict_Next(kwds, &pos, &key, &value)) { PythonData field(value); PyObject* key_utf8 = PyUnicode_AsUTF8String(key); DataKeyword attr(PyBytes_AsString(key_utf8)); Py_DECREF(key_utf8); const MetaFieldBase* fmeta = SolverMRP::metadata->findField(attr.getHash()); if (!fmeta) fmeta = Solver::metadata->findField(attr.getHash()); if (fmeta) // Update the attribute fmeta->setField(s, field); else s->setProperty(attr.getName(), value); }; } // Return the object. The reference count doesn't need to be increased // as we do with other objects, because we want this object to be available // for the garbage collector of Python. return static_cast<PyObject*>(s); } catch (...) { PythonType::evalException(); return NULL; } } DECLARE_EXPORT bool SolverMRP::demand_comparison(const Demand* l1, const Demand* l2) { if (l1->getPriority() != l2->getPriority()) return l1->getPriority() < l2->getPriority(); else if (l1->getDue() != l2->getDue()) return l1->getDue() < l2->getDue(); else return l1->getQuantity() < l2->getQuantity(); } DECLARE_EXPORT void SolverMRP::SolverMRPdata::commit() { // Check SolverMRP* solver = getSolver(); if (!demands || !solver) throw LogicException("Missing demands or solver."); // Message if (solver->getLogLevel()>0) logger << "Start solving cluster " << cluster << " at " << Date::now() << endl; // Solve the planning problem try { // TODO Propagate & solve initial shortages and overloads // Sort the demands of this problem. // We use a stable sort to get reproducible results between platforms // and STL implementations. stable_sort(demands->begin(), demands->end(), demand_comparison); // Solve for safety stock in buffers. if (solver->getPlanSafetyStockFirst()) { constrainedPlanning = (solver->getPlanType() == 1); solveSafetyStock(solver); } // Loop through the list of all demands in this planning problem safety_stock_planning = false; constrainedPlanning = (solver->getPlanType() == 1); for (deque<Demand*>::const_iterator i = demands->begin(); i != demands->end(); ++i) { iteration_count = 0; try { // Plan the demand (*i)->solve(*solver, this); } catch (...) { // Error message logger << "Error: Caught an exception while solving demand '" << (*i)->getName() << "':" << endl; try {throw;} catch (const bad_exception&) {logger << " bad exception" << endl;} catch (const exception& e) {logger << " " << e.what() << endl;} catch (...) {logger << " Unknown type" << endl;} } } // Clean the list of demands of this cluster demands->clear(); // Completely recreate all purchasing operation plans for (set<const OperationItemSupplier*>::iterator o = purchase_operations.begin(); o != purchase_operations.end(); ++o ) { // Erase existing proposed purchases const_cast<OperationItemSupplier*>(*o)->deleteOperationPlans(false); // Create new proposed purchases, unless they can be recreated when // we solve for the safety stock a few lines below if (solver->getPlanSafetyStockFirst()) { try { (*o)->getBuffer()->solve(*solver, this); CommandManager::commit(); } catch(...) { CommandManager::rollback(); } } } purchase_operations.clear(); // Solve for safety stock in buffers. if (!solver->getPlanSafetyStockFirst()) solveSafetyStock(solver); } catch (...) { // We come in this exception handling code only if there is a problem with // with this cluster that goes beyond problems with single orders. // If the problem is with single orders, the exception handling code above // will do a proper rollback. // Error message logger << "Error: Caught an exception while solving cluster " << cluster << ":" << endl; try {throw;} catch (const bad_exception&) {logger << " bad exception" << endl;} catch (const exception& e) {logger << " " << e.what() << endl;} catch (...) {logger << " Unknown type" << endl;} // Clean up the operationplans of this cluster for (Operation::iterator f=Operation::begin(); f!=Operation::end(); ++f) if (f->getCluster() == cluster) f->deleteOperationPlans(); // Clean the list of demands of this cluster demands->clear(); } // Message if (solver->getLogLevel()>0) logger << "End solving cluster " << cluster << " at " << Date::now() << endl; } void SolverMRP::SolverMRPdata::solveSafetyStock(SolverMRP* solver) { OperatorDelete cleanup(this); safety_stock_planning = true; if (getLogLevel() > 0) logger << "Start safety stock replenishment pass " << solver->getConstraints() << endl; vector< list<Buffer*> > bufs(HasLevel::getNumberOfLevels() + 1); for (Buffer::iterator buf = Buffer::begin(); buf != Buffer::end(); ++buf) if (buf->getCluster() == cluster && ( buf->getMinimum() || buf->getMinimumCalendar() || buf->getType() == *BufferProcure::metadata ) ) bufs[(buf->getLevel()>=0) ? buf->getLevel() : 0].push_back(&*buf); for (vector< list<Buffer*> >::iterator b_list = bufs.begin(); b_list != bufs.end(); ++b_list) for (list<Buffer*>::iterator b = b_list->begin(); b != b_list->end(); ++b) try { state->curBuffer = NULL; // A quantity of -1 is a flag for the buffer solver to solve safety stock. state->q_qty = -1.0; state->q_date = Date::infinitePast; state->a_cost = 0.0; state->a_penalty = 0.0; planningDemand = NULL; state->curDemand = NULL; state->curOwnerOpplan = NULL; // Call the buffer solver iteration_count = 0; (*b)->solve(*solver, this); // Check for excess if ((*b)->getType() != *BufferProcure::metadata) (*b)->solve(cleanup, this); CommandManager::commit(); } catch(...) { CommandManager::rollback(); } if (getLogLevel() > 0) logger << "Finished safety stock replenishment pass" << endl; safety_stock_planning = false; } DECLARE_EXPORT void SolverMRP::update_user_exits() { setUserExitBuffer(getPyObjectProperty(Tags::userexit_buffer.getName())); setUserExitDemand(getPyObjectProperty(Tags::userexit_demand.getName())); setUserExitFlow(getPyObjectProperty(Tags::userexit_flow.getName())); setUserExitOperation(getPyObjectProperty(Tags::userexit_operation.getName())); setUserExitResource(getPyObjectProperty(Tags::userexit_resource.getName())); } DECLARE_EXPORT void SolverMRP::solve(void *v) { // Configure user exits update_user_exits(); // Count how many clusters we have to plan int cl = HasLevel::getNumberOfClusters() + 1; // Categorize all demands in their cluster demands_per_cluster.resize(cl); for (Demand::iterator i = Demand::begin(); i != Demand::end(); ++i) demands_per_cluster[i->getCluster()].push_back(&*i); // Delete of operationplans of the affected clusters // This deletion is not multi-threaded... But on the other hand we need to // loop through the operations only once (rather than as many times as there // are clusters) if (getErasePreviousFirst()) { if (getLogLevel()>0) logger << "Deleting previous plan" << endl; for (Operation::iterator e=Operation::begin(); e!=Operation::end(); ++e) e->deleteOperationPlans(); } // Solve in parallel threads. // When not solving in silent and autocommit mode, we only use a single // solver thread. // Otherwise we use as many worker threads as processor cores. ThreadGroup threads; if (getLogLevel()>0 || !getAutocommit()) threads.setMaxParallel(1); // Register all clusters to be solved for (int j = 0; j < cl; ++j) threads.add( SolverMRPdata::runme, new SolverMRPdata(this, j, &(demands_per_cluster[j])) ); // Run the planning command threads and wait for them to exit threads.execute(); // @todo Check the resource setups that were broken - needs to be removed for (Resource::iterator gres = Resource::begin(); gres != Resource::end(); ++gres) if (gres->getSetupMatrix()) gres->updateSetups(); } DECLARE_EXPORT PyObject* SolverMRP::solve(PyObject *self, PyObject *args) { // Parse the argument PyObject *dem = NULL; if (args && !PyArg_ParseTuple(args, "|O:solve", &dem)) return NULL; if (dem && !PyObject_TypeCheck(dem, Demand::metadata->pythonClass)) { PyErr_SetString(PythonDataException, "solve(d) argument must be a demand"); return NULL; } Py_BEGIN_ALLOW_THREADS // Free Python interpreter for other threads try { SolverMRP* sol = static_cast<SolverMRP*>(self); if (!dem) { // Complete replan sol->setAutocommit(true); sol->solve(); } else { // Incrementally plan a single demand sol->setAutocommit(false); sol->update_user_exits(); static_cast<Demand*>(dem)->solve(*sol, &(sol->getCommands())); } } catch(...) { Py_BLOCK_THREADS; PythonType::evalException(); return NULL; } Py_END_ALLOW_THREADS // Reclaim Python interpreter return Py_BuildValue(""); } DECLARE_EXPORT PyObject* SolverMRP::commit(PyObject *self, PyObject *args) { Py_BEGIN_ALLOW_THREADS // Free Python interpreter for other threads try { SolverMRP * me = static_cast<SolverMRP*>(self); me->scanExcess(&(me->commands)); me->commands.CommandManager::commit(); } catch(...) { Py_BLOCK_THREADS; PythonType::evalException(); return NULL; } Py_END_ALLOW_THREADS // Reclaim Python interpreter return Py_BuildValue(""); } DECLARE_EXPORT PyObject* SolverMRP::rollback(PyObject *self, PyObject *args) { Py_BEGIN_ALLOW_THREADS // Free Python interpreter for other threads try { static_cast<SolverMRP*>(self)->commands.rollback(); } catch(...) { Py_BLOCK_THREADS; PythonType::evalException(); return NULL; } Py_END_ALLOW_THREADS // Reclaim Python interpreter return Py_BuildValue(""); } } // end namespace <commit_msg>revised cleanup sweep for PO replenishments<commit_after>/*************************************************************************** * * * Copyright (C) 2007-2015 by frePPLe bvba * * * * This library 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 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 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/>. * * * ***************************************************************************/ #define FREPPLE_CORE #include "frepple/solver.h" namespace frepple { DECLARE_EXPORT const MetaClass* SolverMRP::metadata; const Keyword SolverMRP::tag_iterationthreshold("iterationthreshold"); const Keyword SolverMRP::tag_iterationaccuracy("iterationaccuracy"); const Keyword SolverMRP::tag_lazydelay("lazydelay"); const Keyword SolverMRP::tag_allowsplits("allowsplits"); const Keyword SolverMRP::tag_rotateresources("rotateresources"); const Keyword SolverMRP::tag_planSafetyStockFirst("plansafetystockfirst"); const Keyword SolverMRP::tag_iterationmax("iterationmax"); void LibrarySolver::initialize() { // Initialize only once static bool init = false; if (init) { logger << "Warning: Calling frepple::LibrarySolver::initialize() more " << "than once." << endl; return; } init = true; // Register all classes. int nok = 0; nok += SolverMRP::initialize(); nok += OperatorDelete::initialize(); if (nok) throw RuntimeException("Error registering new Python types"); } int SolverMRP::initialize() { // Initialize the metadata metadata = MetaClass::registerClass<SolverMRP>( "solver", "solver_mrp", Object::create<SolverMRP>, true ); registerFields<SolverMRP>(const_cast<MetaClass*>(metadata)); // Initialize the Python class PythonType& x = FreppleClass<SolverMRP, Solver>::getPythonType(); x.setName("solver_mrp"); x.setDoc("frePPLe solver_mrp"); x.supportgetattro(); x.supportsetattro(); x.supportcreate(create); x.addMethod("solve", solve, METH_NOARGS, "run the solver"); x.addMethod("commit", commit, METH_NOARGS, "commit the plan changes"); x.addMethod("rollback", rollback, METH_NOARGS, "rollback the plan changes"); const_cast<MetaClass*>(metadata)->pythonClass = x.type_object(); return x.typeReady(); } PyObject* SolverMRP::create(PyTypeObject* pytype, PyObject* args, PyObject* kwds) { try { // Create the solver SolverMRP *s = new SolverMRP(); // Iterate over extra keywords, and set attributes. @todo move this responsibility to the readers... if (kwds) { PyObject *key, *value; Py_ssize_t pos = 0; while (PyDict_Next(kwds, &pos, &key, &value)) { PythonData field(value); PyObject* key_utf8 = PyUnicode_AsUTF8String(key); DataKeyword attr(PyBytes_AsString(key_utf8)); Py_DECREF(key_utf8); const MetaFieldBase* fmeta = SolverMRP::metadata->findField(attr.getHash()); if (!fmeta) fmeta = Solver::metadata->findField(attr.getHash()); if (fmeta) // Update the attribute fmeta->setField(s, field); else s->setProperty(attr.getName(), value); }; } // Return the object. The reference count doesn't need to be increased // as we do with other objects, because we want this object to be available // for the garbage collector of Python. return static_cast<PyObject*>(s); } catch (...) { PythonType::evalException(); return NULL; } } DECLARE_EXPORT bool SolverMRP::demand_comparison(const Demand* l1, const Demand* l2) { if (l1->getPriority() != l2->getPriority()) return l1->getPriority() < l2->getPriority(); else if (l1->getDue() != l2->getDue()) return l1->getDue() < l2->getDue(); else return l1->getQuantity() < l2->getQuantity(); } DECLARE_EXPORT void SolverMRP::SolverMRPdata::commit() { // Check SolverMRP* solver = getSolver(); if (!demands || !solver) throw LogicException("Missing demands or solver."); // Message if (solver->getLogLevel()>0) logger << "Start solving cluster " << cluster << " at " << Date::now() << endl; // Solve the planning problem try { // TODO Propagate & solve initial shortages and overloads // Sort the demands of this problem. // We use a stable sort to get reproducible results between platforms // and STL implementations. stable_sort(demands->begin(), demands->end(), demand_comparison); // Solve for safety stock in buffers. if (solver->getPlanSafetyStockFirst()) { constrainedPlanning = (solver->getPlanType() == 1); solveSafetyStock(solver); } // Loop through the list of all demands in this planning problem safety_stock_planning = false; constrainedPlanning = (solver->getPlanType() == 1); for (deque<Demand*>::const_iterator i = demands->begin(); i != demands->end(); ++i) { iteration_count = 0; try { // Plan the demand (*i)->solve(*solver, this); } catch (...) { // Error message logger << "Error: Caught an exception while solving demand '" << (*i)->getName() << "':" << endl; try {throw;} catch (const bad_exception&) {logger << " bad exception" << endl;} catch (const exception& e) {logger << " " << e.what() << endl;} catch (...) {logger << " Unknown type" << endl;} } } // Clean the list of demands of this cluster demands->clear(); // Completely recreate all purchasing operation plans for (set<const OperationItemSupplier*>::iterator o = purchase_operations.begin(); o != purchase_operations.end(); ++o ) { // TODO This code assumes the buffer is ONLY replenished through these purchases. // When it is replenished through an alternate, it will not give the results we expect. // Erase existing proposed purchases const_cast<OperationItemSupplier*>(*o)->deleteOperationPlans(false); // Create new proposed purchases try { safety_stock_planning = true; state->curBuffer = NULL; state->q_qty = -1.0; state->q_date = Date::infinitePast; state->a_cost = 0.0; state->a_penalty = 0.0; state->curDemand = NULL; state->curOwnerOpplan = NULL; state->a_qty = 0; (*o)->getBuffer()->solve(*solver, this); CommandManager::commit(); } catch(...) { CommandManager::rollback(); } } purchase_operations.clear(); // Solve for safety stock in buffers. if (!solver->getPlanSafetyStockFirst()) solveSafetyStock(solver); } catch (...) { // We come in this exception handling code only if there is a problem with // with this cluster that goes beyond problems with single orders. // If the problem is with single orders, the exception handling code above // will do a proper rollback. // Error message logger << "Error: Caught an exception while solving cluster " << cluster << ":" << endl; try {throw;} catch (const bad_exception&) {logger << " bad exception" << endl;} catch (const exception& e) {logger << " " << e.what() << endl;} catch (...) {logger << " Unknown type" << endl;} // Clean up the operationplans of this cluster for (Operation::iterator f=Operation::begin(); f!=Operation::end(); ++f) if (f->getCluster() == cluster) f->deleteOperationPlans(); // Clean the list of demands of this cluster demands->clear(); } // Message if (solver->getLogLevel()>0) logger << "End solving cluster " << cluster << " at " << Date::now() << endl; } void SolverMRP::SolverMRPdata::solveSafetyStock(SolverMRP* solver) { OperatorDelete cleanup(this); safety_stock_planning = true; if (getLogLevel() > 0) logger << "Start safety stock replenishment pass " << solver->getConstraints() << endl; vector< list<Buffer*> > bufs(HasLevel::getNumberOfLevels() + 1); for (Buffer::iterator buf = Buffer::begin(); buf != Buffer::end(); ++buf) if (buf->getCluster() == cluster && ( buf->getMinimum() || buf->getMinimumCalendar() || buf->getType() == *BufferProcure::metadata ) ) bufs[(buf->getLevel()>=0) ? buf->getLevel() : 0].push_back(&*buf); for (vector< list<Buffer*> >::iterator b_list = bufs.begin(); b_list != bufs.end(); ++b_list) for (list<Buffer*>::iterator b = b_list->begin(); b != b_list->end(); ++b) try { state->curBuffer = NULL; // A quantity of -1 is a flag for the buffer solver to solve safety stock. state->q_qty = -1.0; state->q_date = Date::infinitePast; state->a_cost = 0.0; state->a_penalty = 0.0; planningDemand = NULL; state->curDemand = NULL; state->curOwnerOpplan = NULL; // Call the buffer solver iteration_count = 0; (*b)->solve(*solver, this); // Check for excess if ((*b)->getType() != *BufferProcure::metadata) (*b)->solve(cleanup, this); CommandManager::commit(); } catch(...) { CommandManager::rollback(); } if (getLogLevel() > 0) logger << "Finished safety stock replenishment pass" << endl; safety_stock_planning = false; } DECLARE_EXPORT void SolverMRP::update_user_exits() { setUserExitBuffer(getPyObjectProperty(Tags::userexit_buffer.getName())); setUserExitDemand(getPyObjectProperty(Tags::userexit_demand.getName())); setUserExitFlow(getPyObjectProperty(Tags::userexit_flow.getName())); setUserExitOperation(getPyObjectProperty(Tags::userexit_operation.getName())); setUserExitResource(getPyObjectProperty(Tags::userexit_resource.getName())); } DECLARE_EXPORT void SolverMRP::solve(void *v) { // Configure user exits update_user_exits(); // Count how many clusters we have to plan int cl = HasLevel::getNumberOfClusters() + 1; // Categorize all demands in their cluster demands_per_cluster.resize(cl); for (Demand::iterator i = Demand::begin(); i != Demand::end(); ++i) demands_per_cluster[i->getCluster()].push_back(&*i); // Delete of operationplans of the affected clusters // This deletion is not multi-threaded... But on the other hand we need to // loop through the operations only once (rather than as many times as there // are clusters) if (getErasePreviousFirst()) { if (getLogLevel()>0) logger << "Deleting previous plan" << endl; for (Operation::iterator e=Operation::begin(); e!=Operation::end(); ++e) e->deleteOperationPlans(); } // Solve in parallel threads. // When not solving in silent and autocommit mode, we only use a single // solver thread. // Otherwise we use as many worker threads as processor cores. ThreadGroup threads; if (getLogLevel()>0 || !getAutocommit()) threads.setMaxParallel(1); // Register all clusters to be solved for (int j = 0; j < cl; ++j) threads.add( SolverMRPdata::runme, new SolverMRPdata(this, j, &(demands_per_cluster[j])) ); // Run the planning command threads and wait for them to exit threads.execute(); // @todo Check the resource setups that were broken - needs to be removed for (Resource::iterator gres = Resource::begin(); gres != Resource::end(); ++gres) if (gres->getSetupMatrix()) gres->updateSetups(); } DECLARE_EXPORT PyObject* SolverMRP::solve(PyObject *self, PyObject *args) { // Parse the argument PyObject *dem = NULL; if (args && !PyArg_ParseTuple(args, "|O:solve", &dem)) return NULL; if (dem && !PyObject_TypeCheck(dem, Demand::metadata->pythonClass)) { PyErr_SetString(PythonDataException, "solve(d) argument must be a demand"); return NULL; } Py_BEGIN_ALLOW_THREADS // Free Python interpreter for other threads try { SolverMRP* sol = static_cast<SolverMRP*>(self); if (!dem) { // Complete replan sol->setAutocommit(true); sol->solve(); } else { // Incrementally plan a single demand sol->setAutocommit(false); sol->update_user_exits(); static_cast<Demand*>(dem)->solve(*sol, &(sol->getCommands())); } } catch(...) { Py_BLOCK_THREADS; PythonType::evalException(); return NULL; } Py_END_ALLOW_THREADS // Reclaim Python interpreter return Py_BuildValue(""); } DECLARE_EXPORT PyObject* SolverMRP::commit(PyObject *self, PyObject *args) { Py_BEGIN_ALLOW_THREADS // Free Python interpreter for other threads try { SolverMRP * me = static_cast<SolverMRP*>(self); me->scanExcess(&(me->commands)); me->commands.CommandManager::commit(); } catch(...) { Py_BLOCK_THREADS; PythonType::evalException(); return NULL; } Py_END_ALLOW_THREADS // Reclaim Python interpreter return Py_BuildValue(""); } DECLARE_EXPORT PyObject* SolverMRP::rollback(PyObject *self, PyObject *args) { Py_BEGIN_ALLOW_THREADS // Free Python interpreter for other threads try { static_cast<SolverMRP*>(self)->commands.rollback(); } catch(...) { Py_BLOCK_THREADS; PythonType::evalException(); return NULL; } Py_END_ALLOW_THREADS // Reclaim Python interpreter return Py_BuildValue(""); } } // end namespace <|endoftext|>
<commit_before>#include <cstring> #include <algorithm> #include <fstream> #include "xml_parser.h" #include "os.h" #include "string.h" namespace lms { namespace internal { template<typename T> struct PutOnStack { std::stack<T> &stack; PutOnStack(std::stack<T> &stack, const T &obj) : stack(stack) { stack.push(obj); } ~PutOnStack() { stack.pop(); } }; bool evaluateSet(const std::string &condition, const std::vector<std::string> &flags) { return std::find(flags.begin(), flags.end(), condition) != flags.end(); } bool evaluateNotSet(const std::string &condition, const std::vector<std::string> &flags) { return std::find(flags.begin(), flags.end(), condition) == flags.end(); } bool evaluateAnyOf(const std::vector<std::string> &condition, const std::vector<std::string> &flags) { return std::find_first_of(condition.begin(), condition.end(), flags.begin(), flags.end()) != condition.end(); } bool evaluateAllOf(const std::vector<std::string> &condition, const std::vector<std::string> &flags) { for (const std::string &cond : condition) { if (std::find(flags.begin(), flags.end(), cond) == flags.end()) { return false; } } return true; } bool evaluateNothingOf(const std::vector<std::string> &condition, const std::vector<std::string> &flags) { for (const std::string &cond : condition) { if (std::find(flags.begin(), flags.end(), cond) != flags.end()) { return false; } } return true; } void preprocessXML(pugi::xml_node node, const std::vector<std::string> &flags) { if (std::string("/framework/module/config") == node.path()) { // skip <config> nodes return; } for (pugi::xml_node child = node.child("if"); child;) { if (std::string("if") == child.name()) { bool result = false; pugi::xml_attribute setAttr = child.attribute("set"); pugi::xml_attribute notSetAttr = child.attribute("notSet"); pugi::xml_attribute anyOfAttr = child.attribute("anyOf"); pugi::xml_attribute allOfAttr = child.attribute("allOf"); pugi::xml_attribute nothingOfAttr = child.attribute("nothingOf"); if (setAttr) { result = evaluateSet(setAttr.value(), flags); } else if (notSetAttr) { result = evaluateNotSet(notSetAttr.value(), flags); } else if (anyOfAttr) { result = evaluateAnyOf(split(anyOfAttr.value(), ','), flags); } else if (allOfAttr) { result = evaluateAllOf(split(allOfAttr.value(), ','), flags); } else if (nothingOfAttr) { result = evaluateNothingOf(split(nothingOfAttr.value(), ','), flags); } else { std::cout << "Failed to preprocess XML <if>" << std::endl; } // if the condition evaluated to true if (result) { // then move all children of <if> to be siblings of <if> pugi::xml_node moveNode; while ((moveNode = child.first_child())) { node.insert_move_after(moveNode, child); } node.remove_child(child); } else { node.remove_child(child); } // reset child child = node.first_child(); } else { // go further child = child.next_sibling("if"); } } for (pugi::xml_node child : node) { preprocessXML(child, flags); } } XmlParser::XmlParser(RuntimeInfo &info) : runtime(info) {} void parseModuleConfig(pugi::xml_node node, Config &config, const std::string &key) { for (auto subnode : node.children()) { if (subnode.type() == pugi::node_element) { std::string newKey = subnode.attribute("name").as_string(); if (!key.empty()) { newKey = key + "." + newKey; } if (std::strcmp("group", subnode.name()) == 0) { parseModuleConfig(subnode, config, newKey); } else { config.set<std::string>(newKey, trim(subnode.child_value())); } } } } bool XmlParser::parseClock(pugi::xml_node node, ClockInfo &info) { std::string clockUnit; std::int64_t clockValue = 0; pugi::xml_attribute sleepAttr = node.attribute("sleep"); pugi::xml_attribute compensateAttr = node.attribute("compensate"); pugi::xml_attribute unitAttr = node.attribute("unit"); pugi::xml_attribute valueAttr = node.attribute("value"); pugi::xml_attribute watchDog = node.attribute("watchDog"); info.slowWarnings = true; if (sleepAttr) { info.sleep = sleepAttr.as_bool(); } else { // if not enabled attribute is given then the clock is considered // to be disabled info.sleep = false; } if (valueAttr) { clockValue = valueAttr.as_llong(); } else { info.slowWarnings = false; return errorMissingAttr(node, valueAttr); } if (unitAttr) { clockUnit = unitAttr.value(); } else { info.slowWarnings = false; return errorMissingAttr(node, unitAttr); } if (compensateAttr) { info.sleepCompensate = compensateAttr.as_bool(); } else { info.sleepCompensate = false; } if (clockUnit == "hz") { info.cycle = Time::fromMicros(1000000 / clockValue); } else if (clockUnit == "ms") { info.cycle = Time::fromMillis(clockValue); } else if (clockUnit == "us") { info.cycle = Time::fromMicros(clockValue); } else { info.slowWarnings = false; return errorInvalidAttr(node, unitAttr, "ms/us/hz"); } if (watchDog) { info.watchDogEnabled = true; if (clockUnit == "hz") { info.watchDog = Time::fromMicros(1000000 / watchDog.as_llong()); } else if (clockUnit == "ms") { info.watchDog = Time::fromMillis(watchDog.as_llong()); } else if (clockUnit == "us") { info.watchDog = Time::fromMicros(watchDog.as_llong()); } else { info.watchDogEnabled = false; return errorInvalidAttr(node, watchDog, "ms/us/hz"); } } return true; } bool XmlParser::parseInclude(pugi::xml_node node) { pugi::xml_attribute srcAttr = node.attribute("src"); if(! srcAttr) return errorMissingAttr(node, srcAttr); std::string includePath = dirname(m_filestack.top()) + "/" + srcAttr.value(); parseFile(includePath); return true; } bool XmlParser::parseModule(pugi::xml_node node, ModuleInfo &info) { pugi::xml_attribute nameAttr = node.attribute("name"); pugi::xml_attribute libAttr = node.attribute("lib"); pugi::xml_attribute classAttr = node.attribute("class"); pugi::xml_attribute mainThreadAttr = node.attribute("mainThread"); pugi::xml_attribute logLevelAttr = node.attribute("log"); if(! nameAttr) return errorMissingAttr(node, nameAttr); if(! libAttr) return errorMissingAttr(node, libAttr); if(! classAttr) return errorMissingAttr(node, classAttr); info.name = nameAttr.as_string(); info.lib = libAttr.as_string(); info.clazz = classAttr.as_string(); info.mainThread = mainThreadAttr.as_bool(); logging::Level defaultLevel = logging::Level::ALL; if (logLevelAttr) { logging::levelFromName(logLevelAttr.as_string(), defaultLevel); } info.log = defaultLevel; // parse all channel mappings // TODO This now deprecated in favor for channelHint for (pugi::xml_node mappingNode : node.children("channelMapping")) { pugi::xml_attribute fromAttr = mappingNode.attribute("from"); pugi::xml_attribute toAttr = mappingNode.attribute("to"); pugi::xml_attribute priorityAttr = mappingNode.attribute("priority"); if (!fromAttr) return errorMissingAttr(mappingNode, fromAttr); if (!toAttr) return errorMissingAttr(mappingNode, toAttr); int priority = priorityAttr ? priorityAttr.as_int() : 0; info.channelMapping[fromAttr.value()] = std::make_pair(toAttr.value(), priority); } for (pugi::xml_node channelNode : node.children("channelHint")) { pugi::xml_attribute nameAttr = channelNode.attribute("name"); pugi::xml_attribute mapToAttr = channelNode.attribute("mapTo"); pugi::xml_attribute priorityAttr = channelNode.attribute("priority"); if (!nameAttr) return errorMissingAttr(channelNode, nameAttr); std::string mapTo = mapToAttr ? mapToAttr.value() : nameAttr.value(); int priority = priorityAttr ? priorityAttr.as_int() : 0; info.channelMapping[nameAttr.value()] = std::make_pair(mapTo, priority); } // parse all config for (pugi::xml_node configNode : node.children("config")) { pugi::xml_attribute srcAttr = configNode.attribute("src"); pugi::xml_attribute nameAttr = configNode.attribute("name"); std::string name = "default"; if (nameAttr) { name = nameAttr.value(); } if (srcAttr) { std::string lconfPath = dirname(m_filestack.top()) + "/" + srcAttr.value(); bool loadResult = info.configs[name].loadFromFile(lconfPath); if (!loadResult) { return errorFile(lconfPath); } else { m_files.push_back(lconfPath); } } else { // if there was no src attribut then parse the tag's content parseModuleConfig(configNode, info.configs[name], ""); } } return true; } bool XmlParser::parseService(pugi::xml_node node, ServiceInfo &info) { pugi::xml_attribute nameAttr = node.attribute("name"); pugi::xml_attribute libAttr = node.attribute("lib"); pugi::xml_attribute classAttr = node.attribute("class"); pugi::xml_attribute logLevelAttr = node.attribute("log"); if(! nameAttr) return errorMissingAttr(node, nameAttr); if(! libAttr) return errorMissingAttr(node, libAttr); if(! classAttr) return errorMissingAttr(node, classAttr); info.name = nameAttr.as_string(); info.lib = libAttr.as_string(); info.clazz = classAttr.as_string(); logging::Level defaultLevel = logging::Level::ALL; if (logLevelAttr) { logging::levelFromName(logLevelAttr.as_string(), defaultLevel); } info.log = defaultLevel; // parse all config for (pugi::xml_node configNode : node.children("config")) { pugi::xml_attribute srcAttr = configNode.attribute("src"); pugi::xml_attribute nameAttr = configNode.attribute("name"); std::string name = "default"; if (nameAttr) { name = nameAttr.value(); } if (srcAttr) { std::string lconfPath = dirname(m_filestack.top()) + "/" + srcAttr.value(); bool loadResult = info.configs[name].loadFromFile(lconfPath); if (!loadResult) { errorFile(lconfPath); } else { m_files.push_back(lconfPath); } } else { // if there was no src attribut then parse the tag's content parseModuleConfig(configNode, info.configs[name], ""); } } return true; } bool XmlParser::parseFile(std::istream &is, const std::string &file) { PutOnStack<std::string> put(m_filestack, file); m_files.push_back(file); pugi::xml_document doc; pugi::xml_parse_result result = doc.load(is); if (!result) { return errorPugiParseResult(file, result); } pugi::xml_node rootNode = doc.child("lms"); preprocessXML(rootNode, {}); for (pugi::xml_node node : rootNode.children()) { if (std::string("clock") == node.name()) { if(!parseClock(node, runtime.clock)) return false; } else if (std::string("module") == node.name()) { ModuleInfo module; if(parseModule(node, module)) { runtime.modules.push_back(module); } } else if (std::string("include") == node.name()) { parseInclude(node); } else if (std::string("service") == node.name()) { ServiceInfo service; if(parseService(node, service)) { runtime.services.push_back(service); } } else { errorUnknownNode(node); } } return true; } bool XmlParser::parseFile(const std::string &file) { std::ifstream ifs(file); if (!ifs.is_open()) { return errorFile(file); } return parseFile(ifs, file); } std::vector<std::string> const &XmlParser::files() const { return m_files; } std::vector<std::string> const &XmlParser::errors() const { return m_errors; } bool XmlParser::errorMissingAttr(pugi::xml_node node, pugi::xml_attribute attr) { m_errors.push_back(std::string("Missing attribute ") + attr.name() + " in node " + node.path()); return false; } bool XmlParser::errorInvalidAttr(pugi::xml_node node, pugi::xml_attribute attr, const std::string &expectedValue) { m_errors.push_back(std::string("Invalid value for attribute ") + attr.name() + " in node " + node.path() + ", Value is \"" + attr.value() + "\" but expected \"" + expectedValue + "\""); return false; } void XmlParser::errorInvalidNodeContent(pugi::xml_node node, const std::string &expected) { m_errors.push_back("Invalid text content in node " + node.path() + ", content: \"" + node.child_value() + "\", expected \"" + expected + "\""); } bool XmlParser::errorFile(const std::string &file) { m_errors.push_back("Could not open file " + file); return false; } bool XmlParser::errorPugiParseResult(const std::string &file, const pugi::xml_parse_result &result) { m_errors.push_back(std::string() + "Failed to parse " + file + " as XML: " + std::to_string(result.offset) + " " + result.description()); return false; } bool XmlParser::errorUnknownNode(pugi::xml_node node) { m_errors.push_back("Unknown node " + node.path()); return false; } } // namespace internal } // namespace lms <commit_msg>improved debug msg<commit_after>#include <cstring> #include <algorithm> #include <fstream> #include "xml_parser.h" #include "os.h" #include "string.h" namespace lms { namespace internal { template<typename T> struct PutOnStack { std::stack<T> &stack; PutOnStack(std::stack<T> &stack, const T &obj) : stack(stack) { stack.push(obj); } ~PutOnStack() { stack.pop(); } }; bool evaluateSet(const std::string &condition, const std::vector<std::string> &flags) { return std::find(flags.begin(), flags.end(), condition) != flags.end(); } bool evaluateNotSet(const std::string &condition, const std::vector<std::string> &flags) { return std::find(flags.begin(), flags.end(), condition) == flags.end(); } bool evaluateAnyOf(const std::vector<std::string> &condition, const std::vector<std::string> &flags) { return std::find_first_of(condition.begin(), condition.end(), flags.begin(), flags.end()) != condition.end(); } bool evaluateAllOf(const std::vector<std::string> &condition, const std::vector<std::string> &flags) { for (const std::string &cond : condition) { if (std::find(flags.begin(), flags.end(), cond) == flags.end()) { return false; } } return true; } bool evaluateNothingOf(const std::vector<std::string> &condition, const std::vector<std::string> &flags) { for (const std::string &cond : condition) { if (std::find(flags.begin(), flags.end(), cond) != flags.end()) { return false; } } return true; } void preprocessXML(pugi::xml_node node, const std::vector<std::string> &flags) { if (std::string("/framework/module/config") == node.path()) { // skip <config> nodes return; } for (pugi::xml_node child = node.child("if"); child;) { if (std::string("if") == child.name()) { bool result = false; pugi::xml_attribute setAttr = child.attribute("set"); pugi::xml_attribute notSetAttr = child.attribute("notSet"); pugi::xml_attribute anyOfAttr = child.attribute("anyOf"); pugi::xml_attribute allOfAttr = child.attribute("allOf"); pugi::xml_attribute nothingOfAttr = child.attribute("nothingOf"); if (setAttr) { result = evaluateSet(setAttr.value(), flags); } else if (notSetAttr) { result = evaluateNotSet(notSetAttr.value(), flags); } else if (anyOfAttr) { result = evaluateAnyOf(split(anyOfAttr.value(), ','), flags); } else if (allOfAttr) { result = evaluateAllOf(split(allOfAttr.value(), ','), flags); } else if (nothingOfAttr) { result = evaluateNothingOf(split(nothingOfAttr.value(), ','), flags); } else { std::cout << "Failed to preprocess XML <if>" << std::endl; } // if the condition evaluated to true if (result) { // then move all children of <if> to be siblings of <if> pugi::xml_node moveNode; while ((moveNode = child.first_child())) { node.insert_move_after(moveNode, child); } node.remove_child(child); } else { node.remove_child(child); } // reset child child = node.first_child(); } else { // go further child = child.next_sibling("if"); } } for (pugi::xml_node child : node) { preprocessXML(child, flags); } } XmlParser::XmlParser(RuntimeInfo &info) : runtime(info) {} void parseModuleConfig(pugi::xml_node node, Config &config, const std::string &key) { for (auto subnode : node.children()) { if (subnode.type() == pugi::node_element) { std::string newKey = subnode.attribute("name").as_string(); if (!key.empty()) { newKey = key + "." + newKey; } if (std::strcmp("group", subnode.name()) == 0) { parseModuleConfig(subnode, config, newKey); } else { config.set<std::string>(newKey, trim(subnode.child_value())); } } } } bool XmlParser::parseClock(pugi::xml_node node, ClockInfo &info) { std::string clockUnit; std::int64_t clockValue = 0; pugi::xml_attribute sleepAttr = node.attribute("sleep"); pugi::xml_attribute compensateAttr = node.attribute("compensate"); pugi::xml_attribute unitAttr = node.attribute("unit"); pugi::xml_attribute valueAttr = node.attribute("value"); pugi::xml_attribute watchDog = node.attribute("watchDog"); info.slowWarnings = true; if (sleepAttr) { info.sleep = sleepAttr.as_bool(); } else { // if not enabled attribute is given then the clock is considered // to be disabled info.sleep = false; } if (valueAttr) { clockValue = valueAttr.as_llong(); } else { info.slowWarnings = false; return errorMissingAttr(node, valueAttr); } if (unitAttr) { clockUnit = unitAttr.value(); } else { info.slowWarnings = false; return errorMissingAttr(node, unitAttr); } if (compensateAttr) { info.sleepCompensate = compensateAttr.as_bool(); } else { info.sleepCompensate = false; } if (clockUnit == "hz") { info.cycle = Time::fromMicros(1000000 / clockValue); } else if (clockUnit == "ms") { info.cycle = Time::fromMillis(clockValue); } else if (clockUnit == "us") { info.cycle = Time::fromMicros(clockValue); } else { info.slowWarnings = false; return errorInvalidAttr(node, unitAttr, "ms/us/hz"); } if (watchDog) { info.watchDogEnabled = true; if (clockUnit == "hz") { info.watchDog = Time::fromMicros(1000000 / watchDog.as_llong()); } else if (clockUnit == "ms") { info.watchDog = Time::fromMillis(watchDog.as_llong()); } else if (clockUnit == "us") { info.watchDog = Time::fromMicros(watchDog.as_llong()); } else { info.watchDogEnabled = false; return errorInvalidAttr(node, watchDog, "ms/us/hz"); } } return true; } bool XmlParser::parseInclude(pugi::xml_node node) { pugi::xml_attribute srcAttr = node.attribute("src"); if(! srcAttr) return errorMissingAttr(node, srcAttr); std::string includePath = dirname(m_filestack.top()) + "/" + srcAttr.value(); parseFile(includePath); return true; } bool XmlParser::parseModule(pugi::xml_node node, ModuleInfo &info) { pugi::xml_attribute nameAttr = node.attribute("name"); pugi::xml_attribute libAttr = node.attribute("lib"); pugi::xml_attribute classAttr = node.attribute("class"); pugi::xml_attribute mainThreadAttr = node.attribute("mainThread"); pugi::xml_attribute logLevelAttr = node.attribute("log"); if(! nameAttr) return errorMissingAttr(node, nameAttr); if(! libAttr) return errorMissingAttr(node, libAttr); if(! classAttr) return errorMissingAttr(node, classAttr); info.name = nameAttr.as_string(); info.lib = libAttr.as_string(); info.clazz = classAttr.as_string(); info.mainThread = mainThreadAttr.as_bool(); logging::Level defaultLevel = logging::Level::ALL; if (logLevelAttr) { logging::levelFromName(logLevelAttr.as_string(), defaultLevel); } info.log = defaultLevel; // parse all channel mappings // TODO This now deprecated in favor for channelHint for (pugi::xml_node mappingNode : node.children("channelMapping")) { pugi::xml_attribute fromAttr = mappingNode.attribute("from"); pugi::xml_attribute toAttr = mappingNode.attribute("to"); pugi::xml_attribute priorityAttr = mappingNode.attribute("priority"); if (!fromAttr) return errorMissingAttr(mappingNode, fromAttr); if (!toAttr) return errorMissingAttr(mappingNode, toAttr); int priority = priorityAttr ? priorityAttr.as_int() : 0; info.channelMapping[fromAttr.value()] = std::make_pair(toAttr.value(), priority); } for (pugi::xml_node channelNode : node.children("channelHint")) { pugi::xml_attribute nameAttr = channelNode.attribute("name"); pugi::xml_attribute mapToAttr = channelNode.attribute("mapTo"); pugi::xml_attribute priorityAttr = channelNode.attribute("priority"); if (!nameAttr) return errorMissingAttr(channelNode, nameAttr); std::string mapTo = mapToAttr ? mapToAttr.value() : nameAttr.value(); int priority = priorityAttr ? priorityAttr.as_int() : 0; info.channelMapping[nameAttr.value()] = std::make_pair(mapTo, priority); } // parse all config for (pugi::xml_node configNode : node.children("config")) { pugi::xml_attribute srcAttr = configNode.attribute("src"); pugi::xml_attribute nameAttr = configNode.attribute("name"); std::string name = "default"; if (nameAttr) { name = nameAttr.value(); } if (srcAttr) { std::string lconfPath = dirname(m_filestack.top()) + "/" + srcAttr.value(); bool loadResult = info.configs[name].loadFromFile(lconfPath); if (!loadResult) { return errorFile(lconfPath); } else { m_files.push_back(lconfPath); } } else { // if there was no src attribut then parse the tag's content parseModuleConfig(configNode, info.configs[name], ""); } } return true; } bool XmlParser::parseService(pugi::xml_node node, ServiceInfo &info) { pugi::xml_attribute nameAttr = node.attribute("name"); pugi::xml_attribute libAttr = node.attribute("lib"); pugi::xml_attribute classAttr = node.attribute("class"); pugi::xml_attribute logLevelAttr = node.attribute("log"); if(! nameAttr) return errorMissingAttr(node, nameAttr); if(! libAttr) return errorMissingAttr(node, libAttr); if(! classAttr) return errorMissingAttr(node, classAttr); info.name = nameAttr.as_string(); info.lib = libAttr.as_string(); info.clazz = classAttr.as_string(); logging::Level defaultLevel = logging::Level::ALL; if (logLevelAttr) { logging::levelFromName(logLevelAttr.as_string(), defaultLevel); } info.log = defaultLevel; // parse all config for (pugi::xml_node configNode : node.children("config")) { pugi::xml_attribute srcAttr = configNode.attribute("src"); pugi::xml_attribute nameAttr = configNode.attribute("name"); std::string name = "default"; if (nameAttr) { name = nameAttr.value(); } if (srcAttr) { std::string lconfPath = dirname(m_filestack.top()) + "/" + srcAttr.value(); bool loadResult = info.configs[name].loadFromFile(lconfPath); if (!loadResult) { errorFile(lconfPath); } else { m_files.push_back(lconfPath); } } else { // if there was no src attribut then parse the tag's content parseModuleConfig(configNode, info.configs[name], ""); } } return true; } bool XmlParser::parseFile(std::istream &is, const std::string &file) { PutOnStack<std::string> put(m_filestack, file); m_files.push_back(file); pugi::xml_document doc; pugi::xml_parse_result result = doc.load(is); if (!result) { return errorPugiParseResult(file, result); } pugi::xml_node rootNode = doc.child("lms"); preprocessXML(rootNode, {}); for (pugi::xml_node node : rootNode.children()) { if (std::string("clock") == node.name()) { if(!parseClock(node, runtime.clock)) return false; } else if (std::string("module") == node.name()) { ModuleInfo module; if(parseModule(node, module)) { runtime.modules.push_back(module); } } else if (std::string("include") == node.name()) { parseInclude(node); } else if (std::string("service") == node.name()) { ServiceInfo service; if(parseService(node, service)) { runtime.services.push_back(service); } } else { errorUnknownNode(node); } } return true; } bool XmlParser::parseFile(const std::string &file) { std::ifstream ifs(file); if (!ifs.is_open()) { return errorFile(file); } return parseFile(ifs, file); } std::vector<std::string> const &XmlParser::files() const { return m_files; } std::vector<std::string> const &XmlParser::errors() const { return m_errors; } bool XmlParser::errorMissingAttr(pugi::xml_node node, pugi::xml_attribute attr) { m_errors.push_back(std::string("Missing attribute ") + attr.name() + " in node " + node.path() + " in file " + m_filestack.top()); return false; } bool XmlParser::errorInvalidAttr(pugi::xml_node node, pugi::xml_attribute attr, const std::string &expectedValue) { m_errors.push_back(std::string("Invalid value for attribute ") + attr.name() + " in node " + node.path() + ", Value is \"" + attr.value() + "\" but expected \"" + expectedValue + "\""); return false; } void XmlParser::errorInvalidNodeContent(pugi::xml_node node, const std::string &expected) { m_errors.push_back("Invalid text content in node " + node.path() + ", content: \"" + node.child_value() + "\", expected \"" + expected + "\""); } bool XmlParser::errorFile(const std::string &file) { m_errors.push_back("Could not open file " + file); return false; } bool XmlParser::errorPugiParseResult(const std::string &file, const pugi::xml_parse_result &result) { m_errors.push_back(std::string() + "Failed to parse " + file + " as XML: " + std::to_string(result.offset) + " " + result.description()); return false; } bool XmlParser::errorUnknownNode(pugi::xml_node node) { m_errors.push_back("Unknown node " + node.path()); return false; } } // namespace internal } // namespace lms <|endoftext|>
<commit_before>#include "node_operators.h" #include "expression_graph.h" #include "tensors/tensor_operators.h" namespace marian { ConstantNode::ConstantNode(Ptr<ExpressionGraph> graph, const Shape& shape, const Ptr<inits::NodeInitializer>& init, Type value_type) : Node(graph, shape, value_type), init_(init), initialized_(false) { init_->setAllocator(graph->allocator()); setTrainable(false); } size_t ConstantNode::allocate() { size_t elements = 0; if(!val_) { graph()->allocateForward(this); elements = val_->shape().elements(); } return elements; } void ConstantNode::init() { if(!initialized_) { init_->apply(val_); initialized_ = true; } init_.reset(); } ParamNode::ParamNode(Ptr<ExpressionGraph> graph, const Shape& shape, const Ptr<inits::NodeInitializer>& init, bool fixed) : ParamNode(graph, shape, init, Type::float32, fixed) {} ParamNode::ParamNode(Ptr<ExpressionGraph> graph, const Shape& shape, const Ptr<inits::NodeInitializer>& init, const Type& valueType, bool fixed) : Node(graph, shape, valueType), init_(init), initialized_(false) { init_->setAllocator(graph->allocator()); setTrainable(!fixed); setMemoize(graph->isInference()); } void ParamNode::init() { std::cerr << name() << " " << shape() << std::endl; if(!initialized_) { init_->apply(val_); initialized_ = true; } init_.reset(); } } // namespace marian <commit_msg>remove debug code<commit_after>#include "node_operators.h" #include "expression_graph.h" #include "tensors/tensor_operators.h" namespace marian { ConstantNode::ConstantNode(Ptr<ExpressionGraph> graph, const Shape& shape, const Ptr<inits::NodeInitializer>& init, Type value_type) : Node(graph, shape, value_type), init_(init), initialized_(false) { init_->setAllocator(graph->allocator()); setTrainable(false); } size_t ConstantNode::allocate() { size_t elements = 0; if(!val_) { graph()->allocateForward(this); elements = val_->shape().elements(); } return elements; } void ConstantNode::init() { if(!initialized_) { init_->apply(val_); initialized_ = true; } init_.reset(); } ParamNode::ParamNode(Ptr<ExpressionGraph> graph, const Shape& shape, const Ptr<inits::NodeInitializer>& init, bool fixed) : ParamNode(graph, shape, init, Type::float32, fixed) {} ParamNode::ParamNode(Ptr<ExpressionGraph> graph, const Shape& shape, const Ptr<inits::NodeInitializer>& init, const Type& valueType, bool fixed) : Node(graph, shape, valueType), init_(init), initialized_(false) { init_->setAllocator(graph->allocator()); setTrainable(!fixed); setMemoize(graph->isInference()); } void ParamNode::init() { if(!initialized_) { init_->apply(val_); initialized_ = true; } init_.reset(); } } // namespace marian <|endoftext|>
<commit_before>/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) Associated Universities Inc., 2002 * * (c) European Southern Observatory, 2002 * Copyright by ESO (in the framework of the ALMA collaboration) * and Cosylab 2002, All rights reserved * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * * * "@(#) $Id: contLogTestImpl.cpp,v 1.7 2007/12/28 04:13:32 cparedes Exp $" * * who when what * -------- ---------- ---------------------------------------------- * eallaert 2007-11-05 initial version * */ #include <contLogTestImpl.h> #include <ACSErrTypeCommon.h> #include <loggingLogLevelDefinition.h> #include <loggingLogger.h> #include "loggingGetLogger.h" #include <iostream> ACE_RCSID(contLogTest, contLogTestImpl, "$Id: contLogTestImpl.cpp,v 1.7 2007/12/28 04:13:32 cparedes Exp $") /* ----------------------------------------------------------------*/ TestLogLevelsComp::TestLogLevelsComp( const ACE_CString &name, maci::ContainerServices * containerServices) : ACSComponentImpl(name, containerServices) { // ACS_TRACE is used for debugging purposes ACS_TRACE("::TestLogLevelsComp::TestLogLevelsComp"); } /* ----------------------------------------------------------------*/ TestLogLevelsComp::~TestLogLevelsComp() { // ACS_TRACE is used for debugging purposes ACS_TRACE("::TestLogLevelsComp::~TestLogLevelsComp"); ACS_DEBUG_PARAM("::TestLogLevelsComp::~TestLogLevelsComp", "Destroying %s...", name()); } /* --------------------- [ CORBA interface ] ----------------------*/ ::contLogTest::LongSeq* TestLogLevelsComp::getLevels () throw (CORBA::SystemException, ACSErrTypeCommon::CouldntPerformActionEx) { Logging::Logger *l = getLogger(); ::contLogTest::LongSeq_var level = new ::contLogTest::LongSeq(5); level->length(5); // need the equivalent of Java's logConfig.getMinLogLevel() etc. in C++ for (int i = 0; i <5 ; i++) level[i] = static_cast< CORBA::Long >(i); level[3] = static_cast< CORBA::Long >(l->getRemoteLevel()); level[4] = static_cast< CORBA::Long >(l->getLocalLevel()); return level._retn(); } void TestLogLevelsComp::logDummyMessages (const ::contLogTest::LongSeq & levels) { ACE_Log_Priority p; CORBA::ULong t=0; for (t=0; t<levels.length(); t++){ p = LogLevelDefinition::getACELogPriority(levels[t]); LogLevelDefinition lld = LogLevelDefinition::fromInteger(levels[t]); ACS_SHORT_LOG((p, "dummy log message for core level %d/%s", lld.getValue(), lld.getName().c_str())); } ACS_SHORT_LOG((p, "===last log messsage===", levels[t])); } /* --------------- [ MACI DLL support functions ] -----------------*/ #include <maciACSComponentDefines.h> MACI_DLL_SUPPORT_FUNCTIONS(TestLogLevelsComp) /* ----------------------------------------------------------------*/ /*___oOo___*/ <commit_msg>In method logDummyMessages(), log last message always at highest non-OFF level (so it always gets through, unless the central log level is put to OFF).<commit_after>/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) Associated Universities Inc., 2002 * * (c) European Southern Observatory, 2002 * Copyright by ESO (in the framework of the ALMA collaboration) * and Cosylab 2002, All rights reserved * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * * * "@(#) $Id: contLogTestImpl.cpp,v 1.8 2008/01/09 10:11:38 eallaert Exp $" * * who when what * -------- ---------- ---------------------------------------------- * eallaert 2007-11-05 initial version * */ #include <contLogTestImpl.h> #include <ACSErrTypeCommon.h> #include <loggingLogLevelDefinition.h> #include <loggingLogger.h> #include "loggingGetLogger.h" #include <iostream> ACE_RCSID(contLogTest, contLogTestImpl, "$Id: contLogTestImpl.cpp,v 1.8 2008/01/09 10:11:38 eallaert Exp $") /* ----------------------------------------------------------------*/ TestLogLevelsComp::TestLogLevelsComp( const ACE_CString &name, maci::ContainerServices * containerServices) : ACSComponentImpl(name, containerServices) { // ACS_TRACE is used for debugging purposes ACS_TRACE("::TestLogLevelsComp::TestLogLevelsComp"); } /* ----------------------------------------------------------------*/ TestLogLevelsComp::~TestLogLevelsComp() { // ACS_TRACE is used for debugging purposes ACS_TRACE("::TestLogLevelsComp::~TestLogLevelsComp"); ACS_DEBUG_PARAM("::TestLogLevelsComp::~TestLogLevelsComp", "Destroying %s...", name()); } /* --------------------- [ CORBA interface ] ----------------------*/ ::contLogTest::LongSeq* TestLogLevelsComp::getLevels () throw (CORBA::SystemException, ACSErrTypeCommon::CouldntPerformActionEx) { Logging::Logger *l = getLogger(); ::contLogTest::LongSeq_var level = new ::contLogTest::LongSeq(5); level->length(5); // need the equivalent of Java's logConfig.getMinLogLevel() etc. in C++ for (int i = 0; i <5 ; i++) level[i] = static_cast< CORBA::Long >(i); level[3] = static_cast< CORBA::Long >(l->getRemoteLevel()); level[4] = static_cast< CORBA::Long >(l->getLocalLevel()); return level._retn(); } void TestLogLevelsComp::logDummyMessages (const ::contLogTest::LongSeq & levels) { ACE_Log_Priority p; CORBA::ULong t=0; for (t=0; t<levels.length(); t++){ p = LogLevelDefinition::getACELogPriority(levels[t]); LogLevelDefinition lld = LogLevelDefinition::fromInteger(levels[t]); ACS_SHORT_LOG((p, "dummy log message for core level %d/%s", lld.getValue(), lld.getName().c_str())); } // log last message always at highest, non-OFF level (so it should get always through, // unless the central level is put to OFF). p = LogLevelDefinition::getACELogPriority(levels[levels.length()-2]); ACS_SHORT_LOG((p, "===last log messsage===")); } /* --------------- [ MACI DLL support functions ] -----------------*/ #include <maciACSComponentDefines.h> MACI_DLL_SUPPORT_FUNCTIONS(TestLogLevelsComp) /* ----------------------------------------------------------------*/ /*___oOo___*/ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: FieldControls.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: oj $ $Date: 2001-03-14 10:35:10 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an AS IS basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef DBAUI_FIELDCONTROLS_HXX #define DBAUI_FIELDCONTROLS_HXX #ifndef _SV_FIELD_HXX #include <vcl/field.hxx> #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef DBAUI_SQLNAMEEDIT_HXX #include "SqlNameEdit.hxx" #endif namespace dbaui { class OSpecialReadOnly { protected: void SetSpecialReadOnly(BOOL _bReadOnly,Window *pWin) { StyleSettings aSystemStyle = Application::GetSettings().GetStyleSettings(); const Color& rNewColor = _bReadOnly ? aSystemStyle.GetDialogColor() : aSystemStyle.GetFieldColor(); pWin->SetBackground(Wallpaper(rNewColor)); pWin->SetControlBackground(rNewColor); } public: virtual void SetSpecialReadOnly(BOOL _bReadOnly) = 0; }; //================================================================== class OPropColumnEditCtrl : public OSQLNameEdit ,public OSpecialReadOnly { short m_nPos; String m_strHelpText; public: inline OPropColumnEditCtrl(Window* pParent, ::rtl::OUString& _rAllowedChars, INT32 nHelpId, short nPosition = -1, WinBits nWinStyle = 0); inline BOOL IsModified() { return GetText() != GetSavedValue(); } short GetPos() const { return m_nPos; } String GetHelp() const { return m_strHelpText; } virtual void SetSpecialReadOnly(BOOL _bReadOnly) { SetReadOnly(_bReadOnly); OSpecialReadOnly::SetSpecialReadOnly(_bReadOnly,this); } }; inline OPropColumnEditCtrl::OPropColumnEditCtrl(Window* pParent, ::rtl::OUString& _rAllowedChars, INT32 nHelpId, short nPosition, WinBits nWinStyle) :OSQLNameEdit(pParent, _rAllowedChars,nWinStyle) ,m_nPos(nPosition) { m_strHelpText = String(ModuleRes(nHelpId)); } //================================================================== class OPropEditCtrl : public Edit ,public OSpecialReadOnly { short m_nPos; String m_strHelpText; public: inline OPropEditCtrl(Window* pParent, INT32 nHelpId, short nPosition = -1, WinBits nWinStyle = 0); inline BOOL IsModified() { return GetText() != GetSavedValue(); } short GetPos() const { return m_nPos; } String GetHelp() const { return m_strHelpText; } virtual void SetSpecialReadOnly(BOOL _bReadOnly) { SetReadOnly(_bReadOnly); OSpecialReadOnly::SetSpecialReadOnly(_bReadOnly,this); } }; inline OPropEditCtrl::OPropEditCtrl(Window* pParent, INT32 nHelpId, short nPosition, WinBits nWinStyle) :Edit(pParent, nWinStyle) ,m_nPos(nPosition) { m_strHelpText = String(ModuleRes(nHelpId)); } //================================================================== class OPropNumericEditCtrl : public NumericField ,public OSpecialReadOnly { short m_nPos; String m_strHelpText; public: inline OPropNumericEditCtrl(Window* pParent, INT32 nHelpId, short nPosition = -1, WinBits nWinStyle = 0); inline BOOL IsModified() { return GetText() != GetSavedValue(); } short GetPos() const { return m_nPos; } String GetHelp() const { return m_strHelpText; } virtual void SetSpecialReadOnly(BOOL _bReadOnly) { SetReadOnly(_bReadOnly); OSpecialReadOnly::SetSpecialReadOnly(_bReadOnly,this); } }; inline OPropNumericEditCtrl::OPropNumericEditCtrl(Window* pParent, INT32 nHelpId, short nPosition, WinBits nWinStyle) :NumericField(pParent, nWinStyle) ,m_nPos(nPosition) { m_strHelpText = String(ModuleRes(nHelpId)); } //================================================================== class OPropListBoxCtrl : public ListBox ,public OSpecialReadOnly { short m_nPos; String m_strHelpText; public: inline OPropListBoxCtrl(Window* pParent, INT32 nHelpId, short nPosition = -1, WinBits nWinStyle = 0); inline BOOL IsModified() { return GetSelectEntryPos() != GetSavedValue(); } short GetPos() const { return m_nPos; } String GetHelp() const { return m_strHelpText; } virtual void SetSpecialReadOnly(BOOL _bReadOnly) { SetReadOnly(_bReadOnly); OSpecialReadOnly::SetSpecialReadOnly(_bReadOnly,this); } }; inline OPropListBoxCtrl::OPropListBoxCtrl(Window* pParent, INT32 nHelpId, short nPosition, WinBits nWinStyle) :ListBox(pParent, nWinStyle) ,m_nPos(nPosition) { m_strHelpText = String(ModuleRes(nHelpId)); } } #endif // DBAUI_FIELDCONTROLS_HXX <commit_msg>use USHORT instead of INT32<commit_after>/************************************************************************* * * $RCSfile: FieldControls.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: oj $ $Date: 2001-03-19 12:40:59 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an AS IS basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef DBAUI_FIELDCONTROLS_HXX #define DBAUI_FIELDCONTROLS_HXX #ifndef _SV_FIELD_HXX #include <vcl/field.hxx> #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef DBAUI_SQLNAMEEDIT_HXX #include "SqlNameEdit.hxx" #endif namespace dbaui { class OSpecialReadOnly { protected: void SetSpecialReadOnly(BOOL _bReadOnly,Window *pWin) { StyleSettings aSystemStyle = Application::GetSettings().GetStyleSettings(); const Color& rNewColor = _bReadOnly ? aSystemStyle.GetDialogColor() : aSystemStyle.GetFieldColor(); pWin->SetBackground(Wallpaper(rNewColor)); pWin->SetControlBackground(rNewColor); } public: virtual void SetSpecialReadOnly(BOOL _bReadOnly) = 0; }; //================================================================== class OPropColumnEditCtrl : public OSQLNameEdit ,public OSpecialReadOnly { short m_nPos; String m_strHelpText; public: inline OPropColumnEditCtrl(Window* pParent, ::rtl::OUString& _rAllowedChars, USHORT nHelpId, short nPosition = -1, WinBits nWinStyle = 0); inline BOOL IsModified() { return GetText() != GetSavedValue(); } short GetPos() const { return m_nPos; } String GetHelp() const { return m_strHelpText; } virtual void SetSpecialReadOnly(BOOL _bReadOnly) { SetReadOnly(_bReadOnly); OSpecialReadOnly::SetSpecialReadOnly(_bReadOnly,this); } }; inline OPropColumnEditCtrl::OPropColumnEditCtrl(Window* pParent, ::rtl::OUString& _rAllowedChars, USHORT nHelpId, short nPosition, WinBits nWinStyle) :OSQLNameEdit(pParent, _rAllowedChars,nWinStyle) ,m_nPos(nPosition) { m_strHelpText = String(ModuleRes(nHelpId)); } //================================================================== class OPropEditCtrl : public Edit ,public OSpecialReadOnly { short m_nPos; String m_strHelpText; public: inline OPropEditCtrl(Window* pParent, USHORT nHelpId, short nPosition = -1, WinBits nWinStyle = 0); inline OPropEditCtrl(Window* pParent, USHORT nHelpId, const ResId& _rRes,short nPosition = -1); inline BOOL IsModified() { return GetText() != GetSavedValue(); } short GetPos() const { return m_nPos; } String GetHelp() const { return m_strHelpText; } virtual void SetSpecialReadOnly(BOOL _bReadOnly) { SetReadOnly(_bReadOnly); OSpecialReadOnly::SetSpecialReadOnly(_bReadOnly,this); } }; inline OPropEditCtrl::OPropEditCtrl(Window* pParent, USHORT nHelpId, short nPosition, WinBits nWinStyle) :Edit(pParent, nWinStyle) ,m_nPos(nPosition) { m_strHelpText = String(ModuleRes(nHelpId)); } inline OPropEditCtrl::OPropEditCtrl(Window* pParent, USHORT nHelpId, const ResId& _rRes,short nPosition) :Edit(pParent, _rRes) ,m_nPos(nPosition) { m_strHelpText = String(ModuleRes(nHelpId)); } //================================================================== class OPropNumericEditCtrl : public NumericField ,public OSpecialReadOnly { short m_nPos; String m_strHelpText; public: inline OPropNumericEditCtrl(Window* pParent, USHORT nHelpId, short nPosition = -1, WinBits nWinStyle = 0); inline OPropNumericEditCtrl(Window* pParent, USHORT nHelpId, const ResId& _rRes,short nPosition = -1); inline BOOL IsModified() { return GetText() != GetSavedValue(); } short GetPos() const { return m_nPos; } String GetHelp() const { return m_strHelpText; } virtual void SetSpecialReadOnly(BOOL _bReadOnly) { SetReadOnly(_bReadOnly); OSpecialReadOnly::SetSpecialReadOnly(_bReadOnly,this); } }; inline OPropNumericEditCtrl::OPropNumericEditCtrl(Window* pParent, USHORT nHelpId, short nPosition, WinBits nWinStyle) :NumericField(pParent, nWinStyle) ,m_nPos(nPosition) { m_strHelpText = String(ModuleRes(nHelpId)); } inline OPropNumericEditCtrl::OPropNumericEditCtrl(Window* pParent, USHORT nHelpId, const ResId& _rRes,short nPosition) :NumericField(pParent, _rRes) ,m_nPos(nPosition) { m_strHelpText = String(ModuleRes(nHelpId)); } //================================================================== class OPropListBoxCtrl : public ListBox ,public OSpecialReadOnly { short m_nPos; String m_strHelpText; public: inline OPropListBoxCtrl(Window* pParent, USHORT nHelpId, short nPosition = -1, WinBits nWinStyle = 0); inline OPropListBoxCtrl(Window* pParent, USHORT nHelpId, const ResId& _rRes,short nPosition = -1); inline BOOL IsModified() { return GetSelectEntryPos() != GetSavedValue(); } short GetPos() const { return m_nPos; } String GetHelp() const { return m_strHelpText; } virtual void SetSpecialReadOnly(BOOL _bReadOnly) { SetReadOnly(_bReadOnly); OSpecialReadOnly::SetSpecialReadOnly(_bReadOnly,this); } }; inline OPropListBoxCtrl::OPropListBoxCtrl(Window* pParent, USHORT nHelpId, short nPosition, WinBits nWinStyle) :ListBox(pParent, nWinStyle) ,m_nPos(nPosition) { m_strHelpText = String(ModuleRes(nHelpId)); } inline OPropListBoxCtrl::OPropListBoxCtrl(Window* pParent, USHORT nHelpId, const ResId& _rRes,short nPosition) :ListBox(pParent, _rRes) ,m_nPos(nPosition) { m_strHelpText = String(ModuleRes(nHelpId)); } } #endif // DBAUI_FIELDCONTROLS_HXX <|endoftext|>
<commit_before>//---------------------------- thread_management.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2000, 2001, 2002, 2003 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- thread_management.cc --------------------------- #include <base/thread_management.h> #include <iostream> #ifdef DEAL_II_USE_MT_POSIX # include <list> #endif #ifndef DEAL_II_USE_DIRECT_ERRNO_H # include <errno.h> #else # include </usr/include/errno.h> #endif #include <sys/errno.h> namespace Threads { // counter and access mutex for the // number of threads volatile unsigned int n_existing_threads_counter = 1; ThreadMutex n_existing_threads_mutex; void register_new_thread () { n_existing_threads_mutex.acquire (); ++n_existing_threads_counter; n_existing_threads_mutex.release (); } void deregister_new_thread () { n_existing_threads_mutex.acquire (); --n_existing_threads_counter; Assert (n_existing_threads_counter >= 1, ExcInternalError()); n_existing_threads_mutex.release (); } void handle_std_exception (const std::exception &exc) { std::cerr << std::endl << std::endl << "---------------------------------------------------------" << std::endl << "In one of the sub-threads of this program, an exception\n" << "was thrown and not caught. Since exceptions do not\n" << "propagate to the main thread, the library has caught it.\n" << "The information carried by this exception is given below.\n" << std::endl << "---------------------------------------------------------" << std::endl; std::cerr << "Exception on processing: " << std::endl << exc.what() << std::endl << "Aborting!" << std::endl << "---------------------------------------------------------" << std::endl; std::abort (); } void handle_unknown_exception () { std::cerr << std::endl << std::endl << "---------------------------------------------------------" << std::endl << "In one of the sub-threads of this program, an exception\n" << "was thrown and not caught. Since exceptions do not\n" << "propagate to the main thread, the library has caught it.\n" << "The information carried by this exception is given below.\n" << std::endl << "---------------------------------------------------------" << std::endl; std::cerr << "Type of exception is unknown, but not std::exception.\n" << "No additional information is available.\n" << "---------------------------------------------------------" << std::endl; std::abort (); } unsigned int n_existing_threads () { n_existing_threads_mutex.acquire (); const unsigned int n = n_existing_threads_counter; n_existing_threads_mutex.release (); return n; } #if DEAL_II_USE_MT != 1 void DummyThreadManager::spawn (const FunPtr fun_ptr, void * fun_data, int /*flags*/) const { (*fun_ptr) (fun_data); } DummyBarrier::DummyBarrier (const unsigned int count, const char *, void *) { Assert (count == 1, ExcBarrierSizeNotUseful(count)); } #else # ifdef DEAL_II_USE_MT_POSIX PosixThreadMutex::PosixThreadMutex () { pthread_mutex_init (&mutex, 0); } PosixThreadMutex::~PosixThreadMutex () { pthread_mutex_destroy (&mutex); } PosixThreadCondition::PosixThreadCondition () { pthread_cond_init (&cond, 0); } PosixThreadCondition::~PosixThreadCondition () { pthread_cond_destroy (&cond); } #ifndef DEAL_II_USE_MT_POSIX_NO_BARRIERS PosixThreadBarrier::PosixThreadBarrier (const unsigned int count, const char *, void *) { pthread_barrier_init (&barrier, 0, count); } #else PosixThreadBarrier::PosixThreadBarrier (const unsigned int count, const char *, void *) : count (count) { // throw an exception unless we // have the special case that a // count of 1 is given, since // then waiting for a barrier is // a no-op, and we don't need the // POSIX functionality AssertThrow (count == 1, ExcMessage ("Your local POSIX installation does not support\n" "POSIX barriers. You will not be able to use\n" "this class, but the rest of the threading\n" "functionality is available.")); } #endif PosixThreadBarrier::~PosixThreadBarrier () { #ifndef DEAL_II_USE_MT_POSIX_NO_BARRIERS pthread_barrier_destroy (&barrier); #else // unless the barrier is a no-op, // complain again (how did we get // here then?) if (count != 1) std::abort (); #endif } int PosixThreadBarrier::wait () { #ifndef DEAL_II_USE_MT_POSIX_NO_BARRIERS return pthread_barrier_wait (&barrier); #else // in the special case, this // function is a no-op. otherwise // complain about the missing // POSIX functions if (count == 1) return 0; else { std::abort (); return 1; }; #endif } PosixThreadManager::PosixThreadManager () : thread_id_list (new std::list<pthread_t>()) {} PosixThreadManager::~PosixThreadManager () { // wait for all threads, and // release memory wait (); list_mutex.acquire (); if (thread_id_list != 0) delete reinterpret_cast<std::list<pthread_t>*>(thread_id_list); thread_id_list = 0; list_mutex.release (); } void PosixThreadManager::spawn (const FunPtr fun_ptr, void * fun_data, int) { std::list<pthread_t> &tid_list = *reinterpret_cast<std::list<pthread_t>*>(thread_id_list); list_mutex.acquire (); tid_list.push_back (pthread_t()); pthread_t *tid = &tid_list.back(); list_mutex.release (); // start new thread. retry until // we either succeed or get an // error other than EAGAIN int error = 0; do { error = pthread_create (tid, 0, fun_ptr, fun_data); } while (error == EAGAIN); AssertThrow (error == 0, ExcInternalError()); } void PosixThreadManager::wait () const { list_mutex.acquire (); std::list<pthread_t> &tid_list = *reinterpret_cast<std::list<pthread_t>*>(thread_id_list); // wait for all the threads in // turn for (std::list<pthread_t>::iterator i=tid_list.begin(); i != tid_list.end(); ++i) pthread_join (*i, 0); // now we know that these threads // have finished, remove their // tid's from the list. this way, // when new threads are spawned // and waited for, we won't wait // for expired threads with their // invalid handles again tid_list.clear (); list_mutex.release (); } # endif #endif FunDataCounter::FunDataCounter () : n_fun_encapsulation_objects (0), n_fun_data_base_objects (0) {} FunDataCounter::~FunDataCounter () { AssertThrow (n_fun_encapsulation_objects == 0, ExcObjectsExist("FunEncapsulation", n_fun_encapsulation_objects)); AssertThrow (n_fun_data_base_objects == 0, ExcObjectsExist("FunDataBase", n_fun_data_base_objects)); } /** * This is the global object which we will use to count the number of * threads generated, and which is used to complain when there is a * memory leak. */ FunDataCounter fun_data_counter; FunEncapsulation::FunEncapsulation () : fun_data_base (0) { // keep some statistics on the // number of variables around ++fun_data_counter.n_fun_encapsulation_objects; } FunEncapsulation::FunEncapsulation (FunDataBase *fun_data_base) : fun_data_base (fun_data_base) { // keep some statistics on the // number of variables around ++fun_data_counter.n_fun_encapsulation_objects; } FunEncapsulation::FunEncapsulation (const FunEncapsulation &fun_data) : fun_data_base (fun_data.fun_data_base->clone ()) { // keep some statistics on the // number of variables around ++fun_data_counter.n_fun_encapsulation_objects; } FunEncapsulation::~FunEncapsulation () { // note that the spawn() function // makes sure that we only get // here if the data has already // been copied by the spawned // thread, so destruction is safe // here. // // so do so. delete fun_data_base; fun_data_base = 0; // keep some statistics on the // number of variables around --fun_data_counter.n_fun_encapsulation_objects; } const FunEncapsulation & FunEncapsulation::operator = (const FunEncapsulation &/*fun_data*/) { // this is not implemented at // present. return dummy value // instead Assert (false, ExcNotImplemented()); const FunEncapsulation * const p = 0; return *p; } FunDataBase::FunDataBase (const ThreadEntryPoint thread_entry_point) : thread_entry_point (thread_entry_point) { // keep some statistics on the // number of variables around ++fun_data_counter.n_fun_data_base_objects; } FunDataBase::FunDataBase (const FunDataBase &fun_data_base) : thread_entry_point (fun_data_base.thread_entry_point) { // keep some statistics on the // number of variables around ++fun_data_counter.n_fun_data_base_objects; } FunDataBase::~FunDataBase () { // invalidate pointer for security // reasons. accesses to this // pointer after lifetime of this // object will then fail thread_entry_point = 0; // keep some statistics on the // number of variables around --fun_data_counter.n_fun_data_base_objects; } void spawn (ThreadManager &thread_manager, const FunEncapsulation &fun_data) { // lock the @p{fun_data_base} object // to avoid destruction while its // data is still accessed. the lock // is released by the new thread // once it has copied all data fun_data.fun_data_base->lock.acquire (); // now start the new thread #if DEAL_II_USE_MT == 1 # if defined(DEAL_II_USE_MT_POSIX) thread_manager.spawn (*fun_data.fun_data_base->thread_entry_point, (void*)&fun_data, 0); # else # error Not implemented # endif #else // if not in MT mode, then simply // call the respective // serializing function, that // executes the given function // and return thread_manager.spawn (*fun_data.fun_data_base->thread_entry_point, (void*)&fun_data, 0); #endif // unlock the mutex and wait for // the condition that the data // has been copied to be // signalled. unlocking the mutex // will allow the other thread to // proceed to the signal() call, // which we want to catch here // // the mutex will subsequently be // locked again, but since we // don't need it any more, we can // go on unlocking it immediately // again fun_data.fun_data_base->condition.wait(fun_data.fun_data_base->lock); fun_data.fun_data_base->lock.release (); } void spawn_n (ThreadManager &thread_manager, const FunEncapsulation &fun_data, const unsigned int n_threads) { for (unsigned int i=0; i<n_threads; ++i) spawn (thread_manager, fun_data); } std::vector<std::pair<unsigned int,unsigned int> > split_interval (const unsigned int begin, const unsigned int end, const unsigned int n_intervals) { Assert (end >= begin, ExcInternalError()); const unsigned int n_elements = end-begin; const unsigned int n_elements_per_interval = n_elements / n_intervals; const unsigned int residual = n_elements % n_intervals; std::vector<std::pair<unsigned int,unsigned int> > return_values (n_intervals); return_values[0].first = begin; for (unsigned int i=0; i<n_intervals; ++i) { if (i != n_intervals-1) { return_values[i].second = (return_values[i].first + n_elements_per_interval); // distribute residual in // division equally among // the first few // subintervals if (i < residual) ++return_values[i].second; return_values[i+1].first = return_values[i].second; } else return_values[i].second = end; }; return return_values; } } // end namespace Thread <commit_msg>Fix one problem.<commit_after>//---------------------------- thread_management.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2000, 2001, 2002, 2003 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- thread_management.cc --------------------------- #include <base/thread_management.h> #include <iostream> #ifdef DEAL_II_USE_MT_POSIX # include <list> #endif #ifndef DEAL_II_USE_DIRECT_ERRNO_H # include <errno.h> #else # include </usr/include/errno.h> #endif #include <sys/errno.h> namespace Threads { // counter and access mutex for the // number of threads volatile unsigned int n_existing_threads_counter = 1; ThreadMutex n_existing_threads_mutex; void register_new_thread () { n_existing_threads_mutex.acquire (); ++n_existing_threads_counter; n_existing_threads_mutex.release (); } void deregister_new_thread () { n_existing_threads_mutex.acquire (); --n_existing_threads_counter; Assert (n_existing_threads_counter >= 1, ExcInternalError()); n_existing_threads_mutex.release (); } void handle_std_exception (const std::exception &exc) { std::cerr << std::endl << std::endl << "---------------------------------------------------------" << std::endl << "In one of the sub-threads of this program, an exception\n" << "was thrown and not caught. Since exceptions do not\n" << "propagate to the main thread, the library has caught it.\n" << "The information carried by this exception is given below.\n" << std::endl << "---------------------------------------------------------" << std::endl; std::cerr << "Exception on processing: " << std::endl << exc.what() << std::endl << "Aborting!" << std::endl << "---------------------------------------------------------" << std::endl; std::abort (); } void handle_unknown_exception () { std::cerr << std::endl << std::endl << "---------------------------------------------------------" << std::endl << "In one of the sub-threads of this program, an exception\n" << "was thrown and not caught. Since exceptions do not\n" << "propagate to the main thread, the library has caught it.\n" << "The information carried by this exception is given below.\n" << std::endl << "---------------------------------------------------------" << std::endl; std::cerr << "Type of exception is unknown, but not std::exception.\n" << "No additional information is available.\n" << "---------------------------------------------------------" << std::endl; std::abort (); } unsigned int n_existing_threads () { n_existing_threads_mutex.acquire (); const unsigned int n = n_existing_threads_counter; n_existing_threads_mutex.release (); return n; } #if DEAL_II_USE_MT != 1 void DummyThreadManager::spawn (const FunPtr fun_ptr, void * fun_data, int /*flags*/) const { (*fun_ptr) (fun_data); } DummyBarrier::DummyBarrier (const unsigned int count, const char *, void *) { Assert (count == 1, ExcBarrierSizeNotUseful(count)); } #else # ifdef DEAL_II_USE_MT_POSIX PosixThreadMutex::PosixThreadMutex () { pthread_mutex_init (&mutex, 0); } PosixThreadMutex::~PosixThreadMutex () { pthread_mutex_destroy (&mutex); } PosixThreadCondition::PosixThreadCondition () { pthread_cond_init (&cond, 0); } PosixThreadCondition::~PosixThreadCondition () { pthread_cond_destroy (&cond); } #ifndef DEAL_II_USE_MT_POSIX_NO_BARRIERS PosixThreadBarrier::PosixThreadBarrier (const unsigned int count, const char *, void *) { pthread_barrier_init (&barrier, 0, count); } #else PosixThreadBarrier::PosixThreadBarrier (const unsigned int count, const char *, void *) : count (count) { // throw an exception unless we // have the special case that a // count of 1 is given, since // then waiting for a barrier is // a no-op, and we don't need the // POSIX functionality AssertThrow (count == 1, ExcMessage ("Your local POSIX installation does not support\n" "POSIX barriers. You will not be able to use\n" "this class, but the rest of the threading\n" "functionality is available.")); } #endif PosixThreadBarrier::~PosixThreadBarrier () { #ifndef DEAL_II_USE_MT_POSIX_NO_BARRIERS pthread_barrier_destroy (&barrier); #else // unless the barrier is a no-op, // complain again (how did we get // here then?) if (count != 1) std::abort (); #endif } int PosixThreadBarrier::wait () { #ifndef DEAL_II_USE_MT_POSIX_NO_BARRIERS return pthread_barrier_wait (&barrier); #else // in the special case, this // function is a no-op. otherwise // complain about the missing // POSIX functions if (count == 1) return 0; else { std::abort (); return 1; }; #endif } PosixThreadManager::PosixThreadManager () : thread_id_list (new std::list<pthread_t>()) {} PosixThreadManager::~PosixThreadManager () { // wait for all threads, and // release memory wait (); list_mutex.acquire (); if (thread_id_list != 0) delete reinterpret_cast<std::list<pthread_t>*>(thread_id_list); list_mutex.release (); } void PosixThreadManager::spawn (const FunPtr fun_ptr, void * fun_data, int) { std::list<pthread_t> &tid_list = *reinterpret_cast<std::list<pthread_t>*>(thread_id_list); list_mutex.acquire (); tid_list.push_back (pthread_t()); pthread_t *tid = &tid_list.back(); list_mutex.release (); // start new thread. retry until // we either succeed or get an // error other than EAGAIN int error = 0; do { error = pthread_create (tid, 0, fun_ptr, fun_data); } while (error == EAGAIN); AssertThrow (error == 0, ExcInternalError()); } void PosixThreadManager::wait () const { list_mutex.acquire (); std::list<pthread_t> &tid_list = *reinterpret_cast<std::list<pthread_t>*>(thread_id_list); // wait for all the threads in // turn for (std::list<pthread_t>::iterator i=tid_list.begin(); i != tid_list.end(); ++i) pthread_join (*i, 0); // now we know that these threads // have finished, remove their // tid's from the list. this way, // when new threads are spawned // and waited for, we won't wait // for expired threads with their // invalid handles again tid_list.clear (); list_mutex.release (); } # endif #endif FunDataCounter::FunDataCounter () : n_fun_encapsulation_objects (0), n_fun_data_base_objects (0) {} FunDataCounter::~FunDataCounter () { AssertThrow (n_fun_encapsulation_objects == 0, ExcObjectsExist("FunEncapsulation", n_fun_encapsulation_objects)); AssertThrow (n_fun_data_base_objects == 0, ExcObjectsExist("FunDataBase", n_fun_data_base_objects)); } /** * This is the global object which we will use to count the number of * threads generated, and which is used to complain when there is a * memory leak. */ FunDataCounter fun_data_counter; FunEncapsulation::FunEncapsulation () : fun_data_base (0) { // keep some statistics on the // number of variables around ++fun_data_counter.n_fun_encapsulation_objects; } FunEncapsulation::FunEncapsulation (FunDataBase *fun_data_base) : fun_data_base (fun_data_base) { // keep some statistics on the // number of variables around ++fun_data_counter.n_fun_encapsulation_objects; } FunEncapsulation::FunEncapsulation (const FunEncapsulation &fun_data) : fun_data_base (fun_data.fun_data_base->clone ()) { // keep some statistics on the // number of variables around ++fun_data_counter.n_fun_encapsulation_objects; } FunEncapsulation::~FunEncapsulation () { // note that the spawn() function // makes sure that we only get // here if the data has already // been copied by the spawned // thread, so destruction is safe // here. // // so do so. delete fun_data_base; fun_data_base = 0; // keep some statistics on the // number of variables around --fun_data_counter.n_fun_encapsulation_objects; } const FunEncapsulation & FunEncapsulation::operator = (const FunEncapsulation &/*fun_data*/) { // this is not implemented at // present. return dummy value // instead Assert (false, ExcNotImplemented()); const FunEncapsulation * const p = 0; return *p; } FunDataBase::FunDataBase (const ThreadEntryPoint thread_entry_point) : thread_entry_point (thread_entry_point) { // keep some statistics on the // number of variables around ++fun_data_counter.n_fun_data_base_objects; } FunDataBase::FunDataBase (const FunDataBase &fun_data_base) : thread_entry_point (fun_data_base.thread_entry_point) { // keep some statistics on the // number of variables around ++fun_data_counter.n_fun_data_base_objects; } FunDataBase::~FunDataBase () { // invalidate pointer for security // reasons. accesses to this // pointer after lifetime of this // object will then fail thread_entry_point = 0; // keep some statistics on the // number of variables around --fun_data_counter.n_fun_data_base_objects; } void spawn (ThreadManager &thread_manager, const FunEncapsulation &fun_data) { // lock the @p{fun_data_base} object // to avoid destruction while its // data is still accessed. the lock // is released by the new thread // once it has copied all data fun_data.fun_data_base->lock.acquire (); // now start the new thread #if DEAL_II_USE_MT == 1 # if defined(DEAL_II_USE_MT_POSIX) thread_manager.spawn (*fun_data.fun_data_base->thread_entry_point, (void*)&fun_data, 0); # else # error Not implemented # endif #else // if not in MT mode, then simply // call the respective // serializing function, that // executes the given function // and return thread_manager.spawn (*fun_data.fun_data_base->thread_entry_point, (void*)&fun_data, 0); #endif // unlock the mutex and wait for // the condition that the data // has been copied to be // signalled. unlocking the mutex // will allow the other thread to // proceed to the signal() call, // which we want to catch here // // the mutex will subsequently be // locked again, but since we // don't need it any more, we can // go on unlocking it immediately // again fun_data.fun_data_base->condition.wait(fun_data.fun_data_base->lock); fun_data.fun_data_base->lock.release (); } void spawn_n (ThreadManager &thread_manager, const FunEncapsulation &fun_data, const unsigned int n_threads) { for (unsigned int i=0; i<n_threads; ++i) spawn (thread_manager, fun_data); } std::vector<std::pair<unsigned int,unsigned int> > split_interval (const unsigned int begin, const unsigned int end, const unsigned int n_intervals) { Assert (end >= begin, ExcInternalError()); const unsigned int n_elements = end-begin; const unsigned int n_elements_per_interval = n_elements / n_intervals; const unsigned int residual = n_elements % n_intervals; std::vector<std::pair<unsigned int,unsigned int> > return_values (n_intervals); return_values[0].first = begin; for (unsigned int i=0; i<n_intervals; ++i) { if (i != n_intervals-1) { return_values[i].second = (return_values[i].first + n_elements_per_interval); // distribute residual in // division equally among // the first few // subintervals if (i < residual) ++return_values[i].second; return_values[i+1].first = return_values[i].second; } else return_values[i].second = end; }; return return_values; } } // end namespace Thread <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Blueberry #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> #include <berryWorkbenchPlugin.h> #include <berryIQtStyleManager.h> // Qmitk #include "ChartExample.h" // Qt #include <QMessageBox> #include <QRandomGenerator> // mitk image #include <mitkImage.h> const std::string ChartExample::VIEW_ID = "org.mitk.views.chartexample"; void ChartExample::SetFocus() { m_Controls.m_buttonCreateChart->setFocus(); } void ChartExample::CreateQtPartControl(QWidget *parent) { // create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi(parent); connect(m_Controls.m_buttonCreateChart, &QPushButton::clicked, this, &ChartExample::CreateChart); connect(m_Controls.m_buttonClearChart, &QPushButton::clicked, this, &ChartExample::ClearChart); connect(m_Controls.m_buttonAddData, &QPushButton::clicked, this, &ChartExample::AddData); FillRandomDataValues(); m_Controls.m_Chart->SetTheme(GetColorTheme()); m_Controls.m_lineEditXAxisLabel->setText("xLabel"); m_Controls.m_lineEditYAxisLabel->setText("yLabel"); m_chartNameToChartType.emplace("bar", QmitkChartWidget::ChartType::bar); m_chartNameToChartType.emplace("line", QmitkChartWidget::ChartType::line); m_chartNameToChartType.emplace("spline", QmitkChartWidget::ChartType::spline); m_chartNameToChartType.emplace("pie", QmitkChartWidget::ChartType::pie); m_chartNameToChartType.emplace("area", QmitkChartWidget::ChartType::area); m_chartNameToChartType.emplace("area-spline", QmitkChartWidget::ChartType::area_spline); m_chartNameToChartType.emplace("scatter", QmitkChartWidget::ChartType::scatter); m_LineNameToLineType.emplace("solid", QmitkChartWidget::LineStyle::solid); m_LineNameToLineType.emplace("dashed", QmitkChartWidget::LineStyle::dashed); m_AxisScaleNameToAxisScaleType.emplace("linear", QmitkChartWidget::AxisScale::linear); m_AxisScaleNameToAxisScaleType.emplace("logarithmic", QmitkChartWidget::AxisScale::log); } void ChartExample::FillRandomDataValues() { std::vector<double> numbers = generateRandomNumbers(10, 10.0); std::string text = convertToText(numbers, ";"); m_Controls.m_lineEditDataVector->setText(QString::fromStdString(text)); m_Controls.m_lineEditDataLabel->setText("test" + QString::number(countForUID)); countForUID++; } void ChartExample::CreateChart() { auto dataYAxisScaleType = m_AxisScaleNameToAxisScaleType.at(m_Controls.m_comboBoxYAxisScale->currentText().toStdString()); auto xAxisLabel = m_Controls.m_lineEditXAxisLabel->text().toStdString(); auto yAxisLabel = m_Controls.m_lineEditYAxisLabel->text().toStdString(); auto showLegend = m_Controls.m_checkBoxShowLegend->isChecked(); auto showDataPoints = m_Controls.m_checkBoxShowDataPoints->isChecked(); auto stackedData = m_Controls.m_checkBoxStackedData->isChecked(); auto showSubchart = m_Controls.m_checkBoxShowSubchart->isChecked(); m_Controls.m_Chart->SetYAxisScale(dataYAxisScaleType); m_Controls.m_Chart->SetXAxisLabel(xAxisLabel); m_Controls.m_Chart->SetYAxisLabel(yAxisLabel); m_Controls.m_Chart->SetShowLegend(showLegend); m_Controls.m_Chart->SetShowDataPoints(showDataPoints); m_Controls.m_Chart->SetStackedData(stackedData); m_Controls.m_Chart->Show(showSubchart); } void ChartExample::ClearChart() { m_Controls.m_Chart->Clear(); m_Controls.m_plainTextEditDataView->clear(); } void ChartExample::AddData() { auto lineEditData = m_Controls.m_lineEditDataVector->text(); std::vector<double> data; for(const QString entry : lineEditData.split(';')) { data.push_back(entry.toDouble()); } auto chartType = m_chartNameToChartType.at(m_Controls.m_comboBoxChartType->currentText().toStdString()); std::string dataLabel = m_Controls.m_lineEditDataLabel->text().toStdString(); std::string dataColor = m_Controls.m_lineEditColor->text().toStdString(); auto dataLineStyleType = m_LineNameToLineType.at(m_Controls.m_comboBoxLineStyle->currentText().toStdString()); m_Controls.m_Chart->AddData1D(data, dataLabel, chartType); if (!dataColor.empty()) { m_Controls.m_Chart->SetColor(dataLabel, dataColor); } m_Controls.m_Chart->SetLineStyle(dataLabel, dataLineStyleType); QString dataOverview; dataOverview.append(m_Controls.m_lineEditDataLabel->text()); dataOverview.append("(").append(m_Controls.m_comboBoxChartType->currentText()); if (!dataColor.empty()) { dataOverview.append(", ").append(dataColor.c_str()); } dataOverview.append(", ").append(m_Controls.m_comboBoxLineStyle->currentText()); dataOverview.append(")"); dataOverview.append(":").append(lineEditData); m_Controls.m_plainTextEditDataView->appendPlainText(dataOverview); FillRandomDataValues(); } std::vector<double> ChartExample::generateRandomNumbers(unsigned int amount, double max) const { QRandomGenerator gen; gen.seed(time(NULL)); std::vector<double> data; for (unsigned int i = 0; i < amount; i++) { data.push_back(gen.bounded(max)); } return data; } std::string ChartExample::convertToText(std::vector<double> numbers, std::string delimiter) const { std::ostringstream oss; oss.precision(3); if (!numbers.empty()) { for (auto number : numbers) { oss << number << delimiter; } } auto aString = oss.str(); aString.pop_back(); return aString; } QmitkChartWidget::ChartStyle ChartExample::GetColorTheme() const { ctkPluginContext* context = berry::WorkbenchPlugin::GetDefault()->GetPluginContext(); ctkServiceReference styleManagerRef = context->getServiceReference<berry::IQtStyleManager>(); if (styleManagerRef) { auto styleManager = context->getService<berry::IQtStyleManager>(styleManagerRef); if (styleManager->GetStyle().name == "Dark") { return QmitkChartWidget::ChartStyle::darkstyle; } else { return QmitkChartWidget::ChartStyle::lightstyle; } } return QmitkChartWidget::ChartStyle::darkstyle; } <commit_msg>removed unecessary include<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Blueberry #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> #include <berryWorkbenchPlugin.h> #include <berryIQtStyleManager.h> // Qmitk #include "ChartExample.h" // Qt #include <QMessageBox> #include <QRandomGenerator> const std::string ChartExample::VIEW_ID = "org.mitk.views.chartexample"; void ChartExample::SetFocus() { m_Controls.m_buttonCreateChart->setFocus(); } void ChartExample::CreateQtPartControl(QWidget *parent) { // create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi(parent); connect(m_Controls.m_buttonCreateChart, &QPushButton::clicked, this, &ChartExample::CreateChart); connect(m_Controls.m_buttonClearChart, &QPushButton::clicked, this, &ChartExample::ClearChart); connect(m_Controls.m_buttonAddData, &QPushButton::clicked, this, &ChartExample::AddData); FillRandomDataValues(); m_Controls.m_Chart->SetTheme(GetColorTheme()); m_Controls.m_lineEditXAxisLabel->setText("xLabel"); m_Controls.m_lineEditYAxisLabel->setText("yLabel"); m_chartNameToChartType.emplace("bar", QmitkChartWidget::ChartType::bar); m_chartNameToChartType.emplace("line", QmitkChartWidget::ChartType::line); m_chartNameToChartType.emplace("spline", QmitkChartWidget::ChartType::spline); m_chartNameToChartType.emplace("pie", QmitkChartWidget::ChartType::pie); m_chartNameToChartType.emplace("area", QmitkChartWidget::ChartType::area); m_chartNameToChartType.emplace("area-spline", QmitkChartWidget::ChartType::area_spline); m_chartNameToChartType.emplace("scatter", QmitkChartWidget::ChartType::scatter); m_LineNameToLineType.emplace("solid", QmitkChartWidget::LineStyle::solid); m_LineNameToLineType.emplace("dashed", QmitkChartWidget::LineStyle::dashed); m_AxisScaleNameToAxisScaleType.emplace("linear", QmitkChartWidget::AxisScale::linear); m_AxisScaleNameToAxisScaleType.emplace("logarithmic", QmitkChartWidget::AxisScale::log); } void ChartExample::FillRandomDataValues() { std::vector<double> numbers = generateRandomNumbers(10, 10.0); std::string text = convertToText(numbers, ";"); m_Controls.m_lineEditDataVector->setText(QString::fromStdString(text)); m_Controls.m_lineEditDataLabel->setText("test" + QString::number(countForUID)); countForUID++; } void ChartExample::CreateChart() { auto dataYAxisScaleType = m_AxisScaleNameToAxisScaleType.at(m_Controls.m_comboBoxYAxisScale->currentText().toStdString()); auto xAxisLabel = m_Controls.m_lineEditXAxisLabel->text().toStdString(); auto yAxisLabel = m_Controls.m_lineEditYAxisLabel->text().toStdString(); auto showLegend = m_Controls.m_checkBoxShowLegend->isChecked(); auto showDataPoints = m_Controls.m_checkBoxShowDataPoints->isChecked(); auto stackedData = m_Controls.m_checkBoxStackedData->isChecked(); auto showSubchart = m_Controls.m_checkBoxShowSubchart->isChecked(); m_Controls.m_Chart->SetYAxisScale(dataYAxisScaleType); m_Controls.m_Chart->SetXAxisLabel(xAxisLabel); m_Controls.m_Chart->SetYAxisLabel(yAxisLabel); m_Controls.m_Chart->SetShowLegend(showLegend); m_Controls.m_Chart->SetShowDataPoints(showDataPoints); m_Controls.m_Chart->SetStackedData(stackedData); m_Controls.m_Chart->Show(showSubchart); } void ChartExample::ClearChart() { m_Controls.m_Chart->Clear(); m_Controls.m_plainTextEditDataView->clear(); } void ChartExample::AddData() { auto lineEditData = m_Controls.m_lineEditDataVector->text(); std::vector<double> data; for(const QString entry : lineEditData.split(';')) { data.push_back(entry.toDouble()); } auto chartType = m_chartNameToChartType.at(m_Controls.m_comboBoxChartType->currentText().toStdString()); std::string dataLabel = m_Controls.m_lineEditDataLabel->text().toStdString(); std::string dataColor = m_Controls.m_lineEditColor->text().toStdString(); auto dataLineStyleType = m_LineNameToLineType.at(m_Controls.m_comboBoxLineStyle->currentText().toStdString()); m_Controls.m_Chart->AddData1D(data, dataLabel, chartType); if (!dataColor.empty()) { m_Controls.m_Chart->SetColor(dataLabel, dataColor); } m_Controls.m_Chart->SetLineStyle(dataLabel, dataLineStyleType); QString dataOverview; dataOverview.append(m_Controls.m_lineEditDataLabel->text()); dataOverview.append("(").append(m_Controls.m_comboBoxChartType->currentText()); if (!dataColor.empty()) { dataOverview.append(", ").append(dataColor.c_str()); } dataOverview.append(", ").append(m_Controls.m_comboBoxLineStyle->currentText()); dataOverview.append(")"); dataOverview.append(":").append(lineEditData); m_Controls.m_plainTextEditDataView->appendPlainText(dataOverview); FillRandomDataValues(); } std::vector<double> ChartExample::generateRandomNumbers(unsigned int amount, double max) const { QRandomGenerator gen; gen.seed(time(NULL)); std::vector<double> data; for (unsigned int i = 0; i < amount; i++) { data.push_back(gen.bounded(max)); } return data; } std::string ChartExample::convertToText(std::vector<double> numbers, std::string delimiter) const { std::ostringstream oss; oss.precision(3); if (!numbers.empty()) { for (auto number : numbers) { oss << number << delimiter; } } auto aString = oss.str(); aString.pop_back(); return aString; } QmitkChartWidget::ChartStyle ChartExample::GetColorTheme() const { ctkPluginContext* context = berry::WorkbenchPlugin::GetDefault()->GetPluginContext(); ctkServiceReference styleManagerRef = context->getServiceReference<berry::IQtStyleManager>(); if (styleManagerRef) { auto styleManager = context->getService<berry::IQtStyleManager>(styleManagerRef); if (styleManager->GetStyle().name == "Dark") { return QmitkChartWidget::ChartStyle::darkstyle; } else { return QmitkChartWidget::ChartStyle::lightstyle; } } return QmitkChartWidget::ChartStyle::darkstyle; } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginCommandLineArgs // INPUTS: {qb_RoadExtract.tif} // OUTPUTS: {OBIARadiometricAttribute1.tif}, {qb_ExtractRoad_Radiometry_pretty.jpg} // STATS::Ndvi::Mean 0 0.5 16 16 50 1.0 // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // This example shows the basic approach to perform object based analysis on a image. // The input image is firstly segmented using the \doxygen{otb}{MeanShiftImageFilter} // Then each segmented region is converted to a Map of labeled objects. // Afterwards the \doxygen{otb}{RadiometricAttributesLabelMapFilter} computes // radiometric attributes for each object. // // This filter internally applies the // \doxygen{otb}{StatisticsAttributesLabelMapFilter} to the following features: // \begin{itemize} // \item GEMI // \item NDVI // \item IR // \item IC // \item IB // \item NDWI2 // \item Intensity // \item and original B, G, R and NIR channels // \end{itemize} // Here we use the \doxygen{otb}{AttributesMapOpeningLabelMapFilter} to extract vegetated areas. // Let's get to the source code explanation. // // Software Guide : EndLatex #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "otbMeanShiftVectorImageFilter.h" #include "itkLabelImageToLabelMapFilter.h" #include "otbAttributesMapLabelObject.h" #include "itkLabelMap.h" #include "otbShapeAttributesLabelMapFilter.h" #include "otbStatisticsAttributesLabelMapFilter.h" #include "otbBandsStatisticsAttributesLabelMapFilter.h" #include "otbAttributesMapOpeningLabelMapFilter.h" #include "itkLabelMapToBinaryImageFilter.h" #include "otbMultiChannelExtractROI.h" #include "otbVectorRescaleIntensityImageFilter.h" #include "otbVegetationIndicesFunctor.h" #include "otbMultiChannelRAndNIRIndexImageFilter.h" #include "otbImageToVectorImageCastFilter.h" int main(int argc, char * argv[]) { if (argc != 11) { std::cerr << "Usage: " << argv[0] << " reffname outfname outprettyfname attribute_name "; std::cerr << "lowerThan tresh spatialRadius rangeRadius minregionsize scale" << std::endl; return EXIT_FAILURE; } const char * reffname = argv[1]; const char * outfname = argv[2]; const char * outprettyfname = argv[3]; const char * attr = argv[4]; double lowerThan = atof(argv[5]); double thresh = atof(argv[6]); const unsigned int spatialRadius = atoi(argv[7]); const double rangeRadius = atof(argv[8]); const unsigned int minRegionSize = atoi(argv[9]); const double scale = atoi(argv[10]); const unsigned int Dimension = 2; // Labeled image type typedef unsigned short LabelType; typedef double PixelType; typedef otb::Image<LabelType, Dimension> LabeledImageType; typedef otb::Image<PixelType, Dimension> ImageType; typedef otb::VectorImage<PixelType, Dimension> VectorImageType; typedef otb::VectorImage<unsigned char, Dimension> OutputVectorImageType; typedef otb::ImageFileReader<LabeledImageType> LabeledReaderType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileReader<VectorImageType> VectorReaderType; typedef otb::ImageFileWriter<LabeledImageType> WriterType; typedef otb::ImageFileWriter<OutputVectorImageType> VectorWriterType; typedef otb::VectorRescaleIntensityImageFilter <VectorImageType, OutputVectorImageType> VectorRescalerType; typedef otb::MultiChannelExtractROI<unsigned char, unsigned char> ChannelExtractorType; // Label map typedef typedef otb::AttributesMapLabelObject<LabelType, Dimension, double> LabelObjectType; typedef itk::LabelMap<LabelObjectType> LabelMapType; typedef itk::LabelImageToLabelMapFilter<LabeledImageType, LabelMapType> LabelMapFilterType; typedef otb::ShapeAttributesLabelMapFilter<LabelMapType> ShapeLabelMapFilterType; typedef otb::BandsStatisticsAttributesLabelMapFilter<LabelMapType, ImageType> StatisticsLabelMapFilterType; typedef otb::BandsStatisticsAttributesLabelMapFilter<LabelMapType, VectorImageType> RadiometricLabelMapFilterType; typedef otb::AttributesMapOpeningLabelMapFilter<LabelMapType> OpeningLabelMapFilterType; typedef itk::LabelMapToBinaryImageFilter<LabelMapType, LabeledImageType> LabelMapToBinaryImageFilterType; typedef otb::MultiChannelRAndNIRIndexImageFilter<VectorImageType, ImageType> NDVIImageFilterType; typedef otb::ImageToVectorImageCastFilter<ImageType,VectorImageType> ImageToVectorImageCastFilterType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(reffname); LabeledReaderType::Pointer lreader = LabeledReaderType::New(); lreader->SetFileName(reffname); VectorReaderType::Pointer vreader = VectorReaderType::New(); vreader->SetFileName(reffname); vreader->Update(); // Software Guide : BeginLatex // // Firstly, segment the input image by using the Mean Shift algorithm (see \ref{sec:MeanShift} for deeper // explanations). // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::MeanShiftVectorImageFilter <VectorImageType, VectorImageType, LabeledImageType> FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetSpatialRadius(spatialRadius); filter->SetRangeRadius(rangeRadius); filter->SetMinimumRegionSize(minRegionSize); filter->SetScale(scale); // Software Guide : EndCodeSnippet // For non regression tests, set the number of threads to 1 // because MeanShift results depends on the number of threads filter->SetNumberOfThreads(1); // Software Guide : BeginLatex // // The \doxygen{otb}{MeanShiftImageFilter} type is instantiated using the image // types. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->SetInput(vreader->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The \doxygen{itk}{LabelImageToLabelMapFilter} type is instantiated using the output // of the \doxygen{otb}{MeanShiftImageFilter}. This filter produces a labeled image // where each segmented region has a unique label. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet LabelMapFilterType::Pointer labelMapFilter = LabelMapFilterType::New(); labelMapFilter->SetInput(filter->GetLabeledClusteredOutput()); labelMapFilter->SetBackgroundValue(itk::NumericTraits<LabelType>::min()); ShapeLabelMapFilterType::Pointer shapeLabelMapFilter = ShapeLabelMapFilterType::New(); shapeLabelMapFilter->SetInput(labelMapFilter->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Instantiate the \doxygen{otb}{BandsStatisticsAttributesLabelMapFilter} to // compute radiometric value on each label object. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet RadiometricLabelMapFilterType::Pointer radiometricLabelMapFilter = RadiometricLabelMapFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Feature image could be one of the following image: // \item GEMI // \item NDVI // \item IR // \item IC // \item IB // \item NDWI2 // \item Intensity // // Input image must be convert to the desired coefficient. // In our case, radiometric label map will be process on a NDVI coefficient. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet NDVIImageFilterType:: Pointer ndviImageFilter = NDVIImageFilterType::New(); ndviImageFilter->SetRedIndex(3); ndviImageFilter->SetNIRIndex(4); ndviImageFilter->SetInput(vreader->GetOutput()); ImageToVectorImageCastFilterType::Pointer ndviVectorImageFilter = ImageToVectorImageCastFilterType::New(); ndviVectorImageFilter->SetInput(ndviImageFilter->GetOutput()); radiometricLabelMapFilter->SetInput(shapeLabelMapFilter->GetOutput()); radiometricLabelMapFilter->SetFeatureImage(ndviVectorImageFilter->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The \doxygen{otb}{AttributesMapOpeningLabelMapFilter} will perform the selection. // There are three parameters. \code{AttributeName} specifies the radiometric attribute, \code{Lambda} // controls the thresholding of the input and \code{ReverseOrdering} make this filter to remove the // object with an attribute value greater than \code{Lambda} instead. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet OpeningLabelMapFilterType::Pointer opening = OpeningLabelMapFilterType::New(); opening->SetInput(radiometricLabelMapFilter->GetOutput()); opening->SetAttributeName(attr); opening->SetLambda(thresh); opening->SetReverseOrdering(lowerThan); opening->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Then, Label objects selected are transform in a Label Image using the // \doxygen{itk}{LabelMapToLabelImageFilter}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet LabelMapToBinaryImageFilterType::Pointer labelMap2LabeledImage = LabelMapToBinaryImageFilterType::New(); labelMap2LabeledImage->SetInput(opening->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // And finally, we declare the writer and call its \code{Update()} method to // trigger the full pipeline execution. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outfname); writer->SetInput(labelMap2LabeledImage->GetOutput()); writer->Update(); // Software Guide : EndCodeSnippet OutputVectorImageType::PixelType minimum, maximum; minimum.SetSize(vreader->GetOutput()->GetNumberOfComponentsPerPixel()); maximum.SetSize(vreader->GetOutput()->GetNumberOfComponentsPerPixel()); minimum.Fill(0); maximum.Fill(255); VectorRescalerType::Pointer vr = VectorRescalerType::New(); vr->SetInput(filter->GetClusteredOutput()); vr->SetOutputMinimum(minimum); vr->SetOutputMaximum(maximum); vr->SetClampThreshold(0.01); ChannelExtractorType::Pointer selecter = ChannelExtractorType::New(); selecter->SetInput(vr->GetOutput()); selecter->SetExtractionRegion(vreader->GetOutput()->GetLargestPossibleRegion()); selecter->SetChannel(3); selecter->SetChannel(2); selecter->SetChannel(1); VectorWriterType::Pointer vectWriter = VectorWriterType::New(); vectWriter->SetFileName(outprettyfname); vectWriter->SetInput(selecter->GetOutput()); vectWriter->Update(); return EXIT_SUCCESS; } // Software Guide : BeginLatex // // Figure~\ref{fig:RADIOMETRIC_LABEL_MAP_FILTER} shows the result of applying // the object selection based on radiometric attributes. // \begin{figure} [htbp] // \center // \includegraphics[width=0.44\textwidth]{qb_ExtractRoad_Radiometry_pretty.eps} // \includegraphics[width=0.44\textwidth]{OBIARadiometricAttribute1.eps} // \itkcaption[Object based extraction based on ]{Vegetation mask resulting from processing.} // \label{fig:RADIOMETRIC_LABEL_MAP_FILTER} // \end{figure} // // Software Guide : EndLatex <commit_msg>DOC:replace STATS:Ndvi:Mean by STATS::Band1::Mean and update the associated documentation<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginCommandLineArgs // INPUTS: {qb_RoadExtract.tif} // OUTPUTS: {OBIARadiometricAttribute1.tif}, {qb_ExtractRoad_Radiometry_pretty.jpg} // STATS::Band1::Mean 0 0.5 16 16 50 1.0 // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // This example shows the basic approach to perform object based analysis on a image. // The input image is firstly segmented using the \doxygen{otb}{MeanShiftImageFilter} // Then each segmented region is converted to a Map of labeled objects. // Afterwards the \doxygen{otb}{otbMultiChannelRAndNIRIndexImageFilter} computes // radiometric attributes for each object. In this example the NDVI is computed. // The computed feature is passed to the \doxygen{otb}{BandsStatisticsAttributesLabelMapFilter} // which computes statistics over the resulting band. // Therefore, region's statistics over each band can be access by concatening // STATS, the band number and the statistical attribute separated by colons. In this example // the mean of the first band (which contains the NDVI) is access over all the regions // with the attribute: 'STATS::Band1::Mean'. // // Software Guide : EndLatex #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "otbMeanShiftVectorImageFilter.h" #include "itkLabelImageToLabelMapFilter.h" #include "otbAttributesMapLabelObject.h" #include "itkLabelMap.h" #include "otbShapeAttributesLabelMapFilter.h" #include "otbStatisticsAttributesLabelMapFilter.h" #include "otbBandsStatisticsAttributesLabelMapFilter.h" #include "itkLabelMapToBinaryImageFilter.h" #include "otbMultiChannelExtractROI.h" #include "otbAttributesMapOpeningLabelMapFilter.h" #include "otbVectorRescaleIntensityImageFilter.h" #include "otbVegetationIndicesFunctor.h" #include "otbMultiChannelRAndNIRIndexImageFilter.h" #include "otbImageToVectorImageCastFilter.h" int main(int argc, char * argv[]) { if (argc != 11) { std::cerr << "Usage: " << argv[0] << " reffname outfname outprettyfname attribute_name "; std::cerr << "lowerThan tresh spatialRadius rangeRadius minregionsize scale" << std::endl; return EXIT_FAILURE; } const char * reffname = argv[1]; const char * outfname = argv[2]; const char * outprettyfname = argv[3]; const char * attr = argv[4]; double lowerThan = atof(argv[5]); double thresh = atof(argv[6]); const unsigned int spatialRadius = atoi(argv[7]); const double rangeRadius = atof(argv[8]); const unsigned int minRegionSize = atoi(argv[9]); const double scale = atoi(argv[10]); const unsigned int Dimension = 2; // Labeled image type typedef unsigned short LabelType; typedef double PixelType; typedef otb::Image<LabelType, Dimension> LabeledImageType; typedef otb::Image<PixelType, Dimension> ImageType; typedef otb::VectorImage<PixelType, Dimension> VectorImageType; typedef otb::VectorImage<unsigned char, Dimension> OutputVectorImageType; typedef otb::ImageFileReader<LabeledImageType> LabeledReaderType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileReader<VectorImageType> VectorReaderType; typedef otb::ImageFileWriter<LabeledImageType> WriterType; typedef otb::ImageFileWriter<OutputVectorImageType> VectorWriterType; typedef otb::VectorRescaleIntensityImageFilter <VectorImageType, OutputVectorImageType> VectorRescalerType; typedef otb::MultiChannelExtractROI<unsigned char, unsigned char> ChannelExtractorType; // Label map typedef typedef otb::AttributesMapLabelObject<LabelType, Dimension, double> LabelObjectType; typedef itk::LabelMap<LabelObjectType> LabelMapType; typedef itk::LabelImageToLabelMapFilter<LabeledImageType, LabelMapType> LabelMapFilterType; typedef otb::ShapeAttributesLabelMapFilter<LabelMapType> ShapeLabelMapFilterType; typedef otb::BandsStatisticsAttributesLabelMapFilter<LabelMapType, ImageType> StatisticsLabelMapFilterType; typedef otb::BandsStatisticsAttributesLabelMapFilter<LabelMapType, VectorImageType> RadiometricLabelMapFilterType; typedef otb::AttributesMapOpeningLabelMapFilter<LabelMapType> OpeningLabelMapFilterType; typedef itk::LabelMapToBinaryImageFilter<LabelMapType, LabeledImageType> LabelMapToBinaryImageFilterType; typedef otb::MultiChannelRAndNIRIndexImageFilter<VectorImageType, ImageType> NDVIImageFilterType; typedef otb::ImageToVectorImageCastFilter<ImageType,VectorImageType> ImageToVectorImageCastFilterType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(reffname); LabeledReaderType::Pointer lreader = LabeledReaderType::New(); lreader->SetFileName(reffname); VectorReaderType::Pointer vreader = VectorReaderType::New(); vreader->SetFileName(reffname); vreader->Update(); // Software Guide : BeginLatex // // Firstly, segment the input image by using the Mean Shift algorithm (see \ref{sec:MeanShift} for deeper // explanations). // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::MeanShiftVectorImageFilter <VectorImageType, VectorImageType, LabeledImageType> FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetSpatialRadius(spatialRadius); filter->SetRangeRadius(rangeRadius); filter->SetMinimumRegionSize(minRegionSize); filter->SetScale(scale); // Software Guide : EndCodeSnippet // For non regression tests, set the number of threads to 1 // because MeanShift results depends on the number of threads filter->SetNumberOfThreads(1); // Software Guide : BeginLatex // // The \doxygen{otb}{MeanShiftImageFilter} type is instantiated using the image // types. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->SetInput(vreader->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The \doxygen{itk}{LabelImageToLabelMapFilter} type is instantiated using the output // of the \doxygen{otb}{MeanShiftImageFilter}. This filter produces a labeled image // where each segmented region has a unique label. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet LabelMapFilterType::Pointer labelMapFilter = LabelMapFilterType::New(); labelMapFilter->SetInput(filter->GetLabeledClusteredOutput()); labelMapFilter->SetBackgroundValue(itk::NumericTraits<LabelType>::min()); ShapeLabelMapFilterType::Pointer shapeLabelMapFilter = ShapeLabelMapFilterType::New(); shapeLabelMapFilter->SetInput(labelMapFilter->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Instantiate the \doxygen{otb}{BandsStatisticsAttributesLabelMapFilter} to // compute radiometric value on each label object. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet RadiometricLabelMapFilterType::Pointer radiometricLabelMapFilter = RadiometricLabelMapFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Feature image could be one of the following image: // \item GEMI // \item NDVI // \item IR // \item IC // \item IB // \item NDWI2 // \item Intensity // // Input image must be convert to the desired coefficient. // In our case, radiometric label map will be process on a NDVI coefficient. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet NDVIImageFilterType:: Pointer ndviImageFilter = NDVIImageFilterType::New(); ndviImageFilter->SetRedIndex(3); ndviImageFilter->SetNIRIndex(4); ndviImageFilter->SetInput(vreader->GetOutput()); ImageToVectorImageCastFilterType::Pointer ndviVectorImageFilter = ImageToVectorImageCastFilterType::New(); ndviVectorImageFilter->SetInput(ndviImageFilter->GetOutput()); radiometricLabelMapFilter->SetInput(shapeLabelMapFilter->GetOutput()); radiometricLabelMapFilter->SetFeatureImage(ndviVectorImageFilter->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The \doxygen{otb}{AttributesMapOpeningLabelMapFilter} will perform the selection. // There are three parameters. \code{AttributeName} specifies the radiometric attribute, \code{Lambda} // controls the thresholding of the input and \code{ReverseOrdering} make this filter to remove the // object with an attribute value greater than \code{Lambda} instead. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet OpeningLabelMapFilterType::Pointer opening = OpeningLabelMapFilterType::New(); opening->SetInput(radiometricLabelMapFilter->GetOutput()); opening->SetAttributeName(attr); opening->SetLambda(thresh); opening->SetReverseOrdering(lowerThan); opening->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Then, Label objects selected are transform in a Label Image using the // \doxygen{itk}{LabelMapToLabelImageFilter}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet LabelMapToBinaryImageFilterType::Pointer labelMap2LabeledImage = LabelMapToBinaryImageFilterType::New(); labelMap2LabeledImage->SetInput(opening->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // And finally, we declare the writer and call its \code{Update()} method to // trigger the full pipeline execution. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outfname); writer->SetInput(labelMap2LabeledImage->GetOutput()); writer->Update(); // Software Guide : EndCodeSnippet OutputVectorImageType::PixelType minimum, maximum; minimum.SetSize(vreader->GetOutput()->GetNumberOfComponentsPerPixel()); maximum.SetSize(vreader->GetOutput()->GetNumberOfComponentsPerPixel()); minimum.Fill(0); maximum.Fill(255); VectorRescalerType::Pointer vr = VectorRescalerType::New(); vr->SetInput(filter->GetClusteredOutput()); vr->SetOutputMinimum(minimum); vr->SetOutputMaximum(maximum); vr->SetClampThreshold(0.01); ChannelExtractorType::Pointer selecter = ChannelExtractorType::New(); selecter->SetInput(vr->GetOutput()); selecter->SetExtractionRegion(vreader->GetOutput()->GetLargestPossibleRegion()); selecter->SetChannel(3); selecter->SetChannel(2); selecter->SetChannel(1); VectorWriterType::Pointer vectWriter = VectorWriterType::New(); vectWriter->SetFileName(outprettyfname); vectWriter->SetInput(selecter->GetOutput()); vectWriter->Update(); return EXIT_SUCCESS; } // Software Guide : BeginLatex // // Figure~\ref{fig:RADIOMETRIC_LABEL_MAP_FILTER} shows the result of applying // the object selection based on radiometric attributes. // \begin{figure} [htbp] // \center // \includegraphics[width=0.44\textwidth]{qb_ExtractRoad_Radiometry_pretty.eps} // \includegraphics[width=0.44\textwidth]{OBIARadiometricAttribute1.eps} // \itkcaption[Object based extraction based on ]{Vegetation mask resulting from processing.} // \label{fig:RADIOMETRIC_LABEL_MAP_FILTER} // \end{figure} // // Software Guide : EndLatex <|endoftext|>
<commit_before>/* * Copyright 2007-2021 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 "HeadIstream.hxx" #include "ForwardIstream.hxx" #include "UnusedPtr.hxx" #include "Bucket.hxx" #include "New.hxx" #include <algorithm> #include <assert.h> class HeadIstream final : public ForwardIstream { off_t rest; const bool authoritative; public: HeadIstream(struct pool &p, UnusedIstreamPtr _input, size_t size, bool _authoritative) noexcept :ForwardIstream(p, std::move(_input)), rest(size), authoritative(_authoritative) {} /* virtual methods from class Istream */ off_t _GetAvailable(bool partial) noexcept override; off_t _Skip(off_t length) noexcept override; void _Read() noexcept override; void _FillBucketList(IstreamBucketList &list) override; int _AsFd() noexcept override { return -1; } /* virtual methods from class IstreamHandler */ size_t OnData(const void *data, size_t length) noexcept override; ssize_t OnDirect(FdType type, int fd, size_t max_length) noexcept override; }; /* * istream handler * */ size_t HeadIstream::OnData(const void *data, size_t length) noexcept { if (rest == 0) { DestroyEof(); return 0; } if ((off_t)length > rest) length = rest; size_t nbytes = InvokeData(data, length); assert((off_t)nbytes <= rest); if (nbytes > 0) { rest -= nbytes; if (rest == 0) { DestroyEof(); return 0; } } return nbytes; } void HeadIstream::_FillBucketList(IstreamBucketList &list) { if (rest == 0) return; IstreamBucketList tmp1; try { input.FillBucketList(tmp1); } catch (...) { Destroy(); throw; } size_t nbytes = list.SpliceBuffersFrom(std::move(tmp1), rest); if ((off_t)nbytes >= rest) list.SetMore(false); } ssize_t HeadIstream::OnDirect(FdType type, int fd, size_t max_length) noexcept { if (rest == 0) { DestroyEof(); return ISTREAM_RESULT_CLOSED; } if ((off_t)max_length > rest) max_length = rest; ssize_t nbytes = InvokeDirect(type, fd, max_length); assert(nbytes < 0 || (off_t)nbytes <= rest); if (nbytes > 0) { rest -= (size_t)nbytes; if (rest == 0) { DestroyEof(); return ISTREAM_RESULT_CLOSED; } } return nbytes; } /* * istream implementation * */ off_t HeadIstream::_GetAvailable(bool partial) noexcept { if (authoritative) { assert(partial || input.GetAvailable(partial) < 0 || input.GetAvailable(partial) >= (off_t)rest); return rest; } off_t available = input.GetAvailable(partial); return std::min(available, rest); } off_t HeadIstream::_Skip(off_t length) noexcept { if (length >= rest) length = rest; off_t nbytes = ForwardIstream::_Skip(length); assert(nbytes <= length); if (nbytes > 0) rest -= nbytes; return nbytes; } void HeadIstream::_Read() noexcept { if (rest == 0) { DestroyEof(); } else { ForwardIstream::_Read(); } } /* * constructor * */ UnusedIstreamPtr istream_head_new(struct pool &pool, UnusedIstreamPtr input, size_t size, bool authoritative) noexcept { return NewIstreamPtr<HeadIstream>(pool, std::move(input), size, authoritative); } <commit_msg>istream/head: implement _ConsumeBucketList() to fix assertion failure<commit_after>/* * Copyright 2007-2021 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 "HeadIstream.hxx" #include "ForwardIstream.hxx" #include "UnusedPtr.hxx" #include "Bucket.hxx" #include "New.hxx" #include <algorithm> #include <assert.h> class HeadIstream final : public ForwardIstream { off_t rest; const bool authoritative; public: HeadIstream(struct pool &p, UnusedIstreamPtr _input, size_t size, bool _authoritative) noexcept :ForwardIstream(p, std::move(_input)), rest(size), authoritative(_authoritative) {} /* virtual methods from class Istream */ off_t _GetAvailable(bool partial) noexcept override; size_t _ConsumeBucketList(size_t nbytes) noexcept override; off_t _Skip(off_t length) noexcept override; void _Read() noexcept override; void _FillBucketList(IstreamBucketList &list) override; int _AsFd() noexcept override { return -1; } /* virtual methods from class IstreamHandler */ size_t OnData(const void *data, size_t length) noexcept override; ssize_t OnDirect(FdType type, int fd, size_t max_length) noexcept override; }; /* * istream handler * */ size_t HeadIstream::OnData(const void *data, size_t length) noexcept { if (rest == 0) { DestroyEof(); return 0; } if ((off_t)length > rest) length = rest; size_t nbytes = InvokeData(data, length); assert((off_t)nbytes <= rest); if (nbytes > 0) { rest -= nbytes; if (rest == 0) { DestroyEof(); return 0; } } return nbytes; } void HeadIstream::_FillBucketList(IstreamBucketList &list) { if (rest == 0) return; IstreamBucketList tmp1; try { input.FillBucketList(tmp1); } catch (...) { Destroy(); throw; } size_t nbytes = list.SpliceBuffersFrom(std::move(tmp1), rest); if ((off_t)nbytes >= rest) list.SetMore(false); } size_t HeadIstream::_ConsumeBucketList(size_t nbytes) noexcept { if ((off_t)nbytes > rest) nbytes = rest; nbytes = ForwardIstream::_ConsumeBucketList(nbytes); rest -= nbytes; return nbytes; } ssize_t HeadIstream::OnDirect(FdType type, int fd, size_t max_length) noexcept { if (rest == 0) { DestroyEof(); return ISTREAM_RESULT_CLOSED; } if ((off_t)max_length > rest) max_length = rest; ssize_t nbytes = InvokeDirect(type, fd, max_length); assert(nbytes < 0 || (off_t)nbytes <= rest); if (nbytes > 0) { rest -= (size_t)nbytes; if (rest == 0) { DestroyEof(); return ISTREAM_RESULT_CLOSED; } } return nbytes; } /* * istream implementation * */ off_t HeadIstream::_GetAvailable(bool partial) noexcept { if (authoritative) { assert(partial || input.GetAvailable(partial) < 0 || input.GetAvailable(partial) >= (off_t)rest); return rest; } off_t available = input.GetAvailable(partial); return std::min(available, rest); } off_t HeadIstream::_Skip(off_t length) noexcept { if (length >= rest) length = rest; off_t nbytes = ForwardIstream::_Skip(length); assert(nbytes <= length); if (nbytes > 0) rest -= nbytes; return nbytes; } void HeadIstream::_Read() noexcept { if (rest == 0) { DestroyEof(); } else { ForwardIstream::_Read(); } } /* * constructor * */ UnusedIstreamPtr istream_head_new(struct pool &pool, UnusedIstreamPtr input, size_t size, bool authoritative) noexcept { return NewIstreamPtr<HeadIstream>(pool, std::move(input), size, authoritative); } <|endoftext|>
<commit_before>/* Adplug - Replayer for many OPL2/OPL3 audio file formats. Copyright (C) 1999 - 2007 Simon Peter <[email protected]>, et al. 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 fmc.cpp - FMC Loader by Riven the Mage <[email protected]> */ #include <cstring> #include "fmc.h" /* -------- Public Methods -------------------------------- */ CPlayer *CfmcLoader::factory(Copl *newopl) { return new CfmcLoader(newopl); } bool CfmcLoader::load(const std::string &filename, const CFileProvider &fp) { binistream *f = fp.open(filename); if(!f) return false; const unsigned char conv_fx[16] = {0,1,2,3,4,8,255,255,255,255,26,11,12,13,14,15}; int i,j,k,t=0; // read header f->readString(header.id, 4); f->readString(header.title, 21); header.numchan = f->readInt(1); // 'FMC!' - signed ? if (strncmp(header.id,"FMC!",4)) { fp.close(f); return false; } // init CmodPlayer realloc_instruments(32); realloc_order(256); realloc_patterns(64,64,header.numchan); init_trackord(); // load order for(i = 0; i < 256; i++) order[i] = f->readInt(1); f->ignore(2); // load instruments for(i = 0; i < 32; i++) { instruments[i].synthesis = f->readInt(1); instruments[i].feedback = f->readInt(1); instruments[i].mod_attack = f->readInt(1); instruments[i].mod_decay = f->readInt(1); instruments[i].mod_sustain = f->readInt(1); instruments[i].mod_release = f->readInt(1); instruments[i].mod_volume = f->readInt(1); instruments[i].mod_ksl = f->readInt(1); instruments[i].mod_freq_multi = f->readInt(1); instruments[i].mod_waveform = f->readInt(1); instruments[i].mod_sustain_sound = f->readInt(1); instruments[i].mod_ksr = f->readInt(1); instruments[i].mod_vibrato = f->readInt(1); instruments[i].mod_tremolo = f->readInt(1); instruments[i].car_attack = f->readInt(1); instruments[i].car_decay = f->readInt(1); instruments[i].car_sustain = f->readInt(1); instruments[i].car_release = f->readInt(1); instruments[i].car_volume = f->readInt(1); instruments[i].car_ksl = f->readInt(1); instruments[i].car_freq_multi = f->readInt(1); instruments[i].car_waveform = f->readInt(1); instruments[i].car_sustain_sound = f->readInt(1); instruments[i].car_ksr = f->readInt(1); instruments[i].car_vibrato = f->readInt(1); instruments[i].car_tremolo = f->readInt(1); instruments[i].pitch_shift = f->readInt(1); f->readString(instruments[i].name, 21); } // load tracks for (i=0;i<64;i++) { if(f->ateof()) break; for (j=0;j<header.numchan;j++) { for (k=0;k<64;k++) { fmc_event event; // read event event.byte0 = f->readInt(1); event.byte1 = f->readInt(1); event.byte2 = f->readInt(1); // convert event tracks[t][k].note = event.byte0 & 0x7F; tracks[t][k].inst = ((event.byte0 & 0x80) >> 3) + (event.byte1 >> 4) + 1; tracks[t][k].command = conv_fx[event.byte1 & 0x0F]; tracks[t][k].param1 = event.byte2 >> 4; tracks[t][k].param2 = event.byte2 & 0x0F; // fix effects if (tracks[t][k].command == 0x0E) // 0x0E (14): Retrig tracks[t][k].param1 = 3; if (tracks[t][k].command == 0x1A) { // 0x1A (26): Volume Slide if (tracks[t][k].param1 > tracks[t][k].param2) { tracks[t][k].param1 -= tracks[t][k].param2; tracks[t][k].param2 = 0; } else { tracks[t][k].param2 -= tracks[t][k].param1; tracks[t][k].param1 = 0; } } } t++; } } fp.close(f); // convert instruments for (i=0;i<31;i++) buildinst(i); // order length for (i=0;i<256;i++) { if (order[i] >= 0xFE) { length = i; break; } } // data for Protracker activechan = (0xffffffff >> (32 - header.numchan)) << (32 - header.numchan); nop = t / header.numchan; restartpos = 0; // flags flags = Faust; rewind(0); return true; } float CfmcLoader::getrefresh() { return 50.0f; } std::string CfmcLoader::gettype() { return std::string("Faust Music Creator"); } std::string CfmcLoader::gettitle() { return std::string(header.title); } std::string CfmcLoader::getinstrument(unsigned int n) { return std::string(instruments[n].name); } unsigned int CfmcLoader::getinstruments() { return 32; } /* -------- Private Methods ------------------------------- */ void CfmcLoader::buildinst(unsigned char i) { inst[i].data[0] = ((instruments[i].synthesis & 1) ^ 1); inst[i].data[0] |= ((instruments[i].feedback & 7) << 1); inst[i].data[3] = ((instruments[i].mod_attack & 15) << 4); inst[i].data[3] |= (instruments[i].mod_decay & 15); inst[i].data[5] = ((15 - (instruments[i].mod_sustain & 15)) << 4); inst[i].data[5] |= (instruments[i].mod_release & 15); inst[i].data[9] = (63 - (instruments[i].mod_volume & 63)); inst[i].data[9] |= ((instruments[i].mod_ksl & 3) << 6); inst[i].data[1] = (instruments[i].mod_freq_multi & 15); inst[i].data[7] = (instruments[i].mod_waveform & 3); inst[i].data[1] |= ((instruments[i].mod_sustain_sound & 1) << 5); inst[i].data[1] |= ((instruments[i].mod_ksr & 1) << 4); inst[i].data[1] |= ((instruments[i].mod_vibrato & 1) << 6); inst[i].data[1] |= ((instruments[i].mod_tremolo & 1) << 7); inst[i].data[4] = ((instruments[i].car_attack & 15) << 4); inst[i].data[4] |= (instruments[i].car_decay & 15); inst[i].data[6] = ((15 - (instruments[i].car_sustain & 15)) << 4); inst[i].data[6] |= (instruments[i].car_release & 15); inst[i].data[10] = (63 - (instruments[i].car_volume & 63)); inst[i].data[10] |= ((instruments[i].car_ksl & 3) << 6); inst[i].data[2] = (instruments[i].car_freq_multi & 15); inst[i].data[8] = (instruments[i].car_waveform & 3); inst[i].data[2] |= ((instruments[i].car_sustain_sound & 1) << 5); inst[i].data[2] |= ((instruments[i].car_ksr & 1) << 4); inst[i].data[2] |= ((instruments[i].car_vibrato & 1) << 6); inst[i].data[2] |= ((instruments[i].car_tremolo & 1) << 7); inst[i].slide = instruments[i].pitch_shift; } <commit_msg>Fix division by zero and unterminated strings in CfmcLoader::load()<commit_after>/* Adplug - Replayer for many OPL2/OPL3 audio file formats. Copyright (C) 1999 - 2007 Simon Peter <[email protected]>, et al. 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 fmc.cpp - FMC Loader by Riven the Mage <[email protected]> */ #include <cstring> #include "fmc.h" /* -------- Public Methods -------------------------------- */ CPlayer *CfmcLoader::factory(Copl *newopl) { return new CfmcLoader(newopl); } bool CfmcLoader::load(const std::string &filename, const CFileProvider &fp) { binistream *f = fp.open(filename); if(!f) return false; const unsigned char conv_fx[16] = {0,1,2,3,4,8,255,255,255,255,26,11,12,13,14,15}; int i,j,k,t=0; // read header f->readString(header.id, 4); f->readString(header.title, 21); header.title[20] = 0; header.numchan = f->readInt(1); // 'FMC!' - signed ? if (memcmp(header.id, "FMC!", 4) || header.numchan < 1 || header.numchan > 32) { fp.close(f); return false; } // init CmodPlayer realloc_instruments(32); realloc_order(256); realloc_patterns(64,64,header.numchan); init_trackord(); // load order for(i = 0; i < 256; i++) order[i] = f->readInt(1); f->ignore(2); // load instruments for(i = 0; i < 32; i++) { instruments[i].synthesis = f->readInt(1); instruments[i].feedback = f->readInt(1); instruments[i].mod_attack = f->readInt(1); instruments[i].mod_decay = f->readInt(1); instruments[i].mod_sustain = f->readInt(1); instruments[i].mod_release = f->readInt(1); instruments[i].mod_volume = f->readInt(1); instruments[i].mod_ksl = f->readInt(1); instruments[i].mod_freq_multi = f->readInt(1); instruments[i].mod_waveform = f->readInt(1); instruments[i].mod_sustain_sound = f->readInt(1); instruments[i].mod_ksr = f->readInt(1); instruments[i].mod_vibrato = f->readInt(1); instruments[i].mod_tremolo = f->readInt(1); instruments[i].car_attack = f->readInt(1); instruments[i].car_decay = f->readInt(1); instruments[i].car_sustain = f->readInt(1); instruments[i].car_release = f->readInt(1); instruments[i].car_volume = f->readInt(1); instruments[i].car_ksl = f->readInt(1); instruments[i].car_freq_multi = f->readInt(1); instruments[i].car_waveform = f->readInt(1); instruments[i].car_sustain_sound = f->readInt(1); instruments[i].car_ksr = f->readInt(1); instruments[i].car_vibrato = f->readInt(1); instruments[i].car_tremolo = f->readInt(1); instruments[i].pitch_shift = f->readInt(1); f->readString(instruments[i].name, 21); instruments[i].name[20] = 0; } // load tracks for (i=0;i<64;i++) { if(f->ateof()) break; for (j=0;j<header.numchan;j++) { for (k=0;k<64;k++) { fmc_event event; // read event event.byte0 = f->readInt(1); event.byte1 = f->readInt(1); event.byte2 = f->readInt(1); // convert event tracks[t][k].note = event.byte0 & 0x7F; tracks[t][k].inst = ((event.byte0 & 0x80) >> 3) + (event.byte1 >> 4) + 1; tracks[t][k].command = conv_fx[event.byte1 & 0x0F]; tracks[t][k].param1 = event.byte2 >> 4; tracks[t][k].param2 = event.byte2 & 0x0F; // fix effects if (tracks[t][k].command == 0x0E) // 0x0E (14): Retrig tracks[t][k].param1 = 3; if (tracks[t][k].command == 0x1A) { // 0x1A (26): Volume Slide if (tracks[t][k].param1 > tracks[t][k].param2) { tracks[t][k].param1 -= tracks[t][k].param2; tracks[t][k].param2 = 0; } else { tracks[t][k].param2 -= tracks[t][k].param1; tracks[t][k].param1 = 0; } } } t++; } } fp.close(f); // convert instruments for (i=0;i<31;i++) buildinst(i); // order length for (i=0;i<256;i++) { if (order[i] >= 0xFE) { length = i; break; } } // data for Protracker activechan = (0xffffffffUL >> (32 - header.numchan)) << (32 - header.numchan); nop = t / header.numchan; restartpos = 0; // flags flags = Faust; rewind(0); return true; } float CfmcLoader::getrefresh() { return 50.0f; } std::string CfmcLoader::gettype() { return std::string("Faust Music Creator"); } std::string CfmcLoader::gettitle() { return std::string(header.title); } std::string CfmcLoader::getinstrument(unsigned int n) { return n < 32 ? std::string(instruments[n].name) : std::string(); } unsigned int CfmcLoader::getinstruments() { return 32; } /* -------- Private Methods ------------------------------- */ void CfmcLoader::buildinst(unsigned char i) { inst[i].data[0] = ((instruments[i].synthesis & 1) ^ 1); inst[i].data[0] |= ((instruments[i].feedback & 7) << 1); inst[i].data[3] = ((instruments[i].mod_attack & 15) << 4); inst[i].data[3] |= (instruments[i].mod_decay & 15); inst[i].data[5] = ((15 - (instruments[i].mod_sustain & 15)) << 4); inst[i].data[5] |= (instruments[i].mod_release & 15); inst[i].data[9] = (63 - (instruments[i].mod_volume & 63)); inst[i].data[9] |= ((instruments[i].mod_ksl & 3) << 6); inst[i].data[1] = (instruments[i].mod_freq_multi & 15); inst[i].data[7] = (instruments[i].mod_waveform & 3); inst[i].data[1] |= ((instruments[i].mod_sustain_sound & 1) << 5); inst[i].data[1] |= ((instruments[i].mod_ksr & 1) << 4); inst[i].data[1] |= ((instruments[i].mod_vibrato & 1) << 6); inst[i].data[1] |= ((instruments[i].mod_tremolo & 1) << 7); inst[i].data[4] = ((instruments[i].car_attack & 15) << 4); inst[i].data[4] |= (instruments[i].car_decay & 15); inst[i].data[6] = ((15 - (instruments[i].car_sustain & 15)) << 4); inst[i].data[6] |= (instruments[i].car_release & 15); inst[i].data[10] = (63 - (instruments[i].car_volume & 63)); inst[i].data[10] |= ((instruments[i].car_ksl & 3) << 6); inst[i].data[2] = (instruments[i].car_freq_multi & 15); inst[i].data[8] = (instruments[i].car_waveform & 3); inst[i].data[2] |= ((instruments[i].car_sustain_sound & 1) << 5); inst[i].data[2] |= ((instruments[i].car_ksr & 1) << 4); inst[i].data[2] |= ((instruments[i].car_vibrato & 1) << 6); inst[i].data[2] |= ((instruments[i].car_tremolo & 1) << 7); inst[i].slide = instruments[i].pitch_shift; } <|endoftext|>
<commit_before>#include "desktop_media_manager.h" #include <cassert> DesktopMediaManager::DesktopMediaManager(const std::string& hostname) : hostname_(hostname), format_() { } void DesktopMediaManager::Play() { assert(gst_pipeline_); gst_pipeline_->SetState(GST_STATE_PLAYING); } void DesktopMediaManager::Pause() { assert(gst_pipeline_); gst_pipeline_->SetState(GST_STATE_PAUSED); } void DesktopMediaManager::Teardown() { if (gst_pipeline_) gst_pipeline_->SetState(GST_STATE_READY); } bool DesktopMediaManager::IsPaused() const { return (gst_pipeline_->GetState() != GST_STATE_PLAYING); } void DesktopMediaManager::SetSinkRtpPorts(int port1, int port2) { sink_port1_ = port1; sink_port2_ = port2; gst_pipeline_.reset(new MiracGstTestSource(WFD_DESKTOP, hostname_, port1)); gst_pipeline_->SetState(GST_STATE_READY); } std::pair<int, int> DesktopMediaManager::SinkRtpPorts() const { return std::pair<int, int>(sink_port1_, sink_port2_); } int DesktopMediaManager::SourceRtpPort() const { return gst_pipeline_->UdpSourcePort(); } std::vector<wfd::SelectableH264VideoFormat> DesktopMediaManager::GetSelectableH264VideoFormats() const { return {wfd::SelectableH264VideoFormat()}; } bool DesktopMediaManager::SetOptimalFormat( const wfd::SelectableH264VideoFormat& optimal_format) { format_ = optimal_format; return true; } wfd::SelectableH264VideoFormat DesktopMediaManager::GetOptimalFormat() const { return format_; } <commit_msg>Make gstreamer source support full set of resolutions<commit_after>#include "desktop_media_manager.h" #include <cassert> DesktopMediaManager::DesktopMediaManager(const std::string& hostname) : hostname_(hostname), format_() { } void DesktopMediaManager::Play() { assert(gst_pipeline_); gst_pipeline_->SetState(GST_STATE_PLAYING); } void DesktopMediaManager::Pause() { assert(gst_pipeline_); gst_pipeline_->SetState(GST_STATE_PAUSED); } void DesktopMediaManager::Teardown() { if (gst_pipeline_) gst_pipeline_->SetState(GST_STATE_READY); } bool DesktopMediaManager::IsPaused() const { return (gst_pipeline_->GetState() != GST_STATE_PLAYING); } void DesktopMediaManager::SetSinkRtpPorts(int port1, int port2) { sink_port1_ = port1; sink_port2_ = port2; gst_pipeline_.reset(new MiracGstTestSource(WFD_DESKTOP, hostname_, port1)); gst_pipeline_->SetState(GST_STATE_READY); } std::pair<int, int> DesktopMediaManager::SinkRtpPorts() const { return std::pair<int, int>(sink_port1_, sink_port2_); } int DesktopMediaManager::SourceRtpPort() const { return gst_pipeline_->UdpSourcePort(); } std::vector<wfd::SelectableH264VideoFormat> DesktopMediaManager::GetSelectableH264VideoFormats() const { std::vector<wfd::SelectableH264VideoFormat> formats; wfd::RateAndResolution i; for (i = wfd::CEA640x480p60; i <= wfd::CEA1920x1080p24; i = i + 1) formats.push_back(wfd::SelectableH264VideoFormat(wfd::CHP, wfd::k4_2, wfd::CEARatesAndResolutions(i))); for (i = wfd::VESA800x600p30; i <= wfd::VESA1920x1200p30; i = i + 1) formats.push_back(wfd::SelectableH264VideoFormat(wfd::CHP, wfd::k4_2, wfd::VESARatesAndResolutions(i))); for (i = wfd::HH800x480p30; i <= wfd::HH848x480p60; i = i + 1) formats.push_back(wfd::SelectableH264VideoFormat(wfd::CHP, wfd::k4_2, wfd::HHRatesAndResolutions(i))); return formats; } bool DesktopMediaManager::SetOptimalFormat( const wfd::SelectableH264VideoFormat& optimal_format) { format_ = optimal_format; return true; } wfd::SelectableH264VideoFormat DesktopMediaManager::GetOptimalFormat() const { return format_; } <|endoftext|>
<commit_before>#include "blockdevices.h" #include <list> #include <cxxutils/posix_helpers.h> #include <unistd.h> #if defined(__linux__) #include <linux/fs.h> #else // *BSD/Darwin #include <sys/disklabel.h> #include <sys/disk.h> #endif #include <arpa/inet.h> #ifndef DEVFS_PATH #define DEVFS_PATH "/dev" #endif #define EXT_MAGIC_NUMBER 0xEF53 #define EXT_COMPAT_FLAG_HAS_JOURNAL 0x00000004 #define EXT_INCOMPAT_FLAG_JOURNAL_DEV 0x00000008 #define EXT_BLOCK_COUNT_OFFSET (superblock + 0x04) #define EXT_BLOCK_SIZE_OFFSET (superblock + 0x18) #define EXT_MAGIC_NUMBER_OFFSET (superblock + 0x38) #define EXT_COMPAT_FLAGS_OFFSET (superblock + 0x5C) #define EXT_INCOMPAT_FLAGS_OFFSET (superblock + 0x60) #define EXT_UUID_OFFSET (superblock + 0x68) #define EXT_LABEL_OFFSET (superblock + 0x78) uint64_t read(posix::fd_t fd, off_t offset, uint8_t* buffer, uint64_t length) { if(::lseek(fd, offset, SEEK_SET) != offset) return 0; uint64_t remaining = length; ssize_t rval; for(uint8_t* pos = buffer; remaining > 0; pos += rval, remaining -= rval) rval = posix::read(fd, pos, remaining); return length - remaining; } #ifndef BLOCK_SIZE #define BLOCK_SIZE 0x400 #endif struct uintle16_t { uint8_t low; uint8_t high; constexpr operator uint16_t(void) const { return low + (high << 8); } }; static_assert(sizeof(uintle16_t) == sizeof(uint16_t), "naughty compiler!"); struct uintle32_t { uint8_t bottom; uint8_t low; uint8_t high; uint8_t top; constexpr operator uint32_t(void) const { return bottom + (low << 8) + (high << 16) + (top << 24); } }; static_assert(sizeof(uintle32_t) == sizeof(uint32_t), "naughty compiler!"); template<typename T> constexpr uint16_t get16(T* x) { return *reinterpret_cast<uint16_t*>(x); } template<typename T> constexpr uint32_t get32(T* x) { return *reinterpret_cast<uint32_t*>(x); } template<typename T> constexpr uint16_t getLE16(T* x) { return *reinterpret_cast<uintle16_t*>(x); } template<typename T> constexpr uint32_t getLE32(T* x) { return *reinterpret_cast<uintle32_t*>(x); } constexpr char uuid_digit(uint8_t* data, uint8_t digit) { return "0123456789ABCDEF"[(digit & 1) ? (data[digit/2] & 0x0F) : (data[digit/2] >> 4)]; } static bool uuid_matches(const char* str, uint8_t* data) { size_t length = std::strlen(str); for(uint8_t digit = 0; digit < 32; ++digit, ++str) { if(!std::isxdigit(*str)) { --length; ++str; } if(digit >= length || std::toupper(*str) != uuid_digit(data, digit)) return false; } return true; } /* static void uuid_decode(uint8_t* data, std::string& uuid) { for(uint8_t digit = 0; digit < 32; ++digit) uuid.push_back(uuid_digit(data, digit)); } */ namespace blockdevices { static std::list<blockdevice_t> devices; void detect(void); #if defined(WANT_PROCFS) void init(const char* procfs_path) { devices.clear(); char filename[PATH_MAX] = { 0 }; std::strcpy(filename, procfs_path); std::strcat(filename, "/partitions"); std::FILE* file = posix::fopen(filename, "r"); if(file == nullptr) return; posix::ssize_t count = 0; posix::size_t size = 0; char* line = nullptr; char* begin = nullptr; while((count = ::getline(&line, &size, file)) != posix::error_response) { char* pos = line; if(!std::isspace(*pos)) // if line doesn't start with a space then it's not an entry! continue; while(*pos && std::isspace(*pos)) ++pos; while(*pos && std::isdigit(*pos)) ++pos; while(*pos && std::isspace(*pos)) ++pos; while(*pos && std::isdigit(*pos)) ++pos; while(*pos && std::isspace(*pos)) ++pos; while(*pos && std::isdigit(*pos)) ++pos; while(*pos && std::isspace(*pos)) ++pos; if(!*pos) // if at end of line, skip continue; // read device name blockdevice_t dev; std::strcpy(dev.path, DEVFS_PATH); std::strcat(dev.path, "/"); for(char* field = dev.path + std::strlen(dev.path); *pos && pos < dev.path + sizeof(blockdevice_t::path) && std::isgraph(*pos); ++pos, ++field) *field = *pos; { devices.emplace_back(dev); } } ::free(line); // use C free() because we're using C getline() line = nullptr; posix::fclose(file); detect(); } #else void init(void) { #pragma message("Code needed to detect GEOM devices like gpart@") detect(); } #endif blockdevice_t* lookupByPath(const char* path) noexcept // finds device based on absolute path { for(blockdevice_t& dev : devices) if(!std::strcmp(path, dev.path)) return &dev; return nullptr; } blockdevice_t* lookupByUUID(const char* uuid) noexcept // finds device based on uuid { for(blockdevice_t& dev : devices) if(uuid_matches(uuid, dev.uuid)) return &dev; return nullptr; } blockdevice_t* lookupByLabel(const char* label) noexcept // finds device based on label { for(blockdevice_t& dev : devices) if(!std::strcmp(label, dev.label)) return &dev; return nullptr; } blockdevice_t* lookup(const char* id) { for(blockdevice_t& dev : devices) { if(!std::strcmp(id, dev.label) || !std::strcmp(id, dev.path) || uuid_matches(id, dev.uuid)) return &dev; } return nullptr; } void detect(void) { uint8_t superblock[BLOCK_SIZE]; uint32_t blocksize; uint64_t blockcount; for(blockdevice_t& dev : devices) { posix::fd_t fd = posix::open(dev.path, O_RDONLY); dev.size = 0; if(fd != posix::error_response) { #if defined(BLKGETSIZE64) // Linux 2.6+ posix::ioctl(fd, BLKGETSIZE64, &dev.size); #elif defined(DKIOCGETBLOCKCOUNT) // Darwin blocksize = 0; blockcount = 0; if(posix::ioctl(fd, DKIOCGETBLOCKSIZE , &blocksize ) > posix::error_response && posix::ioctl(fd, DKIOCGETBLOCKCOUNT, &blockcount) > posix::error_response) dev.size = blockcount * blocksize; #elif defined(DIOCGMEDIASIZE) // current BSD posix::ioctl(fd, DIOCGMEDIASIZE, &dev.size); #elif defined(DIOCGDINFO) // old BSD struct disklabel info; if(posix::ioctl(fd, DIOCGDINFO, &info) > posix::error_response) dev.size = info.d_ncylinders * info.d_secpercyl * info.d_secsize; #else dev.size = ::lseek(fd, 0, SEEK_END); // behavior not defined in POSIX for devices but try as a last resort #pragma message("No device interface defined for this operating system. Please add one to device.cpp!") #endif } std::memset(superblock, 0, BLOCK_SIZE); if(read(fd, BLOCK_SIZE, superblock, BLOCK_SIZE) == BLOCK_SIZE) // if read filesystem superblock { // see "struct ext2_super_block" in https://github.com/torvalds/linux/blob/master/fs/ext2/ext2.h // see "struct ext4_super_block" in https://github.com/torvalds/linux/blob/master/fs/ext4/ext4.h // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout#The_Super_Block if(getLE16(EXT_MAGIC_NUMBER_OFFSET) == EXT_MAGIC_NUMBER) // test if Ext2/3/4 { blockcount = getLE32(EXT_BLOCK_COUNT_OFFSET); blocksize = BLOCK_SIZE << getLE32(EXT_BLOCK_SIZE_OFFSET); //if(get32(EXT_INCOMPAT_FLAGS_OFFSET) & EXT_INCOMPAT_FLAG_JOURNAL_DEV) if(getLE32(EXT_COMPAT_FLAGS_OFFSET) & EXT_COMPAT_FLAG_HAS_JOURNAL) std::strcpy(dev.fstype, "ext3"); else std::strcpy(dev.fstype, "ext2"); std::memcpy(dev.uuid, EXT_UUID_OFFSET, 16); std::strncpy(dev.label, (const char*)EXT_LABEL_OFFSET, 16); } } /* std::string uuid; uuid_decode(dev.uuid, uuid); printf("PATH: %s - UUID: %s - LABEL: %s - filesystem: %s - size: %lu\n", dev.path, uuid.c_str(), dev.label, dev.fstype, dev.size); */ } // for each device } // end detect() } // end namespace <commit_msg>detects EXT based partitions<commit_after>#include "blockdevices.h" #include <list> #include <cxxutils/posix_helpers.h> #include <unistd.h> #if defined(__linux__) #include <linux/fs.h> #else // *BSD/Darwin #include <sys/disklabel.h> #include <sys/disk.h> #endif #include <arpa/inet.h> #ifndef DEVFS_PATH #define DEVFS_PATH "/dev" #endif #define EXT_MAGIC_NUMBER 0xEF53 #define EXT_COMPAT_FLAG_HAS_JOURNAL 0x00000004 #define EXT_INCOMPAT_FLAG_JOURNAL_DEV 0x00000008 /* for s_flags */ #define EXT_FLAGS_TEST_FILESYS 0x0004 /* for s_feature_compat */ #define EXT3_FEATURE_COMPAT_HAS_JOURNAL 0x0004 /* for s_feature_ro_compat */ #define EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER 0x0001 #define EXT2_FEATURE_RO_COMPAT_LARGE_FILE 0x0002 #define EXT2_FEATURE_RO_COMPAT_BTREE_DIR 0x0004 #define EXT4_FEATURE_RO_COMPAT_HUGE_FILE 0x0008 #define EXT4_FEATURE_RO_COMPAT_GDT_CSUM 0x0010 #define EXT4_FEATURE_RO_COMPAT_DIR_NLINK 0x0020 #define EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE 0x0040 /* for s_feature_incompat */ #define EXT2_FEATURE_INCOMPAT_FILETYPE 0x0002 #define EXT3_FEATURE_INCOMPAT_RECOVER 0x0004 #define EXT3_FEATURE_INCOMPAT_JOURNAL_DEV 0x0008 #define EXT2_FEATURE_INCOMPAT_META_BG 0x0010 #define EXT4_FEATURE_INCOMPAT_EXTENTS 0x0040 // extents support #define EXT4_FEATURE_INCOMPAT_64BIT 0x0080 #define EXT4_FEATURE_INCOMPAT_MMP 0x0100 #define EXT4_FEATURE_INCOMPAT_FLEX_BG 0x0200 #define EXT2_FEATURE_RO_COMPAT_SUPP (EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER | EXT2_FEATURE_RO_COMPAT_LARGE_FILE | EXT2_FEATURE_RO_COMPAT_BTREE_DIR) #define EXT2_FEATURE_INCOMPAT_SUPP (EXT2_FEATURE_INCOMPAT_FILETYPE | EXT2_FEATURE_INCOMPAT_META_BG) #define EXT2_FEATURE_INCOMPAT_UNSUPPORTED ~EXT2_FEATURE_INCOMPAT_SUPP #define EXT2_FEATURE_RO_COMPAT_UNSUPPORTED ~EXT2_FEATURE_RO_COMPAT_SUPP #define EXT3_FEATURE_RO_COMPAT_SUPP (EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER | EXT2_FEATURE_RO_COMPAT_LARGE_FILE | EXT2_FEATURE_RO_COMPAT_BTREE_DIR) #define EXT3_FEATURE_INCOMPAT_SUPP (EXT2_FEATURE_INCOMPAT_FILETYPE | EXT3_FEATURE_INCOMPAT_RECOVER | EXT2_FEATURE_INCOMPAT_META_BG) #define EXT3_FEATURE_INCOMPAT_UNSUPPORTED ~EXT3_FEATURE_INCOMPAT_SUPP #define EXT3_FEATURE_RO_COMPAT_UNSUPPORTED ~EXT3_FEATURE_RO_COMPAT_SUPP #define EXT_BLOCK_COUNT_OFFSET (superblock + 0x0004) #define EXT_BLOCK_SIZE_OFFSET (superblock + 0x0018) #define EXT_MAGIC_NUMBER_OFFSET (superblock + 0x0038) #define EXT_COMPAT_FLAGS_OFFSET (superblock + 0x005C) // s_feature_compat #define EXT_INCOMPAT_FLAGS_OFFSET (superblock + 0x0060) // s_feature_incompat #define EXT_RO_COMPAT_FLAGS_OFFSET (superblock + 0x0064) // s_feature_ro_compat #define EXT_UUID_OFFSET (superblock + 0x0068) // s_uuid[16] #define EXT_LABEL_OFFSET (superblock + 0x0078) // s_volume_name[16] #define EXT_MISC_FLAGS_OFFSET (superblock + 0x0160) // s_flags uint64_t read(posix::fd_t fd, off_t offset, uint8_t* buffer, uint64_t length) { if(::lseek(fd, offset, SEEK_SET) != offset) return 0; uint64_t remaining = length; ssize_t rval; for(uint8_t* pos = buffer; remaining > 0; pos += rval, remaining -= rval) rval = posix::read(fd, pos, remaining); return length - remaining; } #ifndef BLOCK_SIZE #define BLOCK_SIZE 0x400 #endif struct uintle16_t { uint8_t low; uint8_t high; constexpr operator uint16_t(void) const { return low + (high << 8); } }; static_assert(sizeof(uintle16_t) == sizeof(uint16_t), "naughty compiler!"); struct uintle32_t { uint8_t bottom; uint8_t low; uint8_t high; uint8_t top; constexpr operator uint32_t(void) const { return bottom + (low << 8) + (high << 16) + (top << 24); } }; static_assert(sizeof(uintle32_t) == sizeof(uint32_t), "naughty compiler!"); template<typename T> constexpr uint16_t get16(T* x) { return *reinterpret_cast<uint16_t*>(x); } template<typename T> constexpr uint32_t get32(T* x) { return *reinterpret_cast<uint32_t*>(x); } template<typename T> constexpr uint16_t getLE16(T* x) { return *reinterpret_cast<uintle16_t*>(x); } template<typename T> constexpr uint32_t getLE32(T* x) { return *reinterpret_cast<uintle32_t*>(x); } template<typename T> constexpr uint32_t flagsSet(T addr, uint32_t flags) { return getLE32(addr) & flags; } template<typename T> constexpr bool flagsAreSet(T addr, uint32_t flags) { return flagsSet(addr, flags) == flags; } template<typename T> constexpr bool flagsNotSet(T addr, uint32_t flags) { return !flagsSet(addr, flags); } constexpr char uuid_digit(uint8_t* data, uint8_t digit) { return "0123456789ABCDEF"[(digit & 1) ? (data[digit/2] & 0x0F) : (data[digit/2] >> 4)]; } static bool uuid_matches(const char* str, uint8_t* data) { size_t length = std::strlen(str); for(uint8_t digit = 0; digit < 32; ++digit, ++str) { if(!std::isxdigit(*str)) { --length; ++str; } if(digit >= length || std::toupper(*str) != uuid_digit(data, digit)) return false; } return true; } /* static void uuid_decode(uint8_t* data, std::string& uuid) { for(uint8_t digit = 0; digit < 32; ++digit) uuid.push_back(uuid_digit(data, digit)); } */ namespace blockdevices { static std::list<blockdevice_t> devices; void detect(void); #if defined(WANT_PROCFS) void init(const char* procfs_path) { devices.clear(); char filename[PATH_MAX] = { 0 }; std::strcpy(filename, procfs_path); std::strcat(filename, "/partitions"); std::FILE* file = posix::fopen(filename, "r"); if(file == nullptr) return; posix::ssize_t count = 0; posix::size_t size = 0; char* line = nullptr; char* begin = nullptr; while((count = ::getline(&line, &size, file)) != posix::error_response) { char* pos = line; if(!std::isspace(*pos)) // if line doesn't start with a space then it's not an entry! continue; while(*pos && std::isspace(*pos)) ++pos; while(*pos && std::isdigit(*pos)) ++pos; while(*pos && std::isspace(*pos)) ++pos; while(*pos && std::isdigit(*pos)) ++pos; while(*pos && std::isspace(*pos)) ++pos; while(*pos && std::isdigit(*pos)) ++pos; while(*pos && std::isspace(*pos)) ++pos; if(!*pos) // if at end of line, skip continue; // read device name blockdevice_t dev; std::strcpy(dev.path, DEVFS_PATH); std::strcat(dev.path, "/"); for(char* field = dev.path + std::strlen(dev.path); *pos && pos < dev.path + sizeof(blockdevice_t::path) && std::isgraph(*pos); ++pos, ++field) *field = *pos; { devices.emplace_back(dev); } } ::free(line); // use C free() because we're using C getline() line = nullptr; posix::fclose(file); detect(); } #else void init(void) { #pragma message("Code needed to detect GEOM devices like gpart@") detect(); } #endif blockdevice_t* lookupByPath(const char* path) noexcept // finds device based on absolute path { for(blockdevice_t& dev : devices) if(!std::strcmp(path, dev.path)) return &dev; return nullptr; } blockdevice_t* lookupByUUID(const char* uuid) noexcept // finds device based on uuid { for(blockdevice_t& dev : devices) if(uuid_matches(uuid, dev.uuid)) return &dev; return nullptr; } blockdevice_t* lookupByLabel(const char* label) noexcept // finds device based on label { for(blockdevice_t& dev : devices) if(!std::strcmp(label, dev.label)) return &dev; return nullptr; } blockdevice_t* lookup(const char* id) { for(blockdevice_t& dev : devices) { if(!std::strcmp(id, dev.label) || !std::strcmp(id, dev.path) || uuid_matches(id, dev.uuid)) return &dev; } return nullptr; } void detect(void) { uint8_t superblock[BLOCK_SIZE]; uint32_t blocksize; uint64_t blockcount; for(blockdevice_t& dev : devices) { posix::fd_t fd = posix::open(dev.path, O_RDONLY); dev.size = 0; if(fd != posix::error_response) { #if defined(BLKGETSIZE64) // Linux 2.6+ posix::ioctl(fd, BLKGETSIZE64, &dev.size); #elif defined(DKIOCGETBLOCKCOUNT) // Darwin blocksize = 0; blockcount = 0; if(posix::ioctl(fd, DKIOCGETBLOCKSIZE , &blocksize ) > posix::error_response && posix::ioctl(fd, DKIOCGETBLOCKCOUNT, &blockcount) > posix::error_response) dev.size = blockcount * blocksize; #elif defined(DIOCGMEDIASIZE) // current BSD posix::ioctl(fd, DIOCGMEDIASIZE, &dev.size); #elif defined(DIOCGDINFO) // old BSD struct disklabel info; if(posix::ioctl(fd, DIOCGDINFO, &info) > posix::error_response) dev.size = info.d_ncylinders * info.d_secpercyl * info.d_secsize; #else dev.size = ::lseek(fd, 0, SEEK_END); // behavior not defined in POSIX for devices but try as a last resort #pragma message("No device interface defined for this operating system. Please add one to device.cpp!") #endif } std::memset(superblock, 0, BLOCK_SIZE); if(read(fd, BLOCK_SIZE, superblock, BLOCK_SIZE) == BLOCK_SIZE) // if read filesystem superblock { // see "struct ext2_super_block" in https://github.com/torvalds/linux/blob/master/fs/ext2/ext2.h // see "struct ext4_super_block" in https://github.com/torvalds/linux/blob/master/fs/ext4/ext4.h // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout#The_Super_Block if(getLE16(EXT_MAGIC_NUMBER_OFFSET) == EXT_MAGIC_NUMBER) // test if Ext2/3/4 { blockcount = getLE32(EXT_BLOCK_COUNT_OFFSET); blocksize = BLOCK_SIZE << getLE32(EXT_BLOCK_SIZE_OFFSET); if(flagsAreSet(EXT_INCOMPAT_FLAGS_OFFSET , EXT3_FEATURE_INCOMPAT_JOURNAL_DEV)) std::strcpy(dev.fstype, "jbd"); if(flagsNotSet(EXT_INCOMPAT_FLAGS_OFFSET , EXT3_FEATURE_INCOMPAT_JOURNAL_DEV) && flagsAreSet(EXT_MISC_FLAGS_OFFSET , EXT_FLAGS_TEST_FILESYS)) std::strcpy(dev.fstype, "ext4dev"); if(flagsNotSet(EXT_INCOMPAT_FLAGS_OFFSET , EXT3_FEATURE_INCOMPAT_JOURNAL_DEV) && (flagsSet(EXT_RO_COMPAT_FLAGS_OFFSET, EXT3_FEATURE_RO_COMPAT_UNSUPPORTED) || flagsSet(EXT_INCOMPAT_FLAGS_OFFSET , EXT3_FEATURE_INCOMPAT_UNSUPPORTED)) && flagsNotSet(EXT_MISC_FLAGS_OFFSET , EXT_FLAGS_TEST_FILESYS)) std::strcpy(dev.fstype, "ext4"); if(flagsAreSet(EXT_COMPAT_FLAGS_OFFSET , EXT3_FEATURE_COMPAT_HAS_JOURNAL) && flagsNotSet(EXT_RO_COMPAT_FLAGS_OFFSET , EXT3_FEATURE_RO_COMPAT_UNSUPPORTED) && flagsNotSet(EXT_INCOMPAT_FLAGS_OFFSET , EXT3_FEATURE_INCOMPAT_UNSUPPORTED)) std::strcpy(dev.fstype, "ext3"); if(flagsNotSet(EXT_COMPAT_FLAGS_OFFSET , EXT3_FEATURE_COMPAT_HAS_JOURNAL) && flagsNotSet(EXT_RO_COMPAT_FLAGS_OFFSET , EXT2_FEATURE_RO_COMPAT_UNSUPPORTED) && flagsNotSet(EXT_INCOMPAT_FLAGS_OFFSET , EXT2_FEATURE_INCOMPAT_UNSUPPORTED)) std::strcpy(dev.fstype, "ext2"); std::memcpy(dev.uuid, EXT_UUID_OFFSET, 16); std::strncpy(dev.label, (const char*)EXT_LABEL_OFFSET, 16); } else if(true) // test other filesystem type { } } } // for each device } // end detect() } // end namespace <|endoftext|>
<commit_before>#ifndef DISSENT_CRYPTO_CPP_DSA_LIBRARY_H_GUARD #define DISSENT_CRYPTO_CPP_DSA_LIBRARY_H_GUARD #include "CppDiffieHellman.hpp" #include "CppHash.hpp" #include "CppIntegerData.hpp" #include "CppRandom.hpp" #include "CppDsaPrivateKey.hpp" #include "CppDsaPublicKey.hpp" #include "Library.hpp" namespace Dissent { namespace Crypto { class CppDsaLibrary : public Library { public: /** * Load a public key from a file */ inline virtual AsymmetricKey *LoadPublicKeyFromFile(const QString &filename) { return new CppDsaPublicKey(filename); } /** * Loading a public key from a byte array */ inline virtual AsymmetricKey *LoadPublicKeyFromByteArray(const QByteArray &data) { return new CppDsaPublicKey(data); } /** * Generate a public key using the given data as a seed to a RNG */ inline virtual AsymmetricKey *GeneratePublicKey(const QByteArray &seed) { return CppDsaPublicKey::GenerateKey(seed); } /** * Load a private key from a file */ inline virtual AsymmetricKey *LoadPrivateKeyFromFile(const QString &filename) { return new CppDsaPrivateKey(filename); } /** * Loading a private key from a byte array */ inline virtual AsymmetricKey *LoadPrivateKeyFromByteArray(const QByteArray &data) { return new CppDsaPrivateKey(data); } /** * Generate a private key using the given data as a seed to a RNG */ inline virtual AsymmetricKey *GeneratePrivateKey(const QByteArray &seed) { return CppDsaPrivateKey::GenerateKey(seed); } /** * Generates a unique (new) private key */ inline virtual AsymmetricKey *CreatePrivateKey() { return new CppDsaPrivateKey(); } /** * Returns the minimum asymmetric key size */ inline virtual int MinimumKeySize() const { return CppDsaPublicKey::GetMinimumKeySize(); } /** * Returns a deterministic random number generator */ inline virtual Dissent::Utils::Random *GetRandomNumberGenerator(const QByteArray &seed, uint index) { return new CppRandom(seed, index); } inline virtual uint RngOptimalSeedSize() { return CppRandom::OptimalSeedSize(); } /** * Returns a hash algorithm */ inline virtual Hash *GetHashAlgorithm() { return new CppHash(); } /** * Returns an integer data */ inline virtual IntegerData *GetIntegerData(int value) { return new CppIntegerData(value); } /** * Returns an integer data */ inline virtual IntegerData *GetIntegerData(const QByteArray &value) { return new CppIntegerData(value); } /** * Returns an integer data */ inline virtual IntegerData *GetIntegerData(const QString &value) { return new CppIntegerData(value); } /** * returns a random integer data * @param bit_count the amount of bits in the integer * @param mod the modulus of the integer * @param prime if the integer should be prime */ virtual IntegerData *GetRandomInteger(int bit_count, const IntegerData *mod, bool prime) { return CppIntegerData::GetRandomInteger(bit_count, mod, prime); } /** * Returns a DiffieHellman operator */ virtual DiffieHellman *CreateDiffieHellman() { return new CppDiffieHellman(); } /** * Generate a DiffieHellman operator using the given data as a seed to a RNG * @param seed seed used to generate the DiffieHellman exchange */ virtual DiffieHellman *GenerateDiffieHellman(const QByteArray &seed) { return new CppDiffieHellman(seed, true); } /** * Loads a DiffieHellman key from a byte array * @param private_component the private component in the DH exchange */ virtual DiffieHellman *LoadDiffieHellman(const QByteArray &private_component) { return new CppDiffieHellman(private_component); } }; } } #endif <commit_msg>[Crypto] simplified the DSA library<commit_after>#ifndef DISSENT_CRYPTO_CPP_DSA_LIBRARY_H_GUARD #define DISSENT_CRYPTO_CPP_DSA_LIBRARY_H_GUARD #include "CppDiffieHellman.hpp" #include "CppHash.hpp" #include "CppIntegerData.hpp" #include "CppRandom.hpp" #include "CppDsaPrivateKey.hpp" #include "CppDsaPublicKey.hpp" #include "CppLibrary.hpp" namespace Dissent { namespace Crypto { class CppDsaLibrary : public CppLibrary { public: /** * Load a public key from a file */ inline virtual AsymmetricKey *LoadPublicKeyFromFile(const QString &filename) { return new CppDsaPublicKey(filename); } /** * Loading a public key from a byte array */ inline virtual AsymmetricKey *LoadPublicKeyFromByteArray(const QByteArray &data) { return new CppDsaPublicKey(data); } /** * Generate a public key using the given data as a seed to a RNG */ inline virtual AsymmetricKey *GeneratePublicKey(const QByteArray &seed) { return CppDsaPublicKey::GenerateKey(seed); } /** * Load a private key from a file */ inline virtual AsymmetricKey *LoadPrivateKeyFromFile(const QString &filename) { return new CppDsaPrivateKey(filename); } /** * Loading a private key from a byte array */ inline virtual AsymmetricKey *LoadPrivateKeyFromByteArray(const QByteArray &data) { return new CppDsaPrivateKey(data); } /** * Generate a private key using the given data as a seed to a RNG */ inline virtual AsymmetricKey *GeneratePrivateKey(const QByteArray &seed) { return CppDsaPrivateKey::GenerateKey(seed); } /** * Generates a unique (new) private key */ inline virtual AsymmetricKey *CreatePrivateKey() { return new CppDsaPrivateKey(); } /** * Returns the minimum asymmetric key size */ inline virtual int MinimumKeySize() const { return CppDsaPublicKey::GetMinimumKeySize(); } }; } } #endif <|endoftext|>
<commit_before>#include <vtkSmartPointer.h> #include <vtkFillHolesFilter.h> #include <vtkPolyDataNormals.h> #include <vtkCleanPolyData.h> #include <vtkSelectionNode.h> #include <vtkInformation.h> #include <vtkUnstructuredGrid.h> #include <vtkPolyData.h> #include <vtkPointData.h> #include <vtkOBJReader.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkSelection.h> #include <vtkSelectionNode.h> #include <vtkSphereSource.h> #include <vtkPolyDataMapper.h> #include <vtkActor.h> #include <vtkCamera.h> #include <vtkProperty.h> #include <vtkIdTypeArray.h> #include <vtkExtractSelection.h> #include <vtkDataSetSurfaceFilter.h> #include <vtkNamedColors.h> static void GenerateData(vtkPolyData*); int main(int argc, char *argv[]) { vtkSmartPointer<vtkPolyData> input = vtkSmartPointer<vtkPolyData>::New(); if(argc == 1) { GenerateData(input); } else { std::string inputFilename = argv[1]; vtkSmartPointer<vtkOBJReader> reader = vtkSmartPointer<vtkOBJReader>::New(); reader->SetFileName(inputFilename.c_str()); reader->Update(); vtkSmartPointer<vtkCleanPolyData> clean = vtkSmartPointer<vtkCleanPolyData>::New(); clean->SetInputData(reader->GetOutput()); clean->Update(); input->ShallowCopy(clean->GetOutput()); } vtkSmartPointer<vtkNamedColors> colors = vtkSmartPointer<vtkNamedColors>::New(); vtkSmartPointer<vtkFillHolesFilter> fillHolesFilter = vtkSmartPointer<vtkFillHolesFilter>::New(); fillHolesFilter->SetInputData(input); fillHolesFilter->SetHoleSize(100000.0); fillHolesFilter->Update(); // Make the triangle winding order consistent vtkSmartPointer<vtkPolyDataNormals> normals = vtkSmartPointer<vtkPolyDataNormals>::New(); normals->SetInputData(fillHolesFilter->GetOutput()); normals->ConsistencyOn(); normals->SplittingOff(); normals->Update(); #if 0 // Restore the original normals normals->GetOutput()->GetPointData()-> SetNormals(input->GetPointData()->GetNormals()); #endif // Visualize // Define viewport ranges // (xmin, ymin, xmax, ymax) double leftViewport[4] = {0.0, 0.0, 0.5, 1.0}; double rightViewport[4] = {0.5, 0.0, 1.0, 1.0}; // Create a mapper and actor vtkSmartPointer<vtkPolyDataMapper> originalMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); originalMapper->SetInputData(input); vtkSmartPointer<vtkProperty> backfaceProp = vtkSmartPointer<vtkProperty>::New(); backfaceProp->SetDiffuseColor(colors->GetColor3d("Banana").GetData()); vtkSmartPointer<vtkActor> originalActor = vtkSmartPointer<vtkActor>::New(); originalActor->SetMapper(originalMapper); originalActor->SetBackfaceProperty(backfaceProp); originalActor->GetProperty()->SetDiffuseColor( colors->GetColor3d("Flesh").GetData()); vtkSmartPointer<vtkPolyDataMapper> filledMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); filledMapper->SetInputData(fillHolesFilter->GetOutput()); vtkSmartPointer<vtkActor> filledActor = vtkSmartPointer<vtkActor>::New(); filledActor->SetMapper(filledMapper); filledActor->GetProperty()->SetDiffuseColor( colors->GetColor3d("Flesh").GetData()); filledActor->SetBackfaceProperty(backfaceProp); // Create a renderer, render window, and interactor vtkSmartPointer<vtkRenderer> leftRenderer = vtkSmartPointer<vtkRenderer>::New(); leftRenderer->SetViewport(leftViewport); vtkSmartPointer<vtkRenderer> rightRenderer = vtkSmartPointer<vtkRenderer>::New(); rightRenderer->SetViewport(rightViewport); vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->SetSize(600,300); renderWindow->AddRenderer(leftRenderer); renderWindow->AddRenderer(rightRenderer); vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); renderWindowInteractor->SetRenderWindow(renderWindow); // Add the actor to the scene leftRenderer->AddActor(originalActor); rightRenderer->AddActor(filledActor); leftRenderer->SetBackground(colors->GetColor3d("PaleGreen").GetData()); leftRenderer->GetActiveCamera()->SetPosition(0, -1, 0); leftRenderer->GetActiveCamera()->SetFocalPoint(0, 0, 0); leftRenderer->GetActiveCamera()->SetViewUp(0, 0, 1); leftRenderer->GetActiveCamera()->Azimuth(30); leftRenderer->GetActiveCamera()->Elevation(30); leftRenderer->ResetCamera(); rightRenderer->SetBackground(colors->GetColor3d("LightGreen").GetData()); // Share the camera rightRenderer->SetActiveCamera(leftRenderer->GetActiveCamera()); // Render and interact renderWindow->Render(); renderWindowInteractor->Start(); return EXIT_SUCCESS; } void GenerateData(vtkPolyData* input) { // Create a sphere vtkSmartPointer<vtkSphereSource> sphereSource = vtkSmartPointer<vtkSphereSource>::New(); sphereSource->Update(); // Remove some cells vtkSmartPointer<vtkIdTypeArray> ids = vtkSmartPointer<vtkIdTypeArray>::New(); ids->SetNumberOfComponents(1); // Set values ids->InsertNextValue(2); ids->InsertNextValue(10); vtkSmartPointer<vtkSelectionNode> selectionNode = vtkSmartPointer<vtkSelectionNode>::New(); selectionNode->SetFieldType(vtkSelectionNode::CELL); selectionNode->SetContentType(vtkSelectionNode::INDICES); selectionNode->SetSelectionList(ids); selectionNode->GetProperties()->Set(vtkSelectionNode::INVERSE(), 1); //invert the selection vtkSmartPointer<vtkSelection> selection = vtkSmartPointer<vtkSelection>::New(); selection->AddNode(selectionNode); vtkSmartPointer<vtkExtractSelection> extractSelection = vtkSmartPointer<vtkExtractSelection>::New(); extractSelection->SetInputConnection(0, sphereSource->GetOutputPort()); extractSelection->SetInputData(1, selection); extractSelection->Update(); // In selection vtkSmartPointer<vtkDataSetSurfaceFilter> surfaceFilter = vtkSmartPointer<vtkDataSetSurfaceFilter>::New(); surfaceFilter->SetInputConnection(extractSelection->GetOutputPort()); surfaceFilter->Update(); input->ShallowCopy(surfaceFilter->GetOutput()); } <commit_msg>ENH: Add ReadPolyData<commit_after>#include <vtkSmartPointer.h> #include <vtkFillHolesFilter.h> #include <vtkPolyDataNormals.h> #include <vtkCleanPolyData.h> #include <vtkSelectionNode.h> #include <vtkInformation.h> #include <vtkUnstructuredGrid.h> #include <vtkPolyData.h> #include <vtkPointData.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkSelection.h> #include <vtkSelectionNode.h> #include <vtkSphereSource.h> #include <vtkPolyDataMapper.h> #include <vtkActor.h> #include <vtkCamera.h> #include <vtkProperty.h> #include <vtkIdTypeArray.h> #include <vtkExtractSelection.h> #include <vtkDataSetSurfaceFilter.h> #include <vtkBYUReader.h> #include <vtkOBJReader.h> #include <vtkPLYReader.h> #include <vtkPolyDataReader.h> #include <vtkSTLReader.h> #include <vtkXMLPolyDataReader.h> #include <vtkSphereSource.h> #include <vtksys/SystemTools.hxx> #include <vtkNamedColors.h> namespace { vtkSmartPointer<vtkPolyData> ReadPolyData(const char *fileName); } int main(int argc, char *argv[]) { vtkSmartPointer<vtkPolyData> input = ReadPolyData(argc > 1 ? argv[1] : ""); vtkSmartPointer<vtkNamedColors> colors = vtkSmartPointer<vtkNamedColors>::New(); vtkSmartPointer<vtkFillHolesFilter> fillHolesFilter = vtkSmartPointer<vtkFillHolesFilter>::New(); fillHolesFilter->SetInputData(input); fillHolesFilter->SetHoleSize(100000.0); fillHolesFilter->Update(); // Make the triangle winding order consistent vtkSmartPointer<vtkPolyDataNormals> normals = vtkSmartPointer<vtkPolyDataNormals>::New(); normals->SetInputData(fillHolesFilter->GetOutput()); normals->ConsistencyOn(); normals->SplittingOff(); normals->Update(); #if 0 // Restore the original normals normals->GetOutput()->GetPointData()-> SetNormals(input->GetPointData()->GetNormals()); #endif // Visualize // Define viewport ranges // (xmin, ymin, xmax, ymax) double leftViewport[4] = {0.0, 0.0, 0.5, 1.0}; double rightViewport[4] = {0.5, 0.0, 1.0, 1.0}; // Create a mapper and actor vtkSmartPointer<vtkPolyDataMapper> originalMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); originalMapper->SetInputData(input); vtkSmartPointer<vtkProperty> backfaceProp = vtkSmartPointer<vtkProperty>::New(); backfaceProp->SetDiffuseColor(colors->GetColor3d("Banana").GetData()); vtkSmartPointer<vtkActor> originalActor = vtkSmartPointer<vtkActor>::New(); originalActor->SetMapper(originalMapper); originalActor->SetBackfaceProperty(backfaceProp); originalActor->GetProperty()->SetDiffuseColor( colors->GetColor3d("Flesh").GetData()); vtkSmartPointer<vtkPolyDataMapper> filledMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); filledMapper->SetInputData(fillHolesFilter->GetOutput()); vtkSmartPointer<vtkActor> filledActor = vtkSmartPointer<vtkActor>::New(); filledActor->SetMapper(filledMapper); filledActor->GetProperty()->SetDiffuseColor( colors->GetColor3d("Flesh").GetData()); filledActor->SetBackfaceProperty(backfaceProp); // Create a renderer, render window, and interactor vtkSmartPointer<vtkRenderer> leftRenderer = vtkSmartPointer<vtkRenderer>::New(); leftRenderer->SetViewport(leftViewport); vtkSmartPointer<vtkRenderer> rightRenderer = vtkSmartPointer<vtkRenderer>::New(); rightRenderer->SetViewport(rightViewport); vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->SetSize(600,300); renderWindow->AddRenderer(leftRenderer); renderWindow->AddRenderer(rightRenderer); vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); renderWindowInteractor->SetRenderWindow(renderWindow); // Add the actor to the scene leftRenderer->AddActor(originalActor); rightRenderer->AddActor(filledActor); leftRenderer->SetBackground(colors->GetColor3d("PaleGreen").GetData()); leftRenderer->GetActiveCamera()->SetPosition(0, -1, 0); leftRenderer->GetActiveCamera()->SetFocalPoint(0, 0, 0); leftRenderer->GetActiveCamera()->SetViewUp(0, 0, 1); leftRenderer->GetActiveCamera()->Azimuth(30); leftRenderer->GetActiveCamera()->Elevation(30); leftRenderer->ResetCamera(); rightRenderer->SetBackground(colors->GetColor3d("LightGreen").GetData()); // Share the camera rightRenderer->SetActiveCamera(leftRenderer->GetActiveCamera()); // Render and interact renderWindow->Render(); renderWindowInteractor->Start(); return EXIT_SUCCESS; } void GenerateData(vtkPolyData* input) { // Create a sphere vtkSmartPointer<vtkSphereSource> sphereSource = vtkSmartPointer<vtkSphereSource>::New(); sphereSource->Update(); // Remove some cells vtkSmartPointer<vtkIdTypeArray> ids = vtkSmartPointer<vtkIdTypeArray>::New(); ids->SetNumberOfComponents(1); // Set values ids->InsertNextValue(2); ids->InsertNextValue(10); vtkSmartPointer<vtkSelectionNode> selectionNode = vtkSmartPointer<vtkSelectionNode>::New(); selectionNode->SetFieldType(vtkSelectionNode::CELL); selectionNode->SetContentType(vtkSelectionNode::INDICES); selectionNode->SetSelectionList(ids); selectionNode->GetProperties()->Set(vtkSelectionNode::INVERSE(), 1); //invert the selection vtkSmartPointer<vtkSelection> selection = vtkSmartPointer<vtkSelection>::New(); selection->AddNode(selectionNode); vtkSmartPointer<vtkExtractSelection> extractSelection = vtkSmartPointer<vtkExtractSelection>::New(); extractSelection->SetInputConnection(0, sphereSource->GetOutputPort()); extractSelection->SetInputData(1, selection); extractSelection->Update(); // In selection vtkSmartPointer<vtkDataSetSurfaceFilter> surfaceFilter = vtkSmartPointer<vtkDataSetSurfaceFilter>::New(); surfaceFilter->SetInputConnection(extractSelection->GetOutputPort()); surfaceFilter->Update(); input->ShallowCopy(surfaceFilter->GetOutput()); } // Snippets namespace { vtkSmartPointer<vtkPolyData> ReadPolyData(const char *fileName) { vtkSmartPointer<vtkPolyData> polyData; std::string extension = vtksys::SystemTools::GetFilenameExtension(std::string(fileName)); if (extension == ".ply") { vtkSmartPointer<vtkPLYReader> reader = vtkSmartPointer<vtkPLYReader>::New(); reader->SetFileName (fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".vtp") { vtkSmartPointer<vtkXMLPolyDataReader> reader = vtkSmartPointer<vtkXMLPolyDataReader>::New(); reader->SetFileName (fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".obj") { vtkSmartPointer<vtkOBJReader> reader = vtkSmartPointer<vtkOBJReader>::New(); reader->SetFileName (fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".stl") { vtkSmartPointer<vtkSTLReader> reader = vtkSmartPointer<vtkSTLReader>::New(); reader->SetFileName (fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".vtk") { vtkSmartPointer<vtkPolyDataReader> reader = vtkSmartPointer<vtkPolyDataReader>::New(); reader->SetFileName (fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".g") { vtkSmartPointer<vtkBYUReader> reader = vtkSmartPointer<vtkBYUReader>::New(); reader->SetGeometryFileName (fileName); reader->Update(); polyData = reader->GetOutput(); } else { vtkSmartPointer<vtkSphereSource> source = vtkSmartPointer<vtkSphereSource>::New(); source->Update(); polyData = source->GetOutput(); } return polyData; } } <|endoftext|>
<commit_before>// ========================================================================== // // This file is part of DO++, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2013 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/. // ========================================================================== // #ifndef DO_CORE_STATICASSERT_HPP #define DO_CORE_STATICASSERT_HPP //! @file //! \brief Implementation from: //! http://stackoverflow.com/questions/1980012/boost-static-assert-without-boost //! Concatenation macro used for the implementation of DO_STATIC_ASSERT. #define CAT(arg1, arg2) CAT1(arg1, arg2) #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CAT1(arg1, arg2) CAT2(arg1, arg2) #define CAT2(arg1, arg2) arg1##arg2 #endif /*! \ingroup Meta \brief Static assertion macro. \param expression a boolean expression \param message some error message Usage: DO_STATIC_ASSERT(expression, message); When the static assertion test fails, a compiler error message that somehow contains the "STATIC_ASSERTION_FAILED_AT_LINE_xxx_message" is generated. WARNING: message has to be a valid C++ identifier, that is to say it must not contain space characters, cannot start with a digit, etc. DO_STATIC_ASSERT(true, this_message_will_never_be_displayed); */ #define DO_STATIC_ASSERT(expression, message) \ struct CAT(__static_assertion_at_line_, __LINE__) \ { \ DO::Meta::StaticAssertion<static_cast<bool>((expression))> \ CAT(CAT(CAT(STATIC_ASSERTION_FAILED_AT_LINE_, __LINE__), _), message); \ }; \ typedef DO::Meta::StaticAssertionTest< \ sizeof(CAT(__static_assertion_at_line_, __LINE__)) > \ CAT(__static_assertion_test_at_line_, __LINE__) // Note that we wrap the non existing type inside a struct to avoid warning // messages about unused variables when static assertions are used at function // scope // the use of sizeof makes sure the assertion error is not ignored by SFINAE namespace DO { namespace Meta { //! Used for the implementation of DO_STATIC_ASSERT. template <bool> struct StaticAssertion; //! Used for the implementation of DO_STATIC_ASSERT. template <> struct StaticAssertion<true> {}; //! Used for the implementation of DO_STATIC_ASSERT. template<int i> struct StaticAssertionTest {}; } /* namespace Meta */ } /* namespace DO */ #endif /* DO_CORE_STATICASSERT_HPP */<commit_msg>Add a precision on the usage of DO_STATIC_ASSERT.<commit_after>// ========================================================================== // // This file is part of DO++, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2013 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/. // ========================================================================== // #ifndef DO_CORE_STATICASSERT_HPP #define DO_CORE_STATICASSERT_HPP //! @file //! \brief Implementation from: //! http://stackoverflow.com/questions/1980012/boost-static-assert-without-boost //! Concatenation macro used for the implementation of DO_STATIC_ASSERT. #define CAT(arg1, arg2) CAT1(arg1, arg2) #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CAT1(arg1, arg2) CAT2(arg1, arg2) #define CAT2(arg1, arg2) arg1##arg2 #endif /*! \ingroup Meta \brief Static assertion macro. \param expression a boolean expression \param message some error message Usage: DO_STATIC_ASSERT(expression, message); // **don't forget** the semi-colon! When the static assertion test fails, a compiler error message that somehow contains the "STATIC_ASSERTION_FAILED_AT_LINE_xxx_message" is generated. WARNING: message has to be a valid C++ identifier, that is to say it must not contain space characters, cannot start with a digit, etc. DO_STATIC_ASSERT(true, this_message_will_never_be_displayed); */ #define DO_STATIC_ASSERT(expression, message) \ struct CAT(__static_assertion_at_line_, __LINE__) \ { \ DO::Meta::StaticAssertion<static_cast<bool>((expression))> \ CAT(CAT(CAT(STATIC_ASSERTION_FAILED_AT_LINE_, __LINE__), _), message); \ } // Note that we wrap the non existing type inside a struct to avoid warning // messages about unused variables when static assertions are used at function // scope // the use of sizeof makes sure the assertion error is not ignored by SFINAE namespace DO { namespace Meta { //! Used for the implementation of DO_STATIC_ASSERT. template <bool> struct StaticAssertion; //! Used for the implementation of DO_STATIC_ASSERT. template <> struct StaticAssertion<true> {}; //! Used for the implementation of DO_STATIC_ASSERT. template<int i> struct StaticAssertionTest {}; } /* namespace Meta */ } /* namespace DO */ #endif /* DO_CORE_STATICASSERT_HPP */ <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbReciprocalHAlphaImageFilter.h" #include "otbSinclairReciprocalImageFilter.h" #include "otbSinclairToReciprocalCoherencyMatrixFunctor.h" #include "otbPerBandVectorImageFilter.h" #include "itkMeanImageFilter.h" namespace otb { namespace Wrapper { class SARDecompositions : public Application { public: /** Standard class typedefs. */ typedef SARDecompositions Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; typedef otb::Functor::SinclairToReciprocalCoherencyMatrixFunctor<ComplexFloatImageType::PixelType, ComplexFloatImageType::PixelType, ComplexFloatImageType::PixelType, ComplexFloatVectorImageType::PixelType> FunctorType; typedef SinclairReciprocalImageFilter<ComplexFloatImageType, ComplexFloatImageType, ComplexFloatImageType, ComplexFloatVectorImageType, FunctorType > SRFilterType; typedef otb::ReciprocalHAlphaImageFilter<ComplexFloatVectorImageType, FloatVectorImageType> HAFilterType; typedef itk::MeanImageFilter<ComplexFloatImageType, ComplexFloatImageType> MeanFilterType; typedef otb::PerBandVectorImageFilter<ComplexFloatVectorImageType, ComplexFloatVectorImageType, MeanFilterType> PerBandMeanFilterType; //FloatImageType /** Standard macro */ itkNewMacro(Self); itkTypeMacro(SARDecompositions, otb::Application); private: void DoInit() { SetName("SARDecompositions"); SetDescription("From one-band complex images (each one related to an element of the Sinclair matrix), returns the selected decomposition."); // Documentation SetDocName("SARDecompositions"); SetDocLongDescription("From one-band complex images (HH, HV, VH, VV), returns the selected decomposition.\n \n" "The H-alpha-A decomposition is currently the only one available; it is implemented for the monostatic case (transmitter and receiver are co-located).\n" "User must provide three one-band complex images HH, HV or VH, and VV (monostatic case <=> HV = VH).\n" "The H-alpha-A decomposition consists in averaging 3x3 complex coherency matrices (incoherent analysis); the user must provide the size of the averaging window, thanks to the parameter inco.kernelsize.\n " "The applications returns a float vector image, made up of three channels : H (entropy), Alpha, A (Anisotropy)." ); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso(""); AddDocTag(Tags::SAR); AddParameter(ParameterType_ComplexInputImage, "inhh", "Input Image"); SetParameterDescription("inhh", "Input image (HH)"); AddParameter(ParameterType_ComplexInputImage, "inhv", "Input Image"); SetParameterDescription("inhv", "Input image (HV)"); MandatoryOff("inhv"); AddParameter(ParameterType_ComplexInputImage, "invh", "Input Image"); SetParameterDescription("invh", "Input image (VH)"); MandatoryOff("invh"); AddParameter(ParameterType_ComplexInputImage, "invv", "Input Image"); SetParameterDescription("invv", "Input image (VV)"); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription("out", "Output image"); AddParameter(ParameterType_Choice, "decomp", "Decompositions"); AddChoice("decomp.haa","H-alpha-A decomposition"); SetParameterDescription("decomp.haa","H-alpha-A decomposition"); AddParameter(ParameterType_Group,"inco","Incoherent decompositions"); SetParameterDescription("inco","This group allows to set parameters related to the incoherent decompositions."); AddParameter(ParameterType_Int, "inco.kernelsize", "Kernel size for spatial incoherent averaging."); SetParameterDescription("inco.kernelsize", "Minute (0-59)"); SetMinimumParameterIntValue("inco.kernelsize", 1); SetDefaultParameterInt("inco.kernelsize", 3); MandatoryOff("inco.kernelsize"); AddRAMParameter(); // Default values SetDefaultParameterInt("decomp", 0); // H-alpha-A // Doc example parameter settings SetDocExampleParameterValue("inhh", "HH.tif"); SetDocExampleParameterValue("invh", "VH.tif"); SetDocExampleParameterValue("invv", "VV.tif"); SetDocExampleParameterValue("decomp", "haa"); SetDocExampleParameterValue("out", "HaA.tif"); } void DoUpdateParameters() { // Nothing to do here : all parameters are independent } void DoExecute() { bool inhv = HasUserValue("inhv"); bool invh = HasUserValue("invh"); if ( (!inhv) && (!invh) ) otbAppLogFATAL( << "Parameter inhv or invh not set. Please provide a HV or a VH complex image."); switch (GetParameterInt("decomp")) { case 0: // H-alpha-A m_SRFilter = SRFilterType::New(); m_HAFilter = HAFilterType::New(); m_MeanFilter = PerBandMeanFilterType::New(); if (inhv) m_SRFilter->SetInputHV_VH(GetParameterComplexFloatImage("inhv")); else if (invh) m_SRFilter->SetInputHV_VH(GetParameterComplexFloatImage("invh")); m_SRFilter->SetInputHH(GetParameterComplexFloatImage("inhh")); m_SRFilter->SetInputVV(GetParameterComplexFloatImage("invv")); MeanFilterType::InputSizeType radius; radius.Fill( GetParameterInt("inco.kernelsize") ); m_MeanFilter->GetFilter()->SetRadius(radius); m_MeanFilter->SetInput(m_SRFilter->GetOutput()); m_HAFilter->SetInput(m_MeanFilter->GetOutput()); SetParameterOutputImage("out", m_HAFilter->GetOutput() ); break; } } //MCPSFilterType::Pointer m_MCPSFilter; SRFilterType::Pointer m_SRFilter; HAFilterType::Pointer m_HAFilter; PerBandMeanFilterType::Pointer m_MeanFilter; }; } //end namespace Wrapper } //end namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::SARDecompositions) <commit_msg>ENH: SARDecompositions app, float to double pixels<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbReciprocalHAlphaImageFilter.h" #include "otbSinclairReciprocalImageFilter.h" #include "otbSinclairToReciprocalCoherencyMatrixFunctor.h" #include "otbPerBandVectorImageFilter.h" #include "itkMeanImageFilter.h" namespace otb { namespace Wrapper { class SARDecompositions : public Application { public: /** Standard class typedefs. */ typedef SARDecompositions Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; typedef otb::Functor::SinclairToReciprocalCoherencyMatrixFunctor<ComplexDoubleImageType::PixelType, ComplexDoubleImageType::PixelType, ComplexDoubleImageType::PixelType, ComplexDoubleVectorImageType::PixelType> FunctorType; typedef SinclairReciprocalImageFilter<ComplexDoubleImageType, ComplexDoubleImageType, ComplexDoubleImageType, ComplexDoubleVectorImageType, FunctorType > SRFilterType; typedef otb::ReciprocalHAlphaImageFilter<ComplexDoubleVectorImageType, DoubleVectorImageType> HAFilterType; typedef itk::MeanImageFilter<ComplexDoubleImageType, ComplexDoubleImageType> MeanFilterType; typedef otb::PerBandVectorImageFilter<ComplexDoubleVectorImageType, ComplexDoubleVectorImageType, MeanFilterType> PerBandMeanFilterType; //FloatImageType /** Standard macro */ itkNewMacro(Self); itkTypeMacro(SARDecompositions, otb::Application); private: void DoInit() { SetName("SARDecompositions"); SetDescription("From one-band complex images (each one related to an element of the Sinclair matrix), returns the selected decomposition."); // Documentation SetDocName("SARDecompositions"); SetDocLongDescription("From one-band complex images (HH, HV, VH, VV), returns the selected decomposition.\n \n" "The H-alpha-A decomposition is currently the only one available; it is implemented for the monostatic case (transmitter and receiver are co-located).\n" "User must provide three one-band complex images HH, HV or VH, and VV (monostatic case <=> HV = VH).\n" "The H-alpha-A decomposition consists in averaging 3x3 complex coherency matrices (incoherent analysis); the user must provide the size of the averaging window, thanks to the parameter inco.kernelsize.\n " "The applications returns a float vector image, made up of three channels : H (entropy), Alpha, A (Anisotropy)." ); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso(""); AddDocTag(Tags::SAR); AddParameter(ParameterType_ComplexInputImage, "inhh", "Input Image"); SetParameterDescription("inhh", "Input image (HH)"); AddParameter(ParameterType_ComplexInputImage, "inhv", "Input Image"); SetParameterDescription("inhv", "Input image (HV)"); MandatoryOff("inhv"); AddParameter(ParameterType_ComplexInputImage, "invh", "Input Image"); SetParameterDescription("invh", "Input image (VH)"); MandatoryOff("invh"); AddParameter(ParameterType_ComplexInputImage, "invv", "Input Image"); SetParameterDescription("invv", "Input image (VV)"); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription("out", "Output image"); AddParameter(ParameterType_Choice, "decomp", "Decompositions"); AddChoice("decomp.haa","H-alpha-A decomposition"); SetParameterDescription("decomp.haa","H-alpha-A decomposition"); AddParameter(ParameterType_Group,"inco","Incoherent decompositions"); SetParameterDescription("inco","This group allows to set parameters related to the incoherent decompositions."); AddParameter(ParameterType_Int, "inco.kernelsize", "Kernel size for spatial incoherent averaging."); SetParameterDescription("inco.kernelsize", "Minute (0-59)"); SetMinimumParameterIntValue("inco.kernelsize", 1); SetDefaultParameterInt("inco.kernelsize", 3); MandatoryOff("inco.kernelsize"); AddRAMParameter(); // Default values SetDefaultParameterInt("decomp", 0); // H-alpha-A // Doc example parameter settings SetDocExampleParameterValue("inhh", "HH.tif"); SetDocExampleParameterValue("invh", "VH.tif"); SetDocExampleParameterValue("invv", "VV.tif"); SetDocExampleParameterValue("decomp", "haa"); SetDocExampleParameterValue("out", "HaA.tif"); } void DoUpdateParameters() { // Nothing to do here : all parameters are independent } void DoExecute() { bool inhv = HasUserValue("inhv"); bool invh = HasUserValue("invh"); if ( (!inhv) && (!invh) ) otbAppLogFATAL( << "Parameter inhv or invh not set. Please provide a HV or a VH complex image."); switch (GetParameterInt("decomp")) { case 0: // H-alpha-A m_SRFilter = SRFilterType::New(); m_HAFilter = HAFilterType::New(); m_MeanFilter = PerBandMeanFilterType::New(); if (inhv) m_SRFilter->SetInputHV_VH(GetParameterComplexDoubleImage("inhv")); else if (invh) m_SRFilter->SetInputHV_VH(GetParameterComplexDoubleImage("invh")); m_SRFilter->SetInputHH(GetParameterComplexDoubleImage("inhh")); m_SRFilter->SetInputVV(GetParameterComplexDoubleImage("invv")); MeanFilterType::InputSizeType radius; radius.Fill( GetParameterInt("inco.kernelsize") ); m_MeanFilter->GetFilter()->SetRadius(radius); m_MeanFilter->SetInput(m_SRFilter->GetOutput()); m_HAFilter->SetInput(m_MeanFilter->GetOutput()); SetParameterOutputImage("out", m_HAFilter->GetOutput() ); break; } } //MCPSFilterType::Pointer m_MCPSFilter; SRFilterType::Pointer m_SRFilter; HAFilterType::Pointer m_HAFilter; PerBandMeanFilterType::Pointer m_MeanFilter; }; } //end namespace Wrapper } //end namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::SARDecompositions) <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_GRIDS_PROVIDER_CUBE_HH #define DUNE_STUFF_GRIDS_PROVIDER_CUBE_HH #include <memory> #include <sstream> #include <type_traits> #include <vector> #include <array> #include <boost/numeric/conversion/cast.hpp> #if HAVE_DUNE_GRID # include <dune/grid/sgrid.hh> # include <dune/grid/yaspgrid.hh> # if HAVE_ALUGRID # include <dune/grid/alugrid.hh> # endif # if HAVE_DUNE_SPGRID # include <dune/grid/spgrid.hh> # endif # include <dune/stuff/grid/structuredgridfactory.hh> #endif #include <dune/stuff/common/fvector.hh> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/memory.hh> #include "default.hh" namespace Dune { namespace Stuff { namespace Grid { namespace Providers { namespace Configs { static Common::Configuration Cube_default(const std::string sub_name = "") { Common::Configuration config; config["lower_left"] = "[0 0 0 0]"; config["upper_right"] = "[1 1 1 1]"; config["num_elements"] = "[8 8 8 8]"; config["num_refinements"] = "0"; if (sub_name.empty()) return config; else { Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... Cube_default(...) } // namespace Configs namespace internal { template< typename GridType > struct ElementVariant; template< typename GridType > struct ElementVariant { static const int id = 2; }; #if HAVE_DUNE_GRID template< int dim > struct ElementVariant< Dune::YaspGrid< dim > > { static const int id = 1; }; template< int dimGrid, int dimWorld > struct ElementVariant< Dune::SGrid< dimGrid, dimWorld > > { static const int id = 1; }; #if HAVE_DUNE_SPGRID template< class ct, int dim, SPRefinementStrategy strategy, class Comm > struct ElementVariant< Dune::SPGrid< ct, dim, strategy, Comm > > { static const int id = 1; }; #endif #endif // HAVE_DUNE_GRID #if HAVE_ALUGRID template< int dimGrid, int dimWorld > struct ElementVariant< Dune::ALUCubeGrid< dimGrid, dimWorld > > { static const int id = 1; }; template< int dimGrid, int dimWorld, class MpiCommImp > struct ElementVariant< Dune::ALUGrid< dimGrid, dimWorld, Dune::cube, Dune::conforming, MpiCommImp > > { static const int id = 1; }; template< int dimGrid, int dimWorld, class MpiCommImp > struct ElementVariant< Dune::ALUGrid< dimGrid, dimWorld, Dune::cube, Dune::nonconforming, MpiCommImp > > { static const int id = 1; }; #endif // HAVE_ALUGRID } // namespace internal #if HAVE_DUNE_GRID /** * \brief Creates a grid of a cube in various dimensions. * * Default implementation using the Dune::StructuredGridFactory to create a grid of a cube in 1, 2 or 3 * dimensions. Tested with * <ul><li> \c YASPGRID, \c variant 1, dim = 1, 2, 3, * <li> \c SGRID, \c variant 1, dim = 1, 2, 3, * <li> \c ALUGRID_SIMPLEX, \c variant 2, dim = 2, 3, * <li> \c ALUGRID_CONFORM, \c variant 2, dim = 2, 2 and * <li> \c ALUGRID_CUBE, \c variant 1, dim = 2, 3.</ul> * \tparam GridImp * Type of the underlying grid. * \tparam variant * Type of the codim 0 elements: * <ul><li>\c 1: cubes * <li>2: simplices</ul> **/ template< typename GridImp, int variant = internal::ElementVariant< GridImp >::id > class Cube : public ProviderInterface< GridImp > { typedef ProviderInterface< GridImp > BaseType; typedef Cube< GridImp, variant > ThisType; public: using typename BaseType::GridType; static const size_t dimDomain = BaseType::dimDomain; using typename BaseType::DomainFieldType; using typename BaseType::DomainType; static const std::string static_id() { return BaseType::static_id() + ".cube"; } static Common::Configuration default_config(const std::string sub_name = "") { return Configs::Cube_default(sub_name); } static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Common::Configuration default_cfg = default_config(); return Common::make_unique< ThisType >( cfg.get("lower_left", default_cfg.get< DomainType >("lower_left")), cfg.get("upper_right", default_cfg.get< DomainType >("upper_right")), cfg.get("num_elements", default_cfg.get< std::vector< unsigned int > >("num_elements"), dimDomain), cfg.get("num_refinements", default_cfg.get< size_t >("num_refinements"))); } // ... create(...) /** * \brief Creates a cube. * \param[in] lower_left * Used as a lower left corner (in each dimension, if scalar). * \param[in] upper_right * Used as an upper right corner (in each dimension, if scalar). * \param[in] num_elements (optional) * Number of elements. **/ explicit Cube(const DomainFieldType lower_left = default_config().get< DomainFieldType >("lower_left"), const DomainFieldType upper_right = default_config().get< DomainFieldType >("upper_right"), const unsigned int num_elements = default_config().get< std::vector< unsigned int > >("num_elements")[0], const size_t num_refinements = default_config().get< size_t >("num_refinements")) : grid_ptr_(create_grid(DomainType(lower_left), DomainType(upper_right), parse_array(num_elements), num_refinements)) {} Cube(const DSC::FieldVector< DomainFieldType, dimDomain >& lower_left, const DSC::FieldVector< DomainFieldType, dimDomain >& upper_right, const unsigned int num_elements = default_config().get< std::vector< unsigned int > >("num_elements")[0], const size_t num_refinements = default_config().get< size_t >("num_refinements")) : grid_ptr_(create_grid(lower_left, upper_right, parse_array(num_elements), num_refinements)) {} Cube(const DSC::FieldVector< DomainFieldType, dimDomain >& lower_left, const DSC::FieldVector< DomainFieldType, dimDomain >& upper_right, const std::vector< unsigned int > num_elements = default_config().get< std::vector< unsigned int > >("num_elements"), const size_t num_refinements = default_config().get< size_t >("num_refinements")) : grid_ptr_(create_grid(lower_left, upper_right, parse_array(num_elements), num_refinements)) {} virtual GridType& grid() override { return *grid_ptr_; } virtual const GridType& grid() const override { return *grid_ptr_; } std::shared_ptr< GridType > grid_ptr() { return grid_ptr_; } const std::shared_ptr< const GridType >& grid_ptr() const { return grid_ptr_; } private: static std::array< unsigned int, dimDomain > parse_array(const unsigned int in) { std::array< unsigned int, dimDomain > ret; std::fill(ret.begin(), ret.end(), in); return ret; } // ... parse_array(...) static std::array< unsigned int, dimDomain > parse_array(const std::vector< unsigned int >& in) { if (in.size() < dimDomain) DUNE_THROW(Exceptions::wrong_input_given, "Given vector is too short: should be " << dimDomain << ", is " << in.size() << "!"); std::array< unsigned int, dimDomain > ret; for (size_t ii = 0; ii < dimDomain; ++ii) ret[ii] = in[ii]; return ret; } // ... parse_array(...) static std::shared_ptr< GridType > create_grid(DomainType lower_left, DomainType upper_right, const std::array< unsigned int, dimDomain >& num_elements, const size_t num_refinements) { static_assert(variant == 1 || variant == 2, "variant has to be 1 or 2!"); for (size_t dd = 0; dd < dimDomain; ++dd) { if (!(lower_left[dd] < upper_right[dd])) DUNE_THROW(Exceptions::wrong_input_given, "lower_left has to be elementwise smaller than upper_right!\n\n" << lower_left[dd] << " vs. " << upper_right[dd]); } std::shared_ptr< GridType > grd_ptr(nullptr); switch (variant) { case 1: grd_ptr = DSG::StructuredGridFactory< GridType >::createCubeGrid(lower_left, upper_right, num_elements); break; case 2: default: grd_ptr = DSG::StructuredGridFactory< GridType >::createSimplexGrid(lower_left, upper_right, num_elements); break; } grd_ptr->loadBalance(); grd_ptr->preAdapt(); grd_ptr->globalRefine(boost::numeric_cast< int >(num_refinements)); grd_ptr->postAdapt(); grd_ptr->loadBalance(); return grd_ptr; } // ... create_grid(...) std::shared_ptr< GridType > grid_ptr_; }; // class Cube #else // HAVE_DUNE_GRID template< typename GridImp, int variant = 1 > class Cube { static_assert(AlwaysFalse< GridImp >::value, "You are missing dune-grid!"); }; #endif // HAVE_DUNE_GRID } // namespace Providers } // namespace Grid } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_GRIDS_PROVIDER_CUBE_HH <commit_msg>[provider.cube] makes overlap settable<commit_after>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_GRIDS_PROVIDER_CUBE_HH #define DUNE_STUFF_GRIDS_PROVIDER_CUBE_HH #include <memory> #include <sstream> #include <type_traits> #include <vector> #include <array> #include <boost/numeric/conversion/cast.hpp> #if HAVE_DUNE_GRID # include <dune/grid/sgrid.hh> # include <dune/grid/yaspgrid.hh> # if HAVE_ALUGRID # include <dune/grid/alugrid.hh> # endif # if HAVE_DUNE_SPGRID # include <dune/grid/spgrid.hh> # endif # include <dune/stuff/grid/structuredgridfactory.hh> #endif #include <dune/stuff/common/fvector.hh> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/memory.hh> #include "default.hh" namespace Dune { namespace Stuff { namespace Grid { namespace Providers { namespace Configs { static Common::Configuration Cube_default(const std::string sub_name = "") { Common::Configuration config; config["lower_left"] = "[0 0 0 0]"; config["upper_right"] = "[1 1 1 1]"; config["num_elements"] = "[8 8 8 8]"; config["num_refinements"] = "0"; config["overlap"] = "1"; if (sub_name.empty()) return config; else { Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... Cube_default(...) } // namespace Configs namespace internal { template< typename GridType > struct ElementVariant; template< typename GridType > struct ElementVariant { static const int id = 2; }; #if HAVE_DUNE_GRID template< int dim > struct ElementVariant< Dune::YaspGrid< dim > > { static const int id = 1; }; template< int dimGrid, int dimWorld > struct ElementVariant< Dune::SGrid< dimGrid, dimWorld > > { static const int id = 1; }; #if HAVE_DUNE_SPGRID template< class ct, int dim, SPRefinementStrategy strategy, class Comm > struct ElementVariant< Dune::SPGrid< ct, dim, strategy, Comm > > { static const int id = 1; }; #endif #endif // HAVE_DUNE_GRID #if HAVE_ALUGRID template< int dimGrid, int dimWorld > struct ElementVariant< Dune::ALUCubeGrid< dimGrid, dimWorld > > { static const int id = 1; }; template< int dimGrid, int dimWorld, class MpiCommImp > struct ElementVariant< Dune::ALUGrid< dimGrid, dimWorld, Dune::cube, Dune::conforming, MpiCommImp > > { static const int id = 1; }; template< int dimGrid, int dimWorld, class MpiCommImp > struct ElementVariant< Dune::ALUGrid< dimGrid, dimWorld, Dune::cube, Dune::nonconforming, MpiCommImp > > { static const int id = 1; }; #endif // HAVE_ALUGRID } // namespace internal #if HAVE_DUNE_GRID /** * \brief Creates a grid of a cube in various dimensions. * * Default implementation using the Dune::StructuredGridFactory to create a grid of a cube in 1, 2 or 3 * dimensions. Tested with * <ul><li> \c YASPGRID, \c variant 1, dim = 1, 2, 3, * <li> \c SGRID, \c variant 1, dim = 1, 2, 3, * <li> \c ALUGRID_SIMPLEX, \c variant 2, dim = 2, 3, * <li> \c ALUGRID_CONFORM, \c variant 2, dim = 2, 2 and * <li> \c ALUGRID_CUBE, \c variant 1, dim = 2, 3.</ul> * \tparam GridImp * Type of the underlying grid. * \tparam variant * Type of the codim 0 elements: * <ul><li>\c 1: cubes * <li>2: simplices</ul> **/ template< typename GridImp, int variant = internal::ElementVariant< GridImp >::id > class Cube : public ProviderInterface< GridImp > { typedef ProviderInterface< GridImp > BaseType; typedef Cube< GridImp, variant > ThisType; public: using typename BaseType::GridType; static const size_t dimDomain = BaseType::dimDomain; using typename BaseType::DomainFieldType; using typename BaseType::DomainType; static const std::string static_id() { return BaseType::static_id() + ".cube"; } static Common::Configuration default_config(const std::string sub_name = "") { return Configs::Cube_default(sub_name); } static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const auto overlap = cfg.get("overlap", default_config().get< unsigned int >("overlap")); const auto overlap_array = DSC::make_array< unsigned int, dimDomain >(overlap); return Common::make_unique< ThisType >( cfg.get("lower_left", default_config().get< DomainType >("lower_left")), cfg.get("upper_right", default_config().get< DomainType >("upper_right")), cfg.get("num_elements", default_config().get< std::vector< unsigned int > >("num_elements"), dimDomain), cfg.get("num_refinements", default_config().get< size_t >("num_refinements")), overlap_array); } // ... create(...) /** * \brief Creates a cube. * \param[in] lower_left * Used as a lower left corner (in each dimension, if scalar). * \param[in] upper_right * Used as an upper right corner (in each dimension, if scalar). * \param[in] num_elements (optional) * Number of elements. **/ explicit Cube(const DomainFieldType lower_left = default_config().get< DomainFieldType >("lower_left"), const DomainFieldType upper_right = default_config().get< DomainFieldType >("upper_right"), const unsigned int num_elements = default_config().get< std::vector< unsigned int > >("num_elements")[0], const size_t num_refinements = default_config().get< size_t >("num_refinements"), const std::array< unsigned int, dimDomain > overlap = DSC::make_array< unsigned int, dimDomain >(default_config().get< unsigned int >("overlap"))) : grid_ptr_(create_grid(DomainType(lower_left), DomainType(upper_right), parse_array(num_elements), num_refinements)) {} Cube(const DSC::FieldVector< DomainFieldType, dimDomain >& lower_left, const DSC::FieldVector< DomainFieldType, dimDomain >& upper_right, const unsigned int num_elements = default_config().get< std::vector< unsigned int > >("num_elements")[0], const size_t num_refinements = default_config().get< size_t >("num_refinements"), const std::array< unsigned int, dimDomain > overlap = DSC::make_array< unsigned int, dimDomain >(default_config().get< unsigned int >("overlap"))) : grid_ptr_(create_grid(lower_left, upper_right, parse_array(num_elements), num_refinements)) {} Cube(const DSC::FieldVector< DomainFieldType, dimDomain >& lower_left, const DSC::FieldVector< DomainFieldType, dimDomain >& upper_right, const std::vector< unsigned int > num_elements = default_config().get< std::vector< unsigned int > >("num_elements"), const size_t num_refinements = default_config().get< size_t >("num_refinements"), const std::array< unsigned int, dimDomain > overlap = DSC::make_array< unsigned int, dimDomain >(default_config().get< unsigned int >("overlap"))) : grid_ptr_(create_grid(lower_left, upper_right, parse_array(num_elements), num_refinements)) {} virtual GridType& grid() override { return *grid_ptr_; } virtual const GridType& grid() const override { return *grid_ptr_; } std::shared_ptr< GridType > grid_ptr() { return grid_ptr_; } const std::shared_ptr< const GridType >& grid_ptr() const { return grid_ptr_; } private: static std::array< unsigned int, dimDomain > parse_array(const unsigned int in) { std::array< unsigned int, dimDomain > ret; std::fill(ret.begin(), ret.end(), in); return ret; } // ... parse_array(...) static std::array< unsigned int, dimDomain > parse_array(const std::vector< unsigned int >& in) { if (in.size() < dimDomain) DUNE_THROW(Exceptions::wrong_input_given, "Given vector is too short: should be " << dimDomain << ", is " << in.size() << "!"); std::array< unsigned int, dimDomain > ret; for (size_t ii = 0; ii < dimDomain; ++ii) ret[ii] = in[ii]; return ret; } // ... parse_array(...) ///TODO simplex grid overlap static std::shared_ptr< GridType > create_grid(DomainType lower_left, DomainType upper_right, const std::array< unsigned int, dimDomain >& num_elements, const size_t num_refinements, const std::array< unsigned int, dimDomain > overlap = DSC::make_array< unsigned int, dimDomain >(default_config().get< size_t >("overlap"))) { static_assert(variant == 1 || variant == 2, "variant has to be 1 or 2!"); for (size_t dd = 0; dd < dimDomain; ++dd) { if (!(lower_left[dd] < upper_right[dd])) DUNE_THROW(Exceptions::wrong_input_given, "lower_left has to be elementwise smaller than upper_right!\n\n" << lower_left[dd] << " vs. " << upper_right[dd]); } std::shared_ptr< GridType > grd_ptr(nullptr); switch (variant) { case 1: grd_ptr = DSG::StructuredGridFactory< GridType >::createCubeGrid(lower_left, upper_right, num_elements, overlap); break; case 2: default: grd_ptr = DSG::StructuredGridFactory< GridType >::createSimplexGrid(lower_left, upper_right, num_elements); break; } grd_ptr->loadBalance(); grd_ptr->preAdapt(); grd_ptr->globalRefine(boost::numeric_cast< int >(num_refinements)); grd_ptr->postAdapt(); grd_ptr->loadBalance(); return grd_ptr; } // ... create_grid(...) std::shared_ptr< GridType > grid_ptr_; }; // class Cube #else // HAVE_DUNE_GRID template< typename GridImp, int variant = 1 > class Cube { static_assert(AlwaysFalse< GridImp >::value, "You are missing dune-grid!"); }; #endif // HAVE_DUNE_GRID } // namespace Providers } // namespace Grid } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_GRIDS_PROVIDER_CUBE_HH <|endoftext|>
<commit_before>#include "NFCMasterNet_WebServerModule.h" #include "NFComm/NFMessageDefine/NFProtocolDefine.hpp" #include <thread> extern "C" int uhStats(UrlHandlerParam* param); UrlHandler urlHandlerList[] = { { "stats", uhStats, NULL }, { NULL }, }; AuthHandler authHandlerList[] = { { "stats", "user", "pass", "group=admin", "" }, { NULL } }; bool NFCMasterNet_WebServerModule::Init() { return true; } bool NFCMasterNet_WebServerModule::BeforeShut() { return true; } bool NFCMasterNet_WebServerModule::Shut() { // cleanup _mwCloseAllConnections(hp); SYSLOG(LOG_INFO, "Cleaning up...\n"); for (i = 0; i < hp->maxClients; i++) { if (hp->hsSocketQueue[i].buffer) free(hp->hsSocketQueue[i].buffer); } for (i = 0; hp->pxUrlHandler[i].pchUrlPrefix; i++) { if (hp->pxUrlHandler[i].pfnUrlHandler && hp->pxUrlHandler[i].pfnEventHandler) hp->pxUrlHandler[i].pfnEventHandler(MW_UNINIT, &hp->pxUrlHandler[i], hp); } free(hp->hsSocketQueue); hp->hsSocketQueue = 0; // clear state vars hp->bKillWebserver = FALSE; hp->bWebserverRunning = FALSE; mwServerShutdown(&httpParam); UninitSocket(); return true; } char * NFCMasterNet_WebServerModule::GetLocalAddrString() { return "127.0.0.1"; } void NFCMasterNet_WebServerModule::GetFullPath(char * buffer, const char * path) { strcpy(buffer, path); } bool NFCMasterNet_WebServerModule::AfterInit() { mKernelModule = pPluginManager->FindModule<NFIKernelModule>(); m_pLogicClassModule = pPluginManager->FindModule<NFIClassModule>(); m_pElementModule = pPluginManager->FindModule<NFIElementModule>(); NF_SHARE_PTR<NFIClass> xLogicClass = m_pLogicClassModule->GetElement(NFrame::HttpServer::ThisName()); if (xLogicClass) { NFList<std::string>& strIdList = xLogicClass->GetIdList(); std::string strId; for (bool bRet = strIdList.First(strId); bRet; bRet = strIdList.Next(strId)) { nWebPort = m_pElementModule->GetPropertyInt(strId, NFrame::HttpServer::WebPort()); strWebRootPath = m_pElementModule->GetPropertyString(strId, NFrame::HttpServer::WebRootPath()); } } //fill in default settings mwInitParam(&httpParam); httpParam.maxClients = 50; GetFullPath(httpParam.pchWebPath, strWebRootPath.c_str()); httpParam.httpPort = nWebPort; httpParam.pxAuthHandler = authHandlerList; httpParam.pxUrlHandler = urlHandlerList; httpParam.flags = FLAG_DIR_LISTING; httpParam.tmSocketExpireTime = 15; { int i; int error = 0; for (i = 0; urlHandlerList[i].pchUrlPrefix; i++) { if (urlHandlerList[i].pfnEventHandler) { if (urlHandlerList[i].pfnEventHandler(MW_PARSE_ARGS, urlHandlerList[i].pfnEventHandler, &httpParam)) error++; } } if (error > 0) { printf("Error parsing command line options\n"); return -1; } } InitSocket(); { int n; printf("Host: %s:%d\n", GetLocalAddrString(), httpParam.httpPort); printf("Web root: %s\n", httpParam.pchWebPath); printf("Max clients (per IP): %d (%d)\n", httpParam.maxClients, httpParam.maxClientsPerIP); for (n = 0;urlHandlerList[n].pchUrlPrefix;n++); printf("URL handlers: %d\n", n); if (httpParam.flags & FLAG_DIR_LISTING) printf("Dir listing enabled\n"); if (httpParam.flags & FLAG_DISABLE_RANGE) printf("Byte-range disabled\n"); //register page variable substitution callback //httpParam[i].pfnSubst=DefaultWebSubstCallback; //start server if (mwServerStart(&httpParam)) { printf("Error starting HTTP server\n"); } } return true; } bool NFCMasterNet_WebServerModule::Execute() { // main processing loop if (!hp->bKillWebserver) { time_t tmCurrentTime; SOCKET iSelectMaxFds; fd_set fdsSelectRead; fd_set fdsSelectWrite; // clear descriptor sets FD_ZERO(&fdsSelectRead); FD_ZERO(&fdsSelectWrite); FD_SET(hp->listenSocket, &fdsSelectRead); iSelectMaxFds = hp->listenSocket; // get current time #ifndef WINCE tmCurrentTime = time(NULL); #else tmCurrentTime = GetTickCount() >> 10; #endif // build descriptor sets and close timed out sockets for (int i = 0; i < hp->maxClients; i++) { phsSocketCur = hp->hsSocketQueue + i; // get socket fd socket = phsSocketCur->socket; if (!socket) continue; { int iError = 0; int iOptSize = sizeof(int); if (getsockopt(socket, SOL_SOCKET, SO_ERROR, (char*)&iError, &iOptSize)) { // if a socket contains a error, close it SYSLOG(LOG_INFO, "[%d] Socket no longer vaild.\n", socket); phsSocketCur->flags = FLAG_CONN_CLOSE; _mwCloseSocket(hp, phsSocketCur); continue; } } // check expiration timer (for non-listening, in-use sockets) if (tmCurrentTime > phsSocketCur->tmExpirationTime) { SYSLOG(LOG_INFO, "[%d] Http socket expired\n", phsSocketCur->socket); hp->stats.timeOutCount++; // close connection phsSocketCur->flags = FLAG_CONN_CLOSE; _mwCloseSocket(hp, phsSocketCur); } else { if (phsSocketCur->dwResumeTick) { // suspended if (phsSocketCur->dwResumeTick > GetTickCount()) continue; else phsSocketCur->dwResumeTick = 0; } if (ISFLAGSET(phsSocketCur, FLAG_RECEIVING)) { // add to read descriptor set FD_SET(socket, &fdsSelectRead); } if (ISFLAGSET(phsSocketCur, FLAG_SENDING)) { // add to write descriptor set FD_SET(socket, &fdsSelectWrite); } // check if new max socket if (socket > iSelectMaxFds) { iSelectMaxFds = socket; } } } { struct timeval tvSelectWait; // initialize select delay tvSelectWait.tv_sec = 1; tvSelectWait.tv_usec = 0; // note: using timeval here -> usec not nsec // and check sockets (may take a while!) iRc = select(iSelectMaxFds + 1, &fdsSelectRead, &fdsSelectWrite, NULL, &tvSelectWait); } if (iRc < 0) { msleep(1000); return true; } if (iRc > 0) { // check which sockets are read/write able for (i = 0; i < hp->maxClients; i++) { BOOL bRead; BOOL bWrite; phsSocketCur = hp->hsSocketQueue + i; // get socket fd socket = phsSocketCur->socket; if (!socket) continue; // get read/write status for socket bRead = FD_ISSET(socket, &fdsSelectRead); bWrite = FD_ISSET(socket, &fdsSelectWrite); if ((bRead | bWrite) != 0) { //DBG("socket %d bWrite=%d, bRead=%d\n",phsSocketCur->socket,bWrite,bRead); // if readable or writeable then process if (bWrite && ISFLAGSET(phsSocketCur, FLAG_SENDING)) { iRc = _mwProcessWriteSocket(hp, phsSocketCur); } else if (bRead && ISFLAGSET(phsSocketCur, FLAG_RECEIVING)) { iRc = _mwProcessReadSocket(hp, phsSocketCur); } else { iRc = -1; DBG("Invalid socket state (flag: %08x)\n", phsSocketCur->flags); } if (!iRc) { // and reset expiration timer #ifndef WINCE phsSocketCur->tmExpirationTime = time(NULL) + hp->tmSocketExpireTime; #else phsSocketCur->tmExpirationTime = (GetTickCount() >> 10) + hp->tmSocketExpireTime; #endif } else { SETFLAG(phsSocketCur, FLAG_CONN_CLOSE); _mwCloseSocket(hp, phsSocketCur); } } } // check if any socket to accept and accept the socket if (FD_ISSET(hp->listenSocket, &fdsSelectRead)) { // find empty slot phsSocketCur = 0; for (i = 0; i < hp->maxClients; i++) { if (hp->hsSocketQueue[i].socket == 0) { phsSocketCur = hp->hsSocketQueue + i; break; } } if (!phsSocketCur) { DBG("WARNING: clientCount:%d > maxClients:%d\n", hp->stats.clientCount, hp->maxClients); _mwDenySocket(hp, &sinaddr); return true; } phsSocketCur->socket = _mwAcceptSocket(hp, &sinaddr); if (phsSocketCur->socket == 0) return true; phsSocketCur->ipAddr.laddr = ntohl(sinaddr.sin_addr.s_addr); SYSLOG(LOG_INFO, "[%d] IP: %d.%d.%d.%d\n", phsSocketCur->socket, phsSocketCur->ipAddr.caddr[3], phsSocketCur->ipAddr.caddr[2], phsSocketCur->ipAddr.caddr[1], phsSocketCur->ipAddr.caddr[0]); hp->stats.clientCount++; //fill structure with data _mwInitSocketData(phsSocketCur); phsSocketCur->request.pucPayload = 0; #ifndef WINCE phsSocketCur->tmAcceptTime = time(NULL); #else phsSocketCur->tmAcceptTime = GetTickCount() >> 10; #endif phsSocketCur->tmExpirationTime = phsSocketCur->tmAcceptTime + hp->tmSocketExpireTime; phsSocketCur->iRequestCount = 0; DBG("Connected clients: %d\n", hp->stats.clientCount); //update max client count if (hp->stats.clientCount > hp->stats.clientCountMax) hp->stats.clientCountMax = hp->stats.clientCount; } } else { //DBG("Select Timeout\n"); // select timeout // call idle event if (hp->pfnIdleCallback) { (*hp->pfnIdleCallback)(hp); } } } return true; } <commit_msg>fixed for compile<commit_after>#include "NFCMasterNet_WebServerModule.h" #include "NFComm/NFMessageDefine/NFProtocolDefine.hpp" #include <thread> extern "C" int uhStats(UrlHandlerParam* param); UrlHandler urlHandlerList[] = { { "stats", uhStats, NULL }, { NULL }, }; AuthHandler authHandlerList[] = { { "stats", "user", "pass", "group=admin", "" }, { NULL } }; bool NFCMasterNet_WebServerModule::Init() { return true; } bool NFCMasterNet_WebServerModule::BeforeShut() { return true; } bool NFCMasterNet_WebServerModule::Shut() { // cleanup _mwCloseAllConnections(hp); SYSLOG(LOG_INFO, "Cleaning up...\n"); for (i = 0; i < hp->maxClients; i++) { if (hp->hsSocketQueue[i].buffer) free(hp->hsSocketQueue[i].buffer); } for (i = 0; hp->pxUrlHandler[i].pchUrlPrefix; i++) { if (hp->pxUrlHandler[i].pfnUrlHandler && hp->pxUrlHandler[i].pfnEventHandler) hp->pxUrlHandler[i].pfnEventHandler(MW_UNINIT, &hp->pxUrlHandler[i], hp); } free(hp->hsSocketQueue); hp->hsSocketQueue = 0; // clear state vars hp->bKillWebserver = FALSE; hp->bWebserverRunning = FALSE; mwServerShutdown(&httpParam); UninitSocket(); return true; } char * NFCMasterNet_WebServerModule::GetLocalAddrString() { return "127.0.0.1"; } void NFCMasterNet_WebServerModule::GetFullPath(char * buffer, const char * path) { strcpy(buffer, path); } bool NFCMasterNet_WebServerModule::AfterInit() { mKernelModule = pPluginManager->FindModule<NFIKernelModule>(); m_pLogicClassModule = pPluginManager->FindModule<NFIClassModule>(); m_pElementModule = pPluginManager->FindModule<NFIElementModule>(); NF_SHARE_PTR<NFIClass> xLogicClass = m_pLogicClassModule->GetElement(NFrame::HttpServer::ThisName()); if (xLogicClass) { NFList<std::string>& strIdList = xLogicClass->GetIdList(); std::string strId; for (bool bRet = strIdList.First(strId); bRet; bRet = strIdList.Next(strId)) { nWebPort = m_pElementModule->GetPropertyInt(strId, NFrame::HttpServer::WebPort()); strWebRootPath = m_pElementModule->GetPropertyString(strId, NFrame::HttpServer::WebRootPath()); } } //fill in default settings mwInitParam(&httpParam); httpParam.maxClients = 50; GetFullPath(httpParam.pchWebPath, strWebRootPath.c_str()); httpParam.httpPort = nWebPort; httpParam.pxAuthHandler = authHandlerList; httpParam.pxUrlHandler = urlHandlerList; httpParam.flags = FLAG_DIR_LISTING; httpParam.tmSocketExpireTime = 15; { int i; int error = 0; for (i = 0; urlHandlerList[i].pchUrlPrefix; i++) { if (urlHandlerList[i].pfnEventHandler) { if (urlHandlerList[i].pfnEventHandler(MW_PARSE_ARGS, (void*)urlHandlerList[i].pfnEventHandler, &httpParam)) error++; } } if (error > 0) { printf("Error parsing command line options\n"); return -1; } } InitSocket(); { int n; printf("Host: %s:%d\n", GetLocalAddrString(), httpParam.httpPort); printf("Web root: %s\n", httpParam.pchWebPath); printf("Max clients (per IP): %d (%d)\n", httpParam.maxClients, httpParam.maxClientsPerIP); for (n = 0;urlHandlerList[n].pchUrlPrefix;n++); printf("URL handlers: %d\n", n); if (httpParam.flags & FLAG_DIR_LISTING) printf("Dir listing enabled\n"); if (httpParam.flags & FLAG_DISABLE_RANGE) printf("Byte-range disabled\n"); //register page variable substitution callback //httpParam[i].pfnSubst=DefaultWebSubstCallback; //start server if (mwServerStart(&httpParam)) { printf("Error starting HTTP server\n"); } } return true; } bool NFCMasterNet_WebServerModule::Execute() { // main processing loop if (!hp->bKillWebserver) { time_t tmCurrentTime; SOCKET iSelectMaxFds; fd_set fdsSelectRead; fd_set fdsSelectWrite; // clear descriptor sets FD_ZERO(&fdsSelectRead); FD_ZERO(&fdsSelectWrite); FD_SET(hp->listenSocket, &fdsSelectRead); iSelectMaxFds = hp->listenSocket; // get current time #ifndef WINCE tmCurrentTime = time(NULL); #else tmCurrentTime = GetTickCount() >> 10; #endif // build descriptor sets and close timed out sockets for (int i = 0; i < hp->maxClients; i++) { phsSocketCur = hp->hsSocketQueue + i; // get socket fd socket = phsSocketCur->socket; if (!socket) continue; { int iError = 0; int iOptSize = sizeof(int); if (getsockopt(socket, SOL_SOCKET, SO_ERROR, (char*)&iError, (socklen_t*)&iOptSize)) { // if a socket contains a error, close it SYSLOG(LOG_INFO, "[%d] Socket no longer vaild.\n", socket); phsSocketCur->flags = FLAG_CONN_CLOSE; _mwCloseSocket(hp, phsSocketCur); continue; } } // check expiration timer (for non-listening, in-use sockets) if (tmCurrentTime > phsSocketCur->tmExpirationTime) { SYSLOG(LOG_INFO, "[%d] Http socket expired\n", phsSocketCur->socket); hp->stats.timeOutCount++; // close connection phsSocketCur->flags = FLAG_CONN_CLOSE; _mwCloseSocket(hp, phsSocketCur); } else { if (phsSocketCur->dwResumeTick) { // suspended if (phsSocketCur->dwResumeTick > GetTickCount()) continue; else phsSocketCur->dwResumeTick = 0; } if (ISFLAGSET(phsSocketCur, FLAG_RECEIVING)) { // add to read descriptor set FD_SET(socket, &fdsSelectRead); } if (ISFLAGSET(phsSocketCur, FLAG_SENDING)) { // add to write descriptor set FD_SET(socket, &fdsSelectWrite); } // check if new max socket if (socket > iSelectMaxFds) { iSelectMaxFds = socket; } } } { struct timeval tvSelectWait; // initialize select delay tvSelectWait.tv_sec = 1; tvSelectWait.tv_usec = 0; // note: using timeval here -> usec not nsec // and check sockets (may take a while!) iRc = select(iSelectMaxFds + 1, &fdsSelectRead, &fdsSelectWrite, NULL, &tvSelectWait); } if (iRc < 0) { msleep(1000); return true; } if (iRc > 0) { // check which sockets are read/write able for (i = 0; i < hp->maxClients; i++) { BOOL bRead; BOOL bWrite; phsSocketCur = hp->hsSocketQueue + i; // get socket fd socket = phsSocketCur->socket; if (!socket) continue; // get read/write status for socket bRead = FD_ISSET(socket, &fdsSelectRead); bWrite = FD_ISSET(socket, &fdsSelectWrite); if ((bRead | bWrite) != 0) { //DBG("socket %d bWrite=%d, bRead=%d\n",phsSocketCur->socket,bWrite,bRead); // if readable or writeable then process if (bWrite && ISFLAGSET(phsSocketCur, FLAG_SENDING)) { iRc = _mwProcessWriteSocket(hp, phsSocketCur); } else if (bRead && ISFLAGSET(phsSocketCur, FLAG_RECEIVING)) { iRc = _mwProcessReadSocket(hp, phsSocketCur); } else { iRc = -1; DBG("Invalid socket state (flag: %08x)\n", phsSocketCur->flags); } if (!iRc) { // and reset expiration timer #ifndef WINCE phsSocketCur->tmExpirationTime = time(NULL) + hp->tmSocketExpireTime; #else phsSocketCur->tmExpirationTime = (GetTickCount() >> 10) + hp->tmSocketExpireTime; #endif } else { SETFLAG(phsSocketCur, FLAG_CONN_CLOSE); _mwCloseSocket(hp, phsSocketCur); } } } // check if any socket to accept and accept the socket if (FD_ISSET(hp->listenSocket, &fdsSelectRead)) { // find empty slot phsSocketCur = 0; for (i = 0; i < hp->maxClients; i++) { if (hp->hsSocketQueue[i].socket == 0) { phsSocketCur = hp->hsSocketQueue + i; break; } } if (!phsSocketCur) { DBG("WARNING: clientCount:%d > maxClients:%d\n", hp->stats.clientCount, hp->maxClients); _mwDenySocket(hp, &sinaddr); return true; } phsSocketCur->socket = _mwAcceptSocket(hp, &sinaddr); if (phsSocketCur->socket == 0) return true; phsSocketCur->ipAddr.laddr = ntohl(sinaddr.sin_addr.s_addr); SYSLOG(LOG_INFO, "[%d] IP: %d.%d.%d.%d\n", phsSocketCur->socket, phsSocketCur->ipAddr.caddr[3], phsSocketCur->ipAddr.caddr[2], phsSocketCur->ipAddr.caddr[1], phsSocketCur->ipAddr.caddr[0]); hp->stats.clientCount++; //fill structure with data _mwInitSocketData(phsSocketCur); phsSocketCur->request.pucPayload = 0; #ifndef WINCE phsSocketCur->tmAcceptTime = time(NULL); #else phsSocketCur->tmAcceptTime = GetTickCount() >> 10; #endif phsSocketCur->tmExpirationTime = phsSocketCur->tmAcceptTime + hp->tmSocketExpireTime; phsSocketCur->iRequestCount = 0; DBG("Connected clients: %d\n", hp->stats.clientCount); //update max client count if (hp->stats.clientCount > hp->stats.clientCountMax) hp->stats.clientCountMax = hp->stats.clientCount; } } else { //DBG("Select Timeout\n"); // select timeout // call idle event if (hp->pfnIdleCallback) { (*hp->pfnIdleCallback)(hp); } } } return true; } <|endoftext|>
<commit_before>#include "Common.h" #include "DarunGrim.h" #include "LogOperation.h" LogOperation Logger; DarunGrim::DarunGrim(): pStorageDB(NULL), pOneIDAClientManagerTheSource(NULL), pOneIDAClientManagerTheTarget(NULL), pDiffMachine(NULL), pIDAClientManager(NULL), SourceFilename(NULL), TargetFilename(NULL), IsLoadedSourceFile( FALSE ) { Logger.SetLogOutputType( LogToStdout ); Logger.SetDebugLevel( 100 ); Logger.Log(10, "%s: entry\n", __FUNCTION__ ); pIDAClientManager = new IDAClientManager(); } DarunGrim::~DarunGrim() { Logger.Log(10, "%s: entry\n", __FUNCTION__ ); if( pStorageDB ) { pStorageDB->CloseDatabase(); delete pStorageDB; } if( pDiffMachine ) delete pDiffMachine; if( pIDAClientManager ) delete pIDAClientManager; if( pOneIDAClientManagerTheSource ) delete pOneIDAClientManagerTheSource; if( pOneIDAClientManagerTheTarget ) delete pOneIDAClientManagerTheTarget; } void DarunGrim::SetLogParameters( int ParamLogOutputType, int ParamDebugLevel, const char *LogFile ) { Logger.Log(10, "%s: entry\n", __FUNCTION__ ); Logger.SetLogOutputType( ParamLogOutputType ); if( LogFile ) Logger.SetLogFilename( LogFile ); Logger.SetDebugLevel( ParamDebugLevel ); } void DarunGrim::SetIDAPath( const char *path ) { Logger.Log(10, "%s: entry\n", __FUNCTION__ ); if( path ) pIDAClientManager->SetIDAPath( path ); } bool DarunGrim::GenerateDB( char *ParamStorageFilename, char *LogFilename, DWORD start_address_for_source, DWORD end_address_for_source, DWORD start_address_for_target, DWORD end_address_for_target ) { Logger.Log(10, "%s: entry\n", __FUNCTION__ ); StorageFilename = ParamStorageFilename; pIDAClientManager->SetOutputFilename(StorageFilename); pIDAClientManager->SetLogFilename(LogFilename); pIDAClientManager->RunIDAToGenerateDB( SourceFilename, start_address_for_source, end_address_for_source ); pIDAClientManager->RunIDAToGenerateDB( TargetFilename, start_address_for_target, end_address_for_target ); return OpenDatabase(); } DWORD WINAPI ConnectToDarunGrim2Thread( LPVOID lpParameter ) { DarunGrim *pDarunGrim=( DarunGrim * )lpParameter; IDAClientManager *pIDAClientManager; if( pDarunGrim && (pIDAClientManager = pDarunGrim->GetIDAClientManager()) ) { if( !pDarunGrim->LoadedSourceFile() ) { pIDAClientManager->ConnectToDarunGrim2( pDarunGrim->GetSourceFilename() ); } else { pIDAClientManager->ConnectToDarunGrim2( pDarunGrim->GetTargetFilename() ); } } return 1; } char *DarunGrim::GetSourceFilename() { return SourceFilename; } void DarunGrim::SetSourceFilename( char *source_filename ) { SourceFilename = source_filename; } char *DarunGrim::GetTargetFilename() { return TargetFilename; } void DarunGrim::SetTargetFilename( char *target_filename ) { TargetFilename = target_filename; } bool DarunGrim::LoadedSourceFile() { return IsLoadedSourceFile; } void DarunGrim::SetLoadedSourceFile( bool is_loaded ) { IsLoadedSourceFile = is_loaded; } bool DarunGrim::AcceptIDAClientsFromSocket( const char *storage_filename ) { Logger.Log(10, "%s: entry\n", __FUNCTION__ ); if( storage_filename ) { if( pStorageDB ) delete pStorageDB; pStorageDB = new DBWrapper( (char *) storage_filename ); } if( pStorageDB ) { pIDAClientManager->SetDatabase( pStorageDB ); } pIDAClientManager->StartIDAListener( DARUNGRIM2_PORT ); pOneIDAClientManagerTheSource=new OneIDAClientManager( pStorageDB ); pOneIDAClientManagerTheTarget=new OneIDAClientManager( pStorageDB ); //Create a thread that will call ConnectToDarunGrim2 one by one DWORD dwThreadId; CreateThread( NULL, 0, ConnectToDarunGrim2Thread, ( PVOID )this, 0, &dwThreadId ); pIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheSource, pDiffMachine? FALSE:pStorageDB?TRUE:FALSE ); SetLoadedSourceFile( TRUE ); CreateThread( NULL, 0, ConnectToDarunGrim2Thread, ( PVOID )this, 0, &dwThreadId ); pIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheTarget, pDiffMachine? FALSE:pStorageDB?TRUE:FALSE ); if( !pDiffMachine ) { Analyze(); } pIDAClientManager->SetMembers( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget, pDiffMachine ); pIDAClientManager->CreateIDACommandProcessorThread(); pIDAClientManager->StopIDAListener(); return TRUE; } bool DarunGrim::OpenDatabase() { Logger.Log(10, "%s: entry\n", __FUNCTION__ ); if( pStorageDB ) delete pStorageDB; pStorageDB = new DBWrapper( StorageFilename ); pStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_STATEMENT); pStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_START_ADDRESS_INDEX_STATEMENT); pStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_END_ADDRESS_INDEX_STATEMENT); pStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_STATEMENT); pStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_INDEX_STATEMENT); pStorageDB->ExecuteStatement(NULL,NULL,CREATE_FILE_INFO_TABLE_STATEMENT); return TRUE; } bool DarunGrim::LoadDiffResults( const char *storage_filename ) { pStorageDB = new DBWrapper( (char *) storage_filename ); if( pStorageDB ) { pDiffMachine = new DiffMachine(); if( pDiffMachine ) { pDiffMachine->Retrieve( *pStorageDB,TRUE, 1 , 2 ); return TRUE; } } return FALSE; } bool DarunGrim::Analyze() { Logger.Log(10, "%s: entry\n", __FUNCTION__ ); int source_file_id=1; int target_file_id=2; if( pStorageDB ) { pDiffMachine = new DiffMachine(); pDiffMachine->Retrieve( *pStorageDB,TRUE,source_file_id,target_file_id); } else if( pOneIDAClientManagerTheSource && pOneIDAClientManagerTheTarget ) { pDiffMachine = new DiffMachine( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget ); } if( pDiffMachine ) { pDiffMachine->Analyze(); pDiffMachine->Save( *pStorageDB ); } return TRUE; } bool DarunGrim::ShowOnIDA() { Logger.Log(10, "%s: entry\n", __FUNCTION__ ); //pDiffMachine->PrintMatchMapInfo(); if( pIDAClientManager ) { pIDAClientManager->SetMembers( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget, pDiffMachine ); pIDAClientManager->ShowResultsOnIDA(); pIDAClientManager->IDACommandProcessor(); return TRUE; } return FALSE; } void DarunGrim::ShowAddresses( unsigned long source_address, unsigned long target_address ) { pOneIDAClientManagerTheSource->ShowAddress( source_address ); pOneIDAClientManagerTheTarget->ShowAddress( target_address ); } void DarunGrim::ColorAddress( int index, unsigned long start_address, unsigned long end_address,unsigned long color ) { if( index == 0 ) { pOneIDAClientManagerTheSource->ColorAddress( start_address, end_address, color ); } else { pOneIDAClientManagerTheTarget->ColorAddress( start_address, end_address, color ); } } IDAClientManager *DarunGrim::GetIDAClientManager() { return pIDAClientManager; } <commit_msg>Support address coloring<commit_after>#include "Common.h" #include "DarunGrim.h" #include "LogOperation.h" LogOperation Logger; DarunGrim::DarunGrim(): pStorageDB(NULL), pOneIDAClientManagerTheSource(NULL), pOneIDAClientManagerTheTarget(NULL), pDiffMachine(NULL), pIDAClientManager(NULL), SourceFilename(NULL), TargetFilename(NULL), IsLoadedSourceFile( FALSE ) { Logger.SetLogOutputType( LogToStdout ); Logger.SetDebugLevel( 100 ); Logger.Log(10, "%s: entry\n", __FUNCTION__ ); pIDAClientManager = new IDAClientManager(); } DarunGrim::~DarunGrim() { Logger.Log(10, "%s: entry\n", __FUNCTION__ ); if( pStorageDB ) { pStorageDB->CloseDatabase(); delete pStorageDB; } if( pDiffMachine ) delete pDiffMachine; if( pIDAClientManager ) delete pIDAClientManager; if( pOneIDAClientManagerTheSource ) delete pOneIDAClientManagerTheSource; if( pOneIDAClientManagerTheTarget ) delete pOneIDAClientManagerTheTarget; } void DarunGrim::SetLogParameters( int ParamLogOutputType, int ParamDebugLevel, const char *LogFile ) { Logger.Log(10, "%s: entry\n", __FUNCTION__ ); Logger.SetLogOutputType( ParamLogOutputType ); if( LogFile ) Logger.SetLogFilename( LogFile ); Logger.SetDebugLevel( ParamDebugLevel ); } void DarunGrim::SetIDAPath( const char *path ) { Logger.Log(10, "%s: entry\n", __FUNCTION__ ); if( path ) pIDAClientManager->SetIDAPath( path ); } bool DarunGrim::GenerateDB( char *ParamStorageFilename, char *LogFilename, DWORD start_address_for_source, DWORD end_address_for_source, DWORD start_address_for_target, DWORD end_address_for_target ) { Logger.Log(10, "%s: entry\n", __FUNCTION__ ); StorageFilename = ParamStorageFilename; pIDAClientManager->SetOutputFilename(StorageFilename); pIDAClientManager->SetLogFilename(LogFilename); pIDAClientManager->RunIDAToGenerateDB( SourceFilename, start_address_for_source, end_address_for_source ); pIDAClientManager->RunIDAToGenerateDB( TargetFilename, start_address_for_target, end_address_for_target ); return OpenDatabase(); } DWORD WINAPI ConnectToDarunGrim2Thread( LPVOID lpParameter ) { DarunGrim *pDarunGrim=( DarunGrim * )lpParameter; IDAClientManager *pIDAClientManager; if( pDarunGrim && (pIDAClientManager = pDarunGrim->GetIDAClientManager()) ) { if( !pDarunGrim->LoadedSourceFile() ) { pIDAClientManager->ConnectToDarunGrim2( pDarunGrim->GetSourceFilename() ); } else { pIDAClientManager->ConnectToDarunGrim2( pDarunGrim->GetTargetFilename() ); } } return 1; } char *DarunGrim::GetSourceFilename() { return SourceFilename; } void DarunGrim::SetSourceFilename( char *source_filename ) { SourceFilename = source_filename; } char *DarunGrim::GetTargetFilename() { return TargetFilename; } void DarunGrim::SetTargetFilename( char *target_filename ) { TargetFilename = target_filename; } bool DarunGrim::LoadedSourceFile() { return IsLoadedSourceFile; } void DarunGrim::SetLoadedSourceFile( bool is_loaded ) { IsLoadedSourceFile = is_loaded; } bool DarunGrim::AcceptIDAClientsFromSocket( const char *storage_filename ) { Logger.Log(10, "%s: entry\n", __FUNCTION__ ); if( storage_filename ) { if( pStorageDB ) delete pStorageDB; pStorageDB = new DBWrapper( (char *) storage_filename ); } if( pStorageDB ) { pIDAClientManager->SetDatabase( pStorageDB ); } pIDAClientManager->StartIDAListener( DARUNGRIM2_PORT ); pOneIDAClientManagerTheSource=new OneIDAClientManager( pStorageDB ); pOneIDAClientManagerTheTarget=new OneIDAClientManager( pStorageDB ); //Create a thread that will call ConnectToDarunGrim2 one by one DWORD dwThreadId; CreateThread( NULL, 0, ConnectToDarunGrim2Thread, ( PVOID )this, 0, &dwThreadId ); pIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheSource, pDiffMachine? FALSE:pStorageDB?TRUE:FALSE ); SetLoadedSourceFile( TRUE ); CreateThread( NULL, 0, ConnectToDarunGrim2Thread, ( PVOID )this, 0, &dwThreadId ); pIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheTarget, pDiffMachine? FALSE:pStorageDB?TRUE:FALSE ); if( !pDiffMachine ) { Analyze(); } pIDAClientManager->SetMembers( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget, pDiffMachine ); pIDAClientManager->CreateIDACommandProcessorThread(); pIDAClientManager->StopIDAListener(); return TRUE; } bool DarunGrim::OpenDatabase() { Logger.Log(10, "%s: entry\n", __FUNCTION__ ); if( pStorageDB ) delete pStorageDB; pStorageDB = new DBWrapper( StorageFilename ); pStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_STATEMENT); pStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_START_ADDRESS_INDEX_STATEMENT); pStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_END_ADDRESS_INDEX_STATEMENT); pStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_STATEMENT); pStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_INDEX_STATEMENT); pStorageDB->ExecuteStatement(NULL,NULL,CREATE_FILE_INFO_TABLE_STATEMENT); return TRUE; } bool DarunGrim::LoadDiffResults( const char *storage_filename ) { pStorageDB = new DBWrapper( (char *) storage_filename ); if( pStorageDB ) { pDiffMachine = new DiffMachine(); if( pDiffMachine ) { pDiffMachine->Retrieve( *pStorageDB,TRUE, 1 , 2 ); return TRUE; } } return FALSE; } bool DarunGrim::Analyze() { Logger.Log(10, "%s: entry\n", __FUNCTION__ ); int source_file_id=1; int target_file_id=2; if( pStorageDB ) { pDiffMachine = new DiffMachine(); pDiffMachine->Retrieve( *pStorageDB,TRUE,source_file_id,target_file_id); } else if( pOneIDAClientManagerTheSource && pOneIDAClientManagerTheTarget ) { pDiffMachine = new DiffMachine( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget ); } if( pDiffMachine ) { pDiffMachine->Analyze(); pDiffMachine->Save( *pStorageDB ); } return TRUE; } bool DarunGrim::ShowOnIDA() { Logger.Log(10, "%s: entry\n", __FUNCTION__ ); //pDiffMachine->PrintMatchMapInfo(); if( pIDAClientManager ) { pIDAClientManager->SetMembers( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget, pDiffMachine ); pIDAClientManager->ShowResultsOnIDA(); pIDAClientManager->IDACommandProcessor(); return TRUE; } return FALSE; } void DarunGrim::ShowAddresses( unsigned long source_address, unsigned long target_address ) { if( pOneIDAClientManagerTheSource ) pOneIDAClientManagerTheSource->ShowAddress( source_address ); if( pOneIDAClientManagerTheTarget ) pOneIDAClientManagerTheTarget->ShowAddress( target_address ); } void DarunGrim::ColorAddress( int index, unsigned long start_address, unsigned long end_address,unsigned long color ) { if( index == 0 ) { if( pOneIDAClientManagerTheSource ) pOneIDAClientManagerTheSource->ColorAddress( start_address, end_address, color ); } else { if( pOneIDAClientManagerTheTarget ) pOneIDAClientManagerTheTarget->ColorAddress( start_address, end_address, color ); } } IDAClientManager *DarunGrim::GetIDAClientManager() { return pIDAClientManager; } <|endoftext|>
<commit_before>#include <ocean/displacement_map.h> #include <util/error.h> #include <util/util.h> namespace ocean { #define N_FFT_BATCHES 5 displacement_map::displacement_map(gpu::compute::command_queue queue, const surface_params& params) : queue(queue), wave_spectrum(queue.getInfo<CL_QUEUE_CONTEXT>(), params), fft_algorithm(queue, params.grid_size, N_FFT_BATCHES), displacement_map(queue.getInfo<CL_QUEUE_CONTEXT>(), params.grid_size, texture_format::TEXTURE_FORMAT_RGBA8), height_gradient_map(queue.getInfo<CL_QUEUE_CONTEXT>(), params.grid_size, texture_format::TEXTURE_FORMAT_RG16F) { int N = wave_spectrum.get_N(); int M = wave_spectrum.get_M(); auto context = queue.getInfo<CL_QUEUE_CONTEXT>(); size_t buf_size_bytes = N_FFT_BATCHES * (N + 2) * M * sizeof(float); fft_buffer = gpu::compute::buffer(context, CL_MEM_READ_WRITE, buf_size_bytes); load_export_kernel(); } displacement_map::shared_texture::shared_texture(gpu::compute::context& context, math::ivec2 size, texture_format format) { tex.init(size.x, size.y, format); tex.set_max_anisotropy(2); img = gpu::compute::graphics_image(context, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, tex.get_api_texture()); tex.generate_mipmap(); } void displacement_map::enqueue_generate(math::real time, const gpu::compute::event_vector *wait_events) { gpu::compute::event event; event = wave_spectrum.enqueue_generate(queue, time, fft_buffer, wait_events); event = fft_algorithm.enqueue_transform(queue, fft_buffer, &gpu::compute::event_vector({ event })); event = enqueue_export_kernel(&gpu::compute::event_vector({ event })); event.wait(); displacement_map.tex.generate_mipmap(); height_gradient_map.tex.generate_mipmap(); } void displacement_map::load_export_kernel() { auto program = gpu::compute::create_program_from_file(queue.getInfo<CL_QUEUE_CONTEXT>(), "kernels/export_to_texture.cl"); export_kernel = gpu::compute::kernel(program, "export_to_texture"); export_kernel.setArg(0, fft_buffer); export_kernel.setArg(1, wave_spectrum.get_N()); export_kernel.setArg(2, wave_spectrum.get_M()); export_kernel.setArg(3, displacement_map.img); export_kernel.setArg(4, height_gradient_map.img); } gpu::compute::event displacement_map::enqueue_export_kernel(const gpu::compute::event_vector *wait_events) { gpu::compute::event event; std::vector<gpu::compute::memory_object> gl_objects = { displacement_map.img, height_gradient_map.img }; queue.enqueueAcquireGLObjects(&gl_objects, wait_events, &event); gpu::compute::nd_range offset = { 0, 0 }, local_size = { 1, 1 }; gpu::compute::nd_range global_size = { static_cast<size_t>(wave_spectrum.get_N()), static_cast<size_t>(wave_spectrum.get_M()) }; queue.enqueueNDRangeKernel(export_kernel, offset, global_size, local_size, &gpu::compute::event_vector({ event }), &event); queue.enqueueReleaseGLObjects(&gl_objects, &gpu::compute::event_vector({ event }), &event); return event; } } // namespace ocean <commit_msg>move fft_buffer init to initializer list<commit_after>#include <ocean/displacement_map.h> #include <util/error.h> #include <util/util.h> namespace ocean { #define N_FFT_BATCHES 5 displacement_map::displacement_map(gpu::compute::command_queue queue, const surface_params& params) : queue(queue), wave_spectrum(queue.getInfo<CL_QUEUE_CONTEXT>(), params), fft_algorithm(queue, params.grid_size, N_FFT_BATCHES), fft_buffer(queue.getInfo<CL_QUEUE_CONTEXT>(), CL_MEM_READ_ONLY, N_FFT_BATCHES * (params.grid_size.x + 2) * params.grid_size.y * sizeof(float)), displacement_map(queue.getInfo<CL_QUEUE_CONTEXT>(), params.grid_size, texture_format::TEXTURE_FORMAT_RGBA8), height_gradient_map(queue.getInfo<CL_QUEUE_CONTEXT>(), params.grid_size, texture_format::TEXTURE_FORMAT_RG16F) { load_export_kernel(); } displacement_map::shared_texture::shared_texture(gpu::compute::context& context, math::ivec2 size, texture_format format) { tex.init(size.x, size.y, format); tex.set_max_anisotropy(2); img = gpu::compute::graphics_image(context, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, tex.get_api_texture()); tex.generate_mipmap(); } void displacement_map::enqueue_generate(math::real time, const gpu::compute::event_vector *wait_events) { gpu::compute::event event; event = wave_spectrum.enqueue_generate(queue, time, fft_buffer, wait_events); event = fft_algorithm.enqueue_transform(queue, fft_buffer, &gpu::compute::event_vector({ event })); event = enqueue_export_kernel(&gpu::compute::event_vector({ event })); event.wait(); displacement_map.tex.generate_mipmap(); height_gradient_map.tex.generate_mipmap(); } void displacement_map::load_export_kernel() { auto program = gpu::compute::create_program_from_file(queue.getInfo<CL_QUEUE_CONTEXT>(), "kernels/export_to_texture.cl"); export_kernel = gpu::compute::kernel(program, "export_to_texture"); export_kernel.setArg(0, fft_buffer); export_kernel.setArg(1, wave_spectrum.get_N()); export_kernel.setArg(2, wave_spectrum.get_M()); export_kernel.setArg(3, displacement_map.img); export_kernel.setArg(4, height_gradient_map.img); } gpu::compute::event displacement_map::enqueue_export_kernel(const gpu::compute::event_vector *wait_events) { gpu::compute::event event; std::vector<gpu::compute::memory_object> gl_objects = { displacement_map.img, height_gradient_map.img }; queue.enqueueAcquireGLObjects(&gl_objects, wait_events, &event); gpu::compute::nd_range offset = { 0, 0 }, local_size = { 1, 1 }; gpu::compute::nd_range global_size = { static_cast<size_t>(wave_spectrum.get_N()), static_cast<size_t>(wave_spectrum.get_M()) }; queue.enqueueNDRangeKernel(export_kernel, offset, global_size, local_size, &gpu::compute::event_vector({ event }), &event); queue.enqueueReleaseGLObjects(&gl_objects, &gpu::compute::event_vector({ event }), &event); return event; } } // namespace ocean <|endoftext|>
<commit_before>#include <cassert> #include <cstring> #include <cstdlib> #include <sstream> #include <iostream> #include <set> #include <unordered_set> #include "clause.h" #include "config.h" using namespace satsolver; Clause::Clause(int nb_var, std::shared_ptr<std::vector<int>> literals) { this->literals = std::unordered_set<int>() ; this->nb_variables = nb_var; for(std::vector<int>::iterator it = literals->begin(); it != literals->end(); ++it) { assert(*it != 0 && abs(*it) <= nb_var); this->literals.insert(*it) ; } if (WITH_WL) this->watched = std::pair<int,int>(0,0) ; this->aff = NULL ; } Clause::Clause(int nb_var, std::vector<int> literals) { this->literals = std::unordered_set<int>() ; this->nb_variables = nb_var; for(std::vector<int>::iterator it = literals.begin(); it != literals.end(); ++it) { assert(*it != 0 && abs(*it) <= nb_var); this->literals.insert(*it) ; } if (WITH_WL) this->watched = std::pair<int,int>(0,0) ; this->aff = NULL ; } Clause::Clause(const Clause &c){ this->literals = std::unordered_set<int>(c.literals) ; this->nb_variables = c.nb_variables ; if (WITH_WL) this->watched = std::pair<int,int>(c.watched) ; this->aff = c.aff ; } Clause& Clause::operator=(const Clause &that) { this->literals = that.literals; this->nb_variables = that.nb_variables; if (WITH_WL) this->watched = that.watched ; return *this; this->aff = that.aff ; } Clause::~Clause() { } int Clause::get_size() const { return (int) this->literals.size() ; } bool Clause::is_empty() const { return this->get_size() == 0 ; } bool Clause::contains_literal(int literal) const { assert(abs(literal)<=this->nb_variables && literal != 0); return this->literals.find(literal) != this->literals.end() ; } void Clause::add(int literal) { assert(abs(literal)<=this->nb_variables && literal != 0); this->literals.insert(literal) ; } void Clause::remove(int literal) { assert(abs(literal)<=this->nb_variables && literal != 0); this->literals.erase(literal) ; } bool Clause::is_tautology() const { for(int i = 1 ; i <= this->nb_variables ; i++) { if(this->contains_literal(i) && this->contains_literal(-i)) return true ; } return false ; } std::string Clause::to_string() { std::ostringstream oss; bool flag = false ; oss << "{" ; for(int i = 1 ; i <= this->nb_variables ; i++) { if(this->contains_literal(-i)) { if(flag) oss << "," ; flag = true ; oss << -i ; } if(this->contains_literal(i)) { if(flag) oss << "," ; flag = true ; oss << i ; } } oss << "}" ; if(WITH_WL) oss << " WL : " << this->fst_WL() << " & " << this->snd_WL() ; return oss.str() ; } std::string Clause::to_string2() { std::ostringstream oss; for(int i = 1 ; i <= this->nb_variables ; i++) { if(this->contains_literal(-i)) { oss << -i << " "; } if(this->contains_literal(i)) { oss << i << " "; } } oss << "0" ; return oss.str() ; } std::set<int> Clause::to_set() const { std::set<int> s = std::set<int>() ; for(auto l : this->literals) { if(!this->aff->is_false(l)) { s.insert(l) ; } } return s ; } bool Clause::contains_clause(satsolver::Clause &c) const { if(this->get_size() < c.get_size()) { return false ; } for(int i = 1 ; i <= this->nb_variables ; i++) { if(!this->contains_literal(i) && c.contains_literal(i)) return false ; if(!this->contains_literal(-i) && c.contains_literal(-i)) return false ; } return true ; } void Clause::init_WL() { assert(WITH_WL); assert(this->get_size() >= 2) ; std::unordered_set<int>::iterator it = this->literals.begin() ; this->watched.first = *it ; ++it ; this->watched.second = *it ; } int Clause::fst_WL() const{ assert(WITH_WL); return this->watched.first ; } int Clause::snd_WL() const{ assert(WITH_WL); return this->watched.second ; } bool Clause::is_WL(int x) { assert(WITH_WL); return this->watched.first == x || this->watched.second == x ; } void Clause::set_affectation(Affectation *a) { this->aff = a ; } int Clause::set_true(int x) { if (!WITH_WL) return 0; if(this->contains_literal(x) && !this->is_WL(x)) { // on installe x comme littéral surveillé if(this->aff->is_unknown(this->fst_WL())) // priorité aux littéraux vrais this->watched.first = x ; else this->watched.second = x ; return 0 ; } else if(this->contains_literal(x)) { // rien return 0 ; } else if(this->is_WL(-x)) { // on surveille un littéral qui a été mis à faux if(this->aff->is_true(this->fst_WL()) || this->aff->is_true(this->snd_WL())) return 0 ; // rien à faire, la clause est satisfaite for(auto literal : this->literals) { if(!this->aff->is_false(literal) && !this->is_WL(literal)) { // nouveau literal surveillé if(this->fst_WL() == -x) this->watched.first = literal ; else this->watched.second = literal ; return 0 ; // pas de propagation unitaire, on a trouvé un remplaçant } } // On n'a pas trouvé de remplaçant, il ne reste donc qu'un literal non faux if(this->fst_WL() != -x) return this->fst_WL() ; else return this->snd_WL() ; } return 0 ; } int Clause::set_false(int x) { return this->set_true(-x) ; } bool Clause::is_true() { for(auto l : this->literals) { if(this->aff->is_true(l)) return true ; } return false ; } int Clause::monome_begin() { if(this->literals.size() == 1) return *(this->literals.begin()) ; return 0 ; } int Clause::monome() { assert(!WITH_WL) ; int literal = 0, count = 0; for(auto l : literals) { if(this->aff->is_true(l)) return 0 ; else if(this->aff->is_unknown(l)) { if(count > 0) return 0 ; literal = l ; count ++ ; } } return literal ; } bool Clause::is_evaluated_to_false() const { if(WITH_WL) return (this->aff->is_false(this->fst_WL()) && this->aff->is_false(this->snd_WL())) ; for (auto literal : this->literals) if (!this->aff->is_false(literal)) return false; return true; } bool Clause::is_evaluated_to_true() const { if(WITH_WL) return (this->aff->is_true(this->fst_WL()) || this->aff->is_true(this->snd_WL())) ; for (auto literal : this->literals) if (this->aff->is_true(literal)) return true; return false; } void Clause::add_literals_to_vector(std::vector<int> &v) const { if(this->is_evaluated_to_true()) return ; for(auto l : this->literals) { // clause insatisfaite, on ajoute tous les littéraux non faux if(this->aff->is_unknown(l)) v.push_back(l) ; } } <commit_msg>Small update of true clauses detection.<commit_after>#include <cassert> #include <cstring> #include <cstdlib> #include <sstream> #include <iostream> #include <set> #include <unordered_set> #include "clause.h" #include "config.h" using namespace satsolver; Clause::Clause(int nb_var, std::shared_ptr<std::vector<int>> literals) { this->literals = std::unordered_set<int>() ; this->nb_variables = nb_var; for(std::vector<int>::iterator it = literals->begin(); it != literals->end(); ++it) { assert(*it != 0 && abs(*it) <= nb_var); this->literals.insert(*it) ; } if (WITH_WL) this->watched = std::pair<int,int>(0,0) ; this->aff = NULL ; } Clause::Clause(int nb_var, std::vector<int> literals) { this->literals = std::unordered_set<int>() ; this->nb_variables = nb_var; for(std::vector<int>::iterator it = literals.begin(); it != literals.end(); ++it) { assert(*it != 0 && abs(*it) <= nb_var); this->literals.insert(*it) ; } if (WITH_WL) this->watched = std::pair<int,int>(0,0) ; this->aff = NULL ; } Clause::Clause(const Clause &c){ this->literals = std::unordered_set<int>(c.literals) ; this->nb_variables = c.nb_variables ; if (WITH_WL) this->watched = std::pair<int,int>(c.watched) ; this->aff = c.aff ; } Clause& Clause::operator=(const Clause &that) { this->literals = that.literals; this->nb_variables = that.nb_variables; if (WITH_WL) this->watched = that.watched ; return *this; this->aff = that.aff ; } Clause::~Clause() { } int Clause::get_size() const { return (int) this->literals.size() ; } bool Clause::is_empty() const { return this->get_size() == 0 ; } bool Clause::contains_literal(int literal) const { assert(abs(literal)<=this->nb_variables && literal != 0); return this->literals.find(literal) != this->literals.end() ; } void Clause::add(int literal) { assert(abs(literal)<=this->nb_variables && literal != 0); this->literals.insert(literal) ; } void Clause::remove(int literal) { assert(abs(literal)<=this->nb_variables && literal != 0); this->literals.erase(literal) ; } bool Clause::is_tautology() const { for(int i = 1 ; i <= this->nb_variables ; i++) { if(this->contains_literal(i) && this->contains_literal(-i)) return true ; } return false ; } std::string Clause::to_string() { std::ostringstream oss; bool flag = false ; oss << "{" ; for(int i = 1 ; i <= this->nb_variables ; i++) { if(this->contains_literal(-i)) { if(flag) oss << "," ; flag = true ; oss << -i ; } if(this->contains_literal(i)) { if(flag) oss << "," ; flag = true ; oss << i ; } } oss << "}" ; if(WITH_WL) oss << " WL : " << this->fst_WL() << " & " << this->snd_WL() ; return oss.str() ; } std::string Clause::to_string2() { std::ostringstream oss; for(int i = 1 ; i <= this->nb_variables ; i++) { if(this->contains_literal(-i)) { oss << -i << " "; } if(this->contains_literal(i)) { oss << i << " "; } } oss << "0" ; return oss.str() ; } std::set<int> Clause::to_set() const { std::set<int> s = std::set<int>() ; for(auto l : this->literals) { if(!this->aff->is_false(l)) { s.insert(l) ; } } return s ; } bool Clause::contains_clause(satsolver::Clause &c) const { if(this->get_size() < c.get_size()) { return false ; } for(int i = 1 ; i <= this->nb_variables ; i++) { if(!this->contains_literal(i) && c.contains_literal(i)) return false ; if(!this->contains_literal(-i) && c.contains_literal(-i)) return false ; } return true ; } void Clause::init_WL() { assert(WITH_WL); assert(this->get_size() >= 2) ; std::unordered_set<int>::iterator it = this->literals.begin() ; this->watched.first = *it ; ++it ; this->watched.second = *it ; } int Clause::fst_WL() const{ assert(WITH_WL); return this->watched.first ; } int Clause::snd_WL() const{ assert(WITH_WL); return this->watched.second ; } bool Clause::is_WL(int x) { assert(WITH_WL); return this->watched.first == x || this->watched.second == x ; } void Clause::set_affectation(Affectation *a) { this->aff = a ; } int Clause::set_true(int x) { if (!WITH_WL) return 0; if(this->contains_literal(x) && !this->is_WL(x)) { // on installe x comme littéral surveillé if(this->aff->is_unknown(this->fst_WL())) // priorité aux littéraux vrais this->watched.first = x ; else this->watched.second = x ; return 0 ; } else if(this->contains_literal(x)) { // rien return 0 ; } else if(this->is_WL(-x)) { // on surveille un littéral qui a été mis à faux if(this->aff->is_true(this->fst_WL()) || this->aff->is_true(this->snd_WL())) return 0 ; // rien à faire, la clause est satisfaite for(auto literal : this->literals) { if(!this->aff->is_false(literal) && !this->is_WL(literal)) { // nouveau literal surveillé if(this->fst_WL() == -x) this->watched.first = literal ; else this->watched.second = literal ; return 0 ; // pas de propagation unitaire, on a trouvé un remplaçant } } // On n'a pas trouvé de remplaçant, il ne reste donc qu'un literal non faux if(this->fst_WL() != -x) return this->fst_WL() ; else return this->snd_WL() ; } return 0 ; } int Clause::set_false(int x) { return this->set_true(-x) ; } bool Clause::is_true() { for(auto l : this->literals) { if(this->aff->is_true(l)) return true ; } return false ; } int Clause::monome_begin() { if(this->literals.size() == 1) return *(this->literals.begin()) ; return 0 ; } int Clause::monome() { assert(!WITH_WL) ; int literal = 0, count = 0; for(auto l : literals) { if(this->aff->is_true(l)) return 0 ; else if(this->aff->is_unknown(l)) { if(count > 0) return 0 ; literal = l ; count ++ ; } } return literal ; } bool Clause::is_evaluated_to_false() const { if(WITH_WL) return (this->aff->is_false(this->fst_WL()) && this->aff->is_false(this->snd_WL())) ; for (auto literal : this->literals) if (!this->aff->is_false(literal)) return false; return true; } bool Clause::is_evaluated_to_true() const { if(WITH_WL && (this->aff->is_true(this->fst_WL()) || this->aff->is_true(this->snd_WL()))) return true ; for (auto literal : this->literals) if (this->aff->is_true(literal)) return true; return false; } void Clause::add_literals_to_vector(std::vector<int> &v) const { if(this->is_evaluated_to_true()) return ; for(auto l : this->literals) { // clause insatisfaite, on ajoute tous les littéraux non faux if(this->aff->is_unknown(l)) v.push_back(l) ; } } <|endoftext|>
<commit_before>/******************************************************************************* * ALMA - Atacama Large Millimeter Array * Copyright (c) ESO - European Southern Observatory, 2011 * (in the framework of the ALMA collaboration). * All rights reserved. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *******************************************************************************/ /************************************************************************* * E.S.O. - VLT project * * "@(#) $Id: acscomponentImpl.cpp,v 1.40 2012/05/02 09:48:14 bjeram Exp $" * * who when what * -------- -------- -------------------------------------------------- * rcirami 2003-08-28 created */ #include "acscomponentImpl.h" #include "loggingLogger.h" #include "acsErrTypeComponent.h" #include <string> using namespace maci; using namespace acscomponent; // // ACSComponent Constructor // ACSComponentImpl::ACSComponentImpl( const ACE_CString& name, maci::ContainerServices *containerServices) : Logging::Loggable(containerServices->getLogger()), m_name(name), m_containerServices_p(containerServices) { ACS_TRACE("acscomponent::ACSComponentImpl::ACSComponentImpl"); // Check if the ContainerServices is NULL // Now the ContainerServices is very important and does a lof things // and the component if (containerServices==NULL) { acsErrTypeComponent::InvalidContainerServicesExImpl ex(__FILE__,__LINE__,"acscomponent::ACSComponentImpl::ACSComponentImpl"); throw ex; } } // // ACSComponent Destructor // ACSComponentImpl::~ACSComponentImpl() { ACS_TRACE("acscomponent::ACSComponentImpl::~ACSComponentImpl"); } /*********************** IDL interface **********************/ char * ACSComponentImpl::name () { return CORBA::string_dup(m_name.c_str()); } ACS::ComponentStates ACSComponentImpl::componentState () { if (m_containerServices_p==NULL) { return ACS::COMPSTATE_UNKNOWN; } else if (m_containerServices_p->getComponentStateManager()==NULL) { return ACS::COMPSTATE_UNKNOWN; } else return m_containerServices_p->getComponentStateManager()->getCurrentState(); } /********************** LifeCycle methods ***********************/ void ACSComponentImpl::initialize() { ACS_TRACE("acscomponent::ACSComponentImpl::initialize"); } void ACSComponentImpl::execute() { ACS_TRACE("acscomponent::ACSComponentImpl::execute"); } void ACSComponentImpl::cleanUp() { ACS_TRACE("acscomponent::ACSComponentImpl::cleanUp"); } void ACSComponentImpl::aboutToAbort() { ACS_TRACE("acscomponent::ACSComponentImpl::cleanUp"); } void ACSComponentImpl::__initialize() { ACS_TRACE("acscomponent::ACSComponentImpl::__initialize"); try { initialize(); } catch (ACSErr::ACSbaseExImpl &ex) { throw acsErrTypeLifeCycle::LifeCycleExImpl(ex, __FILE__,__LINE__,"ACSComponentImpl::__initialize"); }catch(const std::exception &stdex){ ACSErrTypeCommon::StdExceptionExImpl ex(__FILE__, __LINE__, __FUNCTION__); ex.setWhat(stdex.what()); acsErrTypeLifeCycle::LifeCycleExImpl lex(ex, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: initialize can throw just ACS based exceptions. Please check your code."); throw lex; }catch( CORBA::SystemException &_ex ) { ACSErrTypeCommon::CORBAProblemExImpl corbaProblemEx(__FILE__, __LINE__, __FUNCTION__); corbaProblemEx.setMinor(_ex.minor()); corbaProblemEx.setCompletionStatus(_ex.completed()); corbaProblemEx.setInfo(_ex._info().c_str()); acsErrTypeLifeCycle::LifeCycleExImpl lex(corbaProblemEx, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: initialize can throw just ACS based exceptions. Please check your code."); throw lex; }catch( CORBA::UserException &_ex ) { ACSErrTypeCommon::CORBAUserExceptionExImpl corbaProblemEx(__FILE__, __LINE__, __FUNCTION__); corbaProblemEx.setInfo(_ex._info()); acsErrTypeLifeCycle::LifeCycleExImpl lex(__FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: initialize can throw just ACS based exceptions. Please check your code."); throw lex; }catch(...){ ACSErrTypeCommon::UnknownExImpl ex(__FILE__, __LINE__, __FUNCTION__); acsErrTypeLifeCycle::LifeCycleExImpl lex(ex, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: initialize can throw just ACS based exceptions. Please check your code."); throw lex; } } void ACSComponentImpl::__execute() { ACS_TRACE("acscomponent::ACSComponentImpl::__execute"); /* startAllThreads is not there but it might be goot to put there so that all threads are just created in suspend mode and than startAllThreads would resume them if (getContainerServices()->getThreadManager()->startAllThreads() == false) { throw acsErrTypeLifeCycle::LifeCycleExImpl(ex,__FILE__,__LINE__,"ACSComponentImpl::__execute(): startAllThreads failed"); } */ try { execute(); } catch (ACSErr::ACSbaseExImpl &ex) { throw acsErrTypeLifeCycle::LifeCycleExImpl(ex,__FILE__,__LINE__,"ACSComponentImpl::__execute"); }catch(const std::exception &stdex){ ACSErrTypeCommon::StdExceptionExImpl ex(__FILE__, __LINE__, __FUNCTION__); ex.setWhat(stdex.what()); acsErrTypeLifeCycle::LifeCycleExImpl lex(ex, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: execute can throw just ACS based exceptions. Please check your code."); throw lex; }catch( CORBA::SystemException &_ex ) { ACSErrTypeCommon::CORBAProblemExImpl corbaProblemEx(__FILE__, __LINE__, __FUNCTION__); corbaProblemEx.setMinor(_ex.minor()); corbaProblemEx.setCompletionStatus(_ex.completed()); corbaProblemEx.setInfo(_ex._info().c_str()); acsErrTypeLifeCycle::LifeCycleExImpl lex(corbaProblemEx, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: execute can throw just ACS based exceptions. Please check your code."); throw lex; }catch( CORBA::UserException &_ex ) { ACSErrTypeCommon::CORBAUserExceptionExImpl corbaProblemEx(__FILE__, __LINE__, __FUNCTION__); corbaProblemEx.setInfo(_ex._info()); acsErrTypeLifeCycle::LifeCycleExImpl lex(__FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: execute can throw just ACS based exceptions. Please check your code."); throw lex; }catch(...){ ACSErrTypeCommon::UnknownExImpl ex(__FILE__, __LINE__, __FUNCTION__); acsErrTypeLifeCycle::LifeCycleExImpl lex(ex, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: execute can throw just ACS based exceptions. Please check your code."); throw lex; } } void ACSComponentImpl::__aboutToAbort() { ACS_TRACE("acscomponent::ACSComponentImpl::__aboutToAbort"); if (getContainerServices()->getThreadManager()->stopAll() == false) { throw acsErrTypeLifeCycle::StoppingThreadsFailureExImpl(__FILE__,__LINE__,"ACSComponentImpl::__aboutToAbort"); } try { aboutToAbort(); } catch (ACSErr::ACSbaseExImpl &ex) { throw acsErrTypeLifeCycle::LifeCycleExImpl(ex,__FILE__,__LINE__,"ACSComponentImpl::__aboutToAbort"); }catch(const std::exception &stdex){ ACSErrTypeCommon::StdExceptionExImpl ex(__FILE__, __LINE__, __FUNCTION__); ex.setWhat(stdex.what()); acsErrTypeLifeCycle::LifeCycleExImpl lex(ex, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: aboutToAbort can throw just ACS based exceptions. Please check your code."); throw lex; }catch( CORBA::SystemException &_ex ) { ACSErrTypeCommon::CORBAProblemExImpl corbaProblemEx(__FILE__, __LINE__, __FUNCTION__); corbaProblemEx.setMinor(_ex.minor()); corbaProblemEx.setCompletionStatus(_ex.completed()); corbaProblemEx.setInfo(_ex._info().c_str()); acsErrTypeLifeCycle::LifeCycleExImpl lex(corbaProblemEx, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: aboutToAbort can throw just ACS based exceptions. Please check your code."); throw lex; }catch( CORBA::UserException &_ex ) { ACSErrTypeCommon::CORBAUserExceptionExImpl corbaProblemEx(__FILE__, __LINE__, __FUNCTION__); corbaProblemEx.setInfo(_ex._info()); acsErrTypeLifeCycle::LifeCycleExImpl lex(__FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: aboutToAbort can throw just ACS based exceptions. Please check your code."); throw lex; }catch(...){ ACSErrTypeCommon::UnknownExImpl ex(__FILE__, __LINE__, __FUNCTION__); acsErrTypeLifeCycle::LifeCycleExImpl lex(ex, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: aboutToAbort can throw just ACS based exceptions. Please check your code."); throw lex; } } void ACSComponentImpl::__cleanUp() { ACS_TRACE("acscomponent::ACSComponentImpl::__cleanUp"); try { cleanUp(); } catch(ACSErr::ACSbaseExImpl &ex) { throw acsErrTypeLifeCycle::LifeCycleExImpl(ex, __FILE__,__LINE__,"ACSComponentImpl::__cleanUp"); }catch(const std::exception &stdex){ ACSErrTypeCommon::StdExceptionExImpl ex(__FILE__, __LINE__, __FUNCTION__); ex.setWhat(stdex.what()); acsErrTypeLifeCycle::LifeCycleExImpl lex(ex, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: cleanUp can throw just ACS based exceptions. Please check your code."); throw lex; }catch( CORBA::SystemException &_ex ) { ACSErrTypeCommon::CORBAProblemExImpl corbaProblemEx(__FILE__, __LINE__, __FUNCTION__); corbaProblemEx.setMinor(_ex.minor()); corbaProblemEx.setCompletionStatus(_ex.completed()); corbaProblemEx.setInfo(_ex._info().c_str()); acsErrTypeLifeCycle::LifeCycleExImpl lex(corbaProblemEx, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: cleanUp can throw just ACS based exceptions. Please check your code."); throw lex; }catch( CORBA::UserException &_ex ) { ACSErrTypeCommon::CORBAUserExceptionExImpl corbaProblemEx(__FILE__, __LINE__, __FUNCTION__); corbaProblemEx.setInfo(_ex._info()); acsErrTypeLifeCycle::LifeCycleExImpl lex(__FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: cleanUp can throw just ACS based exceptions. Please check your code."); throw lex; }catch(...){ ACSErrTypeCommon::UnknownExImpl ex(__FILE__, __LINE__, __FUNCTION__); acsErrTypeLifeCycle::LifeCycleExImpl lex(ex, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: cleanUp can throw just ACS based exceptions. Please check your code."); throw lex; } // just in case if a user does not stop the threads we stop them here if (getContainerServices()->getThreadManager()->stopAll() == false) { throw acsErrTypeLifeCycle::StoppingThreadsFailureExImpl(__FILE__,__LINE__,"ACSComponentImpl::__cleanUp"); } } /******************************* protected methods *******************************/ maci::ContainerServices* ACSComponentImpl::getContainerServices() { return GetImpl(m_containerServices_p); } <commit_msg>name() builds the CORBA::string by getting the name of the component with componentName().<commit_after>/******************************************************************************* * ALMA - Atacama Large Millimeter Array * Copyright (c) ESO - European Southern Observatory, 2011 * (in the framework of the ALMA collaboration). * All rights reserved. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *******************************************************************************/ /************************************************************************* * E.S.O. - VLT project * * "@(#) $Id: acscomponentImpl.cpp,v 1.41 2013/01/16 16:22:16 acaproni Exp $" * * who when what * -------- -------- -------------------------------------------------- * rcirami 2003-08-28 created */ #include "acscomponentImpl.h" #include "loggingLogger.h" #include "acsErrTypeComponent.h" #include <string> using namespace maci; using namespace acscomponent; // // ACSComponent Constructor // ACSComponentImpl::ACSComponentImpl( const ACE_CString& name, maci::ContainerServices *containerServices) : Logging::Loggable(containerServices->getLogger()), m_name(name), m_containerServices_p(containerServices) { ACS_TRACE("acscomponent::ACSComponentImpl::ACSComponentImpl"); // Check if the ContainerServices is NULL // Now the ContainerServices is very important and does a lof things // and the component if (containerServices==NULL) { acsErrTypeComponent::InvalidContainerServicesExImpl ex(__FILE__,__LINE__,"acscomponent::ACSComponentImpl::ACSComponentImpl"); throw ex; } } // // ACSComponent Destructor // ACSComponentImpl::~ACSComponentImpl() { ACS_TRACE("acscomponent::ACSComponentImpl::~ACSComponentImpl"); } /*********************** IDL interface **********************/ char * ACSComponentImpl::name () { return CORBA::string_dup(componentName()); } ACS::ComponentStates ACSComponentImpl::componentState () { if (m_containerServices_p==NULL) { return ACS::COMPSTATE_UNKNOWN; } else if (m_containerServices_p->getComponentStateManager()==NULL) { return ACS::COMPSTATE_UNKNOWN; } else return m_containerServices_p->getComponentStateManager()->getCurrentState(); } /********************** LifeCycle methods ***********************/ void ACSComponentImpl::initialize() { ACS_TRACE("acscomponent::ACSComponentImpl::initialize"); } void ACSComponentImpl::execute() { ACS_TRACE("acscomponent::ACSComponentImpl::execute"); } void ACSComponentImpl::cleanUp() { ACS_TRACE("acscomponent::ACSComponentImpl::cleanUp"); } void ACSComponentImpl::aboutToAbort() { ACS_TRACE("acscomponent::ACSComponentImpl::cleanUp"); } void ACSComponentImpl::__initialize() { ACS_TRACE("acscomponent::ACSComponentImpl::__initialize"); try { initialize(); } catch (ACSErr::ACSbaseExImpl &ex) { throw acsErrTypeLifeCycle::LifeCycleExImpl(ex, __FILE__,__LINE__,"ACSComponentImpl::__initialize"); }catch(const std::exception &stdex){ ACSErrTypeCommon::StdExceptionExImpl ex(__FILE__, __LINE__, __FUNCTION__); ex.setWhat(stdex.what()); acsErrTypeLifeCycle::LifeCycleExImpl lex(ex, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: initialize can throw just ACS based exceptions. Please check your code."); throw lex; }catch( CORBA::SystemException &_ex ) { ACSErrTypeCommon::CORBAProblemExImpl corbaProblemEx(__FILE__, __LINE__, __FUNCTION__); corbaProblemEx.setMinor(_ex.minor()); corbaProblemEx.setCompletionStatus(_ex.completed()); corbaProblemEx.setInfo(_ex._info().c_str()); acsErrTypeLifeCycle::LifeCycleExImpl lex(corbaProblemEx, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: initialize can throw just ACS based exceptions. Please check your code."); throw lex; }catch( CORBA::UserException &_ex ) { ACSErrTypeCommon::CORBAUserExceptionExImpl corbaProblemEx(__FILE__, __LINE__, __FUNCTION__); corbaProblemEx.setInfo(_ex._info()); acsErrTypeLifeCycle::LifeCycleExImpl lex(__FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: initialize can throw just ACS based exceptions. Please check your code."); throw lex; }catch(...){ ACSErrTypeCommon::UnknownExImpl ex(__FILE__, __LINE__, __FUNCTION__); acsErrTypeLifeCycle::LifeCycleExImpl lex(ex, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: initialize can throw just ACS based exceptions. Please check your code."); throw lex; } } void ACSComponentImpl::__execute() { ACS_TRACE("acscomponent::ACSComponentImpl::__execute"); /* startAllThreads is not there but it might be goot to put there so that all threads are just created in suspend mode and than startAllThreads would resume them if (getContainerServices()->getThreadManager()->startAllThreads() == false) { throw acsErrTypeLifeCycle::LifeCycleExImpl(ex,__FILE__,__LINE__,"ACSComponentImpl::__execute(): startAllThreads failed"); } */ try { execute(); } catch (ACSErr::ACSbaseExImpl &ex) { throw acsErrTypeLifeCycle::LifeCycleExImpl(ex,__FILE__,__LINE__,"ACSComponentImpl::__execute"); }catch(const std::exception &stdex){ ACSErrTypeCommon::StdExceptionExImpl ex(__FILE__, __LINE__, __FUNCTION__); ex.setWhat(stdex.what()); acsErrTypeLifeCycle::LifeCycleExImpl lex(ex, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: execute can throw just ACS based exceptions. Please check your code."); throw lex; }catch( CORBA::SystemException &_ex ) { ACSErrTypeCommon::CORBAProblemExImpl corbaProblemEx(__FILE__, __LINE__, __FUNCTION__); corbaProblemEx.setMinor(_ex.minor()); corbaProblemEx.setCompletionStatus(_ex.completed()); corbaProblemEx.setInfo(_ex._info().c_str()); acsErrTypeLifeCycle::LifeCycleExImpl lex(corbaProblemEx, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: execute can throw just ACS based exceptions. Please check your code."); throw lex; }catch( CORBA::UserException &_ex ) { ACSErrTypeCommon::CORBAUserExceptionExImpl corbaProblemEx(__FILE__, __LINE__, __FUNCTION__); corbaProblemEx.setInfo(_ex._info()); acsErrTypeLifeCycle::LifeCycleExImpl lex(__FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: execute can throw just ACS based exceptions. Please check your code."); throw lex; }catch(...){ ACSErrTypeCommon::UnknownExImpl ex(__FILE__, __LINE__, __FUNCTION__); acsErrTypeLifeCycle::LifeCycleExImpl lex(ex, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: execute can throw just ACS based exceptions. Please check your code."); throw lex; } } void ACSComponentImpl::__aboutToAbort() { ACS_TRACE("acscomponent::ACSComponentImpl::__aboutToAbort"); if (getContainerServices()->getThreadManager()->stopAll() == false) { throw acsErrTypeLifeCycle::StoppingThreadsFailureExImpl(__FILE__,__LINE__,"ACSComponentImpl::__aboutToAbort"); } try { aboutToAbort(); } catch (ACSErr::ACSbaseExImpl &ex) { throw acsErrTypeLifeCycle::LifeCycleExImpl(ex,__FILE__,__LINE__,"ACSComponentImpl::__aboutToAbort"); }catch(const std::exception &stdex){ ACSErrTypeCommon::StdExceptionExImpl ex(__FILE__, __LINE__, __FUNCTION__); ex.setWhat(stdex.what()); acsErrTypeLifeCycle::LifeCycleExImpl lex(ex, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: aboutToAbort can throw just ACS based exceptions. Please check your code."); throw lex; }catch( CORBA::SystemException &_ex ) { ACSErrTypeCommon::CORBAProblemExImpl corbaProblemEx(__FILE__, __LINE__, __FUNCTION__); corbaProblemEx.setMinor(_ex.minor()); corbaProblemEx.setCompletionStatus(_ex.completed()); corbaProblemEx.setInfo(_ex._info().c_str()); acsErrTypeLifeCycle::LifeCycleExImpl lex(corbaProblemEx, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: aboutToAbort can throw just ACS based exceptions. Please check your code."); throw lex; }catch( CORBA::UserException &_ex ) { ACSErrTypeCommon::CORBAUserExceptionExImpl corbaProblemEx(__FILE__, __LINE__, __FUNCTION__); corbaProblemEx.setInfo(_ex._info()); acsErrTypeLifeCycle::LifeCycleExImpl lex(__FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: aboutToAbort can throw just ACS based exceptions. Please check your code."); throw lex; }catch(...){ ACSErrTypeCommon::UnknownExImpl ex(__FILE__, __LINE__, __FUNCTION__); acsErrTypeLifeCycle::LifeCycleExImpl lex(ex, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: aboutToAbort can throw just ACS based exceptions. Please check your code."); throw lex; } } void ACSComponentImpl::__cleanUp() { ACS_TRACE("acscomponent::ACSComponentImpl::__cleanUp"); try { cleanUp(); } catch(ACSErr::ACSbaseExImpl &ex) { throw acsErrTypeLifeCycle::LifeCycleExImpl(ex, __FILE__,__LINE__,"ACSComponentImpl::__cleanUp"); }catch(const std::exception &stdex){ ACSErrTypeCommon::StdExceptionExImpl ex(__FILE__, __LINE__, __FUNCTION__); ex.setWhat(stdex.what()); acsErrTypeLifeCycle::LifeCycleExImpl lex(ex, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: cleanUp can throw just ACS based exceptions. Please check your code."); throw lex; }catch( CORBA::SystemException &_ex ) { ACSErrTypeCommon::CORBAProblemExImpl corbaProblemEx(__FILE__, __LINE__, __FUNCTION__); corbaProblemEx.setMinor(_ex.minor()); corbaProblemEx.setCompletionStatus(_ex.completed()); corbaProblemEx.setInfo(_ex._info().c_str()); acsErrTypeLifeCycle::LifeCycleExImpl lex(corbaProblemEx, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: cleanUp can throw just ACS based exceptions. Please check your code."); throw lex; }catch( CORBA::UserException &_ex ) { ACSErrTypeCommon::CORBAUserExceptionExImpl corbaProblemEx(__FILE__, __LINE__, __FUNCTION__); corbaProblemEx.setInfo(_ex._info()); acsErrTypeLifeCycle::LifeCycleExImpl lex(__FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: cleanUp can throw just ACS based exceptions. Please check your code."); throw lex; }catch(...){ ACSErrTypeCommon::UnknownExImpl ex(__FILE__, __LINE__, __FUNCTION__); acsErrTypeLifeCycle::LifeCycleExImpl lex(ex, __FILE__,__LINE__, __FUNCTION__); lex.addData("WARNING:", "component lifecylce method: cleanUp can throw just ACS based exceptions. Please check your code."); throw lex; } // just in case if a user does not stop the threads we stop them here if (getContainerServices()->getThreadManager()->stopAll() == false) { throw acsErrTypeLifeCycle::StoppingThreadsFailureExImpl(__FILE__,__LINE__,"ACSComponentImpl::__cleanUp"); } } /******************************* protected methods *******************************/ maci::ContainerServices* ACSComponentImpl::getContainerServices() { return GetImpl(m_containerServices_p); } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2011, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * 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 John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "Gaffer/CompoundPlug.h" #include "Gaffer/PlugIterator.h" #include "GafferUI/ArrayNodule.h" #include "GafferUI/LinearContainer.h" #include "boost/bind.hpp" #include "boost/bind/placeholders.hpp" using namespace GafferUI; using namespace Imath; using namespace std; IE_CORE_DEFINERUNTIMETYPED( ArrayNodule ); ArrayNodule::ArrayNodule( Gaffer::CompoundPlugPtr plug ) : Nodule( plug ) { m_row = new LinearContainer( "row", LinearContainer::X, LinearContainer::Centre, 0.0f ); addChild( m_row ); plug->childAddedSignal().connect( boost::bind( &ArrayNodule::childAdded, this, ::_1, ::_2 ) ); plug->childRemovedSignal().connect( boost::bind( &ArrayNodule::childRemoved, this, ::_1, ::_2 ) ); Gaffer::PlugIterator it = Gaffer::PlugIterator( plug->children().begin(), plug->children().end() ); Gaffer::PlugIterator end = Gaffer::PlugIterator( plug->children().end(), plug->children().end() ); for( ; it!=end; it++ ) { NodulePtr nodule = Nodule::create( *it ); if( nodule ) { m_row->addChild( nodule ); } } m_row->renderRequestSignal().connect( boost::bind( &ArrayNodule::childRenderRequest, this, ::_1 ) ); } ArrayNodule::~ArrayNodule() { } Imath::Box3f ArrayNodule::bound() const { return m_row->bound(); } void ArrayNodule::doRender( IECore::RendererPtr renderer ) const { m_row->render( renderer ); } bool ArrayNodule::acceptsChild( Gaffer::ConstGraphComponentPtr potentialChild ) const { return children().size()==0; } NodulePtr ArrayNodule::nodule( Gaffer::ConstPlugPtr plug ) { ChildNoduleIterator it = ChildNoduleIterator( m_row->children().begin(), m_row->children().end() ); ChildNoduleIterator end = ChildNoduleIterator( m_row->children().end(), m_row->children().end() ); for( ; it!=end; it++ ) { if( (*it)->plug() == plug ) { return *it; } } return 0; } ConstNodulePtr ArrayNodule::nodule( Gaffer::ConstPlugPtr plug ) const { // preferring the nasty casts over mainaining two nearly identical implementations return const_cast<ArrayNodule *>( this )->nodule( plug ); } void ArrayNodule::childAdded( Gaffer::GraphComponentPtr parent, Gaffer::GraphComponentPtr child ) { Gaffer::PlugPtr plug = IECore::runTimeCast<Gaffer::Plug>( child ); if( !plug ) { return; } NodulePtr nodule = Nodule::create( plug ); if( nodule ) { m_row->addChild( nodule ); } } void ArrayNodule::childRemoved( Gaffer::GraphComponentPtr parent, Gaffer::GraphComponentPtr child ) { Gaffer::PlugPtr plug = IECore::runTimeCast<Gaffer::Plug>( child ); if( !plug ) { return; } ChildNoduleIterator it = ChildNoduleIterator( m_row->children().begin(), m_row->children().end() ); ChildNoduleIterator end = ChildNoduleIterator( m_row->children().end(), m_row->children().end() ); for( ; it!=end; it++ ) { if( (*it)->plug() == plug ) { m_row->removeChild( *it ); break; } } } void ArrayNodule::childRenderRequest( Gadget *child ) { renderRequestSignal()( this ); } <commit_msg>Removing whitespace.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2011, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * 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 John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "Gaffer/CompoundPlug.h" #include "Gaffer/PlugIterator.h" #include "GafferUI/ArrayNodule.h" #include "GafferUI/LinearContainer.h" #include "boost/bind.hpp" #include "boost/bind/placeholders.hpp" using namespace GafferUI; using namespace Imath; using namespace std; IE_CORE_DEFINERUNTIMETYPED( ArrayNodule ); ArrayNodule::ArrayNodule( Gaffer::CompoundPlugPtr plug ) : Nodule( plug ) { m_row = new LinearContainer( "row", LinearContainer::X, LinearContainer::Centre, 0.0f ); addChild( m_row ); plug->childAddedSignal().connect( boost::bind( &ArrayNodule::childAdded, this, ::_1, ::_2 ) ); plug->childRemovedSignal().connect( boost::bind( &ArrayNodule::childRemoved, this, ::_1, ::_2 ) ); Gaffer::PlugIterator it = Gaffer::PlugIterator( plug->children().begin(), plug->children().end() ); Gaffer::PlugIterator end = Gaffer::PlugIterator( plug->children().end(), plug->children().end() ); for( ; it!=end; it++ ) { NodulePtr nodule = Nodule::create( *it ); if( nodule ) { m_row->addChild( nodule ); } } m_row->renderRequestSignal().connect( boost::bind( &ArrayNodule::childRenderRequest, this, ::_1 ) ); } ArrayNodule::~ArrayNodule() { } Imath::Box3f ArrayNodule::bound() const { return m_row->bound(); } void ArrayNodule::doRender( IECore::RendererPtr renderer ) const { m_row->render( renderer ); } bool ArrayNodule::acceptsChild( Gaffer::ConstGraphComponentPtr potentialChild ) const { return children().size()==0; } NodulePtr ArrayNodule::nodule( Gaffer::ConstPlugPtr plug ) { ChildNoduleIterator it = ChildNoduleIterator( m_row->children().begin(), m_row->children().end() ); ChildNoduleIterator end = ChildNoduleIterator( m_row->children().end(), m_row->children().end() ); for( ; it!=end; it++ ) { if( (*it)->plug() == plug ) { return *it; } } return 0; } ConstNodulePtr ArrayNodule::nodule( Gaffer::ConstPlugPtr plug ) const { // preferring the nasty casts over mainaining two nearly identical implementations return const_cast<ArrayNodule *>( this )->nodule( plug ); } void ArrayNodule::childAdded( Gaffer::GraphComponentPtr parent, Gaffer::GraphComponentPtr child ) { Gaffer::PlugPtr plug = IECore::runTimeCast<Gaffer::Plug>( child ); if( !plug ) { return; } NodulePtr nodule = Nodule::create( plug ); if( nodule ) { m_row->addChild( nodule ); } } void ArrayNodule::childRemoved( Gaffer::GraphComponentPtr parent, Gaffer::GraphComponentPtr child ) { Gaffer::PlugPtr plug = IECore::runTimeCast<Gaffer::Plug>( child ); if( !plug ) { return; } ChildNoduleIterator it = ChildNoduleIterator( m_row->children().begin(), m_row->children().end() ); ChildNoduleIterator end = ChildNoduleIterator( m_row->children().end(), m_row->children().end() ); for( ; it!=end; it++ ) { if( (*it)->plug() == plug ) { m_row->removeChild( *it ); break; } } } void ArrayNodule::childRenderRequest( Gadget *child ) { renderRequestSignal()( this ); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AreaChartType.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2007-05-22 18:43:44 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "AreaChartType.hxx" #include "macros.hxx" #include "servicenames_charttypes.hxx" using namespace ::com::sun::star; namespace chart { AreaChartType::AreaChartType( const uno::Reference< uno::XComponentContext > & xContext ) : ChartType( xContext ) {} AreaChartType::AreaChartType( const AreaChartType & rOther ) : ChartType( rOther ) {} AreaChartType::~AreaChartType() {} // ____ XCloneable ____ uno::Reference< util::XCloneable > SAL_CALL AreaChartType::createClone() throw (uno::RuntimeException) { return uno::Reference< util::XCloneable >( new AreaChartType( *this )); } // ____ XChartType ____ ::rtl::OUString SAL_CALL AreaChartType::getChartType() throw (uno::RuntimeException) { return CHART2_SERVICE_NAME_CHARTTYPE_AREA; } uno::Sequence< ::rtl::OUString > AreaChartType::getSupportedServiceNames_Static() { uno::Sequence< ::rtl::OUString > aServices( 2 ); aServices[ 0 ] = CHART2_SERVICE_NAME_CHARTTYPE_AREA; aServices[ 1 ] = C2U( "com.sun.star.chart2.ChartType" ); return aServices; } // implement XServiceInfo methods basing upon getSupportedServiceNames_Static APPHELPER_XSERVICEINFO_IMPL( AreaChartType, C2U( "com.sun.star.comp.chart.AreaChartType" )); } // namespace chart <commit_msg>INTEGRATION: CWS changefileheader (1.5.126); FILE MERGED 2008/03/28 16:44:10 rt 1.5.126.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: AreaChartType.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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "AreaChartType.hxx" #include "macros.hxx" #include "servicenames_charttypes.hxx" using namespace ::com::sun::star; namespace chart { AreaChartType::AreaChartType( const uno::Reference< uno::XComponentContext > & xContext ) : ChartType( xContext ) {} AreaChartType::AreaChartType( const AreaChartType & rOther ) : ChartType( rOther ) {} AreaChartType::~AreaChartType() {} // ____ XCloneable ____ uno::Reference< util::XCloneable > SAL_CALL AreaChartType::createClone() throw (uno::RuntimeException) { return uno::Reference< util::XCloneable >( new AreaChartType( *this )); } // ____ XChartType ____ ::rtl::OUString SAL_CALL AreaChartType::getChartType() throw (uno::RuntimeException) { return CHART2_SERVICE_NAME_CHARTTYPE_AREA; } uno::Sequence< ::rtl::OUString > AreaChartType::getSupportedServiceNames_Static() { uno::Sequence< ::rtl::OUString > aServices( 2 ); aServices[ 0 ] = CHART2_SERVICE_NAME_CHARTTYPE_AREA; aServices[ 1 ] = C2U( "com.sun.star.chart2.ChartType" ); return aServices; } // implement XServiceInfo methods basing upon getSupportedServiceNames_Static APPHELPER_XSERVICEINFO_IMPL( AreaChartType, C2U( "com.sun.star.comp.chart.AreaChartType" )); } // namespace chart <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved */ #ifndef _Stroika_Foundation_Memory_BlockAllocator_inl_ #define _Stroika_Foundation_Memory_BlockAllocator_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include <algorithm> #include <mutex> #include <vector> #include "../Debug/Assertions.h" #include "../Debug/Valgrind.h" #include "../Execution/Common.h" #include "../Execution/SpinLock.h" #include "Common.h" /** * \brief qStroika_Foundation_Memory_BlockAllocator_UseLockFree_ provides a lock-free implementation of BlockAllocator (which should be faster) * * STILL EXPERIMENTAL< but appears to be working well so leave on by default */ //#define qStroika_Foundation_Memory_BlockAllocator_UseLockFree_ 0 #if !defined(qStroika_Foundation_Memory_BlockAllocator_UseLockFree_) #define qStroika_Foundation_Memory_BlockAllocator_UseLockFree_ 1 #endif /* * qStroika_Foundation_Memory_BlockAllocator_UseMallocDirectly_ is currently experimental as * a test to see if its faster than calling operator new (for blocks of RAM). * * operator new[] does very little for us, and could in principle have call overhead and * overhead to track the number of entries in the array (which would be pointless). */ #if !defined(qStroika_Foundation_Memory_BlockAllocator_UseMallocDirectly_) #define qStroika_Foundation_Memory_BlockAllocator_UseMallocDirectly_ 1 #endif #if qStroika_Foundation_Memory_BlockAllocator_UseMallocDirectly_ #include "../Execution/Exceptions.h" #include <cstdlib> #endif namespace Stroika::Foundation::Memory { namespace Private_ { /* * kUseSpinLock_ is probaly best true (empirical tests with the * performance regression test indicated that this helped considerably). * * It should be generally pretty safe because the locks are very narrow (so threads shoudln't spend much time * spinning. And we could reduce this further during mallocs of new blocks. */ constexpr bool kUseSpinLock_ = !qStroika_Foundation_Memory_BlockAllocator_UseLockFree_ and Execution::kSpinLock_IsFasterThan_mutex; #if qStroika_Foundation_Memory_BlockAllocator_UseLockFree_ /** * Basic idea is to use a sentinal value to indicate LOCKED - and use atomic exchange, with * the head of list pointer. * * If we exchange and get the sentinal, we didnt get the lock so retry. * * If don't get the sentinal, we have the lock (and stored the sentinal so nobody else will get the lock) * so go ahead and complete the operation. * * \note I tried to make kLockedSentinal_ constexpr, but this generates errors, apparently because: * http://en.cppreference.com/w/cpp/language/constant_expression * * Address constant expression is a prvalue core constant expression (after conversions required by context) * of type nullptr_t or of a pointer type, which points to an object with static storage duration, one past * the end of an array with static storage duration, to a function, or is a null pointer * * @todo COULD use UNION to workaround this... */ static void* const kLockedSentinal_ = (void*)1; // any invalid pointer #else struct BlockAllocator_ModuleInit_ { BlockAllocator_ModuleInit_ (); ~BlockAllocator_ModuleInit_ (); }; using LockType_ = conditional_t<kUseSpinLock_, Execution::SpinLock, mutex>; extern LockType_* sLock_; inline LockType_& GetLock_ () { AssertNotNull (sLock_); // automatically initailized by BlockAllocated::Private_::ActualModuleInit return *sLock_; } void DoDeleteHandlingLocksExceptionsEtc_ (void* p, void** staticNextLinkP) noexcept; #endif } namespace Private_ { /* * Picked particular kTargetMallocSize since with malloc overhead likely to turn out to be * a chunk which memory allocator can do a good job on. */ constexpr size_t kTargetMallocSize_ = 16360; // 16384 = 16K - leave a few bytes sluff... inline constexpr size_t BlockAllocation_Private_ComputeChunks_ (size_t poolElementSize) { return max (static_cast<size_t> (kTargetMallocSize_ / poolElementSize), static_cast<size_t> (10)); } // This must be included here to keep genclass happy, since the .cc file will not be included // in the genclassed .cc file.... inline void** GetMem_Util_ (size_t sz) { Require (sz >= sizeof (void*)); const size_t kChunks = BlockAllocation_Private_ComputeChunks_ (sz); Assert (kChunks >= 1); /* * Please note that the following line is NOT a memory leak. @see BlockAllocator<> */ #if qStroika_Foundation_Memory_BlockAllocator_UseMallocDirectly_ void** newLinks = (void**)::malloc (kChunks * sz); Execution::ThrowIfNull (newLinks); #else void** newLinks = (void**)new char[kChunks * sz]; #endif AssertNotNull (newLinks); void** curLink = newLinks; for (size_t i = 1; i < kChunks; i++) { *curLink = &(((char*)newLinks)[i * sz]); curLink = (void**)*curLink; } *curLink = nullptr; // nullptr-terminate the link list return newLinks; } /* * BlockAllocationPool_ implements the core logic for allocation/deallocation of a particular pool. These are organized * by size rather than type to reduce fragmentation. */ template <size_t SIZE> class BlockAllocationPool_ { public: static void* Allocate (size_t n); static void Deallocate (void* p) noexcept; static void Compact (); private: static inline conditional_t<qStroika_Foundation_Memory_BlockAllocator_UseLockFree_, atomic<void*>, void*> sHeadLink_{nullptr}; }; } /* ******************************************************************************** ***************** Private_::BlockAllocationPool_<SIZE> ************************* ******************************************************************************** */ template <size_t SIZE> inline void* Private_::BlockAllocationPool_<SIZE>::Allocate ([[maybe_unused]] size_t n) { static_assert (SIZE >= sizeof (void*), "SIZE >= sizeof (void*)"); Require (n <= SIZE); #if qStroika_Foundation_Memory_BlockAllocator_UseLockFree_ /* * Note - once we have stored Private_::kLockedSentinal_ in the sHeadLink_ and gotten back something other than that, we * effectively have a lock for the scope below (because nobody else can get other than Private_::kLockedSentinal_ from exchange). */ again: void* p = sHeadLink_.exchange (Private_::kLockedSentinal_, memory_order_acq_rel); if (p == Private_::kLockedSentinal_) { // we stored and retrieved a sentinal. So no lock. Try again! this_thread::yield (); // nb: until Stroika v2.0a209, this called Execution::Yield (), making this a cancelation point. goto again; } // if we got here, p contains the real head, and have a pseudo lock if (p == nullptr) { p = GetMem_Util_ (SIZE); } void* result = p; AssertNotNull (result); /* * Treat this as a linked list, and make head point to next member. * * Use atomic_load to guarantee the value not loaded from cache line not shared across threads. */ static_assert (sizeof (void*) == sizeof (atomic<void*>), "atomic doesn't change size"); void* next = reinterpret_cast<const atomic<void*>*> (p)->load (memory_order_acquire); Verify (sHeadLink_.exchange (next, memory_order_acq_rel) == Private_::kLockedSentinal_); // must return Private_::kLockedSentinal_ cuz we owned lock, so Private_::kLockedSentinal_ must be there return result; #else [[maybe_unused]] auto&& critSec = lock_guard{Private_::GetLock_ ()}; /* * To implement linked list of BlockAllocated(T)'s before they are * actually alloced, re-use the begining of this as a link pointer. */ if (sHeadLink_ == nullptr) { sHeadLink_ = GetMem_Util_ (SIZE); } void* result = sHeadLink_; AssertNotNull (result); /* * treat this as a linked list, and make head point to next member */ sHeadLink_ = (*(void**)sHeadLink_); return result; #endif } template <size_t SIZE> inline void Private_::BlockAllocationPool_<SIZE>::Deallocate (void* p) noexcept { static_assert (SIZE >= sizeof (void*), "SIZE >= sizeof (void*)"); RequireNotNull (p); #if qStroika_Foundation_Memory_BlockAllocator_UseLockFree_ /* * Note - once we have stored Private_::kLockedSentinal_ in the sHeadLink_ and gotten back something other than that, we * effectively have a lock for the scope below (because nobody else can get other than Private_::kLockedSentinal_ from exchange). */ again: void* prevHead = sHeadLink_.exchange (Private_::kLockedSentinal_, memory_order_acq_rel); if (prevHead == Private_::kLockedSentinal_) { // we stored and retrieved a sentinal. So no lock. Try again! this_thread::yield (); // nb: until Stroika v2.0a209, this called Execution::Yield (), making this a cancelation point. goto again; } /* * Push p onto the head of linked free list. * * Use atomic to guarantee the value not pushed to RAM so shared across threads. */ static_assert (sizeof (void*) == sizeof (atomic<void*>), "atomic doesn't change size"); void* newHead = p; reinterpret_cast<atomic<void*>*> (newHead)->store (prevHead, memory_order_release); Verify (sHeadLink_.exchange (newHead, memory_order_acq_rel) == Private_::kLockedSentinal_); // must return Private_::kLockedSentinal_ cuz we owned lock, so Private_::kLockedSentinal_ must be there #else Private_::DoDeleteHandlingLocksExceptionsEtc_ (p, &sHeadLink_); #endif #if qStroika_FeatureSupported_Valgrind VALGRIND_HG_CLEAN_MEMORY (p, SIZE); #endif } template <size_t SIZE> void Private_::BlockAllocationPool_<SIZE>::Compact () { #if qStroika_Foundation_Memory_BlockAllocator_UseLockFree_ // cannot compact lock-free - no biggie #else [[maybe_unused]] auto&& critSec = lock_guard{Private_::GetLock_ ()}; // step one: put all the links into a single, sorted vector const size_t kChunks = BlockAllocation_Private_ComputeChunks_ (SIZE); Assert (kChunks >= 1); vector<void*> links; try { links.reserve (kChunks * 2); void* link = sHeadLink_; while (link != nullptr) { // probably should use Containers::ReserveSpeedTweekAddN - but want to avoid embrace of dependencies if (links.size () == links.capacity ()) { links.reserve (links.size () * 2); } links.push_back (link); link = *(void**)link; } } catch (...) { return; } sort (links.begin (), links.end ()); // now look for unused memory blocks. Since the vector is sorted by pointer value, the first pointer encountered is potentially the start of a block. // Look at the next N vector elements, where N is the amount of elements that would have been alloced (the chunk size). If they are all there, then the // block is unused can can be freed. Otherwise do the same thing to the first element found outside of the block. size_t originalSize = links.size (); size_t index = 0; while (index < links.size ()) { Byte* deleteCandidate = (Byte*)links[index]; bool canDelete = true; size_t i = 1; for (; i < kChunks; ++i) { if ((index + i) >= links.size ()) break; Byte* next = (Byte*)links[index + i]; Byte* prev = (Byte*)links[index + i - 1]; if (canDelete and ((next - prev) != SIZE)) { canDelete = false; // don't break here, as have to find end up this block, which could be further on } if (static_cast<size_t> (abs (next - deleteCandidate) / SIZE) >= kChunks) { Assert (not canDelete); break; } } if (canDelete) { links.erase (links.begin () + index, links.begin () + index + kChunks); #if qStroika_Foundation_Memory_BlockAllocator_UseMallocDirectly_ ::free ((void*)deleteCandidate); #else delete static_cast<Byte*> ((void*)deleteCandidate); #endif } else { index += i; } } // finally, clean up the pool. The head link is probably wrong, and the elements are no longer linked up correctly sHeadLink_ = (links.size () == 0) ? nullptr : links[0]; if (links.size () != originalSize and links.size () > 0) { // we delete some, which means that the next pointers are bad void** curLink = (void**)sHeadLink_; for (size_t i = 1; i < links.size (); i++) { *curLink = links[i]; curLink = (void**)*curLink; } *curLink = nullptr; } #endif } /* ******************************************************************************** ******************************** BlockAllocator<T> ***************************** ******************************************************************************** */ template <typename T> inline void* BlockAllocator<T>::Allocate ([[maybe_unused]] size_t n) { using Private_::BlockAllocationPool_; Require (n == sizeof (T)); #if qAllowBlockAllocation void* result = BlockAllocationPool_<AdjustSizeForPool_ ()>::Allocate (n); #else void* result = ::operator new (n); #endif EnsureNotNull (result); Ensure (reinterpret_cast<ptrdiff_t> (result) % alignof (T) == 0); // see https://stroika.atlassian.net/browse/STK-511 - assure aligned return result; } template <typename T> inline void BlockAllocator<T>::Deallocate (void* p) noexcept { using Private_::BlockAllocationPool_; #if qAllowBlockAllocation if (p != nullptr) { BlockAllocationPool_<AdjustSizeForPool_ ()>::Deallocate (p); } #else :: operator delete (p); #endif } template <typename T> void BlockAllocator<T>::Compact () { using Private_::BlockAllocationPool_; #if qAllowBlockAllocation BlockAllocationPool_<AdjustSizeForPool_ ()>::Compact (); #endif } template <typename T> // not quite right - too much of a PITA to support both constexpr and non- just wait til all our compilers support constexpr and then fix! constexpr size_t BlockAllocator<T>::AdjustSizeForPool_ () { size_t n = sizeof (T); // when we really fix constexpr usage, we can use the below! //return Math::RoundUpTo (sizeof(T), sizeof (void*)); return (((n + sizeof (void*) - 1u) / sizeof (void*)) * sizeof (void*)); } } #if !qStroika_Foundation_Memory_BlockAllocator_UseLockFree_ namespace { Stroika::Foundation::Execution::ModuleInitializer<Stroika::Foundation::Memory::Private_::BlockAllocator_ModuleInit_> _Stroika_Foundation_Memory_BlockAllocator_ModuleInit_; // this object constructed for the CTOR/DTOR per-module side-effects } #endif #endif /*_Stroika_Foundation_Memory_BlockAllocator_inl_*/ <commit_msg>more cleanups of BlockAllocator<T>::AdjustSizeForPool_ ()<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved */ #ifndef _Stroika_Foundation_Memory_BlockAllocator_inl_ #define _Stroika_Foundation_Memory_BlockAllocator_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include <algorithm> #include <mutex> #include <vector> #include "../Debug/Assertions.h" #include "../Debug/Valgrind.h" #include "../Execution/Common.h" #include "../Execution/SpinLock.h" #include "../Math/Common.h" #include "Common.h" /** * \brief qStroika_Foundation_Memory_BlockAllocator_UseLockFree_ provides a lock-free implementation of BlockAllocator (which should be faster) * * STILL EXPERIMENTAL< but appears to be working well so leave on by default */ //#define qStroika_Foundation_Memory_BlockAllocator_UseLockFree_ 0 #if !defined(qStroika_Foundation_Memory_BlockAllocator_UseLockFree_) #define qStroika_Foundation_Memory_BlockAllocator_UseLockFree_ 1 #endif /* * qStroika_Foundation_Memory_BlockAllocator_UseMallocDirectly_ is currently experimental as * a test to see if its faster than calling operator new (for blocks of RAM). * * operator new[] does very little for us, and could in principle have call overhead and * overhead to track the number of entries in the array (which would be pointless). */ #if !defined(qStroika_Foundation_Memory_BlockAllocator_UseMallocDirectly_) #define qStroika_Foundation_Memory_BlockAllocator_UseMallocDirectly_ 1 #endif #if qStroika_Foundation_Memory_BlockAllocator_UseMallocDirectly_ #include "../Execution/Exceptions.h" #include <cstdlib> #endif namespace Stroika::Foundation::Memory { namespace Private_ { /* * kUseSpinLock_ is probaly best true (empirical tests with the * performance regression test indicated that this helped considerably). * * It should be generally pretty safe because the locks are very narrow (so threads shoudln't spend much time * spinning. And we could reduce this further during mallocs of new blocks. */ constexpr bool kUseSpinLock_ = !qStroika_Foundation_Memory_BlockAllocator_UseLockFree_ and Execution::kSpinLock_IsFasterThan_mutex; #if qStroika_Foundation_Memory_BlockAllocator_UseLockFree_ /** * Basic idea is to use a sentinal value to indicate LOCKED - and use atomic exchange, with * the head of list pointer. * * If we exchange and get the sentinal, we didnt get the lock so retry. * * If don't get the sentinal, we have the lock (and stored the sentinal so nobody else will get the lock) * so go ahead and complete the operation. * * \note I tried to make kLockedSentinal_ constexpr, but this generates errors, apparently because: * http://en.cppreference.com/w/cpp/language/constant_expression * * Address constant expression is a prvalue core constant expression (after conversions required by context) * of type nullptr_t or of a pointer type, which points to an object with static storage duration, one past * the end of an array with static storage duration, to a function, or is a null pointer * * @todo COULD use UNION to workaround this... */ static void* const kLockedSentinal_ = (void*)1; // any invalid pointer #else struct BlockAllocator_ModuleInit_ { BlockAllocator_ModuleInit_ (); ~BlockAllocator_ModuleInit_ (); }; using LockType_ = conditional_t<kUseSpinLock_, Execution::SpinLock, mutex>; extern LockType_* sLock_; inline LockType_& GetLock_ () { AssertNotNull (sLock_); // automatically initailized by BlockAllocated::Private_::ActualModuleInit return *sLock_; } void DoDeleteHandlingLocksExceptionsEtc_ (void* p, void** staticNextLinkP) noexcept; #endif } namespace Private_ { /* * Picked particular kTargetMallocSize since with malloc overhead likely to turn out to be * a chunk which memory allocator can do a good job on. */ constexpr size_t kTargetMallocSize_ = 16360; // 16384 = 16K - leave a few bytes sluff... inline constexpr size_t BlockAllocation_Private_ComputeChunks_ (size_t poolElementSize) { return max (static_cast<size_t> (kTargetMallocSize_ / poolElementSize), static_cast<size_t> (10)); } // This must be included here to keep genclass happy, since the .cc file will not be included // in the genclassed .cc file.... inline void** GetMem_Util_ (size_t sz) { Require (sz >= sizeof (void*)); const size_t kChunks = BlockAllocation_Private_ComputeChunks_ (sz); Assert (kChunks >= 1); /* * Please note that the following line is NOT a memory leak. @see BlockAllocator<> */ #if qStroika_Foundation_Memory_BlockAllocator_UseMallocDirectly_ void** newLinks = (void**)::malloc (kChunks * sz); Execution::ThrowIfNull (newLinks); #else void** newLinks = (void**)new char[kChunks * sz]; #endif AssertNotNull (newLinks); void** curLink = newLinks; for (size_t i = 1; i < kChunks; i++) { *curLink = &(((char*)newLinks)[i * sz]); curLink = (void**)*curLink; } *curLink = nullptr; // nullptr-terminate the link list return newLinks; } /* * BlockAllocationPool_ implements the core logic for allocation/deallocation of a particular pool. These are organized * by size rather than type to reduce fragmentation. */ template <size_t SIZE> class BlockAllocationPool_ { public: // never returns nullptr - throws if memory exhausted static void* Allocate (size_t n); // require p != nullptr static void Deallocate (void* p) noexcept; static void Compact (); private: static inline conditional_t<qStroika_Foundation_Memory_BlockAllocator_UseLockFree_, atomic<void*>, void*> sHeadLink_{nullptr}; }; } /* ******************************************************************************** ***************** Private_::BlockAllocationPool_<SIZE> ************************* ******************************************************************************** */ template <size_t SIZE> inline void* Private_::BlockAllocationPool_<SIZE>::Allocate ([[maybe_unused]] size_t n) { static_assert (SIZE >= sizeof (void*), "SIZE >= sizeof (void*)"); Require (n <= SIZE); #if qStroika_Foundation_Memory_BlockAllocator_UseLockFree_ /* * Note - once we have stored Private_::kLockedSentinal_ in the sHeadLink_ and gotten back something other than that, we * effectively have a lock for the scope below (because nobody else can get other than Private_::kLockedSentinal_ from exchange). */ again: void* p = sHeadLink_.exchange (Private_::kLockedSentinal_, memory_order_acq_rel); if (p == Private_::kLockedSentinal_) { // we stored and retrieved a sentinal. So no lock. Try again! this_thread::yield (); // nb: until Stroika v2.0a209, this called Execution::Yield (), making this a cancelation point. goto again; } // if we got here, p contains the real head, and have a pseudo lock if (p == nullptr) { p = GetMem_Util_ (SIZE); } void* result = p; AssertNotNull (result); /* * Treat this as a linked list, and make head point to next member. * * Use atomic_load to guarantee the value not loaded from cache line not shared across threads. */ static_assert (sizeof (void*) == sizeof (atomic<void*>), "atomic doesn't change size"); void* next = reinterpret_cast<const atomic<void*>*> (p)->load (memory_order_acquire); Verify (sHeadLink_.exchange (next, memory_order_acq_rel) == Private_::kLockedSentinal_); // must return Private_::kLockedSentinal_ cuz we owned lock, so Private_::kLockedSentinal_ must be there return result; #else [[maybe_unused]] auto&& critSec = lock_guard{Private_::GetLock_ ()}; /* * To implement linked list of BlockAllocated(T)'s before they are * actually alloced, re-use the begining of this as a link pointer. */ if (sHeadLink_ == nullptr) { sHeadLink_ = GetMem_Util_ (SIZE); } void* result = sHeadLink_; AssertNotNull (result); /* * treat this as a linked list, and make head point to next member */ sHeadLink_ = (*(void**)sHeadLink_); return result; #endif } template <size_t SIZE> inline void Private_::BlockAllocationPool_<SIZE>::Deallocate (void* p) noexcept { static_assert (SIZE >= sizeof (void*), "SIZE >= sizeof (void*)"); RequireNotNull (p); #if qStroika_Foundation_Memory_BlockAllocator_UseLockFree_ /* * Note - once we have stored Private_::kLockedSentinal_ in the sHeadLink_ and gotten back something other than that, we * effectively have a lock for the scope below (because nobody else can get other than Private_::kLockedSentinal_ from exchange). */ again: void* prevHead = sHeadLink_.exchange (Private_::kLockedSentinal_, memory_order_acq_rel); if (prevHead == Private_::kLockedSentinal_) { // we stored and retrieved a sentinal. So no lock. Try again! this_thread::yield (); // nb: until Stroika v2.0a209, this called Execution::Yield (), making this a cancelation point. goto again; } /* * Push p onto the head of linked free list. * * Use atomic to guarantee the value not pushed to RAM so shared across threads. */ static_assert (sizeof (void*) == sizeof (atomic<void*>), "atomic doesn't change size"); void* newHead = p; reinterpret_cast<atomic<void*>*> (newHead)->store (prevHead, memory_order_release); Verify (sHeadLink_.exchange (newHead, memory_order_acq_rel) == Private_::kLockedSentinal_); // must return Private_::kLockedSentinal_ cuz we owned lock, so Private_::kLockedSentinal_ must be there #else Private_::DoDeleteHandlingLocksExceptionsEtc_ (p, &sHeadLink_); #endif #if qStroika_FeatureSupported_Valgrind VALGRIND_HG_CLEAN_MEMORY (p, SIZE); #endif } template <size_t SIZE> void Private_::BlockAllocationPool_<SIZE>::Compact () { #if qStroika_Foundation_Memory_BlockAllocator_UseLockFree_ // cannot compact lock-free - no biggie #else [[maybe_unused]] auto&& critSec = lock_guard{Private_::GetLock_ ()}; // step one: put all the links into a single, sorted vector const size_t kChunks = BlockAllocation_Private_ComputeChunks_ (SIZE); Assert (kChunks >= 1); vector<void*> links; try { links.reserve (kChunks * 2); void* link = sHeadLink_; while (link != nullptr) { // probably should use Containers::ReserveSpeedTweekAddN - but want to avoid embrace of dependencies if (links.size () == links.capacity ()) { links.reserve (links.size () * 2); } links.push_back (link); link = *(void**)link; } } catch (...) { return; } sort (links.begin (), links.end ()); // now look for unused memory blocks. Since the vector is sorted by pointer value, the first pointer encountered is potentially the start of a block. // Look at the next N vector elements, where N is the amount of elements that would have been alloced (the chunk size). If they are all there, then the // block is unused can can be freed. Otherwise do the same thing to the first element found outside of the block. size_t originalSize = links.size (); size_t index = 0; while (index < links.size ()) { Byte* deleteCandidate = (Byte*)links[index]; bool canDelete = true; size_t i = 1; for (; i < kChunks; ++i) { if ((index + i) >= links.size ()) break; Byte* next = (Byte*)links[index + i]; Byte* prev = (Byte*)links[index + i - 1]; if (canDelete and ((next - prev) != SIZE)) { canDelete = false; // don't break here, as have to find end up this block, which could be further on } if (static_cast<size_t> (abs (next - deleteCandidate) / SIZE) >= kChunks) { Assert (not canDelete); break; } } if (canDelete) { links.erase (links.begin () + index, links.begin () + index + kChunks); #if qStroika_Foundation_Memory_BlockAllocator_UseMallocDirectly_ ::free ((void*)deleteCandidate); #else delete static_cast<Byte*> ((void*)deleteCandidate); #endif } else { index += i; } } // finally, clean up the pool. The head link is probably wrong, and the elements are no longer linked up correctly sHeadLink_ = (links.size () == 0) ? nullptr : links[0]; if (links.size () != originalSize and links.size () > 0) { // we delete some, which means that the next pointers are bad void** curLink = (void**)sHeadLink_; for (size_t i = 1; i < links.size (); i++) { *curLink = links[i]; curLink = (void**)*curLink; } *curLink = nullptr; } #endif } /* ******************************************************************************** ******************************** BlockAllocator<T> ***************************** ******************************************************************************** */ template <typename T> inline void* BlockAllocator<T>::Allocate ([[maybe_unused]] size_t n) { using Private_::BlockAllocationPool_; Require (n == sizeof (T)); #if qAllowBlockAllocation void* result = BlockAllocationPool_<AdjustSizeForPool_ ()>::Allocate (sizeof (T)); #else void* result = ::operator new (sizeof (T)); #endif EnsureNotNull (result); Ensure (reinterpret_cast<ptrdiff_t> (result) % alignof (T) == 0); // see https://stroika.atlassian.net/browse/STK-511 - assure aligned return result; } template <typename T> inline void BlockAllocator<T>::Deallocate (void* p) noexcept { using Private_::BlockAllocationPool_; #if qAllowBlockAllocation if (p != nullptr) { BlockAllocationPool_<AdjustSizeForPool_ ()>::Deallocate (p); } #else :: operator delete (p); #endif } template <typename T> void BlockAllocator<T>::Compact () { using Private_::BlockAllocationPool_; #if qAllowBlockAllocation BlockAllocationPool_<AdjustSizeForPool_ ()>::Compact (); #endif } template <typename T> // not quite right - too much of a PITA to support both constexpr and non- just wait til all our compilers support constexpr and then fix! constexpr size_t BlockAllocator<T>::AdjustSizeForPool_ () { return Math::RoundUpTo (sizeof (T), sizeof (void*)); } } #if !qStroika_Foundation_Memory_BlockAllocator_UseLockFree_ namespace { Stroika::Foundation::Execution::ModuleInitializer<Stroika::Foundation::Memory::Private_::BlockAllocator_ModuleInit_> _Stroika_Foundation_Memory_BlockAllocator_ModuleInit_; // this object constructed for the CTOR/DTOR per-module side-effects } #endif #endif /*_Stroika_Foundation_Memory_BlockAllocator_inl_*/ <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////// // // Python wrappers // // ---------------------------------------------------------------- // // AUTHOR: Miguel Ramos Pernas // e-mail: [email protected] // // Last update: 20/09/2017 // // ---------------------------------------------------------------- /////////////////////////////////////////////////////////////////// #include "GlobalWrappers.h" #include "NumpyUtils.h" #include "TreeWrapper.h" #include <Python.h> #include <boost/python/dict.hpp> #include <boost/python/extract.hpp> #include <boost/python/iterator.hpp> #include <boost/python/list.hpp> #include <boost/python/object.hpp> #include <boost/python/object_operators.hpp> #include <boost/python/tuple.hpp> #include "BufferVariable.h" #include "Definitions.h" #include "Messenger.h" #include "RootUtils.h" #include "TreeBuffer.h" #include "TreeManagement.h" #include "Utils.h" #include "TBranch.h" #include "TDirectory.h" #include "TEventList.h" #include "TFile.h" #include "TObject.h" #include "TPython.h" #include "TTree.h" #include <iostream> #include <map> #include <string> #include <vector> //_______________________________________________________________ namespace iboost { //_______________________________________________________________ // np::ndarray treeToNumpyArray( std::string fpath, std::string tpath, py::object &vars, std::string cuts, bool use_regex ) { // Open the Root file and access the tree TFile *ifile = TFile::Open(fpath.c_str()); TTree *itree = static_cast<TTree*>(isis::getSafeObject(ifile, tpath)); // Extracts the list of events to be used itree->Draw(">>evtlist", cuts.c_str()); TEventList *evtlist = (TEventList*) gDirectory->Get("evtlist"); // Get the branch names to be used itree->SetBranchStatus("*", 0); isis::Strings brnames; const py::ssize_t nvars = py::len(vars); for ( py::ssize_t i = 0; i < nvars; ++i ) { auto var = extractFromIndex<std::string>(vars, i); bool s = true; if ( use_regex ) s = isis::getBranchNames(brnames, itree, var); else { if ( itree->GetBranch(var.c_str()) ) brnames.push_back(var); else s = false; } if ( !s ) IWarning << "No variables have been found following expression < " << var << " >" << IEndMsg; } // Do not swap these two lines, since the path must be set after the // variable is enabled isis::TreeBuffer buffer(itree); for ( const auto br : brnames ) { itree->SetBranchStatus(br.c_str(), 1); buffer.loadVariable(br); } // Make the output array auto output = void_ndarray(evtlist->GetN(), buffer); // Build the writers std::vector<BuffVarWriter*> outvec; size_t n = brnames.size(); outvec.reserve(n); for ( const auto el: buffer.getMap() ) { np::ndarray a = py::extract<np::ndarray>(output[el.first]); outvec.push_back(new BuffVarWriter(el.second, a)); } // Calling to < append > is faster than assigning by index for ( int i = 0; i < evtlist->GetN(); ++i ) { Long64_t ievt = evtlist->GetEntry(i); itree->GetEntry(ievt); for ( auto &el : outvec ) el->appendToArray(i, n); } // The branches are enabled again itree->SetBranchStatus("*", 1); ifile->Close(); // Delete allocated memory for ( auto &v : outvec ) delete v; return output; } //_______________________________________________________________ // py::object numpyArrayToTree( py::tuple args, py::dict kwargs ) { checkArgs(args, 1); checkKwargs(kwargs, {"name", "tree", "variables", "use_regex"}); np::ndarray vartup = extractFromIndex<np::ndarray>(args, 0); py::list varkeys = struct_array_keys(vartup); // Get the tree name or the given tree TTree *tree = 0; if ( kwargs.has_key(py::object("tree")) ) { py::object el = kwargs["tree"]; TObject *treeproxy = (TObject*) TPython::ObjectProxy_AsVoidPtr(el.ptr()); tree = dynamic_cast<TTree*>(treeproxy); } std::string tname; if ( kwargs.has_key("name") ) tname = py::extract<std::string>(kwargs["name"]); // Get the list of variables to work with py::list variables; if ( kwargs.has_key("variables") ) { variables = py::extract<py::list>(kwargs["variables"]); if ( !py::len(variables) ) variables = varkeys; } else variables = varkeys; // Determine whether regex will be used or not bool use_regex = false; if ( kwargs.has_key("use_regex") ) use_regex = py::extract<bool>(kwargs["use_regex"]); // Warning message if both the tree and tree name are provided if ( !tree ) { tree = new TTree(tname.c_str(), tname.c_str(), 0); tree->AutoSave(); } else if ( !tname.empty() ) IWarning << "The given tree name is not being used" << IEndMsg; // Prepare the variables to iterate with. The vector keeps // track of the types for each variable. isis::TreeBuffer buffer(tree); auto vars = boostListToStdCont<std::vector, std::string>(variables); auto vec_keys = boostListToStdCont<std::vector, std::string>(varkeys); // Get the variables from the given expressions isis::Strings brnames; for ( const auto &exp : vars ) { if ( use_regex ) isis::stringVectorFilter(brnames, vec_keys, exp); else brnames.push_back(exp); } std::vector<BuffVarWriter*> varvec; varvec.reserve(brnames.size()); for ( const auto &br : brnames ) varvec.push_back(new BuffVarWriter( buffer, br, py::extract<np::ndarray>(vartup[br])) ); // Loop over all the events in the dictionary py::ssize_t nvals = py::len(vartup); for ( py::ssize_t ievt = 0; ievt < nvals; ++ievt ) { // Loop over all the variables in the dictionary const size_t n = varvec.size(); for ( auto &v : varvec ) v->appendToVar(ievt, n); tree->Fill(); } tree->AutoSave(); // Delete the allocated memory for ( auto &v : varvec ) delete v; // Returns "None" return py::object(); } } <commit_msg>Fix issue in TreeWrapper.cpp, when writting data to root<commit_after>/////////////////////////////////////////////////////////////////// // // Python wrappers // // ---------------------------------------------------------------- // // AUTHOR: Miguel Ramos Pernas // e-mail: [email protected] // // Last update: 21/09/2017 // // ---------------------------------------------------------------- /////////////////////////////////////////////////////////////////// #include "GlobalWrappers.h" #include "NumpyUtils.h" #include "TreeWrapper.h" #include <Python.h> #include <boost/python/dict.hpp> #include <boost/python/extract.hpp> #include <boost/python/iterator.hpp> #include <boost/python/list.hpp> #include <boost/python/object.hpp> #include <boost/python/object_operators.hpp> #include <boost/python/tuple.hpp> #include "BufferVariable.h" #include "Definitions.h" #include "Messenger.h" #include "RootUtils.h" #include "TreeBuffer.h" #include "TreeManagement.h" #include "Utils.h" #include "TBranch.h" #include "TDirectory.h" #include "TEventList.h" #include "TFile.h" #include "TObject.h" #include "TPython.h" #include "TTree.h" #include <iostream> #include <map> #include <string> #include <vector> //_______________________________________________________________ namespace iboost { //_______________________________________________________________ // np::ndarray treeToNumpyArray( std::string fpath, std::string tpath, py::object &vars, std::string cuts, bool use_regex ) { // Open the Root file and access the tree TFile *ifile = TFile::Open(fpath.c_str()); TTree *itree = static_cast<TTree*>(isis::getSafeObject(ifile, tpath)); // Extracts the list of events to be used itree->Draw(">>evtlist", cuts.c_str()); TEventList *evtlist = (TEventList*) gDirectory->Get("evtlist"); // Get the branch names to be used itree->SetBranchStatus("*", 0); isis::Strings brnames; const py::ssize_t nvars = py::len(vars); for ( py::ssize_t i = 0; i < nvars; ++i ) { auto var = extractFromIndex<std::string>(vars, i); bool s = true; if ( use_regex ) s = isis::getBranchNames(brnames, itree, var); else { if ( itree->GetBranch(var.c_str()) ) brnames.push_back(var); else s = false; } if ( !s ) IWarning << "No variables have been found following expression < " << var << " >" << IEndMsg; } // Do not swap these two lines, since the path must be set after the // variable is enabled isis::TreeBuffer buffer(itree); for ( const auto br : brnames ) { itree->SetBranchStatus(br.c_str(), 1); buffer.loadVariable(br); } // Make the output array auto output = void_ndarray(evtlist->GetN(), buffer); // Build the writers std::vector<BuffVarWriter*> outvec; const size_t n = brnames.size(); outvec.reserve(n); for ( const auto el: buffer.getMap() ) { np::ndarray a = py::extract<np::ndarray>(output[el.first]); outvec.push_back(new BuffVarWriter(el.second, a)); } // Calling to < append > is faster than assigning by index for ( int i = 0; i < evtlist->GetN(); ++i ) { Long64_t ievt = evtlist->GetEntry(i); itree->GetEntry(ievt); for ( auto &el : outvec ) el->appendToArray(i, n); } // The branches are enabled again itree->SetBranchStatus("*", 1); ifile->Close(); // Delete allocated memory for ( auto &v : outvec ) delete v; return output; } //_______________________________________________________________ // py::object numpyArrayToTree( py::tuple args, py::dict kwargs ) { checkArgs(args, 1); checkKwargs(kwargs, {"name", "tree", "variables", "use_regex"}); np::ndarray vartup = extractFromIndex<np::ndarray>(args, 0); py::list varkeys = struct_array_keys(vartup); // Get the tree name or the given tree TTree *tree = 0; if ( kwargs.has_key(py::object("tree")) ) { py::object el = kwargs["tree"]; TObject *treeproxy = (TObject*) TPython::ObjectProxy_AsVoidPtr(el.ptr()); tree = dynamic_cast<TTree*>(treeproxy); } std::string tname; if ( kwargs.has_key("name") ) tname = py::extract<std::string>(kwargs["name"]); // Get the list of variables to work with py::list variables; if ( kwargs.has_key("variables") ) { variables = py::extract<py::list>(kwargs["variables"]); if ( !py::len(variables) ) variables = varkeys; } else variables = varkeys; // Determine whether regex will be used or not bool use_regex = false; if ( kwargs.has_key("use_regex") ) use_regex = py::extract<bool>(kwargs["use_regex"]); // Warning message if both the tree and tree name are provided if ( !tree ) { tree = new TTree(tname.c_str(), tname.c_str(), 0); tree->AutoSave(); } else if ( !tname.empty() ) IWarning << "The given tree name is not being used" << IEndMsg; // Prepare the variables to iterate with. The vector keeps // track of the types for each variable. isis::TreeBuffer buffer(tree); auto vars = boostListToStdCont<std::vector, std::string>(variables); auto vec_keys = boostListToStdCont<std::vector, std::string>(varkeys); // Get the variables from the given expressions isis::Strings brnames; for ( const auto &exp : vars ) { if ( use_regex ) isis::stringVectorFilter(brnames, vec_keys, exp); else brnames.push_back(exp); } std::vector<BuffVarWriter*> varvec; const size_t n = brnames.size(); varvec.reserve(n); for ( const auto &br : brnames ) varvec.push_back(new BuffVarWriter( buffer, br, py::extract<np::ndarray>(vartup[br])) ); // Loop over all the events in the array, the whole number of variables // in the input array must be used to access correctly to the data py::ssize_t nvals = py::len(vartup); py::ssize_t nkeys = py::len(varkeys); for ( py::ssize_t ievt = 0; ievt < nvals; ++ievt ) { // Loop over all the variables in the array for ( auto &v : varvec ) v->appendToVar(ievt, nkeys); tree->Fill(); } tree->AutoSave(); // Delete the allocated memory for ( auto &v : varvec ) delete v; // Returns "None" return py::object(); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: CustomAnimationPanel.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2005-03-18 17:00:55 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SD_TOOLPANEL_CONTROLS_CUSTOM_ANIMATION_PANEL_HXX #define SD_TOOLPANEL_CONTROLS_CUSTOM_ANIMATION_PANEL_HXX #include "taskpane/SubToolPanel.hxx" namespace sd { class ViewShellBase; } namespace sd { namespace toolpanel { class TreeNode; class ControlFactory; } } namespace sd { namespace toolpanel { namespace controls { class CustomAnimationPanel : public SubToolPanel { public: CustomAnimationPanel ( TreeNode* pParent, ViewShellBase& rBase); virtual ~CustomAnimationPanel (void); static std::auto_ptr<ControlFactory> CreateControlFactory (ViewShellBase& rBase); virtual Size GetPreferredSize (void); virtual sal_Int32 GetPreferredWidth (sal_Int32 nHeigh); virtual sal_Int32 GetPreferredHeight (sal_Int32 nWidth); virtual ::Window* GetWindow (void); virtual bool IsResizable (void); virtual bool IsExpandable (void) const; private: Size maPreferredSize; ::Window* mpWrappedControl; }; } } } // end of namespace ::sd::toolpanel::controls #endif <commit_msg>INTEGRATION: CWS impress51 (1.3.46); FILE MERGED 2005/05/20 09:02:53 af 1.3.46.1: #i48247# Added CreateAccessibleObject() method.<commit_after>/************************************************************************* * * $RCSfile: CustomAnimationPanel.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2005-07-14 10:24:59 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SD_TOOLPANEL_CONTROLS_CUSTOM_ANIMATION_PANEL_HXX #define SD_TOOLPANEL_CONTROLS_CUSTOM_ANIMATION_PANEL_HXX #include "taskpane/SubToolPanel.hxx" namespace sd { class ViewShellBase; } namespace sd { namespace toolpanel { class TreeNode; class ControlFactory; } } namespace sd { namespace toolpanel { namespace controls { class CustomAnimationPanel : public SubToolPanel { public: CustomAnimationPanel ( TreeNode* pParent, ViewShellBase& rBase); virtual ~CustomAnimationPanel (void); static std::auto_ptr<ControlFactory> CreateControlFactory (ViewShellBase& rBase); virtual Size GetPreferredSize (void); virtual sal_Int32 GetPreferredWidth (sal_Int32 nHeigh); virtual sal_Int32 GetPreferredHeight (sal_Int32 nWidth); virtual ::Window* GetWindow (void); virtual bool IsResizable (void); virtual bool IsExpandable (void) const; virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessibleObject ( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible>& rxParent); private: Size maPreferredSize; ::Window* mpWrappedControl; }; } } } // end of namespace ::sd::toolpanel::controls #endif <|endoftext|>
<commit_before>// Copyright 2011 Alessio Sclocco <[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. #define __CL_ENABLE_EXCEPTIONS #include <CL/cl.hpp> #include <vector> #include <utils.hpp> #include <Exceptions.hpp> #ifndef INITIALIZE_OPENCL_HPP #define INITIALIZE_OPENCL_HPP namespace isa { namespace OpenCL { void initializeOpenCL(unsigned int platform, unsigned int nrQueues, std::vector< cl::Platform > * platforms, cl::Context * context, std::vector< cl::Device > * devices, std::vector< std::vector< cl::CommandQueue > > * queues) throw (isa::OpenCL::OpenCLError) { try { unsigned int nrDevices = 0; cl::Platform::get(platforms); cl_context_properties properties[] = {CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms->at(platform))(), 0}; *context = cl::Context(CL_DEVICE_TYPE_ALL, properties); *devices = context->getInfo<CL_CONTEXT_DEVICES>(); nrDevices = devices->size(); for ( unsigned int device = 0; device < nrDevices; device++ ) { queues->push_back(std::vector< cl::CommandQueue >()); for ( unsigned int queue = 0; queue < nrQueues; queue++ ) { (queues->at(device)).push_back(cl::CommandQueue(*context, devices->at(device)));; } } } catch ( cl::Error &e ) { throw isa::OpenCL::OpenCLError("Impossible to initialize OpenCL: " + isa::utils::toString(e.err()) + "."); } } } // OpenCL } // isa #endif // INITIALIZE_OPENCL_HPP <commit_msg>Allocating the context in initializeOpenCL().<commit_after>// Copyright 2011 Alessio Sclocco <[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. #define __CL_ENABLE_EXCEPTIONS #include <CL/cl.hpp> #include <vector> #include <utils.hpp> #include <Exceptions.hpp> #ifndef INITIALIZE_OPENCL_HPP #define INITIALIZE_OPENCL_HPP namespace isa { namespace OpenCL { void initializeOpenCL(unsigned int platform, unsigned int nrQueues, std::vector< cl::Platform > * platforms, cl::Context * context, std::vector< cl::Device > * devices, std::vector< std::vector< cl::CommandQueue > > * queues) throw (isa::OpenCL::OpenCLError) { try { unsigned int nrDevices = 0; cl::Platform::get(platforms); cl_context_properties properties[] = {CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms->at(platform))(), 0}; context = new cl::Context(); *context = cl::Context(CL_DEVICE_TYPE_ALL, properties); *devices = context->getInfo<CL_CONTEXT_DEVICES>(); nrDevices = devices->size(); for ( unsigned int device = 0; device < nrDevices; device++ ) { queues->push_back(std::vector< cl::CommandQueue >()); for ( unsigned int queue = 0; queue < nrQueues; queue++ ) { (queues->at(device)).push_back(cl::CommandQueue(*context, devices->at(device)));; } } } catch ( cl::Error &e ) { throw isa::OpenCL::OpenCLError("Impossible to initialize OpenCL: " + isa::utils::toString(e.err()) + "."); } } } // OpenCL } // isa #endif // INITIALIZE_OPENCL_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 <jni.h> #include "chrome/browser/android/chrome_startup_flags.h" #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/android/sys_utils.h" #include "base/command_line.h" #include "base/logging.h" #include "chrome/common/chrome_switches.h" #include "content/public/common/content_switches.h" #include "media/base/media_switches.h" namespace { void SetCommandLineSwitch(const std::string& switch_string) { CommandLine* command_line = CommandLine::ForCurrentProcess(); if (!command_line->HasSwitch(switch_string)) command_line->AppendSwitch(switch_string); } void SetCommandLineSwitchASCII(const std::string& switch_string, const std::string& value) { CommandLine* command_line = CommandLine::ForCurrentProcess(); if (!command_line->HasSwitch(switch_string)) command_line->AppendSwitchASCII(switch_string, value); } } // namespace void SetChromeSpecificCommandLineFlags() { // Turn on autologin. SetCommandLineSwitch(switches::kEnableAutologin); // Enable prerender for the omnibox. SetCommandLineSwitchASCII( switches::kPrerenderMode, switches::kPrerenderModeSwitchValueEnabled); SetCommandLineSwitchASCII( switches::kPrerenderFromOmnibox, switches::kPrerenderFromOmniboxSwitchValueEnabled); if (base::android::SysUtils::IsLowEndDevice()) SetCommandLineSwitch(switches::kDisableSyncFavicons); } <commit_msg>[android] Enable DOM distiller by default on development channels.<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 <jni.h> #include "chrome/browser/android/chrome_startup_flags.h" #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/android/sys_utils.h" #include "base/command_line.h" #include "base/logging.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version_info.h" #include "content/public/common/content_switches.h" #include "media/base/media_switches.h" namespace { void SetCommandLineSwitch(const std::string& switch_string) { CommandLine* command_line = CommandLine::ForCurrentProcess(); if (!command_line->HasSwitch(switch_string)) command_line->AppendSwitch(switch_string); } void SetCommandLineSwitchASCII(const std::string& switch_string, const std::string& value) { CommandLine* command_line = CommandLine::ForCurrentProcess(); if (!command_line->HasSwitch(switch_string)) command_line->AppendSwitchASCII(switch_string, value); } } // namespace void SetChromeSpecificCommandLineFlags() { // Turn on autologin. SetCommandLineSwitch(switches::kEnableAutologin); // Enable prerender for the omnibox. SetCommandLineSwitchASCII(switches::kPrerenderMode, switches::kPrerenderModeSwitchValueEnabled); SetCommandLineSwitchASCII(switches::kPrerenderFromOmnibox, switches::kPrerenderFromOmniboxSwitchValueEnabled); // Disable syncing favicons on low end devices. if (base::android::SysUtils::IsLowEndDevice()) SetCommandLineSwitch(switches::kDisableSyncFavicons); // Enable DOM Distiller on local builds, canary and dev-channel. chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel(); if (channel == chrome::VersionInfo::CHANNEL_UNKNOWN || channel == chrome::VersionInfo::CHANNEL_CANARY || channel == chrome::VersionInfo::CHANNEL_DEV) { SetCommandLineSwitch(switches::kEnableDomDistiller); } } <|endoftext|>
<commit_before>#include "core/mat4.h" #include "core/random.h" #include "core/mat4.h" #include "core/axisangle.h" #include "core/aabb.h" #include "core/texturetypes.h" #include "core/vfs.h" #include "core/vfs_imagegenerator.h" #include "core/vfs_path.h" #include "core/os.h" #include "core/range.h" #include "core/camera.h" #include "core/stringutils.h" #include "core/stdutils.h" #include "core/proto.h" #include "core/log.h" #include "core/rgb.h" #include "core/colors.h" #include "core/palette_lospec.h" #include "core/palette.h" #include "render/init.h" #include "render/debuggl.h" #include "render/materialshader.h" #include "render/compiledmesh.h" #include "render/texturecache.h" #include "render/shaderattribute3d.h" #include "render/texture.h" #include "render/world.h" #include "render/viewport.h" #include "render/materialshadercache.h" #include "render/defaultfiles.h" #include "window/imguilibrary.h" #include "window/timer.h" #include "window/imgui_ext.h" #include "window/imgui_extra.h" #include "window/sdllibrary.h" #include "window/sdlwindow.h" #include "window/sdlglcontext.h" #include "window/filesystem.h" #include "window/engine.h" #include "window/canvas.h" #include "imgui/imgui.h" #include "SDL.h" #include <iostream> #include <memory> #define IMGUI_DEFINE_MATH_OPERATORS #include "imgui/imgui_internal.h" #include "window/imgui_ext.h" using namespace euphoria::core; using namespace euphoria::render; using namespace euphoria::window; ImU32 C(const Rgbai& c) { return IM_COL32(c.r, c.g, c.b, c.a); } bool IsOver(const ImVec2& min, const ImVec2& max, const ImVec2& mouse) { const auto over_min = min.x <= mouse.x && min.y <= mouse.y; const auto over_max = max.x >= mouse.x && max.y >= mouse.y; return over_min && over_max; } int main(int argc, char** argv) { Engine engine; if (const auto r = engine.Setup(argparse::Arguments::Extract(argc, argv)); r != 0) { return r; } int window_width = 1280; int window_height = 720; if(!engine.CreateWindow("Painter", window_width, window_height, true)) { return -1; } // ViewportHandler viewport_handler; // viewport_handler.SetSize(window_width, window_height); bool running = true; ////////////////////////////////////////////////////////////////////////////// // main loop CanvasConfig cc; Canvas canvas; Image image; Random random; auto palette = palette::EDG64(); auto foreground = 0; auto background = 1; image.SetupNoAlphaSupport(64, 64); image.SetAllTopBottom([&](int x, int y) { return Rgbai{palette.colors[background]}; }); while(running) { SDL_Event e; while(SDL_PollEvent(&e) != 0) { engine.imgui->ProcessEvents(&e); if(engine.HandleResize(e, &window_width, &window_height)) { // viewport_handler.SetSize(window_width, window_height); } switch(e.type) { case SDL_QUIT: running = false; break; default: // ignore other events break; } } engine.imgui->StartNewFrame(); if(ImGui::BeginMainMenuBar()) { if(ImGui::BeginMenu("File")) { if(ImGui::MenuItem("Exit", "Ctrl+Q")) { running = false; } ImGui::EndMenu(); } } ImGui::EndMainMenuBar(); if(ImGui::Begin("palette")) { const auto tile_size = 20; const auto spacing = 3; auto x = 0.0f; auto y = 0.0f; if(imgui::CanvasBegin(ImVec4(0.3, 0.3, 0.3, 1.0f), "palette")) { const auto p = ImGui::GetCursorScreenPos(); const auto size = ImGui::GetContentRegionAvail(); const auto hovering = ImGui::IsAnyItemHovered(); const auto left_clicked = ImGui::IsMouseClicked(0); const auto right_clicked = ImGui::IsMouseClicked(1); ImDrawList* draw_list = ImGui::GetWindowDrawList(); for(int palette_index=0; palette_index<palette.colors.size(); palette_index+=1) { if(x + tile_size > size.x) { x = 0; y += tile_size + spacing; } const auto min = p + ImVec2(x, y); const auto max = min + ImVec2(tile_size, tile_size); const auto mouse = ImGui::GetMousePos(); draw_list->AddRectFilled(min, max, C(palette.colors[palette_index])); x += tile_size + spacing; if(!hovering && (left_clicked || right_clicked)) { if(IsOver(min, max, mouse)) { if(left_clicked) { foreground = palette_index; } else { background = palette_index; } } } } imgui::CanvasEnd(); } } ImGui::End(); ImGui::SetNextWindowSize(ImVec2 {300, 300}, ImGuiCond_FirstUseEver); if(ImGui::Begin("pixel")) { if(image.IsValid()) { const auto hovering = ImGui::IsAnyItemHovered(); const auto left_down = ImGui::IsMouseDown(0); const auto right_down = ImGui::IsMouseDown(1); canvas.Begin(cc); canvas.ShowGrid(cc); // draw image ImDrawList* draw_list = ImGui::GetWindowDrawList(); image.ForAllTopBottom([&](int x, int y, const Rgbai& c) { const auto pixel_size = 5; const auto p = ImVec2(x * pixel_size, y*pixel_size); const auto s = ImVec2(pixel_size, pixel_size); const auto ps = canvas.WorldToScreen(p); const auto pss = canvas.WorldToScreen(p+s); const auto m = ImGui::GetMousePos(); if(ps.x <= m.x && ps.y <= m.y && pss.x >= m.x && pss.y >= m.y) { // hovering over pixel if(!hovering && left_down) { image.SetPixel(x, y, palette.colors[foreground]); } // hovering over pixel if(!hovering && right_down) { image.SetPixel(x, y, palette.colors[background]); } } draw_list->AddRectFilled(ps, pss, C(c)); }); canvas.ShowRuler(cc); canvas.End(cc); } } ImGui::End(); // ImGui::ShowMetricsWindow(); engine.init->ClearScreen(Color::LightGray); engine.imgui->Render(); SDL_GL_SwapWindow(engine.window->window); } return 0; } <commit_msg>draw currently selected palette<commit_after>#include "core/mat4.h" #include "core/random.h" #include "core/mat4.h" #include "core/axisangle.h" #include "core/aabb.h" #include "core/texturetypes.h" #include "core/vfs.h" #include "core/vfs_imagegenerator.h" #include "core/vfs_path.h" #include "core/os.h" #include "core/range.h" #include "core/camera.h" #include "core/stringutils.h" #include "core/stdutils.h" #include "core/proto.h" #include "core/log.h" #include "core/rgb.h" #include "core/colors.h" #include "core/palette_lospec.h" #include "core/palette.h" #include "render/init.h" #include "render/debuggl.h" #include "render/materialshader.h" #include "render/compiledmesh.h" #include "render/texturecache.h" #include "render/shaderattribute3d.h" #include "render/texture.h" #include "render/world.h" #include "render/viewport.h" #include "render/materialshadercache.h" #include "render/defaultfiles.h" #include "window/imguilibrary.h" #include "window/timer.h" #include "window/imgui_ext.h" #include "window/imgui_extra.h" #include "window/sdllibrary.h" #include "window/sdlwindow.h" #include "window/sdlglcontext.h" #include "window/filesystem.h" #include "window/engine.h" #include "window/canvas.h" #include "imgui/imgui.h" #include "SDL.h" #include <iostream> #include <memory> #define IMGUI_DEFINE_MATH_OPERATORS #include "imgui/imgui_internal.h" #include "window/imgui_ext.h" using namespace euphoria::core; using namespace euphoria::render; using namespace euphoria::window; ImU32 C(const Rgbai& c) { return IM_COL32(c.r, c.g, c.b, c.a); } bool IsOver(const ImVec2& min, const ImVec2& max, const ImVec2& mouse) { const auto over_min = min.x <= mouse.x && min.y <= mouse.y; const auto over_max = max.x >= mouse.x && max.y >= mouse.y; return over_min && over_max; } int main(int argc, char** argv) { Engine engine; if (const auto r = engine.Setup(argparse::Arguments::Extract(argc, argv)); r != 0) { return r; } int window_width = 1280; int window_height = 720; if(!engine.CreateWindow("Painter", window_width, window_height, true)) { return -1; } // ViewportHandler viewport_handler; // viewport_handler.SetSize(window_width, window_height); bool running = true; ////////////////////////////////////////////////////////////////////////////// // main loop CanvasConfig cc; Canvas canvas; Image image; Random random; auto palette = palette::EDG64(); auto foreground = 0; auto background = 1; image.SetupNoAlphaSupport(64, 64); image.SetAllTopBottom([&](int x, int y) { return Rgbai{palette.colors[background]}; }); while(running) { SDL_Event e; while(SDL_PollEvent(&e) != 0) { engine.imgui->ProcessEvents(&e); if(engine.HandleResize(e, &window_width, &window_height)) { // viewport_handler.SetSize(window_width, window_height); } switch(e.type) { case SDL_QUIT: running = false; break; default: // ignore other events break; } } engine.imgui->StartNewFrame(); if(ImGui::BeginMainMenuBar()) { if(ImGui::BeginMenu("File")) { if(ImGui::MenuItem("Exit", "Ctrl+Q")) { running = false; } ImGui::EndMenu(); } } ImGui::EndMainMenuBar(); if(ImGui::Begin("palette")) { const auto tile_size = 20; const auto spacing = 3; const auto big_spacing = 10; const auto big_offset = 0.20f; const auto max_pal_size = tile_size * 5; if(imgui::CanvasBegin(ImVec4(0.3, 0.3, 0.3, 1.0f), "palette")) { const auto p = ImGui::GetCursorScreenPos(); const auto size = ImGui::GetContentRegionAvail(); const auto hovering = ImGui::IsAnyItemHovered(); const auto left_clicked = ImGui::IsMouseClicked(0); const auto right_clicked = ImGui::IsMouseClicked(1); const auto mouse = ImGui::GetMousePos(); ImDrawList* draw_list = ImGui::GetWindowDrawList(); auto x = 0.0f; auto y = 0.0f; for(int palette_index=0; palette_index<palette.colors.size(); palette_index+=1) { if(x + tile_size > size.x) { x = 0; y += tile_size + spacing; } const auto min = p + ImVec2(x, y); const auto max = min + ImVec2(tile_size, tile_size); draw_list->AddRectFilled(min, max, C(palette.colors[palette_index])); x += tile_size + spacing; if(!hovering && (left_clicked || right_clicked)) { if(IsOver(min, max, mouse)) { if(left_clicked) { foreground = palette_index; } else { background = palette_index; } } } } y += tile_size; const auto big_size = std::min(size.x, size.y - y) - big_spacing * 2; if(big_size > 0) { const auto bsf = std::min<float>(max_pal_size, big_size / (1+big_offset)); const auto bs = ImVec2(bsf, bsf); const auto foreground_pos = ImVec2 ( size.x/2 - (bsf * (1+big_offset))/2, y+big_spacing ); const auto background_pos = foreground_pos + bs * big_offset; draw_list->AddRectFilled(p + background_pos, p + background_pos + bs, C(palette.GetSafeIndex(background))); draw_list->AddRectFilled(p + foreground_pos, p + foreground_pos + bs, C(palette.GetSafeIndex(foreground))); } imgui::CanvasEnd(); } } ImGui::End(); ImGui::SetNextWindowSize(ImVec2 {300, 300}, ImGuiCond_FirstUseEver); if(ImGui::Begin("pixel")) { if(image.IsValid()) { const auto hovering = ImGui::IsAnyItemHovered(); const auto left_down = ImGui::IsMouseDown(0); const auto right_down = ImGui::IsMouseDown(1); canvas.Begin(cc); canvas.ShowGrid(cc); // draw image ImDrawList* draw_list = ImGui::GetWindowDrawList(); image.ForAllTopBottom([&](int x, int y, const Rgbai& c) { const auto pixel_size = 5; const auto p = ImVec2(x * pixel_size, y*pixel_size); const auto s = ImVec2(pixel_size, pixel_size); const auto ps = canvas.WorldToScreen(p); const auto pss = canvas.WorldToScreen(p+s); const auto m = ImGui::GetMousePos(); if(ps.x <= m.x && ps.y <= m.y && pss.x >= m.x && pss.y >= m.y) { // hovering over pixel if(!hovering && left_down) { image.SetPixel(x, y, palette.colors[foreground]); } // hovering over pixel if(!hovering && right_down) { image.SetPixel(x, y, palette.colors[background]); } } draw_list->AddRectFilled(ps, pss, C(c)); }); canvas.ShowRuler(cc); canvas.End(cc); } } ImGui::End(); // ImGui::ShowMetricsWindow(); engine.init->ClearScreen(Color::LightGray); engine.imgui->Render(); SDL_GL_SwapWindow(engine.window->window); } return 0; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtQml/qqmlextensionplugin.h> #include <QtQml/qqml.h> #include <QtQml/qjsvalue.h> #include <QtQml/qjsengine.h> #include "QtQuickTest/private/quicktestresult_p.h" #include "QtQuickTest/private/quicktestevent_p.h" #include "private/qtestoptions_p.h" #include "QtQuick/qquickitem.h" #include <QtQml/private/qqmlengine_p.h> #include <QtGui/QGuiApplication> #include <QtGui/qstylehints.h> QML_DECLARE_TYPE(QuickTestResult) QML_DECLARE_TYPE(QuickTestEvent) #include <QtDebug> QT_BEGIN_NAMESPACE class QuickTestUtil : public QObject { Q_OBJECT Q_PROPERTY(bool printAvailableFunctions READ printAvailableFunctions NOTIFY printAvailableFunctionsChanged) Q_PROPERTY(int dragThreshold READ dragThreshold NOTIFY dragThresholdChanged) public: QuickTestUtil(QObject *parent = 0) :QObject(parent) {} ~QuickTestUtil() {} bool printAvailableFunctions() const { return QTest::printAvailableFunctions; } int dragThreshold() const { return qApp->styleHints()->startDragDistance(); } Q_SIGNALS: void printAvailableFunctionsChanged(); void dragThresholdChanged(); public Q_SLOTS: QQmlV4Handle typeName(const QVariant& v) const { QString name(v.typeName()); if (v.canConvert<QObject*>()) { QQmlType *type = 0; const QMetaObject *mo = v.value<QObject*>()->metaObject(); while (!type && mo) { type = QQmlMetaType::qmlType(mo); mo = mo->superClass(); } if (type) { name = type->qmlTypeName(); } } return QQmlV4Handle(v8::String::New(name.toUtf8())->v4Value()); } bool compare(const QVariant& act, const QVariant& exp) const { return act == exp; } QQmlV4Handle callerFile(int frameIndex = 0) const { QQmlEngine *engine = qmlEngine(this); QV4::ExecutionEngine *v4 = QV8Engine::getV4(engine->handle()); QVector<QV4::ExecutionEngine::StackFrame> stack = v4->stackTrace(frameIndex + 1); if (stack.size() > frameIndex) return QQmlV4Handle(QV4::Value::fromString(v4->newString(stack.at(frameIndex).source))); return QQmlV4Handle(); } int callerLine(int frameIndex = 0) const { QQmlEngine *engine = qmlEngine(this); QV4::ExecutionEngine *v4 = QV8Engine::getV4(engine->handle()); QVector<QV4::ExecutionEngine::StackFrame> stack = v4->stackTrace(frameIndex + 1); if (stack.size() > frameIndex) return stack.at(frameIndex).line; return -1; } }; QT_END_NAMESPACE QML_DECLARE_TYPE(QuickTestUtil) QT_BEGIN_NAMESPACE class QTestQmlModule : public QQmlExtensionPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface") public: virtual void registerTypes(const char *uri) { Q_ASSERT(QLatin1String(uri) == QLatin1String("QtTest")); qmlRegisterType<QuickTestResult>(uri,1,0,"TestResult"); qmlRegisterType<QuickTestEvent>(uri,1,0,"TestEvent"); qmlRegisterType<QuickTestUtil>(uri,1,0,"TestUtil"); } void initializeEngine(QQmlEngine *, const char *) { } }; QT_END_NAMESPACE #include "main.moc" <commit_msg>Remove last v8 dependency in the testlib<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtQml/qqmlextensionplugin.h> #include <QtQml/qqml.h> #include <QtQml/qjsvalue.h> #include <QtQml/qjsengine.h> #include "QtQuickTest/private/quicktestresult_p.h" #include "QtQuickTest/private/quicktestevent_p.h" #include "private/qtestoptions_p.h" #include "QtQuick/qquickitem.h" #include <QtQml/private/qqmlengine_p.h> #include <QtGui/QGuiApplication> #include <QtGui/qstylehints.h> QML_DECLARE_TYPE(QuickTestResult) QML_DECLARE_TYPE(QuickTestEvent) #include <QtDebug> QT_BEGIN_NAMESPACE class QuickTestUtil : public QObject { Q_OBJECT Q_PROPERTY(bool printAvailableFunctions READ printAvailableFunctions NOTIFY printAvailableFunctionsChanged) Q_PROPERTY(int dragThreshold READ dragThreshold NOTIFY dragThresholdChanged) public: QuickTestUtil(QObject *parent = 0) :QObject(parent) {} ~QuickTestUtil() {} bool printAvailableFunctions() const { return QTest::printAvailableFunctions; } int dragThreshold() const { return qApp->styleHints()->startDragDistance(); } Q_SIGNALS: void printAvailableFunctionsChanged(); void dragThresholdChanged(); public Q_SLOTS: QQmlV4Handle typeName(const QVariant& v) const { QString name(v.typeName()); if (v.canConvert<QObject*>()) { QQmlType *type = 0; const QMetaObject *mo = v.value<QObject*>()->metaObject(); while (!type && mo) { type = QQmlMetaType::qmlType(mo); mo = mo->superClass(); } if (type) { name = type->qmlTypeName(); } } QQmlEngine *engine = qmlEngine(this); QV4::ExecutionEngine *v4 = QV8Engine::getV4(engine->handle()); return QQmlV4Handle(QV4::Value::fromString(v4->newString(name))); } bool compare(const QVariant& act, const QVariant& exp) const { return act == exp; } QQmlV4Handle callerFile(int frameIndex = 0) const { QQmlEngine *engine = qmlEngine(this); QV4::ExecutionEngine *v4 = QV8Engine::getV4(engine->handle()); QVector<QV4::ExecutionEngine::StackFrame> stack = v4->stackTrace(frameIndex + 1); if (stack.size() > frameIndex) return QQmlV4Handle(QV4::Value::fromString(v4->newString(stack.at(frameIndex).source))); return QQmlV4Handle(); } int callerLine(int frameIndex = 0) const { QQmlEngine *engine = qmlEngine(this); QV4::ExecutionEngine *v4 = QV8Engine::getV4(engine->handle()); QVector<QV4::ExecutionEngine::StackFrame> stack = v4->stackTrace(frameIndex + 1); if (stack.size() > frameIndex) return stack.at(frameIndex).line; return -1; } }; QT_END_NAMESPACE QML_DECLARE_TYPE(QuickTestUtil) QT_BEGIN_NAMESPACE class QTestQmlModule : public QQmlExtensionPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface") public: virtual void registerTypes(const char *uri) { Q_ASSERT(QLatin1String(uri) == QLatin1String("QtTest")); qmlRegisterType<QuickTestResult>(uri,1,0,"TestResult"); qmlRegisterType<QuickTestEvent>(uri,1,0,"TestEvent"); qmlRegisterType<QuickTestUtil>(uri,1,0,"TestUtil"); } void initializeEngine(QQmlEngine *, const char *) { } }; QT_END_NAMESPACE #include "main.moc" <|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 "chrome/browser/profiles/profile.h" #include "base/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/platform_file.h" #include "base/version.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/chrome_version_service.h" #include "chrome/browser/profiles/profile_impl.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace { class MockProfileDelegate : public Profile::Delegate { public: MOCK_METHOD3(OnProfileCreated, void(Profile*, bool, bool)); }; // Creates a prefs file in the given directory. void CreatePrefsFileInDirectory(const FilePath& directory_path) { FilePath pref_path(directory_path.Append(chrome::kPreferencesFilename)); base::PlatformFile file = base::CreatePlatformFile(pref_path, base::PLATFORM_FILE_CREATE | base::PLATFORM_FILE_WRITE, NULL, NULL); ASSERT_TRUE(file != base::kInvalidPlatformFileValue); ASSERT_TRUE(base::ClosePlatformFile(file)); std::string data("{}"); ASSERT_TRUE(file_util::WriteFile(pref_path, data.c_str(), data.size())); } void CheckChromeVersion(Profile *profile, bool is_new) { std::string created_by_version; if (is_new) { chrome::VersionInfo version_info; created_by_version = version_info.Version(); } else { created_by_version = "1.0.0.0"; } std::string pref_version = ChromeVersionService::GetVersion(profile->GetPrefs()); // Assert that created_by_version pref gets set to current version. EXPECT_EQ(created_by_version, pref_version); } } // namespace typedef InProcessBrowserTest ProfileBrowserTest; // Test OnProfileCreate is called with is_new_profile set to true when // creating a new profile synchronously. // // Flaky (sometimes timeout): http://crbug.com/141141 IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, DISABLED_CreateNewProfileSynchronous) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); MockProfileDelegate delegate; EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true)); scoped_ptr<Profile> profile(Profile::CreateProfile( temp_dir.path(), &delegate, Profile::CREATE_MODE_SYNCHRONOUS)); ASSERT_TRUE(profile.get()); CheckChromeVersion(profile.get(), true); } // Test OnProfileCreate is called with is_new_profile set to false when // creating a profile synchronously with an existing prefs file. // Flaky: http://crbug.com/141517 IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, DISABLED_CreateOldProfileSynchronous) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); CreatePrefsFileInDirectory(temp_dir.path()); MockProfileDelegate delegate; EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, false)); scoped_ptr<Profile> profile(Profile::CreateProfile( temp_dir.path(), &delegate, Profile::CREATE_MODE_SYNCHRONOUS)); ASSERT_TRUE(profile.get()); CheckChromeVersion(profile.get(), false); } // Test OnProfileCreate is called with is_new_profile set to true when // creating a new profile asynchronously. // This test is flaky on Linux, Win and Mac. See crbug.com/142787 IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, DISABLED_CreateNewProfileAsynchronous) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); MockProfileDelegate delegate; EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true)); scoped_ptr<Profile> profile(Profile::CreateProfile( temp_dir.path(), &delegate, Profile::CREATE_MODE_ASYNCHRONOUS)); ASSERT_TRUE(profile.get()); // Wait for the profile to be created. content::WindowedNotificationObserver observer( chrome::NOTIFICATION_PROFILE_CREATED, content::Source<Profile>(profile.get())); observer.Wait(); CheckChromeVersion(profile.get(), true); } // Test OnProfileCreate is called with is_new_profile set to false when // creating a profile asynchronously with an existing prefs file. // Flaky: http://crbug.com/141517 IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, DISABLED_CreateOldProfileAsynchronous) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); CreatePrefsFileInDirectory(temp_dir.path()); MockProfileDelegate delegate; EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, false)); scoped_ptr<Profile> profile(Profile::CreateProfile( temp_dir.path(), &delegate, Profile::CREATE_MODE_ASYNCHRONOUS)); ASSERT_TRUE(profile.get()); // Wait for the profile to be created. content::WindowedNotificationObserver observer( chrome::NOTIFICATION_PROFILE_CREATED, content::Source<Profile>(profile.get())); observer.Wait(); CheckChromeVersion(profile.get(), false); } // Test that a README file is created for profiles that didn't have it. // Flaky: http://crbug.com/140882 IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, DISABLED_ProfileReadmeCreated) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); MockProfileDelegate delegate; EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true)); // No delay before README creation. ProfileImpl::create_readme_delay_ms = 0; scoped_ptr<Profile> profile(Profile::CreateProfile( temp_dir.path(), &delegate, Profile::CREATE_MODE_ASYNCHRONOUS)); ASSERT_TRUE(profile.get()); // Wait for the profile to be created. content::WindowedNotificationObserver observer( chrome::NOTIFICATION_PROFILE_CREATED, content::Source<Profile>(profile.get())); observer.Wait(); content::RunAllPendingInMessageLoop(content::BrowserThread::FILE); // Verify that README exists. EXPECT_TRUE(file_util::PathExists( temp_dir.path().Append(chrome::kReadmeFilename))); } // Test that Profile can be deleted before README file is created. IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, ProfileDeletedBeforeReadmeCreated) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); MockProfileDelegate delegate; EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true)); // No delay before README creation. ProfileImpl::create_readme_delay_ms = 0; scoped_ptr<Profile> profile(Profile::CreateProfile( temp_dir.path(), &delegate, Profile::CREATE_MODE_SYNCHRONOUS)); ASSERT_TRUE(profile.get()); // Delete the Profile instance and run pending tasks (this includes the task // for README creation). profile.reset(); content::RunAllPendingInMessageLoop(); content::RunAllPendingInMessageLoop(content::BrowserThread::FILE); } // Test that repeated setting of exit type is handled correctly. IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, ExitType) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); MockProfileDelegate delegate; EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true)); scoped_ptr<Profile> profile(Profile::CreateProfile( temp_dir.path(), &delegate, Profile::CREATE_MODE_SYNCHRONOUS)); ASSERT_TRUE(profile.get()); PrefService* prefs = profile->GetPrefs(); // The initial state is crashed; store for later reference. std::string crash_value(prefs->GetString(prefs::kSessionExitType)); // The first call to a type other than crashed should change the value. profile->SetExitType(Profile::EXIT_SESSION_ENDED); std::string first_call_value(prefs->GetString(prefs::kSessionExitType)); EXPECT_NE(crash_value, first_call_value); // Subsequent calls to a non-crash value should be ignored. profile->SetExitType(Profile::EXIT_NORMAL); std::string second_call_value(prefs->GetString(prefs::kSessionExitType)); EXPECT_EQ(first_call_value, second_call_value); // Setting back to a crashed value should work. profile->SetExitType(Profile::EXIT_CRASHED); std::string final_value(prefs->GetString(prefs::kSessionExitType)); EXPECT_EQ(crash_value, final_value); } <commit_msg>Disable ProfileBrowserTest.ExitType on Windows where it times out sometimes.<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 "chrome/browser/profiles/profile.h" #include "base/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/platform_file.h" #include "base/version.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/chrome_version_service.h" #include "chrome/browser/profiles/profile_impl.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace { class MockProfileDelegate : public Profile::Delegate { public: MOCK_METHOD3(OnProfileCreated, void(Profile*, bool, bool)); }; // Creates a prefs file in the given directory. void CreatePrefsFileInDirectory(const FilePath& directory_path) { FilePath pref_path(directory_path.Append(chrome::kPreferencesFilename)); base::PlatformFile file = base::CreatePlatformFile(pref_path, base::PLATFORM_FILE_CREATE | base::PLATFORM_FILE_WRITE, NULL, NULL); ASSERT_TRUE(file != base::kInvalidPlatformFileValue); ASSERT_TRUE(base::ClosePlatformFile(file)); std::string data("{}"); ASSERT_TRUE(file_util::WriteFile(pref_path, data.c_str(), data.size())); } void CheckChromeVersion(Profile *profile, bool is_new) { std::string created_by_version; if (is_new) { chrome::VersionInfo version_info; created_by_version = version_info.Version(); } else { created_by_version = "1.0.0.0"; } std::string pref_version = ChromeVersionService::GetVersion(profile->GetPrefs()); // Assert that created_by_version pref gets set to current version. EXPECT_EQ(created_by_version, pref_version); } } // namespace typedef InProcessBrowserTest ProfileBrowserTest; // Test OnProfileCreate is called with is_new_profile set to true when // creating a new profile synchronously. // // Flaky (sometimes timeout): http://crbug.com/141141 IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, DISABLED_CreateNewProfileSynchronous) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); MockProfileDelegate delegate; EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true)); scoped_ptr<Profile> profile(Profile::CreateProfile( temp_dir.path(), &delegate, Profile::CREATE_MODE_SYNCHRONOUS)); ASSERT_TRUE(profile.get()); CheckChromeVersion(profile.get(), true); } // Test OnProfileCreate is called with is_new_profile set to false when // creating a profile synchronously with an existing prefs file. // Flaky: http://crbug.com/141517 IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, DISABLED_CreateOldProfileSynchronous) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); CreatePrefsFileInDirectory(temp_dir.path()); MockProfileDelegate delegate; EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, false)); scoped_ptr<Profile> profile(Profile::CreateProfile( temp_dir.path(), &delegate, Profile::CREATE_MODE_SYNCHRONOUS)); ASSERT_TRUE(profile.get()); CheckChromeVersion(profile.get(), false); } // Test OnProfileCreate is called with is_new_profile set to true when // creating a new profile asynchronously. // This test is flaky on Linux, Win and Mac. See crbug.com/142787 IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, DISABLED_CreateNewProfileAsynchronous) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); MockProfileDelegate delegate; EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true)); scoped_ptr<Profile> profile(Profile::CreateProfile( temp_dir.path(), &delegate, Profile::CREATE_MODE_ASYNCHRONOUS)); ASSERT_TRUE(profile.get()); // Wait for the profile to be created. content::WindowedNotificationObserver observer( chrome::NOTIFICATION_PROFILE_CREATED, content::Source<Profile>(profile.get())); observer.Wait(); CheckChromeVersion(profile.get(), true); } // Test OnProfileCreate is called with is_new_profile set to false when // creating a profile asynchronously with an existing prefs file. // Flaky: http://crbug.com/141517 IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, DISABLED_CreateOldProfileAsynchronous) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); CreatePrefsFileInDirectory(temp_dir.path()); MockProfileDelegate delegate; EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, false)); scoped_ptr<Profile> profile(Profile::CreateProfile( temp_dir.path(), &delegate, Profile::CREATE_MODE_ASYNCHRONOUS)); ASSERT_TRUE(profile.get()); // Wait for the profile to be created. content::WindowedNotificationObserver observer( chrome::NOTIFICATION_PROFILE_CREATED, content::Source<Profile>(profile.get())); observer.Wait(); CheckChromeVersion(profile.get(), false); } // Test that a README file is created for profiles that didn't have it. // Flaky: http://crbug.com/140882 IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, DISABLED_ProfileReadmeCreated) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); MockProfileDelegate delegate; EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true)); // No delay before README creation. ProfileImpl::create_readme_delay_ms = 0; scoped_ptr<Profile> profile(Profile::CreateProfile( temp_dir.path(), &delegate, Profile::CREATE_MODE_ASYNCHRONOUS)); ASSERT_TRUE(profile.get()); // Wait for the profile to be created. content::WindowedNotificationObserver observer( chrome::NOTIFICATION_PROFILE_CREATED, content::Source<Profile>(profile.get())); observer.Wait(); content::RunAllPendingInMessageLoop(content::BrowserThread::FILE); // Verify that README exists. EXPECT_TRUE(file_util::PathExists( temp_dir.path().Append(chrome::kReadmeFilename))); } // Test that Profile can be deleted before README file is created. IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, ProfileDeletedBeforeReadmeCreated) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); MockProfileDelegate delegate; EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true)); // No delay before README creation. ProfileImpl::create_readme_delay_ms = 0; scoped_ptr<Profile> profile(Profile::CreateProfile( temp_dir.path(), &delegate, Profile::CREATE_MODE_SYNCHRONOUS)); ASSERT_TRUE(profile.get()); // Delete the Profile instance and run pending tasks (this includes the task // for README creation). profile.reset(); content::RunAllPendingInMessageLoop(); content::RunAllPendingInMessageLoop(content::BrowserThread::FILE); } // Test that repeated setting of exit type is handled correctly. #if defined(OS_WIN) // Flaky on Windows: http://crbug.com/163713 #define MAYBE_ExitType DISABLED_ExitType #else #define MAYBE_ExitType ExitType #endif IN_PROC_BROWSER_TEST_F(ProfileBrowserTest, MAYBE_ExitType) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); MockProfileDelegate delegate; EXPECT_CALL(delegate, OnProfileCreated(testing::NotNull(), true, true)); scoped_ptr<Profile> profile(Profile::CreateProfile( temp_dir.path(), &delegate, Profile::CREATE_MODE_SYNCHRONOUS)); ASSERT_TRUE(profile.get()); PrefService* prefs = profile->GetPrefs(); // The initial state is crashed; store for later reference. std::string crash_value(prefs->GetString(prefs::kSessionExitType)); // The first call to a type other than crashed should change the value. profile->SetExitType(Profile::EXIT_SESSION_ENDED); std::string first_call_value(prefs->GetString(prefs::kSessionExitType)); EXPECT_NE(crash_value, first_call_value); // Subsequent calls to a non-crash value should be ignored. profile->SetExitType(Profile::EXIT_NORMAL); std::string second_call_value(prefs->GetString(prefs::kSessionExitType)); EXPECT_EQ(first_call_value, second_call_value); // Setting back to a crashed value should work. profile->SetExitType(Profile::EXIT_CRASHED); std::string final_value(prefs->GetString(prefs::kSessionExitType)); EXPECT_EQ(crash_value, final_value); } <|endoftext|>
<commit_before><commit_msg>user c-array instead of vector<> in hot loop<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/signin_manager.h" #include "chrome/browser/net/gaia/token_service.h" #include "chrome/browser/net/gaia/token_service_unittest.h" #include "chrome/browser/password_manager/encryptor.h" #include "chrome/browser/sync/util/oauth.h" #include "chrome/browser/webdata/web_data_service.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/net/gaia/gaia_urls.h" #include "chrome/test/base/signaling_task.h" #include "chrome/test/base/testing_profile.h" #include "content/test/test_url_fetcher_factory.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_status.h" #include "testing/gtest/include/gtest/gtest.h" class SigninManagerTest : public TokenServiceTestHarness { public: virtual void SetUp() OVERRIDE { TokenServiceTestHarness::SetUp(); manager_.reset(new SigninManager()); google_login_success_.ListenFor( chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL, Source<Profile>(profile_.get())); google_login_failure_.ListenFor(chrome::NOTIFICATION_GOOGLE_SIGNIN_FAILED, Source<Profile>(profile_.get())); originally_using_oauth_ = browser_sync::IsUsingOAuth(); } virtual void TearDown() OVERRIDE { browser_sync::SetIsUsingOAuthForTest(originally_using_oauth_); } void SimulateValidResponseClientLogin() { DCHECK(!browser_sync::IsUsingOAuth()); // Simulate the correct ClientLogin response. TestURLFetcher* fetcher = factory_.GetFetcherByID(0); DCHECK(fetcher); DCHECK(fetcher->delegate()); fetcher->delegate()->OnURLFetchComplete( fetcher, GURL(GaiaUrls::GetInstance()->client_login_url()), net::URLRequestStatus(), 200, net::ResponseCookies(), "SID=sid\nLSID=lsid\nAuth=auth"); // Then simulate the correct GetUserInfo response for the canonical email. // A new URL fetcher is used for each call. fetcher = factory_.GetFetcherByID(0); DCHECK(fetcher); DCHECK(fetcher->delegate()); fetcher->delegate()->OnURLFetchComplete( fetcher, GURL(GaiaUrls::GetInstance()->get_user_info_url()), net::URLRequestStatus(), 200, net::ResponseCookies(), "[email protected]"); } void SimulateSigninStartOAuth() { DCHECK(browser_sync::IsUsingOAuth()); // Simulate a valid OAuth-based signin manager_->OnGetOAuthTokenSuccess("oauth_token-Ev1Vu1hv"); manager_->OnOAuthGetAccessTokenSuccess("oauth1_access_token-qOAmlrSM", "secret-NKKn1DuR"); manager_->OnOAuthWrapBridgeSuccess(browser_sync::SyncServiceName(), "oauth2_wrap_access_token-R0Z3nRtw", "3600"); } void SimulateOAuthUserInfoSuccess() { manager_->OnUserInfoSuccess("[email protected]"); } void SimulateValidSigninOAuth() { SimulateSigninStartOAuth(); SimulateOAuthUserInfoSuccess(); } TestURLFetcherFactory factory_; scoped_ptr<SigninManager> manager_; TestNotificationTracker google_login_success_; TestNotificationTracker google_login_failure_; bool originally_using_oauth_; }; // NOTE: ClientLogin's "StartSignin" is called after collecting credentials // from the user. See also SigninManagerTest::SignInOAuth. TEST_F(SigninManagerTest, SignInClientLogin) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); manager_->StartSignIn("username", "password", "", ""); EXPECT_FALSE(manager_->GetUsername().empty()); SimulateValidResponseClientLogin(); // Should go into token service and stop. EXPECT_EQ(1U, google_login_success_.size()); EXPECT_EQ(0U, google_login_failure_.size()); // Should persist across resets. manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_EQ("[email protected]", manager_->GetUsername()); } // NOTE: OAuth's "StartOAuthSignIn" is called before collecting credentials // from the user. See also SigninManagerTest::SignInClientLogin. TEST_F(SigninManagerTest, SignInOAuth) { browser_sync::SetIsUsingOAuthForTest(true); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); SimulateValidSigninOAuth(); EXPECT_FALSE(manager_->GetUsername().empty()); // Should go into token service and stop. EXPECT_EQ(1U, google_login_success_.size()); EXPECT_EQ(0U, google_login_failure_.size()); // Should persist across resets. manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_EQ("[email protected]", manager_->GetUsername()); } TEST_F(SigninManagerTest, SignOutClientLogin) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); SimulateValidResponseClientLogin(); manager_->OnClientLoginSuccess(credentials_); EXPECT_EQ("[email protected]", manager_->GetUsername()); manager_->SignOut(); EXPECT_TRUE(manager_->GetUsername().empty()); // Should not be persisted anymore manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, SignOutOAuth) { browser_sync::SetIsUsingOAuthForTest(true); manager_->Initialize(profile_.get()); SimulateValidSigninOAuth(); EXPECT_FALSE(manager_->GetUsername().empty()); EXPECT_EQ("[email protected]", manager_->GetUsername()); manager_->SignOut(); EXPECT_TRUE(manager_->GetUsername().empty()); // Should not be persisted anymore manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, SignInFailureClientLogin) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); GoogleServiceAuthError error(GoogleServiceAuthError::REQUEST_CANCELED); manager_->OnClientLoginFailure(error); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(1U, google_login_failure_.size()); EXPECT_TRUE(manager_->GetUsername().empty()); // Should not be persisted manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, ProvideSecondFactorSuccess) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); GoogleServiceAuthError error(GoogleServiceAuthError::TWO_FACTOR); manager_->OnClientLoginFailure(error); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(1U, google_login_failure_.size()); EXPECT_FALSE(manager_->GetUsername().empty()); manager_->ProvideSecondFactorAccessCode("access"); SimulateValidResponseClientLogin(); EXPECT_EQ(1U, google_login_success_.size()); EXPECT_EQ(1U, google_login_failure_.size()); } TEST_F(SigninManagerTest, ProvideSecondFactorFailure) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); GoogleServiceAuthError error1(GoogleServiceAuthError::TWO_FACTOR); manager_->OnClientLoginFailure(error1); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(1U, google_login_failure_.size()); EXPECT_FALSE(manager_->GetUsername().empty()); manager_->ProvideSecondFactorAccessCode("badaccess"); GoogleServiceAuthError error2( GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); manager_->OnClientLoginFailure(error2); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(2U, google_login_failure_.size()); EXPECT_FALSE(manager_->GetUsername().empty()); manager_->ProvideSecondFactorAccessCode("badaccess"); GoogleServiceAuthError error3(GoogleServiceAuthError::CONNECTION_FAILED); manager_->OnClientLoginFailure(error3); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(3U, google_login_failure_.size()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, SignOutMidConnect) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); manager_->SignOut(); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(0U, google_login_failure_.size()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, SignOutOnUserInfoSucessRaceTest) { browser_sync::SetIsUsingOAuthForTest(true); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); SimulateSigninStartOAuth(); manager_->SignOut(); SimulateOAuthUserInfoSuccess(); EXPECT_TRUE(manager_->GetUsername().empty()); } <commit_msg>Sync/Valgrind: Fix a leak in SigninManagerTest.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/signin_manager.h" #include "chrome/browser/net/gaia/token_service.h" #include "chrome/browser/net/gaia/token_service_unittest.h" #include "chrome/browser/password_manager/encryptor.h" #include "chrome/browser/sync/util/oauth.h" #include "chrome/browser/webdata/web_data_service.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/net/gaia/gaia_urls.h" #include "chrome/test/base/signaling_task.h" #include "chrome/test/base/testing_profile.h" #include "content/test/test_url_fetcher_factory.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_status.h" #include "testing/gtest/include/gtest/gtest.h" class SigninManagerTest : public TokenServiceTestHarness { public: virtual void SetUp() OVERRIDE { TokenServiceTestHarness::SetUp(); manager_.reset(new SigninManager()); google_login_success_.ListenFor( chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL, Source<Profile>(profile_.get())); google_login_failure_.ListenFor(chrome::NOTIFICATION_GOOGLE_SIGNIN_FAILED, Source<Profile>(profile_.get())); originally_using_oauth_ = browser_sync::IsUsingOAuth(); } virtual void TearDown() OVERRIDE { TokenServiceTestHarness::TearDown(); browser_sync::SetIsUsingOAuthForTest(originally_using_oauth_); } void SimulateValidResponseClientLogin() { DCHECK(!browser_sync::IsUsingOAuth()); // Simulate the correct ClientLogin response. TestURLFetcher* fetcher = factory_.GetFetcherByID(0); DCHECK(fetcher); DCHECK(fetcher->delegate()); fetcher->delegate()->OnURLFetchComplete( fetcher, GURL(GaiaUrls::GetInstance()->client_login_url()), net::URLRequestStatus(), 200, net::ResponseCookies(), "SID=sid\nLSID=lsid\nAuth=auth"); // Then simulate the correct GetUserInfo response for the canonical email. // A new URL fetcher is used for each call. fetcher = factory_.GetFetcherByID(0); DCHECK(fetcher); DCHECK(fetcher->delegate()); fetcher->delegate()->OnURLFetchComplete( fetcher, GURL(GaiaUrls::GetInstance()->get_user_info_url()), net::URLRequestStatus(), 200, net::ResponseCookies(), "[email protected]"); } void SimulateSigninStartOAuth() { DCHECK(browser_sync::IsUsingOAuth()); // Simulate a valid OAuth-based signin manager_->OnGetOAuthTokenSuccess("oauth_token-Ev1Vu1hv"); manager_->OnOAuthGetAccessTokenSuccess("oauth1_access_token-qOAmlrSM", "secret-NKKn1DuR"); manager_->OnOAuthWrapBridgeSuccess(browser_sync::SyncServiceName(), "oauth2_wrap_access_token-R0Z3nRtw", "3600"); } void SimulateOAuthUserInfoSuccess() { manager_->OnUserInfoSuccess("[email protected]"); } void SimulateValidSigninOAuth() { SimulateSigninStartOAuth(); SimulateOAuthUserInfoSuccess(); } TestURLFetcherFactory factory_; scoped_ptr<SigninManager> manager_; TestNotificationTracker google_login_success_; TestNotificationTracker google_login_failure_; bool originally_using_oauth_; }; // NOTE: ClientLogin's "StartSignin" is called after collecting credentials // from the user. See also SigninManagerTest::SignInOAuth. TEST_F(SigninManagerTest, SignInClientLogin) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); manager_->StartSignIn("username", "password", "", ""); EXPECT_FALSE(manager_->GetUsername().empty()); SimulateValidResponseClientLogin(); // Should go into token service and stop. EXPECT_EQ(1U, google_login_success_.size()); EXPECT_EQ(0U, google_login_failure_.size()); // Should persist across resets. manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_EQ("[email protected]", manager_->GetUsername()); } // NOTE: OAuth's "StartOAuthSignIn" is called before collecting credentials // from the user. See also SigninManagerTest::SignInClientLogin. TEST_F(SigninManagerTest, SignInOAuth) { browser_sync::SetIsUsingOAuthForTest(true); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); SimulateValidSigninOAuth(); EXPECT_FALSE(manager_->GetUsername().empty()); // Should go into token service and stop. EXPECT_EQ(1U, google_login_success_.size()); EXPECT_EQ(0U, google_login_failure_.size()); // Should persist across resets. manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_EQ("[email protected]", manager_->GetUsername()); } TEST_F(SigninManagerTest, SignOutClientLogin) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); SimulateValidResponseClientLogin(); manager_->OnClientLoginSuccess(credentials_); EXPECT_EQ("[email protected]", manager_->GetUsername()); manager_->SignOut(); EXPECT_TRUE(manager_->GetUsername().empty()); // Should not be persisted anymore manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, SignOutOAuth) { browser_sync::SetIsUsingOAuthForTest(true); manager_->Initialize(profile_.get()); SimulateValidSigninOAuth(); EXPECT_FALSE(manager_->GetUsername().empty()); EXPECT_EQ("[email protected]", manager_->GetUsername()); manager_->SignOut(); EXPECT_TRUE(manager_->GetUsername().empty()); // Should not be persisted anymore manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, SignInFailureClientLogin) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); GoogleServiceAuthError error(GoogleServiceAuthError::REQUEST_CANCELED); manager_->OnClientLoginFailure(error); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(1U, google_login_failure_.size()); EXPECT_TRUE(manager_->GetUsername().empty()); // Should not be persisted manager_.reset(new SigninManager()); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, ProvideSecondFactorSuccess) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); GoogleServiceAuthError error(GoogleServiceAuthError::TWO_FACTOR); manager_->OnClientLoginFailure(error); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(1U, google_login_failure_.size()); EXPECT_FALSE(manager_->GetUsername().empty()); manager_->ProvideSecondFactorAccessCode("access"); SimulateValidResponseClientLogin(); EXPECT_EQ(1U, google_login_success_.size()); EXPECT_EQ(1U, google_login_failure_.size()); } TEST_F(SigninManagerTest, ProvideSecondFactorFailure) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); GoogleServiceAuthError error1(GoogleServiceAuthError::TWO_FACTOR); manager_->OnClientLoginFailure(error1); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(1U, google_login_failure_.size()); EXPECT_FALSE(manager_->GetUsername().empty()); manager_->ProvideSecondFactorAccessCode("badaccess"); GoogleServiceAuthError error2( GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); manager_->OnClientLoginFailure(error2); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(2U, google_login_failure_.size()); EXPECT_FALSE(manager_->GetUsername().empty()); manager_->ProvideSecondFactorAccessCode("badaccess"); GoogleServiceAuthError error3(GoogleServiceAuthError::CONNECTION_FAILED); manager_->OnClientLoginFailure(error3); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(3U, google_login_failure_.size()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, SignOutMidConnect) { browser_sync::SetIsUsingOAuthForTest(false); manager_->Initialize(profile_.get()); manager_->StartSignIn("username", "password", "", ""); manager_->SignOut(); EXPECT_EQ(0U, google_login_success_.size()); EXPECT_EQ(0U, google_login_failure_.size()); EXPECT_TRUE(manager_->GetUsername().empty()); } TEST_F(SigninManagerTest, SignOutOnUserInfoSucessRaceTest) { browser_sync::SetIsUsingOAuthForTest(true); manager_->Initialize(profile_.get()); EXPECT_TRUE(manager_->GetUsername().empty()); SimulateSigninStartOAuth(); manager_->SignOut(); SimulateOAuthUserInfoSuccess(); EXPECT_TRUE(manager_->GetUsername().empty()); } <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "session.h" #include "domain.h" #include "domainpart.h" #include <vespa/fastlib/io/bufferedfile.h> #include <cassert> #include <vespa/log/log.h> LOG_SETUP(".transactionlog.session"); namespace search::transactionlog { vespalib::Executor::Task::UP Session::createTask(const Session::SP & session) { return std::make_unique<VisitTask>(session); } Session::VisitTask::VisitTask(const Session::SP & session) : _session(session) { _session->startVisit(); } Session::VisitTask::~VisitTask() = default; void Session::VisitTask::run() { _session->visitOnly(); } bool Session::visit(FastOS_FileInterface & file, DomainPart & dp) { Packet packet(size_t(-1)); bool more(false); if (dp.isClosed()) { more = dp.visit(file, _range, packet); } else { more = dp.visit(_range, packet); } if ( ! packet.getHandle().empty()) { send(packet); } return more; } void Session::visit() { LOG(debug, "[%d] : Visiting %" PRIu64 " - %" PRIu64, _id, _range.from(), _range.to()); for (DomainPart::SP dpSafe = _domain->findPart(_range.from()); dpSafe.get() && (_range.from() < _range.to()) && (dpSafe.get()->range().from() <= _range.to()); dpSafe = _domain->findPart(_range.from())) { // Must use findPart and iterate until no candidate parts found. DomainPart * dp(dpSafe.get()); LOG(debug, "[%d] : Visiting the interval %" PRIu64 " - %" PRIu64 " in domain part [%" PRIu64 ", %" PRIu64 "]", _id, _range.from(), _range.to(), dp->range().from(), dp->range().to()); Fast_BufferedFile file; file.EnableDirectIO(); for(bool more(true); ok() && more && (_range.from() < _range.to()); ) { more = visit(file, *dp); } // Nothing more in this DomainPart, force switch to next one. if (_range.from() < dp->range().to()) { _range.from(std::min(dp->range().to(), _range.to())); } } LOG(debug, "[%d] : Done visiting, starting subscribe %" PRIu64 " - %" PRIu64, _id, _range.from(), _range.to()); } void Session::startVisit() { assert(!_visitRunning); _visitRunning = true; } void Session::visitOnly() { visit(); sendDone(); finalize(); _visitRunning = false; } bool Session::finished() const { return _finished || ! _destination->connected(); } void Session::finalize() { if (!ok()) { LOG(error, "[%d] : Error in %s(%" PRIu64 " - %" PRIu64 "), stopping since I have no idea on what to do.", _id, "visitor", _range.from(), _range.to()); } LOG(debug, "[%d] : Stopped %" PRIu64 " - %" PRIu64, _id, _range.from(), _range.to()); _finished = true; } Session::Session(int sId, const SerialNumRange & r, const Domain::SP & d, std::unique_ptr<Destination> destination) : _destination(std::move(destination)), _domain(d), _range(r), _id(sId), _visitRunning(false), _inSync(false), _finished(false), _startTime() { } Session::~Session() = default; bool Session::send(const Packet & packet) { return _destination->send(_id, _domain->name(), packet); } bool Session::sendDone() { bool retval = _destination->sendDone(_id, _domain->name()); _inSync = true; return retval; } } <commit_msg>Only visit via file.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "session.h" #include "domain.h" #include "domainpart.h" #include <vespa/fastlib/io/bufferedfile.h> #include <cassert> #include <vespa/log/log.h> LOG_SETUP(".transactionlog.session"); namespace search::transactionlog { vespalib::Executor::Task::UP Session::createTask(const Session::SP & session) { return std::make_unique<VisitTask>(session); } Session::VisitTask::VisitTask(const Session::SP & session) : _session(session) { _session->startVisit(); } Session::VisitTask::~VisitTask() = default; void Session::VisitTask::run() { _session->visitOnly(); } bool Session::visit(FastOS_FileInterface & file, DomainPart & dp) { Packet packet(size_t(-1)); bool more = dp.visit(file, _range, packet); if ( ! packet.getHandle().empty()) { send(packet); } return more; } void Session::visit() { LOG(debug, "[%d] : Visiting %" PRIu64 " - %" PRIu64, _id, _range.from(), _range.to()); for (DomainPart::SP dpSafe = _domain->findPart(_range.from()); dpSafe.get() && (_range.from() < _range.to()) && (dpSafe.get()->range().from() <= _range.to()); dpSafe = _domain->findPart(_range.from())) { // Must use findPart and iterate until no candidate parts found. DomainPart * dp(dpSafe.get()); LOG(debug, "[%d] : Visiting the interval %" PRIu64 " - %" PRIu64 " in domain part [%" PRIu64 ", %" PRIu64 "]", _id, _range.from(), _range.to(), dp->range().from(), dp->range().to()); Fast_BufferedFile file; file.EnableDirectIO(); for(bool more(true); ok() && more && (_range.from() < _range.to()); ) { more = visit(file, *dp); } // Nothing more in this DomainPart, force switch to next one. if (_range.from() < dp->range().to()) { _range.from(std::min(dp->range().to(), _range.to())); } } LOG(debug, "[%d] : Done visiting, starting subscribe %" PRIu64 " - %" PRIu64, _id, _range.from(), _range.to()); } void Session::startVisit() { assert(!_visitRunning); _visitRunning = true; } void Session::visitOnly() { visit(); sendDone(); finalize(); _visitRunning = false; } bool Session::finished() const { return _finished || ! _destination->connected(); } void Session::finalize() { if (!ok()) { LOG(error, "[%d] : Error in %s(%" PRIu64 " - %" PRIu64 "), stopping since I have no idea on what to do.", _id, "visitor", _range.from(), _range.to()); } LOG(debug, "[%d] : Stopped %" PRIu64 " - %" PRIu64, _id, _range.from(), _range.to()); _finished = true; } Session::Session(int sId, const SerialNumRange & r, const Domain::SP & d, std::unique_ptr<Destination> destination) : _destination(std::move(destination)), _domain(d), _range(r), _id(sId), _visitRunning(false), _inSync(false), _finished(false), _startTime() { } Session::~Session() = default; bool Session::send(const Packet & packet) { return _destination->send(_id, _domain->name(), packet); } bool Session::sendDone() { bool retval = _destination->sendDone(_id, _domain->name()); _inSync = true; return retval; } } <|endoftext|>
<commit_before>// xiva (acronym for HTTP Extended EVent Automata) is a simple HTTP server. // Copyright (C) 2009 Yandex <[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. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. #ifndef XIVA_DETAILS_FUNCTORS_HPP_INCLUDED #define XIVA_DETAILS_FUNCTORS_HPP_INCLUDED #include <functional> #include <boost/type_traits.hpp> #include <boost/static_assert.hpp> #include "details/char_traits.hpp" namespace xiva { namespace details { template <typename Pred, typename T> struct unary_predicate : public std::unary_function<T, bool> { bool operator () (T var) const; }; template <typename Pred, typename T> struct binary_predicate : public std::binary_function<T const&, T const&, bool> { bool operator () (T const &var, T const &target) const; }; template <typename Char> struct is_space : public unary_predicate<is_space<Char>, Char> { static bool check(Char value); }; template <typename Char> struct is_blank : public unary_predicate<is_blank<Char>, Char> { static bool check(Char value); }; template <typename Char> struct is_line_end : public unary_predicate<is_line_end<Char>, Char> { static bool check(Char value); }; template <typename Char> struct is_not_line_end : public unary_predicate<is_not_line_end<Char>, Char> { static bool check(Char value); }; template <typename Range> struct ci_less : public binary_predicate<ci_less<Range>, Range> { static bool check(Range const &var, Range const &target); }; template <typename Range> struct ci_equal : public binary_predicate<ci_equal<Range>, Range> { static bool check(Range const &var, Range const &target); }; template <> struct ci_less<char> : public std::binary_function<char, char, bool> { bool operator () (char var, char target) const; }; template <> struct ci_equal<char> : public std::binary_function<char, char, bool> { bool operator () (char var, char target) const; }; template <typename R1, typename R2> inline bool is_ci_less(R1 const &var, R2 const &target) { BOOST_STATIC_ASSERT((boost::is_same<typename R1::value_type, typename R2::value_type>::value)); return std::lexicographical_compare(var.begin(), var.end(), target.begin(), target.end(), ci_less<typename R1::value_type>()); } template <typename R1, typename R2> inline bool is_ci_equal(R1 const &var, R2 const &target) { //BOOST_STATIC_ASSERT((boost::is_same<typename R1::value_type, typename R2::value_type>::value)); BOOST_STATIC_ASSERT((sizeof(typename R1::value_type) == sizeof(typename R2::value_type))); if (var.size() == target.size()) { return std::equal(var.begin(), var.end(), target.begin(), ci_equal<typename R1::value_type>()); } return false; } template <typename Pred, typename T> inline bool unary_predicate<Pred, T>::operator () (T value) const { return Pred::check(value); } template <typename Pred, typename T> inline bool binary_predicate<Pred, T>::operator () (T const &var, T const &target) const { return Pred::check(var, target); } template <typename Char> inline bool is_space<Char>::check(Char value) { return char_traits<Char>::is_space(value); } template <typename Char> inline bool is_blank<Char>::check(Char value) { return char_traits<Char>::is_blank(value); } template <typename Char> inline bool is_line_end<Char>::check(Char value) { return (static_cast<Char>('\n') == value || static_cast<Char>('\r') == value); } template <typename Char> inline bool is_not_line_end<Char>::check(Char value) { return !is_line_end<Char>::check(value); } template <typename Range> inline bool ci_less<Range>::check(Range const &var, Range const &target) { return is_ci_less(var, target); } template <typename Range> inline bool ci_equal<Range>::check(Range const &var, Range const &target) { return is_ci_equal(var, target); } inline bool ci_less<char>::operator () (char var, char target) const { return char_traits<char>::to_lower(var) < char_traits<char>::to_lower(target); } inline bool ci_equal<char>::operator () (char var, char target) const { return char_traits<char>::to_lower(var) == char_traits<char>::to_lower(target); } }} // namespaces #endif // XIVA_DETAILS_FUNCTORS_HPP_INCLUDED <commit_msg>probably fixed errors<commit_after>// xiva (acronym for HTTP Extended EVent Automata) is a simple HTTP server. // Copyright (C) 2009 Yandex <[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. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. #ifndef XIVA_DETAILS_FUNCTORS_HPP_INCLUDED #define XIVA_DETAILS_FUNCTORS_HPP_INCLUDED #include <functional> #include <boost/type_traits.hpp> #include <boost/static_assert.hpp> #include "details/char_traits.hpp" namespace xiva { namespace details { template <typename Pred, typename T> struct unary_predicate : public std::unary_function<T, bool> { bool operator () (T var) const; }; template <typename Pred, typename T> struct binary_predicate : public std::binary_function<T const&, T const&, bool> { bool operator () (T const &var, T const &target) const; }; template <typename Char> struct is_space : public unary_predicate<is_space<Char>, Char> { static bool check(Char value); }; template <typename Char> struct is_blank : public unary_predicate<is_blank<Char>, Char> { static bool check(Char value); }; template <typename Char> struct is_line_end : public unary_predicate<is_line_end<Char>, Char> { static bool check(Char value); }; template <typename Char> struct is_not_line_end : public unary_predicate<is_not_line_end<Char>, Char> { static bool check(Char value); }; template <typename Range> struct ci_less : public binary_predicate<ci_less<Range>, Range> { static bool check(Range const &var, Range const &target); }; template <typename Range> struct ci_equal : public binary_predicate<ci_equal<Range>, Range> { static bool check(Range const &var, Range const &target); }; template <> struct ci_less<char> : public std::binary_function<char, char, bool> { bool operator () (char var, char target) const; }; template <> struct ci_less<const char> : public std::binary_function<const char, const char, bool> { bool operator () (const char var, const char target) const; }; template <> struct ci_equal<char> : public std::binary_function<char, char, bool> { bool operator () (char var, char target) const; }; template <> struct ci_equal<const char> : public std::binary_function<const char, const char, bool> { bool operator () (const char var, const char target) const; }; template <typename R1, typename R2> inline bool is_ci_less(R1 const &var, R2 const &target) { BOOST_STATIC_ASSERT((boost::is_same<typename R1::value_type, typename R2::value_type>::value)); return std::lexicographical_compare(var.begin(), var.end(), target.begin(), target.end(), ci_less<typename R1::value_type>()); } template <typename R1, typename R2> inline bool is_ci_equal(R1 const &var, R2 const &target) { //BOOST_STATIC_ASSERT((boost::is_same<typename R1::value_type, typename R2::value_type>::value)); BOOST_STATIC_ASSERT((sizeof(typename R1::value_type) == sizeof(typename R2::value_type))); if (var.size() == target.size()) { return std::equal(var.begin(), var.end(), target.begin(), ci_equal<typename R1::value_type>()); } return false; } template <typename Pred, typename T> inline bool unary_predicate<Pred, T>::operator () (T value) const { return Pred::check(value); } template <typename Pred, typename T> inline bool binary_predicate<Pred, T>::operator () (T const &var, T const &target) const { return Pred::check(var, target); } template <typename Char> inline bool is_space<Char>::check(Char value) { return char_traits<Char>::is_space(value); } template <typename Char> inline bool is_blank<Char>::check(Char value) { return char_traits<Char>::is_blank(value); } template <typename Char> inline bool is_line_end<Char>::check(Char value) { return (static_cast<Char>('\n') == value || static_cast<Char>('\r') == value); } template <typename Char> inline bool is_not_line_end<Char>::check(Char value) { return !is_line_end<Char>::check(value); } template <typename Range> inline bool ci_less<Range>::check(Range const &var, Range const &target) { return is_ci_less(var, target); } template <typename Range> inline bool ci_equal<Range>::check(Range const &var, Range const &target) { return is_ci_equal(var, target); } inline bool ci_less<char>::operator () (char var, char target) const { return char_traits<char>::to_lower(var) < char_traits<char>::to_lower(target); } inline bool ci_less<const char>::operator () (const char var, const char target) const { return char_traits<const char>::to_lower(var) < char_traits<const char>::to_lower(target); } inline bool ci_equal<char>::operator () (char var, char target) const { return char_traits<char>::to_lower(var) == char_traits<char>::to_lower(target); } inline bool ci_equal<const char>::operator () (const char var, const char target) const { return char_traits<const char>::to_lower(var) == char_traits<const char>::to_lower(target); } }} // namespaces #endif // XIVA_DETAILS_FUNCTORS_HPP_INCLUDED <|endoftext|>
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld 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. */ #ifndef FLUSSPFERD_CLASS_HPP #define FLUSSPFERD_CLASS_HPP #include "native_function_base.hpp" #include "create.hpp" #include "init.hpp" #include "local_root_scope.hpp" #include <boost/mpl/size_t.hpp> #include <boost/ref.hpp> namespace flusspferd { namespace detail { template<typename T> struct class_constructor : native_function_base { class_constructor(unsigned arity, char const *name) : native_function_base(arity, name) {} void call(call_context &x) { x.result = create_native_object<T>( x.function.get_property("prototype").to_object(), boost::ref(x)); } }; } struct class_info { typedef boost::mpl::size_t<0> constructor_arity; static void augment_constructor(object const &) { } static object create_prototype() { return create_object(); } }; template<typename T> object load_class(object container = global()) { std::size_t const arity = T::class_info::constructor_arity::value; char const *name = T::class_info::constructor_name(); local_root_scope scope; context ctx = get_current_context(); value previous = container.get_property(name); if (previous.is_object()) return previous.get_object(); function constructor( create_native_function<detail::class_constructor<T> >(arity, name)); ctx.add_constructor<T>(constructor); object prototype = T::class_info::create_prototype(); ctx.add_prototype<T>(prototype); constructor.define_property( "prototype", prototype, object::dont_enumerate); T::class_info::augment_constructor(object(constructor)); container.define_property( name, constructor, object::dont_enumerate); return constructor; } template<typename T> bool load_internal_class() { local_root_scope scope; context ctx = get_current_context(); object proto = ctx.get_prototype<T>(); if (proto.is_valid()) return false; proto = T::class_info::create_prototype(); ctx.add_prototype<T>(proto); return true; } } #endif <commit_msg>Core: replace load_internal_class<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld 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. */ #ifndef FLUSSPFERD_CLASS_HPP #define FLUSSPFERD_CLASS_HPP #include "native_function_base.hpp" #include "create.hpp" #include "init.hpp" #include "local_root_scope.hpp" #include <boost/mpl/has_xxx.hpp> #include <boost/mpl/or.hpp> #include <boost/mpl/not.hpp> #include <boost/mpl/size_t.hpp> #include <boost/utility/enable_if.hpp> #include <boost/ref.hpp> namespace flusspferd { namespace detail { BOOST_MPL_HAS_XXX_TRAIT_DEF(constructible) template<typename T> struct get_constructible { typedef typename T::constructible type; }; template<typename T> struct is_constructible : boost::mpl::or_< boost::mpl::not_<has_constructible<T> >, get_constructible<T> >::type {}; template<typename T> struct class_constructor : native_function_base { class_constructor(unsigned arity, char const *name) : native_function_base(arity, name) {} void call(call_context &x) { x.result = create_native_object<T>( x.function.get_property("prototype").to_object(), boost::ref(x)); } }; template<typename T> object load_class(object &container, char const *name) { context ctx = get_current_context(); object constructor(ctx.get_constructor<T>()); object prototype = T::class_info::create_prototype(); ctx.add_prototype<T>(prototype); constructor.define_property( "prototype", prototype, object::dont_enumerate); T::class_info::augment_constructor(object(constructor)); container.define_property(name, constructor, object::dont_enumerate); return constructor; } } struct class_info { typedef boost::mpl::size_t<0> constructor_arity; static void augment_constructor(object const &) {} static object create_prototype() { return create_object(); } }; template<typename T> object load_class( object container = global(), typename boost::enable_if< detail::is_constructible<typename T::class_info> >::type * = 0) { std::size_t const arity = T::class_info::constructor_arity::value; char const *name = T::class_info::constructor_name(); local_root_scope scope; context ctx = get_current_context(); value previous = container.get_property(name); if (previous.is_object()) return previous.get_object(); if (!ctx.get_constructor<T>().is_valid()) ctx.add_constructor<T>( create_native_function<detail::class_constructor<T> >(arity, name)); return detail::load_class<T>(container, name); } template<typename T> bool load_class( object container = global(), typename boost::enable_if< boost::mpl::not_<detail::is_constructible<typename T::class_info> > >::type * = 0) { char const *name = T::class_info::constructor_name(); local_root_scope scope; context ctx = get_current_context(); value previous = container.get_property(name); if (previous.is_object()) return previous.get_object(); if (!ctx.get_constructor<T>().is_valid()) ctx.add_constructor<T>(create_object()); return detail::load_class<T>(container, name); } } #endif <|endoftext|>
<commit_before>/* The IF Contextual Media Group Kernel Version 3 Source Code Written By Jeff Koftinoff <[email protected]> Copyright (c) 1995-2005 By Contextual Media Group, Inc. http://www.contextualmediagroup.com/ ALL RIGHTS RESERVED. */ #ifndef IFCMG_DB_NEEDLES_HPP #define IFCMG_DB_NEEDLES_HPP #include "ifcmg_world.hpp" #include "ifcmg_string.hpp" #include "ifcmg_db_util.hpp" namespace ifcmg { class db_needles_row_t { public: db_needles_row_t() : m_id(-1) { } db_needles_row_t( db_needles_row_t const &o ) : m_id( o.m_id ) { } db_needles_row_t( string_t const &line ) { } ~db_needles_row_t() { } db_needles_row_t & operator = ( db_needles_row_t const &o ) { return *this; } int64_t m_id; char m_needle[128]; int64_t m_section; int64_t m_category1; int64_t m_category2; int64_t m_category3; int64_t m_category4; int32_t m_score; int32_t m_autogen; }; typedef std::vector< db_needles_row_t > db_needles_table_t; void load( db_needles_table_t &t, filename_t file ); } #endif <commit_msg>more database needles implementation.<commit_after>/* The IF Contextual Media Group Kernel Version 3 Source Code Written By Jeff Koftinoff <[email protected]> Copyright (c) 1995-2005 By Contextual Media Group, Inc. http://www.contextualmediagroup.com/ ALL RIGHTS RESERVED. */ #ifndef IFCMG_DB_NEEDLES_HPP #define IFCMG_DB_NEEDLES_HPP #include "ifcmg_world.hpp" #include "ifcmg_string.hpp" #include "ifcmg_db_util.hpp" namespace ifcmg { class db_needles_row_t { public: db_needles_row_t() : m_id(-1) { } db_needles_row_t( db_needles_row_t const &o ) : m_id( o.m_id ) { } db_needles_row_t( string_t const &line ) { } ~db_needles_row_t() { } db_needles_row_t & operator = ( db_needles_row_t const &o ) { m_id = o.m_id; m_needle = o.m_needle; m_section = o.m_section; m_category1 = o.m_category1; m_category2 = o.m_category2; m_category3 = o.m_category3; m_category4 = o.m_category4; m_score = o.m_score; m_autogen = o.m_autogen; return *this; } int64_t m_id; std::string m_needle; int64_t m_section; int64_t m_category1; int64_t m_category2; int64_t m_category3; int64_t m_category4; int32_t m_score; int32_t m_autogen; }; class db_needles_table_t { public: }; void load( db_needles_table_t &t, filename_t file ); } #endif <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkProgrammableSource.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkProgrammableSource.h" #include "vtkPolyData.h" #include "vtkStructuredGrid.h" #include "vtkStructuredPoints.h" #include "vtkUnstructuredGrid.h" #include "vtkRectilinearGrid.h" // Construct programmable filter with empty execute method. vtkProgrammableSource::vtkProgrammableSource() { this->ExecuteMethod = NULL; this->ExecuteMethodArg = NULL; this->PolyData = vtkPolyData::New(); this->PolyData->SetSource(this); this->StructuredPoints = vtkStructuredPoints::New(); this->StructuredPoints->SetSource(this); this->StructuredGrid = vtkStructuredGrid::New(); this->StructuredGrid->SetSource(this); this->UnstructuredGrid = vtkUnstructuredGrid::New(); this->UnstructuredGrid->SetSource(this); this->RectilinearGrid = vtkRectilinearGrid::New(); this->RectilinearGrid->SetSource(this); //This is done because filter superclass assumes output is defined. this->Output = this->PolyData; } vtkProgrammableSource::~vtkProgrammableSource() { this->StructuredPoints->Delete(); this->StructuredGrid->Delete(); this->UnstructuredGrid->Delete(); this->RectilinearGrid->Delete(); this->PolyData->Delete(); // Output should only be one of the above. We set it to NULL // so that we don't free it twice this->Output = NULL; // delete the current arg if there is one and a delete meth if ((this->ExecuteMethodArg)&&(this->ExecuteMethodArgDelete)) { (*this->ExecuteMethodArgDelete)(this->ExecuteMethodArg); } } // Specify the function to use to generate the source data. Note // that the function takes a single (void *) argument. void vtkProgrammableSource::SetExecuteMethod(void (*f)(void *), void *arg) { if ( f != this->ExecuteMethod || arg != this->ExecuteMethodArg ) { // delete the current arg if there is one and a delete meth if ((this->ExecuteMethodArg)&&(this->ExecuteMethodArgDelete)) { (*this->ExecuteMethodArgDelete)(this->ExecuteMethodArg); } this->ExecuteMethod = f; this->ExecuteMethodArg = arg; this->Modified(); } } // Set the arg delete method. This is used to free user memory. void vtkProgrammableSource::SetExecuteMethodArgDelete(void (*f)(void *)) { if ( f != this->ExecuteMethodArgDelete) { this->ExecuteMethodArgDelete = f; this->Modified(); } } // Get the output as a concrete type. This method is typically used by the // writer of the source function to get the output as a particular type (i.e., // it essentially does type casting). It is the users responsibility to know // the correct type of the output data. vtkPolyData *vtkProgrammableSource::GetPolyDataOutput() { return this->PolyData; } // Get the output as a concrete type. vtkStructuredPoints *vtkProgrammableSource::GetStructuredPointsOutput() { return this->StructuredPoints; } // Get the output as a concrete type. vtkStructuredGrid *vtkProgrammableSource::GetStructuredGridOutput() { return this->StructuredGrid; } // Get the output as a concrete type. vtkUnstructuredGrid *vtkProgrammableSource::GetUnstructuredGridOutput() { return this->UnstructuredGrid; } // Get the output as a concrete type. vtkRectilinearGrid *vtkProgrammableSource::GetRectilinearGridOutput() { return this->RectilinearGrid; } void vtkProgrammableSource::Execute() { vtkDebugMacro(<<"Executing programmable filter"); // Now invoke the procedure, if specified. if ( this->ExecuteMethod != NULL ) { (*this->ExecuteMethod)(this->ExecuteMethodArg); } } void vtkProgrammableSource::PrintSelf(ostream& os, vtkIndent indent) { vtkSource::PrintSelf(os,indent); os << indent << "Execute Time: " <<this->ExecuteTime.GetMTime() << "\n"; } <commit_msg>ENH: uninitialized ivar.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkProgrammableSource.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkProgrammableSource.h" #include "vtkPolyData.h" #include "vtkStructuredGrid.h" #include "vtkStructuredPoints.h" #include "vtkUnstructuredGrid.h" #include "vtkRectilinearGrid.h" // Construct programmable filter with empty execute method. vtkProgrammableSource::vtkProgrammableSource() { this->ExecuteMethod = NULL; this->ExecuteMethodArg = NULL; this->ExecuteMethodArgDelete = NULL; this->PolyData = vtkPolyData::New(); this->PolyData->SetSource(this); this->StructuredPoints = vtkStructuredPoints::New(); this->StructuredPoints->SetSource(this); this->StructuredGrid = vtkStructuredGrid::New(); this->StructuredGrid->SetSource(this); this->UnstructuredGrid = vtkUnstructuredGrid::New(); this->UnstructuredGrid->SetSource(this); this->RectilinearGrid = vtkRectilinearGrid::New(); this->RectilinearGrid->SetSource(this); //This is done because filter superclass assumes output is defined. this->Output = this->PolyData; } vtkProgrammableSource::~vtkProgrammableSource() { this->StructuredPoints->Delete(); this->StructuredGrid->Delete(); this->UnstructuredGrid->Delete(); this->RectilinearGrid->Delete(); this->PolyData->Delete(); // Output should only be one of the above. We set it to NULL // so that we don't free it twice this->Output = NULL; // delete the current arg if there is one and a delete meth if ((this->ExecuteMethodArg)&&(this->ExecuteMethodArgDelete)) { (*this->ExecuteMethodArgDelete)(this->ExecuteMethodArg); } } // Specify the function to use to generate the source data. Note // that the function takes a single (void *) argument. void vtkProgrammableSource::SetExecuteMethod(void (*f)(void *), void *arg) { if ( f != this->ExecuteMethod || arg != this->ExecuteMethodArg ) { // delete the current arg if there is one and a delete meth if ((this->ExecuteMethodArg)&&(this->ExecuteMethodArgDelete)) { (*this->ExecuteMethodArgDelete)(this->ExecuteMethodArg); } this->ExecuteMethod = f; this->ExecuteMethodArg = arg; this->Modified(); } } // Set the arg delete method. This is used to free user memory. void vtkProgrammableSource::SetExecuteMethodArgDelete(void (*f)(void *)) { if ( f != this->ExecuteMethodArgDelete) { this->ExecuteMethodArgDelete = f; this->Modified(); } } // Get the output as a concrete type. This method is typically used by the // writer of the source function to get the output as a particular type (i.e., // it essentially does type casting). It is the users responsibility to know // the correct type of the output data. vtkPolyData *vtkProgrammableSource::GetPolyDataOutput() { return this->PolyData; } // Get the output as a concrete type. vtkStructuredPoints *vtkProgrammableSource::GetStructuredPointsOutput() { return this->StructuredPoints; } // Get the output as a concrete type. vtkStructuredGrid *vtkProgrammableSource::GetStructuredGridOutput() { return this->StructuredGrid; } // Get the output as a concrete type. vtkUnstructuredGrid *vtkProgrammableSource::GetUnstructuredGridOutput() { return this->UnstructuredGrid; } // Get the output as a concrete type. vtkRectilinearGrid *vtkProgrammableSource::GetRectilinearGridOutput() { return this->RectilinearGrid; } void vtkProgrammableSource::Execute() { vtkDebugMacro(<<"Executing programmable filter"); // Now invoke the procedure, if specified. if ( this->ExecuteMethod != NULL ) { (*this->ExecuteMethod)(this->ExecuteMethodArg); } } void vtkProgrammableSource::PrintSelf(ostream& os, vtkIndent indent) { vtkSource::PrintSelf(os,indent); os << indent << "Execute Time: " <<this->ExecuteTime.GetMTime() << "\n"; } <|endoftext|>
<commit_before>/* Copyright (c) 2003, 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_DEBUG_HPP_INCLUDED #define TORRENT_DEBUG_HPP_INCLUDED #include <string> #include <fstream> #include <iostream> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/lexical_cast.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/filesystem/convenience.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif namespace libtorrent { // DEBUG API namespace fs = boost::filesystem; struct logger { logger(fs::path const& filename, int instance, bool append = true) { fs::path dir(fs::complete("libtorrent_logs" + boost::lexical_cast<std::string>(instance))); if (!fs::exists(dir)) fs::create_directories(dir); m_file.open((dir / filename).string().c_str(), std::ios_base::out | (append ? std::ios_base::app : std::ios_base::out)); *this << "\n\n\n*** starting log ***\n"; } template <class T> logger& operator<<(T const& v) { m_file << v; m_file.flush(); return *this; } std::ofstream m_file; }; } #endif // TORRENT_DEBUG_HPP_INCLUDED <commit_msg>fixes issue whith failure to create logs causes libtorrent to quit, fixes ticket #168<commit_after>/* Copyright (c) 2003, 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_DEBUG_HPP_INCLUDED #define TORRENT_DEBUG_HPP_INCLUDED #include <string> #include <fstream> #include <iostream> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/lexical_cast.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/filesystem/convenience.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif namespace libtorrent { // DEBUG API namespace fs = boost::filesystem; struct logger { logger(fs::path const& filename, int instance, bool append = true) { try { fs::path dir(fs::complete("libtorrent_logs" + boost::lexical_cast<std::string>(instance))); if (!fs::exists(dir)) fs::create_directories(dir); m_file.open((dir / filename).string().c_str(), std::ios_base::out | (append ? std::ios_base::app : std::ios_base::out)); *this << "\n\n\n*** starting log ***\n"; } catch (std::exception& e) { std::cerr << "failed to create log '" << filename << "': " << e.what() << std::endl; } } template <class T> logger& operator<<(T const& v) { m_file << v; m_file.flush(); return *this; } std::ofstream m_file; }; } #endif // TORRENT_DEBUG_HPP_INCLUDED <|endoftext|>
<commit_before>#ifndef LIB_MART_COMMON_GUARD_NW_UNIX_H #define LIB_MART_COMMON_GUARD_NW_UNIX_H /** * unix.h (mart-netlib) * * Copyright (C) 2019: Michael Balszun <[email protected]> * * This software may be modified and distributed under the terms * of the MIT license. See either the LICENSE file in the library's root * directory or http://opensource.org/licenses/MIT for details. * * @author: Michael Balszun <[email protected]> * @brief: This file provides a simple unix doamin socket implementation * */ #include "port_layer.hpp" #include <im_str/im_str.hpp> #include <mart-common/utils.h> #include <filesystem> #include <string_view> #include "detail/socket_base.hpp" namespace mart::nw { // classes related to the unix sockets protocol in general namespace un { class endpoint { public: using abi_endpoint_type = mart::nw::socks::port_layer::SockaddrUn; static constexpr socks::Domain domain = socks::Domain::Local; constexpr endpoint() noexcept = default; endpoint( mba::im_zstr path ) noexcept : _addr( std::move( path ) ) { } explicit endpoint( std::string_view path ) noexcept : _addr( mba::im_zstr(path) ) { } explicit endpoint( const std::filesystem::path& path ) noexcept // TODO use "native()" on platforms that use u8 encoding natively : _addr( std::string_view( path.string() ) ) { } explicit endpoint( const abi_endpoint_type& path ) noexcept : endpoint( std::string_view( path.path() ) ) { } mba::im_str asString() const noexcept { return _addr; } mba::im_str toString() const noexcept { return _addr; } mba::im_str toStringEx() const noexcept { return _addr; } bool valid() const noexcept { return _addr.data() != nullptr; } abi_endpoint_type toSockAddrUn() const noexcept { return abi_endpoint_type( _addr.data(), _addr.size() ); } // for use in generic contexts abi_endpoint_type toSockAddr() const noexcept { return toSockAddrUn(); } friend bool operator==( const endpoint& l, const endpoint& r ) noexcept { return l._addr == r._addr; } friend bool operator!=( const endpoint& l, const endpoint& r ) noexcept { return l._addr != r._addr; } friend bool operator<( const endpoint& l, const endpoint& r ) noexcept { return l._addr < r._addr; } private: mba::im_str _addr{}; }; } // namespace un } // namespace mart::nw namespace mart::nw::socks::detail { extern template class DgramSocket<mart::nw::un::endpoint>; } namespace mart::nw { // classes related to the unix sockets protocol in general namespace un { using Socket = mart::nw::socks::detail::DgramSocket<endpoint>; } } // namespace mart::nw #endif<commit_msg>[netlib] Make use of std::filesystem optional<commit_after>#ifndef LIB_MART_COMMON_GUARD_NW_UNIX_H #define LIB_MART_COMMON_GUARD_NW_UNIX_H /** * unix.h (mart-netlib) * * Copyright (C) 2019: Michael Balszun <[email protected]> * * This software may be modified and distributed under the terms * of the MIT license. See either the LICENSE file in the library's root * directory or http://opensource.org/licenses/MIT for details. * * @author: Michael Balszun <[email protected]> * @brief: This file provides a simple unix doamin socket implementation * */ #include "port_layer.hpp" #include <im_str/im_str.hpp> #include <mart-common/utils.h> #if __has_include(<filesystem>) #include <filesystem> #endif #include <string_view> #include "detail/socket_base.hpp" namespace mart::nw { // classes related to the unix sockets protocol in general namespace un { class endpoint { public: using abi_endpoint_type = mart::nw::socks::port_layer::SockaddrUn; static constexpr socks::Domain domain = socks::Domain::Local; constexpr endpoint() noexcept = default; endpoint( mba::im_zstr path ) noexcept : _addr( std::move( path ) ) { } explicit endpoint( std::string_view path ) noexcept : _addr( mba::im_zstr(path) ) { } #ifdef __cpp_lib_filesystem explicit endpoint( const std::filesystem::path& path ) noexcept // TODO use "native()" on platforms that use u8 encoding natively : _addr( std::string_view( path.string() ) ) { } #endif explicit endpoint( const abi_endpoint_type& path ) noexcept : endpoint( std::string_view( path.path() ) ) { } mba::im_str asString() const noexcept { return _addr; } mba::im_str toString() const noexcept { return _addr; } mba::im_str toStringEx() const noexcept { return _addr; } bool valid() const noexcept { return _addr.data() != nullptr; } abi_endpoint_type toSockAddrUn() const noexcept { return abi_endpoint_type( _addr.data(), _addr.size() ); } // for use in generic contexts abi_endpoint_type toSockAddr() const noexcept { return toSockAddrUn(); } friend bool operator==( const endpoint& l, const endpoint& r ) noexcept { return l._addr == r._addr; } friend bool operator!=( const endpoint& l, const endpoint& r ) noexcept { return l._addr != r._addr; } friend bool operator<( const endpoint& l, const endpoint& r ) noexcept { return l._addr < r._addr; } private: mba::im_str _addr{}; }; } // namespace un } // namespace mart::nw namespace mart::nw::socks::detail { extern template class DgramSocket<mart::nw::un::endpoint>; } namespace mart::nw { // classes related to the unix sockets protocol in general namespace un { using Socket = mart::nw::socks::detail::DgramSocket<endpoint>; } } // namespace mart::nw #endif<|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <[email protected]> //------------------------------------------------------------------------------ #include "cling/MetaProcessor/MetaProcessor.h" #include "InputValidator.h" #include "cling/Interpreter/Interpreter.h" #include "clang/Basic/TargetInfo.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/Preprocessor.h" #include "llvm/Support/Path.h" #include <cstdio> using namespace clang; namespace cling { MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) { m_InputValidator.reset(new InputValidator()); } MetaProcessor::~MetaProcessor() {} int MetaProcessor::process(const char* input_text, Value* result /*=0*/) { if (!input_text) { // null pointer, nothing to do. return 0; } if (!input_text[0]) { // empty string, nothing to do. return m_InputValidator->getExpectedIndent(); } std::string input_line(input_text); if (input_line == "\n") { // just a blank line, nothing to do. return 0; } // Check for and handle any '.' commands. bool was_meta = false; if ((input_line[0] == '.') && (input_line.size() > 1)) { was_meta = ProcessMeta(input_line, result); } if (was_meta) { return 0; } // Check if the current statement is now complete. If not, return to // prompt for more. if (m_InputValidator->Validate(input_line, m_Interp.getCI()->getLangOpts()) == InputValidator::kIncomplete) { return m_InputValidator->getExpectedIndent(); } // We have a complete statement, compile and execute it. std::string input = m_InputValidator->TakeInput(); m_InputValidator->Reset(); m_Interp.processLine(input, m_Options.RawInput, result); return 0; } MetaProcessorOpts& MetaProcessor::getMetaProcessorOpts() { // Take interpreter's state m_Options.PrintingAST = m_Interp.isPrintingAST(); return m_Options; } bool MetaProcessor::ProcessMeta(const std::string& input_line, Value* result){ llvm::MemoryBuffer* MB = llvm::MemoryBuffer::getMemBuffer(input_line); const LangOptions& LO = m_Interp.getCI()->getLangOpts(); Lexer RawLexer(SourceLocation(), LO, MB->getBufferStart(), MB->getBufferStart(), MB->getBufferEnd()); Token Tok; RawLexer.LexFromRawLexer(Tok); if (Tok.isNot(tok::period)) return false; // Read the command RawLexer.LexFromRawLexer(Tok); if (!Tok.isAnyIdentifier() && Tok.isNot(tok::at)) return false; const std::string Command = GetRawTokenName(Tok); std::string Param; // .q //Quits if (Command == "q") { m_Options.Quitting = true; return true; } // .L <filename> // Load code fragment. else if (Command == "L") { // Check for params RawLexer.LexFromRawLexer(Tok); if (!Tok.isAnyIdentifier()) return false; Param = GetRawTokenName(Tok); bool success = m_Interp.loadFile(Param); if (!success) { llvm::errs() << "Load file failed.\n"; } return true; } // .(x|X) <filename> // Execute function from file, function name is // // filename without extension. else if ((Command == "x") || (Command == "X")) { // TODO: add extensive checks the folder paths and filenames //RawLexer->LexFromRawLexer(Tok); //if (!Tok.isAnyIdentifier()) // return false; const char* CurPtr = RawLexer.getBufferLocation();; Token TmpTok; RawLexer.getAndAdvanceChar(CurPtr, TmpTok); llvm::StringRef Param(CurPtr, MB->getBufferSize() - (CurPtr - MB->getBufferStart())); llvm::sys::Path path(Param); if (!path.isValid()) return false; bool success = executeFile(path.c_str(), result); if (!success) { llvm::errs()<< "Execute file failed.\n"; } return true; } // .printAST [0|1] // Toggle the printing of the AST or if 1 or 0 is given // // enable or disable it. else if (Command == "printAST") { // Check for params RawLexer.LexFromRawLexer(Tok); if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof)) return false; if (Tok.is(tok::eof)) { // toggle: bool print = !m_Interp.isPrintingAST(); m_Interp.enablePrintAST(print); llvm::errs()<< (print?"P":"Not p") << "rinting AST\n"; } else { Param = GetRawTokenName(Tok); if (Param == "0") m_Interp.enablePrintAST(false); else m_Interp.enablePrintAST(true); } m_Options.PrintingAST = m_Interp.isPrintingAST(); return true; } // .rawInput [0|1] // Toggle the raw input or if 1 or 0 is given enable // // or disable it. else if (Command == "rawInput") { // Check for params RawLexer.LexFromRawLexer(Tok); if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof)) return false; if (Tok.is(tok::eof)) { // toggle: m_Options.RawInput = !m_Options.RawInput; llvm::errs() << (m_Options.RawInput?"U":"Not u") << "sing raw input\n"; } else { Param = GetRawTokenName(Tok); if (Param == "0") m_Options.RawInput = false; else m_Options.RawInput = true; } return true; } // // .U <filename> // // Unload code fragment. // //if (cmd_char == 'U') { // llvm::sys::Path path(param); // if (path.isDynamicLibrary()) { // std::cerr << "[i] Failure: cannot unload shared libraries yet!" // << std::endl; // } // bool success = m_Interp.unloadFile(param); // if (!success) { // //fprintf(stderr, "Unload file failed.\n"); // } // return true; //} // // Unrecognized command. // //fprintf(stderr, "Unrecognized command.\n"); else if (Command == "I") { // Check for params RawLexer.LexFromRawLexer(Tok); if (Tok.is(tok::eof)) m_Interp.DumpIncludePath(); else { // TODO: add extensive checks the folder paths and filenames const char* CurPtr = RawLexer.getBufferLocation();; Token TmpTok; RawLexer.getAndAdvanceChar(CurPtr, TmpTok); llvm::StringRef Param(CurPtr, MB->getBufferSize()-(CurPtr-MB->getBufferStart())); llvm::sys::Path path(Param); if (path.isValid()) m_Interp.AddIncludePath(path.c_str()); else return false; } return true; } // Cancel the multiline input that has been requested else if (Command == "@") { m_InputValidator->Reset(); return true; } // Enable/Disable DynamicExprTransformer else if (Command == "dynamicExtensions") { // Check for params RawLexer.LexFromRawLexer(Tok); if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof)) return false; if (Tok.is(tok::eof)) { // toggle: bool dynlookup = !m_Interp.isDynamicLookupEnabled(); m_Interp.enableDynamicLookup(dynlookup); llvm::errs() << (dynlookup?"U":"Not u") <<"sing dynamic extensions\n"; } else { Param = GetRawTokenName(Tok); if (Param == "0") m_Interp.enableDynamicLookup(false); else m_Interp.enableDynamicLookup(true); } return true; } // Print Help else if (Command == "help") { PrintCommandHelp(); return true; } return false; } std::string MetaProcessor::GetRawTokenName(const Token& Tok) { assert(!Tok.needsCleaning() && "Not implemented yet"); switch (Tok.getKind()) { default: return ""; case tok::numeric_constant: return Tok.getLiteralData(); case tok::raw_identifier: return StringRef(Tok.getRawIdentifierData(), Tok.getLength()).str(); case tok::slash: return "/"; } } void MetaProcessor::PrintCommandHelp() { llvm::outs() << "Cling meta commands usage\n"; llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n"; llvm::outs() << "\n"; llvm::outs() << ".q\t\t\t\t - Exit the program\n"; llvm::outs() << ".L <filename>\t\t\t - Load file or library\n"; llvm::outs() << ".(x|X) <filename>[args]\t\t - Same as .L and runs a "; llvm::outs() << "function with signature ret_type filename(args)\n"; llvm::outs() << ".I [path]\t\t\t - Shows the include path. If a path is "; llvm::outs() << "given - adds the path to the list with the include paths\n"; llvm::outs() << ".@ \t\t\t\t - Cancels and ignores the multiline input\n"; llvm::outs() << ".rawInput [0|1]\t\t\t - Toggles the wrapping and printing "; llvm::outs() << "the execution results of the input\n"; llvm::outs() << ".dynamicExtensions [0|1]\t - Toggles the use of the "; llvm::outs() << "dynamic scopes and the late binding\n"; llvm::outs() << ".printAST [0|1]\t\t\t - Toggles the printing of input's "; llvm::outs() << "corresponding AST nodes\n"; llvm::outs() << ".help\t\t\t\t - Shows this information\n"; } // Run a file: .x file[(args)] bool MetaProcessor::executeFile(const std::string& fileWithArgs, Value* result) { // Look for start of parameters: typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair; StringRefPair pairFileArgs = llvm::StringRef(fileWithArgs).split('('); if (pairFileArgs.second.empty()) { pairFileArgs.second = ")"; } StringRefPair pairPathFile = pairFileArgs.first.rsplit('/'); if (pairPathFile.second.empty()) { pairPathFile.second = pairPathFile.first; } StringRefPair pairFuncExt = pairPathFile.second.rsplit('.'); //fprintf(stderr, "funcname: %s\n", pairFuncExt.first.data()); Interpreter::CompilationResult interpRes = m_Interp.processLine(std::string("#include \"") + pairFileArgs.first.str() + std::string("\""), true /*raw*/); if (interpRes != Interpreter::kFailure) { std::string expression = pairFuncExt.first.str() + "(" + pairFileArgs.second.str(); interpRes = m_Interp.processLine(expression, false /*not raw*/, result); } return (interpRes != Interpreter::kFailure); } } // end namespace cling <commit_msg>No need of cstio anymore<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <[email protected]> //------------------------------------------------------------------------------ #include "cling/MetaProcessor/MetaProcessor.h" #include "InputValidator.h" #include "cling/Interpreter/Interpreter.h" #include "clang/Basic/TargetInfo.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/Preprocessor.h" #include "llvm/Support/Path.h" using namespace clang; namespace cling { MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) { m_InputValidator.reset(new InputValidator()); } MetaProcessor::~MetaProcessor() {} int MetaProcessor::process(const char* input_text, Value* result /*=0*/) { if (!input_text) { // null pointer, nothing to do. return 0; } if (!input_text[0]) { // empty string, nothing to do. return m_InputValidator->getExpectedIndent(); } std::string input_line(input_text); if (input_line == "\n") { // just a blank line, nothing to do. return 0; } // Check for and handle any '.' commands. bool was_meta = false; if ((input_line[0] == '.') && (input_line.size() > 1)) { was_meta = ProcessMeta(input_line, result); } if (was_meta) { return 0; } // Check if the current statement is now complete. If not, return to // prompt for more. if (m_InputValidator->Validate(input_line, m_Interp.getCI()->getLangOpts()) == InputValidator::kIncomplete) { return m_InputValidator->getExpectedIndent(); } // We have a complete statement, compile and execute it. std::string input = m_InputValidator->TakeInput(); m_InputValidator->Reset(); m_Interp.processLine(input, m_Options.RawInput, result); return 0; } MetaProcessorOpts& MetaProcessor::getMetaProcessorOpts() { // Take interpreter's state m_Options.PrintingAST = m_Interp.isPrintingAST(); return m_Options; } bool MetaProcessor::ProcessMeta(const std::string& input_line, Value* result){ llvm::MemoryBuffer* MB = llvm::MemoryBuffer::getMemBuffer(input_line); const LangOptions& LO = m_Interp.getCI()->getLangOpts(); Lexer RawLexer(SourceLocation(), LO, MB->getBufferStart(), MB->getBufferStart(), MB->getBufferEnd()); Token Tok; RawLexer.LexFromRawLexer(Tok); if (Tok.isNot(tok::period)) return false; // Read the command RawLexer.LexFromRawLexer(Tok); if (!Tok.isAnyIdentifier() && Tok.isNot(tok::at)) return false; const std::string Command = GetRawTokenName(Tok); std::string Param; // .q //Quits if (Command == "q") { m_Options.Quitting = true; return true; } // .L <filename> // Load code fragment. else if (Command == "L") { // Check for params RawLexer.LexFromRawLexer(Tok); if (!Tok.isAnyIdentifier()) return false; Param = GetRawTokenName(Tok); bool success = m_Interp.loadFile(Param); if (!success) { llvm::errs() << "Load file failed.\n"; } return true; } // .(x|X) <filename> // Execute function from file, function name is // // filename without extension. else if ((Command == "x") || (Command == "X")) { // TODO: add extensive checks the folder paths and filenames //RawLexer->LexFromRawLexer(Tok); //if (!Tok.isAnyIdentifier()) // return false; const char* CurPtr = RawLexer.getBufferLocation();; Token TmpTok; RawLexer.getAndAdvanceChar(CurPtr, TmpTok); llvm::StringRef Param(CurPtr, MB->getBufferSize() - (CurPtr - MB->getBufferStart())); llvm::sys::Path path(Param); if (!path.isValid()) return false; bool success = executeFile(path.c_str(), result); if (!success) { llvm::errs()<< "Execute file failed.\n"; } return true; } // .printAST [0|1] // Toggle the printing of the AST or if 1 or 0 is given // // enable or disable it. else if (Command == "printAST") { // Check for params RawLexer.LexFromRawLexer(Tok); if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof)) return false; if (Tok.is(tok::eof)) { // toggle: bool print = !m_Interp.isPrintingAST(); m_Interp.enablePrintAST(print); llvm::errs()<< (print?"P":"Not p") << "rinting AST\n"; } else { Param = GetRawTokenName(Tok); if (Param == "0") m_Interp.enablePrintAST(false); else m_Interp.enablePrintAST(true); } m_Options.PrintingAST = m_Interp.isPrintingAST(); return true; } // .rawInput [0|1] // Toggle the raw input or if 1 or 0 is given enable // // or disable it. else if (Command == "rawInput") { // Check for params RawLexer.LexFromRawLexer(Tok); if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof)) return false; if (Tok.is(tok::eof)) { // toggle: m_Options.RawInput = !m_Options.RawInput; llvm::errs() << (m_Options.RawInput?"U":"Not u") << "sing raw input\n"; } else { Param = GetRawTokenName(Tok); if (Param == "0") m_Options.RawInput = false; else m_Options.RawInput = true; } return true; } // // .U <filename> // // Unload code fragment. // //if (cmd_char == 'U') { // llvm::sys::Path path(param); // if (path.isDynamicLibrary()) { // std::cerr << "[i] Failure: cannot unload shared libraries yet!" // << std::endl; // } // bool success = m_Interp.unloadFile(param); // if (!success) { // //fprintf(stderr, "Unload file failed.\n"); // } // return true; //} // // Unrecognized command. // //fprintf(stderr, "Unrecognized command.\n"); else if (Command == "I") { // Check for params RawLexer.LexFromRawLexer(Tok); if (Tok.is(tok::eof)) m_Interp.DumpIncludePath(); else { // TODO: add extensive checks the folder paths and filenames const char* CurPtr = RawLexer.getBufferLocation();; Token TmpTok; RawLexer.getAndAdvanceChar(CurPtr, TmpTok); llvm::StringRef Param(CurPtr, MB->getBufferSize()-(CurPtr-MB->getBufferStart())); llvm::sys::Path path(Param); if (path.isValid()) m_Interp.AddIncludePath(path.c_str()); else return false; } return true; } // Cancel the multiline input that has been requested else if (Command == "@") { m_InputValidator->Reset(); return true; } // Enable/Disable DynamicExprTransformer else if (Command == "dynamicExtensions") { // Check for params RawLexer.LexFromRawLexer(Tok); if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof)) return false; if (Tok.is(tok::eof)) { // toggle: bool dynlookup = !m_Interp.isDynamicLookupEnabled(); m_Interp.enableDynamicLookup(dynlookup); llvm::errs() << (dynlookup?"U":"Not u") <<"sing dynamic extensions\n"; } else { Param = GetRawTokenName(Tok); if (Param == "0") m_Interp.enableDynamicLookup(false); else m_Interp.enableDynamicLookup(true); } return true; } // Print Help else if (Command == "help") { PrintCommandHelp(); return true; } return false; } std::string MetaProcessor::GetRawTokenName(const Token& Tok) { assert(!Tok.needsCleaning() && "Not implemented yet"); switch (Tok.getKind()) { default: return ""; case tok::numeric_constant: return Tok.getLiteralData(); case tok::raw_identifier: return StringRef(Tok.getRawIdentifierData(), Tok.getLength()).str(); case tok::slash: return "/"; } } void MetaProcessor::PrintCommandHelp() { llvm::outs() << "Cling meta commands usage\n"; llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n"; llvm::outs() << "\n"; llvm::outs() << ".q\t\t\t\t - Exit the program\n"; llvm::outs() << ".L <filename>\t\t\t - Load file or library\n"; llvm::outs() << ".(x|X) <filename>[args]\t\t - Same as .L and runs a "; llvm::outs() << "function with signature ret_type filename(args)\n"; llvm::outs() << ".I [path]\t\t\t - Shows the include path. If a path is "; llvm::outs() << "given - adds the path to the list with the include paths\n"; llvm::outs() << ".@ \t\t\t\t - Cancels and ignores the multiline input\n"; llvm::outs() << ".rawInput [0|1]\t\t\t - Toggles the wrapping and printing "; llvm::outs() << "the execution results of the input\n"; llvm::outs() << ".dynamicExtensions [0|1]\t - Toggles the use of the "; llvm::outs() << "dynamic scopes and the late binding\n"; llvm::outs() << ".printAST [0|1]\t\t\t - Toggles the printing of input's "; llvm::outs() << "corresponding AST nodes\n"; llvm::outs() << ".help\t\t\t\t - Shows this information\n"; } // Run a file: .x file[(args)] bool MetaProcessor::executeFile(const std::string& fileWithArgs, Value* result) { // Look for start of parameters: typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair; StringRefPair pairFileArgs = llvm::StringRef(fileWithArgs).split('('); if (pairFileArgs.second.empty()) { pairFileArgs.second = ")"; } StringRefPair pairPathFile = pairFileArgs.first.rsplit('/'); if (pairPathFile.second.empty()) { pairPathFile.second = pairPathFile.first; } StringRefPair pairFuncExt = pairPathFile.second.rsplit('.'); //fprintf(stderr, "funcname: %s\n", pairFuncExt.first.data()); Interpreter::CompilationResult interpRes = m_Interp.processLine(std::string("#include \"") + pairFileArgs.first.str() + std::string("\""), true /*raw*/); if (interpRes != Interpreter::kFailure) { std::string expression = pairFuncExt.first.str() + "(" + pairFileArgs.second.str(); interpRes = m_Interp.processLine(expression, false /*not raw*/, result); } return (interpRes != Interpreter::kFailure); } } // end namespace cling <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 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 * *****************************************************************************/ //$Id: image_symbolizer.hpp 39 2005-04-10 20:39:53Z pavlenko $ #ifndef POINT_SYMBOLIZER_HPP #define POINT_SYMBOLIZER_HPP #include <boost/shared_ptr.hpp> #include "graphics.hpp" namespace mapnik { struct MAPNIK_DECL point_symbolizer { point_symbolizer(std::string const& file, std::string const& type, unsigned width,unsigned height); point_symbolizer(point_symbolizer const& rhs); ImageData32 const& get_data() const; private: boost::shared_ptr<ImageData32> symbol_; }; } #endif // POINT_SYMBOLIZER_HPP <commit_msg>replaced tabs with spaces<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 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 * *****************************************************************************/ //$Id: image_symbolizer.hpp 39 2005-04-10 20:39:53Z pavlenko $ #ifndef POINT_SYMBOLIZER_HPP #define POINT_SYMBOLIZER_HPP #include <boost/shared_ptr.hpp> #include "graphics.hpp" namespace mapnik { struct MAPNIK_DECL point_symbolizer { point_symbolizer(std::string const& file, std::string const& type, unsigned width,unsigned height); point_symbolizer(point_symbolizer const& rhs); ImageData32 const& get_data() const; private: boost::shared_ptr<ImageData32> symbol_; }; } #endif // POINT_SYMBOLIZER_HPP <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // This class provides storage for event and track information which // are used for same-event as well as mixed-event analyses in AliAnalysisTaskKPFemto // Author: [email protected] // was: [email protected] (derived and adapted from D. Gangadharan PWGCF/FEMTOSCOPY/Chaoticity/AliChaoticityEventCollection // and J. Salzwedel PWGCF/FEMTOSCOPY/V0LamAnalysis/AliAnalysisV0LamEventCollection) // //////////////////////////////////////////////////////////////////////////////// #include "AliAnalysisKPEventCollection.h" //_____________________________________________________________________________ // Default constructor AliReconstructedFirst::AliReconstructedFirst() : fPt(0), fEta(0), fTheta(0), fPhi(0), fRap(0), fCharge(0), fDCAxy(0), fDCAz(0), isTOFmismatch(kFALSE), isMCptc(kFALSE), fMCcode(0), fPDGcode(0), fMCmumIdx(0), fMCmumPDG(0), fMCgrandmumIdx(0), fMCgrandmumPDG(0), index(0), mcFirstOriginType(kUnassigned), doSkipOver(kFALSE), fEtaS(0), fPhiS(0), isP(0), isaP(0) { // std::fill(fMomentum,fMomentum+3,0.); // std::fill(fMomentumTruth,fMomentumTruth+3,0.); // std::fill(fShiftedGlobalPosition,fShiftedGlobalPosition+3,0.); // std::fill(iptoPV,iptoPV+2,0.); // std::fill(nSigmaFirstTPC,nSigmaFirstTPC+5,0.); // std::fill(nSigmaFirstTOF,nSigmaFirstTOF+5,0.); // copy constructor } //_____________________________________________________________________________ AliReconstructedSecond::AliReconstructedSecond() : sPt(0), sEta(0), sTheta(0), sPhi(0), sRap(0), sCharge(0), sDCAxy(0), sDCAz(0), isTOFmismatch(kFALSE), isMCptc(kFALSE), sMCcode(0), sPDGcode(0), sMCmumIdx(0), sMCmumPDG(0), sMCgrandmumIdx(0), sMCgrandmumPDG(0), index(0), mcSecondOriginType(kUnassigned), doSkipOver(kFALSE), sEtaS(0), sPhiS(0), isP(0), isaP(0) { // std::fill(sMomentum,sMomentum+3,0.); // std::fill(sMomentumTruth,sMomentumTruth+3,0.); // std::fill(sShiftedGlobalPosition,sShiftedGlobalPosition+3,0.); // std::fill(iptoPV,iptoPV+2,0.); // std::fill(nSigmaSecondTPC,nSigmaSecondTPC+5,0.); // std::fill(nSigmaSecondTOF,nSigmaSecondTOF+5,0.); // Default constructor } //_____________________________________________________________________________ AliReconstructedFirst::~AliReconstructedFirst() { } //_____________________________________________________________________________ AliReconstructedSecond::~AliReconstructedSecond() { } //_____________________________________________________________________________ AliAnalysisKPEvent::AliAnalysisKPEvent(): fNumberCandidateFirst(0), fNumberCandidateSecond(0), fReconstructedFirst(0x0), fReconstructedSecond(0x0) { //Default constructor } //_____________________________________________________________________________ AliAnalysisKPEvent::~AliAnalysisKPEvent() { //Destructor if(fReconstructedFirst){ delete fReconstructedFirst; fReconstructedFirst= NULL; } if(fReconstructedSecond){ delete fReconstructedSecond; fReconstructedSecond= NULL; } } //_____________________________________________________________________________ AliAnalysisKPEventCollection::AliAnalysisKPEventCollection() : fEvt(0x0), fifo(0) { } //______________________________________________________________________________ AliAnalysisKPEventCollection::~AliAnalysisKPEventCollection(){ for(Int_t i = 0; i < fifo; i++){ if((fEvt + i)->fReconstructedFirst != NULL){ delete [] (fEvt + i)->fReconstructedFirst; } if((fEvt + i)->fReconstructedSecond != NULL){ delete [] (fEvt + i)->fReconstructedSecond; } } delete [] fEvt;fEvt = NULL; } //_____________________________________________________________________________ AliAnalysisKPEventCollection::AliAnalysisKPEventCollection(Short_t eventBuffSize, Int_t maxFirstMult, Int_t maxSecondMult) : fEvt(0x0), fifo(0) { SetBuffSize(eventBuffSize); fEvt = new AliAnalysisKPEvent[fifo]; //allocate pointer array of AliAnalysisKPEvents for(Int_t ii = 0; ii < fifo; ii++){ //Initialize particle table pointers to NULL (fEvt + ii)->fReconstructedFirst = NULL; (fEvt + ii)->fNumberCandidateFirst = 0; (fEvt + ii)->fReconstructedFirst = new AliReconstructedFirst[maxFirstMult]; (fEvt + ii)->fReconstructedSecond = NULL; (fEvt + ii)->fNumberCandidateSecond = 0; (fEvt + ii)->fReconstructedSecond = new AliReconstructedSecond[maxSecondMult]; } } //_____________________________________________________________________________ void AliAnalysisKPEventCollection::FifoShift() { //Shift elements in FIFO by one and clear last element in FIFO for(unsigned short i=fifo-1 ; i > 0; i--) { for(Int_t j=0; j<(fEvt + i-1)->fNumberCandidateFirst; j++){ (fEvt + i)->fReconstructedFirst[j] = (fEvt + i-1)->fReconstructedFirst[j]; } (fEvt + i)->fNumberCandidateFirst = (fEvt + i-1)->fNumberCandidateFirst; for(Int_t j=0; j<(fEvt + i-1)->fNumberCandidateSecond; j++){ (fEvt + i)->fReconstructedSecond[j] = (fEvt + i-1)->fReconstructedSecond[j]; } (fEvt + i)->fNumberCandidateSecond = (fEvt + i-1)->fNumberCandidateSecond; for(Int_t j=0; j<3; j++){ (fEvt + i)->fPrimaryVertex[j] = (fEvt + i-1)->fPrimaryVertex[j]; } } (fEvt)->fNumberCandidateFirst=0; (fEvt)->fNumberCandidateSecond=0; for(Int_t j=0; j<3; j++) { (fEvt)->fPrimaryVertex[j] = 0.; } } <commit_msg>Additional improvement to the event collection task<commit_after>//////////////////////////////////////////////////////////////////////////////// // // This class provides storage for event and track information which // are used for same-event as well as mixed-event analyses in AliAnalysisTaskKPFemto // Author: [email protected] // was: [email protected] (derived and adapted from D. Gangadharan PWGCF/FEMTOSCOPY/Chaoticity/AliChaoticityEventCollection // and J. Salzwedel PWGCF/FEMTOSCOPY/V0LamAnalysis/AliAnalysisV0LamEventCollection) // //////////////////////////////////////////////////////////////////////////////// #include "AliAnalysisKPEventCollection.h" //_____________________________________________________________________________ // Default constructor AliReconstructedFirst::AliReconstructedFirst() : fPt(0), fEta(0), fTheta(0), fPhi(0), fRap(0), fCharge(0), fDCAxy(0), fDCAz(0), isTOFmismatch(kFALSE), isMCptc(kFALSE), fMCcode(0), fPDGcode(0), fMCmumIdx(0), fMCmumPDG(0), fMCgrandmumIdx(0), fMCgrandmumPDG(0), index(0), mcFirstOriginType(kUnassigned), doSkipOver(kFALSE), fEtaS(0), fPhiS(0), isP(0), isaP(0) { // std::fill(fMomentum,fMomentum+3,0.); // std::fill(fMomentumTruth,fMomentumTruth+3,0.); // std::fill(fShiftedGlobalPosition,fShiftedGlobalPosition+3,0.); // std::fill(iptoPV,iptoPV+2,0.); // std::fill(nSigmaFirstTPC,nSigmaFirstTPC+5,0.); // std::fill(nSigmaFirstTOF,nSigmaFirstTOF+5,0.); // default constructor constructor } //_____________________________________________________________________________ AliReconstructedFirst::AliReconstructedFirst(const AliReconstructedFirst &obj) : fPt(obj.fPt), fEta(obj.fEta), fTheta(obj.fTheta), fPhi(obj.fPhi), fRap(obj.fRap), fCharge(obj.fCharge), fDCAxy(obj.fDCAxy), fDCAz(obj.fDCAz), isTOFmismatch(obj.isTOFmismatch), isMCptc(obj.isMCptc), fMCcode(obj.fMCcode), fPDGcode(obj.fPDGcode), fMCmumIdx(obj.fMCmumIdx), fMCmumPDG(obj.fMCmumPDG), fMCgrandmumIdx(obj.fMCgrandmumIdx), fMCgrandmumPDG(obj.fMCgrandmumPDG), index(obj.index), mcFirstOriginType(kUnassigned), doSkipOver(obj.doSkipOver), fEtaS(obj.fEtaS), fPhiS(obj.fPhiS), isP(obj.isP), isaP(obj.isaP) { // copy constructor } //_____________________________________________________________________________ AliReconstructedFirst &AliReconstructedFirst::operator=(const AliReconstructedFirst &obj) { //Assignment operator if(this == &obj) return *this; fPt = obj.fPt; fEta = obj.fEta; fTheta = obj.fTheta; fPhi = obj.fPhi; fRap = obj.fRap; fCharge = obj.fCharge; fDCAxy = obj.fDCAxy; fDCAz = obj.fDCAz; isTOFmismatch = obj.isTOFmismatch; isMCptc = obj.isMCptc; fMCcode = obj.fMCcode; fPDGcode = obj.fPDGcode; fMCmumIdx = obj.fMCmumIdx; fMCmumPDG = obj.fMCmumPDG; fMCgrandmumIdx = obj.fMCgrandmumIdx; fMCgrandmumPDG = obj.fMCgrandmumPDG; index = obj.index; mcFirstOriginType = kUnassigned; doSkipOver = obj.doSkipOver; fEtaS = obj.fEtaS; fPhiS = obj.fPhiS; isP = obj.isP; isaP = obj.isaP; return (*this); } //_____________________________________________________________________________ AliReconstructedFirst::~AliReconstructedFirst() { } //_____________________________________________________________________________ AliReconstructedSecond::AliReconstructedSecond() : sPt(0), sEta(0), sTheta(0), sPhi(0), sRap(0), sCharge(0), sDCAxy(0), sDCAz(0), isTOFmismatch(kFALSE), isMCptc(kFALSE), sMCcode(0), sPDGcode(0), sMCmumIdx(0), sMCmumPDG(0), sMCgrandmumIdx(0), sMCgrandmumPDG(0), index(0), mcSecondOriginType(kUnassigned), doSkipOver(kFALSE), sEtaS(0), sPhiS(0), isP(0), isaP(0) { // std::fill(sMomentum,sMomentum+3,0.); // std::fill(sMomentumTruth,sMomentumTruth+3,0.); // std::fill(sShiftedGlobalPosition,sShiftedGlobalPosition+3,0.); // std::fill(iptoPV,iptoPV+2,0.); // std::fill(nSigmaSecondTPC,nSigmaSecondTPC+5,0.); // std::fill(nSigmaSecondTOF,nSigmaSecondTOF+5,0.); // Default constructor } //_____________________________________________________________________________ AliReconstructedSecond::AliReconstructedSecond(const AliReconstructedSecond &obj) : sPt(obj.sPt), sEta(obj.sEta), sTheta(obj.sTheta), sPhi(obj.sPhi), sRap(obj.sRap), sCharge(obj.sCharge), sDCAxy(obj.sDCAxy), sDCAz(obj.sDCAz), isTOFmismatch(obj.isTOFmismatch), isMCptc(obj.isMCptc), sMCcode(obj.sMCcode), sPDGcode(obj.sPDGcode), sMCmumIdx(obj.sMCmumIdx), sMCmumPDG(obj.sMCmumPDG), sMCgrandmumIdx(obj.sMCgrandmumIdx), sMCgrandmumPDG(obj.sMCgrandmumPDG), index(obj.index), mcSecondOriginType(kUnassigned), doSkipOver(obj.doSkipOver), sEtaS(obj.sEtaS), sPhiS(obj.sPhiS), isP(obj.isP), isaP(obj.isaP) { // copy constructor } //_____________________________________________________________________________ AliReconstructedSecond &AliReconstructedSecond::operator=(const AliReconstructedSecond &obj) { //Assignment operator if(this == &obj) return *this; sPt = obj.sPt; sEta = obj.sEta; sTheta = obj.sTheta; sPhi = obj.sPhi; sRap = obj.sRap; sCharge = obj.sCharge; sDCAxy = obj.sDCAxy; sDCAz = obj.sDCAz; isTOFmismatch = obj.isTOFmismatch; isMCptc = obj.isMCptc; sMCcode = obj.sMCcode; sPDGcode = obj.sPDGcode; sMCmumIdx = obj.sMCmumIdx; sMCmumPDG = obj.sMCmumPDG; sMCgrandmumIdx = obj.sMCgrandmumIdx; sMCgrandmumPDG = obj.sMCgrandmumPDG; index = obj.index; mcSecondOriginType = kUnassigned; doSkipOver = obj.doSkipOver; sEtaS = obj.sEtaS; sPhiS = obj.sPhiS; isP = obj.isP; isaP = obj.isaP; return (*this); } //_____________________________________________________________________________ AliReconstructedSecond::~AliReconstructedSecond() { } //_____________________________________________________________________________ AliAnalysisKPEvent::AliAnalysisKPEvent(): fNumberCandidateFirst(0), fNumberCandidateSecond(0), fReconstructedFirst(0x0), fReconstructedSecond(0x0) { //Default constructor } //_____________________________________________________________________________ AliAnalysisKPEvent::~AliAnalysisKPEvent() { //Destructor if(fReconstructedFirst){ delete fReconstructedFirst; fReconstructedFirst= NULL; } if(fReconstructedSecond){ delete fReconstructedSecond; fReconstructedSecond= NULL; } } //_____________________________________________________________________________ AliAnalysisKPEventCollection::AliAnalysisKPEventCollection() : fEvt(0x0), fifo(0) { } //______________________________________________________________________________ AliAnalysisKPEventCollection::~AliAnalysisKPEventCollection(){ for(Int_t i = 0; i < fifo; i++){ if((fEvt + i)->fReconstructedFirst != NULL){ delete [] (fEvt + i)->fReconstructedFirst; } if((fEvt + i)->fReconstructedSecond != NULL){ delete [] (fEvt + i)->fReconstructedSecond; } } delete [] fEvt;fEvt = NULL; } //_____________________________________________________________________________ AliAnalysisKPEventCollection::AliAnalysisKPEventCollection(Short_t eventBuffSize, Int_t maxFirstMult, Int_t maxSecondMult) : fEvt(0x0), fifo(0) { SetBuffSize(eventBuffSize); fEvt = new AliAnalysisKPEvent[fifo]; //allocate pointer array of AliAnalysisKPEvents for(Int_t ii = 0; ii < fifo; ii++){ //Initialize particle table pointers to NULL (fEvt + ii)->fReconstructedFirst = NULL; (fEvt + ii)->fNumberCandidateFirst = 0; (fEvt + ii)->fReconstructedFirst = new AliReconstructedFirst[maxFirstMult]; (fEvt + ii)->fReconstructedSecond = NULL; (fEvt + ii)->fNumberCandidateSecond = 0; (fEvt + ii)->fReconstructedSecond = new AliReconstructedSecond[maxSecondMult]; } } //_____________________________________________________________________________ void AliAnalysisKPEventCollection::FifoShift() { //Shift elements in FIFO by one and clear last element in FIFO for(unsigned short i=fifo-1 ; i > 0; i--) { for(Int_t j=0; j<(fEvt + i-1)->fNumberCandidateFirst; j++){ (fEvt + i)->fReconstructedFirst[j] = (fEvt + i-1)->fReconstructedFirst[j]; } (fEvt + i)->fNumberCandidateFirst = (fEvt + i-1)->fNumberCandidateFirst; for(Int_t j=0; j<(fEvt + i-1)->fNumberCandidateSecond; j++){ (fEvt + i)->fReconstructedSecond[j] = (fEvt + i-1)->fReconstructedSecond[j]; } (fEvt + i)->fNumberCandidateSecond = (fEvt + i-1)->fNumberCandidateSecond; for(Int_t j=0; j<3; j++){ (fEvt + i)->fPrimaryVertex[j] = (fEvt + i-1)->fPrimaryVertex[j]; } } (fEvt)->fNumberCandidateFirst=0; (fEvt)->fNumberCandidateSecond=0; for(Int_t j=0; j<3; j++) { (fEvt)->fPrimaryVertex[j] = 0.; } } <|endoftext|>
<commit_before>// Copyright (c) 2012-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <compat/sanity.h> #include <key.h> #include <test/util/setup_common.h> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(sanity_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(basic_sanity) { BOOST_CHECK_MESSAGE(glibcxx_sanity_test() == true, "stdlib sanity test"); BOOST_CHECK_MESSAGE(ECC_InitSanityCheck() == true, "openssl ECC test"); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>test: fix message for ECC_InitSanityCheck test<commit_after>// Copyright (c) 2012-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <compat/sanity.h> #include <key.h> #include <test/util/setup_common.h> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(sanity_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(basic_sanity) { BOOST_CHECK_MESSAGE(glibcxx_sanity_test() == true, "stdlib sanity test"); BOOST_CHECK_MESSAGE(ECC_InitSanityCheck() == true, "secp256k1 sanity test"); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include "opencv2/imgproc/imgproc.hpp" #include "opencv2/objdetect/objdetect.hpp" #include <opencv2/core/core.hpp> #include <opencv2/ml/ml.hpp> //#include <boost/lexical_cast.hpp> #include <boost/filesystem.hpp> #include <iostream> #include <fstream> #include <cstdlib> #include "ocr_train.hpp" using namespace cv; using namespace std; namespace fs = boost::filesystem; Mat vector2Mat1D(vector<int> vec) { Mat result; Mat_<int> templ = Mat_<int>(vec.size(),1); for(vector<int>::iterator i = vec.begin(); i != vec.end(); ++i) { templ << *i; } result = (templ); return result; } Mat vector2Mat2D(vector< vector<int> > vec) { Mat result; Mat_<int> templ = Mat_<int>(vec.at(0).size(),2); //todo: vec.at(0).size() remove this hack for(vector< vector<int> >::iterator i = vec.begin(); i != vec.end(); ++i) { for(vector<int>::iterator j = (*i).begin(); j != (*i).end(); ++j) { templ << *j; } } result = (templ); return result; } int main() { //1. training string samples_str = "samples"; string responses_str = "responses"; vector<int> responses = loadArray< vector<int> >(responses_str); vector< vector<int> > samples = loadArray<vector < vector<int> > >(samples_str); //test: convert vector to Mat Mat samples_mat = vector2Mat2D(samples); Mat responses_mat = vector2Mat1D(responses); //train CvKNearest kn_model = CvKNearest(); kn_model.train(samples_mat, responses_mat); //2. testing return 0; } <commit_msg>Finished porting ocr_recognizer, need to test<commit_after>#include <opencv2/imgproc/imgproc.hpp> #include <opencv2/objdetect/objdetect.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/core/core.hpp> #include <opencv2/ml/ml.hpp> #include <boost/lexical_cast.hpp> #include <boost/filesystem.hpp> #include <iostream> #include <fstream> #include <cstdlib> #include "ocr_train.hpp" using namespace cv; using namespace std; namespace fs = boost::filesystem; Mat vector2Mat1D(vector<int> vec) { Mat result; Mat_<int> templ = Mat_<int>(vec.size(),1); for(vector<int>::iterator i = vec.begin(); i != vec.end(); ++i) { templ << *i; } result = (templ); return result; } Mat vector2Mat2D(vector< vector<int> > vec) { Mat result; Mat_<int> templ = Mat_<int>(vec.at(0).size(),2); //todo: vec.at(0).size() remove this hack for(vector< vector<int> >::iterator i = vec.begin(); i != vec.end(); ++i) { for(vector<int>::iterator j = (*i).begin(); j != (*i).end(); ++j) { templ << *j; } } result = (templ); return result; } int main() { //1. training string samples_str = "samples"; string responses_str = "responses"; vector<int> responses = loadArray< vector<int> >(responses_str); vector< vector<int> > samples = loadArray<vector < vector<int> > >(samples_str); //test: convert vector to Mat Mat samples_mat = vector2Mat2D(samples); Mat responses_mat = vector2Mat1D(responses); //train CvKNearest kn_model = CvKNearest(); kn_model.train(samples_mat, responses_mat); //2. testing //Loads test image with numbers Mat img = imread("test.jpg"); Mat img_original; img.copyTo(img_original); //Grayscale Mat gray; cvtColor(img, gray, CV_BGR2GRAY); //Builds a threshold making a binary image Mat thresh; adaptiveThreshold(gray, thresh, 255, 1, 1, 11, 2); //Output Mat out; //Find contours vector<vector<Point> > contours; vector<Vec4i> hierarchy; findContours(thresh, contours, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE); double cntArea; Mat contourMat; for (vector< vector<Point> >::iterator it = contours.begin(); it != contours.end(); ++it ) { vector<Point> cnt = *it; cntArea = contourArea(cnt); if (cntArea<50) { continue; } Rect boundbox = boundingRect(cnt); int x = boundbox.x; int y = boundbox.y; int width = boundbox.width; int height = boundbox.height; if (height<25) { //If it isn't high enough continue; } Point px(x,y); Point py(x+width, y+height); Scalar color(0, 0, 255); //red img.copyTo(contourMat); rectangle(contourMat, px, py, color, 2); //draws a rectangle on top of img Mat roi; roi = thresh(boundbox); //todo could be reverse (x,y) (y,x), am not sure //resize it to 10x10 Mat roismall; Size_<int> smallSize(10,10); resize(roi, roismall, smallSize); //todo "" roismall = roismall.reshape((1,100)) //roismall = np.float32(roismall) Mat results, neighborResponses, dist; float retval = kn_model.find_nearest(roismall, 1, results, neighborResponses, dist); float number_res = results.at<float>(0,0); string str_result = boost::lexical_cast<string>(number_res); Point start_point(x,y+height); putText(out, str_result, start_point, 0, 1, color); } imshow("img", img); imshow("out", out); return 0; } <|endoftext|>
<commit_before>AliAnalysisVertexingHF* ConfigVertexingHF() { printf("MYCONFIGPID Call to AliAnalysisVertexingHF parameters setting :\n"); vHF = new AliAnalysisVertexingHF(); //Set Reduce Size dAOD vHF->SetMakeReducedRHF(kTRUE); //--- switch-off candidates finding (default: all on) //vHF->SetD0toKpiOff(); vHF->SetJPSItoEleOff(); //vHF->Set3ProngOff(); //vHF->SetLikeSignOn(); // like-sign pairs and triplets // vHF->SetLikeSign3prongOff(); //vHF->Set4ProngOff(); // vHF->SetDstarOff(); vHF->SetFindVertexForDstar(kFALSE); //--- secondary vertex with KF? //vHF->SetSecVtxWithKF(); //Cascade vHF->SetCascadesOn(); vHF->SetFindVertexForCascades(kTRUE); vHF->SetV0TypeForCascadeVertex(AliRDHFCuts::kAllV0s); //All V0s 0, Offline 1, OnTheFly 2 //as in Config_Pb_AllCent vHF->SetUseProtonPIDforLambdaC2V0(); vHF->SetMassCutBeforeVertexing(kTRUE); // PbPb //set PID vHF->SetUseKaonPIDfor3Prong(kTRUE); vHF->SetUseProtonAndPionPIDforLambdaC(); vHF->SetnSigmaTOFforKaonSel(3., 5.); vHF->SetnSigmaTPCforKaonSel(5., 5.); vHF->SetnSigmaTOFforProtonSel(3.,5.); vHF->SetnSigmaTPCforProtonSel(5., 5.); vHF->SetnSigmaTPCforPionSel(4., 4.); vHF->SetnSigmaTOFforPionSel(40.,40.); vHF->SetMaxMomForTPCPid(9999999999.); vHF->SetUseTPCPID(kTRUE); vHF->SetUseTOFPID(kTRUE); vHF->SetUseTPCPIDOnlyIfNoTOF(kTRUE); //--- set cuts for single-track selection // displaced tracks AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts","default"); esdTrackCuts->SetRequireTPCRefit(kTRUE); esdTrackCuts->SetMinNClustersTPC(70); esdTrackCuts->SetRequireITSRefit(kTRUE); //esdTrackCuts->SetMinNClustersITS(4); esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kAny); // |d0|>30 micron for pt<2GeV, no cut above 2 esdTrackCuts->SetMinDCAToVertexXYPtDep("0.003*TMath::Max(0.,(1-TMath::Floor(TMath::Abs(pt)/2.)))"); esdTrackCuts->SetMaxDCAToVertexXY(1.); esdTrackCuts->SetMaxDCAToVertexZ(1.); esdTrackCuts->SetPtRange(0.4,1.e10); esdTrackCuts->SetEtaRange(-0.8,+0.8); AliAnalysisFilter *trkFilter = new AliAnalysisFilter("trackFilter"); trkFilter->AddCuts(esdTrackCuts); vHF->SetTrackFilter(trkFilter); // D* soft pion tracks AliESDtrackCuts *esdTrackCutsSoftPi = new AliESDtrackCuts("AliESDtrackCuts","default"); esdTrackCutsSoftPi->SetMinNClustersITS(2); esdTrackCutsSoftPi->SetMaxDCAToVertexXY(1.); esdTrackCutsSoftPi->SetMaxDCAToVertexZ(1.); esdTrackCutsSoftPi->SetPtRange(0.2,1.e10); esdTrackCutsSoftPi->SetEtaRange(-0.8,+0.8); AliAnalysisFilter *trkFilterSoftPi = new AliAnalysisFilter("trackFilterSoftPi"); trkFilterSoftPi->AddCuts(esdTrackCutsSoftPi); vHF->SetTrackFilterSoftPi(trkFilterSoftPi); //--- set cuts for candidates selection Int_t nptbins=2; Float_t ptlimits[2]={0.,1000000.}; AliRDHFCutsD0toKpi *cutsD0toKpi = new AliRDHFCutsD0toKpi("CutsD0toKpi"); cutsD0toKpi->SetStandardCutsPbPb2010(); cutsD0toKpi->SetMinCentrality(-10); cutsD0toKpi->SetMaxCentrality(110); cutsD0toKpi->SetUseSpecialCuts(kFALSE); cutsD0toKpi->SetMinPtCandidate(0.); cutsD0toKpi->SetUsePID(kFALSE); cutsD0toKpi->SetUsePhysicsSelection(kFALSE); cutsD0toKpi->SetMaxVtxZ(1.e6); cutsD0toKpi->SetTriggerClass(""); Float_t cutsArrayD0toKpi[11]={0.4,999999.,1.1,0.,0.,999999.,999999.,0.,0.5,-1,0.}; cutsD0toKpi->SetPtBins(nptbins,ptlimits); cutsD0toKpi->SetCuts(11,cutsArrayD0toKpi); cutsD0toKpi->AddTrackCuts(esdTrackCuts); vHF->SetCutsD0toKpi(cutsD0toKpi); AliRDHFCutsJpsitoee *cutsJpsitoee = new AliRDHFCutsJpsitoee("CutsJpsitoee"); Float_t cutsArrayJpsitoee[9]={0.350,100000.,1.1,0.,0.,100000.,100000.,100000000.,-1.1}; cutsJpsitoee->SetCuts(9,cutsArrayJpsitoee); cutsJpsitoee->AddTrackCuts(esdTrackCuts); vHF->SetCutsJpsitoee(cutsJpsitoee); AliRDHFCutsDplustoKpipi *cutsDplustoKpipi = new AliRDHFCutsDplustoKpipi("CutsDplustoKpipi"); cutsDplustoKpipi->SetStandardCutsPbPb2010(); cutsDplustoKpipi->SetUsePID(kFALSE); Float_t cutsArrayDplustoKpipi[14]={0.,0.3,0.3,0.,0.,0.01,0.05,0.05,0.,0.88,0.,10000000000.,0.,-1.}; cutsDplustoKpipi->SetPtBins(nptbins,ptlimits); cutsDplustoKpipi->SetCuts(14,cutsArrayDplustoKpipi); cutsDplustoKpipi->AddTrackCuts(esdTrackCuts); cutsDplustoKpipi->SetMinPtCandidate(2000000000.); vHF->SetCutsDplustoKpipi(cutsDplustoKpipi); AliRDHFCutsDstoKKpi *cutsDstoKKpi = new AliRDHFCutsDstoKKpi("CutsDstoKKpi"); cutsDstoKKpi->SetStandardCutsPbPb2010(); cutsDstoKKpi->SetUsePID(kFALSE); Float_t cutsArrayDstoKKpi[20]={0.,0.3,0.3,0.,0.,0.005,0.06,0.,0.,0.9,0.,100000.,0.035,0.0001,-1.,1.,0.,0.,0.,-1.}; cutsDstoKKpi->SetPtBins(nptbins,ptlimits); cutsDstoKKpi->SetCuts(20,cutsArrayDstoKKpi); cutsDstoKKpi->AddTrackCuts(esdTrackCuts); cutsDstoKKpi->SetMinPtCandidate(1000000000.); vHF->SetCutsDstoKKpi(cutsDstoKKpi); AliRDHFCutsLctopKpi *cutsLctopKpi = new AliRDHFCutsLctopKpi("CutsLctopKpi"); cutsLctopKpi->SetStandardCutsPbPb2010(); cutsLctopKpi->SetUsePID(kFALSE); Float_t cutsArrayLctopKpi[13]={0.13,0.4,0.4,0.,0.,0.,0.06,0.,0.,0.,0.,0.05,0.4}; cutsLctopKpi->SetPtBins(nptbins,ptlimits); cutsLctopKpi->SetCuts(13,cutsArrayLctopKpi); cutsLctopKpi->AddTrackCuts(esdTrackCuts); cutsLctopKpi->SetMinPtCandidate(2.); vHF->SetCutsLctopKpi(cutsLctopKpi); AliRDHFCutsD0toKpipipi *cutsD0toKpipipi = new AliRDHFCutsD0toKpipipi("CutsD0toKpipipi"); Float_t cutsArrayD0toKpipipi[9]={0.2,0.04,0.00,0.01,0.02,0.8,0.,0.1,0.}; cutsD0toKpipipi->SetCuts(9,cutsArrayD0toKpipipi); cutsD0toKpipipi->AddTrackCuts(esdTrackCuts); vHF->SetCutsD0toKpipipi(cutsD0toKpipipi); // D* pt dependent cuts ------------------------------------------ AliRDHFCutsDStartoKpipi *cutsDStartoKpipi = new AliRDHFCutsDStartoKpipi("CutsDStartoKpipi"); cutsDStartoKpipi->SetUsePID(kFALSE); const Int_t nvars=16; const Int_t nptbins=2; Float_t* ptbins; ptbins=new Float_t[nptbins+1]; ptbins[0]=0.; ptbins[1]=5.; ptbins[2]=999.; cutsDStartoKpipi->SetPtBins(nptbins+1,ptbins); Float_t** rdcutsvalmine; rdcutsvalmine=new Float_t*[nvars]; for(Int_t iv=0;iv<nvars;iv++){ rdcutsvalmine[iv]=new Float_t[nptbins]; } //0-5 rdcutsvalmine[0][0]=0.10; //D0 inv mass window rdcutsvalmine[1][0]=0.06; // dca rdcutsvalmine[2][0]=0.9; // thetastar rdcutsvalmine[3][0]=0.5; // pt Pion rdcutsvalmine[4][0]=0.5; // Pt Kaon rdcutsvalmine[5][0]=0.1; // d0K rdcutsvalmine[6][0]=0.1; // d0Pi rdcutsvalmine[7][0]=0.0001; // d0xd0 rdcutsvalmine[8][0]=0.8; // costhetapoint rdcutsvalmine[9][0]=0.15; // Dstar inv mass window rdcutsvalmine[10][0]=0.03; // half width of (M_Kpipi-M_D0) rdcutsvalmine[11][0]=0.1; // Pt min of Pi soft rdcutsvalmine[12][0]=100.; // Pt max of pi soft rdcutsvalmine[13][0]=9999.; // theta rdcutsvalmine[14][0]=0.9; // |cosThetaPointXY| rdcutsvalmine[15][0]=1.; // NormDecayLenghtXY //5-999 rdcutsvalmine[0][1]=0.10; //D0 inv mass window rdcutsvalmine[1][1]=0.06; // dca rdcutsvalmine[2][1]=0.9; // thetastar rdcutsvalmine[3][1]=0.5; // pt Pion rdcutsvalmine[4][1]=0.5; // Pt Kaon rdcutsvalmine[5][1]=0.1; // d0K rdcutsvalmine[6][1]=0.1; // d0Pi rdcutsvalmine[7][1]=0.0001; // d0xd0 rdcutsvalmine[8][1]=0.7; // costhetapoint rdcutsvalmine[9][1]=0.15; // Dstar inv mass window rdcutsvalmine[10][1]=0.03; // half width of (M_Kpipi-M_D0) rdcutsvalmine[11][1]=0.1; // Pt min of Pi soft rdcutsvalmine[12][1]=100.; // Pt max of pi soft rdcutsvalmine[13][1]=9999.; // theta rdcutsvalmine[14][1]=0.8; // |cosThetaPointXY| rdcutsvalmine[15][1]=0.; // NormDecayLenghtXY cutsDStartoKpipi->SetCuts(nvars,nptbins,rdcutsvalmine); cutsDStartoKpipi->AddTrackCuts(esdTrackCuts); cutsDStartoKpipi->AddTrackCutsSoftPi(esdTrackCutsSoftPi); cutsDStartoKpipi->SetMinPtCandidate(2.); vHF->SetCutsDStartoKpipi(cutsDStartoKpipi); //-------------------------------------------------------- AliRDHFCutsLctoV0 *cutsLctoV0 = new AliRDHFCutsLctoV0("CutsLctoV0"); Float_t cutsArrayLctoV0[21]={1.0,1.0,0.05,0.05,0.0,0.0,0.0,1000.,1000.,0.99,3.,1000.,0.,0.,0.,0.,9999.,-9999.,-9999.,-9999.,0.0};//from the Config_Pb_AllCent_NOLS cutsLctoV0->SetCuts(21,cutsArrayLctoV0); cutsLctoV0->AddTrackCuts(esdTrackCuts); AliESDtrackCuts *esdV0daughterTrackCuts = new AliESDtrackCuts("AliESDtrackCutsForV0D","default cuts for V0 daughters"); esdV0daughterTrackCuts->SetRequireTPCRefit(kTRUE); esdV0daughterTrackCuts->SetMinNClustersTPC(30); esdV0daughterTrackCuts->SetRequireITSRefit(kFALSE); esdV0daughterTrackCuts->SetMinDCAToVertexXY(0.); esdV0daughterTrackCuts->SetPtRange(0.05,1.e10); esdV0daughterTrackCuts->SetEtaRange(-1.1,+1.1); esdV0daughterTrackCuts->SetAcceptKinkDaughters(kTRUE); esdV0daughterTrackCuts->SetRequireSigmaToVertex(kFALSE); cutsLctoV0->AddTrackCutsV0daughters(esdV0daughterTrackCuts); vHF->SetCutsLctoV0(cutsLctoV0); // //--- set this if you want to reconstruct primary vertex candidate by // candidate using other tracks in the event (for pp, broad // interaction region) //vHF->SetRecoPrimVtxSkippingTrks(); //--- OR set this if you want to remove the candidate daughters from // the primary vertex, without recostructing it from scratch //vHF->SetRmTrksFromPrimVtx(); //--- check the settings vHF->PrintStatus(); //--- verbose // AliLog::SetClassDebugLevel("AliAnalysisVertexingHF",2); return vHF; } <commit_msg>Fix for the ConfigVertexingHF for the MC upgrade production<commit_after>AliAnalysisVertexingHF* ConfigVertexingHF() { printf("MYCONFIGPID Call to AliAnalysisVertexingHF parameters setting :\n"); vHF = new AliAnalysisVertexingHF(); //Set Reduce Size dAOD vHF->SetMakeReducedRHF(kTRUE); //--- switch-off candidates finding (default: all on) //vHF->SetD0toKpiOff(); // vHF->SetD0toKpiOn(); vHF->SetJPSItoEleOff(); //vHF->Set3ProngOff(); //vHF->SetLikeSignOn(); // like-sign pairs and triplets // vHF->SetLikeSign3prongOff(); //vHF->Set4ProngOff(); // vHF->SetDstarOn(); vHF->SetFindVertexForDstar(kFALSE); //--- secondary vertex with KF? //vHF->SetSecVtxWithKF(); //Cascade vHF->SetCascadesOn(); vHF->SetFindVertexForCascades(kFALSE); vHF->SetMassCutBeforeVertexing(kTRUE); // PbPb vHF->SetV0TypeForCascadeVertex(AliRDHFCuts::kAllV0s); //All V0s 0, Offline 1, OnTheFly 2 //as in Config_Pb_AllCent vHF->SetUseProtonPIDforLambdaC2V0(); vHF->SetMassCutBeforeVertexing(kTRUE); // PbPb //--- set cuts for single-track selection // displaced tracks AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts","default"); esdTrackCuts->SetRequireTPCRefit(kTRUE); esdTrackCuts->SetMinNClustersTPC(70); esdTrackCuts->SetRequireITSRefit(kTRUE); //esdTrackCuts->SetMinNClustersITS(4); esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kAny); // |d0|>30 micron for pt<2GeV, no cut above 2 esdTrackCuts->SetMinDCAToVertexXYPtDep("0.003*TMath::Max(0.,(1-TMath::Floor(TMath::Abs(pt)/2.)))"); esdTrackCuts->SetMaxDCAToVertexXY(1.); esdTrackCuts->SetMaxDCAToVertexZ(1.); esdTrackCuts->SetPtRange(0.4,1.e10); esdTrackCuts->SetEtaRange(-0.8,+0.8); AliAnalysisFilter *trkFilter = new AliAnalysisFilter("trackFilter"); trkFilter->AddCuts(esdTrackCuts); vHF->SetTrackFilter(trkFilter); // D* soft pion tracks AliESDtrackCuts *esdTrackCutsSoftPi = new AliESDtrackCuts("AliESDtrackCuts","default"); esdTrackCutsSoftPi->SetMinNClustersITS(2); esdTrackCutsSoftPi->SetMaxDCAToVertexXY(1.); esdTrackCutsSoftPi->SetMaxDCAToVertexZ(1.); esdTrackCutsSoftPi->SetPtRange(0.1,1.e10); esdTrackCutsSoftPi->SetEtaRange(-0.8,+0.8); AliAnalysisFilter *trkFilterSoftPi = new AliAnalysisFilter("trackFilterSoftPi"); trkFilterSoftPi->AddCuts(esdTrackCutsSoftPi); vHF->SetTrackFilterSoftPi(trkFilterSoftPi); //--- set cuts for candidates selection Int_t nptbins=2; Float_t ptlimits[2]={0.,1000000.}; AliRDHFCutsD0toKpi *cutsD0toKpi = new AliRDHFCutsD0toKpi("CutsD0toKpi"); cutsD0toKpi->SetStandardCutsPbPb2010(); cutsD0toKpi->SetUseCentrality(kFALSE); // cutsD0toKpi->SetMinCentrality(-10); //cutsD0toKpi->SetMaxCentrality(110); cutsD0toKpi->SetUseSpecialCuts(kFALSE); cutsD0toKpi->SetMinPtCandidate(0.); cutsD0toKpi->SetUsePID(kFALSE); cutsD0toKpi->SetUsePhysicsSelection(kFALSE); cutsD0toKpi->SetMaxVtxZ(1.e6); cutsD0toKpi->SetTriggerClass(""); Float_t cutsArrayD0toKpi[11]={0.4,999999.,1.1,0.,0.,999999.,999999.,0.,0.5,-1,0.}; cutsD0toKpi->SetPtBins(nptbins,ptlimits); cutsD0toKpi->SetCuts(11,cutsArrayD0toKpi); cutsD0toKpi->AddTrackCuts(esdTrackCuts); vHF->SetCutsD0toKpi(cutsD0toKpi); AliRDHFCutsJpsitoee *cutsJpsitoee = new AliRDHFCutsJpsitoee("CutsJpsitoee"); Float_t cutsArrayJpsitoee[9]={0.350,100000.,1.1,0.,0.,100000.,100000.,100000000.,-1.1}; cutsJpsitoee->SetCuts(9,cutsArrayJpsitoee); cutsJpsitoee->AddTrackCuts(esdTrackCuts); vHF->SetCutsJpsitoee(cutsJpsitoee); AliRDHFCutsDplustoKpipi *cutsDplustoKpipi = new AliRDHFCutsDplustoKpipi("CutsDplustoKpipi"); cutsDplustoKpipi->SetStandardCutsPbPb2010(); cutsDplustoKpipi->SetUseCentrality(kFALSE); cutsDplustoKpipi->SetUsePID(kFALSE); Float_t cutsArrayDplustoKpipi[14]={0.25,0.3,0.3,0.,0.,0.01,0.05,0.05,0.,0.7,0.,10000000000.,0.,-1.}; cutsDplustoKpipi->SetPtBins(nptbins,ptlimits); cutsDplustoKpipi->SetCuts(14,cutsArrayDplustoKpipi); cutsDplustoKpipi->AddTrackCuts(esdTrackCuts); cutsDplustoKpipi->SetMinPtCandidate(2.); vHF->SetCutsDplustoKpipi(cutsDplustoKpipi); AliRDHFCutsDstoKKpi *cutsDstoKKpi = new AliRDHFCutsDstoKKpi("CutsDstoKKpi"); cutsDstoKKpi->SetStandardCutsPbPb2010(); cutsDstoKKpi->SetUseCentrality(kFALSE); cutsDstoKKpi->SetUsePID(kFALSE); Float_t cutsArrayDstoKKpi[20]={0.35,0.3,0.3,0.,0.,0.005,0.06,0.,0.,0.7,0.,100000.,0.035,0.0001,-1.,1.,0.,0.,0.,-1.}; cutsDstoKKpi->SetPtBins(nptbins,ptlimits); cutsDstoKKpi->SetCuts(20,cutsArrayDstoKKpi); cutsDstoKKpi->AddTrackCuts(esdTrackCuts); cutsDstoKKpi->SetMinPtCandidate(2.); vHF->SetCutsDstoKKpi(cutsDstoKKpi); AliRDHFCutsLctopKpi *cutsLctopKpi = new AliRDHFCutsLctopKpi("CutsLctopKpi"); cutsLctopKpi->SetStandardCutsPbPb2010(); cutsLctopKpi->SetUseCentrality(kFALSE); cutsLctopKpi->SetUsePID(kFALSE); Float_t cutsArrayLctopKpi[13]={0.13,0.4,0.4,0.,0.,0.,0.06,0.,0.,0.,0.,0.05,0.4}; cutsLctopKpi->SetPtBins(nptbins,ptlimits); cutsLctopKpi->SetCuts(13,cutsArrayLctopKpi); cutsLctopKpi->AddTrackCuts(esdTrackCuts); cutsLctopKpi->SetMinPtCandidate(2.); vHF->SetCutsLctopKpi(cutsLctopKpi); AliRDHFCutsD0toKpipipi *cutsD0toKpipipi = new AliRDHFCutsD0toKpipipi("CutsD0toKpipipi"); Float_t cutsArrayD0toKpipipi[9]={0.2,0.04,0.00,0.01,0.02,0.8,0.,0.1,0.}; cutsD0toKpipipi->SetCuts(9,cutsArrayD0toKpipipi); cutsD0toKpipipi->AddTrackCuts(esdTrackCuts); vHF->SetCutsD0toKpipipi(cutsD0toKpipipi); AliRDHFCutsDStartoKpipi *cutsDStartoKpipi = new AliRDHFCutsDStartoKpipi("CutsDStartoKpipi"); Float_t cutsArrayDStartoKpipi[16]={0.1,999999.,1.1,0.,0.,999999.,999999.,999999.,0.7,0.03, 0.1, 0.05, 100000000000.0, 0.5,-1.,1.}; // first 9 for D0 from D*, next 5 for D*, last 2 for D0 again cutsDStartoKpipi->SetUsePID(kFALSE); cutsDStartoKpipi->SetCuts(16,cutsArrayDStartoKpipi); cutsDStartoKpipi->AddTrackCuts(esdTrackCuts); cutsDStartoKpipi->AddTrackCutsSoftPi(esdTrackCutsSoftPi); cutsDStartoKpipi->SetMinPtCandidate(2.); vHF->SetCutsDStartoKpipi(cutsDStartoKpipi); //-------------------------------------------------------- AliRDHFCutsLctoV0 *cutsLctoV0 = new AliRDHFCutsLctoV0("CutsLctoV0"); /* Float_t cutsArrayLctoV0[9]={4.0,4.0,2.0,2.0,0.0,0.0,0.0,1000.,1000.}; cutsLctoV0->SetCuts(9,cutsArrayLctoV0); */ //last dummy Float_t cutsArrayLctoV0[21]={1.0,1.0,0.05,0.05,0.0,0.0,0.0,1000.,1000.,0.99,3.,1000.,0.,0.,0.,0.,9999.,-9999.,-9999.,-9999.,0.0};//from the Config_Pb_AllCent_NOLS cutsLctoV0->SetCuts(21,cutsArrayLctoV0); cutsLctoV0->AddTrackCuts(esdTrackCuts); AliESDtrackCuts *esdV0daughterTrackCuts = new AliESDtrackCuts("AliESDtrackCutsForV0D","default cuts for V0 daughters"); esdV0daughterTrackCuts->SetRequireTPCRefit(kTRUE); esdV0daughterTrackCuts->SetMinNClustersTPC(30); esdV0daughterTrackCuts->SetRequireITSRefit(kFALSE); esdV0daughterTrackCuts->SetMinDCAToVertexXY(0.); esdV0daughterTrackCuts->SetPtRange(0.05,1.e10); esdV0daughterTrackCuts->SetEtaRange(-1.1,+1.1); esdV0daughterTrackCuts->SetAcceptKinkDaughters(kTRUE); esdV0daughterTrackCuts->SetRequireSigmaToVertex(kFALSE); cutsLctoV0->AddTrackCutsV0daughters(esdV0daughterTrackCuts); vHF->SetCutsLctoV0(cutsLctoV0); // //--- set this if you want to reconstruct primary vertex candidate by // candidate using other tracks in the event (for pp, broad // interaction region) //vHF->SetRecoPrimVtxSkippingTrks(); //--- OR set this if you want to remove the candidate daughters from // the primary vertex, without recostructing it from scratch //vHF->SetRmTrksFromPrimVtx(); //--- check the settings vHF->PrintStatus(); //--- verbose // AliLog::SetClassDebugLevel("AliAnalysisVertexingHF",2); return vHF; } <|endoftext|>
<commit_before>#include "osg/Uniform" #include "osg/io_utils" #include "osg/Notify" #include "osgDB/Registry" #include "osgDB/Input" #include "osgDB/Output" #include "Matrix.h" using namespace osg; using namespace osgDB; using namespace std; // forward declare functions to use later. bool Uniform_readLocalData(Object& obj, Input& fr); bool Uniform_writeLocalData(const Object& obj, Output& fw); // register the read and write functions with the osgDB::Registry. RegisterDotOsgWrapperProxy g_UniformProxy ( new osg::Uniform, "Uniform", "Object Uniform", &Uniform_readLocalData, &Uniform_writeLocalData ); bool Uniform_readLocalData(Object& obj, Input& fr) { bool iteratorAdvanced = false; Uniform& uniform = static_cast<Uniform&>(obj); if (fr.matchSequence("name %s")) { uniform.setName(fr[1].getStr()); fr+=2; iteratorAdvanced = true; } if (fr[0].isWord()) { uniform.setType( Uniform::getTypeId(fr[0].getStr()) ); fr+=1; iteratorAdvanced = true; } switch( Uniform::getGlApiType(uniform.getType()) ) { case(osg::Uniform::FLOAT): { float value; if (fr[0].getFloat(value)) { uniform.set(value); fr+=1; iteratorAdvanced = true; } break; } case(osg::Uniform::FLOAT_VEC2): { osg::Vec2 value; if (fr[0].getFloat(value[0]) && fr[1].getFloat(value[1])) { uniform.set(value); fr+=2; iteratorAdvanced = true; } break; } case(osg::Uniform::FLOAT_VEC3): { osg::Vec3 value; if (fr[0].getFloat(value[0]) && fr[1].getFloat(value[1]) && fr[2].getFloat(value[2])) { uniform.set(value); fr+=3; iteratorAdvanced = true; } break; } case(osg::Uniform::FLOAT_VEC4): { osg::Vec4 value; if (fr[0].getFloat(value[0]) && fr[1].getFloat(value[1]) && fr[2].getFloat(value[2]) && fr[3].getFloat(value[3])) { uniform.set(value); fr+=4; iteratorAdvanced = true; } break; } case(osg::Uniform::INT): { int value; if (fr[0].getInt(value)) { uniform.set(value); fr+=1; iteratorAdvanced = true; } break; } case(osg::Uniform::INT_VEC2): { int value[2]; if (fr[0].getInt(value[0]) && fr[1].getInt(value[1])) { uniform.set(value[0],value[1]); fr+=2; iteratorAdvanced = true; } break; } case(osg::Uniform::INT_VEC3): { int value[3]; if (fr[0].getInt(value[0]) && fr[1].getInt(value[1]) && fr[2].getInt(value[2])) { uniform.set(value[0],value[1],value[2]); fr+=3; iteratorAdvanced = true; } break; } case(osg::Uniform::INT_VEC4): { int value[4]; if (fr[0].getInt(value[0]) && fr[1].getInt(value[1]) && fr[2].getInt(value[2]) && fr[3].getInt(value[3])) { uniform.set(value[0],value[1],value[2],value[3]); fr+=4; iteratorAdvanced = true; } break; } case(osg::Uniform::FLOAT_MAT2): { osg::notify(osg::WARN)<<"Warning : type mat2 not supported for reading."<<std::endl; break; } case(osg::Uniform::FLOAT_MAT3): { osg::notify(osg::WARN)<<"Warning : type mat3 not supported for reading."<<std::endl; break; } case(osg::Uniform::FLOAT_MAT4): { Matrix value; if( readMatrix(value,fr) ) { uniform.set(value); iteratorAdvanced = true; } break; } case(osg::Uniform::UNDEFINED): { break; } } return iteratorAdvanced; } bool Uniform_writeLocalData(const Object& obj,Output& fw) { const Uniform& uniform = static_cast<const Uniform&>(obj); fw.indent() << "name "<< fw.wrapString(uniform.getName()) << std::endl; fw.indent() << Uniform::getTypename( uniform.getType() ) << " "; switch( Uniform::getGlApiType(uniform.getType()) ) { case(osg::Uniform::FLOAT): { float value = 0.0f; uniform.get(value); fw << value; break; } case(osg::Uniform::FLOAT_VEC2): { Vec2 value; uniform.get(value); fw << value; break; } case(osg::Uniform::FLOAT_VEC3): { Vec3 value; uniform.get(value); fw << value; break; } case(osg::Uniform::FLOAT_VEC4): { Vec4 value; uniform.get(value); fw << value; break; } case(osg::Uniform::INT): { int value = 0; uniform.get(value); fw << value; break; } case(osg::Uniform::INT_VEC2): { int value[2]; uniform.get(value[0],value[1]); fw << value[0]<<" "<<value[1]; break; } case(osg::Uniform::INT_VEC3): { int value[3]; uniform.get(value[0],value[1],value[2]); fw << value[0]<<" "<<value[1]<<" "<<value[2]; break; } case(osg::Uniform::INT_VEC4): { int value[4]; uniform.get(value[0],value[1],value[2],value[3]); fw << value[0]<<" "<<value[1]<<" "<<value[2]<<" "<<value[3]; break; } case(osg::Uniform::FLOAT_MAT2): { osg::notify(osg::WARN)<<"Warning : type mat2 not supported for writing."<<std::endl; break; } case(osg::Uniform::FLOAT_MAT3): { osg::notify(osg::WARN)<<"Warning : type mat3 not supported for writing."<<std::endl; break; } case(osg::Uniform::FLOAT_MAT4): { Matrix value; uniform.get(value); writeMatrix(value,fw); break; } case(osg::Uniform::UNDEFINED): { break; } } fw << std::endl; return true; } <commit_msg>Fixed compile warning.<commit_after>#include "osg/Uniform" #include "osg/io_utils" #include "osg/Notify" #include "osgDB/Registry" #include "osgDB/Input" #include "osgDB/Output" #include "Matrix.h" using namespace osg; using namespace osgDB; using namespace std; // forward declare functions to use later. bool Uniform_readLocalData(Object& obj, Input& fr); bool Uniform_writeLocalData(const Object& obj, Output& fw); // register the read and write functions with the osgDB::Registry. RegisterDotOsgWrapperProxy g_UniformProxy ( new osg::Uniform, "Uniform", "Object Uniform", &Uniform_readLocalData, &Uniform_writeLocalData ); bool Uniform_readLocalData(Object& obj, Input& fr) { bool iteratorAdvanced = false; Uniform& uniform = static_cast<Uniform&>(obj); if (fr.matchSequence("name %s")) { uniform.setName(fr[1].getStr()); fr+=2; iteratorAdvanced = true; } if (fr[0].isWord()) { uniform.setType( Uniform::getTypeId(fr[0].getStr()) ); fr+=1; iteratorAdvanced = true; } switch( Uniform::getGlApiType(uniform.getType()) ) { case(osg::Uniform::FLOAT): { float value; if (fr[0].getFloat(value)) { uniform.set(value); fr+=1; iteratorAdvanced = true; } break; } case(osg::Uniform::FLOAT_VEC2): { osg::Vec2 value; if (fr[0].getFloat(value[0]) && fr[1].getFloat(value[1])) { uniform.set(value); fr+=2; iteratorAdvanced = true; } break; } case(osg::Uniform::FLOAT_VEC3): { osg::Vec3 value; if (fr[0].getFloat(value[0]) && fr[1].getFloat(value[1]) && fr[2].getFloat(value[2])) { uniform.set(value); fr+=3; iteratorAdvanced = true; } break; } case(osg::Uniform::FLOAT_VEC4): { osg::Vec4 value; if (fr[0].getFloat(value[0]) && fr[1].getFloat(value[1]) && fr[2].getFloat(value[2]) && fr[3].getFloat(value[3])) { uniform.set(value); fr+=4; iteratorAdvanced = true; } break; } case(osg::Uniform::INT): { int value; if (fr[0].getInt(value)) { uniform.set(value); fr+=1; iteratorAdvanced = true; } break; } case(osg::Uniform::INT_VEC2): { int value[2]; if (fr[0].getInt(value[0]) && fr[1].getInt(value[1])) { uniform.set(value[0],value[1]); fr+=2; iteratorAdvanced = true; } break; } case(osg::Uniform::INT_VEC3): { int value[3]; if (fr[0].getInt(value[0]) && fr[1].getInt(value[1]) && fr[2].getInt(value[2])) { uniform.set(value[0],value[1],value[2]); fr+=3; iteratorAdvanced = true; } break; } case(osg::Uniform::INT_VEC4): { int value[4]; if (fr[0].getInt(value[0]) && fr[1].getInt(value[1]) && fr[2].getInt(value[2]) && fr[3].getInt(value[3])) { uniform.set(value[0],value[1],value[2],value[3]); fr+=4; iteratorAdvanced = true; } break; } case(osg::Uniform::FLOAT_MAT2): { osg::notify(osg::WARN)<<"Warning : type mat2 not supported for reading."<<std::endl; break; } case(osg::Uniform::FLOAT_MAT3): { osg::notify(osg::WARN)<<"Warning : type mat3 not supported for reading."<<std::endl; break; } case(osg::Uniform::FLOAT_MAT4): { Matrix value; if( readMatrix(value,fr) ) { uniform.set(value); iteratorAdvanced = true; } break; } default: { break; } } return iteratorAdvanced; } bool Uniform_writeLocalData(const Object& obj,Output& fw) { const Uniform& uniform = static_cast<const Uniform&>(obj); fw.indent() << "name "<< fw.wrapString(uniform.getName()) << std::endl; fw.indent() << Uniform::getTypename( uniform.getType() ) << " "; switch( Uniform::getGlApiType(uniform.getType()) ) { case(osg::Uniform::FLOAT): { float value = 0.0f; uniform.get(value); fw << value; break; } case(osg::Uniform::FLOAT_VEC2): { Vec2 value; uniform.get(value); fw << value; break; } case(osg::Uniform::FLOAT_VEC3): { Vec3 value; uniform.get(value); fw << value; break; } case(osg::Uniform::FLOAT_VEC4): { Vec4 value; uniform.get(value); fw << value; break; } case(osg::Uniform::INT): { int value = 0; uniform.get(value); fw << value; break; } case(osg::Uniform::INT_VEC2): { int value[2]; uniform.get(value[0],value[1]); fw << value[0]<<" "<<value[1]; break; } case(osg::Uniform::INT_VEC3): { int value[3]; uniform.get(value[0],value[1],value[2]); fw << value[0]<<" "<<value[1]<<" "<<value[2]; break; } case(osg::Uniform::INT_VEC4): { int value[4]; uniform.get(value[0],value[1],value[2],value[3]); fw << value[0]<<" "<<value[1]<<" "<<value[2]<<" "<<value[3]; break; } case(osg::Uniform::FLOAT_MAT2): { osg::notify(osg::WARN)<<"Warning : type mat2 not supported for writing."<<std::endl; break; } case(osg::Uniform::FLOAT_MAT3): { osg::notify(osg::WARN)<<"Warning : type mat3 not supported for writing."<<std::endl; break; } case(osg::Uniform::FLOAT_MAT4): { Matrix value; uniform.get(value); writeMatrix(value,fw); break; } default: { break; } } fw << std::endl; return true; } <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file EthereumHost.cpp * @author Gav Wood <[email protected]> * @date 2014 */ #include "EthereumHost.h" #include <set> #include <chrono> #include <thread> #include <libdevcore/Common.h> #include <libp2p/Host.h> #include <libp2p/Session.h> #include <libethcore/Exceptions.h> #include "BlockChain.h" #include "TransactionQueue.h" #include "BlockQueue.h" #include "EthereumPeer.h" #include "DownloadMan.h" using namespace std; using namespace dev; using namespace dev::eth; using namespace p2p; EthereumHost::EthereumHost(BlockChain const& _ch, TransactionQueue& _tq, BlockQueue& _bq, u256 _networkId): HostCapability<EthereumPeer>(), Worker ("ethsync"), m_chain (_ch), m_tq (_tq), m_bq (_bq), m_networkId (_networkId) { m_latestBlockSent = _ch.currentHash(); } EthereumHost::~EthereumHost() { for (auto i: peerSessions()) i.first->cap<EthereumPeer>().get()->abortSync(); } bool EthereumHost::ensureInitialised() { if (!m_latestBlockSent) { // First time - just initialise. m_latestBlockSent = m_chain.currentHash(); clog(NetNote) << "Initialising: latest=" << m_latestBlockSent.abridged(); for (auto const& i: m_tq.transactions()) m_transactionsSent.insert(i.first); return true; } return false; } void EthereumHost::noteNeedsSyncing(EthereumPeer* _who) { // if already downloading hash-chain, ignore. if (isSyncing()) { clog(NetAllDetail) << "Sync in progress: Just set to help out."; if (m_syncer->m_asking == Asking::Blocks) _who->transition(Asking::Blocks); } else // otherwise check to see if we should be downloading... _who->attemptSync(); } void EthereumHost::changeSyncer(EthereumPeer* _syncer) { if (_syncer) clog(NetAllDetail) << "Changing syncer to" << _syncer->session()->socketId(); else clog(NetAllDetail) << "Clearing syncer."; m_syncer = _syncer; if (isSyncing()) { if (_syncer->m_asking == Asking::Blocks) for (auto j: peerSessions()) { auto e = j.first->cap<EthereumPeer>().get(); if (e != _syncer && e->m_asking == Asking::Nothing) e->transition(Asking::Blocks); } } else { // start grabbing next hash chain if there is one. for (auto j: peerSessions()) { j.first->cap<EthereumPeer>()->attemptSync(); if (isSyncing()) return; } clog(NetNote) << "No more peers to sync with."; } } void EthereumHost::noteDoneBlocks(EthereumPeer* _who, bool _clemency) { if (m_man.isComplete()) { // Done our chain-get. clog(NetNote) << "Chain download complete."; // 1/100th for each useful block hash. _who->addRating(m_man.chain().size() / 100); m_man.reset(); } else if (_who->isSyncing()) { if (_clemency) clog(NetNote) << "Chain download failed. Aborted while incomplete."; else { // Done our chain-get. clog(NetNote) << "Chain download failed. Peer with blocks didn't have them all. This peer is bad and should be punished."; m_banned.insert(_who->session()->id()); // We know who you are! _who->disable("Peer sent hashes but was unable to provide the blocks."); } m_man.reset(); } } void EthereumHost::reset() { if (m_syncer) m_syncer->abortSync(); m_man.resetToChain(h256s()); m_latestBlockSent = h256(); m_transactionsSent.clear(); } void EthereumHost::doWork() { bool netChange = ensureInitialised(); auto h = m_chain.currentHash(); // If we've finished our initial sync (including getting all the blocks into the chain so as to reduce invalid transactions), start trading transactions & blocks if (!isSyncing() && m_chain.isKnown(m_latestBlockSent)) { if (m_newTransactions) { m_newTransactions = false; maintainTransactions(); } if (m_newBlocks) { m_newBlocks = false; maintainBlocks(h); } } for (auto p: peerSessions()) if (shared_ptr<EthereumPeer> const& ep = p.first->cap<EthereumPeer>()) ep->tick(); // return netChange; // TODO: Figure out what to do with netChange. (void)netChange; } void EthereumHost::maintainTransactions() { // Send any new transactions. map<std::shared_ptr<EthereumPeer>, h256s> peerTransactions; auto ts = m_tq.transactions(); for (auto const& i: ts) { bool unsent = !m_transactionsSent.count(i.first); for (auto const& p: randomSelection(25, [&](EthereumPeer* p) { return p->m_requireTransactions || (unsent && !p->m_knownTransactions.count(i.first)); })) peerTransactions[p].push_back(i.first); } for (auto p: peerSessions()) if (auto ep = p.first->cap<EthereumPeer>()) { bytes b; unsigned n = 0; for (auto const& h: peerTransactions[ep]) { b += ts[h].rlp(); ++n; } for (auto const& t: ts) m_transactionsSent.insert(t.first); ep->clearKnownTransactions(); if (n || ep->m_requireTransactions) { RLPStream ts; ep->prep(ts, TransactionsPacket, n).appendRaw(b, n); ep->sealAndSend(ts); } ep->m_requireTransactions = false; } } std::vector<std::shared_ptr<EthereumPeer>> EthereumHost::randomSelection(unsigned _percent, std::function<bool(EthereumPeer*)> const& _allow) { std::vector<std::shared_ptr<EthereumPeer>> candidates; candidates.reserve(peerSessions().size()); for (auto const& j: peerSessions()) { auto pp = j.first->cap<EthereumPeer>(); if (_allow(pp.get())) candidates.push_back(pp); } std::vector<std::shared_ptr<EthereumPeer>> ret; for (unsigned i = (peerSessions().size() * _percent + 99) / 100; i-- && candidates.size();) { unsigned n = rand() % candidates.size(); ret.push_back(std::move(candidates[n])); candidates.erase(candidates.begin() + n); } return ret; } void EthereumHost::maintainBlocks(h256 _currentHash) { // Send any new blocks. if (m_chain.details(m_latestBlockSent).totalDifficulty < m_chain.details(_currentHash).totalDifficulty) { clog(NetMessageSummary) << "Sending a new block (current is" << _currentHash << ", was" << m_latestBlockSent << ")"; for (auto const& p: randomSelection(25, [&](EthereumPeer* p){return !p->m_knownBlocks.count(_currentHash); })) { RLPStream ts; p->prep(ts, NewBlockPacket, 2).appendRaw(m_chain.block(), 1).append(m_chain.details().totalDifficulty); Guard l(p->x_knownBlocks); p->sealAndSend(ts); p->m_knownBlocks.clear(); } m_latestBlockSent = _currentHash; } } <commit_msg>Minor cleanup for node's tx management.<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file EthereumHost.cpp * @author Gav Wood <[email protected]> * @date 2014 */ #include "EthereumHost.h" #include <set> #include <chrono> #include <thread> #include <libdevcore/Common.h> #include <libp2p/Host.h> #include <libp2p/Session.h> #include <libethcore/Exceptions.h> #include "BlockChain.h" #include "TransactionQueue.h" #include "BlockQueue.h" #include "EthereumPeer.h" #include "DownloadMan.h" using namespace std; using namespace dev; using namespace dev::eth; using namespace p2p; EthereumHost::EthereumHost(BlockChain const& _ch, TransactionQueue& _tq, BlockQueue& _bq, u256 _networkId): HostCapability<EthereumPeer>(), Worker ("ethsync"), m_chain (_ch), m_tq (_tq), m_bq (_bq), m_networkId (_networkId) { m_latestBlockSent = _ch.currentHash(); } EthereumHost::~EthereumHost() { for (auto i: peerSessions()) i.first->cap<EthereumPeer>().get()->abortSync(); } bool EthereumHost::ensureInitialised() { if (!m_latestBlockSent) { // First time - just initialise. m_latestBlockSent = m_chain.currentHash(); clog(NetNote) << "Initialising: latest=" << m_latestBlockSent.abridged(); for (auto const& i: m_tq.transactions()) m_transactionsSent.insert(i.first); return true; } return false; } void EthereumHost::noteNeedsSyncing(EthereumPeer* _who) { // if already downloading hash-chain, ignore. if (isSyncing()) { clog(NetAllDetail) << "Sync in progress: Just set to help out."; if (m_syncer->m_asking == Asking::Blocks) _who->transition(Asking::Blocks); } else // otherwise check to see if we should be downloading... _who->attemptSync(); } void EthereumHost::changeSyncer(EthereumPeer* _syncer) { if (_syncer) clog(NetAllDetail) << "Changing syncer to" << _syncer->session()->socketId(); else clog(NetAllDetail) << "Clearing syncer."; m_syncer = _syncer; if (isSyncing()) { if (_syncer->m_asking == Asking::Blocks) for (auto j: peerSessions()) { auto e = j.first->cap<EthereumPeer>().get(); if (e != _syncer && e->m_asking == Asking::Nothing) e->transition(Asking::Blocks); } } else { // start grabbing next hash chain if there is one. for (auto j: peerSessions()) { j.first->cap<EthereumPeer>()->attemptSync(); if (isSyncing()) return; } clog(NetNote) << "No more peers to sync with."; } } void EthereumHost::noteDoneBlocks(EthereumPeer* _who, bool _clemency) { if (m_man.isComplete()) { // Done our chain-get. clog(NetNote) << "Chain download complete."; // 1/100th for each useful block hash. _who->addRating(m_man.chain().size() / 100); m_man.reset(); } else if (_who->isSyncing()) { if (_clemency) clog(NetNote) << "Chain download failed. Aborted while incomplete."; else { // Done our chain-get. clog(NetNote) << "Chain download failed. Peer with blocks didn't have them all. This peer is bad and should be punished."; m_banned.insert(_who->session()->id()); // We know who you are! _who->disable("Peer sent hashes but was unable to provide the blocks."); } m_man.reset(); } } void EthereumHost::reset() { if (m_syncer) m_syncer->abortSync(); m_man.resetToChain(h256s()); m_latestBlockSent = h256(); m_transactionsSent.clear(); } void EthereumHost::doWork() { bool netChange = ensureInitialised(); auto h = m_chain.currentHash(); // If we've finished our initial sync (including getting all the blocks into the chain so as to reduce invalid transactions), start trading transactions & blocks if (!isSyncing() && m_chain.isKnown(m_latestBlockSent)) { if (m_newTransactions) { m_newTransactions = false; maintainTransactions(); } if (m_newBlocks) { m_newBlocks = false; maintainBlocks(h); } } for (auto p: peerSessions()) if (shared_ptr<EthereumPeer> const& ep = p.first->cap<EthereumPeer>()) ep->tick(); // return netChange; // TODO: Figure out what to do with netChange. (void)netChange; } void EthereumHost::maintainTransactions() { // Send any new transactions. map<std::shared_ptr<EthereumPeer>, h256s> peerTransactions; auto ts = m_tq.transactions(); for (auto const& i: ts) { bool unsent = !m_transactionsSent.count(i.first); for (auto const& p: randomSelection(25, [&](EthereumPeer* p) { return p->m_requireTransactions || (unsent && !p->m_knownTransactions.count(i.first)); })) peerTransactions[p].push_back(i.first); } for (auto const& t: ts) m_transactionsSent.insert(t.first); for (auto p: peerSessions()) if (auto ep = p.first->cap<EthereumPeer>()) { bytes b; unsigned n = 0; for (auto const& h: peerTransactions[ep]) { ep->m_knownTransactions.insert(h); b += ts[h].rlp(); ++n; } ep->clearKnownTransactions(); if (n || ep->m_requireTransactions) { RLPStream ts; ep->prep(ts, TransactionsPacket, n).appendRaw(b, n); ep->sealAndSend(ts); } ep->m_requireTransactions = false; } } std::vector<std::shared_ptr<EthereumPeer>> EthereumHost::randomSelection(unsigned _percent, std::function<bool(EthereumPeer*)> const& _allow) { std::vector<std::shared_ptr<EthereumPeer>> candidates; candidates.reserve(peerSessions().size()); for (auto const& j: peerSessions()) { auto pp = j.first->cap<EthereumPeer>(); if (_allow(pp.get())) candidates.push_back(pp); } std::vector<std::shared_ptr<EthereumPeer>> ret; for (unsigned i = (peerSessions().size() * _percent + 99) / 100; i-- && candidates.size();) { unsigned n = rand() % candidates.size(); ret.push_back(std::move(candidates[n])); candidates.erase(candidates.begin() + n); } return ret; } void EthereumHost::maintainBlocks(h256 _currentHash) { // Send any new blocks. if (m_chain.details(m_latestBlockSent).totalDifficulty < m_chain.details(_currentHash).totalDifficulty) { clog(NetMessageSummary) << "Sending a new block (current is" << _currentHash << ", was" << m_latestBlockSent << ")"; for (auto const& p: randomSelection(25, [&](EthereumPeer* p){return !p->m_knownBlocks.count(_currentHash); })) { RLPStream ts; p->prep(ts, NewBlockPacket, 2).appendRaw(m_chain.block(), 1).append(m_chain.details().totalDifficulty); Guard l(p->x_knownBlocks); p->sealAndSend(ts); p->m_knownBlocks.clear(); } m_latestBlockSent = _currentHash; } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 Litecoin Developers // Copyright (c) 2013 DogeCoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "irc.h" #include "net.h" #include "strlcpy.h" #include "base58.h" using namespace std; using namespace boost; int nGotIRCAddresses = 0; void ThreadIRCSeed2(void* parg); #pragma pack(push, 1) struct ircaddr { struct in_addr ip; short port; }; #pragma pack(pop) string EncodeAddress(const CService& addr) { struct ircaddr tmp; if (addr.GetInAddr(&tmp.ip)) { tmp.port = htons(addr.GetPort()); vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp)); return string("u") + EncodeBase58Check(vch); } return ""; } bool DecodeAddress(string str, CService& addr) { vector<unsigned char> vch; if (!DecodeBase58Check(str.substr(1), vch)) return false; struct ircaddr tmp; if (vch.size() != sizeof(tmp)) return false; memcpy(&tmp, &vch[0], sizeof(tmp)); addr = CService(tmp.ip, ntohs(tmp.port)); return true; } static bool Send(SOCKET hSocket, const char* pszSend) { if (strstr(pszSend, "PONG") != pszSend) printf("IRC SENDING: %s\n", pszSend); const char* psz = pszSend; const char* pszEnd = psz + strlen(psz); while (psz < pszEnd) { int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL); if (ret < 0) return false; psz += ret; } return true; } bool RecvLineIRC(SOCKET hSocket, string& strLine) { loop { bool fRet = RecvLine(hSocket, strLine); if (fRet) { if (fShutdown) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() >= 1 && vWords[0] == "PING") { strLine[1] = 'O'; strLine += '\r'; Send(hSocket, strLine.c_str()); continue; } } return fRet; } } int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL) { loop { string strLine; strLine.reserve(10000); if (!RecvLineIRC(hSocket, strLine)) return 0; printf("IRC %s\n", strLine.c_str()); if (psz1 && strLine.find(psz1) != string::npos) return 1; if (psz2 && strLine.find(psz2) != string::npos) return 2; if (psz3 && strLine.find(psz3) != string::npos) return 3; if (psz4 && strLine.find(psz4) != string::npos) return 4; } } bool Wait(int nSeconds) { if (fShutdown) return false; printf("IRC waiting %d seconds to reconnect\n", nSeconds); for (int i = 0; i < nSeconds; i++) { if (fShutdown) return false; Sleep(1000); } return true; } bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet) { strRet.clear(); loop { string strLine; if (!RecvLineIRC(hSocket, strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; if (vWords[1] == psz1) { printf("IRC %s\n", strLine.c_str()); strRet = strLine; return true; } } } bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet) { Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str()); string strLine; if (!RecvCodeLine(hSocket, "302", strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 4) return false; string str = vWords[3]; if (str.rfind("@") == string::npos) return false; string strHost = str.substr(str.rfind("@")+1); // Hybrid IRC used by lfnet always returns IP when you userhost yourself, // but in case another IRC is ever used this should work. printf("GetIPFromIRC() got userhost %s\n", strHost.c_str()); CNetAddr addr(strHost, true); if (!addr.IsValid()) return false; ipRet = addr; return true; } void ThreadIRCSeed(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg)); // Make this thread recognisable as the IRC seeding thread RenameThread("bitcoin-ircseed"); try { ThreadIRCSeed2(parg); } catch (std::exception& e) { PrintExceptionContinue(&e, "ThreadIRCSeed()"); } catch (...) { PrintExceptionContinue(NULL, "ThreadIRCSeed()"); } printf("ThreadIRCSeed exited\n"); } void ThreadIRCSeed2(void* parg) { /* Dont advertise on IRC if we don't allow incoming connections */ if (mapArgs.count("-connect") || fNoListen) return; if (!GetBoolArg("-irc", false)) return; printf("ThreadIRCSeed started\n"); int nErrorWait = 10; int nRetryWait = 10; while (!fShutdown) { CService addrConnect("92.243.23.21", 6667); // irc.lfnet.org CService addrIRC("irc.lfnet.org", 6667, true); if (addrIRC.IsValid()) addrConnect = addrIRC; SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) { printf("IRC connect failed\n"); nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname")) { closesocket(hSocket); hSocket = INVALID_SOCKET; nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses CService addrLocal; string strMyName; if (GetLocal(addrLocal, &addrIPv4)) strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); if (strMyName == "") strMyName = strprintf("x%u", GetRand(1000000000)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str()); int nRet = RecvUntil(hSocket, " 004 ", " 433 "); if (nRet != 1) { closesocket(hSocket); hSocket = INVALID_SOCKET; if (nRet == 2) { printf("IRC name already in use\n"); Wait(10); continue; } nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } Sleep(500); // Get our external IP from the IRC server and re-nick before joining the channel CNetAddr addrFromIRC; if (GetIPFromIRC(hSocket, strMyName, addrFromIRC)) { printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str()); if (addrFromIRC.IsRoutable()) { // IRC lets you to re-nick AddLocal(addrFromIRC, LOCAL_IRC); strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); } } if (fTestNet) { Send(hSocket, "JOIN #dogecoinTEST3\r"); Send(hSocket, "WHO #dogecoinTEST3\r"); } else { // randomly join #dogecoin00-#dogecoin99 int channel_number = GetRandInt(100); channel_number = 0; // DogeCoin: for now, just use one channel Send(hSocket, strprintf("JOIN #dogecoin%02d\r", channel_number).c_str()); Send(hSocket, strprintf("WHO #dogecoin%02d\r", channel_number).c_str()); } int64 nStart = GetTime(); string strLine; strLine.reserve(10000); while (!fShutdown && RecvLineIRC(hSocket, strLine)) { if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':') continue; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; char pszName[10000]; pszName[0] = '\0'; if (vWords[1] == "352" && vWords.size() >= 8) { // index 7 is limited to 16 characters // could get full length name at index 10, but would be different from join messages strlcpy(pszName, vWords[7].c_str(), sizeof(pszName)); printf("IRC got who\n"); } if (vWords[1] == "JOIN" && vWords[0].size() > 1) { // :[email protected] JOIN :#channelname strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName)); if (strchr(pszName, '!')) *strchr(pszName, '!') = '\0'; printf("IRC got join\n"); } if (pszName[0] == 'u') { CAddress addr; if (DecodeAddress(pszName, addr)) { addr.nTime = GetAdjustedTime(); if (addrman.Add(addr, addrConnect, 51 * 60)) printf("IRC got new address: %s\n", addr.ToString().c_str()); nGotIRCAddresses++; } else { printf("IRC decode failed\n"); } } } closesocket(hSocket); hSocket = INVALID_SOCKET; if (GetTime() - nStart > 20 * 60) { nErrorWait /= 3; nRetryWait /= 3; } nRetryWait = nRetryWait * 11 / 10; if (!Wait(nRetryWait += 60)) return; } } #ifdef TEST int main(int argc, char *argv[]) { WSADATA wsadata; if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR) { printf("Error at WSAStartup()\n"); return false; } ThreadIRCSeed(NULL); WSACleanup(); return 0; } #endif <commit_msg>network is now over 3k peers , get them to join 50 random channels!<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 Litecoin Developers // Copyright (c) 2013 DogeCoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "irc.h" #include "net.h" #include "strlcpy.h" #include "base58.h" using namespace std; using namespace boost; int nGotIRCAddresses = 0; void ThreadIRCSeed2(void* parg); #pragma pack(push, 1) struct ircaddr { struct in_addr ip; short port; }; #pragma pack(pop) string EncodeAddress(const CService& addr) { struct ircaddr tmp; if (addr.GetInAddr(&tmp.ip)) { tmp.port = htons(addr.GetPort()); vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp)); return string("u") + EncodeBase58Check(vch); } return ""; } bool DecodeAddress(string str, CService& addr) { vector<unsigned char> vch; if (!DecodeBase58Check(str.substr(1), vch)) return false; struct ircaddr tmp; if (vch.size() != sizeof(tmp)) return false; memcpy(&tmp, &vch[0], sizeof(tmp)); addr = CService(tmp.ip, ntohs(tmp.port)); return true; } static bool Send(SOCKET hSocket, const char* pszSend) { if (strstr(pszSend, "PONG") != pszSend) printf("IRC SENDING: %s\n", pszSend); const char* psz = pszSend; const char* pszEnd = psz + strlen(psz); while (psz < pszEnd) { int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL); if (ret < 0) return false; psz += ret; } return true; } bool RecvLineIRC(SOCKET hSocket, string& strLine) { loop { bool fRet = RecvLine(hSocket, strLine); if (fRet) { if (fShutdown) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() >= 1 && vWords[0] == "PING") { strLine[1] = 'O'; strLine += '\r'; Send(hSocket, strLine.c_str()); continue; } } return fRet; } } int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL) { loop { string strLine; strLine.reserve(10000); if (!RecvLineIRC(hSocket, strLine)) return 0; printf("IRC %s\n", strLine.c_str()); if (psz1 && strLine.find(psz1) != string::npos) return 1; if (psz2 && strLine.find(psz2) != string::npos) return 2; if (psz3 && strLine.find(psz3) != string::npos) return 3; if (psz4 && strLine.find(psz4) != string::npos) return 4; } } bool Wait(int nSeconds) { if (fShutdown) return false; printf("IRC waiting %d seconds to reconnect\n", nSeconds); for (int i = 0; i < nSeconds; i++) { if (fShutdown) return false; Sleep(1000); } return true; } bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet) { strRet.clear(); loop { string strLine; if (!RecvLineIRC(hSocket, strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; if (vWords[1] == psz1) { printf("IRC %s\n", strLine.c_str()); strRet = strLine; return true; } } } bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet) { Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str()); string strLine; if (!RecvCodeLine(hSocket, "302", strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 4) return false; string str = vWords[3]; if (str.rfind("@") == string::npos) return false; string strHost = str.substr(str.rfind("@")+1); // Hybrid IRC used by lfnet always returns IP when you userhost yourself, // but in case another IRC is ever used this should work. printf("GetIPFromIRC() got userhost %s\n", strHost.c_str()); CNetAddr addr(strHost, true); if (!addr.IsValid()) return false; ipRet = addr; return true; } void ThreadIRCSeed(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg)); // Make this thread recognisable as the IRC seeding thread RenameThread("bitcoin-ircseed"); try { ThreadIRCSeed2(parg); } catch (std::exception& e) { PrintExceptionContinue(&e, "ThreadIRCSeed()"); } catch (...) { PrintExceptionContinue(NULL, "ThreadIRCSeed()"); } printf("ThreadIRCSeed exited\n"); } void ThreadIRCSeed2(void* parg) { /* Dont advertise on IRC if we don't allow incoming connections */ if (mapArgs.count("-connect") || fNoListen) return; if (!GetBoolArg("-irc", false)) return; printf("ThreadIRCSeed started\n"); int nErrorWait = 10; int nRetryWait = 10; while (!fShutdown) { CService addrConnect("92.243.23.21", 6667); // irc.lfnet.org CService addrIRC("irc.lfnet.org", 6667, true); if (addrIRC.IsValid()) addrConnect = addrIRC; SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) { printf("IRC connect failed\n"); nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname")) { closesocket(hSocket); hSocket = INVALID_SOCKET; nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses CService addrLocal; string strMyName; if (GetLocal(addrLocal, &addrIPv4)) strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); if (strMyName == "") strMyName = strprintf("x%u", GetRand(1000000000)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str()); int nRet = RecvUntil(hSocket, " 004 ", " 433 "); if (nRet != 1) { closesocket(hSocket); hSocket = INVALID_SOCKET; if (nRet == 2) { printf("IRC name already in use\n"); Wait(10); continue; } nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } Sleep(500); // Get our external IP from the IRC server and re-nick before joining the channel CNetAddr addrFromIRC; if (GetIPFromIRC(hSocket, strMyName, addrFromIRC)) { printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str()); if (addrFromIRC.IsRoutable()) { // IRC lets you to re-nick AddLocal(addrFromIRC, LOCAL_IRC); strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); } } if (fTestNet) { Send(hSocket, "JOIN #dogecoinTEST3\r"); Send(hSocket, "WHO #dogecoinTEST3\r"); } else { // randomly join #dogecoin00-#dogecoin99 // network is now over 3k peers , get them to join 50 random channels! // channel_number = 0; int channel_number = GetRandInt(50); Send(hSocket, strprintf("JOIN #dogecoin%02d\r", channel_number).c_str()); Send(hSocket, strprintf("WHO #dogecoin%02d\r", channel_number).c_str()); } int64 nStart = GetTime(); string strLine; strLine.reserve(10000); while (!fShutdown && RecvLineIRC(hSocket, strLine)) { if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':') continue; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; char pszName[10000]; pszName[0] = '\0'; if (vWords[1] == "352" && vWords.size() >= 8) { // index 7 is limited to 16 characters // could get full length name at index 10, but would be different from join messages strlcpy(pszName, vWords[7].c_str(), sizeof(pszName)); printf("IRC got who\n"); } if (vWords[1] == "JOIN" && vWords[0].size() > 1) { // :[email protected] JOIN :#channelname strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName)); if (strchr(pszName, '!')) *strchr(pszName, '!') = '\0'; printf("IRC got join\n"); } if (pszName[0] == 'u') { CAddress addr; if (DecodeAddress(pszName, addr)) { addr.nTime = GetAdjustedTime(); if (addrman.Add(addr, addrConnect, 51 * 60)) printf("IRC got new address: %s\n", addr.ToString().c_str()); nGotIRCAddresses++; } else { printf("IRC decode failed\n"); } } } closesocket(hSocket); hSocket = INVALID_SOCKET; if (GetTime() - nStart > 20 * 60) { nErrorWait /= 3; nRetryWait /= 3; } nRetryWait = nRetryWait * 11 / 10; if (!Wait(nRetryWait += 60)) return; } } #ifdef TEST int main(int argc, char *argv[]) { WSADATA wsadata; if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR) { printf("Error at WSAStartup()\n"); return false; } ThreadIRCSeed(NULL); WSACleanup(); return 0; } #endif <|endoftext|>
<commit_before>#include "RuntimeManager.h" #include "preprocessor/llvm_includes_start.h" #include <llvm/IR/IntrinsicInst.h> #include "preprocessor/llvm_includes_end.h" #include "Stack.h" #include "Utils.h" namespace dev { namespace eth { namespace jit { llvm::StructType* RuntimeManager::getRuntimeDataType() { static llvm::StructType* type = nullptr; if (!type) { llvm::Type* elems[] = { Type::Size, // gas Type::Size, // gasPrice Type::BytePtr, // callData Type::Size, // callDataSize Type::Word, // address Type::Word, // caller Type::Word, // origin Type::Word, // callValue Type::Word, // coinBase Type::Word, // difficulty Type::Word, // gasLimit Type::Size, // blockNumber Type::Size, // blockTimestamp Type::BytePtr, // code Type::Size, // codeSize }; type = llvm::StructType::create(elems, "RuntimeData"); } return type; } llvm::StructType* RuntimeManager::getRuntimeType() { static llvm::StructType* type = nullptr; if (!type) { llvm::Type* elems[] = { Type::RuntimeDataPtr, // data Type::EnvPtr, // Env* Array::getType() // memory }; type = llvm::StructType::create(elems, "Runtime"); } return type; } namespace { llvm::Twine getName(RuntimeData::Index _index) { switch (_index) { default: return ""; case RuntimeData::Gas: return "msg.gas"; case RuntimeData::GasPrice: return "tx.gasprice"; case RuntimeData::CallData: return "msg.data.ptr"; case RuntimeData::CallDataSize: return "msg.data.size"; case RuntimeData::Address: return "this.address"; case RuntimeData::Caller: return "msg.caller"; case RuntimeData::Origin: return "tx.origin"; case RuntimeData::CallValue: return "msg.value"; case RuntimeData::CoinBase: return "block.coinbase"; case RuntimeData::Difficulty: return "block.difficulty"; case RuntimeData::GasLimit: return "block.gaslimit"; case RuntimeData::Number: return "block.number"; case RuntimeData::Timestamp: return "block.timestamp"; case RuntimeData::Code: return "code.ptr"; case RuntimeData::CodeSize: return "code.size"; } } } RuntimeManager::RuntimeManager(llvm::IRBuilder<>& _builder, code_iterator _codeBegin, code_iterator _codeEnd): CompilerHelper(_builder), m_codeBegin(_codeBegin), m_codeEnd(_codeEnd) { m_longjmp = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::eh_sjlj_longjmp); // Unpack data auto rtPtr = getRuntimePtr(); m_dataPtr = m_builder.CreateLoad(m_builder.CreateStructGEP(getRuntimeType(), rtPtr, 0), "dataPtr"); assert(m_dataPtr->getType() == Type::RuntimeDataPtr); m_gasPtr = m_builder.CreateStructGEP(getRuntimeDataType(), m_dataPtr, 0, "gasPtr"); assert(m_gasPtr->getType() == Type::Gas->getPointerTo()); m_memPtr = m_builder.CreateStructGEP(getRuntimeType(), rtPtr, 2, "mem"); assert(m_memPtr->getType() == Array::getType()->getPointerTo()); m_envPtr = m_builder.CreateLoad(m_builder.CreateStructGEP(getRuntimeType(), rtPtr, 1), "env"); assert(m_envPtr->getType() == Type::EnvPtr); m_stackSize = m_builder.CreateAlloca(Type::Size, nullptr, "stackSize"); m_builder.CreateStore(m_builder.getInt64(0), m_stackSize); auto data = m_builder.CreateLoad(m_dataPtr, "data"); for (unsigned i = 0; i < m_dataElts.size(); ++i) m_dataElts[i] = m_builder.CreateExtractValue(data, i, getName(RuntimeData::Index(i))); llvm::Type* checkStackLimitArgs[] = {Type::Size->getPointerTo(), Type::Size, Type::Size, Type::BytePtr}; m_checkStackLimit = llvm::Function::Create(llvm::FunctionType::get(Type::Void, checkStackLimitArgs, false), llvm::Function::PrivateLinkage, "stack.checkSize", getModule()); m_checkStackLimit->setDoesNotThrow(); m_checkStackLimit->setDoesNotCapture(1); auto checkBB = llvm::BasicBlock::Create(_builder.getContext(), "Check", m_checkStackLimit); auto updateBB = llvm::BasicBlock::Create(_builder.getContext(), "Update", m_checkStackLimit); auto outOfStackBB = llvm::BasicBlock::Create(_builder.getContext(), "OutOfStack", m_checkStackLimit); auto currSizePtr = &m_checkStackLimit->getArgumentList().front(); currSizePtr->setName("currSize"); auto max = currSizePtr->getNextNode(); max->setName("max"); auto diff = max->getNextNode(); diff->setName("diff"); auto jmpBuf = diff->getNextNode(); jmpBuf->setName("jmpBuf"); InsertPointGuard guard{m_builder}; m_builder.SetInsertPoint(checkBB); auto currSize = m_builder.CreateLoad(currSizePtr, "cur"); auto maxSize = m_builder.CreateNUWAdd(currSize, max, "maxSize"); auto ok = m_builder.CreateICmpULE(maxSize, m_builder.getInt64(1024), "ok"); m_builder.CreateCondBr(ok, updateBB, outOfStackBB, Type::expectTrue); m_builder.SetInsertPoint(updateBB); auto newSize = m_builder.CreateNSWAdd(currSize, diff); m_builder.CreateStore(newSize, currSizePtr); m_builder.CreateRetVoid(); m_builder.SetInsertPoint(outOfStackBB); abort(jmpBuf); m_builder.CreateUnreachable(); } void RuntimeManager::checkStackLimit(size_t _max, int _diff) { createCall(m_checkStackLimit, {m_stackSize, m_builder.getInt64(_max), m_builder.getInt64(_diff), getJmpBuf()}); } llvm::Value* RuntimeManager::getRuntimePtr() { // Expect first argument of a function to be a pointer to Runtime auto func = m_builder.GetInsertBlock()->getParent(); auto rtPtr = &func->getArgumentList().front(); assert(rtPtr->getType() == Type::RuntimePtr); return rtPtr; } llvm::Value* RuntimeManager::getDataPtr() { if (getMainFunction()) return m_dataPtr; auto rtPtr = getRuntimePtr(); auto dataPtr = m_builder.CreateLoad(m_builder.CreateStructGEP(getRuntimeType(), rtPtr, 0), "data"); assert(dataPtr->getType() == getRuntimeDataType()->getPointerTo()); return dataPtr; } llvm::Value* RuntimeManager::getEnvPtr() { assert(getMainFunction()); // Available only in main function return m_envPtr; } llvm::Value* RuntimeManager::getPtr(RuntimeData::Index _index) { auto ptr = getBuilder().CreateStructGEP(getRuntimeDataType(), getDataPtr(), _index); assert(getRuntimeDataType()->getElementType(_index)->getPointerTo() == ptr->getType()); return ptr; } llvm::Value* RuntimeManager::get(RuntimeData::Index _index) { return m_dataElts[_index]; } void RuntimeManager::set(RuntimeData::Index _index, llvm::Value* _value) { auto ptr = getPtr(_index); assert(ptr->getType() == _value->getType()->getPointerTo()); getBuilder().CreateStore(_value, ptr); } void RuntimeManager::registerReturnData(llvm::Value* _offset, llvm::Value* _size) { auto memPtr = m_builder.CreateBitCast(getMem(), Type::BytePtr->getPointerTo()); auto mem = getBuilder().CreateLoad(memPtr, "memory"); auto returnDataPtr = getBuilder().CreateGEP(mem, _offset); set(RuntimeData::ReturnData, returnDataPtr); auto size64 = getBuilder().CreateTrunc(_size, Type::Size); set(RuntimeData::ReturnDataSize, size64); } void RuntimeManager::registerSuicide(llvm::Value* _balanceAddress) { set(RuntimeData::SuicideDestAddress, _balanceAddress); } void RuntimeManager::exit(ReturnCode _returnCode) { if (m_stack) m_stack->free(); m_builder.CreateRet(Constant::get(_returnCode)); } void RuntimeManager::abort(llvm::Value* _jmpBuf) { auto longjmp = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::eh_sjlj_longjmp); createCall(longjmp, {_jmpBuf}); } llvm::Value* RuntimeManager::get(Instruction _inst) { switch (_inst) { default: assert(false); return nullptr; case Instruction::ADDRESS: return get(RuntimeData::Address); case Instruction::CALLER: return get(RuntimeData::Caller); case Instruction::ORIGIN: return get(RuntimeData::Origin); case Instruction::CALLVALUE: return get(RuntimeData::CallValue); case Instruction::GASPRICE: return get(RuntimeData::GasPrice); case Instruction::COINBASE: return get(RuntimeData::CoinBase); case Instruction::DIFFICULTY: return get(RuntimeData::Difficulty); case Instruction::GASLIMIT: return get(RuntimeData::GasLimit); case Instruction::NUMBER: return get(RuntimeData::Number); case Instruction::TIMESTAMP: return get(RuntimeData::Timestamp); } } llvm::Value* RuntimeManager::getCallData() { return get(RuntimeData::CallData); } llvm::Value* RuntimeManager::getCode() { // OPT Check what is faster //return get(RuntimeData::Code); return m_builder.CreateGlobalStringPtr({reinterpret_cast<char const*>(m_codeBegin), static_cast<size_t>(m_codeEnd - m_codeBegin)}, "code"); } llvm::Value* RuntimeManager::getCodeSize() { return Constant::get(m_codeEnd - m_codeBegin); } llvm::Value* RuntimeManager::getCallDataSize() { auto value = get(RuntimeData::CallDataSize); assert(value->getType() == Type::Size); return getBuilder().CreateZExt(value, Type::Word); } llvm::Value* RuntimeManager::getGas() { return getBuilder().CreateLoad(getGasPtr(), "gas"); } llvm::Value* RuntimeManager::getGasPtr() { assert(getMainFunction()); return m_gasPtr; } llvm::Value* RuntimeManager::getMem() { assert(getMainFunction()); return m_memPtr; } void RuntimeManager::setGas(llvm::Value* _gas) { assert(_gas->getType() == Type::Gas); set(RuntimeData::Gas, _gas); } } } } <commit_msg>Copy gas counter to local function stack (alloca)<commit_after>#include "RuntimeManager.h" #include "preprocessor/llvm_includes_start.h" #include <llvm/IR/IntrinsicInst.h> #include "preprocessor/llvm_includes_end.h" #include "Stack.h" #include "Utils.h" namespace dev { namespace eth { namespace jit { llvm::StructType* RuntimeManager::getRuntimeDataType() { static llvm::StructType* type = nullptr; if (!type) { llvm::Type* elems[] = { Type::Size, // gas Type::Size, // gasPrice Type::BytePtr, // callData Type::Size, // callDataSize Type::Word, // address Type::Word, // caller Type::Word, // origin Type::Word, // callValue Type::Word, // coinBase Type::Word, // difficulty Type::Word, // gasLimit Type::Size, // blockNumber Type::Size, // blockTimestamp Type::BytePtr, // code Type::Size, // codeSize }; type = llvm::StructType::create(elems, "RuntimeData"); } return type; } llvm::StructType* RuntimeManager::getRuntimeType() { static llvm::StructType* type = nullptr; if (!type) { llvm::Type* elems[] = { Type::RuntimeDataPtr, // data Type::EnvPtr, // Env* Array::getType() // memory }; type = llvm::StructType::create(elems, "Runtime"); } return type; } namespace { llvm::Twine getName(RuntimeData::Index _index) { switch (_index) { default: return ""; case RuntimeData::Gas: return "msg.gas"; case RuntimeData::GasPrice: return "tx.gasprice"; case RuntimeData::CallData: return "msg.data.ptr"; case RuntimeData::CallDataSize: return "msg.data.size"; case RuntimeData::Address: return "this.address"; case RuntimeData::Caller: return "msg.caller"; case RuntimeData::Origin: return "tx.origin"; case RuntimeData::CallValue: return "msg.value"; case RuntimeData::CoinBase: return "block.coinbase"; case RuntimeData::Difficulty: return "block.difficulty"; case RuntimeData::GasLimit: return "block.gaslimit"; case RuntimeData::Number: return "block.number"; case RuntimeData::Timestamp: return "block.timestamp"; case RuntimeData::Code: return "code.ptr"; case RuntimeData::CodeSize: return "code.size"; } } } RuntimeManager::RuntimeManager(llvm::IRBuilder<>& _builder, code_iterator _codeBegin, code_iterator _codeEnd): CompilerHelper(_builder), m_codeBegin(_codeBegin), m_codeEnd(_codeEnd) { m_longjmp = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::eh_sjlj_longjmp); // Unpack data auto rtPtr = getRuntimePtr(); m_dataPtr = m_builder.CreateLoad(m_builder.CreateStructGEP(getRuntimeType(), rtPtr, 0), "dataPtr"); assert(m_dataPtr->getType() == Type::RuntimeDataPtr); m_memPtr = m_builder.CreateStructGEP(getRuntimeType(), rtPtr, 2, "mem"); assert(m_memPtr->getType() == Array::getType()->getPointerTo()); m_envPtr = m_builder.CreateLoad(m_builder.CreateStructGEP(getRuntimeType(), rtPtr, 1), "env"); assert(m_envPtr->getType() == Type::EnvPtr); m_stackSize = m_builder.CreateAlloca(Type::Size, nullptr, "stackSize"); m_builder.CreateStore(m_builder.getInt64(0), m_stackSize); auto data = m_builder.CreateLoad(m_dataPtr, "data"); for (unsigned i = 0; i < m_dataElts.size(); ++i) m_dataElts[i] = m_builder.CreateExtractValue(data, i, getName(RuntimeData::Index(i))); m_gasPtr = m_builder.CreateAlloca(Type::Gas, nullptr, "gas.ptr"); m_builder.CreateStore(m_dataElts[RuntimeData::Index::Gas], m_gasPtr); llvm::Type* checkStackLimitArgs[] = {Type::Size->getPointerTo(), Type::Size, Type::Size, Type::BytePtr}; m_checkStackLimit = llvm::Function::Create(llvm::FunctionType::get(Type::Void, checkStackLimitArgs, false), llvm::Function::PrivateLinkage, "stack.checkSize", getModule()); m_checkStackLimit->setDoesNotThrow(); m_checkStackLimit->setDoesNotCapture(1); auto checkBB = llvm::BasicBlock::Create(_builder.getContext(), "Check", m_checkStackLimit); auto updateBB = llvm::BasicBlock::Create(_builder.getContext(), "Update", m_checkStackLimit); auto outOfStackBB = llvm::BasicBlock::Create(_builder.getContext(), "OutOfStack", m_checkStackLimit); auto currSizePtr = &m_checkStackLimit->getArgumentList().front(); currSizePtr->setName("currSize"); auto max = currSizePtr->getNextNode(); max->setName("max"); auto diff = max->getNextNode(); diff->setName("diff"); auto jmpBuf = diff->getNextNode(); jmpBuf->setName("jmpBuf"); InsertPointGuard guard{m_builder}; m_builder.SetInsertPoint(checkBB); auto currSize = m_builder.CreateLoad(currSizePtr, "cur"); auto maxSize = m_builder.CreateNUWAdd(currSize, max, "maxSize"); auto ok = m_builder.CreateICmpULE(maxSize, m_builder.getInt64(1024), "ok"); m_builder.CreateCondBr(ok, updateBB, outOfStackBB, Type::expectTrue); m_builder.SetInsertPoint(updateBB); auto newSize = m_builder.CreateNSWAdd(currSize, diff); m_builder.CreateStore(newSize, currSizePtr); m_builder.CreateRetVoid(); m_builder.SetInsertPoint(outOfStackBB); abort(jmpBuf); m_builder.CreateUnreachable(); } void RuntimeManager::checkStackLimit(size_t _max, int _diff) { createCall(m_checkStackLimit, {m_stackSize, m_builder.getInt64(_max), m_builder.getInt64(_diff), getJmpBuf()}); } llvm::Value* RuntimeManager::getRuntimePtr() { // Expect first argument of a function to be a pointer to Runtime auto func = m_builder.GetInsertBlock()->getParent(); auto rtPtr = &func->getArgumentList().front(); assert(rtPtr->getType() == Type::RuntimePtr); return rtPtr; } llvm::Value* RuntimeManager::getDataPtr() { if (getMainFunction()) return m_dataPtr; auto rtPtr = getRuntimePtr(); auto dataPtr = m_builder.CreateLoad(m_builder.CreateStructGEP(getRuntimeType(), rtPtr, 0), "data"); assert(dataPtr->getType() == getRuntimeDataType()->getPointerTo()); return dataPtr; } llvm::Value* RuntimeManager::getEnvPtr() { assert(getMainFunction()); // Available only in main function return m_envPtr; } llvm::Value* RuntimeManager::getPtr(RuntimeData::Index _index) { auto ptr = getBuilder().CreateStructGEP(getRuntimeDataType(), getDataPtr(), _index); assert(getRuntimeDataType()->getElementType(_index)->getPointerTo() == ptr->getType()); return ptr; } llvm::Value* RuntimeManager::get(RuntimeData::Index _index) { return m_dataElts[_index]; } void RuntimeManager::set(RuntimeData::Index _index, llvm::Value* _value) { auto ptr = getPtr(_index); assert(ptr->getType() == _value->getType()->getPointerTo()); getBuilder().CreateStore(_value, ptr); } void RuntimeManager::registerReturnData(llvm::Value* _offset, llvm::Value* _size) { auto memPtr = m_builder.CreateBitCast(getMem(), Type::BytePtr->getPointerTo()); auto mem = getBuilder().CreateLoad(memPtr, "memory"); auto returnDataPtr = getBuilder().CreateGEP(mem, _offset); set(RuntimeData::ReturnData, returnDataPtr); auto size64 = getBuilder().CreateTrunc(_size, Type::Size); set(RuntimeData::ReturnDataSize, size64); } void RuntimeManager::registerSuicide(llvm::Value* _balanceAddress) { set(RuntimeData::SuicideDestAddress, _balanceAddress); } void RuntimeManager::exit(ReturnCode _returnCode) { if (m_stack) m_stack->free(); auto extGasPtr = m_builder.CreateStructGEP(getRuntimeDataType(), getDataPtr(), RuntimeData::Index::Gas, "msg.gas.ptr"); m_builder.CreateStore(getGas(), extGasPtr); m_builder.CreateRet(Constant::get(_returnCode)); } void RuntimeManager::abort(llvm::Value* _jmpBuf) { auto longjmp = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::eh_sjlj_longjmp); createCall(longjmp, {_jmpBuf}); } llvm::Value* RuntimeManager::get(Instruction _inst) { switch (_inst) { default: assert(false); return nullptr; case Instruction::ADDRESS: return get(RuntimeData::Address); case Instruction::CALLER: return get(RuntimeData::Caller); case Instruction::ORIGIN: return get(RuntimeData::Origin); case Instruction::CALLVALUE: return get(RuntimeData::CallValue); case Instruction::GASPRICE: return get(RuntimeData::GasPrice); case Instruction::COINBASE: return get(RuntimeData::CoinBase); case Instruction::DIFFICULTY: return get(RuntimeData::Difficulty); case Instruction::GASLIMIT: return get(RuntimeData::GasLimit); case Instruction::NUMBER: return get(RuntimeData::Number); case Instruction::TIMESTAMP: return get(RuntimeData::Timestamp); } } llvm::Value* RuntimeManager::getCallData() { return get(RuntimeData::CallData); } llvm::Value* RuntimeManager::getCode() { // OPT Check what is faster //return get(RuntimeData::Code); return m_builder.CreateGlobalStringPtr({reinterpret_cast<char const*>(m_codeBegin), static_cast<size_t>(m_codeEnd - m_codeBegin)}, "code"); } llvm::Value* RuntimeManager::getCodeSize() { return Constant::get(m_codeEnd - m_codeBegin); } llvm::Value* RuntimeManager::getCallDataSize() { auto value = get(RuntimeData::CallDataSize); assert(value->getType() == Type::Size); return getBuilder().CreateZExt(value, Type::Word); } llvm::Value* RuntimeManager::getGas() { return getBuilder().CreateLoad(getGasPtr(), "gas"); } llvm::Value* RuntimeManager::getGasPtr() { assert(getMainFunction()); return m_gasPtr; } llvm::Value* RuntimeManager::getMem() { assert(getMainFunction()); return m_memPtr; } void RuntimeManager::setGas(llvm::Value* _gas) { assert(_gas->getType() == Type::Gas); getBuilder().CreateStore(_gas, getGasPtr()); } } } } <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "MaxQpsThread.h" #include "FEProblem.h" #include "Assembly.h" #include "libmesh/fe_base.h" #include "libmesh/threads.h" #include LIBMESH_INCLUDE_UNORDERED_SET LIBMESH_DEFINE_HASH_POINTERS #include "libmesh/quadrature.h" MaxQpsThread::MaxQpsThread(FEProblemBase & fe_problem) : _fe_problem(fe_problem), _max(0), _max_shape_funcs(0) { } // Splitting Constructor MaxQpsThread::MaxQpsThread(MaxQpsThread & x, Threads::split /*split*/) : _fe_problem(x._fe_problem), _max(x._max), _max_shape_funcs(x._max_shape_funcs) { } void MaxQpsThread::operator()(const ConstElemRange & range) { ParallelUniqueId puid; _tid = puid.id; auto & assem = _fe_problem.assembly(_tid); // For short circuiting reinit. With potential block-specific qrules we // need to track "seen" element types by their subdomains as well. std::set<std::pair<ElemType, SubdomainID>> seen_it; for (const auto & elem : range) { // Only reinit if the element type has not previously been seen if (!seen_it.insert(std::make_pair(elem->type(), elem->subdomain_id())).second) continue; // This ensures we can access the correct qrules if any block-specific // qrules have been created. assem.setCurrentSubdomainID(elem->subdomain_id()); FEType fe_type(FIRST, LAGRANGE); unsigned int dim = elem->dim(); unsigned int side = 0; // we assume that any element will have at least one side ;) // We cannot mess with the FE objects in Assembly, because we might need to request second // derivatives // later on. If we used them, we'd call reinit on them, thus making the call to request second // derivatives harmful (i.e. leading to segfaults/asserts). Thus, we have to use a locally // allocated object here. // // We'll use one for element interiors, which calculates nothing std::unique_ptr<FEBase> fe(FEBase::build(dim, fe_type)); fe->get_nothing(); // And another for element sides, which calculates the minimum // libMesh currently allows for that std::unique_ptr<FEBase> side_fe(FEBase::build(dim, fe_type)); side_fe->get_xyz(); // figure out the number of qps for volume auto qrule = assem.attachQRuleElem(dim, *fe); fe->reinit(elem); if (qrule->n_points() > _max) _max = qrule->n_points(); unsigned int n_shape_funcs = fe->n_shape_functions(); if (n_shape_funcs > _max_shape_funcs) _max_shape_funcs = n_shape_funcs; // figure out the number of qps for the face // NOTE: user might specify higher order rule for faces, thus possibly ending up with more qps // than in the volume auto qrule_face = assem.attachQRuleFace(dim, *side_fe); side_fe->reinit(elem, side); if (qrule_face->n_points() > _max) _max = qrule_face->n_points(); // In initial conditions nodes are enumerated as pretend quadrature points // using the _qp index to access coupled variables. In order to be able to // use _zero (resized according to _max_qps) with _qp, we need to count nodes. if (elem->n_nodes() > _max) _max = elem->n_nodes(); } } void MaxQpsThread::join(const MaxQpsThread & y) { if (y._max > _max) _max = y._max; if (y._max_shape_funcs > _max_shape_funcs) _max_shape_funcs = y._max_shape_funcs; } <commit_msg>Fix MaxQpsThread on meshes with NodeElems<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "MaxQpsThread.h" #include "FEProblem.h" #include "Assembly.h" #include "libmesh/fe_base.h" #include "libmesh/threads.h" #include LIBMESH_INCLUDE_UNORDERED_SET LIBMESH_DEFINE_HASH_POINTERS #include "libmesh/quadrature.h" MaxQpsThread::MaxQpsThread(FEProblemBase & fe_problem) : _fe_problem(fe_problem), _max(0), _max_shape_funcs(0) { } // Splitting Constructor MaxQpsThread::MaxQpsThread(MaxQpsThread & x, Threads::split /*split*/) : _fe_problem(x._fe_problem), _max(x._max), _max_shape_funcs(x._max_shape_funcs) { } void MaxQpsThread::operator()(const ConstElemRange & range) { ParallelUniqueId puid; _tid = puid.id; auto & assem = _fe_problem.assembly(_tid); // For short circuiting reinit. With potential block-specific qrules we // need to track "seen" element types by their subdomains as well. std::set<std::pair<ElemType, SubdomainID>> seen_it; for (const auto & elem : range) { // Only reinit if the element type has not previously been seen if (!seen_it.insert(std::make_pair(elem->type(), elem->subdomain_id())).second) continue; // This ensures we can access the correct qrules if any block-specific // qrules have been created. assem.setCurrentSubdomainID(elem->subdomain_id()); FEType fe_type(FIRST, LAGRANGE); unsigned int dim = elem->dim(); unsigned int side = 0; // we assume that any element will have at least one side ;) // We cannot mess with the FE objects in Assembly, because we might need to request second // derivatives // later on. If we used them, we'd call reinit on them, thus making the call to request second // derivatives harmful (i.e. leading to segfaults/asserts). Thus, we have to use a locally // allocated object here. // // We'll use one for element interiors, which calculates nothing std::unique_ptr<FEBase> fe(FEBase::build(dim, fe_type)); fe->get_nothing(); // And another for element sides, which calculates the minimum // libMesh currently allows for that std::unique_ptr<FEBase> side_fe(FEBase::build(dim, fe_type)); side_fe->get_xyz(); // figure out the number of qps for volume auto qrule = assem.attachQRuleElem(dim, *fe); fe->reinit(elem); if (qrule->n_points() > _max) _max = qrule->n_points(); unsigned int n_shape_funcs = fe->n_shape_functions(); if (n_shape_funcs > _max_shape_funcs) _max_shape_funcs = n_shape_funcs; // figure out the number of qps for the face // NOTE: user might specify higher order rule for faces, thus possibly ending up with more qps // than in the volume auto qrule_face = assem.attachQRuleFace(dim, *side_fe); if (dim > 0) // side reinit in 0D makes no sense, but we may have NodeElems { side_fe->reinit(elem, side); if (qrule_face->n_points() > _max) _max = qrule_face->n_points(); } // In initial conditions nodes are enumerated as pretend quadrature points // using the _qp index to access coupled variables. In order to be able to // use _zero (resized according to _max_qps) with _qp, we need to count nodes. if (elem->n_nodes() > _max) _max = elem->n_nodes(); } } void MaxQpsThread::join(const MaxQpsThread & y) { if (y._max > _max) _max = y._max; if (y._max_shape_funcs > _max_shape_funcs) _max_shape_funcs = y._max_shape_funcs; } <|endoftext|>
<commit_before>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "MultiApp.h" // Moose #include "AppFactory.h" #include "SetupInterface.h" #include "Executioner.h" #include "UserObject.h" #include "FEProblem.h" #include "Output.h" #include "AppFactory.h" // libMesh #include "libmesh/mesh_tools.h" #include <iostream> #include <iomanip> template<> InputParameters validParams<MultiApp>() { InputParameters params = validParams<MooseObject>(); params.addPrivateParam<bool>("use_displaced_mesh", false); std::ostringstream app_types_strings; registeredMooseAppIterator it = AppFactory::instance()->registeredObjectsBegin(); while(it != AppFactory::instance()->registeredObjectsEnd()) { app_types_strings << it->first; ++it; if(it != AppFactory::instance()->registeredObjectsEnd()) app_types_strings<< ", "; } MooseEnum app_types_options(app_types_strings.str()); params.addRequiredParam<MooseEnum>("app_type", app_types_options, "The type of application to build."); params.addRequiredParam<std::vector<Real> >("positions", "The positions of the App locations. Each set of 3 values will represent a Point."); params.addRequiredParam<std::vector<std::string> >("input_files", "The input file for each App. If this parameter only contains one input file it will be used for all of the Apps."); params.addPrivateParam<MPI_Comm>("_mpi_comm"); MooseEnum execute_options(SetupInterface::getExecuteOptions()); execute_options = "timestep_begin"; // set the default params.addParam<MooseEnum>("execute_on", execute_options, "Set to (residual|jacobian|timestep|timestep_begin|custom) to execute only at that moment"); params.addPrivateParam<std::string>("built_by_action", "add_multi_app"); return params; } MultiApp::MultiApp(const std::string & name, InputParameters parameters): MooseObject(name, parameters), _fe_problem(getParam<FEProblem *>("_fe_problem")), _app_type(getParam<MooseEnum>("app_type")), _positions_vec(getParam<std::vector<Real> >("positions")), _input_files(getParam<std::vector<std::string> >("input_files")), _orig_comm(getParam<MPI_Comm>("_mpi_comm")), _execute_on(getParam<MooseEnum>("execute_on")) { { // Read the positions out of the vector unsigned int num_vec_entries = _positions_vec.size(); mooseAssert(num_vec_entries % LIBMESH_DIM == 0, "Wrong number of entries in 'positions'"); _positions.reserve(num_vec_entries / LIBMESH_DIM); for(unsigned int i=0; i<num_vec_entries; i+=3) _positions.push_back(Point(_positions_vec[i], _positions_vec[i+1], _positions_vec[i+2])); } _total_num_apps = _positions.size(); mooseAssert(_input_files.size() == 1 || _positions.size() == _input_files.size(), "Number of positions and input files are not the same!"); /// Set up our Comm and set the number of apps we're going to be working on buildComm(); MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm); _apps.resize(_my_num_apps); for(unsigned int i=0; i<_my_num_apps; i++) { InputParameters app_params = AppFactory::instance()->getValidParams(_app_type); MooseApp * app = AppFactory::instance()->create(_app_type, "multi_app", app_params); std::ostringstream output_base; // Create an output base by taking the output base of the master problem and appending // the name of the multiapp + a number to it output_base << _fe_problem->out().fileBase() << "_" << _name << std::setw(_total_num_apps/10) << std::setprecision(0) << std::setfill('0') << std::right << _first_local_app + i; _apps[i] = app; std::string input_file = ""; if(_input_files.size() == 1) // If only one input file was provide, use it for all the solves input_file = _input_files[0]; else input_file = _input_files[_first_local_app+i]; app->setInputFileName(input_file); app->setOutputFileBase(output_base.str()); app->setupOptions(); app->runInputFile(); } // Swap back Moose::swapLibMeshComm(swapped); } MultiApp::~MultiApp() { for(unsigned int i=0; i<_my_num_apps; i++) delete _apps[i]; } Executioner * MultiApp::getExecutioner(unsigned int app) { return _apps[globalAppToLocal(app)]->getExecutioner(); } MeshTools::BoundingBox MultiApp::getBoundingBox(unsigned int app) { FEProblem * problem = appProblem(app); MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm); MooseMesh & mesh = problem->mesh(); MeshTools::BoundingBox bbox = MeshTools::bounding_box(mesh); Moose::swapLibMeshComm(swapped); return bbox; } FEProblem * MultiApp::appProblem(unsigned int app) { unsigned int local_app = globalAppToLocal(app); FEProblem * problem = dynamic_cast<FEProblem *>(&_apps[local_app]->getExecutioner()->problem()); mooseAssert(problem, "Not an FEProblem!"); return problem; } const UserObject & MultiApp::appUserObjectBase(unsigned int app, const std::string & name) { return appProblem(app)->getUserObjectBase(name); } Real MultiApp::appPostprocessorValue(unsigned int app, const std::string & name) { return appProblem(app)->getPostprocessorValue(name); } bool MultiApp::hasLocalApp(unsigned int global_app) { if(global_app >= _first_local_app && global_app <= _first_local_app + (_my_num_apps-1)) return true; return false; } void MultiApp::buildComm() { MPI_Comm_size(_orig_comm, (int*)&_orig_num_procs); MPI_Comm_rank(_orig_comm, (int*)&_orig_rank); // If we have more apps than processors then we're just going to divide up the work if(_total_num_apps >= _orig_num_procs) { _my_comm = MPI_COMM_SELF; _my_rank = 0; _my_num_apps = _total_num_apps/_orig_num_procs; _first_local_app = _my_num_apps * _orig_rank; // The last processor will pick up any extra apps if(_orig_rank == _orig_num_procs - 1) _my_num_apps += _total_num_apps % _orig_num_procs; return; } // In this case we need to divide up the processors that are going to work on each app int rank; MPI_Comm_rank(_orig_comm, &rank); // sleep(rank); int procs_per_app = _orig_num_procs / _total_num_apps; int my_app = rank / procs_per_app; int procs_for_my_app = procs_per_app; if((unsigned int) my_app >= _total_num_apps-1) // The last app will gain any left-over procs { my_app = _total_num_apps - 1; procs_for_my_app += _orig_num_procs % _total_num_apps; } // Only one app here _first_local_app = my_app; _my_num_apps = 1; std::vector<int> ranks_in_my_group(procs_for_my_app); // Add all the processors in that are in my group for(int i=0; i<procs_for_my_app; i++) ranks_in_my_group[i] = (my_app * procs_per_app) + i; MPI_Group orig_group, new_group; // Extract the original group handle MPI_Comm_group(_orig_comm, &orig_group); // Create a group MPI_Group_incl(orig_group, procs_for_my_app, &ranks_in_my_group[0], &new_group); // Create new communicator MPI_Comm_create(_orig_comm, new_group, &_my_comm); MPI_Comm_rank(_my_comm, (int*)&_my_rank); } unsigned int MultiApp::globalAppToLocal(unsigned int global_app) { if(global_app >= _first_local_app && global_app <= _first_local_app + (_my_num_apps-1)) return global_app-_first_local_app; std::cout<<_first_local_app<<" "<<global_app<<std::endl; mooseError("Invalid global_app!"); } <commit_msg>allow reading positions from a file ref #1845<commit_after>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "MultiApp.h" // Moose #include "AppFactory.h" #include "SetupInterface.h" #include "Executioner.h" #include "UserObject.h" #include "FEProblem.h" #include "Output.h" #include "AppFactory.h" // libMesh #include "libmesh/mesh_tools.h" #include <iostream> #include <iomanip> #include <iterator> #include <fstream> #include <vector> #include <algorithm> template<> InputParameters validParams<MultiApp>() { InputParameters params = validParams<MooseObject>(); params.addPrivateParam<bool>("use_displaced_mesh", false); std::ostringstream app_types_strings; registeredMooseAppIterator it = AppFactory::instance()->registeredObjectsBegin(); while(it != AppFactory::instance()->registeredObjectsEnd()) { app_types_strings << it->first; ++it; if(it != AppFactory::instance()->registeredObjectsEnd()) app_types_strings<< ", "; } MooseEnum app_types_options(app_types_strings.str()); params.addRequiredParam<MooseEnum>("app_type", app_types_options, "The type of application to build."); params.addParam<std::vector<Real> >("positions", "The positions of the App locations. Each set of 3 values will represent a Point. Either this must be supplied or 'positions_file'"); params.addParam<FileName>("positions_file", "A filename that should be looked in for positions. Each set of 3 values in that file will represent a Point. Either this must be supplied or 'positions'"); params.addRequiredParam<std::vector<std::string> >("input_files", "The input file for each App. If this parameter only contains one input file it will be used for all of the Apps."); params.addPrivateParam<MPI_Comm>("_mpi_comm"); MooseEnum execute_options(SetupInterface::getExecuteOptions()); execute_options = "timestep_begin"; // set the default params.addParam<MooseEnum>("execute_on", execute_options, "Set to (residual|jacobian|timestep|timestep_begin|custom) to execute only at that moment"); params.addPrivateParam<std::string>("built_by_action", "add_multi_app"); return params; } MultiApp::MultiApp(const std::string & name, InputParameters parameters): MooseObject(name, parameters), _fe_problem(getParam<FEProblem *>("_fe_problem")), _app_type(getParam<MooseEnum>("app_type")), _input_files(getParam<std::vector<std::string> >("input_files")), _orig_comm(getParam<MPI_Comm>("_mpi_comm")), _execute_on(getParam<MooseEnum>("execute_on")) { if(isParamValid("positions")) _positions_vec = getParam<std::vector<Real> >("positions"); else if(isParamValid("positions_file")) { // Read the file on the root processor then broadcast it if(libMesh::processor_id() == 0) { std::ifstream is(getParam<FileName>("positions_file").c_str()); std::istream_iterator<Real> begin(is), end; _positions_vec.insert(_positions_vec.begin(), begin, end); } unsigned int num_values = _positions_vec.size(); Parallel::broadcast(num_values); _positions_vec.resize(num_values); Parallel::broadcast(_positions_vec); std::cerr<<_positions_vec.size()<<std::endl; } else mooseError("Must supply either 'positions' or 'positions_file' for MultiApp "<<_name); { // Read the positions out of the vector unsigned int num_vec_entries = _positions_vec.size(); mooseAssert(num_vec_entries % LIBMESH_DIM == 0, "Wrong number of entries in 'positions'"); _positions.reserve(num_vec_entries / LIBMESH_DIM); for(unsigned int i=0; i<num_vec_entries; i+=3) _positions.push_back(Point(_positions_vec[i], _positions_vec[i+1], _positions_vec[i+2])); } _total_num_apps = _positions.size(); mooseAssert(_input_files.size() == 1 || _positions.size() == _input_files.size(), "Number of positions and input files are not the same!"); /// Set up our Comm and set the number of apps we're going to be working on buildComm(); MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm); _apps.resize(_my_num_apps); for(unsigned int i=0; i<_my_num_apps; i++) { InputParameters app_params = AppFactory::instance()->getValidParams(_app_type); MooseApp * app = AppFactory::instance()->create(_app_type, "multi_app", app_params); std::ostringstream output_base; // Create an output base by taking the output base of the master problem and appending // the name of the multiapp + a number to it output_base << _fe_problem->out().fileBase() << "_" << _name << std::setw(_total_num_apps/10) << std::setprecision(0) << std::setfill('0') << std::right << _first_local_app + i; _apps[i] = app; std::string input_file = ""; if(_input_files.size() == 1) // If only one input file was provide, use it for all the solves input_file = _input_files[0]; else input_file = _input_files[_first_local_app+i]; app->setInputFileName(input_file); app->setOutputFileBase(output_base.str()); app->setupOptions(); app->runInputFile(); } // Swap back Moose::swapLibMeshComm(swapped); } MultiApp::~MultiApp() { for(unsigned int i=0; i<_my_num_apps; i++) delete _apps[i]; } Executioner * MultiApp::getExecutioner(unsigned int app) { return _apps[globalAppToLocal(app)]->getExecutioner(); } MeshTools::BoundingBox MultiApp::getBoundingBox(unsigned int app) { FEProblem * problem = appProblem(app); MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm); MooseMesh & mesh = problem->mesh(); MeshTools::BoundingBox bbox = MeshTools::bounding_box(mesh); Moose::swapLibMeshComm(swapped); return bbox; } FEProblem * MultiApp::appProblem(unsigned int app) { unsigned int local_app = globalAppToLocal(app); FEProblem * problem = dynamic_cast<FEProblem *>(&_apps[local_app]->getExecutioner()->problem()); mooseAssert(problem, "Not an FEProblem!"); return problem; } const UserObject & MultiApp::appUserObjectBase(unsigned int app, const std::string & name) { return appProblem(app)->getUserObjectBase(name); } Real MultiApp::appPostprocessorValue(unsigned int app, const std::string & name) { return appProblem(app)->getPostprocessorValue(name); } bool MultiApp::hasLocalApp(unsigned int global_app) { if(global_app >= _first_local_app && global_app <= _first_local_app + (_my_num_apps-1)) return true; return false; } void MultiApp::buildComm() { MPI_Comm_size(_orig_comm, (int*)&_orig_num_procs); MPI_Comm_rank(_orig_comm, (int*)&_orig_rank); // If we have more apps than processors then we're just going to divide up the work if(_total_num_apps >= _orig_num_procs) { _my_comm = MPI_COMM_SELF; _my_rank = 0; _my_num_apps = _total_num_apps/_orig_num_procs; _first_local_app = _my_num_apps * _orig_rank; // The last processor will pick up any extra apps if(_orig_rank == _orig_num_procs - 1) _my_num_apps += _total_num_apps % _orig_num_procs; return; } // In this case we need to divide up the processors that are going to work on each app int rank; MPI_Comm_rank(_orig_comm, &rank); // sleep(rank); int procs_per_app = _orig_num_procs / _total_num_apps; int my_app = rank / procs_per_app; int procs_for_my_app = procs_per_app; if((unsigned int) my_app >= _total_num_apps-1) // The last app will gain any left-over procs { my_app = _total_num_apps - 1; procs_for_my_app += _orig_num_procs % _total_num_apps; } // Only one app here _first_local_app = my_app; _my_num_apps = 1; std::vector<int> ranks_in_my_group(procs_for_my_app); // Add all the processors in that are in my group for(int i=0; i<procs_for_my_app; i++) ranks_in_my_group[i] = (my_app * procs_per_app) + i; MPI_Group orig_group, new_group; // Extract the original group handle MPI_Comm_group(_orig_comm, &orig_group); // Create a group MPI_Group_incl(orig_group, procs_for_my_app, &ranks_in_my_group[0], &new_group); // Create new communicator MPI_Comm_create(_orig_comm, new_group, &_my_comm); MPI_Comm_rank(_my_comm, (int*)&_my_rank); } unsigned int MultiApp::globalAppToLocal(unsigned int global_app) { if(global_app >= _first_local_app && global_app <= _first_local_app + (_my_num_apps-1)) return global_app-_first_local_app; std::cout<<_first_local_app<<" "<<global_app<<std::endl; mooseError("Invalid global_app!"); } <|endoftext|>
<commit_before>#include "PetscSupport.h" #ifdef LIBMESH_HAVE_PETSC #include "Moose.h" #include "MooseSystem.h" #include "Executioner.h" //libMesh Includes #include "libmesh_common.h" #include "equation_systems.h" #include "nonlinear_implicit_system.h" #include "linear_implicit_system.h" #include "sparse_matrix.h" #include "petsc_vector.h" #include "petsc_matrix.h" #include "petsc_linear_solver.h" #include "petsc_preconditioner.h" //PETSc includes #include <petsc.h> #include <petscsnes.h> #include <petscksp.h> #include <private/kspimpl.h> #include <private/snesimpl.h> namespace Moose { namespace PetscSupport { /** The following functionality is encapsulated in the Moose ExecutionBlock but * still needed by Pronghorn for the time being */ void petscParseOptions(GetPot & input_file) { // Set PETSC options: int num_petsc_opt = input_file.vector_variable_size("Execution/petsc_options"); for(int i=0;i<num_petsc_opt;i++) { std::string petsc_opts = input_file("Execution/petsc_options","", i); PetscOptionsSetValue(petsc_opts.c_str(),PETSC_NULL); } // end of i-LOOP... int num_petsc_opt0 = input_file.vector_variable_size("Execution/petsc_options_iname"); int num_petsc_opt1 = input_file.vector_variable_size("Execution/petsc_options_value"); if(num_petsc_opt0 != num_petsc_opt1) { printf("Error in reading petsc_options_xxxxx\n"); libmesh_error(); } for(int i=0;i<num_petsc_opt0;i++) { std::string petsc_opts_iname = input_file("Execution/petsc_options_iname", "", i); std::string petsc_opts_value = input_file("Execution/petsc_options_value", "", i); PetscOptionsSetValue(petsc_opts_iname.c_str(),petsc_opts_value.c_str()); } // end of i-LOOP... } PetscErrorCode petscConverged(KSP ksp,PetscInt n,PetscReal rnorm,KSPConvergedReason *reason,void *dummy) { MooseSystem *moose_system = (MooseSystem *) dummy; // C strikes *reason = KSP_CONVERGED_ITERATING; //If it's the beginning of a new set of iterations, reset last_rnorm if(!n) moose_system->_last_rnorm = 1e99; PetscReal norm_diff = std::fabs(rnorm - moose_system->_last_rnorm); if(norm_diff < moose_system->_l_abs_step_tol) { *reason = KSP_CONVERGED_RTOL; return(0); } moose_system->_last_rnorm = rnorm; // From here, we want the default behavior of the KSPDefaultConverged // test, but we don't want PETSc to die in that function with a // CHKERRQ call... therefore we Push/Pop a different error handler // and then call KSPDefaultConverged(). Finally, if we hit the // max iteration count, we want to set KSP_CONVERGED_ITS. PetscPushErrorHandler(PetscReturnErrorHandler,/* void* ctx= */PETSC_NULL); // As of PETSc 3.0.0, you must call KSPDefaultConverged with a // non-NULL context pointer which must be created with // KSPDefaultConvergedCreate(), and destroyed with // KSPDefaultConvergedDestroy(). /*PetscErrorCode ierr = */ KSPDefaultConverged(ksp, n, rnorm, reason, dummy); // Pop the Error handler we pushed on the stack to go back // to default PETSc error handling behavior. PetscPopErrorHandler(); // If we hit max its then we consider that converged if (n >= ksp->max_it) *reason = KSP_CONVERGED_ITS; return 0; } PetscErrorCode petscNonlinearConverged(SNES snes,PetscInt it,PetscReal xnorm,PetscReal pnorm,PetscReal fnorm,SNESConvergedReason *reason,void * dummy) { MooseSystem *moose_system = (MooseSystem *) dummy; // C strikes // unused // TransientNonlinearImplicitSystem * system = dynamic_cast<TransientNonlinearImplicitSystem *>(&_equation_system->get_system("NonlinearSystem")); // for(unsigned int var = 0; var < system->n_vars(); var++) // std::cout<<var<<": "<<system->calculate_norm(*system->rhs,var,DISCRETE_L2)<<std::endl; *reason = SNES_CONVERGED_ITERATING; if (!it) { /* set parameter for default relative tolerance convergence test */ snes->ttol = fnorm*snes->rtol; moose_system->_initial_residual = fnorm; } if (fnorm != fnorm) { PetscInfo(snes,"Failed to converged, function norm is NaN\n"); *reason = SNES_DIVERGED_FNORM_NAN; } else if (fnorm < snes->abstol) { PetscInfo2(snes,"Converged due to function norm %G < %G\n",fnorm,snes->abstol); *reason = SNES_CONVERGED_FNORM_ABS; } else if (snes->nfuncs >= snes->max_funcs) { PetscInfo2(snes,"Exceeded maximum number of function evaluations: %D > %D\n",snes->nfuncs,snes->max_funcs); *reason = SNES_DIVERGED_FUNCTION_COUNT; } else if(fnorm >= moose_system->_initial_residual * (1.0/snes->rtol)) { PetscInfo2(snes,"Nonlinear solve was blowing up!",snes->nfuncs,snes->max_funcs); *reason = SNES_DIVERGED_LS_FAILURE; } if (it && !*reason) { if (fnorm <= snes->ttol) { PetscInfo2(snes,"Converged due to function norm %G < %G (relative tolerance)\n",fnorm,snes->ttol); *reason = SNES_CONVERGED_FNORM_RELATIVE; } else if (pnorm < snes->xtol*xnorm) { PetscInfo3(snes,"Converged due to small update length: %G < %G * %G\n",pnorm,snes->xtol,xnorm); *reason = SNES_CONVERGED_PNORM_RELATIVE; } } return(0); } /** * Called at the beginning of every nonlinear step (before Jacobian is formed) */ PetscErrorCode petscNewtonUpdate(SNES snes, PetscInt step) { void *ctx = NULL; SNESGetApplicationContext(snes, &ctx); if (ctx != NULL) { Executioner *exec = (Executioner *) ctx; // C strikes again exec->updateNewtonStep(); exec->onNewtonUpdate(); } return 0; } void petscSetDefaults(MooseSystem &moose_system, Executioner *executioner) { PetscNonlinearSolver<Number> * petsc_solver = dynamic_cast<PetscNonlinearSolver<Number> *>(moose_system.getNonlinearSystem()->nonlinear_solver.get()); SNES snes = petsc_solver->snes(); KSP ksp; SNESGetKSP(snes, &ksp); KSPSetPreconditionerSide(ksp, PC_RIGHT); SNESSetMaxLinearSolveFailures(snes, 1000000); SNESLineSearchSetPostCheck(snes, dampedCheck, moose_system.getEquationSystems()); #if PETSC_VERSION_LESS_THAN(3,0,0) KSPSetConvergenceTest(ksp, petscConverged, &moose_system); SNESSetConvergenceTest(snes, petscNonlinearConverged, &moose_system); #else // In 3.0.0, the context pointer must actually be used, and the // final argument to KSPSetConvergenceTest() is a pointer to a // routine for destroying said private data context. In this case, // we use the default context provided by PETSc in addition to // a few other tests. { PetscErrorCode ierr = KSPSetConvergenceTest(ksp, petscConverged, &moose_system, PETSC_NULL); CHKERRABORT(libMesh::COMM_WORLD,ierr); } #endif SNESSetUpdate(snes, petscNewtonUpdate); SNESSetApplicationContext(snes, (void *) executioner); /* PC pc; KSPGetPC(ksp,&pc); PCSetType(pc,PCSHELL); PCShellSetSetUp(pc,MatrixFreePreconditionerSetup); PCShellSetApply(pc,MatrixFreePreconditioner); */ } // PetscErrorCode petscPhysicsBasedLineSearch(SNES snes,void *lsctx,Vec x,Vec /*f*/,Vec g,Vec y,Vec w, PetscReal /*fnorm*/,PetscReal *ynorm,PetscReal *gnorm,PetscTruth *flag) PetscErrorCode dampedCheck(SNES snes, Vec x, Vec y, Vec w, void *lsctx, PetscTruth * changed_y, PetscTruth * changed_w) { //w = updated solution = x+ scaling*y //x = current solution //y = updates. // for simple newton use w = x-y int ierr; Real damping = 1.0; EquationSystems * equation_systems = static_cast<EquationSystems *>(lsctx); MooseSystem * moose_system = equation_systems->parameters.get<MooseSystem *>("moose_system"); MeshBase & mesh = equation_systems->get_mesh(); TransientNonlinearImplicitSystem& system = equation_systems->get_system<TransientNonlinearImplicitSystem> ("NonlinearSystem"); unsigned int sys = system.number(); //create PetscVector PetscVector<Number> update_vec_x(x); PetscVector<Number> update_vec_y(y); PetscVector<Number> update_vec_w(w); damping = moose_system->compute_damping(update_vec_w, update_vec_y); if(damping != 1.0) { VecScale(y, damping); *changed_y = PETSC_TRUE; } return(ierr); } } } #endif //LIBMESH_HAVE_PETSC <commit_msg>small change<commit_after>#include "PetscSupport.h" #ifdef LIBMESH_HAVE_PETSC #include "Moose.h" #include "MooseSystem.h" #include "Executioner.h" //libMesh Includes #include "libmesh_common.h" #include "equation_systems.h" #include "nonlinear_implicit_system.h" #include "linear_implicit_system.h" #include "sparse_matrix.h" #include "petsc_vector.h" #include "petsc_matrix.h" #include "petsc_linear_solver.h" #include "petsc_preconditioner.h" //PETSc includes #include <petsc.h> #include <petscsnes.h> #include <petscksp.h> #include <private/kspimpl.h> #include <private/snesimpl.h> namespace Moose { namespace PetscSupport { /** The following functionality is encapsulated in the Moose ExecutionBlock but * still needed by Pronghorn for the time being */ void petscParseOptions(GetPot & input_file) { // Set PETSC options: int num_petsc_opt = input_file.vector_variable_size("Execution/petsc_options"); for(int i=0;i<num_petsc_opt;i++) { std::string petsc_opts = input_file("Execution/petsc_options","", i); PetscOptionsSetValue(petsc_opts.c_str(),PETSC_NULL); } // end of i-LOOP... int num_petsc_opt0 = input_file.vector_variable_size("Execution/petsc_options_iname"); int num_petsc_opt1 = input_file.vector_variable_size("Execution/petsc_options_value"); if(num_petsc_opt0 != num_petsc_opt1) { printf("Error in reading petsc_options_xxxxx\n"); libmesh_error(); } for(int i=0;i<num_petsc_opt0;i++) { std::string petsc_opts_iname = input_file("Execution/petsc_options_iname", "", i); std::string petsc_opts_value = input_file("Execution/petsc_options_value", "", i); PetscOptionsSetValue(petsc_opts_iname.c_str(),petsc_opts_value.c_str()); } // end of i-LOOP... } PetscErrorCode petscConverged(KSP ksp,PetscInt n,PetscReal rnorm,KSPConvergedReason *reason,void *dummy) { MooseSystem *moose_system = (MooseSystem *) dummy; // C strikes *reason = KSP_CONVERGED_ITERATING; //If it's the beginning of a new set of iterations, reset last_rnorm if(!n) moose_system->_last_rnorm = 1e99; PetscReal norm_diff = std::fabs(rnorm - moose_system->_last_rnorm); if(norm_diff < moose_system->_l_abs_step_tol) { *reason = KSP_CONVERGED_RTOL; return(0); } moose_system->_last_rnorm = rnorm; // From here, we want the default behavior of the KSPDefaultConverged // test, but we don't want PETSc to die in that function with a // CHKERRQ call... therefore we Push/Pop a different error handler // and then call KSPDefaultConverged(). Finally, if we hit the // max iteration count, we want to set KSP_CONVERGED_ITS. PetscPushErrorHandler(PetscReturnErrorHandler,/* void* ctx= */PETSC_NULL); // As of PETSc 3.0.0, you must call KSPDefaultConverged with a // non-NULL context pointer which must be created with // KSPDefaultConvergedCreate(), and destroyed with // KSPDefaultConvergedDestroy(). /*PetscErrorCode ierr = */ KSPDefaultConverged(ksp, n, rnorm, reason, dummy); // Pop the Error handler we pushed on the stack to go back // to default PETSc error handling behavior. PetscPopErrorHandler(); // If we hit max its then we consider that converged if (n >= ksp->max_it) *reason = KSP_CONVERGED_ITS; return 0; } PetscErrorCode petscNonlinearConverged(SNES snes,PetscInt it,PetscReal xnorm,PetscReal pnorm,PetscReal fnorm,SNESConvergedReason *reason,void * dummy) { MooseSystem *moose_system = (MooseSystem *) dummy; // C strikes // unused // TransientNonlinearImplicitSystem * system = dynamic_cast<TransientNonlinearImplicitSystem *>(&_equation_system->get_system("NonlinearSystem")); // for(unsigned int var = 0; var < system->n_vars(); var++) // std::cout<<var<<": "<<system->calculate_norm(*system->rhs,var,DISCRETE_L2)<<std::endl; *reason = SNES_CONVERGED_ITERATING; if (!it) { /* set parameter for default relative tolerance convergence test */ snes->ttol = fnorm*snes->rtol; moose_system->_initial_residual = fnorm; } if (fnorm != fnorm) { PetscInfo(snes,"Failed to converged, function norm is NaN\n"); *reason = SNES_DIVERGED_FNORM_NAN; } else if (fnorm < snes->abstol) { PetscInfo2(snes,"Converged due to function norm %G < %G\n",fnorm,snes->abstol); *reason = SNES_CONVERGED_FNORM_ABS; } else if (snes->nfuncs >= snes->max_funcs) { PetscInfo2(snes,"Exceeded maximum number of function evaluations: %D > %D\n",snes->nfuncs,snes->max_funcs); *reason = SNES_DIVERGED_FUNCTION_COUNT; } else if(fnorm >= moose_system->_initial_residual * (1.0/snes->rtol)) { PetscInfo2(snes,"Nonlinear solve was blowing up!",snes->nfuncs,snes->max_funcs); *reason = SNES_DIVERGED_LS_FAILURE; } if (it && !*reason) { if (fnorm <= snes->ttol) { PetscInfo2(snes,"Converged due to function norm %G < %G (relative tolerance)\n",fnorm,snes->ttol); *reason = SNES_CONVERGED_FNORM_RELATIVE; } else if (pnorm < snes->xtol*xnorm) { PetscInfo3(snes,"Converged due to small update length: %G < %G * %G\n",pnorm,snes->xtol,xnorm); *reason = SNES_CONVERGED_PNORM_RELATIVE; } } return(0); } /** * Called at the beginning of every nonlinear step (before Jacobian is formed) */ PetscErrorCode petscNewtonUpdate(SNES snes, PetscInt step) { void *ctx = NULL; SNESGetApplicationContext(snes, &ctx); if (ctx != NULL) { Executioner *exec = (Executioner *) ctx; // C strikes again exec->updateNewtonStep(); exec->onNewtonUpdate(); } return 0; } void petscSetDefaults(MooseSystem &moose_system, Executioner *executioner) { PetscNonlinearSolver<Number> * petsc_solver = dynamic_cast<PetscNonlinearSolver<Number> *>(moose_system.getNonlinearSystem()->nonlinear_solver.get()); SNES snes = petsc_solver->snes(); KSP ksp; SNESGetKSP(snes, &ksp); KSPSetPreconditionerSide(ksp, PC_RIGHT); SNESSetMaxLinearSolveFailures(snes, 1000000); SNESLineSearchSetPostCheck(snes, dampedCheck, moose_system.getEquationSystems()); #if PETSC_VERSION_LESS_THAN(3,0,0) KSPSetConvergenceTest(ksp, petscConverged, &moose_system); SNESSetConvergenceTest(snes, petscNonlinearConverged, &moose_system); #else // In 3.0.0, the context pointer must actually be used, and the // final argument to KSPSetConvergenceTest() is a pointer to a // routine for destroying said private data context. In this case, // we use the default context provided by PETSc in addition to // a few other tests. { PetscErrorCode ierr = KSPSetConvergenceTest(ksp, petscConverged, &moose_system, PETSC_NULL); CHKERRABORT(libMesh::COMM_WORLD,ierr); } #endif SNESSetUpdate(snes, petscNewtonUpdate); SNESSetApplicationContext(snes, (void *) executioner); /* PC pc; KSPGetPC(ksp,&pc); PCSetType(pc,PCSHELL); PCShellSetSetUp(pc,MatrixFreePreconditionerSetup); PCShellSetApply(pc,MatrixFreePreconditioner); */ } // PetscErrorCode petscPhysicsBasedLineSearch(SNES snes,void *lsctx,Vec x,Vec /*f*/,Vec g,Vec y,Vec w, PetscReal /*fnorm*/,PetscReal *ynorm,PetscReal *gnorm,PetscTruth *flag) PetscErrorCode dampedCheck(SNES snes, Vec x, Vec y, Vec w, void *lsctx, PetscTruth * changed_y, PetscTruth * changed_w) { //w = updated solution = x+ scaling*y //x = current solution //y = updates. // for simple newton use w = x-y int ierr = 0; Real damping = 1.0; EquationSystems * equation_systems = static_cast<EquationSystems *>(lsctx); MooseSystem * moose_system = equation_systems->parameters.get<MooseSystem *>("moose_system"); MeshBase & mesh = equation_systems->get_mesh(); TransientNonlinearImplicitSystem& system = equation_systems->get_system<TransientNonlinearImplicitSystem> ("NonlinearSystem"); unsigned int sys = system.number(); //create PetscVector PetscVector<Number> update_vec_x(x); PetscVector<Number> update_vec_y(y); PetscVector<Number> update_vec_w(w); damping = moose_system->compute_damping(update_vec_w, update_vec_y); if(damping != 1.0) { VecScale(y, damping); *changed_y = PETSC_TRUE; } return(ierr); } } } #endif //LIBMESH_HAVE_PETSC <|endoftext|>
<commit_before>#include "cfilelistview.h" #include "../columns.h" #include "model/cfilelistsortfilterproxymodel.h" #include "delegate/cfilelistitemdelegate.h" DISABLE_COMPILER_WARNINGS #include <QApplication> #include <QDebug> #include <QDragMoveEvent> #include <QHeaderView> #include <QKeyEvent> #include <QMouseEvent> RESTORE_COMPILER_WARNINGS #include <time.h> #include <set> #if defined __linux__ || defined __APPLE__ #include "cfocusframestyle.h" #endif CFileListView::CFileListView(QWidget *parent) : QTreeView(parent), _controller(CController::get()) { setMouseTracking(true); setItemDelegate(new CFileListItemDelegate); connect(this, &QTreeView::doubleClicked, [this](const QModelIndex &idx) { _currentItemBeforeMouseClick = QModelIndex(); _singleMouseClickValid = false; for(FileListViewEventObserver* observer: _eventObservers) { if (observer->fileListReturnPressOrDoubleClickPerformed(idx)) break; } }); QHeaderView * headerView = header(); assert_r(headerView); headerView->installEventFilter(this); #if defined __linux__ || defined __APPLE__ setStyle(new CFocusFrameStyle); #endif } void CFileListView::addEventObserver(FileListViewEventObserver* observer) { _eventObservers.push_back(observer); } // Sets the position (left or right) of a panel that this model represents void CFileListView::setPanelPosition(enum Panel p) { assert_r(_panelPosition == UnknownPanel); // Doesn't make sense to call this method more than once _panelPosition = p; } // Preserves item's selection state void CFileListView::moveCursorToItem(const QModelIndex& index, bool invertSelection) { if (index.isValid() && selectionModel()->model()->hasIndex(index.row(), index.column())) { const QModelIndex normalizedTargetIndex = model()->index(index.row(), index.column()); // There was some problem with using the index directly, like it was from the wrong model or something const QModelIndex currentIdx = currentIndex(); if (invertSelection && currentIdx.isValid()) { int startRow = std::min(currentIdx.row(), normalizedTargetIndex.row()); int endRow = std::max(currentIdx.row(), normalizedTargetIndex.row()); for (int row = startRow; row <= endRow; ++row) selectionModel()->setCurrentIndex(model()->index(row, 0), (!_shiftPressedItemSelected ? QItemSelectionModel::Select : QItemSelectionModel::Deselect) | QItemSelectionModel::Rows); } selectionModel()->setCurrentIndex(normalizedTargetIndex, QItemSelectionModel::Current | QItemSelectionModel::Rows); scrollTo(normalizedTargetIndex); } } // Header management void CFileListView::saveHeaderState() { if (header()) { _headerGeometry = header()->saveGeometry(); _headerState = header()->saveState(); } } void CFileListView::restoreHeaderState() { QHeaderView * headerView = header(); assert_and_return_r(headerView, ); if (!_headerGeometry.isEmpty()) headerView->restoreGeometry(_headerGeometry); if (!_headerState.isEmpty()) headerView->restoreState(_headerState); } void CFileListView::invertSelection() { QItemSelection allItems(model()->index(0, 0), model()->index(model()->rowCount() - 1, 0)); selectionModel()->select(allItems, QItemSelectionModel::Toggle | QItemSelectionModel::Rows); } void CFileListView::modelAboutToBeReset() { _currentItemBeforeMouseClick = QModelIndex(); _singleMouseClickValid = false; if (_bHeaderAdjustmentRequired) { _bHeaderAdjustmentRequired = false; for (int i = 0; i < model()->columnCount(); ++i) resizeColumnToContents(i); sortByColumn(ExtColumn, Qt::AscendingOrder); } } // For managing selection and cursor void CFileListView::mousePressEvent(QMouseEvent *e) { _singleMouseClickValid = !_singleMouseClickValid && e->modifiers() == Qt::NoModifier; _currentItemBeforeMouseClick = currentIndex(); const bool selectionWasEmpty = selectionModel()->selectedRows().empty(); // Always let Qt process this event QTreeView::mousePressEvent(e); if (_currentItemShouldBeSelectedOnMouseClick && e->modifiers() == Qt::ControlModifier && selectionWasEmpty && _currentItemBeforeMouseClick.isValid()) { _currentItemShouldBeSelectedOnMouseClick = false; selectionModel()->select(_currentItemBeforeMouseClick, QItemSelectionModel::Rows | QItemSelectionModel::Select); } } void CFileListView::mouseMoveEvent(QMouseEvent * e) { if (_singleMouseClickValid && (e->pos() - _singleMouseClickPos).manhattanLength() > 15) { _singleMouseClickValid = false; _currentItemBeforeMouseClick = QModelIndex(); } QTreeView::mouseMoveEvent(e); } // For showing context menu void CFileListView::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::RightButton) { // Selecting an item that was clicked upon const auto index = indexAt(event->pos()); if (!index.isValid()) clearSelection(); // clearing selection if there wasn't any item under cursor // Calling a context menu emit contextMenuRequested(QCursor::pos()); // Getting global screen coordinates } else if (event->button() == Qt::LeftButton) { const QModelIndex itemClicked = indexAt(event->pos()); if (_currentItemBeforeMouseClick == itemClicked && _singleMouseClickValid && event->modifiers() == Qt::NoModifier) { _singleMouseClickPos = event->pos(); QTimer::singleShot(QApplication::doubleClickInterval()+50, [this]() { if (_singleMouseClickValid) { edit(model()->index(currentIndex().row(), 0), AllEditTriggers, nullptr); _currentItemBeforeMouseClick = QModelIndex(); _singleMouseClickValid = false; } }); } // Bug fix for #49 - preventing item selection with a single LMB click if (event->modifiers() == Qt::NoModifier && itemClicked.isValid()) selectionModel()->clearSelection(); } // Always let Qt process this event QTreeView::mouseReleaseEvent(event); } // For managing selection and cursor void CFileListView::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Control) _currentItemShouldBeSelectedOnMouseClick = true; if (event->key() == Qt::Key_Down || event->key() == Qt::Key_Up || event->key() == Qt::Key_PageDown || event->key() == Qt::Key_PageUp || event->key() == Qt::Key_Home || event->key() == Qt::Key_End) { if ((event->modifiers() & (~Qt::KeypadModifier) & (~Qt::ShiftModifier)) == Qt::NoModifier) { const bool shiftPressed = (event->modifiers() & Qt::ShiftModifier) != 0; if (shiftPressed) _shiftPressedItemSelected = currentIndex().isValid() ? selectionModel()->isSelected(currentIndex()) : false; if (event->key() == Qt::Key_Down) moveCursorToNextItem(shiftPressed); else if (event->key() == Qt::Key_Up) moveCursorToPreviousItem(shiftPressed); else if (event->key() == Qt::Key_Home) moveCursorToItem(model()->index(0, 0), shiftPressed); else if (event->key() == Qt::Key_End) moveCursorToItem(model()->index(model()->rowCount()-1, 0), shiftPressed); else if (event->key() == Qt::Key_PageUp) pgUp(shiftPressed); else if (event->key() == Qt::Key_PageDown) pgDn(shiftPressed); event->accept(); return; } } else if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) { const auto modifiers = event->modifiers() & ~Qt::KeypadModifier; if (modifiers == Qt::NoModifier) { bool returnPressConsumed = false; for(FileListViewEventObserver* observer: _eventObservers) { returnPressConsumed = observer->fileListReturnPressed(); if (returnPressConsumed) break; } if (!returnPressConsumed) for (FileListViewEventObserver* observer: _eventObservers) { if (currentIndex().isValid()) { returnPressConsumed = observer->fileListReturnPressOrDoubleClickPerformed(currentIndex()); if (returnPressConsumed) break; } } } else if (modifiers == Qt::ControlModifier) emit ctrlEnterPressed(); else if (modifiers == (Qt::ControlModifier | Qt::ShiftModifier)) emit ctrlShiftEnterPressed(); return; } else if (event->key() == Qt::Key_Shift) { _shiftPressedItemSelected = currentIndex().isValid() ? selectionModel()->isSelected(currentIndex()) : false; } else emit keyPressed(event->text(), event->key(), event->modifiers()); QTreeView::keyPressEvent(event); #ifdef __linux__ // FIXME: find out why this hack is necessary if (event->key() == Qt::Key_Down || event->key() == Qt::Key_Up || event->key() == Qt::Key_PageDown || event->key() == Qt::Key_PageUp || event->key() == Qt::Key_Home || event->key() == Qt::Key_End) if ((event->modifiers() & Qt::ShiftModifier) != 0) scrollTo(currentIndex()); #endif } void CFileListView::keyReleaseEvent(QKeyEvent * event) { if (event->key() == Qt::Key_Control) _currentItemShouldBeSelectedOnMouseClick = true; QTreeView::keyReleaseEvent(event); } bool CFileListView::edit(const QModelIndex & index, QAbstractItemView::EditTrigger trigger, QEvent * event) { return QTreeView::edit(model()->index(index.row(), 0), trigger, event); } // canDropMimeData is not called by QAbstractItemModel as of Qt 5.3 (https://bugreports.qt-project.org/browse/QTBUG-30534), so we're re-defining dragEnterEvent to fix this void CFileListView::dragMoveEvent(QDragMoveEvent * event) { QModelIndex targetIndex = indexAt(event->pos()); if (model()->canDropMimeData(event->mimeData(), (Qt::DropAction)((int)event->possibleActions()), targetIndex.row(), targetIndex.column(), QModelIndex())) { if (state() != DraggingState) setState(DraggingState); QTreeView::dragMoveEvent(event); } else event->ignore(); } bool CFileListView::eventFilter(QObject* target, QEvent* event) { QHeaderView * headerView = header(); if (target == headerView && event && event->type() == QEvent::Resize && headerView->count() == NumberOfColumns) { auto resizeEvent = dynamic_cast<QResizeEvent*>(event); assert_and_return_r(resizeEvent, false); float oldHeaderWidth = 0.0f; for (int i = 0; i < headerView->count(); ++i) oldHeaderWidth += (float)headerView->sectionSize(i); const float newHeaderWidth = (float)resizeEvent->size().width(); if (oldHeaderWidth <= 0.0f || newHeaderWidth <= 0.0f || oldHeaderWidth == newHeaderWidth) return false; std::vector<float> relativeColumnSizes(NumberOfColumns, 0.0f); for (int i = 0; i < headerView->count(); ++i) relativeColumnSizes[i] = headerView->sectionSize(i) / oldHeaderWidth; for (int i = 0; i < headerView->count(); ++i) headerView->resizeSection(i, (int)(newHeaderWidth * relativeColumnSizes[i] + 0.5f)); return false; } return QTreeView::eventFilter(target, event); } void CFileListView::selectRegion(const QModelIndex &start, const QModelIndex &end) { bool itemBelongsToSelection = false; assert_r(selectionModel()); for (int i = 0; i < model()->rowCount(); ++i) { // Start item found - beginning selection QModelIndex currentItem = model()->index(i, 0); if (!itemBelongsToSelection && (currentItem == start || currentItem == end)) { itemBelongsToSelection = true; selectionModel()->select(currentItem, QItemSelectionModel::Select | QItemSelectionModel::Rows); } else if (itemBelongsToSelection && (currentItem == start || currentItem == end)) { // End item found - finishing selection selectionModel()->select(currentItem, QItemSelectionModel::Select | QItemSelectionModel::Rows); return; } if (itemBelongsToSelection) selectionModel()->select(currentItem, QItemSelectionModel::Select | QItemSelectionModel::Rows); } } void CFileListView::moveCursorToNextItem(bool invertSelection) { if (model()->rowCount() <= 0) return; const QModelIndex curIdx(currentIndex()); if (curIdx.isValid() && curIdx.row()+1 < model()->rowCount()) moveCursorToItem(model()->index(curIdx.row()+1, 0), invertSelection); else if (!curIdx.isValid()) moveCursorToItem(model()->index(0, 0), invertSelection); } void CFileListView::moveCursorToPreviousItem(bool invertSelection) { if (model()->rowCount() <= 0) return; const QModelIndex curIdx(currentIndex()); if (curIdx.isValid() && curIdx.row() > 0) moveCursorToItem(model()->index(curIdx.row()-1, 0), invertSelection); else if (!curIdx.isValid()) moveCursorToItem(model()->index(0, 0), invertSelection); } void CFileListView::pgUp(bool invertSelection) { const QModelIndex curIdx(currentIndex()); if (!curIdx.isValid()) return; const int numItemsVisible = numRowsVisible(); if (numItemsVisible <= 0) return; moveCursorToItem(model()->index(std::max(curIdx.row()-numItemsVisible, 0), 0), invertSelection); } void CFileListView::pgDn(bool invertSelection) { const QModelIndex curIdx(currentIndex()); if (!curIdx.isValid()) return; const int numItemsVisible = numRowsVisible(); if (numItemsVisible <= 0) return; moveCursorToItem(model()->index(std::min(curIdx.row()+numItemsVisible, model()->rowCount()-1), 0), invertSelection); } int CFileListView::numRowsVisible() const { // FIXME: rewrite it with indexAt to be O(1) int numRowsVisible = 0; for(int row = 0; row < model()->rowCount(); row++) { if (visualRect(model()->index(row, 0)).intersects(viewport()->rect())) ++numRowsVisible; } return numRowsVisible; } void CFileListView::setHeaderAdjustmentRequired(bool required) { _bHeaderAdjustmentRequired = required; } <commit_msg>Fixed #126<commit_after>#include "cfilelistview.h" #include "../columns.h" #include "model/cfilelistsortfilterproxymodel.h" #include "delegate/cfilelistitemdelegate.h" DISABLE_COMPILER_WARNINGS #include <QApplication> #include <QDebug> #include <QDragMoveEvent> #include <QHeaderView> #include <QKeyEvent> #include <QMouseEvent> RESTORE_COMPILER_WARNINGS #include <time.h> #include <set> #if defined __linux__ || defined __APPLE__ #include "cfocusframestyle.h" #endif CFileListView::CFileListView(QWidget *parent) : QTreeView(parent), _controller(CController::get()) { setMouseTracking(true); setItemDelegate(new CFileListItemDelegate); connect(this, &QTreeView::doubleClicked, [this](const QModelIndex &idx) { _currentItemBeforeMouseClick = QModelIndex(); _singleMouseClickValid = false; for(FileListViewEventObserver* observer: _eventObservers) { if (observer->fileListReturnPressOrDoubleClickPerformed(idx)) break; } }); QHeaderView * headerView = header(); assert_r(headerView); headerView->installEventFilter(this); #if defined __linux__ || defined __APPLE__ setStyle(new CFocusFrameStyle); #endif } void CFileListView::addEventObserver(FileListViewEventObserver* observer) { _eventObservers.push_back(observer); } // Sets the position (left or right) of a panel that this model represents void CFileListView::setPanelPosition(enum Panel p) { assert_r(_panelPosition == UnknownPanel); // Doesn't make sense to call this method more than once _panelPosition = p; } // Preserves item's selection state void CFileListView::moveCursorToItem(const QModelIndex& index, bool invertSelection) { if (index.isValid() && selectionModel()->model()->hasIndex(index.row(), index.column())) { const QModelIndex normalizedTargetIndex = model()->index(index.row(), index.column()); // There was some problem with using the index directly, like it was from the wrong model or something const QModelIndex currentIdx = currentIndex(); if (invertSelection && currentIdx.isValid()) { for (int row = std::min(currentIdx.row(), normalizedTargetIndex.row()), endRow = std::max(currentIdx.row(), normalizedTargetIndex.row()); row <= endRow; ++row) selectionModel()->setCurrentIndex(model()->index(row, 0), (_shiftPressedItemSelected ? QItemSelectionModel::Deselect : QItemSelectionModel::Select) | QItemSelectionModel::Rows); } selectionModel()->setCurrentIndex(normalizedTargetIndex, QItemSelectionModel::Current | QItemSelectionModel::Rows); scrollTo(normalizedTargetIndex); } } // Header management void CFileListView::saveHeaderState() { if (header()) { _headerGeometry = header()->saveGeometry(); _headerState = header()->saveState(); } } void CFileListView::restoreHeaderState() { QHeaderView * headerView = header(); assert_and_return_r(headerView, ); if (!_headerGeometry.isEmpty()) headerView->restoreGeometry(_headerGeometry); if (!_headerState.isEmpty()) headerView->restoreState(_headerState); } void CFileListView::invertSelection() { QItemSelection allItems(model()->index(0, 0), model()->index(model()->rowCount() - 1, 0)); selectionModel()->select(allItems, QItemSelectionModel::Toggle | QItemSelectionModel::Rows); } void CFileListView::modelAboutToBeReset() { _currentItemBeforeMouseClick = QModelIndex(); _singleMouseClickValid = false; if (_bHeaderAdjustmentRequired) { _bHeaderAdjustmentRequired = false; for (int i = 0; i < model()->columnCount(); ++i) resizeColumnToContents(i); sortByColumn(ExtColumn, Qt::AscendingOrder); } } // For managing selection and cursor void CFileListView::mousePressEvent(QMouseEvent *e) { _singleMouseClickValid = !_singleMouseClickValid && e->modifiers() == Qt::NoModifier; _currentItemBeforeMouseClick = currentIndex(); const bool selectionWasEmpty = selectionModel()->selectedRows().empty(); // Always let Qt process this event QTreeView::mousePressEvent(e); if (_currentItemShouldBeSelectedOnMouseClick && e->modifiers() == Qt::ControlModifier && selectionWasEmpty && _currentItemBeforeMouseClick.isValid()) { _currentItemShouldBeSelectedOnMouseClick = false; selectionModel()->select(_currentItemBeforeMouseClick, QItemSelectionModel::Rows | QItemSelectionModel::Select); } } void CFileListView::mouseMoveEvent(QMouseEvent * e) { if (_singleMouseClickValid && (e->pos() - _singleMouseClickPos).manhattanLength() > 15) { _singleMouseClickValid = false; _currentItemBeforeMouseClick = QModelIndex(); } QTreeView::mouseMoveEvent(e); } // For showing context menu void CFileListView::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::RightButton) { // Selecting an item that was clicked upon const auto index = indexAt(event->pos()); if (!index.isValid()) clearSelection(); // clearing selection if there wasn't any item under cursor // Calling a context menu emit contextMenuRequested(QCursor::pos()); // Getting global screen coordinates } else if (event->button() == Qt::LeftButton) { const QModelIndex itemClicked = indexAt(event->pos()); if (_currentItemBeforeMouseClick == itemClicked && _singleMouseClickValid && event->modifiers() == Qt::NoModifier) { _singleMouseClickPos = event->pos(); QTimer::singleShot(QApplication::doubleClickInterval()+50, [this]() { if (_singleMouseClickValid) { edit(model()->index(currentIndex().row(), 0), AllEditTriggers, nullptr); _currentItemBeforeMouseClick = QModelIndex(); _singleMouseClickValid = false; } }); } // Bug fix for #49 - preventing item selection with a single LMB click if (event->modifiers() == Qt::NoModifier && itemClicked.isValid()) selectionModel()->clearSelection(); } // Always let Qt process this event QTreeView::mouseReleaseEvent(event); } // For managing selection and cursor void CFileListView::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Control) _currentItemShouldBeSelectedOnMouseClick = true; if (event->key() == Qt::Key_Down || event->key() == Qt::Key_Up || event->key() == Qt::Key_PageDown || event->key() == Qt::Key_PageUp || event->key() == Qt::Key_Home || event->key() == Qt::Key_End) { if ((event->modifiers() & ~Qt::KeypadModifier & ~Qt::ShiftModifier) == Qt::NoModifier) { const bool shiftPressed = (event->modifiers() & Qt::ShiftModifier) != 0; if (event->key() == Qt::Key_Down) moveCursorToNextItem(shiftPressed); else if (event->key() == Qt::Key_Up) moveCursorToPreviousItem(shiftPressed); else if (event->key() == Qt::Key_Home) moveCursorToItem(model()->index(0, 0), shiftPressed); else if (event->key() == Qt::Key_End) moveCursorToItem(model()->index(model()->rowCount()-1, 0), shiftPressed); else if (event->key() == Qt::Key_PageUp) pgUp(shiftPressed); else if (event->key() == Qt::Key_PageDown) pgDn(shiftPressed); event->accept(); return; } } else if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) { const auto modifiers = event->modifiers() & ~Qt::KeypadModifier; if (modifiers == Qt::NoModifier) { bool returnPressConsumed = false; for(FileListViewEventObserver* observer: _eventObservers) { returnPressConsumed = observer->fileListReturnPressed(); if (returnPressConsumed) break; } if (!returnPressConsumed) for (FileListViewEventObserver* observer: _eventObservers) { if (currentIndex().isValid()) { returnPressConsumed = observer->fileListReturnPressOrDoubleClickPerformed(currentIndex()); if (returnPressConsumed) break; } } } else if (modifiers == Qt::ControlModifier) emit ctrlEnterPressed(); else if (modifiers == (Qt::ControlModifier | Qt::ShiftModifier)) emit ctrlShiftEnterPressed(); return; } else if (event->key() == Qt::Key_Shift) { _shiftPressedItemSelected = currentIndex().isValid() ? selectionModel()->isSelected(currentIndex()) : false; } else emit keyPressed(event->text(), event->key(), event->modifiers()); QTreeView::keyPressEvent(event); #ifdef __linux__ // FIXME: find out why this hack is necessary if (event->key() == Qt::Key_Down || event->key() == Qt::Key_Up || event->key() == Qt::Key_PageDown || event->key() == Qt::Key_PageUp || event->key() == Qt::Key_Home || event->key() == Qt::Key_End) if ((event->modifiers() & Qt::ShiftModifier) != 0) scrollTo(currentIndex()); #endif } void CFileListView::keyReleaseEvent(QKeyEvent * event) { if (event->key() == Qt::Key_Control) _currentItemShouldBeSelectedOnMouseClick = true; else if (event->key() == Qt::Key_Shift) _shiftPressedItemSelected = false; QTreeView::keyReleaseEvent(event); } bool CFileListView::edit(const QModelIndex & index, QAbstractItemView::EditTrigger trigger, QEvent * event) { return QTreeView::edit(model()->index(index.row(), 0), trigger, event); } // canDropMimeData is not called by QAbstractItemModel as of Qt 5.3 (https://bugreports.qt-project.org/browse/QTBUG-30534), so we're re-defining dragEnterEvent to fix this void CFileListView::dragMoveEvent(QDragMoveEvent * event) { QModelIndex targetIndex = indexAt(event->pos()); if (model()->canDropMimeData(event->mimeData(), (Qt::DropAction)((int)event->possibleActions()), targetIndex.row(), targetIndex.column(), QModelIndex())) { if (state() != DraggingState) setState(DraggingState); QTreeView::dragMoveEvent(event); } else event->ignore(); } bool CFileListView::eventFilter(QObject* target, QEvent* event) { QHeaderView * headerView = header(); if (target == headerView && event && event->type() == QEvent::Resize && headerView->count() == NumberOfColumns) { auto resizeEvent = dynamic_cast<QResizeEvent*>(event); assert_and_return_r(resizeEvent, false); float oldHeaderWidth = 0.0f; for (int i = 0; i < headerView->count(); ++i) oldHeaderWidth += (float)headerView->sectionSize(i); const float newHeaderWidth = (float)resizeEvent->size().width(); if (oldHeaderWidth <= 0.0f || newHeaderWidth <= 0.0f || oldHeaderWidth == newHeaderWidth) return false; std::vector<float> relativeColumnSizes(NumberOfColumns, 0.0f); for (int i = 0; i < headerView->count(); ++i) relativeColumnSizes[i] = headerView->sectionSize(i) / oldHeaderWidth; for (int i = 0; i < headerView->count(); ++i) headerView->resizeSection(i, (int)(newHeaderWidth * relativeColumnSizes[i] + 0.5f)); return false; } return QTreeView::eventFilter(target, event); } void CFileListView::selectRegion(const QModelIndex &start, const QModelIndex &end) { bool itemBelongsToSelection = false; assert_r(selectionModel()); for (int i = 0; i < model()->rowCount(); ++i) { // Start item found - beginning selection QModelIndex currentItem = model()->index(i, 0); if (!itemBelongsToSelection && (currentItem == start || currentItem == end)) { itemBelongsToSelection = true; selectionModel()->select(currentItem, QItemSelectionModel::Select | QItemSelectionModel::Rows); } else if (itemBelongsToSelection && (currentItem == start || currentItem == end)) { // End item found - finishing selection selectionModel()->select(currentItem, QItemSelectionModel::Select | QItemSelectionModel::Rows); return; } if (itemBelongsToSelection) selectionModel()->select(currentItem, QItemSelectionModel::Select | QItemSelectionModel::Rows); } } void CFileListView::moveCursorToNextItem(bool invertSelection) { if (model()->rowCount() <= 0) return; const QModelIndex curIdx(currentIndex()); if (curIdx.isValid() && curIdx.row()+1 < model()->rowCount()) moveCursorToItem(model()->index(curIdx.row()+1, 0), invertSelection); else if (!curIdx.isValid()) moveCursorToItem(model()->index(0, 0), invertSelection); } void CFileListView::moveCursorToPreviousItem(bool invertSelection) { if (model()->rowCount() <= 0) return; const QModelIndex curIdx(currentIndex()); if (curIdx.isValid() && curIdx.row() > 0) moveCursorToItem(model()->index(curIdx.row()-1, 0), invertSelection); else if (!curIdx.isValid()) moveCursorToItem(model()->index(0, 0), invertSelection); } void CFileListView::pgUp(bool invertSelection) { const QModelIndex curIdx(currentIndex()); if (!curIdx.isValid()) return; const int numItemsVisible = numRowsVisible(); if (numItemsVisible <= 0) return; moveCursorToItem(model()->index(std::max(curIdx.row()-numItemsVisible, 0), 0), invertSelection); } void CFileListView::pgDn(bool invertSelection) { const QModelIndex curIdx(currentIndex()); if (!curIdx.isValid()) return; const int numItemsVisible = numRowsVisible(); if (numItemsVisible <= 0) return; moveCursorToItem(model()->index(std::min(curIdx.row()+numItemsVisible, model()->rowCount()-1), 0), invertSelection); } int CFileListView::numRowsVisible() const { // TODO: rewrite it with indexAt to be O(1) int numRowsVisible = 0; for(int row = 0, numRows = model()->rowCount(); row < numRows; row++) { if (visualRect(model()->index(row, 0)).intersects(viewport()->rect())) ++numRowsVisible; } return numRowsVisible; } void CFileListView::setHeaderAdjustmentRequired(bool required) { _bHeaderAdjustmentRequired = required; } <|endoftext|>
<commit_before>// Copyright (c) Facebook, Inc. and its affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include "ComponentDescriptorRegistry.h" #include <react/core/ShadowNodeFragment.h> #include <react/uimanager/ComponentDescriptorProviderRegistry.h> #include <react/uimanager/primitives.h> namespace facebook { namespace react { ComponentDescriptorRegistry::ComponentDescriptorRegistry( ComponentDescriptorParameters const &parameters, ComponentDescriptorProviderRegistry const &providerRegistry) : parameters_(parameters), providerRegistry_(&providerRegistry) {} void ComponentDescriptorRegistry::add( ComponentDescriptorProvider componentDescriptorProvider) const { std::unique_lock<better::shared_mutex> lock(mutex_); auto componentDescriptor = componentDescriptorProvider.constructor( {parameters_.eventDispatcher, parameters_.contextContainer, componentDescriptorProvider.flavor}); assert( componentDescriptor->getComponentHandle() == componentDescriptorProvider.handle); assert( componentDescriptor->getComponentName() == componentDescriptorProvider.name); auto sharedComponentDescriptor = std::shared_ptr<ComponentDescriptor const>( std::move(componentDescriptor)); _registryByHandle[componentDescriptorProvider.handle] = sharedComponentDescriptor; _registryByName[componentDescriptorProvider.name] = sharedComponentDescriptor; if (strcmp(componentDescriptorProvider.name, "UnimplementedNativeView") == 0) { auto *self = const_cast<ComponentDescriptorRegistry *>(this); self->setFallbackComponentDescriptor(sharedComponentDescriptor); } } void ComponentDescriptorRegistry::remove( ComponentDescriptorProvider componentDescriptorProvider) const { std::unique_lock<better::shared_mutex> lock(mutex_); assert( _registryByHandle.find(componentDescriptorProvider.handle) != _registryByHandle.end()); assert( _registryByName.find(componentDescriptorProvider.name) != _registryByName.end()); _registryByHandle.erase(componentDescriptorProvider.handle); _registryByName.erase(componentDescriptorProvider.name); } void ComponentDescriptorRegistry::registerComponentDescriptor( SharedComponentDescriptor componentDescriptor) const { ComponentHandle componentHandle = componentDescriptor->getComponentHandle(); _registryByHandle[componentHandle] = componentDescriptor; ComponentName componentName = componentDescriptor->getComponentName(); _registryByName[componentName] = componentDescriptor; } static std::string componentNameByReactViewName(std::string viewName) { // We need this function only for the transition period; // eventually, all names will be unified. std::string rctPrefix("RCT"); if (std::mismatch(rctPrefix.begin(), rctPrefix.end(), viewName.begin()) .first == rctPrefix.end()) { // If `viewName` has "RCT" prefix, remove it. viewName.erase(0, rctPrefix.length()); } // Fabric uses slightly new names for Text components because of differences // in semantic. if (viewName == "Text") { return "Paragraph"; } if (viewName == "VirtualText") { return "Text"; } if (viewName == "ImageView") { return "Image"; } if (viewName == "AndroidHorizontalScrollView") { return "ScrollView"; } if (viewName == "RKShimmeringView") { return "ShimmeringView"; } if (viewName == "AndroidProgressBar") { return "ActivityIndicatorView"; } // We need this temporarily for testing purposes until we have proper // implementation of core components. if (viewName == "SafeAreaView" || viewName == "ScrollContentView" || viewName == "AndroidHorizontalScrollContentView" // Android ) { return "View"; } return viewName; } ComponentDescriptor const &ComponentDescriptorRegistry::at( std::string const &componentName) const { std::shared_lock<better::shared_mutex> lock(mutex_); auto unifiedComponentName = componentNameByReactViewName(componentName); auto it = _registryByName.find(unifiedComponentName); if (it == _registryByName.end()) { assert(providerRegistry_); mutex_.unlock_shared(); providerRegistry_->request(unifiedComponentName.c_str()); mutex_.lock_shared(); it = _registryByName.find(unifiedComponentName); assert(it != _registryByName.end()); } if (it == _registryByName.end()) { if (_fallbackComponentDescriptor == nullptr) { throw std::invalid_argument( ("Unable to find componentDescriptor for " + unifiedComponentName) .c_str()); } return *_fallbackComponentDescriptor.get(); } return *it->second; } ComponentDescriptor const &ComponentDescriptorRegistry::at( ComponentHandle componentHandle) const { std::shared_lock<better::shared_mutex> lock(mutex_); return *_registryByHandle.at(componentHandle); } SharedShadowNode ComponentDescriptorRegistry::createNode( Tag tag, std::string const &viewName, SurfaceId surfaceId, folly::dynamic const &propsDynamic, SharedEventTarget const &eventTarget) const { auto unifiedComponentName = componentNameByReactViewName(viewName); auto const &componentDescriptor = this->at(unifiedComponentName); auto const eventEmitter = componentDescriptor.createEventEmitter(std::move(eventTarget), tag); auto const props = componentDescriptor.cloneProps(nullptr, RawProps(propsDynamic)); auto const state = componentDescriptor.createInitialState( ShadowNodeFragment{surfaceId, tag, props, eventEmitter}); return componentDescriptor.createShadowNode({ /* .tag = */ tag, /* .surfaceId = */ surfaceId, /* .props = */ props, /* .eventEmitter = */ eventEmitter, /* .children = */ ShadowNodeFragment::childrenPlaceholder(), /* .localData = */ ShadowNodeFragment::localDataPlaceholder(), /* .state = */ state, }); } void ComponentDescriptorRegistry::setFallbackComponentDescriptor( SharedComponentDescriptor descriptor) { _fallbackComponentDescriptor = descriptor; registerComponentDescriptor(descriptor); } ComponentDescriptor::Shared ComponentDescriptorRegistry::getFallbackComponentDescriptor() const { return _fallbackComponentDescriptor; } } // namespace react } // namespace facebook <commit_msg>Fix RCTRefreshControl component name in Fabric<commit_after>// Copyright (c) Facebook, Inc. and its affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include "ComponentDescriptorRegistry.h" #include <react/core/ShadowNodeFragment.h> #include <react/uimanager/ComponentDescriptorProviderRegistry.h> #include <react/uimanager/primitives.h> namespace facebook { namespace react { ComponentDescriptorRegistry::ComponentDescriptorRegistry( ComponentDescriptorParameters const &parameters, ComponentDescriptorProviderRegistry const &providerRegistry) : parameters_(parameters), providerRegistry_(&providerRegistry) {} void ComponentDescriptorRegistry::add( ComponentDescriptorProvider componentDescriptorProvider) const { std::unique_lock<better::shared_mutex> lock(mutex_); auto componentDescriptor = componentDescriptorProvider.constructor( {parameters_.eventDispatcher, parameters_.contextContainer, componentDescriptorProvider.flavor}); assert( componentDescriptor->getComponentHandle() == componentDescriptorProvider.handle); assert( componentDescriptor->getComponentName() == componentDescriptorProvider.name); auto sharedComponentDescriptor = std::shared_ptr<ComponentDescriptor const>( std::move(componentDescriptor)); _registryByHandle[componentDescriptorProvider.handle] = sharedComponentDescriptor; _registryByName[componentDescriptorProvider.name] = sharedComponentDescriptor; if (strcmp(componentDescriptorProvider.name, "UnimplementedNativeView") == 0) { auto *self = const_cast<ComponentDescriptorRegistry *>(this); self->setFallbackComponentDescriptor(sharedComponentDescriptor); } } void ComponentDescriptorRegistry::remove( ComponentDescriptorProvider componentDescriptorProvider) const { std::unique_lock<better::shared_mutex> lock(mutex_); assert( _registryByHandle.find(componentDescriptorProvider.handle) != _registryByHandle.end()); assert( _registryByName.find(componentDescriptorProvider.name) != _registryByName.end()); _registryByHandle.erase(componentDescriptorProvider.handle); _registryByName.erase(componentDescriptorProvider.name); } void ComponentDescriptorRegistry::registerComponentDescriptor( SharedComponentDescriptor componentDescriptor) const { ComponentHandle componentHandle = componentDescriptor->getComponentHandle(); _registryByHandle[componentHandle] = componentDescriptor; ComponentName componentName = componentDescriptor->getComponentName(); _registryByName[componentName] = componentDescriptor; } static std::string componentNameByReactViewName(std::string viewName) { // We need this function only for the transition period; // eventually, all names will be unified. std::string rctPrefix("RCT"); if (std::mismatch(rctPrefix.begin(), rctPrefix.end(), viewName.begin()) .first == rctPrefix.end()) { // If `viewName` has "RCT" prefix, remove it. viewName.erase(0, rctPrefix.length()); } // Fabric uses slightly new names for Text components because of differences // in semantic. if (viewName == "Text") { return "Paragraph"; } if (viewName == "VirtualText") { return "Text"; } if (viewName == "ImageView") { return "Image"; } if (viewName == "AndroidHorizontalScrollView") { return "ScrollView"; } if (viewName == "RKShimmeringView") { return "ShimmeringView"; } if (viewName == "RefreshControl") { return "PullToRefreshView"; } if (viewName == "AndroidProgressBar") { return "ActivityIndicatorView"; } // We need this temporarily for testing purposes until we have proper // implementation of core components. if (viewName == "SafeAreaView" || viewName == "ScrollContentView" || viewName == "AndroidHorizontalScrollContentView" // Android ) { return "View"; } return viewName; } ComponentDescriptor const &ComponentDescriptorRegistry::at( std::string const &componentName) const { std::shared_lock<better::shared_mutex> lock(mutex_); auto unifiedComponentName = componentNameByReactViewName(componentName); auto it = _registryByName.find(unifiedComponentName); if (it == _registryByName.end()) { assert(providerRegistry_); mutex_.unlock_shared(); providerRegistry_->request(unifiedComponentName.c_str()); mutex_.lock_shared(); it = _registryByName.find(unifiedComponentName); assert(it != _registryByName.end()); } if (it == _registryByName.end()) { if (_fallbackComponentDescriptor == nullptr) { throw std::invalid_argument( ("Unable to find componentDescriptor for " + unifiedComponentName) .c_str()); } return *_fallbackComponentDescriptor.get(); } return *it->second; } ComponentDescriptor const &ComponentDescriptorRegistry::at( ComponentHandle componentHandle) const { std::shared_lock<better::shared_mutex> lock(mutex_); return *_registryByHandle.at(componentHandle); } SharedShadowNode ComponentDescriptorRegistry::createNode( Tag tag, std::string const &viewName, SurfaceId surfaceId, folly::dynamic const &propsDynamic, SharedEventTarget const &eventTarget) const { auto unifiedComponentName = componentNameByReactViewName(viewName); auto const &componentDescriptor = this->at(unifiedComponentName); auto const eventEmitter = componentDescriptor.createEventEmitter(std::move(eventTarget), tag); auto const props = componentDescriptor.cloneProps(nullptr, RawProps(propsDynamic)); auto const state = componentDescriptor.createInitialState( ShadowNodeFragment{surfaceId, tag, props, eventEmitter}); return componentDescriptor.createShadowNode({ /* .tag = */ tag, /* .surfaceId = */ surfaceId, /* .props = */ props, /* .eventEmitter = */ eventEmitter, /* .children = */ ShadowNodeFragment::childrenPlaceholder(), /* .localData = */ ShadowNodeFragment::localDataPlaceholder(), /* .state = */ state, }); } void ComponentDescriptorRegistry::setFallbackComponentDescriptor( SharedComponentDescriptor descriptor) { _fallbackComponentDescriptor = descriptor; registerComponentDescriptor(descriptor); } ComponentDescriptor::Shared ComponentDescriptorRegistry::getFallbackComponentDescriptor() const { return _fallbackComponentDescriptor; } } // namespace react } // namespace facebook <|endoftext|>
<commit_before>#include "autoattach.h" #include <lua.hpp> #include <mutex> #include <stack> #include <set> #include <vector> #include <intrin.h> #include <detours.h> #include "fp_call.h" #include "../remotedebug/rdebug_delayload.h" namespace autoattach { std::mutex lockLoadDll; std::set<std::wstring> loadedModules; std::set<lua_State*> hookLuaStates; fn_attach debuggerAttach; bool attachProcess = false; HMODULE hookDll = NULL; static bool hook_install(uintptr_t* pointer_ptr, uintptr_t detour) { LONG status; if ((status = DetourTransactionBegin()) == NO_ERROR) { if ((status = DetourUpdateThread(::GetCurrentThread())) == NO_ERROR) { if ((status = DetourAttach((PVOID*)pointer_ptr, (PVOID)detour)) == NO_ERROR) { if ((status = DetourTransactionCommit()) == NO_ERROR) { return true; } } } DetourTransactionAbort(); } ::SetLastError(status); return false; } static bool hook_uninstall(uintptr_t* pointer_ptr, uintptr_t detour) { LONG status; if ((status = DetourTransactionBegin()) == NO_ERROR) { if ((status = DetourUpdateThread(::GetCurrentThread())) == NO_ERROR) { if ((status = DetourDetach((PVOID*)pointer_ptr, (PVOID)detour)) == NO_ERROR) { if ((status = DetourTransactionCommit()) == NO_ERROR) { return true; } } } DetourTransactionAbort(); } ::SetLastError(status); return false; } namespace lua { namespace real { uintptr_t luaL_openlibs = 0; uintptr_t lua_close = 0; uintptr_t lua_settop = 0; } namespace fake_launch { static void __cdecl luaL_openlibs(lua_State* L) { base::c_call<void>(real::luaL_openlibs, L); debuggerAttach(L); } } namespace fake_attach { static void __cdecl luaL_openlibs(lua_State* L) { base::c_call<void>(real::luaL_openlibs, L); if (hookLuaStates.insert(L).second) { debuggerAttach(L); } } static void __cdecl lua_settop(lua_State *L, int index) { if (hookLuaStates.insert(L).second) { debuggerAttach(L); } return base::c_call<void>(real::lua_settop, L, index); } static void __cdecl lua_close(lua_State* L) { hookLuaStates.erase(L); return base::c_call<void>(real::lua_close, L); } } bool hook(HMODULE m) { struct Hook { uintptr_t& real; uintptr_t fake; }; std::vector<Hook> tasks; #define HOOK(type, name) do {\ if (!real::##name) { \ real::##name = (uintptr_t)GetProcAddress(m, #name); \ if (!real::##name) return false; \ tasks.push_back({real::##name, (uintptr_t)fake_##type##::##name}); \ } \ } while (0) if (attachProcess) { HOOK(attach, luaL_openlibs); HOOK(attach, lua_close); HOOK(attach, lua_settop); } else { HOOK(launch, luaL_openlibs); } for (size_t i = 0; i < tasks.size(); ++i) { if (!hook_install(&tasks[i].real, tasks[i].fake)) { for (ptrdiff_t j = i - 1; j >= 0; ++j) { hook_uninstall(&tasks[j].real, tasks[j].fake); } return false; } } return true; } } static HMODULE enumerateModules(HANDLE hProcess, HMODULE hModuleLast, PIMAGE_NT_HEADERS32 pNtHeader) { MEMORY_BASIC_INFORMATION mbi = { 0 }; for (PBYTE pbLast = (PBYTE)hModuleLast + 0x10000;; pbLast = (PBYTE)mbi.BaseAddress + mbi.RegionSize) { if (VirtualQueryEx(hProcess, (PVOID)pbLast, &mbi, sizeof(mbi)) <= 0) { break; } if (((PBYTE)mbi.BaseAddress + mbi.RegionSize) < pbLast) { break; } if ((mbi.State != MEM_COMMIT) || ((mbi.Protect & 0xff) == PAGE_NOACCESS) || (mbi.Protect & PAGE_GUARD)) { continue; } __try { IMAGE_DOS_HEADER idh; if (!ReadProcessMemory(hProcess, pbLast, &idh, sizeof(idh), NULL)) { continue; } if (idh.e_magic != IMAGE_DOS_SIGNATURE || (DWORD)idh.e_lfanew > mbi.RegionSize || (DWORD)idh.e_lfanew < sizeof(idh)) { continue; } if (!ReadProcessMemory(hProcess, pbLast + idh.e_lfanew, pNtHeader, sizeof(*pNtHeader), NULL)) { continue; } if (pNtHeader->Signature != IMAGE_NT_SIGNATURE) { continue; } return (HMODULE)pbLast; } __except (EXCEPTION_EXECUTE_HANDLER) { continue; } } return NULL; } static bool tryHookLuaDll(HMODULE hModule) { if (hookDll) { return true; } wchar_t moduleName[MAX_PATH]; GetModuleFileNameW(hModule, moduleName, MAX_PATH); if (loadedModules.find(moduleName) != loadedModules.end()) { return false; } loadedModules.insert(moduleName); if (!lua::hook(hModule)) { return false; } hookDll = hModule; remotedebug::delayload::set_luadll(hModule); remotedebug::delayload::set_luaapi(luaapi); return true; } static bool findLuaDll() { std::unique_lock<std::mutex> lock(lockLoadDll); HANDLE hProcess = GetCurrentProcess(); HMODULE hModule = NULL; for (;;) { IMAGE_NT_HEADERS32 inh; if ((hModule = enumerateModules(hProcess, hModule, &inh)) == NULL) { break; } if (tryHookLuaDll(hModule)) { return true; } } return false; } uintptr_t realLoadLibraryExW = 0; HMODULE __stdcall fakeLoadLibraryExW(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags) { HMODULE hModule = base::std_call<HMODULE>(realLoadLibraryExW, lpLibFileName, hFile, dwFlags); std::unique_lock<std::mutex> lock(lockLoadDll); tryHookLuaDll(hModule); return hModule; } static void waitLuaDll() { HMODULE hModuleKernel = GetModuleHandleW(L"kernel32.dll"); if (hModuleKernel) { realLoadLibraryExW = (uintptr_t)GetProcAddress(hModuleKernel, "LoadLibraryExW"); if (realLoadLibraryExW) { hook_install(&realLoadLibraryExW, (uintptr_t)fakeLoadLibraryExW); } } } void initialize(fn_attach attach, bool ap) { if (debuggerAttach) { if (!attachProcess && ap && hookDll) { attachProcess = ap; lua::hook(hookDll); } return; } debuggerAttach = attach; attachProcess = ap; if (!findLuaDll()) { waitLuaDll(); } } FARPROC luaapi(const char* name) { #define FIND(api) \ if (lua::real::##api && strcmp(name, #api) == 0) { \ return (FARPROC)lua::real::##api; \ } FIND(luaL_openlibs) FIND(lua_close) FIND(lua_settop) return 0; #undef FIND } } <commit_msg>修正一个错误<commit_after>#include "autoattach.h" #include <lua.hpp> #include <mutex> #include <stack> #include <set> #include <vector> #include <intrin.h> #include <detours.h> #include "fp_call.h" #include "../remotedebug/rdebug_delayload.h" namespace autoattach { std::mutex lockLoadDll; std::set<std::wstring> loadedModules; std::set<lua_State*> hookLuaStates; fn_attach debuggerAttach; bool attachProcess = false; HMODULE hookDll = NULL; static bool hook_install(uintptr_t* pointer_ptr, uintptr_t detour) { LONG status; if ((status = DetourTransactionBegin()) == NO_ERROR) { if ((status = DetourUpdateThread(::GetCurrentThread())) == NO_ERROR) { if ((status = DetourAttach((PVOID*)pointer_ptr, (PVOID)detour)) == NO_ERROR) { if ((status = DetourTransactionCommit()) == NO_ERROR) { return true; } } } DetourTransactionAbort(); } ::SetLastError(status); return false; } static bool hook_uninstall(uintptr_t* pointer_ptr, uintptr_t detour) { LONG status; if ((status = DetourTransactionBegin()) == NO_ERROR) { if ((status = DetourUpdateThread(::GetCurrentThread())) == NO_ERROR) { if ((status = DetourDetach((PVOID*)pointer_ptr, (PVOID)detour)) == NO_ERROR) { if ((status = DetourTransactionCommit()) == NO_ERROR) { return true; } } } DetourTransactionAbort(); } ::SetLastError(status); return false; } namespace lua { namespace real { uintptr_t luaL_openlibs = 0; uintptr_t lua_close = 0; uintptr_t lua_settop = 0; } namespace fake_launch { static void __cdecl luaL_openlibs(lua_State* L) { base::c_call<void>(real::luaL_openlibs, L); debuggerAttach(L); } } namespace fake_attach { static void __cdecl luaL_openlibs(lua_State* L) { base::c_call<void>(real::luaL_openlibs, L); if (hookLuaStates.insert(L).second) { debuggerAttach(L); } } static void __cdecl lua_settop(lua_State *L, int index) { if (hookLuaStates.insert(L).second) { debuggerAttach(L); } return base::c_call<void>(real::lua_settop, L, index); } static void __cdecl lua_close(lua_State* L) { base::c_call<void>(real::lua_close, L); hookLuaStates.erase(L); } } bool hook(HMODULE m) { struct Hook { uintptr_t& real; uintptr_t fake; }; std::vector<Hook> tasks; #define HOOK(type, name) do {\ if (!real::##name) { \ real::##name = (uintptr_t)GetProcAddress(m, #name); \ if (!real::##name) return false; \ tasks.push_back({real::##name, (uintptr_t)fake_##type##::##name}); \ } \ } while (0) if (attachProcess) { HOOK(attach, luaL_openlibs); HOOK(attach, lua_close); HOOK(attach, lua_settop); } else { HOOK(launch, luaL_openlibs); } for (size_t i = 0; i < tasks.size(); ++i) { if (!hook_install(&tasks[i].real, tasks[i].fake)) { for (ptrdiff_t j = i - 1; j >= 0; ++j) { hook_uninstall(&tasks[j].real, tasks[j].fake); } return false; } } return true; } } static HMODULE enumerateModules(HANDLE hProcess, HMODULE hModuleLast, PIMAGE_NT_HEADERS32 pNtHeader) { MEMORY_BASIC_INFORMATION mbi = { 0 }; for (PBYTE pbLast = (PBYTE)hModuleLast + 0x10000;; pbLast = (PBYTE)mbi.BaseAddress + mbi.RegionSize) { if (VirtualQueryEx(hProcess, (PVOID)pbLast, &mbi, sizeof(mbi)) <= 0) { break; } if (((PBYTE)mbi.BaseAddress + mbi.RegionSize) < pbLast) { break; } if ((mbi.State != MEM_COMMIT) || ((mbi.Protect & 0xff) == PAGE_NOACCESS) || (mbi.Protect & PAGE_GUARD)) { continue; } __try { IMAGE_DOS_HEADER idh; if (!ReadProcessMemory(hProcess, pbLast, &idh, sizeof(idh), NULL)) { continue; } if (idh.e_magic != IMAGE_DOS_SIGNATURE || (DWORD)idh.e_lfanew > mbi.RegionSize || (DWORD)idh.e_lfanew < sizeof(idh)) { continue; } if (!ReadProcessMemory(hProcess, pbLast + idh.e_lfanew, pNtHeader, sizeof(*pNtHeader), NULL)) { continue; } if (pNtHeader->Signature != IMAGE_NT_SIGNATURE) { continue; } return (HMODULE)pbLast; } __except (EXCEPTION_EXECUTE_HANDLER) { continue; } } return NULL; } static bool tryHookLuaDll(HMODULE hModule) { if (hookDll) { return true; } wchar_t moduleName[MAX_PATH]; GetModuleFileNameW(hModule, moduleName, MAX_PATH); if (loadedModules.find(moduleName) != loadedModules.end()) { return false; } loadedModules.insert(moduleName); if (!lua::hook(hModule)) { return false; } hookDll = hModule; remotedebug::delayload::set_luadll(hModule); remotedebug::delayload::set_luaapi(luaapi); return true; } static bool findLuaDll() { std::unique_lock<std::mutex> lock(lockLoadDll); HANDLE hProcess = GetCurrentProcess(); HMODULE hModule = NULL; for (;;) { IMAGE_NT_HEADERS32 inh; if ((hModule = enumerateModules(hProcess, hModule, &inh)) == NULL) { break; } if (tryHookLuaDll(hModule)) { return true; } } return false; } uintptr_t realLoadLibraryExW = 0; HMODULE __stdcall fakeLoadLibraryExW(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags) { HMODULE hModule = base::std_call<HMODULE>(realLoadLibraryExW, lpLibFileName, hFile, dwFlags); std::unique_lock<std::mutex> lock(lockLoadDll); tryHookLuaDll(hModule); return hModule; } static void waitLuaDll() { HMODULE hModuleKernel = GetModuleHandleW(L"kernel32.dll"); if (hModuleKernel) { realLoadLibraryExW = (uintptr_t)GetProcAddress(hModuleKernel, "LoadLibraryExW"); if (realLoadLibraryExW) { hook_install(&realLoadLibraryExW, (uintptr_t)fakeLoadLibraryExW); } } } void initialize(fn_attach attach, bool ap) { if (debuggerAttach) { if (!attachProcess && ap && hookDll) { attachProcess = ap; lua::hook(hookDll); } return; } debuggerAttach = attach; attachProcess = ap; if (!findLuaDll()) { waitLuaDll(); } } FARPROC luaapi(const char* name) { #define FIND(api) \ if (lua::real::##api && strcmp(name, #api) == 0) { \ return (FARPROC)lua::real::##api; \ } FIND(luaL_openlibs) FIND(lua_close) FIND(lua_settop) return 0; #undef FIND } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * This file is part of the libetonyek 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/. */ #include <algorithm> #include <cassert> #include "libetonyek_utils.h" #include "KEYMemoryStream.h" namespace libetonyek { KEYMemoryStream::KEYMemoryStream(const RVNGInputStreamPtr_t &input) : m_data(0) , m_length(0) , m_pos(0) { const unsigned long begin = input->tell(); if (input->seek(0, librevenge::RVNG_SEEK_END)) { while (!input->isEnd()) readU8(input); } const unsigned long end = input->tell(); input->seek(begin, librevenge::RVNG_SEEK_SET); read(input, static_cast<unsigned>(end - begin)); } KEYMemoryStream::KEYMemoryStream(const RVNGInputStreamPtr_t &input, const unsigned length) : m_data(0) , m_length(0) , m_pos(0) { read(input, length); } KEYMemoryStream::KEYMemoryStream(std::vector<unsigned char> &data) : m_data(0) , m_length(data.size()) , m_pos(0) { if (data.empty()) throw GenericException(); assign(&data[0], data.size()); } KEYMemoryStream::KEYMemoryStream(const unsigned char *const data, const unsigned length) : m_data(0) , m_length(length) , m_pos(0) { if (0 == length) throw GenericException(); assign(data, length); } KEYMemoryStream::~KEYMemoryStream() { delete[] m_data; } bool KEYMemoryStream::isStructured() { return false; } unsigned KEYMemoryStream::subStreamCount() { return 0; } const char *KEYMemoryStream::subStreamName(unsigned) { return 0; } librevenge::RVNGInputStream *KEYMemoryStream::getSubStreamByName(const char *) { return 0; } librevenge::RVNGInputStream *KEYMemoryStream::getSubStreamById(unsigned) { return 0; } const unsigned char *KEYMemoryStream::read(unsigned long numBytes, unsigned long &numBytesRead) try { numBytesRead = 0; if (0 == numBytes) return 0; if ((m_pos + numBytes) >= static_cast<unsigned long>(m_length)) numBytes = static_cast<unsigned long>(m_length - m_pos); const long oldPos = m_pos; m_pos += numBytes; numBytesRead = numBytes; return m_data + oldPos; } catch (...) { return 0; } int KEYMemoryStream::seek(const long offset, librevenge::RVNG_SEEK_TYPE seekType) try { long pos = 0; switch (seekType) { case librevenge::RVNG_SEEK_SET : pos = offset; break; case librevenge::RVNG_SEEK_CUR : pos = offset + m_pos; break; case librevenge::RVNG_SEEK_END : pos = offset + m_length; break; default : return -1; } if ((pos < 0) || (pos > m_length)) return 1; m_pos = pos; return 0; } catch (...) { return -1; } long KEYMemoryStream::tell() { return m_pos; } bool KEYMemoryStream::isEnd() { return m_length == m_pos; } void KEYMemoryStream::assign(const unsigned char *const data, const unsigned length) { assert(0 != length); unsigned char *buffer = new unsigned char[length]; std::copy(data, data + length, buffer); m_data = buffer; } void KEYMemoryStream::read(const RVNGInputStreamPtr_t &input, const unsigned length) { if (0 == length) return; unsigned long readBytes = 0; const unsigned char *const data = bool(input) ? input->read(length, readBytes) : 0; if (length != readBytes) throw EndOfStreamException(); m_length = length; assign(data, length); } } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */ <commit_msg>CID#1130378 rearrange a bit<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * This file is part of the libetonyek 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/. */ #include <algorithm> #include <cassert> #include "libetonyek_utils.h" #include "KEYMemoryStream.h" namespace libetonyek { KEYMemoryStream::KEYMemoryStream(const RVNGInputStreamPtr_t &input) : m_data(0) , m_length(0) , m_pos(0) { const unsigned long begin = input->tell(); if (input->seek(0, librevenge::RVNG_SEEK_END)) { while (!input->isEnd()) readU8(input); } const unsigned long end = input->tell(); input->seek(begin, librevenge::RVNG_SEEK_SET); read(input, static_cast<unsigned>(end - begin)); } KEYMemoryStream::KEYMemoryStream(const RVNGInputStreamPtr_t &input, const unsigned length) : m_data(0) , m_length(0) , m_pos(0) { read(input, length); } KEYMemoryStream::KEYMemoryStream(std::vector<unsigned char> &data) : m_data(0) , m_length(data.size()) , m_pos(0) { if (data.empty()) throw GenericException(); assign(&data[0], data.size()); } KEYMemoryStream::KEYMemoryStream(const unsigned char *const data, const unsigned length) : m_data(0) , m_length(length) , m_pos(0) { if (0 == length) throw GenericException(); assign(data, length); } KEYMemoryStream::~KEYMemoryStream() { delete[] m_data; } bool KEYMemoryStream::isStructured() { return false; } unsigned KEYMemoryStream::subStreamCount() { return 0; } const char *KEYMemoryStream::subStreamName(unsigned) { return 0; } librevenge::RVNGInputStream *KEYMemoryStream::getSubStreamByName(const char *) { return 0; } librevenge::RVNGInputStream *KEYMemoryStream::getSubStreamById(unsigned) { return 0; } const unsigned char *KEYMemoryStream::read(unsigned long numBytes, unsigned long &numBytesRead) try { numBytesRead = 0; if (0 == numBytes) return 0; if ((m_pos + numBytes) >= static_cast<unsigned long>(m_length)) numBytes = static_cast<unsigned long>(m_length - m_pos); const long oldPos = m_pos; m_pos += numBytes; numBytesRead = numBytes; return m_data + oldPos; } catch (...) { return 0; } int KEYMemoryStream::seek(const long offset, librevenge::RVNG_SEEK_TYPE seekType) try { long pos = 0; switch (seekType) { case librevenge::RVNG_SEEK_SET : pos = offset; break; case librevenge::RVNG_SEEK_CUR : pos = offset + m_pos; break; case librevenge::RVNG_SEEK_END : pos = offset + m_length; break; default : return -1; } if ((pos < 0) || (pos > m_length)) return 1; m_pos = pos; return 0; } catch (...) { return -1; } long KEYMemoryStream::tell() { return m_pos; } bool KEYMemoryStream::isEnd() { return m_length == m_pos; } void KEYMemoryStream::assign(const unsigned char *const data, const unsigned length) { assert(0 != length); unsigned char *buffer = new unsigned char[length]; std::copy(data, data + length, buffer); m_data = buffer; } void KEYMemoryStream::read(const RVNGInputStreamPtr_t &input, const unsigned length) { if (0 == length) return; if (!bool(input)) throw EndOfStreamException(); unsigned long readBytes = 0; const unsigned char *const data = input->read(length, readBytes); if (length != readBytes) throw EndOfStreamException(); m_length = length; assign(data, length); } } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */ <|endoftext|>
<commit_before>/* Copyright (C) 2003 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <ndb_global.h> #include <NdbTCP.h> #include <socket_io.h> #include <NdbOut.hpp> extern "C" int read_socket(NDB_SOCKET_TYPE socket, int timeout_millis, char * buf, int buflen){ if(buflen < 1) return 0; fd_set readset; FD_ZERO(&readset); FD_SET(socket, &readset); struct timeval timeout; timeout.tv_sec = (timeout_millis / 1000); timeout.tv_usec = (timeout_millis % 1000) * 1000; const int selectRes = select(socket + 1, &readset, 0, 0, &timeout); if(selectRes == 0) return 0; if(selectRes == -1){ return -1; } return recv(socket, &buf[0], buflen, 0); } extern "C" int readln_socket(NDB_SOCKET_TYPE socket, int timeout_millis, char * buf, int buflen){ if(buflen <= 1) return 0; int sock_flags= fcntl(socket, F_GETFL); if(fcntl(socket, F_SETFL, sock_flags | O_NONBLOCK) == -1) return -1; fd_set readset; FD_ZERO(&readset); FD_SET(socket, &readset); struct timeval timeout; timeout.tv_sec = (timeout_millis / 1000); timeout.tv_usec = (timeout_millis % 1000) * 1000; const int selectRes = select(socket + 1, &readset, 0, 0, &timeout); if(selectRes == 0){ return 0; } if(selectRes == -1){ fcntl(socket, F_SETFL, sock_flags); return -1; } buf[0] = 0; const int t = recv(socket, buf, buflen, MSG_PEEK); if(t < 1) { fcntl(socket, F_SETFL, sock_flags); return -1; } for(int i=0; i< t;i++) { if(buf[i] == '\n'){ recv(socket, buf, i+1, 0); buf[i] = 0; if(i > 0 && buf[i-1] == '\r'){ i--; buf[i] = 0; } fcntl(socket, F_SETFL, sock_flags); return t; } } if(t == (buflen - 1)){ recv(socket, buf, t, 0); buf[t] = 0; fcntl(socket, F_SETFL, sock_flags); return buflen; } return 0; } extern "C" int write_socket(NDB_SOCKET_TYPE socket, int timeout_millis, const char buf[], int len){ fd_set writeset; FD_ZERO(&writeset); FD_SET(socket, &writeset); struct timeval timeout; timeout.tv_sec = (timeout_millis / 1000); timeout.tv_usec = (timeout_millis % 1000) * 1000; const int selectRes = select(socket + 1, 0, &writeset, 0, &timeout); if(selectRes != 1){ return -1; } const char * tmp = &buf[0]; while(len > 0){ const int w = send(socket, tmp, len, 0); if(w == -1){ return -1; } len -= w; tmp += w; if(len == 0) break; FD_ZERO(&writeset); FD_SET(socket, &writeset); timeout.tv_sec = 1; timeout.tv_usec = 0; const int selectRes = select(socket + 1, 0, &writeset, 0, &timeout); if(selectRes != 1){ return -1; } } return 0; } extern "C" int print_socket(NDB_SOCKET_TYPE socket, int timeout_millis, const char * fmt, ...){ va_list ap; va_start(ap, fmt); int ret = vprint_socket(socket, timeout_millis, fmt, ap); va_end(ap); return ret; } extern "C" int println_socket(NDB_SOCKET_TYPE socket, int timeout_millis, const char * fmt, ...){ va_list ap; va_start(ap, fmt); int ret = vprintln_socket(socket, timeout_millis, fmt, ap); va_end(ap); return ret; } extern "C" int vprint_socket(NDB_SOCKET_TYPE socket, int timeout_millis, const char * fmt, va_list ap){ char buf[1000]; char *buf2 = buf; size_t size; if (fmt != 0 && fmt[0] != 0) { size = BaseString::vsnprintf(buf, sizeof(buf), fmt, ap); /* Check if the output was truncated */ if(size > sizeof(buf)) { buf2 = (char *)malloc(size); if(buf2 == NULL) return -1; BaseString::vsnprintf(buf2, size, fmt, ap); } } else return 0; int ret = write_socket(socket, timeout_millis, buf2, size); if(buf2 != buf) free(buf2); return ret; } extern "C" int vprintln_socket(NDB_SOCKET_TYPE socket, int timeout_millis, const char * fmt, va_list ap){ char buf[1000]; char *buf2 = buf; size_t size; if (fmt != 0 && fmt[0] != 0) { size = BaseString::vsnprintf(buf, sizeof(buf), fmt, ap)+1;// extra byte for '/n' /* Check if the output was truncated */ if(size > sizeof(buf)) { buf2 = (char *)malloc(size); if(buf2 == NULL) return -1; BaseString::vsnprintf(buf2, size, fmt, ap); } } else { size = 1; } buf2[size-1]='\n'; int ret = write_socket(socket, timeout_millis, buf2, size); if(buf2 != buf) free(buf2); return ret; } #ifdef NDB_WIN32 class INIT_WINSOCK2 { public: INIT_WINSOCK2(void); ~INIT_WINSOCK2(void); private: bool m_bAcceptable; }; INIT_WINSOCK2 g_init_winsock2; INIT_WINSOCK2::INIT_WINSOCK2(void) : m_bAcceptable(false) { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD( 2, 2 ); err = WSAStartup( wVersionRequested, &wsaData ); if ( err != 0 ) { /* Tell the user that we could not find a usable */ /* WinSock DLL. */ m_bAcceptable = false; } /* Confirm that the WinSock DLL supports 2.2.*/ /* Note that if the DLL supports versions greater */ /* than 2.2 in addition to 2.2, it will still return */ /* 2.2 in wVersion since that is the version we */ /* requested. */ if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 ) { /* Tell the user that we could not find a usable */ /* WinSock DLL. */ WSACleanup( ); m_bAcceptable = false; } /* The WinSock DLL is acceptable. Proceed. */ m_bAcceptable = true; } INIT_WINSOCK2::~INIT_WINSOCK2(void) { if(m_bAcceptable) { m_bAcceptable = false; WSACleanup(); } } #endif <commit_msg>ndb - bug#24011 <commit_after>/* Copyright (C) 2003 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <ndb_global.h> #include <NdbTCP.h> #include <socket_io.h> #include <NdbOut.hpp> extern "C" int read_socket(NDB_SOCKET_TYPE socket, int timeout_millis, char * buf, int buflen){ if(buflen < 1) return 0; fd_set readset; FD_ZERO(&readset); FD_SET(socket, &readset); struct timeval timeout; timeout.tv_sec = (timeout_millis / 1000); timeout.tv_usec = (timeout_millis % 1000) * 1000; const int selectRes = select(socket + 1, &readset, 0, 0, &timeout); if(selectRes == 0) return 0; if(selectRes == -1){ return -1; } return recv(socket, &buf[0], buflen, 0); } extern "C" int readln_socket(NDB_SOCKET_TYPE socket, int timeout_millis, char * buf, int buflen){ if(buflen <= 1) return 0; fd_set readset; FD_ZERO(&readset); FD_SET(socket, &readset); struct timeval timeout; timeout.tv_sec = (timeout_millis / 1000); timeout.tv_usec = (timeout_millis % 1000) * 1000; const int selectRes = select(socket + 1, &readset, 0, 0, &timeout); if(selectRes == 0){ return 0; } if(selectRes == -1){ return -1; } char* ptr = buf; int len = buflen; do { int t; while((t = recv(socket, ptr, len, MSG_PEEK)) == -1 && errno == EINTR); if(t < 1) { return -1; } for(int i = 0; i<t; i++) { if(ptr[i] == '\n') { /** * Now consume */ for (len = 1 + i; len; ) { while ((t = recv(socket, ptr, len, 0)) == -1 && errno == EINTR); if (t < 1) return -1; ptr += t; len -= t; } ptr[0]= 0; return ptr - buf; } } for (int tmp = t; tmp; ) { while ((t = recv(socket, ptr, tmp, 0)) == -1 && errno == EINTR); if (t < 1) { return -1; } ptr += t; len -= t; tmp -= t; } FD_ZERO(&readset); FD_SET(socket, &readset); timeout.tv_sec = (timeout_millis / 1000); timeout.tv_usec = (timeout_millis % 1000) * 1000; const int selectRes = select(socket + 1, &readset, 0, 0, &timeout); if(selectRes != 1){ return -1; } } while (len > 0); return -1; } extern "C" int write_socket(NDB_SOCKET_TYPE socket, int timeout_millis, const char buf[], int len){ fd_set writeset; FD_ZERO(&writeset); FD_SET(socket, &writeset); struct timeval timeout; timeout.tv_sec = (timeout_millis / 1000); timeout.tv_usec = (timeout_millis % 1000) * 1000; const int selectRes = select(socket + 1, 0, &writeset, 0, &timeout); if(selectRes != 1){ return -1; } const char * tmp = &buf[0]; while(len > 0){ const int w = send(socket, tmp, len, 0); if(w == -1){ return -1; } len -= w; tmp += w; if(len == 0) break; FD_ZERO(&writeset); FD_SET(socket, &writeset); timeout.tv_sec = 1; timeout.tv_usec = 0; const int selectRes = select(socket + 1, 0, &writeset, 0, &timeout); if(selectRes != 1){ return -1; } } return 0; } extern "C" int print_socket(NDB_SOCKET_TYPE socket, int timeout_millis, const char * fmt, ...){ va_list ap; va_start(ap, fmt); int ret = vprint_socket(socket, timeout_millis, fmt, ap); va_end(ap); return ret; } extern "C" int println_socket(NDB_SOCKET_TYPE socket, int timeout_millis, const char * fmt, ...){ va_list ap; va_start(ap, fmt); int ret = vprintln_socket(socket, timeout_millis, fmt, ap); va_end(ap); return ret; } extern "C" int vprint_socket(NDB_SOCKET_TYPE socket, int timeout_millis, const char * fmt, va_list ap){ char buf[1000]; char *buf2 = buf; size_t size; if (fmt != 0 && fmt[0] != 0) { size = BaseString::vsnprintf(buf, sizeof(buf), fmt, ap); /* Check if the output was truncated */ if(size > sizeof(buf)) { buf2 = (char *)malloc(size); if(buf2 == NULL) return -1; BaseString::vsnprintf(buf2, size, fmt, ap); } } else return 0; int ret = write_socket(socket, timeout_millis, buf2, size); if(buf2 != buf) free(buf2); return ret; } extern "C" int vprintln_socket(NDB_SOCKET_TYPE socket, int timeout_millis, const char * fmt, va_list ap){ char buf[1000]; char *buf2 = buf; size_t size; if (fmt != 0 && fmt[0] != 0) { size = BaseString::vsnprintf(buf, sizeof(buf), fmt, ap)+1;// extra byte for '/n' /* Check if the output was truncated */ if(size > sizeof(buf)) { buf2 = (char *)malloc(size); if(buf2 == NULL) return -1; BaseString::vsnprintf(buf2, size, fmt, ap); } } else { size = 1; } buf2[size-1]='\n'; int ret = write_socket(socket, timeout_millis, buf2, size); if(buf2 != buf) free(buf2); return ret; } #ifdef NDB_WIN32 class INIT_WINSOCK2 { public: INIT_WINSOCK2(void); ~INIT_WINSOCK2(void); private: bool m_bAcceptable; }; INIT_WINSOCK2 g_init_winsock2; INIT_WINSOCK2::INIT_WINSOCK2(void) : m_bAcceptable(false) { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD( 2, 2 ); err = WSAStartup( wVersionRequested, &wsaData ); if ( err != 0 ) { /* Tell the user that we could not find a usable */ /* WinSock DLL. */ m_bAcceptable = false; } /* Confirm that the WinSock DLL supports 2.2.*/ /* Note that if the DLL supports versions greater */ /* than 2.2 in addition to 2.2, it will still return */ /* 2.2 in wVersion since that is the version we */ /* requested. */ if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 ) { /* Tell the user that we could not find a usable */ /* WinSock DLL. */ WSACleanup( ); m_bAcceptable = false; } /* The WinSock DLL is acceptable. Proceed. */ m_bAcceptable = true; } INIT_WINSOCK2::~INIT_WINSOCK2(void) { if(m_bAcceptable) { m_bAcceptable = false; WSACleanup(); } } #endif <|endoftext|>
<commit_before>#include "CharacterSelectState.h" #include "Game.h" #include "MenuState.h" #include "BattleState.h" CharacterSelectState::CharacterSelectState(){ background = Sprite("character_select/background.png"); character_slots = Sprite("character_select/character_slots.png"); // FIXME 2 enabled characters for(int i=0;i<2;i++){ available_skin[get_char_info(i).first].assign(4, true); char_name[get_char_info(i).first] = Sprite("character_select/chars/" + get_char_info(i).first + "/name.png"); // loop to get skins for(int j=0;j<4;j++){ char_sprite[get_char_info(i).first].push_back(Sprite("character_select/chars/" + get_char_info(i).first + "/" + to_string(j) + ".png", get_char_info(i).second, 13)); char_sprite[get_char_info(i).first][j].set_scale_x(3); char_sprite[get_char_info(i).first][j].set_scale_y(3); } } for(int i=0;i<4;i++){ name_tag[i] = Sprite("character_select/name_tag_" + to_string(i + 1) + ".png"); number[i] = Sprite("character_select/number_" + to_string(i + 1) + ".png"); } names = { {"flesh",""}, {"blood",""}, {"",""}, {"",""} }; memset(cur_selection_col, 0, sizeof cur_selection_col); memset(cur_selection_row, 0, sizeof cur_selection_row); memset(cur_skin, 0, sizeof cur_skin); memset(selected, false, sizeof selected); name_tag_positions = { ii(91, 234), ii(92, 583), ii(956, 234), ii(955, 583) }; number_delta = { ii(12, 9), ii(93, 9), ii(12, 101), ii(93, 101) }; name_delta = { ii(118, 53), ii(117, 55), ii(47, 54), ii(50, 54) }; sprite_pos = { ii(155, 32), ii(141, 379), ii(923, 34), ii(946, 381) }; col_slots = { 510, 645 }; row_slots = { 55, 197, 395, 536 }; } void CharacterSelectState::update(float delta){ InputManager * input_manager = InputManager::get_instance(); // inputs if(input_manager->quit_requested() || input_manager->key_press(SDLK_ESCAPE) || (not selected[0] && input_manager->joystick_button_press(InputManager::B, 0)) || input_manager->joystick_button_press(InputManager::SELECT, 0)){ m_quit_requested = true; Game::get_instance().push(new MenuState(true)); return; } // only enable start when all players have selected a character if(all_players_selected()){ if(input_manager->key_press(SDLK_RETURN) || input_manager->joystick_button_press(InputManager::START, 0)){ m_quit_requested = true; Game::get_instance().push(new BattleState("1", "swamp_song.ogg")); return; } } for(int i=0;i<4;i++){ if(not selected[i]){ if((input_manager->key_press(SDLK_LEFT) || input_manager->joystick_button_press(InputManager::LEFT, i)) && cur_selection_col[i] != 0){ if(character_enabled(cur_selection_row[i], cur_selection_col[i] - 1)) cur_selection_col[i]--; } if((input_manager->key_press(SDLK_RIGHT) || input_manager->joystick_button_press(InputManager::RIGHT, i)) && cur_selection_col[i] != 1){ if(character_enabled(cur_selection_row[i], cur_selection_col[i] + 1)) cur_selection_col[i]++; } if((input_manager->key_press(SDLK_UP) || input_manager->joystick_button_press(InputManager::UP, i)) && cur_selection_row[i] != 0){ if(character_enabled(cur_selection_row[i] - 1, cur_selection_col[i])) cur_selection_row[i]--; } if((input_manager->key_press(SDLK_DOWN) || input_manager->joystick_button_press(InputManager::DOWN, i)) && cur_selection_row[i] != 3){ if(character_enabled(cur_selection_row[i] + 1, cur_selection_col[i])) cur_selection_row[i]++; } // skins if(input_manager->key_press(SDLK_COMMA) || input_manager->joystick_button_press(InputManager::LT, i)){ cur_skin[i] = (cur_skin[i] - 1 + 4) % 4; } if(input_manager->key_press(SDLK_PERIOD) || input_manager->joystick_button_press(InputManager::RT, i)){ cur_skin[i] = (cur_skin[i] + 1) % 4; } // select character && lock skin if(input_manager->key_press(SDLK_x) || input_manager->joystick_button_press(InputManager::A, i)){ int col_sel = cur_selection_col[i]; int row_sel = cur_selection_row[i]; string char_selected = names[col_sel][row_sel]; if(not available_skin[char_selected][cur_skin[i]]){ printf("SKIN [%d] of [%s] ALREADY CHOSEN\n", cur_skin[i], char_selected.c_str()); } else{ printf("PLAYER %d CHOSE SKIN [%d] of [%s]\n", i + 1, cur_skin[i], char_selected.c_str()); available_skin[char_selected][cur_skin[i]] = false; selected[i] = true; } } } else{ // unselect character if(input_manager->key_press(SDLK_y) || input_manager->joystick_button_press(InputManager::B, i)){ int col_sel = cur_selection_col[i]; int row_sel = cur_selection_row[i]; string char_selected = names[col_sel][row_sel]; available_skin[char_selected][cur_skin[i]] = true; selected[i] = false; printf("PLAYER %d UNSELECTED SKIN [%d] of [%s]\n", i + 1, cur_skin[i], char_selected.c_str()); } } } for(auto it = char_sprite.begin(); it != char_sprite.end(); it++){ for(int i=0; i < (*it).second.size(); i++){ (*it).second[i].update(delta); } } } void CharacterSelectState::render(){ background.render(0, 0); character_slots.render(0, 0); for(int i=0;i<4;i++){ int col_sel = cur_selection_col[i]; int row_sel = cur_selection_row[i]; string char_selected = names[col_sel][row_sel]; char_sprite[char_selected][cur_skin[i]].render(sprite_pos[i].first, sprite_pos[i].second); name_tag[i].render(name_tag_positions[i].first, name_tag_positions[i].second); char_name[char_selected].render( name_tag_positions[i].first + name_delta[i].first, name_tag_positions[i].second + name_delta[i].second ); number[i].render(col_slots[col_sel] + number_delta[i].first, row_slots[row_sel] + number_delta[i].second); } } void CharacterSelectState::pause(){ } void CharacterSelectState::resume(){ } bool CharacterSelectState::character_enabled(int row, int){ // Only characters in first row are available return row == 0; } // returns name and number of frames in corresponding sprite pair<string, int> CharacterSelectState::get_char_info(int idx){ switch(idx){ case 0: return pair<string, int> ("flesh", 12); case 1: return pair<string, int> ("blood", 8); } } bool CharacterSelectState::all_players_selected(){ for(auto cur : selected) if(not cur) return false; return true; } <commit_msg>Add constants to character select menu<commit_after>#include "CharacterSelectState.h" #include "Game.h" #include "MenuState.h" #include "BattleState.h" #define AVAILABLE_CHARS 2 #define NUMBER_OF_PLAYERS 4 #define AVAILABLE_SKINS 4 #define FIRST_PLAYER 0 #define COL_SLOTS 2 #define ROW_SLOTS 4 CharacterSelectState::CharacterSelectState(){ background = Sprite("character_select/background.png"); character_slots = Sprite("character_select/character_slots.png"); for(int i=0;i<AVAILABLE_CHARS;i++){ available_skin[get_char_info(i).first].assign(AVAILABLE_SKINS, true); char_name[get_char_info(i).first] = Sprite("character_select/chars/" + get_char_info(i).first + "/name.png"); // loop to get skins for(int j=0;j<AVAILABLE_SKINS;j++){ char_sprite[get_char_info(i).first].push_back(Sprite("character_select/chars/" + get_char_info(i).first + "/" + to_string(j) + ".png", get_char_info(i).second, 13)); char_sprite[get_char_info(i).first][j].set_scale_x(3); char_sprite[get_char_info(i).first][j].set_scale_y(3); } } for(int i=0;i<NUMBER_OF_PLAYERS;i++){ name_tag[i] = Sprite("character_select/name_tag_" + to_string(i + 1) + ".png"); number[i] = Sprite("character_select/number_" + to_string(i + 1) + ".png"); } names = { {"flesh",""}, {"blood",""}, {"",""}, {"",""} }; memset(cur_selection_col, 0, sizeof cur_selection_col); memset(cur_selection_row, 0, sizeof cur_selection_row); memset(cur_skin, 0, sizeof cur_skin); memset(selected, false, sizeof selected); name_tag_positions = { ii(91, 234), ii(92, 583), ii(956, 234), ii(955, 583) }; number_delta = { ii(12, 9), ii(93, 9), ii(12, 101), ii(93, 101) }; name_delta = { ii(118, 53), ii(117, 55), ii(47, 54), ii(50, 54) }; sprite_pos = { ii(155, 32), ii(141, 379), ii(923, 34), ii(946, 381) }; col_slots = { 510, 645 }; row_slots = { 55, 197, 395, 536 }; } void CharacterSelectState::update(float delta){ InputManager * input_manager = InputManager::get_instance(); // inputs if(input_manager->quit_requested() || input_manager->key_press(SDLK_ESCAPE) || (not selected[FIRST_PLAYER] && input_manager->joystick_button_press(InputManager::B, FIRST_PLAYER)) || input_manager->joystick_button_press(InputManager::SELECT, FIRST_PLAYER)){ m_quit_requested = true; Game::get_instance().push(new MenuState(true)); return; } // only enable start when all players have selected a character if(all_players_selected()){ if(input_manager->key_press(SDLK_RETURN) || input_manager->joystick_button_press(InputManager::START, FIRST_PLAYER)){ m_quit_requested = true; Game::get_instance().push(new BattleState("1", "swamp_song.ogg")); return; } } for(int i=0;i<NUMBER_OF_PLAYERS;i++){ if(not selected[i]){ if((input_manager->key_press(SDLK_LEFT) || input_manager->joystick_button_press(InputManager::LEFT, i)) && cur_selection_col[i] != 0){ if(character_enabled(cur_selection_row[i], cur_selection_col[i] - 1)) cur_selection_col[i]--; } if((input_manager->key_press(SDLK_RIGHT) || input_manager->joystick_button_press(InputManager::RIGHT, i)) && cur_selection_col[i] + 1 < COL_SLOTS){ if(character_enabled(cur_selection_row[i], cur_selection_col[i] + 1)) cur_selection_col[i]++; } if((input_manager->key_press(SDLK_UP) || input_manager->joystick_button_press(InputManager::UP, i)) && cur_selection_row[i] != 0){ if(character_enabled(cur_selection_row[i] - 1, cur_selection_col[i])) cur_selection_row[i]--; } if((input_manager->key_press(SDLK_DOWN) || input_manager->joystick_button_press(InputManager::DOWN, i)) && cur_selection_row[i] + 1 < ROW_SLOTS){ if(character_enabled(cur_selection_row[i] + 1, cur_selection_col[i])) cur_selection_row[i]++; } // skins if(input_manager->key_press(SDLK_COMMA) || input_manager->joystick_button_press(InputManager::LT, i)){ cur_skin[i] = (cur_skin[i] - 1 + AVAILABLE_SKINS) % AVAILABLE_SKINS; } if(input_manager->key_press(SDLK_PERIOD) || input_manager->joystick_button_press(InputManager::RT, i)){ cur_skin[i] = (cur_skin[i] + 1) % AVAILABLE_SKINS; } // select character && lock skin if(input_manager->key_press(SDLK_x) || input_manager->joystick_button_press(InputManager::A, i)){ int col_sel = cur_selection_col[i]; int row_sel = cur_selection_row[i]; string char_selected = names[col_sel][row_sel]; if(not available_skin[char_selected][cur_skin[i]]){ printf("SKIN [%d] of [%s] ALREADY CHOSEN\n", cur_skin[i], char_selected.c_str()); } else{ printf("PLAYER %d CHOSE SKIN [%d] of [%s]\n", i + 1, cur_skin[i], char_selected.c_str()); available_skin[char_selected][cur_skin[i]] = false; selected[i] = true; } } } else{ // unselect character if(input_manager->key_press(SDLK_y) || input_manager->joystick_button_press(InputManager::B, i)){ int col_sel = cur_selection_col[i]; int row_sel = cur_selection_row[i]; string char_selected = names[col_sel][row_sel]; available_skin[char_selected][cur_skin[i]] = true; selected[i] = false; printf("PLAYER %d UNSELECTED SKIN [%d] of [%s]\n", i + 1, cur_skin[i], char_selected.c_str()); } } } for(auto it = char_sprite.begin(); it != char_sprite.end(); it++){ for(int i=0; i < (*it).second.size(); i++){ (*it).second[i].update(delta); } } } void CharacterSelectState::render(){ background.render(0, 0); character_slots.render(0, 0); for(int i=0;i<NUMBER_OF_PLAYERS;i++){ int col_sel = cur_selection_col[i]; int row_sel = cur_selection_row[i]; string char_selected = names[col_sel][row_sel]; char_sprite[char_selected][cur_skin[i]].render(sprite_pos[i].first, sprite_pos[i].second); name_tag[i].render(name_tag_positions[i].first, name_tag_positions[i].second); char_name[char_selected].render( name_tag_positions[i].first + name_delta[i].first, name_tag_positions[i].second + name_delta[i].second ); number[i].render(col_slots[col_sel] + number_delta[i].first, row_slots[row_sel] + number_delta[i].second); } } void CharacterSelectState::pause(){ } void CharacterSelectState::resume(){ } bool CharacterSelectState::character_enabled(int row, int){ // Only characters in first row are available return row == 0; } // returns name and number of frames in corresponding sprite pair<string, int> CharacterSelectState::get_char_info(int idx){ switch(idx){ case 0: return pair<string, int> ("flesh", 12); case 1: return pair<string, int> ("blood", 8); } } bool CharacterSelectState::all_players_selected(){ for(auto cur : selected) if(not cur) return false; return true; } <|endoftext|>
<commit_before>/** \file * * Copyright (c) 2012 by Travis Gockel. All rights reserved. * * This program is free software: you can redistribute it and/or modify it under the terms of the Apache License * as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later * version. * * \author Travis Gockel ([email protected]) **/ #include <json-voorhees/object.hpp> #include "detail.hpp" #include <cstring> using namespace jsonv::detail; namespace jsonv { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // object // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define OBJ _data.object->_values object::object() { _data.object = new detail::object_impl; _kind = kind::object; } object::object(const object& source) : value(source) { } object::object(object&& source) : value(std::move(source)) { } object& object::operator =(const object& source) { value::operator=(source); return *this; } object& object::operator =(object&& source) { value::operator=(std::move(source)); return *this; } void object::ensure_object() const { check_type(kind::object, get_kind()); } object::size_type object::size() const { ensure_object(); return OBJ.size(); } object::iterator object::begin() { ensure_object(); return iterator(OBJ.begin()); } object::const_iterator object::begin() const { ensure_object(); return const_iterator(OBJ.begin()); } object::iterator object::end() { ensure_object(); return iterator(OBJ.end()); } object::const_iterator object::end() const { ensure_object(); return const_iterator(OBJ.end()); } value& object::operator[](const string_type& key) { ensure_object(); return OBJ[key]; } const value& object::operator[](const string_type& key) const { ensure_object(); return OBJ[key]; } object::size_type object::count(const key_type& key) const { ensure_object(); return OBJ.count(key); } object::iterator object::find(const string_type& key) { ensure_object(); return iterator(OBJ.find(key)); } object::const_iterator object::find(const string_type& key) const { ensure_object(); return const_iterator(OBJ.find(key)); } void object::insert(const value_type& pair) { OBJ.insert(pair); } object::size_type object::erase(const key_type& key) { ensure_object(); return OBJ.erase(key); } bool object::operator ==(const object& other) const { if (this == &other) return true; if (size() != other.size()) return false; typedef object_impl::map_type::const_iterator const_iterator; const_iterator self_iter = OBJ.begin(); const_iterator other_iter = other.OBJ.begin(); for (const const_iterator self_end = OBJ.end(); self_iter != self_end; ++self_iter, ++other_iter ) { if (self_iter->first != other_iter->first) return false; if (self_iter->second != other_iter->second) return false; } return true; } bool object::operator !=(const object& other) const { return !operator==(other); } static void stream_single(ostream_type& stream, const object_impl::map_type::value_type& pair) { stream_escaped_string(stream, pair.first) << ":" << pair.second; } ostream_type& operator <<(ostream_type& stream, const object& view) { typedef object_impl::map_type::const_iterator const_iterator; typedef object_impl::map_type::value_type value_type; const_iterator iter = view.OBJ.begin(); const_iterator end = view.OBJ.end(); stream << "{"; if (iter != end) { stream_single(stream, *iter); ++iter; } for ( ; iter != end; ++iter) { stream << ", "; stream_single(stream, *iter); } stream << "}"; return stream; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // object::basic_iterator<T> // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename T> struct object_iter_converter; template <> struct object_iter_converter<object::value_type> { union impl { char* storage; object_impl::map_type::iterator* iter; }; union const_impl { const char* storage; const object_impl::map_type::iterator* iter; }; }; template <> struct object_iter_converter<const object::value_type> { union impl { char* storage; object_impl::map_type::const_iterator* iter; }; union const_impl { const char* storage; const object_impl::map_type::const_iterator* iter; }; }; #define JSONV_INSTANTIATE_OBJVIEW_BASIC_ITERATOR_FUNC(return_, ...) \ template return_ object::basic_iterator<object::value_type>::__VA_ARGS__; \ template return_ object::basic_iterator<const object::value_type>::__VA_ARGS__; \ template <typename T> object::basic_iterator<T>::basic_iterator() { memset(_storage, 0, sizeof _storage); } JSONV_INSTANTIATE_OBJVIEW_BASIC_ITERATOR_FUNC(, basic_iterator()) // private template <typename T> template <typename U> object::basic_iterator<T>::basic_iterator(const U& source) { static_assert(sizeof(U) == sizeof(_storage), "Input must be the same size of storage"); memcpy(_storage, &source, sizeof _storage); } template <typename T> void object::basic_iterator<T>::increment() { typedef typename object_iter_converter<T>::impl converter_union; converter_union convert; convert.storage = _storage; ++(*convert.iter); } JSONV_INSTANTIATE_OBJVIEW_BASIC_ITERATOR_FUNC(void, increment()) template <typename T> void object::basic_iterator<T>::decrement() { typedef typename object_iter_converter<T>::impl converter_union; converter_union convert; convert.storage = _storage; --(*convert.iter); } JSONV_INSTANTIATE_OBJVIEW_BASIC_ITERATOR_FUNC(void, decrement()) template <typename T> T& object::basic_iterator<T>::current() const { typedef typename object_iter_converter<T>::const_impl converter_union; converter_union convert; convert.storage = _storage; return **convert.iter; } template object::value_type& object::basic_iterator<object::value_type>::current() const; template const object::value_type& object::basic_iterator<const object::value_type>::current() const; template <typename T> bool object::basic_iterator<T>::equals(const char* other_storage) const { typedef typename object_iter_converter<T>::const_impl converter_union; converter_union self_convert; self_convert.storage = _storage; converter_union other_convert; other_convert.storage = other_storage; return *self_convert.iter == *other_convert.iter; } JSONV_INSTANTIATE_OBJVIEW_BASIC_ITERATOR_FUNC(bool, equals(const char*) const) template <typename T> void object::basic_iterator<T>::copy_from(const char* other_storage) { typedef typename object_iter_converter<T>::impl converter_union; typedef typename object_iter_converter<T>::const_impl const_converter_union; converter_union self_convert; self_convert.storage = _storage; const_converter_union other_convert; other_convert.storage = other_storage; *self_convert.iter = *other_convert.iter; } JSONV_INSTANTIATE_OBJVIEW_BASIC_ITERATOR_FUNC(void, copy_from(const char*)) template <typename T> template <typename U> object::basic_iterator<T>::basic_iterator(const basic_iterator<U>& source, typename std::enable_if<std::is_convertible<U*, T*>::value>::type* ) { typedef typename object_iter_converter<T>::impl converter_union; typedef typename object_iter_converter<U>::const_impl const_converter_union; converter_union self_convert; self_convert.storage = _storage; const_converter_union other_convert; other_convert.storage = source._storage; *self_convert.iter = *other_convert.iter; } template object::basic_iterator<const object::value_type> ::basic_iterator<object::value_type>(const basic_iterator<object::value_type>&, void*); object::iterator object::erase(const_iterator position) { ensure_object(); typedef typename object_iter_converter<const object::value_type>::const_impl const_converter_union; const_converter_union pos_convert; pos_convert.storage = position._storage; return iterator(OBJ.erase(*pos_convert.iter)); } object::iterator object::erase(const_iterator first, const_iterator last) { ensure_object(); typedef typename object_iter_converter<const object::value_type>::const_impl const_converter_union; const_converter_union first_convert; first_convert.storage = first._storage; const_converter_union last_convert; last_convert.storage = last._storage; return iterator(OBJ.erase(*first_convert.iter, *last_convert.iter)); } } <commit_msg>Remove unused local typedef in operator <<(ostream_type&, const object&).<commit_after>/** \file * * Copyright (c) 2012 by Travis Gockel. All rights reserved. * * This program is free software: you can redistribute it and/or modify it under the terms of the Apache License * as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later * version. * * \author Travis Gockel ([email protected]) **/ #include <json-voorhees/object.hpp> #include "detail.hpp" #include <cstring> using namespace jsonv::detail; namespace jsonv { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // object // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define OBJ _data.object->_values object::object() { _data.object = new detail::object_impl; _kind = kind::object; } object::object(const object& source) : value(source) { } object::object(object&& source) : value(std::move(source)) { } object& object::operator =(const object& source) { value::operator=(source); return *this; } object& object::operator =(object&& source) { value::operator=(std::move(source)); return *this; } void object::ensure_object() const { check_type(kind::object, get_kind()); } object::size_type object::size() const { ensure_object(); return OBJ.size(); } object::iterator object::begin() { ensure_object(); return iterator(OBJ.begin()); } object::const_iterator object::begin() const { ensure_object(); return const_iterator(OBJ.begin()); } object::iterator object::end() { ensure_object(); return iterator(OBJ.end()); } object::const_iterator object::end() const { ensure_object(); return const_iterator(OBJ.end()); } value& object::operator[](const string_type& key) { ensure_object(); return OBJ[key]; } const value& object::operator[](const string_type& key) const { ensure_object(); return OBJ[key]; } object::size_type object::count(const key_type& key) const { ensure_object(); return OBJ.count(key); } object::iterator object::find(const string_type& key) { ensure_object(); return iterator(OBJ.find(key)); } object::const_iterator object::find(const string_type& key) const { ensure_object(); return const_iterator(OBJ.find(key)); } void object::insert(const value_type& pair) { OBJ.insert(pair); } object::size_type object::erase(const key_type& key) { ensure_object(); return OBJ.erase(key); } bool object::operator ==(const object& other) const { if (this == &other) return true; if (size() != other.size()) return false; typedef object_impl::map_type::const_iterator const_iterator; const_iterator self_iter = OBJ.begin(); const_iterator other_iter = other.OBJ.begin(); for (const const_iterator self_end = OBJ.end(); self_iter != self_end; ++self_iter, ++other_iter ) { if (self_iter->first != other_iter->first) return false; if (self_iter->second != other_iter->second) return false; } return true; } bool object::operator !=(const object& other) const { return !operator==(other); } static void stream_single(ostream_type& stream, const object_impl::map_type::value_type& pair) { stream_escaped_string(stream, pair.first) << ":" << pair.second; } ostream_type& operator <<(ostream_type& stream, const object& view) { typedef object_impl::map_type::const_iterator const_iterator; const_iterator iter = view.OBJ.begin(); const_iterator end = view.OBJ.end(); stream << "{"; if (iter != end) { stream_single(stream, *iter); ++iter; } for ( ; iter != end; ++iter) { stream << ", "; stream_single(stream, *iter); } stream << "}"; return stream; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // object::basic_iterator<T> // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename T> struct object_iter_converter; template <> struct object_iter_converter<object::value_type> { union impl { char* storage; object_impl::map_type::iterator* iter; }; union const_impl { const char* storage; const object_impl::map_type::iterator* iter; }; }; template <> struct object_iter_converter<const object::value_type> { union impl { char* storage; object_impl::map_type::const_iterator* iter; }; union const_impl { const char* storage; const object_impl::map_type::const_iterator* iter; }; }; #define JSONV_INSTANTIATE_OBJVIEW_BASIC_ITERATOR_FUNC(return_, ...) \ template return_ object::basic_iterator<object::value_type>::__VA_ARGS__; \ template return_ object::basic_iterator<const object::value_type>::__VA_ARGS__; \ template <typename T> object::basic_iterator<T>::basic_iterator() { memset(_storage, 0, sizeof _storage); } JSONV_INSTANTIATE_OBJVIEW_BASIC_ITERATOR_FUNC(, basic_iterator()) // private template <typename T> template <typename U> object::basic_iterator<T>::basic_iterator(const U& source) { static_assert(sizeof(U) == sizeof(_storage), "Input must be the same size of storage"); memcpy(_storage, &source, sizeof _storage); } template <typename T> void object::basic_iterator<T>::increment() { typedef typename object_iter_converter<T>::impl converter_union; converter_union convert; convert.storage = _storage; ++(*convert.iter); } JSONV_INSTANTIATE_OBJVIEW_BASIC_ITERATOR_FUNC(void, increment()) template <typename T> void object::basic_iterator<T>::decrement() { typedef typename object_iter_converter<T>::impl converter_union; converter_union convert; convert.storage = _storage; --(*convert.iter); } JSONV_INSTANTIATE_OBJVIEW_BASIC_ITERATOR_FUNC(void, decrement()) template <typename T> T& object::basic_iterator<T>::current() const { typedef typename object_iter_converter<T>::const_impl converter_union; converter_union convert; convert.storage = _storage; return **convert.iter; } template object::value_type& object::basic_iterator<object::value_type>::current() const; template const object::value_type& object::basic_iterator<const object::value_type>::current() const; template <typename T> bool object::basic_iterator<T>::equals(const char* other_storage) const { typedef typename object_iter_converter<T>::const_impl converter_union; converter_union self_convert; self_convert.storage = _storage; converter_union other_convert; other_convert.storage = other_storage; return *self_convert.iter == *other_convert.iter; } JSONV_INSTANTIATE_OBJVIEW_BASIC_ITERATOR_FUNC(bool, equals(const char*) const) template <typename T> void object::basic_iterator<T>::copy_from(const char* other_storage) { typedef typename object_iter_converter<T>::impl converter_union; typedef typename object_iter_converter<T>::const_impl const_converter_union; converter_union self_convert; self_convert.storage = _storage; const_converter_union other_convert; other_convert.storage = other_storage; *self_convert.iter = *other_convert.iter; } JSONV_INSTANTIATE_OBJVIEW_BASIC_ITERATOR_FUNC(void, copy_from(const char*)) template <typename T> template <typename U> object::basic_iterator<T>::basic_iterator(const basic_iterator<U>& source, typename std::enable_if<std::is_convertible<U*, T*>::value>::type* ) { typedef typename object_iter_converter<T>::impl converter_union; typedef typename object_iter_converter<U>::const_impl const_converter_union; converter_union self_convert; self_convert.storage = _storage; const_converter_union other_convert; other_convert.storage = source._storage; *self_convert.iter = *other_convert.iter; } template object::basic_iterator<const object::value_type> ::basic_iterator<object::value_type>(const basic_iterator<object::value_type>&, void*); object::iterator object::erase(const_iterator position) { ensure_object(); typedef typename object_iter_converter<const object::value_type>::const_impl const_converter_union; const_converter_union pos_convert; pos_convert.storage = position._storage; return iterator(OBJ.erase(*pos_convert.iter)); } object::iterator object::erase(const_iterator first, const_iterator last) { ensure_object(); typedef typename object_iter_converter<const object::value_type>::const_impl const_converter_union; const_converter_union first_convert; first_convert.storage = first._storage; const_converter_union last_convert; last_convert.storage = last._storage; return iterator(OBJ.erase(*first_convert.iter, *last_convert.iter)); } } <|endoftext|>
<commit_before>//============================================================================================================= /** * @file ssvepBCIFlickeringItem.cpp * @author Viktor Klüber <[email protected]>; * Lorenz Esch <[email protected]>; * Christoph Dinh <[email protected]>; * Matti Hamalainen <[email protected]> * @version 1.0 * @date May 2016 * * @section LICENSE * * Copyright (C) 2014, Lorenz Esch, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief Contains the implementation of the ssvepBCIFlickeringItem class. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "ssvepbciflickeringitem.h" //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace ssvepBCIPlugin; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= ssvepBCIFlickeringItem::ssvepBCIFlickeringItem() : m_dPosX(0) , m_dPosY(0) , m_dWidth(0.4) , m_dHeight(0.4) , m_bFlickerState(true) , m_bSignFlag(false) , m_bIter(m_bRenderOrder) { m_bRenderOrder << 0 << 0 << 1 << 1; //default } //************************************************************************************************************* ssvepBCIFlickeringItem::~ssvepBCIFlickeringItem(){ } //************************************************************************************************************* void ssvepBCIFlickeringItem::setPos(double x, double y){ m_dPosX = x; m_dPosY = y; } //************************************************************************************************************* void ssvepBCIFlickeringItem::setDim(double w, double h){ m_dWidth = w; m_dHeight = h; } //************************************************************************************************************* void ssvepBCIFlickeringItem::setRenderOrder(QList<bool> renderOrder, int freqKey){ //clear the old rendering order list m_bRenderOrder.clear(); //setup the iterator and assign it to the new list m_bRenderOrder = renderOrder; m_bIter = m_bRenderOrder; m_iFreqKey = freqKey; } //************************************************************************************************************* void ssvepBCIFlickeringItem::paint(QPaintDevice *paintDevice) { //setting the nex flicker state (moving iterater to front if necessary) if(!m_bIter.hasNext()) m_bIter.toFront(); m_bFlickerState = m_bIter.next(); //painting the itme's shape QPainter p(paintDevice); if(m_bSignFlag){ // // scaling the letter size to the biggest sign "DEL" // float factor =0.2* m_dWidth*paintDevice->width() / p.fontMetrics().width(m_sSign); // if ((factor < 1) || (factor > 1.25)) // { // QFont f = p.font(); // f.setBold(true); // f.setPointSizeF(f.pointSizeF()*factor); // p.setFont(f); // } QFont f = p.font(); f.setBold(true); f.setPointSize(30); p.setFont(f); } QRect rectangle(m_dPosX*paintDevice->width(),m_dPosY*paintDevice->height(),m_dWidth*paintDevice->width(),m_dHeight*paintDevice->height()); if(true){ p.fillRect(rectangle,Qt::white); p.drawText(rectangle, Qt::AlignCenter, m_sSign); } // else // p.fillRect(m_dPosX*paintDevice->width(),m_dPosY*paintDevice->height(),m_dWidth*paintDevice->width(),m_dHeight*paintDevice->height(),Qt::black); } //************************************************************************************************************* int ssvepBCIFlickeringItem::getFreqKey() { return m_iFreqKey; } void ssvepBCIFlickeringItem::addSign(QString sign){ m_bSignFlag = true; m_sSign = sign; } <commit_msg>[SC-115] edit screen-keyboard<commit_after>//============================================================================================================= /** * @file ssvepBCIFlickeringItem.cpp * @author Viktor Klüber <[email protected]>; * Lorenz Esch <[email protected]>; * Christoph Dinh <[email protected]>; * Matti Hamalainen <[email protected]> * @version 1.0 * @date May 2016 * * @section LICENSE * * Copyright (C) 2014, Lorenz Esch, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief Contains the implementation of the ssvepBCIFlickeringItem class. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "ssvepbciflickeringitem.h" //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace ssvepBCIPlugin; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= ssvepBCIFlickeringItem::ssvepBCIFlickeringItem() : m_dPosX(0) , m_dPosY(0) , m_dWidth(0.4) , m_dHeight(0.4) , m_bFlickerState(true) , m_bSignFlag(false) , m_bIter(m_bRenderOrder) { m_bRenderOrder << 0 << 0 << 1 << 1; //default } //************************************************************************************************************* ssvepBCIFlickeringItem::~ssvepBCIFlickeringItem(){ } //************************************************************************************************************* void ssvepBCIFlickeringItem::setPos(double x, double y){ m_dPosX = x; m_dPosY = y; } //************************************************************************************************************* void ssvepBCIFlickeringItem::setDim(double w, double h){ m_dWidth = w; m_dHeight = h; } //************************************************************************************************************* void ssvepBCIFlickeringItem::setRenderOrder(QList<bool> renderOrder, int freqKey){ //clear the old rendering order list m_bRenderOrder.clear(); //setup the iterator and assign it to the new list m_bRenderOrder = renderOrder; m_bIter = m_bRenderOrder; m_iFreqKey = freqKey; } //************************************************************************************************************* void ssvepBCIFlickeringItem::paint(QPaintDevice *paintDevice) { //setting the nex flicker state (moving iterater to front if necessary) if(!m_bIter.hasNext()) m_bIter.toFront(); m_bFlickerState = m_bIter.next(); //painting the itme's shape QPainter p(paintDevice); if(m_bSignFlag){ // // scaling the letter size to the biggest sign "DEL" // float factor =0.2* m_dWidth*paintDevice->width() / p.fontMetrics().width(m_sSign); // if ((factor < 1) || (factor > 1.25)) // { // QFont f = p.font(); // f.setBold(true); // f.setPointSizeF(f.pointSizeF()*factor); // p.setFont(f); // } QFont f = p.font(); f.setBold(true); f.setPointSize(30); p.setFont(f); } QRect rectangle(m_dPosX*paintDevice->width(),m_dPosY*paintDevice->height(),m_dWidth*paintDevice->width(),m_dHeight*paintDevice->height()); if(m_bFlickerState){ p.fillRect(rectangle,Qt::white); p.drawText(rectangle, Qt::AlignCenter, m_sSign); } else p.fillRect(m_dPosX*paintDevice->width(),m_dPosY*paintDevice->height(),m_dWidth*paintDevice->width(),m_dHeight*paintDevice->height(),Qt::black); } //************************************************************************************************************* int ssvepBCIFlickeringItem::getFreqKey() { return m_iFreqKey; } void ssvepBCIFlickeringItem::addSign(QString sign){ m_bSignFlag = true; m_sSign = sign; } <|endoftext|>
<commit_before> #include <Atomic/IO/Log.h> #include <Atomic/Core/CoreEvents.h> #include <Atomic/Graphics/Graphics.h> #include <Atomic/Graphics/Drawable.h> #include <Atomic/Graphics/DebugRenderer.h> #include <Atomic/Atomic3D/Terrain.h> #include <Atomic/Scene/SceneEvents.h> #include <Atomic/Scene/Node.h> #include <Atomic/Scene/Scene.h> #include "SceneEditor3D.h" #include "SceneEditor3DEvents.h" #include "SceneSelection.h" namespace AtomicEditor { SceneSelection::SceneSelection(Context* context, SceneEditor3D *sceneEditor) : Object(context) { sceneEditor3D_ = sceneEditor; scene_ = sceneEditor3D_->GetScene(); SubscribeToEvent(E_POSTRENDERUPDATE, HANDLER(SceneSelection, HandlePostRenderUpdate)); SubscribeToEvent(scene_, E_NODEREMOVED, HANDLER(SceneSelection, HandleNodeRemoved)); } SceneSelection::~SceneSelection() { } Node* SceneSelection::GetSelectedNode(unsigned index) const { if (index > nodes_.Size()) return 0; return nodes_[index]; } bool SceneSelection::Contains(Node* node) { SharedPtr<Node> _node(node); return nodes_.Contains(_node); } void SceneSelection::AddNode(Node* node, bool clear) { if (clear) Clear(); SharedPtr<Node> _node(node); if (!nodes_.Contains(_node)) { nodes_.Push(_node); VariantMap eventData; eventData[SceneNodeSelected::P_SCENE] = scene_; eventData[SceneNodeSelected::P_NODE] = node; eventData[SceneNodeSelected::P_SELECTED] = true; scene_->SendEvent(E_SCENENODESELECTED, eventData); } } void SceneSelection::RemoveNode(Node* node, bool quiet) { SharedPtr<Node> _node(node); if(!nodes_.Contains(_node)) return; nodes_.Remove(_node); if (quiet) return; VariantMap eventData; eventData[SceneNodeSelected::P_SCENE] = scene_; eventData[SceneNodeSelected::P_NODE] = node; eventData[SceneNodeSelected::P_SELECTED] = false; scene_->SendEvent(E_SCENENODESELECTED, eventData); } void SceneSelection::Clear() { Vector<SharedPtr<Node>> nodes = nodes_; for (unsigned i = 0; i < nodes.Size(); i++) { RemoveNode(nodes[i]); } } void SceneSelection::Paste() { if (!clipBoardNodes_.Size()) return; Vector<SharedPtr<Node>> newClipBoardNodes; Node* parent = scene_; if (nodes_.Size() == 1) parent = nodes_[0]; Clear(); VariantMap eventData; eventData[SceneEditAddRemoveNodes::P_END] = false; scene_->SendEvent(E_SCENEEDITADDREMOVENODES, eventData); for (unsigned i = 0; i < clipBoardNodes_.Size(); i++) { // Nodes must have a parent to clone, so first parent Node* clipNode = clipBoardNodes_[i]; Matrix3x4 transform = clipNode->GetWorldTransform(); parent->AddChild(clipNode); clipNode->SetWorldTransform(transform.Translation(), transform.Rotation(), transform.Scale()); // clone newClipBoardNodes.Push(SharedPtr<Node>(clipNode->Clone())); // remove from parent newClipBoardNodes.Back()->Remove(); newClipBoardNodes.Back()->SetWorldTransform(transform.Translation(), transform.Rotation(), transform.Scale()); // generate scene edit event VariantMap nodeAddedEventData; nodeAddedEventData[SceneEditNodeAdded::P_NODE] = clipNode; nodeAddedEventData[SceneEditNodeAdded::P_PARENT] = parent; nodeAddedEventData[SceneEditNodeAdded::P_SCENE] = scene_; scene_->SendEvent(E_SCENEEDITNODEADDED, nodeAddedEventData); } eventData[SceneEditAddRemoveNodes::P_END] = true; scene_->SendEvent(E_SCENEEDITADDREMOVENODES, eventData); for (unsigned i = 0; i < clipBoardNodes_.Size(); i++) { AddNode(clipBoardNodes_[i], false); } clipBoardNodes_ = newClipBoardNodes; } void SceneSelection::Copy() { clipBoardNodes_.Clear(); for (unsigned i = 0; i < nodes_.Size(); i++) { Node* node = nodes_[i]; if (!node->GetParent()) { clipBoardNodes_.Clear(); LOGERROR("SceneSelection::Copy - unable to copy node to clipboard (no parent)"); return; } for (unsigned j = 0; j < nodes_.Size(); j++) { if ( i == j ) continue; PODVector<Node*> children; nodes_[j]->GetChildren(children, true); if (children.Contains(node)) { node = 0; break; } } if (node) { SharedPtr<Node> clipNode(node->Clone()); clipNode->Remove(); clipBoardNodes_.Push(clipNode); } } } void SceneSelection::Delete() { Vector<SharedPtr<Node>> nodes = nodes_; Clear(); VariantMap eventData; eventData[SceneEditAddRemoveNodes::P_END] = false; scene_->SendEvent(E_SCENEEDITADDREMOVENODES, eventData); for (unsigned i = 0; i < nodes.Size(); i++) { // generate scene edit event VariantMap nodeRemovedEventData; nodeRemovedEventData[SceneEditNodeAdded::P_NODE] = nodes[i]; nodeRemovedEventData[SceneEditNodeAdded::P_PARENT] = nodes[i]->GetParent(); nodeRemovedEventData[SceneEditNodeAdded::P_SCENE] = scene_; scene_->SendEvent(E_SCENEEDITNODEREMOVED, nodeRemovedEventData); nodes[i]->Remove(); } eventData[SceneEditAddRemoveNodes::P_END] = true; scene_->SendEvent(E_SCENEEDITADDREMOVENODES, eventData); } void SceneSelection::GetBounds(BoundingBox& bbox) { bbox.Clear(); if (!nodes_.Size()) return; // Get all the drawables, which define the bounding box of the selection PODVector<Drawable*> drawables; for (unsigned i = 0; i < nodes_.Size(); i++) { Node* node = nodes_[i]; node->GetDerivedComponents<Drawable>(drawables, true, false); } if (!drawables.Size()) return; // Calculate the combined bounding box of all drawables for (unsigned i = 0; i < drawables.Size(); i++ ) { Drawable* drawable = drawables[i]; bbox.Merge(drawable->GetWorldBoundingBox()); } } void SceneSelection::DrawNodeDebug(Node* node, DebugRenderer* debug, bool drawNode) { if (drawNode) debug->AddNode(node, 1.0, false); // Exception for the scene to avoid bringing the editor to its knees: drawing either the whole hierarchy or the subsystem- // components can have a large performance hit. Also do not draw terrain child nodes due to their large amount // (TerrainPatch component itself draws nothing as debug geometry) if (node != scene_ && !node->GetComponent<Terrain>()) { const Vector<SharedPtr<Component> >& components = node->GetComponents(); for (unsigned j = 0; j < components.Size(); ++j) components[j]->DrawDebugGeometry(debug, false); // To avoid cluttering the view, do not draw the node axes for child nodes for (unsigned k = 0; k < node->GetNumChildren(); ++k) DrawNodeDebug(node->GetChild(k), debug, false); } } void SceneSelection::HandleNodeRemoved(StringHash eventType, VariantMap& eventData) { Node* node = (Node*) (eventData[NodeRemoved::P_NODE].GetPtr()); RemoveNode(node, true); } void SceneSelection::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData) { if (!nodes_.Size()) return; // Visualize the currently selected nodes DebugRenderer* debugRenderer = sceneEditor3D_->GetSceneView3D()->GetDebugRenderer(); for (unsigned i = 0; i < nodes_.Size(); i++) { DrawNodeDebug(nodes_[i], debugRenderer); } } } <commit_msg>Copy/Paste updates<commit_after> #include <Atomic/IO/Log.h> #include <Atomic/Core/CoreEvents.h> #include <Atomic/Graphics/Graphics.h> #include <Atomic/Graphics/Drawable.h> #include <Atomic/Graphics/DebugRenderer.h> #include <Atomic/Atomic3D/Terrain.h> #include <Atomic/Scene/SceneEvents.h> #include <Atomic/Scene/Node.h> #include <Atomic/Scene/Scene.h> #include "SceneEditor3D.h" #include "SceneEditor3DEvents.h" #include "SceneSelection.h" namespace AtomicEditor { SceneSelection::SceneSelection(Context* context, SceneEditor3D *sceneEditor) : Object(context) { sceneEditor3D_ = sceneEditor; scene_ = sceneEditor3D_->GetScene(); SubscribeToEvent(E_POSTRENDERUPDATE, HANDLER(SceneSelection, HandlePostRenderUpdate)); SubscribeToEvent(scene_, E_NODEREMOVED, HANDLER(SceneSelection, HandleNodeRemoved)); } SceneSelection::~SceneSelection() { } Node* SceneSelection::GetSelectedNode(unsigned index) const { if (index > nodes_.Size()) return 0; return nodes_[index]; } bool SceneSelection::Contains(Node* node) { SharedPtr<Node> _node(node); return nodes_.Contains(_node); } void SceneSelection::AddNode(Node* node, bool clear) { if (clear) Clear(); SharedPtr<Node> _node(node); if (!nodes_.Contains(_node)) { nodes_.Push(_node); VariantMap eventData; eventData[SceneNodeSelected::P_SCENE] = scene_; eventData[SceneNodeSelected::P_NODE] = node; eventData[SceneNodeSelected::P_SELECTED] = true; scene_->SendEvent(E_SCENENODESELECTED, eventData); } } void SceneSelection::RemoveNode(Node* node, bool quiet) { SharedPtr<Node> _node(node); if(!nodes_.Contains(_node)) return; nodes_.Remove(_node); if (quiet) return; VariantMap eventData; eventData[SceneNodeSelected::P_SCENE] = scene_; eventData[SceneNodeSelected::P_NODE] = node; eventData[SceneNodeSelected::P_SELECTED] = false; scene_->SendEvent(E_SCENENODESELECTED, eventData); } void SceneSelection::Clear() { Vector<SharedPtr<Node>> nodes = nodes_; for (unsigned i = 0; i < nodes.Size(); i++) { RemoveNode(nodes[i]); } } void SceneSelection::Paste() { if (!clipBoardNodes_.Size()) return; Vector<SharedPtr<Node>> newClipBoardNodes; Node* parent = scene_; if (nodes_.Size() >= 1) parent = nodes_[0]->GetParent(); if (!parent) parent = scene_; Clear(); VariantMap eventData; eventData[SceneEditAddRemoveNodes::P_END] = false; scene_->SendEvent(E_SCENEEDITADDREMOVENODES, eventData); for (unsigned i = 0; i < clipBoardNodes_.Size(); i++) { // Nodes must have a parent to clone, so first parent Node* clipNode = clipBoardNodes_[i]; Matrix3x4 transform = clipNode->GetWorldTransform(); clipNode->SetWorldTransform(transform.Translation(), transform.Rotation(), transform.Scale()); parent->AddChild(clipNode); // clone newClipBoardNodes.Push(SharedPtr<Node>(clipNode->Clone())); // remove from parent newClipBoardNodes.Back()->Remove(); newClipBoardNodes.Back()->SetWorldTransform(transform.Translation(), transform.Rotation(), transform.Scale()); // generate scene edit event VariantMap nodeAddedEventData; nodeAddedEventData[SceneEditNodeAdded::P_NODE] = clipNode; nodeAddedEventData[SceneEditNodeAdded::P_PARENT] = parent; nodeAddedEventData[SceneEditNodeAdded::P_SCENE] = scene_; scene_->SendEvent(E_SCENEEDITNODEADDED, nodeAddedEventData); } eventData[SceneEditAddRemoveNodes::P_END] = true; scene_->SendEvent(E_SCENEEDITADDREMOVENODES, eventData); for (unsigned i = 0; i < clipBoardNodes_.Size(); i++) { AddNode(clipBoardNodes_[i], false); } clipBoardNodes_ = newClipBoardNodes; } void SceneSelection::Copy() { clipBoardNodes_.Clear(); for (unsigned i = 0; i < nodes_.Size(); i++) { Node* node = nodes_[i]; if (!node->GetParent()) { clipBoardNodes_.Clear(); LOGERROR("SceneSelection::Copy - unable to copy node to clipboard (no parent)"); return; } for (unsigned j = 0; j < nodes_.Size(); j++) { if ( i == j ) continue; PODVector<Node*> children; nodes_[j]->GetChildren(children, true); if (children.Contains(node)) { node = 0; break; } } if (node) { SharedPtr<Node> clipNode(node->Clone()); clipNode->Remove(); clipBoardNodes_.Push(clipNode); } } } void SceneSelection::Delete() { Vector<SharedPtr<Node>> nodes = nodes_; Clear(); VariantMap eventData; eventData[SceneEditAddRemoveNodes::P_END] = false; scene_->SendEvent(E_SCENEEDITADDREMOVENODES, eventData); for (unsigned i = 0; i < nodes.Size(); i++) { // generate scene edit event VariantMap nodeRemovedEventData; nodeRemovedEventData[SceneEditNodeAdded::P_NODE] = nodes[i]; nodeRemovedEventData[SceneEditNodeAdded::P_PARENT] = nodes[i]->GetParent(); nodeRemovedEventData[SceneEditNodeAdded::P_SCENE] = scene_; scene_->SendEvent(E_SCENEEDITNODEREMOVED, nodeRemovedEventData); nodes[i]->Remove(); } eventData[SceneEditAddRemoveNodes::P_END] = true; scene_->SendEvent(E_SCENEEDITADDREMOVENODES, eventData); } void SceneSelection::GetBounds(BoundingBox& bbox) { bbox.Clear(); if (!nodes_.Size()) return; // Get all the drawables, which define the bounding box of the selection PODVector<Drawable*> drawables; for (unsigned i = 0; i < nodes_.Size(); i++) { Node* node = nodes_[i]; node->GetDerivedComponents<Drawable>(drawables, true, false); } if (!drawables.Size()) return; // Calculate the combined bounding box of all drawables for (unsigned i = 0; i < drawables.Size(); i++ ) { Drawable* drawable = drawables[i]; bbox.Merge(drawable->GetWorldBoundingBox()); } } void SceneSelection::DrawNodeDebug(Node* node, DebugRenderer* debug, bool drawNode) { if (drawNode) debug->AddNode(node, 1.0, false); // Exception for the scene to avoid bringing the editor to its knees: drawing either the whole hierarchy or the subsystem- // components can have a large performance hit. Also do not draw terrain child nodes due to their large amount // (TerrainPatch component itself draws nothing as debug geometry) if (node != scene_ && !node->GetComponent<Terrain>()) { const Vector<SharedPtr<Component> >& components = node->GetComponents(); for (unsigned j = 0; j < components.Size(); ++j) components[j]->DrawDebugGeometry(debug, false); // To avoid cluttering the view, do not draw the node axes for child nodes for (unsigned k = 0; k < node->GetNumChildren(); ++k) DrawNodeDebug(node->GetChild(k), debug, false); } } void SceneSelection::HandleNodeRemoved(StringHash eventType, VariantMap& eventData) { Node* node = (Node*) (eventData[NodeRemoved::P_NODE].GetPtr()); RemoveNode(node, true); } void SceneSelection::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData) { if (!nodes_.Size()) return; // Visualize the currently selected nodes DebugRenderer* debugRenderer = sceneEditor3D_->GetSceneView3D()->GetDebugRenderer(); for (unsigned i = 0; i < nodes_.Size(); i++) { DrawNodeDebug(nodes_[i], debugRenderer); } } } <|endoftext|>
<commit_before>#ifndef Ancona_Engine_Core_Systems_Collision_CollisionSystem_H_ #define Ancona_Engine_Core_Systems_Collision_CollisionSystem_H_ #include <vector> #include <functional> #include <Ancona/Engine/EntityFramework/UnorderedSystem.hpp> #include <Ancona/Engine/Core/Systems/Physics/BasePhysicsSystem.hpp> #include <Ancona/Util/Data.hpp> #include "CollisionComponent.hpp" namespace ild { /** * @brief Function signature used by the collision system. */ typedef std::function<void(const Entity&,const Entity&)> CollisionCallback; /** * @brief System used to provide collision interactions and callbacks for entities. * @author Jeff Swenson */ class CollisionSystem : public UnorderedSystem<CollisionComponent> { public: /** * @brief Construct a collision system and register it with the manager. * * @param name The systems name used for loading. * @param manager Manager that the system belongs to. * @param positions System that defines the position of an entity. */ CollisionSystem(const std::string & name, SystemManager & manager, BasePhysicsSystem & positions); /** * @brief Update the position for all components based off of their velocity * * @param delta Number of ms since last update */ void Update(float delta); /** * @brief Create and attach a collision component for the entity. * * @param entity Entity that the component is attached to. * @param dim Dimension for the entity to be used for collision. * @param type The collision type of the entity. * @param bodyType The body type of the entity. Determines how collision fixing * is handled for it. Defaults to BodyType::None. * * @return A pointer to the component. */ CollisionComponent * CreateComponent(const Entity & entity, const sf::Vector3f & dim, CollisionType type, BodyTypeEnum bodyType = BodyType::None); /** * @brief Create a Type that can be assigned to a component. * * @param key describing the collision type. * * @return A unique Collision Type. */ CollisionType CreateType(const std::string & key); /** * @brief Get the collision type associated with the key. */ CollisionType GetType(const std::string & key); /** * @brief Define the handler that will be used for the collisions between the two types. * * @param typeA One type involved in the collision. * @param typeB The second type involved in the collision. * @param callback The callback will be called as callback(entityA, entityB) where * entityA is an entity of the first type and entityB is an entity of second type. */ void DefineCollisionCallback(CollisionType typeA, CollisionType typeB, CollisionCallback callback); /** * @brief Determine if the collision type has already been created. * * @param key Key that was used to create the collision type. * * @return True if the collision type is defined. False otherwise. */ bool IsCollisionTypeDefined(std::string const &key); /* Getters and Setters */ BasePhysicsSystem & GetPhysics() { return _positions; } void SetMaxSlope(float value) { _maxSlope = value; } private: int _nextType; Table<CollisionCallback> _callbackTable; BasePhysicsSystem & _positions; std::unordered_map<std::string,CollisionType> _collisionTypes; Point _leftGravityBound; Point _rightGravityBound; float _maxSlope = 45; bool UniqueCollision(const Entity & entityA, const Entity & entityB); void HandleCollision( EntityComponentPair &pairA, EntityComponentPair &pairB, const Point &fixNormal, float fixMagnitude); bool EntitiesOverlapping(float fixMagnitude); void UpdateGravityBounds(); void FixCollision(CollisionComponent * a, CollisionComponent * b, const Point & fixNormal, float fixMagnitude); bool IsOnGround(const Point & groundNormal); void PushApart(CollisionComponent * a, CollisionComponent * b, const Point & correctFix); void PushFirstOutOfSecond(CollisionComponent * a, CollisionComponent * b, const Point & correctFix); }; } #endif <commit_msg>CollisionSystem.hpp header order fixed<commit_after>#ifndef Ancona_Engine_Core_Systems_Collision_CollisionSystem_H_ #define Ancona_Engine_Core_Systems_Collision_CollisionSystem_H_ #include <functional> #include <vector> #include <Ancona/Engine/Core/Systems/Physics/BasePhysicsSystem.hpp> #include <Ancona/Engine/EntityFramework/UnorderedSystem.hpp> #include <Ancona/Util/Data.hpp> #include "CollisionComponent.hpp" namespace ild { /** * @brief Function signature used by the collision system. */ typedef std::function<void(const Entity&,const Entity&)> CollisionCallback; /** * @brief System used to provide collision interactions and callbacks for entities. * @author Jeff Swenson */ class CollisionSystem : public UnorderedSystem<CollisionComponent> { public: /** * @brief Construct a collision system and register it with the manager. * * @param name The systems name used for loading. * @param manager Manager that the system belongs to. * @param positions System that defines the position of an entity. */ CollisionSystem(const std::string & name, SystemManager & manager, BasePhysicsSystem & positions); /** * @brief Update the position for all components based off of their velocity * * @param delta Number of ms since last update */ void Update(float delta); /** * @brief Create and attach a collision component for the entity. * * @param entity Entity that the component is attached to. * @param dim Dimension for the entity to be used for collision. * @param type The collision type of the entity. * @param bodyType The body type of the entity. Determines how collision fixing * is handled for it. Defaults to BodyType::None. * * @return A pointer to the component. */ CollisionComponent * CreateComponent(const Entity & entity, const sf::Vector3f & dim, CollisionType type, BodyTypeEnum bodyType = BodyType::None); /** * @brief Create a Type that can be assigned to a component. * * @param key describing the collision type. * * @return A unique Collision Type. */ CollisionType CreateType(const std::string & key); /** * @brief Get the collision type associated with the key. */ CollisionType GetType(const std::string & key); /** * @brief Define the handler that will be used for the collisions between the two types. * * @param typeA One type involved in the collision. * @param typeB The second type involved in the collision. * @param callback The callback will be called as callback(entityA, entityB) where * entityA is an entity of the first type and entityB is an entity of second type. */ void DefineCollisionCallback(CollisionType typeA, CollisionType typeB, CollisionCallback callback); /** * @brief Determine if the collision type has already been created. * * @param key Key that was used to create the collision type. * * @return True if the collision type is defined. False otherwise. */ bool IsCollisionTypeDefined(std::string const &key); /* Getters and Setters */ BasePhysicsSystem & GetPhysics() { return _positions; } void SetMaxSlope(float value) { _maxSlope = value; } private: int _nextType; Table<CollisionCallback> _callbackTable; BasePhysicsSystem & _positions; std::unordered_map<std::string,CollisionType> _collisionTypes; Point _leftGravityBound; Point _rightGravityBound; float _maxSlope = 45; bool UniqueCollision(const Entity & entityA, const Entity & entityB); void HandleCollision( EntityComponentPair &pairA, EntityComponentPair &pairB, const Point &fixNormal, float fixMagnitude); bool EntitiesOverlapping(float fixMagnitude); void UpdateGravityBounds(); void FixCollision(CollisionComponent * a, CollisionComponent * b, const Point & fixNormal, float fixMagnitude); bool IsOnGround(const Point & groundNormal); void PushApart(CollisionComponent * a, CollisionComponent * b, const Point & correctFix); void PushFirstOutOfSecond(CollisionComponent * a, CollisionComponent * b, const Point & correctFix); }; } #endif <|endoftext|>
<commit_before>/* Persons Model Copyright (C) 2012 Aleix Pol Gonzalez <[email protected]> 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 */ #include "duplicatesfinder.h" #include "persons-model.h" #include <QDebug> DuplicatesFinder::DuplicatesFinder(PersonsModel* model, QObject* parent) : KJob(parent) , m_model(model) { m_compareRoles << PersonsModel::NameRole << PersonsModel::EmailRole << PersonsModel::NickRole << PersonsModel::PhoneRole << PersonsModel::IMRole; } void DuplicatesFinder::start() { QMetaObject::invokeMethod(this, "doSearch", Qt::QueuedConnection); } //TODO: start providing partial results so that we can start processing matches while it's not done void DuplicatesFinder::doSearch() { //NOTE: This can probably optimized. I'm just trying to get the semantics right at the moment //maybe using nepomuk for the matching would help? QVector< QVariantList > collectedValues; m_matches.clear(); int count = m_model->rowCount(); for(int i=0; i<count; i++) { QModelIndex idx = m_model->index(i, 0); //we gather the values QVariantList values; for(int role=0; role<m_compareRoles.size(); role++) { values += idx.data(m_compareRoles[role]); } Q_ASSERT(values.size()==m_compareRoles.size()); //we check if it matches int j=0; foreach(const QVariantList& valueToCompare, collectedValues) { QList< int > matchedRoles = matchAt(values, valueToCompare); if(!matchedRoles.isEmpty()) m_matches.append(Match(matchedRoles, i, j)); j++; } //we add our data for comparing later collectedValues.append(values); } emitResult(); } QList<int> DuplicatesFinder::matchAt(const QVariantList& value, const QVariantList& toCompare) const { QList<int> ret; Q_ASSERT(value.size()==toCompare.size()); for(int i=0; i<toCompare.size(); i++) { if(!value[i].isNull() && value[i]==toCompare[i]) ret += m_compareRoles[i]; } return ret; } QList< Match > DuplicatesFinder::results() const { return m_matches; } <commit_msg>Improve duplicates lookup<commit_after>/* Persons Model Copyright (C) 2012 Aleix Pol Gonzalez <[email protected]> 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 */ #include "duplicatesfinder.h" #include "persons-model.h" #include <QDebug> DuplicatesFinder::DuplicatesFinder(PersonsModel* model, QObject* parent) : KJob(parent) , m_model(model) { m_compareRoles << PersonsModel::NameRole << PersonsModel::EmailRole << PersonsModel::NickRole << PersonsModel::PhoneRole << PersonsModel::IMRole; } void DuplicatesFinder::start() { QMetaObject::invokeMethod(this, "doSearch", Qt::QueuedConnection); } //TODO: start providing partial results so that we can start processing matches while it's not done void DuplicatesFinder::doSearch() { //NOTE: This can probably optimized. I'm just trying to get the semantics right at the moment //maybe using nepomuk for the matching would help? QVector< QVariantList > collectedValues; m_matches.clear(); int count = m_model->rowCount(); for(int i=0; i<count; i++) { QModelIndex idx = m_model->index(i, 0); //we gather the values QVariantList values; for(int role=0; role<m_compareRoles.size(); role++) { values += idx.data(m_compareRoles[role]); } Q_ASSERT(values.size()==m_compareRoles.size()); //we check if it matches int j=0; foreach(const QVariantList& valueToCompare, collectedValues) { QList< int > matchedRoles = matchAt(values, valueToCompare); if(!matchedRoles.isEmpty()) m_matches.append(Match(matchedRoles, i, j)); j++; } //we add our data for comparing later collectedValues.append(values); } emitResult(); } QList<int> DuplicatesFinder::matchAt(const QVariantList& value, const QVariantList& toCompare) const { QList<int> ret; Q_ASSERT(value.size()==toCompare.size()); for(int i=0; i<toCompare.size(); i++) { const QVariant& v = value[i]; if(!v.isNull() && v==toCompare[i] && (v.type()!=QVariant::List || !v.toList().isEmpty())) { ret += m_compareRoles[i]; } } return ret; } QList< Match > DuplicatesFinder::results() const { return m_matches; } <|endoftext|>
<commit_before>#include "ros/ros.h" #include "EventTriggerUtility.h" #include "elderly_care_simulation/EventTrigger.h" #include <queue> #include <unistd.h> // sleep #include "Scheduler.h" using namespace elderly_care_simulation; Scheduler scheduler; Scheduler::Scheduler(){ concurrentWeight = 0; allowNewEvents = true; stopRosInfoSpam = false; randomEventLimit[EVENT_TRIGGER_EVENT_TYPE_MORAL_SUPPORT] = false; randomEventLimit[EVENT_TRIGGER_EVENT_TYPE_ILL] = false; randomEventLimit[EVENT_TRIGGER_EVENT_TYPE_VERY_ILL] = false; } Scheduler::~Scheduler() {} /** * Creates a Request EventTrigger message for requesting robot tasks. * @param eventType the event type for the message */ EventTrigger Scheduler::createEventRequestMsg(int eventType, int priority){ EventTrigger msg; msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST; msg.event_type = eventType; msg.event_priority = priority; msg.event_weight = getEventWeight(eventType); msg.result = EVENT_TRIGGER_RESULT_UNDEFINED; return msg; } /** * Clears the eventQueue. */ void Scheduler::clearEventQueue() { eventQueue = std::priority_queue<EventNode >(); } /** * Reset all random event occurrence back to false. */ void Scheduler::resetRandomEventOccurrence() { for(std::map<int, bool >::iterator iter = randomEventLimit.begin(); iter != randomEventLimit.end(); ++iter) { randomEventLimit[iter->first] = false; } } void Scheduler::resetConcurrentWeight() { concurrentWeight = 0; } /** * Returns the current concurrent weight count */ int Scheduler::getConcurrentWeight() const { return concurrentWeight; } /** * Returns the current event queue size */ int Scheduler::getEventQueueSize() const { return eventQueue.size(); } /** * Callback function to deal with external events */ void Scheduler::externalEventReceivedCallback(EventTrigger msg) { // Only allows random events to be added to event queue in the allowed // timeframe (between WAKE and SLEEP) if(!allowNewEvents) { ROS_INFO("Scheduler: Additional events are not allowed at this time."); return; } // If the incoming event is a random event if(randomEventLimit.count(msg.event_type) != 0) { // If it havent occured before, change the flag and continue if(randomEventLimit[msg.event_type] == false) { randomEventLimit[msg.event_type] = true; // If event occured before, then block it } else { ROS_INFO("Scheduler: [%s] cannot occur more than once per day.", eventTypeToString(msg.event_type)); return; } } ROS_INFO("Scheduler: Enqueuing event: [%s] with priority [%s]", eventTypeToString(msg.event_type), priorityToString(msg.event_priority)); eventQueue.push(EventNode(msg)); } /** * Callback function to deal with events replied from service provider robots */ void Scheduler::eventTriggerCallback(EventTrigger msg) { if (msg.msg_type == EVENT_TRIGGER_MSG_TYPE_RESPONSE) { if(msg.result == EVENT_TRIGGER_RESULT_SUCCESS){ if (msg.event_type == EVENT_TRIGGER_EVENT_TYPE_COOK) { ROS_INFO("Scheduler: [%s] done.", eventTypeToString(msg.event_type)); EventTrigger eatMsg; eatMsg = createEventRequestMsg(EVENT_TRIGGER_EVENT_TYPE_EAT, EVENT_TRIGGER_PRIORITY_HIGH); ROS_INFO("Scheduler: Enqueuing event: [%s] with priority [%s]", eventTypeToString(eatMsg.event_type), priorityToString(eatMsg.event_priority)); eventQueue.push(EventNode(eatMsg)); }else{ // ILL has a weight of 0, but still blocks all other events (taking up 2 slots) // Therefore need to -2 to concurrent weight to free the slot. if (msg.event_type == EVENT_TRIGGER_EVENT_TYPE_ILL || msg.event_type == EVENT_TRIGGER_EVENT_TYPE_VERY_ILL) { concurrentWeight -= 2; }else { concurrentWeight -= msg.event_weight; } ROS_INFO("Scheduler: [%s] done.", eventTypeToString(msg.event_type)); } } } } /** * Populates daily scheduled tasks into the event queue. * * Daily Schedule will be queued in the following sequence: * NOTE: The timestamp is just for referencing purpose. * * 07:00 WAKE * 07:00 COOK ---> EAT * 07:00 MEDICATION * 08:00 EXERCISE * 09:00 SHOWER * 10:00 ENTERTAINMENT * * 12:00 COOK ---> EAT * 12:00 MEDICATION * 13:00 CONVERSATION * 14:00 FRIEND & RELATIVE * 16:00 ENTERTAINMENT * * 18:00 COOK ---> EAT * 18:00 MEDICATION * 19:00 COMPANIONSHIP * 20:00 SLEEP * * PAUSE FOR 20 SEC * CLEAR LIST & REPOPULATE DAILY TASKS * */ void Scheduler::populateDailyTasks() { int eventSequence[][2] = { // ====================================== // = COMMENTED OUT STUFF = // ====================================== // // Morning // { EVENT_TRIGGER_EVENT_TYPE_WAKE, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_COOK, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_MOVE_TO_KITCHEN, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_MEDICATION, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_EXERCISE, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_SHOWER, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_MOVE_TO_BEDROOM, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_COOK, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_ENTERTAINMENT, EVENT_TRIGGER_PRIORITY_LOW }, // // Noon // { EVENT_TRIGGER_EVENT_TYPE_MEDICATION, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_CONVERSATION, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_MOVE_TO_HALLWAY, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_RELATIVE, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_FRIEND, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_COOK, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_ENTERTAINMENT, EVENT_TRIGGER_PRIORITY_LOW }, // // Evening // { EVENT_TRIGGER_EVENT_TYPE_MEDICATION, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_MOVE_TO_BEDROOM, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_COMPANIONSHIP, EVENT_TRIGGER_PRIORITY_LOW } // { EVENT_TRIGGER_EVENT_TYPE_SLEEP, EVENT_TRIGGER_PRIORITY_VERY_LOW } }; for(unsigned int i = 0; i < sizeof(eventSequence)/sizeof(*eventSequence); i++) { eventQueue.push(EventNode(createEventRequestMsg(eventSequence[i][0], eventSequence[i][1]))); } } /** * Dequeues an event and publishes to the event_trigger topic. * Allows concurrent events to be triggered up to the limit * set in MAX_CONCURRENT_WEIGHT * * COOK event is not affected as it acts independently of the * Resident. */ void Scheduler::dequeueEvent() { if (eventQueue.size() < 1) { return; } EventTrigger msg; msg = eventQueue.top().getEventTriggerMessage(); // Publish event if enough concurrent weight available if (concurrentWeight + msg.event_weight <= MAX_CONCURRENT_WEIGHT) { ROS_INFO("Scheduler: Publishing event: [%s]", eventTypeToString(msg.event_type)); stopRosInfoSpam = false; switch(msg.event_type) { case EVENT_TRIGGER_EVENT_TYPE_SLEEP: allowNewEvents = true; concurrentWeight += msg.event_weight; eventTriggerPub.publish(msg); eventQueue.pop(); break; case EVENT_TRIGGER_EVENT_TYPE_ILL: allowNewEvents = false; // ILL has a weight of 0, but still blocks all other events concurrentWeight += 2; eventTriggerPub.publish(msg); eventQueue.pop(); eventQueue.push(EventNode(createEventRequestMsg(EVENT_TRIGGER_EVENT_TYPE_SLEEP, EVENT_TRIGGER_PRIORITY_VERY_HIGH))); eventQueue.push(EventNode(createEventRequestMsg(EVENT_TRIGGER_EVENT_TYPE_WAKE, EVENT_TRIGGER_PRIORITY_VERY_HIGH))); break; case EVENT_TRIGGER_EVENT_TYPE_VERY_ILL: allowNewEvents = false; // VERY_ILL has a weight of 0, but still blocks all other events concurrentWeight += 2; eventTriggerPub.publish(msg); eventQueue.pop(); clearEventQueue(); // Enqueue a SLEEP event with max priority so when resident comes back from // hospital it goes to sleep right away. // Since the queue is now empty after the SLEEP event, a new batch of daily // schedules will be repopulated automatically (in the main method). eventQueue.push(EventNode(createEventRequestMsg(EVENT_TRIGGER_EVENT_TYPE_SLEEP, EVENT_TRIGGER_PRIORITY_VERY_HIGH))); break; default: if(msg.event_type == EVENT_TRIGGER_EVENT_TYPE_WAKE) { allowNewEvents = true; } eventTriggerPub.publish(msg); concurrentWeight += msg.event_weight; eventQueue.pop(); break; } } else { if(!stopRosInfoSpam){ ROS_INFO("Scheduler: Pending event: [%s]", eventTypeToString(msg.event_type)); stopRosInfoSpam = true; } } } void callEventTriggerCallback(EventTrigger msg) { scheduler.eventTriggerCallback(msg); } void callExternalEventReceivedCallback(EventTrigger msg) { scheduler.externalEventReceivedCallback(msg); } /** * Main */ int main(int argc, char **argv) { //You must call ros::init() first of all. ros::init() function needs to see argc and argv. The third argument is the name of the node ros::init(argc, argv, "Scheduler"); //NodeHandle is the main access point to communicate with ros. ros::NodeHandle nodeHandle; scheduler = Scheduler(); // advertise to event_trigger topic scheduler.eventTriggerPub = nodeHandle.advertise<EventTrigger>("event_trigger",1000, true); // subscribe to event_trigger topic scheduler.eventTriggerSub = nodeHandle.subscribe<EventTrigger>("event_trigger",1000, callEventTriggerCallback); scheduler.externalEventSub = nodeHandle.subscribe<EventTrigger>("external_event",1000, callExternalEventReceivedCallback); ros::Rate loop_rate(10); // populate queue with day's events scheduler.populateDailyTasks(); //a count of howmany messages we have sent int count = 0; sleep(5); while (ros::ok()) { if(scheduler.getEventQueueSize() == 0 && scheduler.getConcurrentWeight() <= 0) { ROS_INFO("Day Ends...."); sleep(10); scheduler.clearEventQueue(); scheduler.resetConcurrentWeight(); scheduler.resetRandomEventOccurrence(); scheduler.populateDailyTasks(); ROS_INFO("Day Starts...."); }else { scheduler.dequeueEvent(); } ros::spinOnce(); loop_rate.sleep(); ++count; } return 0; } <commit_msg>Resident now moves to hallway instead of kitchen when it wakes up.<commit_after>#include "ros/ros.h" #include "EventTriggerUtility.h" #include "elderly_care_simulation/EventTrigger.h" #include <queue> #include <unistd.h> // sleep #include "Scheduler.h" using namespace elderly_care_simulation; Scheduler scheduler; Scheduler::Scheduler(){ concurrentWeight = 0; allowNewEvents = true; stopRosInfoSpam = false; randomEventLimit[EVENT_TRIGGER_EVENT_TYPE_MORAL_SUPPORT] = false; randomEventLimit[EVENT_TRIGGER_EVENT_TYPE_ILL] = false; randomEventLimit[EVENT_TRIGGER_EVENT_TYPE_VERY_ILL] = false; } Scheduler::~Scheduler() {} /** * Creates a Request EventTrigger message for requesting robot tasks. * @param eventType the event type for the message */ EventTrigger Scheduler::createEventRequestMsg(int eventType, int priority){ EventTrigger msg; msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST; msg.event_type = eventType; msg.event_priority = priority; msg.event_weight = getEventWeight(eventType); msg.result = EVENT_TRIGGER_RESULT_UNDEFINED; return msg; } /** * Clears the eventQueue. */ void Scheduler::clearEventQueue() { eventQueue = std::priority_queue<EventNode >(); } /** * Reset all random event occurrence back to false. */ void Scheduler::resetRandomEventOccurrence() { for(std::map<int, bool >::iterator iter = randomEventLimit.begin(); iter != randomEventLimit.end(); ++iter) { randomEventLimit[iter->first] = false; } } void Scheduler::resetConcurrentWeight() { concurrentWeight = 0; } /** * Returns the current concurrent weight count */ int Scheduler::getConcurrentWeight() const { return concurrentWeight; } /** * Returns the current event queue size */ int Scheduler::getEventQueueSize() const { return eventQueue.size(); } /** * Callback function to deal with external events */ void Scheduler::externalEventReceivedCallback(EventTrigger msg) { // Only allows random events to be added to event queue in the allowed // timeframe (between WAKE and SLEEP) if(!allowNewEvents) { ROS_INFO("Scheduler: Additional events are not allowed at this time."); return; } // If the incoming event is a random event if(randomEventLimit.count(msg.event_type) != 0) { // If it havent occured before, change the flag and continue if(randomEventLimit[msg.event_type] == false) { randomEventLimit[msg.event_type] = true; // If event occured before, then block it } else { ROS_INFO("Scheduler: [%s] cannot occur more than once per day.", eventTypeToString(msg.event_type)); return; } } ROS_INFO("Scheduler: Enqueuing event: [%s] with priority [%s]", eventTypeToString(msg.event_type), priorityToString(msg.event_priority)); eventQueue.push(EventNode(msg)); } /** * Callback function to deal with events replied from service provider robots */ void Scheduler::eventTriggerCallback(EventTrigger msg) { if (msg.msg_type == EVENT_TRIGGER_MSG_TYPE_RESPONSE) { if(msg.result == EVENT_TRIGGER_RESULT_SUCCESS){ if (msg.event_type == EVENT_TRIGGER_EVENT_TYPE_COOK) { ROS_INFO("Scheduler: [%s] done.", eventTypeToString(msg.event_type)); EventTrigger eatMsg; eatMsg = createEventRequestMsg(EVENT_TRIGGER_EVENT_TYPE_EAT, EVENT_TRIGGER_PRIORITY_HIGH); ROS_INFO("Scheduler: Enqueuing event: [%s] with priority [%s]", eventTypeToString(eatMsg.event_type), priorityToString(eatMsg.event_priority)); eventQueue.push(EventNode(eatMsg)); }else{ // ILL has a weight of 0, but still blocks all other events (taking up 2 slots) // Therefore need to -2 to concurrent weight to free the slot. if (msg.event_type == EVENT_TRIGGER_EVENT_TYPE_ILL || msg.event_type == EVENT_TRIGGER_EVENT_TYPE_VERY_ILL) { concurrentWeight -= 2; }else { concurrentWeight -= msg.event_weight; } ROS_INFO("Scheduler: [%s] done.", eventTypeToString(msg.event_type)); } } } } /** * Populates daily scheduled tasks into the event queue. * * Daily Schedule will be queued in the following sequence: * NOTE: The timestamp is just for referencing purpose. * * 07:00 WAKE * 07:00 COOK ---> EAT * 07:00 MEDICATION * 08:00 EXERCISE * 09:00 SHOWER * 10:00 ENTERTAINMENT * * 12:00 COOK ---> EAT * 12:00 MEDICATION * 13:00 CONVERSATION * 14:00 FRIEND & RELATIVE * 16:00 ENTERTAINMENT * * 18:00 COOK ---> EAT * 18:00 MEDICATION * 19:00 COMPANIONSHIP * 20:00 SLEEP * * PAUSE FOR 20 SEC * CLEAR LIST & REPOPULATE DAILY TASKS * */ void Scheduler::populateDailyTasks() { int eventSequence[][2] = { // ====================================== // = COMMENTED OUT STUFF = // ====================================== // // Morning // { EVENT_TRIGGER_EVENT_TYPE_WAKE, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_COOK, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_MOVE_TO_HALLWAY, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_MEDICATION, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_EXERCISE, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_SHOWER, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_MOVE_TO_BEDROOM, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_COOK, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_ENTERTAINMENT, EVENT_TRIGGER_PRIORITY_LOW }, // // Noon // { EVENT_TRIGGER_EVENT_TYPE_MEDICATION, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_CONVERSATION, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_MOVE_TO_HALLWAY, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_RELATIVE, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_FRIEND, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_COOK, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_ENTERTAINMENT, EVENT_TRIGGER_PRIORITY_LOW }, // // Evening // { EVENT_TRIGGER_EVENT_TYPE_MEDICATION, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_MOVE_TO_BEDROOM, EVENT_TRIGGER_PRIORITY_LOW }, // { EVENT_TRIGGER_EVENT_TYPE_COMPANIONSHIP, EVENT_TRIGGER_PRIORITY_LOW } // { EVENT_TRIGGER_EVENT_TYPE_SLEEP, EVENT_TRIGGER_PRIORITY_VERY_LOW } }; for(unsigned int i = 0; i < sizeof(eventSequence)/sizeof(*eventSequence); i++) { eventQueue.push(EventNode(createEventRequestMsg(eventSequence[i][0], eventSequence[i][1]))); } } /** * Dequeues an event and publishes to the event_trigger topic. * Allows concurrent events to be triggered up to the limit * set in MAX_CONCURRENT_WEIGHT * * COOK event is not affected as it acts independently of the * Resident. */ void Scheduler::dequeueEvent() { if (eventQueue.size() < 1) { return; } EventTrigger msg; msg = eventQueue.top().getEventTriggerMessage(); // Publish event if enough concurrent weight available if (concurrentWeight + msg.event_weight <= MAX_CONCURRENT_WEIGHT) { ROS_INFO("Scheduler: Publishing event: [%s]", eventTypeToString(msg.event_type)); stopRosInfoSpam = false; switch(msg.event_type) { case EVENT_TRIGGER_EVENT_TYPE_SLEEP: allowNewEvents = true; concurrentWeight += msg.event_weight; eventTriggerPub.publish(msg); eventQueue.pop(); break; case EVENT_TRIGGER_EVENT_TYPE_ILL: allowNewEvents = false; // ILL has a weight of 0, but still blocks all other events concurrentWeight += 2; eventTriggerPub.publish(msg); eventQueue.pop(); eventQueue.push(EventNode(createEventRequestMsg(EVENT_TRIGGER_EVENT_TYPE_SLEEP, EVENT_TRIGGER_PRIORITY_VERY_HIGH))); eventQueue.push(EventNode(createEventRequestMsg(EVENT_TRIGGER_EVENT_TYPE_WAKE, EVENT_TRIGGER_PRIORITY_VERY_HIGH))); break; case EVENT_TRIGGER_EVENT_TYPE_VERY_ILL: allowNewEvents = false; // VERY_ILL has a weight of 0, but still blocks all other events concurrentWeight += 2; eventTriggerPub.publish(msg); eventQueue.pop(); clearEventQueue(); // Enqueue a SLEEP event with max priority so when resident comes back from // hospital it goes to sleep right away. // Since the queue is now empty after the SLEEP event, a new batch of daily // schedules will be repopulated automatically (in the main method). eventQueue.push(EventNode(createEventRequestMsg(EVENT_TRIGGER_EVENT_TYPE_SLEEP, EVENT_TRIGGER_PRIORITY_VERY_HIGH))); break; default: if(msg.event_type == EVENT_TRIGGER_EVENT_TYPE_WAKE) { allowNewEvents = true; } eventTriggerPub.publish(msg); concurrentWeight += msg.event_weight; eventQueue.pop(); break; } } else { if(!stopRosInfoSpam){ ROS_INFO("Scheduler: Pending event: [%s]", eventTypeToString(msg.event_type)); stopRosInfoSpam = true; } } } void callEventTriggerCallback(EventTrigger msg) { scheduler.eventTriggerCallback(msg); } void callExternalEventReceivedCallback(EventTrigger msg) { scheduler.externalEventReceivedCallback(msg); } /** * Main */ int main(int argc, char **argv) { //You must call ros::init() first of all. ros::init() function needs to see argc and argv. The third argument is the name of the node ros::init(argc, argv, "Scheduler"); //NodeHandle is the main access point to communicate with ros. ros::NodeHandle nodeHandle; scheduler = Scheduler(); // advertise to event_trigger topic scheduler.eventTriggerPub = nodeHandle.advertise<EventTrigger>("event_trigger",1000, true); // subscribe to event_trigger topic scheduler.eventTriggerSub = nodeHandle.subscribe<EventTrigger>("event_trigger",1000, callEventTriggerCallback); scheduler.externalEventSub = nodeHandle.subscribe<EventTrigger>("external_event",1000, callExternalEventReceivedCallback); ros::Rate loop_rate(10); // populate queue with day's events scheduler.populateDailyTasks(); //a count of howmany messages we have sent int count = 0; sleep(5); while (ros::ok()) { if(scheduler.getEventQueueSize() == 0 && scheduler.getConcurrentWeight() <= 0) { ROS_INFO("Day Ends...."); sleep(10); scheduler.clearEventQueue(); scheduler.resetConcurrentWeight(); scheduler.resetRandomEventOccurrence(); scheduler.populateDailyTasks(); ROS_INFO("Day Starts...."); }else { scheduler.dequeueEvent(); } ros::spinOnce(); loop_rate.sleep(); ++count; } return 0; } <|endoftext|>
<commit_before>#include <ellis/ellis_array_node.hpp> #include <ellis/ellis_node.hpp> #include <ellis/private/using.hpp> namespace ellis { ellis_array_node::~ellis_array_node() { /* Do nothing; destruction is handled by ellis_node. */ } ellis_node& ellis_array_node::operator[](size_t index) { return m_node.m_blk->m_arr.operator[](index); } const ellis_node& ellis_array_node::operator[](size_t index) const { return m_node.m_blk->m_arr.operator[](index); } void ellis_array_node::append(const ellis_node &node) { m_node.m_blk->m_arr.push_back(node); } void ellis_array_node::append(ellis_node &&node) { m_node.m_blk->m_arr.push_back(node); } void ellis_array_node::extend(const ellis_array_node &other) { m_node.m_blk->m_arr.insert( m_node.m_blk->m_arr.cend(), other.m_node.m_blk->m_arr.cbegin(), other.m_node.m_blk->m_arr.cend()); } void ellis_array_node::extend(ellis_array_node &&other) { m_node.m_blk->m_arr.insert( m_node.m_blk->m_arr.end(), other.m_node.m_blk->m_arr.begin(), other.m_node.m_blk->m_arr.end()); } void ellis_array_node::insert(size_t pos, const ellis_node &other) { m_node.m_blk->m_arr.insert(m_node.m_blk->m_arr.cbegin() + pos, other); } void ellis_array_node::insert(size_t pos, ellis_node &&other) { m_node.m_blk->m_arr.insert(m_node.m_blk->m_arr.begin() + pos, other); } void ellis_array_node::erase(size_t pos) { m_node.m_blk->m_arr.erase(m_node.m_blk->m_arr.begin() + pos); } void ellis_array_node::reserve(size_t n) { m_node.m_blk->m_arr.reserve(n); } void ellis_array_node::foreach(std::function<void(ellis_node &)> fn) { for (ellis_node &node : m_node.m_blk->m_arr) { fn(node); } } void ellis_array_node::foreach(std::function<void(const ellis_node &)> fn) const { for (const ellis_node &node : m_node.m_blk->m_arr) { fn(node); } } ellis_array_node ellis_array_node::filter(std::function<bool(const ellis_node &)> fn) const { ellis_node res_node(ellis_type::ARRAY); /* TODO: add unsafe version of as_array and other functions and use it */ ellis_array_node &res_arr = res_node.as_array(); for (ellis_node &node : m_node.m_blk->m_arr) { if (fn(node)) { res_arr.append(node); } } /* TODO: is there a way to directly return res_arr? i shouldn't have to * re-call the function, but res_arr is indeed a local reference... */ return res_node.as_array(); } size_t ellis_array_node::length() const { return m_node.m_blk->m_arr.size(); } bool ellis_array_node::empty() const { return m_node.m_blk->m_arr.empty(); } void ellis_array_node::clear() { m_node.m_blk->m_arr.clear(); } } /* namespace ellis */ <commit_msg>ellis_array_node: small consistency fix<commit_after>#include <ellis/ellis_array_node.hpp> #include <ellis/ellis_node.hpp> #include <ellis/private/using.hpp> namespace ellis { ellis_array_node::~ellis_array_node() { /* Do nothing; destruction is handled by ellis_node. */ } ellis_node& ellis_array_node::operator[](size_t index) { return m_node.m_blk->m_arr[index]; } const ellis_node& ellis_array_node::operator[](size_t index) const { return m_node.m_blk->m_arr[index]; } void ellis_array_node::append(const ellis_node &node) { m_node.m_blk->m_arr.push_back(node); } void ellis_array_node::append(ellis_node &&node) { m_node.m_blk->m_arr.push_back(node); } void ellis_array_node::extend(const ellis_array_node &other) { m_node.m_blk->m_arr.insert( m_node.m_blk->m_arr.cend(), other.m_node.m_blk->m_arr.cbegin(), other.m_node.m_blk->m_arr.cend()); } void ellis_array_node::extend(ellis_array_node &&other) { m_node.m_blk->m_arr.insert( m_node.m_blk->m_arr.end(), other.m_node.m_blk->m_arr.begin(), other.m_node.m_blk->m_arr.end()); } void ellis_array_node::insert(size_t pos, const ellis_node &other) { m_node.m_blk->m_arr.insert(m_node.m_blk->m_arr.cbegin() + pos, other); } void ellis_array_node::insert(size_t pos, ellis_node &&other) { m_node.m_blk->m_arr.insert(m_node.m_blk->m_arr.begin() + pos, other); } void ellis_array_node::erase(size_t pos) { m_node.m_blk->m_arr.erase(m_node.m_blk->m_arr.begin() + pos); } void ellis_array_node::reserve(size_t n) { m_node.m_blk->m_arr.reserve(n); } void ellis_array_node::foreach(std::function<void(ellis_node &)> fn) { for (ellis_node &node : m_node.m_blk->m_arr) { fn(node); } } void ellis_array_node::foreach(std::function<void(const ellis_node &)> fn) const { for (const ellis_node &node : m_node.m_blk->m_arr) { fn(node); } } ellis_array_node ellis_array_node::filter(std::function<bool(const ellis_node &)> fn) const { ellis_node res_node(ellis_type::ARRAY); /* TODO: add unsafe version of as_array and other functions and use it */ ellis_array_node &res_arr = res_node.as_array(); for (ellis_node &node : m_node.m_blk->m_arr) { if (fn(node)) { res_arr.append(node); } } /* TODO: is there a way to directly return res_arr? i shouldn't have to * re-call the function, but res_arr is indeed a local reference... */ return res_node.as_array(); } size_t ellis_array_node::length() const { return m_node.m_blk->m_arr.size(); } bool ellis_array_node::empty() const { return m_node.m_blk->m_arr.empty(); } void ellis_array_node::clear() { m_node.m_blk->m_arr.clear(); } } /* namespace ellis */ <|endoftext|>
<commit_before>#include "data-general.hpp" #include "data-course.hpp" #include "data-student.hpp" using namespace std; vector<Course> all_courses; Student user; void loadCourses() { ifstream infile("data/2012-13-s2-csv.csv"); string str; // read in the header line getline(infile, str); while (infile.peek() != -1){ Course incourse(infile); all_courses.push_back(incourse); cout << incourse << endl; } } void whatDidICallThisWith(int argc, const char *argv[]) { printf ("This program was called with \"%s\".\n",argv[0]); if (argc > 1) for (int count = 1; count < argc; count++) printf("argv[%d] = %s\n", count, argv[count]); else printf("The command had no other arguments.\n"); } void welcome() { string name, yearS = "", yearE = "", majors; // cout << "Welcome!" << endl; // cout << "What is your name? "; // getline(cin, name); name = "Xandra Best"; // cout << "What year do you graduate? "; // cin >> yearE; // cout << "What are your majors (ex. CSCI, ASIAN) "; // getline(cin, majors); majors = "CSCI, STAT, ASIAN"; user = Student(name, yearS, yearE, majors); } void getCourses() { string courses; // cout << "What are some courses that you have taken? (ex. CSCI125, STAT 110)" << endl; // cout << "> "; // getline(cin, courses); courses = "CSCI 251, stat 110, THEAT398, writ211"; user.addCourses(courses); } int main(int argc, const char *argv[]) { loadCourses(); // cout << getCourse("STAT 10") << endl; // Course c("BIO 126"); // cout << c << endl; welcome(); getCourses(); user.display(); return 0; } <commit_msg>… and actually use it, too.<commit_after>#include "data-general.hpp" #include "data-course.hpp" #include "data-student.hpp" using namespace std; vector<Course> all_courses; Student user; void loadCourses() { ifstream infile("data/2012-13-s2-csv.csv"); string str; // read in the header line getline(infile, str); while (infile.peek() != -1){ Course incourse(infile); all_courses.push_back(incourse); } for (vector<Course>::iterator c = all_courses.begin(); c != all_courses.end(); ++c) c->displayMany(); } void whatDidICallThisWith(int argc, const char *argv[]) { printf ("This program was called with \"%s\".\n",argv[0]); if (argc > 1) for (int count = 1; count < argc; count++) printf("argv[%d] = %s\n", count, argv[count]); else printf("The command had no other arguments.\n"); } void welcome() { string name, yearS = "", yearE = "", majors; // cout << "Welcome!" << endl; // cout << "What is your name? "; // getline(cin, name); name = "Xandra Best"; // cout << "What year do you graduate? "; // cin >> yearE; // cout << "What are your majors (ex. CSCI, ASIAN) "; // getline(cin, majors); majors = "CSCI, STAT, ASIAN"; user = Student(name, yearS, yearE, majors); } void getCourses() { string courses; // cout << "What are some courses that you have taken? (ex. CSCI125, STAT 110)" << endl; // cout << "> "; // getline(cin, courses); courses = "CSCI 251, stat 110, THEAT398, writ211"; user.addCourses(courses); } int main(int argc, const char *argv[]) { loadCourses(); // cout << getCourse("STAT 10") << endl; // Course c("BIO 126"); // cout << c << endl; welcome(); getCourses(); user.display(); return 0; } <|endoftext|>
<commit_before>#include "core/base64.h" #include "core/assert.h" #include "core/cint.h" #include <sstream> #include <string_view> #include <array> // source: https://en.wikipedia.org/wiki/Base64 namespace euphoria::core::base64 { namespace { constexpr std::string_view CODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; } std::string Encode(std::shared_ptr<MemoryChunk> memory) { MemoryChunk& in = *memory; std::ostringstream out; for(int i = 0; i < in.GetSize(); i += 3) { int b = (in[i] & 0xFC) >> 2; out << CODES[b]; b = (in[i] & 0x03) << 4; if(i + 1 < in.GetSize()) { b |= (in[i + 1] & 0xF0) >> 4; out << CODES[b]; b = (in[i + 1] & 0x0F) << 2; if(i + 2 < in.GetSize()) { b |= (in[i + 2] & 0xC0) >> 6; out << CODES[b]; b = in[i + 2] & 0x3F; out << CODES[b]; } else { out << CODES[b]; out << '='; } } else { out << CODES[b]; out << "=="; } } return out.str(); } std::shared_ptr<MemoryChunk> Decode(const std::string& input) { if(input.length() % 4 == 0) { ASSERT(!input.empty()); auto asize = (input.length() * 3) / 4; auto found = input.find('=') != std::string::npos; auto bsize = found ? (input.length() - input.find('=')) : 0; int size = Csizet_to_int(asize) - Csizet_to_int(bsize); ASSERT(size > 0); auto ret = MemoryChunk::Alloc(size); MemoryChunk& decoded = *ret; int j = 0; for(int i = 0; i < Csizet_to_int(input.size()); i += 4) { // This could be made faster (but more complicated) by precomputing these index locations. const auto b = std::array<unsigned long, 4> { CODES.find(input[i]), CODES.find(input[i + 1]), CODES.find(input[i + 2]), CODES.find(input[i + 3]) }; decoded[j++] = static_cast<char>((b[0] << 2) | (b[1] >> 4)); if(b[2] < 64) { decoded[j++] = static_cast<char>((b[1] << 4) | (b[2] >> 2)); if(b[3] < 64) { decoded[j++] = static_cast<char>((b[2] << 6) | b[3]); } } } return ret; } else { return MemoryChunk::Null(); } } } <commit_msg>fixed windows compilation issue<commit_after>#include "core/base64.h" #include "core/assert.h" #include "core/cint.h" #include <sstream> #include <string_view> #include <array> // source: https://en.wikipedia.org/wiki/Base64 namespace euphoria::core::base64 { namespace { constexpr std::string_view CODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; } std::string Encode(std::shared_ptr<MemoryChunk> memory) { MemoryChunk& in = *memory; std::ostringstream out; for(int i = 0; i < in.GetSize(); i += 3) { int b = (in[i] & 0xFC) >> 2; out << CODES[b]; b = (in[i] & 0x03) << 4; if(i + 1 < in.GetSize()) { b |= (in[i + 1] & 0xF0) >> 4; out << CODES[b]; b = (in[i + 1] & 0x0F) << 2; if(i + 2 < in.GetSize()) { b |= (in[i + 2] & 0xC0) >> 6; out << CODES[b]; b = in[i + 2] & 0x3F; out << CODES[b]; } else { out << CODES[b]; out << '='; } } else { out << CODES[b]; out << "=="; } } return out.str(); } std::shared_ptr<MemoryChunk> Decode(const std::string& input) { if(input.length() % 4 == 0) { ASSERT(!input.empty()); auto asize = (input.length() * 3) / 4; auto found = input.find('=') != std::string::npos; auto bsize = found ? (input.length() - input.find('=')) : 0; int size = Csizet_to_int(asize) - Csizet_to_int(bsize); ASSERT(size > 0); auto ret = MemoryChunk::Alloc(size); MemoryChunk& decoded = *ret; int j = 0; for(int i = 0; i < Csizet_to_int(input.size()); i += 4) { // This could be made faster (but more complicated) by precomputing these index locations. const auto b = std::array<size_t, 4> { CODES.find(input[Cint_to_sizet(i)]), CODES.find(input[Cint_to_sizet(i + 1)]), CODES.find(input[Cint_to_sizet(i + 2)]), CODES.find(input[Cint_to_sizet(i + 3)]) }; decoded[j++] = static_cast<char>((b[0] << 2) | (b[1] >> 4)); if(b[2] < 64) { decoded[j++] = static_cast<char>((b[1] << 4) | (b[2] >> 2)); if(b[3] < 64) { decoded[j++] = static_cast<char>((b[2] << 6) | b[3]); } } } return ret; } else { return MemoryChunk::Null(); } } } <|endoftext|>
<commit_before>#include "clstm.h" #include <assert.h> #include <iostream> #include <vector> #include <memory> #include <math.h> #include <string> #include "extras.h" #include "utils.h" using std_string = std::string; #define string std_string using std::vector; using std::shared_ptr; using std::unique_ptr; using std::to_string; using std::make_pair; using std::cout; using std::stoi; using namespace Eigen; using namespace ocropus; double sqr(double x) { return x * x; } double randu() { static int count = 1; for (;;) { double x = cos(count * 3.7); count++; if (fabs(x) > 0.1) return x; } } void randseq(Sequence &a, int N, int n, int m) { a.resize(N, n, m); for (int t = 0; t < N; t++) for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[t].v(i, j) = randu(); } void randparams(vector<Params> &a) { int N = a.size(); for (int t = 0; t < N; t++) { int n = a[t].rows(); int m = a[t].cols(); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[t].v(i, j) = randu(); } } double err(Sequence &a, Sequence &b) { assert(a.size() == b.size()); assert(a.rows() == b.rows()); assert(a.cols() == b.cols()); int N = a.size(), n = a.rows(), m = a.cols(); double total = 0.0; for (int t = 0; t < N; t++) for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) total += sqr(a[t].v(i, j) - b[t].v(i, j)); return total; } void zero_grad(Network net) { walk_params(net, [](const string &s, Params *p) { p->zeroGrad(); }); } void get_params(vector<Params> &params, Network net) { params.clear(); walk_params( net, [&params](const string &s, Params *p) { params.emplace_back(*p); }); } void set_params(Network net, vector<Params> &params) { int index = 0; walk_params(net, [&index, &params](const string &s, Params *p) { *p = params[index++]; }); assert(index == params.size()); } struct Minimizer { double value = 1e9; double param = 0; void add(double value, double param = NAN) { if (value >= this->value) return; this->value = value; this->param = param; } }; struct Maximizer { double value = -1e9; double param = 0; void add(double value, double param = NAN) { if (value <= this->value) return; this->value = value; this->param = param; } }; void test_net(Network net, string id="", int bs=1) { if (id=="") id = net->kind; print("testing", id); int N = 4; int ninput = net->ninput(); int noutput = net->noutput(); ; bool verbose = getienv("verbose", 0); vector<Params> params, params1; get_params(params, net); randparams(params); set_params(net, params); Sequence xs, ys; randseq(xs, N, ninput, bs); randseq(ys, N, noutput, bs); Maximizer maxinerr; for (int t = 0; t < N; t++) { for (int i = 0; i < ninput; i++) { for (int b = 0; b < bs; b++) { Minimizer minerr; for (float h = 1e-6; h < 1.0; h *= 10) { set_inputs(net, xs); net->forward(); double out1 = err(net->outputs, ys); net->inputs[t].v(i, b) += h; net->forward(); double out2 = err(net->outputs, ys); double num_deriv = (out2 - out1) / h; set_inputs(net, xs); net->forward(); set_targets(net, ys); net->backward(); double a_deriv = net->inputs[t].d(i, b); double error = fabs(1.0 - num_deriv / a_deriv / -2.0); minerr.add(error, h); } if (verbose) print("deltas", t, i, b, minerr.value, minerr.param); assert(minerr.value < 0.1); maxinerr.add(minerr.value); } } } set_inputs(net, xs); net->forward(); double out = err(net->outputs, ys); set_targets(net, ys); zero_grad(net); net->backward(); get_params(params, net); Maximizer maxparamerr; for (int k = 0; k < params.size(); k++) { Params &p = params[k]; int n = p.rows(), m = p.cols(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { Minimizer minerr; for (float h = 1e-6; h < 1.0; h *= 10) { params1 = params; params1[k].v(i, j) += h; set_params(net, params1); net->forward(); double out1 = err(net->outputs, ys); double num_deriv = (out1 - out) / h; double a_deriv = params[k].d(i, j); double error = fabs(1.0 - num_deriv / a_deriv / -2.0); minerr.add(error, h); } if (verbose) print("params", k, i, j, minerr.value, minerr.param); assert(minerr.value < 0.1); maxparamerr.add(minerr.value); } } } print("OK", maxinerr.value, maxparamerr.value); } int main(int argc, char **argv) { TRY { test_net(layer("LinearLayer", 7, 3, {}, {})); test_net(layer("SigmoidLayer", 7, 3, {}, {})); test_net(layer("TanhLayer", 7, 3, {}, {})); test_net(layer("NPLSTM", 7, 3, {}, {})); test_net( layer("Reversed", 7, 3, {}, {layer("SigmoidLayer", 7, 3, {}, {})})); test_net(layer("Parallel", 7, 3, {}, {layer("SigmoidLayer", 7, 3, {}, {}), layer("LinearLayer", 7, 3, {}, {})}), "parallel(sigmoid,linear)"); test_net(make_net("bidi", {{"ninput", 7}, {"noutput", 3}, {"nhidden", 5}, {"output_type", "SigmoidLayer"}}), "bidi"); test_net(layer("Stacked", 3, 3, {}, { layer("Btswitch", 3, 3, {}, {}), layer("Btswitch", 3, 3, {}, {})}), "btswitch"); test_net(layer("Batchstack", 3, 9, {}, {}), "Batchstack", 5); // not testing: SoftmaxLayer and ReluLayer } CATCH(const char *message) { print("ERROR", message); } } <commit_msg>changed test-deriv to use inf/-inf by default<commit_after>#include "clstm.h" #include <assert.h> #include <iostream> #include <vector> #include <memory> #include <math.h> #include <cmath> #include <string> #include "extras.h" #include "utils.h" using std_string = std::string; #define string std_string using std::vector; using std::shared_ptr; using std::unique_ptr; using std::to_string; using std::make_pair; using std::cout; using std::stoi; using namespace Eigen; using namespace ocropus; double sqr(double x) { return x * x; } double randu() { static int count = 1; for (;;) { double x = cos(count * 3.7); count++; if (fabs(x) > 0.1) return x; } } void randseq(Sequence &a, int N, int n, int m) { a.resize(N, n, m); for (int t = 0; t < N; t++) for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[t].v(i, j) = randu(); } void randparams(vector<Params> &a) { int N = a.size(); for (int t = 0; t < N; t++) { int n = a[t].rows(); int m = a[t].cols(); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[t].v(i, j) = randu(); } } double err(Sequence &a, Sequence &b) { assert(a.size() == b.size()); assert(a.rows() == b.rows()); assert(a.cols() == b.cols()); int N = a.size(), n = a.rows(), m = a.cols(); double total = 0.0; for (int t = 0; t < N; t++) for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) total += sqr(a[t].v(i, j) - b[t].v(i, j)); return total; } void zero_grad(Network net) { walk_params(net, [](const string &s, Params *p) { p->zeroGrad(); }); } void get_params(vector<Params> &params, Network net) { params.clear(); walk_params( net, [&params](const string &s, Params *p) { params.emplace_back(*p); }); } void set_params(Network net, vector<Params> &params) { int index = 0; walk_params(net, [&index, &params](const string &s, Params *p) { *p = params[index++]; }); assert(index == params.size()); } struct Minimizer { double value = INFINITY; double param = 0; void add(double value, double param = NAN) { if (value >= this->value) return; this->value = value; this->param = param; } }; struct Maximizer { double value = -INFINITY; double param = 0; void add(double value, double param = NAN) { if (value <= this->value) return; this->value = value; this->param = param; } }; void test_net(Network net, string id="", int bs=1) { if (id=="") id = net->kind; print("testing", id); int N = 4; int ninput = net->ninput(); int noutput = net->noutput(); ; bool verbose = getienv("verbose", 0); vector<Params> params, params1; get_params(params, net); randparams(params); set_params(net, params); Sequence xs, ys; randseq(xs, N, ninput, bs); randseq(ys, N, noutput, bs); Maximizer maxinerr; for (int t = 0; t < N; t++) { for (int i = 0; i < ninput; i++) { for (int b = 0; b < bs; b++) { Minimizer minerr; for (float h = 1e-6; h < 1.0; h *= 10) { set_inputs(net, xs); net->forward(); double out1 = err(net->outputs, ys); net->inputs[t].v(i, b) += h; net->forward(); double out2 = err(net->outputs, ys); double num_deriv = (out2 - out1) / h; set_inputs(net, xs); net->forward(); set_targets(net, ys); net->backward(); double a_deriv = net->inputs[t].d(i, b); double error = fabs(1.0 - num_deriv / a_deriv / -2.0); minerr.add(error, h); } if (verbose) print("deltas", t, i, b, minerr.value, minerr.param); assert(minerr.value < 0.1); maxinerr.add(minerr.value); } } } set_inputs(net, xs); net->forward(); double out = err(net->outputs, ys); set_targets(net, ys); zero_grad(net); net->backward(); get_params(params, net); Maximizer maxparamerr; for (int k = 0; k < params.size(); k++) { Params &p = params[k]; int n = p.rows(), m = p.cols(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { Minimizer minerr; for (float h = 1e-6; h < 1.0; h *= 10) { params1 = params; params1[k].v(i, j) += h; set_params(net, params1); net->forward(); double out1 = err(net->outputs, ys); double num_deriv = (out1 - out) / h; double a_deriv = params[k].d(i, j); double error = fabs(1.0 - num_deriv / a_deriv / -2.0); minerr.add(error, h); } if (verbose) print("params", k, i, j, minerr.value, minerr.param); assert(minerr.value < 0.1); maxparamerr.add(minerr.value); } } } print("OK", maxinerr.value, maxparamerr.value); } int main(int argc, char **argv) { TRY { test_net(layer("LinearLayer", 7, 3, {}, {})); test_net(layer("SigmoidLayer", 7, 3, {}, {})); test_net(layer("TanhLayer", 7, 3, {}, {})); test_net(layer("NPLSTM", 7, 3, {}, {})); test_net( layer("Reversed", 7, 3, {}, {layer("SigmoidLayer", 7, 3, {}, {})})); test_net(layer("Parallel", 7, 3, {}, {layer("SigmoidLayer", 7, 3, {}, {}), layer("LinearLayer", 7, 3, {}, {})}), "parallel(sigmoid,linear)"); test_net(make_net("bidi", {{"ninput", 7}, {"noutput", 3}, {"nhidden", 5}, {"output_type", "SigmoidLayer"}}), "bidi"); test_net(layer("Stacked", 3, 3, {}, { layer("Btswitch", 3, 3, {}, {}), layer("Btswitch", 3, 3, {}, {})}), "btswitch"); test_net(layer("Batchstack", 3, 9, {}, {}), "Batchstack", 5); // not testing: SoftmaxLayer and ReluLayer } CATCH(const char *message) { print("ERROR", message); } } <|endoftext|>
<commit_before>/* Copyright (c) 2007, 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. */ #include "libtorrent/pch.hpp" #include "libtorrent/lsd.hpp" #include "libtorrent/io.hpp" #include "libtorrent/http_tracker_connection.hpp" #include "libtorrent/buffer.hpp" #include "libtorrent/http_parser.hpp" #include "libtorrent/escape_string.hpp" #include <boost/bind.hpp> #include <boost/ref.hpp> #if BOOST_VERSION < 103500 #include <asio/ip/host_name.hpp> #include <asio/ip/multicast.hpp> #else #include <boost/asio/ip/host_name.hpp> #include <boost/asio/ip/multicast.hpp> #endif #include <boost/thread/mutex.hpp> #include <cstdlib> #include <boost/config.hpp> using boost::bind; using namespace libtorrent; namespace libtorrent { // defined in broadcast_socket.cpp address guess_local_address(io_service&); } static error_code ec; lsd::lsd(io_service& ios, address const& listen_interface , peer_callback_t const& cb) : m_callback(cb) , m_retry_count(1) , m_socket(ios, udp::endpoint(address_v4::from_string("239.192.152.143", ec), 6771) , bind(&lsd::on_announce, self(), _1, _2, _3)) , m_broadcast_timer(ios) , m_disabled(false) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc); #endif } lsd::~lsd() {} void lsd::announce(sha1_hash const& ih, int listen_port) { if (m_disabled) return; char ih_hex[41]; to_hex((char const*)&ih[0], 20, ih_hex); char msg[200]; int msg_len = snprintf(msg, 200, "BT-SEARCH * HTTP/1.1\r\n" "Host: 239.192.152.143:6771\r\n" "Port: %d\r\n" "Infohash: %s\r\n" "\r\n\r\n", listen_port, ih_hex); m_retry_count = 1; error_code ec; m_socket.send(msg, msg_len, ec); if (ec) { m_disabled = true; return; } #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) snprintf(msg, 200, "%s ==> announce: ih: %s port: %u\n" , time_now_string(), ih_hex, listen_port); m_log << msg; #endif m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec); m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg)); } void lsd::resend_announce(error_code const& e, std::string msg) { if (e) return; error_code ec; m_socket.send(msg.c_str(), int(msg.size()), ec); ++m_retry_count; if (m_retry_count >= 5) return; m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec); m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg)); } void lsd::on_announce(udp::endpoint const& from, char* buffer , std::size_t bytes_transferred) { using namespace libtorrent::detail; http_parser p; bool error = false; p.incoming(buffer::const_interval(buffer, buffer + bytes_transferred) , error); if (!p.header_finished() || error) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== announce: incomplete HTTP message\n"; #endif return; } if (p.method() != "bt-search") { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== announce: invalid HTTP method: " << p.method() << std::endl; #endif return; } std::string const& port_str = p.header("port"); if (port_str.empty()) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== announce: invalid BT-SEARCH, missing port" << std::endl; #endif return; } std::string const& ih_str = p.header("infohash"); if (ih_str.empty()) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== announce: invalid BT-SEARCH, missing infohash" << std::endl; #endif return; } sha1_hash ih(0); from_hex(ih_str.c_str(), 40, (char*)&ih[0]); int port = std::atoi(port_str.c_str()); if (!ih.is_all_zeros() && port != 0) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) char msg[200]; snprintf(msg, 200, "%s *** incoming local announce %s:%d ih: %s\n" , time_now_string(), print_address(from.address()).c_str() , port, ih_str.c_str()); #endif // we got an announce, pass it on through the callback #ifndef BOOST_NO_EXCEPTIONS try { #endif m_callback(tcp::endpoint(from.address(), port), ih); #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception&) {} #endif } } void lsd::close() { m_socket.close(); error_code ec; m_broadcast_timer.cancel(ec); m_disabled = true; m_callback.clear(); } <commit_msg>fixed lsd logging<commit_after>/* Copyright (c) 2007, 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. */ #include "libtorrent/pch.hpp" #include "libtorrent/lsd.hpp" #include "libtorrent/io.hpp" #include "libtorrent/http_tracker_connection.hpp" #include "libtorrent/buffer.hpp" #include "libtorrent/http_parser.hpp" #include "libtorrent/escape_string.hpp" #include <boost/bind.hpp> #include <boost/ref.hpp> #if BOOST_VERSION < 103500 #include <asio/ip/host_name.hpp> #include <asio/ip/multicast.hpp> #else #include <boost/asio/ip/host_name.hpp> #include <boost/asio/ip/multicast.hpp> #endif #include <boost/thread/mutex.hpp> #include <cstdlib> #include <boost/config.hpp> using boost::bind; using namespace libtorrent; namespace libtorrent { // defined in broadcast_socket.cpp address guess_local_address(io_service&); } static error_code ec; lsd::lsd(io_service& ios, address const& listen_interface , peer_callback_t const& cb) : m_callback(cb) , m_retry_count(1) , m_socket(ios, udp::endpoint(address_v4::from_string("239.192.152.143", ec), 6771) , bind(&lsd::on_announce, self(), _1, _2, _3)) , m_broadcast_timer(ios) , m_disabled(false) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc); #endif } lsd::~lsd() {} void lsd::announce(sha1_hash const& ih, int listen_port) { if (m_disabled) return; char ih_hex[41]; to_hex((char const*)&ih[0], 20, ih_hex); char msg[200]; int msg_len = snprintf(msg, 200, "BT-SEARCH * HTTP/1.1\r\n" "Host: 239.192.152.143:6771\r\n" "Port: %d\r\n" "Infohash: %s\r\n" "\r\n\r\n", listen_port, ih_hex); m_retry_count = 1; error_code ec; m_socket.send(msg, msg_len, ec); if (ec) { m_disabled = true; return; } #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) snprintf(msg, 200, "%s ==> announce: ih: %s port: %u" , time_now_string(), ih_hex, listen_port); m_log << msg << std::endl; #endif m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec); m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg)); } void lsd::resend_announce(error_code const& e, std::string msg) { if (e) return; error_code ec; m_socket.send(msg.c_str(), int(msg.size()), ec); ++m_retry_count; if (m_retry_count >= 5) return; m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec); m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg)); } void lsd::on_announce(udp::endpoint const& from, char* buffer , std::size_t bytes_transferred) { using namespace libtorrent::detail; http_parser p; bool error = false; p.incoming(buffer::const_interval(buffer, buffer + bytes_transferred) , error); if (!p.header_finished() || error) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== announce: incomplete HTTP message" << std::endl; #endif return; } if (p.method() != "bt-search") { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== announce: invalid HTTP method: " << p.method() << std::endl; #endif return; } std::string const& port_str = p.header("port"); if (port_str.empty()) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== announce: invalid BT-SEARCH, missing port" << std::endl; #endif return; } std::string const& ih_str = p.header("infohash"); if (ih_str.empty()) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== announce: invalid BT-SEARCH, missing infohash" << std::endl; #endif return; } sha1_hash ih(0); from_hex(ih_str.c_str(), 40, (char*)&ih[0]); int port = std::atoi(port_str.c_str()); if (!ih.is_all_zeros() && port != 0) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) char msg[200]; snprintf(msg, 200, "%s *** incoming local announce %s:%d ih: %s\n" , time_now_string(), print_address(from.address()).c_str() , port, ih_str.c_str()); #endif // we got an announce, pass it on through the callback #ifndef BOOST_NO_EXCEPTIONS try { #endif m_callback(tcp::endpoint(from.address(), port), ih); #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception&) {} #endif } } void lsd::close() { m_socket.close(); error_code ec; m_broadcast_timer.cancel(ec); m_disabled = true; m_callback.clear(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: iipaobj.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2006-09-25 13:32:14 $ * * 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 _IIPAOBJ_HXX_ #define _IIPAOBJ_HXX_ #if defined(_MSC_VER) && (_MSC_VER > 1310) #pragma warning(disable : 4917 4555) #endif #include "stdafx.h" #include <oleidl.h> #include <osl/interlck.h> #include <rtl/ref.hxx> class EmbedDocument_Impl; class DocumentHolder; class CIIAObj : public IOleInPlaceActiveObject { public: CIIAObj( DocumentHolder * ); virtual ~CIIAObj(); /* IUnknown methods */ STDMETHODIMP QueryInterface(REFIID, LPVOID FAR * ppvObj); STDMETHODIMP_(ULONG) AddRef(void); STDMETHODIMP_(ULONG) Release(void); /* IOleInPlaceActiveObject methods */ STDMETHODIMP GetWindow(HWND *); STDMETHODIMP ContextSensitiveHelp(BOOL); STDMETHODIMP TranslateAccelerator(LPMSG); STDMETHODIMP OnFrameWindowActivate(BOOL); STDMETHODIMP OnDocWindowActivate(BOOL); STDMETHODIMP ResizeBorder(LPCRECT, LPOLEINPLACEUIWINDOW , BOOL); STDMETHODIMP EnableModeless(BOOL); private: oslInterlockedCount m_refCount; ::rtl::Reference< DocumentHolder > m_rDocHolder; }; #endif<commit_msg>INTEGRATION: CWS changefileheader (1.6.38); FILE MERGED 2008/03/31 13:33:42 rt 1.6.38.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: iipaobj.hxx,v $ * $Revision: 1.7 $ * * 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. * ************************************************************************/ #ifndef _IIPAOBJ_HXX_ #define _IIPAOBJ_HXX_ #if defined(_MSC_VER) && (_MSC_VER > 1310) #pragma warning(disable : 4917 4555) #endif #include "stdafx.h" #include <oleidl.h> #include <osl/interlck.h> #include <rtl/ref.hxx> class EmbedDocument_Impl; class DocumentHolder; class CIIAObj : public IOleInPlaceActiveObject { public: CIIAObj( DocumentHolder * ); virtual ~CIIAObj(); /* IUnknown methods */ STDMETHODIMP QueryInterface(REFIID, LPVOID FAR * ppvObj); STDMETHODIMP_(ULONG) AddRef(void); STDMETHODIMP_(ULONG) Release(void); /* IOleInPlaceActiveObject methods */ STDMETHODIMP GetWindow(HWND *); STDMETHODIMP ContextSensitiveHelp(BOOL); STDMETHODIMP TranslateAccelerator(LPMSG); STDMETHODIMP OnFrameWindowActivate(BOOL); STDMETHODIMP OnDocWindowActivate(BOOL); STDMETHODIMP ResizeBorder(LPCRECT, LPOLEINPLACEUIWINDOW , BOOL); STDMETHODIMP EnableModeless(BOOL); private: oslInterlockedCount m_refCount; ::rtl::Reference< DocumentHolder > m_rDocHolder; }; #endif<|endoftext|>
<commit_before>/* Copyright 2017 Istio Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/envoy/utils/utils.h" #include "mixer/v1/attributes.pb.h" using ::google::protobuf::Message; using ::google::protobuf::Struct; using ::google::protobuf::util::Status; namespace Envoy { namespace Utils { namespace { const std::string kSPIFFEPrefix("spiffe://"); // Per-host opaque data field const std::string kPerHostMetadataKey("istio"); // Attribute field for per-host data override const std::string kMetadataDestinationUID("uid"); } // namespace void ExtractHeaders(const Http::HeaderMap& header_map, const std::set<std::string>& exclusives, std::map<std::string, std::string>& headers) { struct Context { Context(const std::set<std::string>& exclusives, std::map<std::string, std::string>& headers) : exclusives(exclusives), headers(headers) {} const std::set<std::string>& exclusives; std::map<std::string, std::string>& headers; }; Context ctx(exclusives, headers); header_map.iterate( [](const Http::HeaderEntry& header, void* context) -> Http::HeaderMap::Iterate { Context* ctx = static_cast<Context*>(context); if (ctx->exclusives.count(header.key().c_str()) == 0) { ctx->headers[header.key().c_str()] = header.value().c_str(); } return Http::HeaderMap::Iterate::Continue; }, &ctx); } bool GetIpPort(const Network::Address::Ip* ip, std::string* str_ip, int* port) { if (ip) { *port = ip->port(); if (ip->ipv4()) { uint32_t ipv4 = ip->ipv4()->address(); *str_ip = std::string(reinterpret_cast<const char*>(&ipv4), sizeof(ipv4)); return true; } if (ip->ipv6()) { absl::uint128 ipv6 = ip->ipv6()->address(); *str_ip = std::string(reinterpret_cast<const char*>(&ipv6), 16); return true; } } return false; } bool GetDestinationUID(const envoy::api::v2::core::Metadata& metadata, std::string* uid) { const auto filter_it = metadata.filter_metadata().find(kPerHostMetadataKey); if (filter_it == metadata.filter_metadata().end()) { return false; } const Struct& struct_pb = filter_it->second; const auto fields_it = struct_pb.fields().find(kMetadataDestinationUID); if (fields_it == struct_pb.fields().end()) { return false; } *uid = fields_it->second.string_value(); return true; } bool GetPrincipal(const Network::Connection* connection, bool peer, std::string* principal) { if (connection) { Ssl::Connection* ssl = const_cast<Ssl::Connection*>(connection->ssl()); if (ssl != nullptr) { std::string result; if (peer) { result = ssl->uriSanPeerCertificate(); } else { result = ssl->uriSanLocalCertificate(); } if (result.empty()) { // empty result is not allowed return false; } if (result.length() >= kSPIFFEPrefix.length() && result.compare(0, kSPIFFEPrefix.length(), kSPIFFEPrefix) == 0) { // Strip out the prefix "spiffe://" in the identity. *principal = result.substr(kSPIFFEPrefix.size()); } else { *principal = result; } return true; } } return false; } bool IsMutualTLS(const Network::Connection* connection) { return connection != nullptr && connection->ssl() != nullptr && connection->ssl()->peerCertificatePresented(); } bool GetRequestedServerName(const Network::Connection* connection, std::string* name) { if (connection) { *name = std::string(connection->requestedServerName()); return true; } return false; } Status ParseJsonMessage(const std::string& json, Message* output) { ::google::protobuf::util::JsonParseOptions options; options.ignore_unknown_fields = true; return ::google::protobuf::util::JsonStringToMessage(json, output, options); } } // namespace Utils } // namespace Envoy <commit_msg>skip empty sni (#1909)<commit_after>/* Copyright 2017 Istio Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/envoy/utils/utils.h" #include "mixer/v1/attributes.pb.h" using ::google::protobuf::Message; using ::google::protobuf::Struct; using ::google::protobuf::util::Status; namespace Envoy { namespace Utils { namespace { const std::string kSPIFFEPrefix("spiffe://"); // Per-host opaque data field const std::string kPerHostMetadataKey("istio"); // Attribute field for per-host data override const std::string kMetadataDestinationUID("uid"); } // namespace void ExtractHeaders(const Http::HeaderMap& header_map, const std::set<std::string>& exclusives, std::map<std::string, std::string>& headers) { struct Context { Context(const std::set<std::string>& exclusives, std::map<std::string, std::string>& headers) : exclusives(exclusives), headers(headers) {} const std::set<std::string>& exclusives; std::map<std::string, std::string>& headers; }; Context ctx(exclusives, headers); header_map.iterate( [](const Http::HeaderEntry& header, void* context) -> Http::HeaderMap::Iterate { Context* ctx = static_cast<Context*>(context); if (ctx->exclusives.count(header.key().c_str()) == 0) { ctx->headers[header.key().c_str()] = header.value().c_str(); } return Http::HeaderMap::Iterate::Continue; }, &ctx); } bool GetIpPort(const Network::Address::Ip* ip, std::string* str_ip, int* port) { if (ip) { *port = ip->port(); if (ip->ipv4()) { uint32_t ipv4 = ip->ipv4()->address(); *str_ip = std::string(reinterpret_cast<const char*>(&ipv4), sizeof(ipv4)); return true; } if (ip->ipv6()) { absl::uint128 ipv6 = ip->ipv6()->address(); *str_ip = std::string(reinterpret_cast<const char*>(&ipv6), 16); return true; } } return false; } bool GetDestinationUID(const envoy::api::v2::core::Metadata& metadata, std::string* uid) { const auto filter_it = metadata.filter_metadata().find(kPerHostMetadataKey); if (filter_it == metadata.filter_metadata().end()) { return false; } const Struct& struct_pb = filter_it->second; const auto fields_it = struct_pb.fields().find(kMetadataDestinationUID); if (fields_it == struct_pb.fields().end()) { return false; } *uid = fields_it->second.string_value(); return true; } bool GetPrincipal(const Network::Connection* connection, bool peer, std::string* principal) { if (connection) { Ssl::Connection* ssl = const_cast<Ssl::Connection*>(connection->ssl()); if (ssl != nullptr) { std::string result; if (peer) { result = ssl->uriSanPeerCertificate(); } else { result = ssl->uriSanLocalCertificate(); } if (result.empty()) { // empty result is not allowed return false; } if (result.length() >= kSPIFFEPrefix.length() && result.compare(0, kSPIFFEPrefix.length(), kSPIFFEPrefix) == 0) { // Strip out the prefix "spiffe://" in the identity. *principal = result.substr(kSPIFFEPrefix.size()); } else { *principal = result; } return true; } } return false; } bool IsMutualTLS(const Network::Connection* connection) { return connection != nullptr && connection->ssl() != nullptr && connection->ssl()->peerCertificatePresented(); } bool GetRequestedServerName(const Network::Connection* connection, std::string* name) { if (connection && !connection->requestedServerName().empty()) { *name = std::string(connection->requestedServerName()); return true; } return false; } Status ParseJsonMessage(const std::string& json, Message* output) { ::google::protobuf::util::JsonParseOptions options; options.ignore_unknown_fields = true; return ::google::protobuf::util::JsonStringToMessage(json, output, options); } } // namespace Utils } // namespace Envoy <|endoftext|>
<commit_before>/* * LIFGap.hpp * * Created on: Jul 29, 2011 * Author: garkenyon */ #ifndef LIFGAP_HPP_ #define LIFGAP_HPP_ #include "LIF.hpp" #define NUM_LIFGAP_EVENTS 1 + NUM_LIF_EVENTS // ??? #define EV_LIF_GSYN_GAP NUM_LIF_EVENTS + 1 namespace PV { class LIFGap: public PV::LIF { public: LIFGap(const char* name, HyPerCol * hc); LIFGap(const char* name, HyPerCol * hc, PVLayerType type); virtual ~LIFGap(); void addGapStrength(float gap_strength){sumGap += gap_strength;} int virtual updateStateOpenCL(float time, float dt); int virtual triggerReceive(InterColComm* comm); int virtual updateState(float time, float dt); int virtual readState(float * time); int virtual writeState(float time, bool last); protected: pvdata_t * G_Gap; pvdata_t sumGap; #ifdef PV_USE_OPENCL virtual int initializeThreadBuffers(char * kernelName); virtual int initializeThreadKernels(char * kernelName); // OpenCL buffers // CLBuffer * clG_Gap; virtual int getNumCLEvents(){return NUM_LIFGAP_EVENTS}; #endif private: virtual int initialize(PVLayerType type, const char * kernelName); }; } /* namespace PV */ #endif /* LIFGAP_HPP_ */ <commit_msg>Added clGSynGap instance variable.<commit_after>/* * LIFGap.hpp * * Created on: Jul 29, 2011 * Author: garkenyon */ #ifndef LIFGAP_HPP_ #define LIFGAP_HPP_ #include "LIF.hpp" #define NUM_LIFGAP_EVENTS 1 + NUM_LIF_EVENTS // ??? #define EV_LIF_GSYN_GAP NUM_LIF_EVENTS + 1 namespace PV { class LIFGap: public PV::LIF { public: LIFGap(const char* name, HyPerCol * hc); LIFGap(const char* name, HyPerCol * hc, PVLayerType type); virtual ~LIFGap(); void addGapStrength(float gap_strength){sumGap += gap_strength;} int virtual updateStateOpenCL(float time, float dt); int virtual triggerReceive(InterColComm* comm); int virtual updateState(float time, float dt); int virtual readState(float * time); int virtual writeState(float time, bool last); protected: pvdata_t * G_Gap; pvdata_t sumGap; #ifdef PV_USE_OPENCL virtual int initializeThreadBuffers(char * kernelName); virtual int initializeThreadKernels(char * kernelName); // OpenCL buffers // CLBuffer * clG_Gap; CLBuffer * clGSynGap; virtual int getNumCLEvents(){return NUM_LIFGAP_EVENTS;} #endif private: virtual int initialize(PVLayerType type, const char * kernelName); }; } /* namespace PV */ #endif /* LIFGAP_HPP_ */ <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * StageprofiWidget.cpp * This is the base widget class * Copyright (C) 2006-2009 Simon Newton */ #include <string.h> #include <algorithm> #include "ola/Callback.h" #include "plugins/stageprofi/StageProfiWidget.h" namespace ola { namespace plugin { namespace stageprofi { enum stageprofi_packet_type_e { ID_GETDMX = 0xFE, ID_SETDMX = 0xFF, ID_SETLO = 0xE0, ID_SETHI = 0xE1, }; typedef enum stageprofi_packet_type_e stageprofi_packet_type; /* * New widget */ StageProfiWidget::~StageProfiWidget() { if (m_socket) { m_socket->Close(); delete m_socket; } } /* * Disconnect from the widget */ int StageProfiWidget::Disconnect() { m_socket->Close(); return 0; } /* * Send a dmx msg. * This has the nasty property of blocking if we remove the device * TODO: fix this */ bool StageProfiWidget::SendDmx(const DmxBuffer &buffer) const { unsigned int index = 0; while (index < buffer.Size()) { unsigned int size = std::min((unsigned int) DMX_MSG_LEN, buffer.Size() - index); Send255(index, buffer.GetRaw() + index, size); index += size; } return true; } /* * Called when there is adata to read */ void StageProfiWidget::SocketReady() { while (m_socket->DataRemaining() > 0) { DoRecv(); } } void StageProfiWidget::Timeout() { if (m_ss) m_ss->Terminate(); } /* * Check if this is actually a StageProfi device * @return true if this is a stageprofi, false otherwise */ bool StageProfiWidget::DetectDevice() { if (m_ss) delete m_ss; m_got_response = false; m_ss = new SelectServer(); m_ss->AddReadDescriptor(m_socket, NULL); m_ss->RegisterSingleTimeout( 100, ola::NewSingleCallback(this, &StageProfiWidget::Timeout)); // try a command, we should get a response SetChannel(0, 0); m_ss->Run(); delete m_ss; m_ss = NULL; if (m_got_response) return true; m_socket->Close(); return false; } //----------------------------------------------------------------------------- // Private methods used for communicating with the widget /* * Set a single channel */ int StageProfiWidget::SetChannel(unsigned int chan, uint8_t val) const { uint8_t msg[3]; msg[0] = chan > DMX_MSG_LEN ? ID_SETHI : ID_SETLO; msg[1] = chan & 0xFF; msg[2] = val; return m_socket->Send(msg, sizeof(msg)); } /* * Send 255 channels worth of data * @param start the start channel for the data * @param buf a pointer to the data * @param len the length of the data */ int StageProfiWidget::Send255(unsigned int start, const uint8_t *buf, unsigned int length) const { uint8_t msg[DMX_MSG_LEN + DMX_HEADER_SIZE]; unsigned int len = std::min((unsigned int) DMX_MSG_LEN, length); msg[0] = ID_SETDMX; msg[1] = start & 0xFF; msg[2] = (start>>8) & 0xFF; msg[3] = len; memcpy(msg + DMX_HEADER_SIZE, buf, len); return m_socket->Send(msg, len + DMX_HEADER_SIZE); } /* * */ int StageProfiWidget::DoRecv() { uint8_t byte = 0x00; unsigned int data_read; while (byte != 'G') { int ret = m_socket->Receive(&byte, 1, data_read); if (ret == -1 || data_read != 1) { return -1; } } m_got_response = true; return 0; } } // stageprofi } // plugin } // ola <commit_msg>Fix a compile error with the StageProfiWidget<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * StageprofiWidget.cpp * This is the base widget class * Copyright (C) 2006-2009 Simon Newton */ #include <string.h> #include <algorithm> #include "ola/Callback.h" #include "plugins/stageprofi/StageProfiWidget.h" namespace ola { namespace plugin { namespace stageprofi { enum stageprofi_packet_type_e { ID_GETDMX = 0xFE, ID_SETDMX = 0xFF, ID_SETLO = 0xE0, ID_SETHI = 0xE1, }; typedef enum stageprofi_packet_type_e stageprofi_packet_type; /* * New widget */ StageProfiWidget::~StageProfiWidget() { if (m_socket) { m_socket->Close(); delete m_socket; } } /* * Disconnect from the widget */ int StageProfiWidget::Disconnect() { m_socket->Close(); return 0; } /* * Send a dmx msg. * This has the nasty property of blocking if we remove the device * TODO: fix this */ bool StageProfiWidget::SendDmx(const DmxBuffer &buffer) const { unsigned int index = 0; while (index < buffer.Size()) { unsigned int size = std::min((unsigned int) DMX_MSG_LEN, buffer.Size() - index); Send255(index, buffer.GetRaw() + index, size); index += size; } return true; } /* * Called when there is adata to read */ void StageProfiWidget::SocketReady() { while (m_socket->DataRemaining() > 0) { DoRecv(); } } void StageProfiWidget::Timeout() { if (m_ss) m_ss->Terminate(); } /* * Check if this is actually a StageProfi device * @return true if this is a stageprofi, false otherwise */ bool StageProfiWidget::DetectDevice() { if (m_ss) delete m_ss; m_got_response = false; m_ss = new SelectServer(); m_ss->AddReadDescriptor(m_socket, false); m_ss->RegisterSingleTimeout( 100, ola::NewSingleCallback(this, &StageProfiWidget::Timeout)); // try a command, we should get a response SetChannel(0, 0); m_ss->Run(); delete m_ss; m_ss = NULL; if (m_got_response) return true; m_socket->Close(); return false; } //----------------------------------------------------------------------------- // Private methods used for communicating with the widget /* * Set a single channel */ int StageProfiWidget::SetChannel(unsigned int chan, uint8_t val) const { uint8_t msg[3]; msg[0] = chan > DMX_MSG_LEN ? ID_SETHI : ID_SETLO; msg[1] = chan & 0xFF; msg[2] = val; return m_socket->Send(msg, sizeof(msg)); } /* * Send 255 channels worth of data * @param start the start channel for the data * @param buf a pointer to the data * @param len the length of the data */ int StageProfiWidget::Send255(unsigned int start, const uint8_t *buf, unsigned int length) const { uint8_t msg[DMX_MSG_LEN + DMX_HEADER_SIZE]; unsigned int len = std::min((unsigned int) DMX_MSG_LEN, length); msg[0] = ID_SETDMX; msg[1] = start & 0xFF; msg[2] = (start>>8) & 0xFF; msg[3] = len; memcpy(msg + DMX_HEADER_SIZE, buf, len); return m_socket->Send(msg, len + DMX_HEADER_SIZE); } /* * */ int StageProfiWidget::DoRecv() { uint8_t byte = 0x00; unsigned int data_read; while (byte != 'G') { int ret = m_socket->Receive(&byte, 1, data_read); if (ret == -1 || data_read != 1) { return -1; } } m_got_response = true; return 0; } } // stageprofi } // plugin } // ola <|endoftext|>
<commit_before>#include "model.h" #include <string> #include <exception> std::istream& operator>>(std::istream& in, Model &model) { int count; in >> count; while (count --> 0) { std::string type; in >> type; if (type == "segment") { int x1, y1, x2, y2; in >> x1 >> y1 >> x2 >> y2; model.addFigure(std::make_shared<figures::Segment>(Point(x1, y1), Point(x2, y2))); } else if (type == "rectangle") { int x1, y1, x2, y2; in >> x1 >> y1 >> x2 >> y2; model.addFigure(std::make_shared<figures::Rectangle>(BoundingBox({Point(x1, y1), Point(x2, y2)}))); } else if (type == "ellipse") { int x1, y1, x2, y2; in >> x1 >> y1 >> x2 >> y2; model.addFigure(std::make_shared<figures::Ellipse>(BoundingBox({Point(x1, y1), Point(x2, y2)}))); } else { throw std::runtime_error("Invalid model format"); } } return in; } <commit_msg>model: operator>>: some information to runtime_exception() throw was added<commit_after>#include "model.h" #include <string> #include <exception> std::istream& operator>>(std::istream& in, Model &model) { int count; in >> count; while (count --> 0) { std::string type; in >> type; if (type == "segment") { int x1, y1, x2, y2; in >> x1 >> y1 >> x2 >> y2; model.addFigure(std::make_shared<figures::Segment>(Point(x1, y1), Point(x2, y2))); } else if (type == "rectangle") { int x1, y1, x2, y2; in >> x1 >> y1 >> x2 >> y2; model.addFigure(std::make_shared<figures::Rectangle>(BoundingBox({Point(x1, y1), Point(x2, y2)}))); } else if (type == "ellipse") { int x1, y1, x2, y2; in >> x1 >> y1 >> x2 >> y2; model.addFigure(std::make_shared<figures::Ellipse>(BoundingBox({Point(x1, y1), Point(x2, y2)}))); } else { throw std::runtime_error("Invalid model format: unknown type: " + type); } } return in; } <|endoftext|>
<commit_before>/** * @file AspectRatio.hpp * @brief AspectRatio class prototype. * @author zer0 * @date 2018-07-10 */ #ifndef __INCLUDE_LIBTBAG__LIBTBAG_MATH_ASPECTRATIO_HPP__ #define __INCLUDE_LIBTBAG__LIBTBAG_MATH_ASPECTRATIO_HPP__ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <libtbag/config.h> #include <libtbag/predef.hpp> #include <libtbag/geometry/Size2.hpp> #include <libtbag/math/Euclidean.hpp> #include <utility> #include <type_traits> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace math { template <typename T> void calcAspectRatio(T a, T b, T & a_result, T & b_result) { auto const GCD = gcd(a, b); a_result = a / GCD; b_result = b / GCD; } template <typename T> std::pair<T, T> calcAspectRatio(T a, T b) { std::pair<T, T> result; calcAspectRatio(a, b, result.first, result.second); return result; } template <typename T, typename ScaleType = typename std::conditional<std::is_floating_point<T>::value, T, double>::type> libtbag::geometry::BaseSize2<T> scaleUpAspectRatio(libtbag::geometry::BaseSize2<T> const & src, libtbag::geometry::BaseSize2<T> const & scale_up) { auto const SCALE_X = scale_up.width / static_cast<ScaleType>(src.width); auto const SCALE_Y = scale_up.height / static_cast<ScaleType>(src.height); if (SCALE_X < SCALE_Y) { return libtbag::geometry::BaseSize2<T>(src.width * SCALE_X, src.height * SCALE_X); } else { return libtbag::geometry::BaseSize2<T>(src.width * SCALE_Y, src.height * SCALE_Y); } } } // namespace math // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- #endif // __INCLUDE_LIBTBAG__LIBTBAG_MATH_ASPECTRATIO_HPP__ <commit_msg>Create getSizeOfAspectRatio() method.<commit_after>/** * @file AspectRatio.hpp * @brief AspectRatio class prototype. * @author zer0 * @date 2018-07-10 */ #ifndef __INCLUDE_LIBTBAG__LIBTBAG_MATH_ASPECTRATIO_HPP__ #define __INCLUDE_LIBTBAG__LIBTBAG_MATH_ASPECTRATIO_HPP__ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <libtbag/config.h> #include <libtbag/predef.hpp> #include <libtbag/geometry/Size2.hpp> #include <libtbag/math/Euclidean.hpp> #include <cassert> #include <utility> #include <type_traits> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace math { template <typename T> void calcAspectRatio(T a, T b, T & a_result, T & b_result) { auto const GCD = gcd(a, b); assert(GCD != 0); a_result = a / GCD; b_result = b / GCD; } template <typename T> std::pair<T, T> calcAspectRatio(T a, T b) { std::pair<T, T> result; calcAspectRatio(a, b, result.first, result.second); return result; } template <typename T, typename ScaleType = typename std::conditional<std::is_floating_point<T>::value, T, double>::type> libtbag::geometry::BaseSize2<T> scaleUpAspectRatio(libtbag::geometry::BaseSize2<T> const & src, libtbag::geometry::BaseSize2<T> const & scale_up) { assert(static_cast<ScaleType>(src.width) != 0); assert(static_cast<ScaleType>(src.height) != 0); auto const SCALE_X = scale_up.width / static_cast<ScaleType>(src.width); auto const SCALE_Y = scale_up.height / static_cast<ScaleType>(src.height); if (SCALE_X < SCALE_Y) { return libtbag::geometry::BaseSize2<T>(src.width * SCALE_X, src.height * SCALE_X); } else { return libtbag::geometry::BaseSize2<T>(src.width * SCALE_Y, src.height * SCALE_Y); } } template <typename T> libtbag::geometry::BaseSize2<T> getSizeOfAspectRatio(T input_width, T input_height, T resize_width) { assert(input_width != 0); return libtbag::geometry::BaseSize2<T>(resize_width, (input_height * resize_width) / input_width); } template <typename T> libtbag::geometry::BaseSize2<T> getSizeOfAspectRatio(T input_width, T input_height, T resize_width, T minimum_height) { auto result = getSizeOfAspectRatio<T>(input_width, input_height, resize_width); if (minimum_height > 0 && result.height >= minimum_height) { assert(input_height != 0); result.width = ((input_width * minimum_height) / input_height); result.height = minimum_height; } return result; } } // namespace math // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- #endif // __INCLUDE_LIBTBAG__LIBTBAG_MATH_ASPECTRATIO_HPP__ <|endoftext|>
<commit_before>/* Copyright (c) 2013 Daniele Bartolini, Michele Rossi Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto 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 "json_parser.h" #include "json.h" #include "temp_allocator.h" #include "string_utils.h" #include "vector.h" #include "map.h" #include "vector2.h" #include "vector3.h" #include "vector4.h" #include "quaternion.h" #include "matrix4x4.h" #include "file.h" namespace crown { //-------------------------------------------------------------------------- JSONElement::JSONElement() : m_at(NULL) { } //-------------------------------------------------------------------------- JSONElement::JSONElement(const char* at) : m_at(at) { } //-------------------------------------------------------------------------- JSONElement::JSONElement(const JSONElement& other) : m_at(other.m_at) { } //-------------------------------------------------------------------------- JSONElement& JSONElement::operator=(const JSONElement& other) { // Our begin is the other's at m_at = other.m_at; return *this; } //-------------------------------------------------------------------------- JSONElement JSONElement::operator[](uint32_t i) { Array<const char*> array(default_allocator()); json::parse_array(m_at, array); CE_ASSERT(i < array::size(array), "Index out of bounds"); return JSONElement(array[i]); } //-------------------------------------------------------------------------- JSONElement JSONElement::index(uint32_t i) { return this->operator[](i); } //-------------------------------------------------------------------------- JSONElement JSONElement::index_or_nil(uint32_t i) { if (m_at != NULL) { Array<const char*> array(default_allocator()); json::parse_array(m_at, array); if (i >= array::size(array)) { return JSONElement(); } return JSONElement(array[i]); } return JSONElement(); } //-------------------------------------------------------------------------- JSONElement JSONElement::key(const char* k) { Map<DynamicString, const char*> object(default_allocator()); json::parse_object(m_at, object); const char* value = map::get(object, DynamicString(k), (const char*) NULL); CE_ASSERT(value != NULL, "Key not found: '%s'", k); return JSONElement(value); } //-------------------------------------------------------------------------- JSONElement JSONElement::key_or_nil(const char* k) { if (m_at != NULL) { Map<DynamicString, const char*> object(default_allocator()); json::parse_object(m_at, object); const char* value = map::get(object, DynamicString(k), (const char*) NULL); if (value) return JSONElement(value); } return JSONElement(); } //-------------------------------------------------------------------------- bool JSONElement::has_key(const char* k) const { Map<DynamicString, const char*> object(default_allocator()); json::parse_object(m_at, object); return map::has(object, DynamicString(k)); } //-------------------------------------------------------------------------- bool JSONElement::to_bool() const { return json::parse_bool(m_at); } //-------------------------------------------------------------------------- int32_t JSONElement::to_int() const { return json::parse_int(m_at); } //-------------------------------------------------------------------------- float JSONElement::to_float() const { return json::parse_float(m_at); } //-------------------------------------------------------------------------- void JSONElement::to_string(DynamicString& str) const { json::parse_string(m_at, str); } //-------------------------------------------------------------------------- Vector2 JSONElement::to_vector2() const { TempAllocator64 alloc; Array<const char*> array(alloc); json::parse_array(m_at, array); return Vector2(json::parse_float(array[0]), json::parse_float(array[1])); } //-------------------------------------------------------------------------- Vector3 JSONElement::to_vector3() const { TempAllocator64 alloc; Array<const char*> array(alloc); json::parse_array(m_at, array); return Vector3(json::parse_float(array[0]), json::parse_float(array[1]), json::parse_float(array[2])); } //-------------------------------------------------------------------------- Vector4 JSONElement::to_vector4() const { TempAllocator64 alloc; Array<const char*> array(alloc); json::parse_array(m_at, array); return Vector4(json::parse_float(array[0]), json::parse_float(array[1]), json::parse_float(array[2]), json::parse_float(array[3])); } //-------------------------------------------------------------------------- Quaternion JSONElement::to_quaternion() const { TempAllocator64 alloc; Array<const char*> array(alloc); json::parse_array(m_at, array); return Quaternion(json::parse_float(array[0]), json::parse_float(array[1]), json::parse_float(array[2]), json::parse_float(array[3])); } //-------------------------------------------------------------------------- Matrix4x4 JSONElement::to_matrix4x4() const { TempAllocator128 alloc; Array<float> array(alloc); to_array(array); return Matrix4x4(array::begin(array)); } //-------------------------------------------------------------------------- StringId32 JSONElement::to_string_id() const { TempAllocator1024 alloc; DynamicString str(alloc); json::parse_string(m_at, str); return str.to_string_id(); } //-------------------------------------------------------------------------- ResourceId JSONElement::to_resource_id(const char* type) const { CE_ASSERT_NOT_NULL(type); TempAllocator1024 alloc; DynamicString str(alloc); json::parse_string(m_at, str); return ResourceId(type, str.c_str()); } //-------------------------------------------------------------------------- void JSONElement::to_array(Array<bool>& array) const { Array<const char*> temp(default_allocator()); json::parse_array(m_at, temp); for (uint32_t i = 0; i < array::size(temp); i++) { array::push_back(array, json::parse_bool(temp[i])); } } //-------------------------------------------------------------------------- void JSONElement::to_array(Array<int16_t>& array) const { Array<const char*> temp(default_allocator()); json::parse_array(m_at, temp); for (uint32_t i = 0; i < array::size(temp); i++) { array::push_back(array, (int16_t)json::parse_int(temp[i])); } } //-------------------------------------------------------------------------- void JSONElement::to_array(Array<uint16_t>& array) const { Array<const char*> temp(default_allocator()); json::parse_array(m_at, temp); for (uint32_t i = 0; i < array::size(temp); i++) { array::push_back(array, (uint16_t)json::parse_int(temp[i])); } } //-------------------------------------------------------------------------- void JSONElement::to_array(Array<int32_t>& array) const { Array<const char*> temp(default_allocator()); json::parse_array(m_at, temp); for (uint32_t i = 0; i < array::size(temp); i++) { array::push_back(array, (int32_t)json::parse_int(temp[i])); } } //-------------------------------------------------------------------------- void JSONElement::to_array(Array<uint32_t>& array) const { Array<const char*> temp(default_allocator()); json::parse_array(m_at, temp); for (uint32_t i = 0; i < array::size(temp); i++) { array::push_back(array, (uint32_t)json::parse_int(temp[i])); } } //-------------------------------------------------------------------------- void JSONElement::to_array(Array<float>& array) const { Array<const char*> temp(default_allocator()); json::parse_array(m_at, temp); for (uint32_t i = 0; i < array::size(temp); i++) { array::push_back(array, json::parse_float(temp[i])); } } //-------------------------------------------------------------------------- void JSONElement::to_array(Vector<DynamicString>& array) const { Array<const char*> temp(default_allocator()); json::parse_array(m_at, temp); for (uint32_t i = 0; i < array::size(temp); i++) { DynamicString str; json::parse_string(temp[i], str); vector::push_back(array, str); } } //-------------------------------------------------------------------------- void JSONElement::to_keys(Vector<DynamicString>& keys) const { Map<DynamicString, const char*> object(default_allocator()); json::parse_object(m_at, object); const Map<DynamicString, const char*>::Node* it = map::begin(object); while (it != map::end(object)) { vector::push_back(keys, (*it).key); it++; } } //-------------------------------------------------------------------------- bool JSONElement::is_nil() const { if (m_at != NULL) { return json::type(m_at) == JSONType::NIL; } return true; } //-------------------------------------------------------------------------- bool JSONElement::is_bool() const { if (m_at != NULL) { return json::type(m_at) == JSONType::BOOL; } return false; } //-------------------------------------------------------------------------- bool JSONElement::is_number() const { if (m_at != NULL) { return json::type(m_at) == JSONType::NUMBER; } return false; } //-------------------------------------------------------------------------- bool JSONElement::is_string() const { if (m_at != NULL) { return json::type(m_at) == JSONType::STRING; } return false; } //-------------------------------------------------------------------------- bool JSONElement::is_array() const { if (m_at != NULL) { return json::type(m_at) == JSONType::ARRAY; } return false; } //-------------------------------------------------------------------------- bool JSONElement::is_object() const { if (m_at != NULL) { return json::type(m_at) == JSONType::OBJECT; } return false; } //-------------------------------------------------------------------------- uint32_t JSONElement::size() const { if (m_at == NULL) { return 0; } switch(json::type(m_at)) { case JSONType::NIL: { return 1; } case JSONType::OBJECT: { Map<DynamicString, const char*> object(default_allocator()); json::parse_object(m_at, object); return map::size(object); } case JSONType::ARRAY: { Array<const char*> array(default_allocator()); json::parse_array(m_at, array); return array::size(array); } case JSONType::STRING: { DynamicString string; json::parse_string(m_at, string); return string.length(); } case JSONType::NUMBER: { return 1; } case JSONType::BOOL: { return 1; } default: { CE_FATAL("Oops, unknown value type"); return 0; } } } //-------------------------------------------------------------------------- JSONParser::JSONParser(const char* s) : m_file(false) , m_document(s) { CE_ASSERT_NOT_NULL(s); } //-------------------------------------------------------------------------- JSONParser::JSONParser(File& f) : m_file(true) , m_document(NULL) { const size_t size = f.size(); char* doc = (char*) default_allocator().allocate(size); f.read(doc, size); m_document = doc; } //-------------------------------------------------------------------------- JSONParser::~JSONParser() { if (m_file) { default_allocator().deallocate((void*) m_document); } } //-------------------------------------------------------------------------- JSONElement JSONParser::root() { const char* ch = m_document; while ((*ch) && (*ch) <= ' ') ch++; return JSONElement(ch); } } //namespace crown <commit_msg>Workaround android crash<commit_after>/* Copyright (c) 2013 Daniele Bartolini, Michele Rossi Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto 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 "json_parser.h" #include "json.h" #include "temp_allocator.h" #include "string_utils.h" #include "vector.h" #include "map.h" #include "vector2.h" #include "vector3.h" #include "vector4.h" #include "quaternion.h" #include "matrix4x4.h" #include "file.h" namespace crown { //-------------------------------------------------------------------------- JSONElement::JSONElement() : m_at(NULL) { } //-------------------------------------------------------------------------- JSONElement::JSONElement(const char* at) : m_at(at) { } //-------------------------------------------------------------------------- JSONElement::JSONElement(const JSONElement& other) : m_at(other.m_at) { } //-------------------------------------------------------------------------- JSONElement& JSONElement::operator=(const JSONElement& other) { // Our begin is the other's at m_at = other.m_at; return *this; } //-------------------------------------------------------------------------- JSONElement JSONElement::operator[](uint32_t i) { Array<const char*> array(default_allocator()); json::parse_array(m_at, array); CE_ASSERT(i < array::size(array), "Index out of bounds"); return JSONElement(array[i]); } //-------------------------------------------------------------------------- JSONElement JSONElement::index(uint32_t i) { return this->operator[](i); } //-------------------------------------------------------------------------- JSONElement JSONElement::index_or_nil(uint32_t i) { if (m_at != NULL) { Array<const char*> array(default_allocator()); json::parse_array(m_at, array); if (i >= array::size(array)) { return JSONElement(); } return JSONElement(array[i]); } return JSONElement(); } //-------------------------------------------------------------------------- JSONElement JSONElement::key(const char* k) { Map<DynamicString, const char*> object(default_allocator()); json::parse_object(m_at, object); const char* value = map::get(object, DynamicString(k), (const char*) NULL); CE_ASSERT(value != NULL, "Key not found: '%s'", k); return JSONElement(value); } //-------------------------------------------------------------------------- JSONElement JSONElement::key_or_nil(const char* k) { if (m_at != NULL) { Map<DynamicString, const char*> object(default_allocator()); json::parse_object(m_at, object); const char* value = map::get(object, DynamicString(k), (const char*) NULL); if (value) return JSONElement(value); } return JSONElement(); } //-------------------------------------------------------------------------- bool JSONElement::has_key(const char* k) const { Map<DynamicString, const char*> object(default_allocator()); json::parse_object(m_at, object); return map::has(object, DynamicString(k)); } //-------------------------------------------------------------------------- bool JSONElement::to_bool() const { return json::parse_bool(m_at); } //-------------------------------------------------------------------------- int32_t JSONElement::to_int() const { return json::parse_int(m_at); } //-------------------------------------------------------------------------- float JSONElement::to_float() const { return json::parse_float(m_at); } //-------------------------------------------------------------------------- void JSONElement::to_string(DynamicString& str) const { json::parse_string(m_at, str); } //-------------------------------------------------------------------------- Vector2 JSONElement::to_vector2() const { TempAllocator64 alloc; Array<const char*> array(alloc); json::parse_array(m_at, array); return Vector2(json::parse_float(array[0]), json::parse_float(array[1])); } //-------------------------------------------------------------------------- Vector3 JSONElement::to_vector3() const { TempAllocator64 alloc; Array<const char*> array(alloc); json::parse_array(m_at, array); return Vector3(json::parse_float(array[0]), json::parse_float(array[1]), json::parse_float(array[2])); } //-------------------------------------------------------------------------- Vector4 JSONElement::to_vector4() const { TempAllocator64 alloc; Array<const char*> array(alloc); json::parse_array(m_at, array); return Vector4(json::parse_float(array[0]), json::parse_float(array[1]), json::parse_float(array[2]), json::parse_float(array[3])); } //-------------------------------------------------------------------------- Quaternion JSONElement::to_quaternion() const { TempAllocator64 alloc; Array<const char*> array(alloc); json::parse_array(m_at, array); return Quaternion(json::parse_float(array[0]), json::parse_float(array[1]), json::parse_float(array[2]), json::parse_float(array[3])); } //-------------------------------------------------------------------------- Matrix4x4 JSONElement::to_matrix4x4() const { TempAllocator128 alloc; Array<float> array(alloc); to_array(array); return Matrix4x4(array::begin(array)); } //-------------------------------------------------------------------------- StringId32 JSONElement::to_string_id() const { TempAllocator1024 alloc; DynamicString str(alloc); json::parse_string(m_at, str); return str.to_string_id(); } //-------------------------------------------------------------------------- ResourceId JSONElement::to_resource_id(const char* type) const { CE_ASSERT_NOT_NULL(type); // TempAllocator1024 alloc; DynamicString str(default_allocator()); json::parse_string(m_at, str); return ResourceId(type, str.c_str()); } //-------------------------------------------------------------------------- void JSONElement::to_array(Array<bool>& array) const { Array<const char*> temp(default_allocator()); json::parse_array(m_at, temp); for (uint32_t i = 0; i < array::size(temp); i++) { array::push_back(array, json::parse_bool(temp[i])); } } //-------------------------------------------------------------------------- void JSONElement::to_array(Array<int16_t>& array) const { Array<const char*> temp(default_allocator()); json::parse_array(m_at, temp); for (uint32_t i = 0; i < array::size(temp); i++) { array::push_back(array, (int16_t)json::parse_int(temp[i])); } } //-------------------------------------------------------------------------- void JSONElement::to_array(Array<uint16_t>& array) const { Array<const char*> temp(default_allocator()); json::parse_array(m_at, temp); for (uint32_t i = 0; i < array::size(temp); i++) { array::push_back(array, (uint16_t)json::parse_int(temp[i])); } } //-------------------------------------------------------------------------- void JSONElement::to_array(Array<int32_t>& array) const { Array<const char*> temp(default_allocator()); json::parse_array(m_at, temp); for (uint32_t i = 0; i < array::size(temp); i++) { array::push_back(array, (int32_t)json::parse_int(temp[i])); } } //-------------------------------------------------------------------------- void JSONElement::to_array(Array<uint32_t>& array) const { Array<const char*> temp(default_allocator()); json::parse_array(m_at, temp); for (uint32_t i = 0; i < array::size(temp); i++) { array::push_back(array, (uint32_t)json::parse_int(temp[i])); } } //-------------------------------------------------------------------------- void JSONElement::to_array(Array<float>& array) const { Array<const char*> temp(default_allocator()); json::parse_array(m_at, temp); for (uint32_t i = 0; i < array::size(temp); i++) { array::push_back(array, json::parse_float(temp[i])); } } //-------------------------------------------------------------------------- void JSONElement::to_array(Vector<DynamicString>& array) const { Array<const char*> temp(default_allocator()); json::parse_array(m_at, temp); for (uint32_t i = 0; i < array::size(temp); i++) { DynamicString str; json::parse_string(temp[i], str); vector::push_back(array, str); } } //-------------------------------------------------------------------------- void JSONElement::to_keys(Vector<DynamicString>& keys) const { Map<DynamicString, const char*> object(default_allocator()); json::parse_object(m_at, object); const Map<DynamicString, const char*>::Node* it = map::begin(object); while (it != map::end(object)) { vector::push_back(keys, (*it).key); it++; } } //-------------------------------------------------------------------------- bool JSONElement::is_nil() const { if (m_at != NULL) { return json::type(m_at) == JSONType::NIL; } return true; } //-------------------------------------------------------------------------- bool JSONElement::is_bool() const { if (m_at != NULL) { return json::type(m_at) == JSONType::BOOL; } return false; } //-------------------------------------------------------------------------- bool JSONElement::is_number() const { if (m_at != NULL) { return json::type(m_at) == JSONType::NUMBER; } return false; } //-------------------------------------------------------------------------- bool JSONElement::is_string() const { if (m_at != NULL) { return json::type(m_at) == JSONType::STRING; } return false; } //-------------------------------------------------------------------------- bool JSONElement::is_array() const { if (m_at != NULL) { return json::type(m_at) == JSONType::ARRAY; } return false; } //-------------------------------------------------------------------------- bool JSONElement::is_object() const { if (m_at != NULL) { return json::type(m_at) == JSONType::OBJECT; } return false; } //-------------------------------------------------------------------------- uint32_t JSONElement::size() const { if (m_at == NULL) { return 0; } switch(json::type(m_at)) { case JSONType::NIL: { return 1; } case JSONType::OBJECT: { Map<DynamicString, const char*> object(default_allocator()); json::parse_object(m_at, object); return map::size(object); } case JSONType::ARRAY: { Array<const char*> array(default_allocator()); json::parse_array(m_at, array); return array::size(array); } case JSONType::STRING: { DynamicString string; json::parse_string(m_at, string); return string.length(); } case JSONType::NUMBER: { return 1; } case JSONType::BOOL: { return 1; } default: { CE_FATAL("Oops, unknown value type"); return 0; } } } //-------------------------------------------------------------------------- JSONParser::JSONParser(const char* s) : m_file(false) , m_document(s) { CE_ASSERT_NOT_NULL(s); } //-------------------------------------------------------------------------- JSONParser::JSONParser(File& f) : m_file(true) , m_document(NULL) { const size_t size = f.size(); char* doc = (char*) default_allocator().allocate(size); f.read(doc, size); m_document = doc; } //-------------------------------------------------------------------------- JSONParser::~JSONParser() { if (m_file) { default_allocator().deallocate((void*) m_document); } } //-------------------------------------------------------------------------- JSONElement JSONParser::root() { const char* ch = m_document; while ((*ch) && (*ch) <= ' ') ch++; return JSONElement(ch); } } //namespace crown <|endoftext|>
<commit_before> #include <mutex> #include <cassert> #include <cstring> #include <sys/stat.h> #include <list> #include <unistd.h> #include "global.h" #include "partition_db.h" std::string GetPartitionDBFilename(partition_t p) { return g_db_files_dirname + "/" + std::to_string(p) + ".db"; } static int createTableCallback(void *NotUsed, int argc, char **argv, char **azColName){ printf("Callback called: create table\n"); int i; char const * value; for(i=0; i<argc; i++) { if (argv[i]) { value = argv[i]; } else { value = "NULL"; } printf("%s = %s\n", azColName[i], value); } printf("\n"); return 0; } PartitionDB::PartitionDB(const std::string &dbName) { filename = dbName; fprintf(stderr, "Open database: %s\n", filename.c_str()); if (sqlite3_open(filename.c_str(), &db)) { fprintf(stderr, "%s\n", sqlite3_errmsg(db)); perror("Can't open database!"); exit(1); } fprintf(stderr, "Opened database successfully\n"); char *sql = "CREATE TABLE IF NOT EXISTS stored_values( " \ "row_id INT PRIMARY KEY," \ "device_id INT NOT NULL," \ "timestamp INT NOT NULL," \ "expiration INT NOT NULL," \ "data BLOB NOT NULL );"; char *errMsg = NULL; if(sqlite3_exec(db, sql, createTableCallback, 0, &errMsg) != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", errMsg); sqlite3_free(errMsg); perror("Table not found and can't create it!"); exit(1); } } PartitionDB::~PartitionDB() { sqlite3_close(db); } static bool compareBuffer(char *buf1, char *buf2, size_t len) { for (int i = 0; i < len; i++) { if (buf1[i] != buf2[i]) return false; } return true; } bool PartitionDB::put(device_t device_id, time_t timestamp, time_t expiration, void *data, size_t datalen) { assert(datalen < kMaxDataLen); int result; sqlite3_stmt *stmt; char sql[256]; int sql_len; std::lock_guard<std::mutex> lg(db_lock); sql_len = sprintf(sql, "SELECT * FROM stored_values WHERE (device_id = %d AND timestamp = %ld);", device_id, timestamp); stmt = NULL; result = sqlite3_prepare_v2(db, sql, sql_len, &stmt, NULL); if (result != SQLITE_OK) { return false; } /* * TODO : Duplicate handling not fully implemented */ while (true) { result = sqlite3_step(stmt); if (result == SQLITE_DONE) { break; } else if (result == SQLITE_ROW) { time_t row_expiration = sqlite3_column_int(stmt, 3); size_t row_data_size = sqlite3_column_bytes(stmt, 4); if (row_data_size != datalen) { sqlite3_finalize(stmt); return false; } void const *row_data = sqlite3_column_blob(stmt, 4); assert(row_data); if (!compareBuffer) { sqlite3_finalize(stmt); return false; } sqlite3_finalize(stmt); return true; } else if (result == SQLITE_BUSY) { usleep(1000); } else { sqlite3_finalize(stmt); return false; } } sqlite3_finalize(stmt); stmt = NULL; sql_len = sprintf(sql, "INSERT INTO stored_values VALUES(NULL, %d, %ld, %ld, ?);", device_id, timestamp, expiration); result = sqlite3_prepare_v2(db, sql, sql_len, &stmt, NULL); if (result != SQLITE_OK) { return false; } result = sqlite3_bind_blob(stmt, 1, data, datalen, SQLITE_STATIC); if (result != SQLITE_OK) { sqlite3_finalize(stmt); return false; } result = sqlite3_step(stmt); bool success = (result == SQLITE_DONE); sqlite3_finalize(stmt); return success; } std::list<Data> * PartitionDB::get(device_t device_id, time_t min_timestamp, time_t max_timestamp) { char sql[256]; int sql_len; int result; sqlite3_stmt *stmt; std::list<Data> *ret = new std::list<Data>(); std::lock_guard<std::mutex> lg(db_lock); sql_len = sprintf(sql, "SELECT * FROM stored_values " \ "WHERE (device_id = %d AND timestamp BETWEEN %ld AND %ld) " \ "ORDER BY timestamp ASC;", device_id, min_timestamp, max_timestamp); result = sqlite3_prepare_v2(db, sql, sql_len, &stmt, NULL); if (result != SQLITE_OK) { sqlite3_finalize(stmt); return nullptr; // TODO Throw exception or return empty list? } while (true) { result = sqlite3_step(stmt); if (result == SQLITE_DONE) { break; } else if (result == SQLITE_ROW) { time_t timestamp = sqlite3_column_int(stmt, 2); time_t expiration = sqlite3_column_int(stmt, 3); size_t data_size = sqlite3_column_bytes(stmt, 4); assert(data_size < kMaxDataLen); void const *data = sqlite3_column_blob(stmt, 4); Data d; d.timestamp = timestamp; d.expiration = expiration; d.datalen = data_size; memcpy(&d.data, data, data_size); ret->push_back(d); } else if (result == SQLITE_BUSY) { usleep(1000); } else { sqlite3_finalize(stmt); throw "sqlite db error"; } } sqlite3_finalize(stmt); return ret; } bool PartitionDB::remove(time_t timestamp) { char sql[256]; int sql_len; int result; sqlite3_stmt *stmt; std::lock_guard<std::mutex> lg(db_lock); sql_len = sprintf(sql, "DELETE FROM stored_values WHERE (timestamp < %ld);", timestamp); result = sqlite3_prepare_v2(db, sql, sql_len, &stmt, NULL); if (result != SQLITE_OK) { sqlite3_finalize(stmt); return false; } result = sqlite3_step(stmt); bool success = (result == SQLITE_DONE); sqlite3_finalize(stmt); return success; } std::list<device_t> * PartitionDB::getDevices(void) { int result; sqlite3_stmt *stmt; std::list<device_t> *ret = new std::list<device_t>; std::lock_guard<std::mutex> lg(db_lock); result = sqlite3_prepare_v2(db, "SELECT DISTINCT device_id FROM stored_values;", -1, &stmt, NULL); if (result != SQLITE_OK) { sqlite3_finalize(stmt); return nullptr; // TODO Empty list or throw exception? } while (true) { result = sqlite3_step(stmt); if (result == SQLITE_DONE) { break; } else if (result == SQLITE_ROW) { device_t d = sqlite3_column_int(stmt, 0); ret->push_back(d); } else if (result == SQLITE_BUSY) { usleep(1000); } else { sqlite3_finalize(stmt); throw "sqlite db error"; } } sqlite3_finalize(stmt); return ret; } long long PartitionDB::size(void) { struct stat sb; if (lstat(filename.c_str(), &sb) != 0) { fprintf(stderr, "failed to stat file %s\n", filename.c_str()); throw "can't stat db file"; } return sb.st_size; } <commit_msg>initialization works, changed db file extension to .sqllite<commit_after> #include <mutex> #include <cassert> #include <cstring> #include <sys/stat.h> #include <list> #include <unistd.h> #include "global.h" #include "partition_db.h" std::string GetPartitionDBFilename(partition_t p) { return g_db_files_dirname + "/" + std::to_string(p) + ".sqllite"; } static int createTableCallback(void *NotUsed, int argc, char **argv, char **azColName){ printf("Callback called: create table\n"); int i; char const * value; for(i=0; i<argc; i++) { if (argv[i]) { value = argv[i]; } else { value = "NULL"; } printf("%s = %s\n", azColName[i], value); } printf("\n"); return 0; } PartitionDB::PartitionDB(const std::string &dbName) { filename = dbName; fprintf(stderr, "Open database: %s\n", filename.c_str()); if (sqlite3_open(filename.c_str(), &db) != SQLITE_OK) { fprintf(stderr, "%s\n", sqlite3_errmsg(db)); perror("Can't open database!"); exit(1); } fprintf(stderr, "Opened database successfully\n"); char *sql = "CREATE TABLE IF NOT EXISTS stored_values( " \ "row_id INT PRIMARY KEY," \ "device_id INT NOT NULL," \ "timestamp INT NOT NULL," \ "expiration INT NOT NULL," \ "data BLOB NOT NULL );"; char *errMsg = NULL; if(sqlite3_exec(db, sql, createTableCallback, 0, &errMsg) != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", errMsg); sqlite3_free(errMsg); perror("Table not found and can't create it!"); exit(1); } } PartitionDB::~PartitionDB() { sqlite3_close(db); } static bool compareBuffer(char *buf1, char *buf2, size_t len) { for (int i = 0; i < len; i++) { if (buf1[i] != buf2[i]) return false; } return true; } bool PartitionDB::put(device_t device_id, time_t timestamp, time_t expiration, void *data, size_t datalen) { assert(datalen < kMaxDataLen); int result; sqlite3_stmt *stmt; char sql[256]; int sql_len; std::lock_guard<std::mutex> lg(db_lock); sql_len = sprintf(sql, "SELECT * FROM stored_values WHERE (device_id = %d AND timestamp = %ld);", device_id, timestamp); stmt = NULL; result = sqlite3_prepare_v2(db, sql, sql_len, &stmt, NULL); if (result != SQLITE_OK) { return false; } /* * TODO : Duplicate handling not fully implemented */ while (true) { result = sqlite3_step(stmt); if (result == SQLITE_DONE) { break; } else if (result == SQLITE_ROW) { time_t row_expiration = sqlite3_column_int(stmt, 3); size_t row_data_size = sqlite3_column_bytes(stmt, 4); if (row_data_size != datalen) { sqlite3_finalize(stmt); return false; } void const *row_data = sqlite3_column_blob(stmt, 4); assert(row_data); if (!compareBuffer) { sqlite3_finalize(stmt); return false; } sqlite3_finalize(stmt); return true; } else if (result == SQLITE_BUSY) { usleep(1000); } else { sqlite3_finalize(stmt); return false; } } sqlite3_finalize(stmt); stmt = NULL; sql_len = sprintf(sql, "INSERT INTO stored_values VALUES(NULL, %d, %ld, %ld, ?);", device_id, timestamp, expiration); result = sqlite3_prepare_v2(db, sql, sql_len, &stmt, NULL); if (result != SQLITE_OK) { return false; } result = sqlite3_bind_blob(stmt, 1, data, datalen, SQLITE_STATIC); if (result != SQLITE_OK) { sqlite3_finalize(stmt); return false; } result = sqlite3_step(stmt); bool success = (result == SQLITE_DONE); sqlite3_finalize(stmt); return success; } std::list<Data> * PartitionDB::get(device_t device_id, time_t min_timestamp, time_t max_timestamp) { char sql[256]; int sql_len; int result; sqlite3_stmt *stmt; std::list<Data> *ret = new std::list<Data>(); std::lock_guard<std::mutex> lg(db_lock); sql_len = sprintf(sql, "SELECT * FROM stored_values " \ "WHERE (device_id = %d AND timestamp BETWEEN %ld AND %ld) " \ "ORDER BY timestamp ASC;", device_id, min_timestamp, max_timestamp); result = sqlite3_prepare_v2(db, sql, sql_len, &stmt, NULL); if (result != SQLITE_OK) { sqlite3_finalize(stmt); return nullptr; // TODO Throw exception or return empty list? } while (true) { result = sqlite3_step(stmt); if (result == SQLITE_DONE) { break; } else if (result == SQLITE_ROW) { time_t timestamp = sqlite3_column_int(stmt, 2); time_t expiration = sqlite3_column_int(stmt, 3); size_t data_size = sqlite3_column_bytes(stmt, 4); assert(data_size < kMaxDataLen); void const *data = sqlite3_column_blob(stmt, 4); Data d; d.timestamp = timestamp; d.expiration = expiration; d.datalen = data_size; memcpy(&d.data, data, data_size); ret->push_back(d); } else if (result == SQLITE_BUSY) { usleep(1000); } else { sqlite3_finalize(stmt); throw "sqlite db error"; } } sqlite3_finalize(stmt); return ret; } bool PartitionDB::remove(time_t timestamp) { char sql[256]; int sql_len; int result; sqlite3_stmt *stmt; std::lock_guard<std::mutex> lg(db_lock); sql_len = sprintf(sql, "DELETE FROM stored_values WHERE (timestamp < %ld);", timestamp); result = sqlite3_prepare_v2(db, sql, sql_len, &stmt, NULL); if (result != SQLITE_OK) { sqlite3_finalize(stmt); return false; } result = sqlite3_step(stmt); bool success = (result == SQLITE_DONE); sqlite3_finalize(stmt); return success; } std::list<device_t> * PartitionDB::getDevices(void) { int result; sqlite3_stmt *stmt; std::list<device_t> *ret = new std::list<device_t>; std::lock_guard<std::mutex> lg(db_lock); result = sqlite3_prepare_v2(db, "SELECT DISTINCT device_id FROM stored_values;", -1, &stmt, NULL); if (result != SQLITE_OK) { sqlite3_finalize(stmt); return nullptr; // TODO Empty list or throw exception? } while (true) { result = sqlite3_step(stmt); if (result == SQLITE_DONE) { break; } else if (result == SQLITE_ROW) { device_t d = sqlite3_column_int(stmt, 0); ret->push_back(d); } else if (result == SQLITE_BUSY) { usleep(1000); } else { sqlite3_finalize(stmt); throw "sqlite db error"; } } sqlite3_finalize(stmt); return ret; } long long PartitionDB::size(void) { struct stat sb; if (lstat(filename.c_str(), &sb) != 0) { fprintf(stderr, "failed to stat file %s\n", filename.c_str()); throw "can't stat db file"; } return sb.st_size; } <|endoftext|>
<commit_before>#include <iostream> #include <map> #include <memory> #include <vector> #include <utility> #include <rematch/compile.h> #include <rematch/execute.h> #include <rematch/rematch.h> #include "db_setup.h" #include "../Rule.h" using std::cout; using std::cerr; using std::endl; using std::string; using std::vector; using regexbench::Rule; static void usage() { cerr << "arguments too few" << endl; cerr << "command line should look like :" << endl; cerr << "$ pcre_checker {db_file}" << endl; } int main(int argc, char **argv) { if (argc < 2) { usage(); return -1; } string dbFile(argv[1]); cout << "db file " << dbFile << endl; try { dbFile = "database=" + dbFile; PcreCheckDb db("sqlite3", dbFile); // db.verbose = true; // turn on when debugging if (db.needsUpgrade()) // TODO : revisit!! db.upgrade(); db.begin(); vector<Rule> rules; // to be used for engine eval vector<DbRule> dbRules = select<DbRule>(db).orderBy(DbRule::Id).all(); for (const auto &dbRule : dbRules) { auto blob = dbRule.content.value(); size_t len = blob.length(); auto temp = std::make_unique<char[]>(len); blob.getData(reinterpret_cast<unsigned char*>(temp.get()), len, 0); std::string line(temp.get(), len); rules.emplace_back(Rule(line, static_cast<size_t>(dbRule.id.value()))); } // for debugging for (const auto &r : rules) { cout << "rule " << r.getID() << ": " << r.getRegexp() << endl; } int engineId; int resMatchId = select<Result>(db, Result::Name == "match").one().id.value(); int resNomatchId = select<Result>(db, Result::Name == "nomatch").one().id.value(); int resErrorId = select<Result>(db, Result::Name == "error").one().id.value(); // rematch test first (TODO) engineId = select<Engine>(db, Engine::Name == "rematch").one().id.value(); rematch2_t* matcher; rematch_match_context_t* context; vector<const char*> rematchExps; vector<unsigned> rematchMods; vector<unsigned> rematchIds; for (const auto& rule : rules) { rematchExps.push_back(rule.getRegexp().data()); rematchIds.push_back(static_cast<unsigned>(rule.getID())); uint32_t opt = 0; if (rule.isSet(regexbench::MOD_CASELESS)) opt |= REMATCH_MOD_CASELESS; if (rule.isSet(regexbench::MOD_MULTILINE)) opt |= REMATCH_MOD_MULTILINE; if (rule.isSet(regexbench::MOD_DOTALL)) opt |= REMATCH_MOD_DOTALL; rematchMods.push_back(opt); } matcher = rematch2_compile(rematchIds.data(), rematchExps.data(), rematchMods.data(), rematchIds.size(), true /* reduce */); if (!matcher) throw std::runtime_error("Could not build REmatch2 matcher."); context = rematch2ContextInit(matcher, 10); // nmatch = 10 (TODO) if (context == nullptr) throw std::runtime_error("Could not initialize context."); // prepare data (only need the data specified in Test table) int lastPid = -1; vector<Test> tests = select<Test>(db).orderBy(Test::Patternid).all(); for (const auto &t : tests) { if (t.patternid.value() == lastPid) continue; lastPid = t.patternid.value(); // we can get excption below // (which should not happen with a db correctly set up) const auto& pattern = select<Pattern>(db, Pattern::Id == lastPid).one(); auto blob = pattern.content.value(); size_t len = blob.length(); auto temp = std::make_unique<char[]>(len); blob.getData(reinterpret_cast<unsigned char*>(temp.get()), len, 0); // for debugging //cout << "pattern " << lastPid << " content : " << string(temp.get(), len) // << endl; // set up Rule-id to (Test-id, result) mapping to be used for TestResult update std::map<int, std::pair<int, bool>> rule2TestMap; auto curTest = select<Test>(db, Test::Patternid == lastPid).cursor(); for (; curTest.rowsLeft(); curTest++) { rule2TestMap[(*curTest).ruleid.value()] = std::make_pair((*curTest).id.value(), false); } // do match int ret = rematch2_exec(matcher, temp.get(), len, context); if (ret == MREG_FINISHED) { // this means we need to adjust 'nmatch' // parameter used for rematch2ContextInit cerr << "rematch2 returned MREG_FINISHED" << endl; } if (context->num_matches > 0) { // match // for debugging //cout << "pattern " << lastPid; //cout << " matched rules :" << endl; for (size_t i = 0; i < context->num_matches; ++i) { // for debugging //cout << " " << context->matchlist[i].fid; stateid_t mid = context->matchlist[i].fid; if (rule2TestMap.count(static_cast<int>(mid)) > 0) rule2TestMap[mid].second = true; } //cout << endl; } else { // nomatch cout << "pattern " << lastPid << " has no match" << endl; } rematch2ContextClear(context, true); // for debugging //cout << "Matched rule and test id for pattern id " << lastPid << endl; //for (const auto& p : rule2TestMap) { // cout << " rule id " << p.first << " test id " << p.second.first // << " matched? " << p.second.second << endl; //} for (const auto& p : rule2TestMap) { try { auto cur = select<TestResult>(db, TestResult::Testid == p.second.first && TestResult::Engineid == engineId) .cursor(); (*cur).resultid = (p.second.second ? resMatchId : resNomatchId); (*cur).update(); } catch (NotFound) { TestResult res(db); res.testid = p.second.first; res.engineid = engineId; res.resultid = (p.second.second ? resMatchId : resNomatchId); res.update(); } } } // for loop for Test table entries // clean-up of REmatch related objects rematch2ContextFree(context); rematch2Free(matcher); db.commit(); // commit changes (mostly about result) } catch (const std::exception &e) { cerr << e.what() << endl; return -1; } catch (Except& e) { // litesql exception cerr << e << endl; return -1; } return 0; } <commit_msg>Add support for hyperscan check<commit_after>#include <iostream> #include <map> #include <memory> #include <vector> #include <utility> #include <rematch/compile.h> #include <rematch/execute.h> #include <rematch/rematch.h> #include <hs/hs_compile.h> #include <hs/hs_runtime.h> #include "db_setup.h" #include "../Rule.h" using std::cout; using std::cerr; using std::endl; using std::string; using std::vector; using regexbench::Rule; static void usage() { cerr << "arguments too few" << endl; cerr << "command line should look like :" << endl; cerr << "$ pcre_checker {db_file}" << endl; } struct AuxInfo { int resMatchId; int resNomatchId; int resErrorId; std::map<string, int> str2EngineId; uint32_t nmatch; // this is rematch only parameter vector<Rule> rules; }; static void checkRematch(PcreCheckDb& db, const struct AuxInfo& aux); static void checkHyperscan(PcreCheckDb& db, struct AuxInfo& aux); //static void checkPcre(PcreCheckDb& db, struct AuxInfo& aux); int main(int argc, char **argv) { if (argc < 2) { usage(); return -1; } string dbFile(argv[1]); try { dbFile = "database=" + dbFile; PcreCheckDb db("sqlite3", dbFile); // db.verbose = true; // turn on when debugging if (db.needsUpgrade()) // TODO : revisit!! db.upgrade(); db.begin(); AuxInfo aux; aux.resMatchId = select<Result>(db, Result::Name == "match").one().id.value(); aux.resNomatchId = select<Result>(db, Result::Name == "nomatch").one().id.value(); aux.resErrorId = select<Result>(db, Result::Name == "error").one().id.value(); aux.str2EngineId["rematch"] = select<Engine>(db, Engine::Name == "rematch").one().id.value(); aux.str2EngineId["hyperscan"] = select<Engine>(db, Engine::Name == "hyperscan").one().id.value(); aux.str2EngineId["pcre"] = select<Engine>(db, Engine::Name == "pcre").one().id.value(); aux.nmatch = 10; // TODO auto& rules = aux.rules; vector<DbRule> dbRules = select<DbRule>(db).orderBy(DbRule::Id).all(); for (const auto &dbRule : dbRules) { auto blob = dbRule.content.value(); size_t len = blob.length(); auto temp = std::make_unique<char[]>(len); blob.getData(reinterpret_cast<unsigned char*>(temp.get()), len, 0); std::string line(temp.get(), len); rules.emplace_back(Rule(line, static_cast<size_t>(dbRule.id.value()))); } // for debugging //for (const auto &r : rules) { // cout << "rule " << r.getID() << ": " << r.getRegexp() << endl; //} checkRematch(db, aux); checkHyperscan(db, aux); db.commit(); // commit changes (mostly about result) } catch (const std::exception &e) { cerr << e.what() << endl; return -1; } catch (Except& e) { // litesql exception cerr << e << endl; return -1; } return 0; } void checkRematch(PcreCheckDb& db, const struct AuxInfo& aux) { int engineId = aux.str2EngineId.at("rematch"); int resMatchId = aux.resMatchId; int resNomatchId = aux.resNomatchId; const auto& rules = aux.rules; rematch2_t* matcher; rematch_match_context_t* context; vector<const char*> rematchExps; vector<unsigned> rematchMods; vector<unsigned> rematchIds; for (const auto& rule : rules) { rematchExps.push_back(rule.getRegexp().data()); rematchIds.push_back(static_cast<unsigned>(rule.getID())); uint32_t opt = 0; if (rule.isSet(regexbench::MOD_CASELESS)) opt |= REMATCH_MOD_CASELESS; if (rule.isSet(regexbench::MOD_MULTILINE)) opt |= REMATCH_MOD_MULTILINE; if (rule.isSet(regexbench::MOD_DOTALL)) opt |= REMATCH_MOD_DOTALL; rematchMods.push_back(opt); } matcher = rematch2_compile(rematchIds.data(), rematchExps.data(), rematchMods.data(), rematchIds.size(), true /* reduce */); if (!matcher) throw std::runtime_error("Could not build REmatch2 matcher."); context = rematch2ContextInit(matcher, aux.nmatch); if (context == nullptr) throw std::runtime_error("Could not initialize context."); // prepare data (only need the data specified in Test table) int lastPid = -1; vector<Test> tests = select<Test>(db).orderBy(Test::Patternid).all(); for (const auto& t : tests) { if (t.patternid.value() == lastPid) continue; lastPid = t.patternid.value(); // we can get excption below // (which should not happen with a db correctly set up) const auto& pattern = select<Pattern>(db, Pattern::Id == lastPid).one(); auto blob = pattern.content.value(); size_t len = blob.length(); auto temp = std::make_unique<char[]>(len); blob.getData(reinterpret_cast<unsigned char*>(temp.get()), len, 0); // for debugging // cout << "pattern " << lastPid << " content : " << string(temp.get(), len) // << endl; // set up Rule-id to (Test-id, result) mapping to be used for TestResult // update std::map<int, std::pair<int, bool>> rule2TestMap; auto curTest = select<Test>(db, Test::Patternid == lastPid).cursor(); for (; curTest.rowsLeft(); curTest++) { rule2TestMap[(*curTest).ruleid.value()] = std::make_pair((*curTest).id.value(), false); } // do match int ret = rematch2_exec(matcher, temp.get(), len, context); if (ret == MREG_FINISHED) { // this means we need to adjust 'nmatch' // parameter used for rematch2ContextInit cerr << "rematch2 returned MREG_FINISHED" << endl; } if (context->num_matches > 0) { // match // for debugging // cout << "pattern " << lastPid; // cout << " matched rules :" << endl; for (size_t i = 0; i < context->num_matches; ++i) { // for debugging // cout << " " << context->matchlist[i].fid; stateid_t mid = context->matchlist[i].fid; if (rule2TestMap.count(static_cast<int>(mid)) > 0) rule2TestMap[static_cast<int>(mid)].second = true; } // cout << endl; } else { // nomatch cout << "pattern " << lastPid << " has no match" << endl; } rematch2ContextClear(context, true); // for debugging // cout << "Matched rule and test id for pattern id " << lastPid << endl; // for (const auto& p : rule2TestMap) { // cout << " rule id " << p.first << " test id " << p.second.first // << " matched? " << p.second.second << endl; //} for (const auto& p : rule2TestMap) { try { auto cur = select<TestResult>(db, TestResult::Testid == p.second.first && TestResult::Engineid == engineId) .cursor(); (*cur).resultid = (p.second.second ? resMatchId : resNomatchId); (*cur).update(); } catch (NotFound) { TestResult res(db); res.testid = p.second.first; res.engineid = engineId; res.resultid = (p.second.second ? resMatchId : resNomatchId); res.update(); } } } // for loop for Test table entries // clean-up of REmatch related objects rematch2ContextFree(context); rematch2Free(matcher); } static int hsOnMatch(unsigned int, unsigned long long, unsigned long long, unsigned int, void* ctx) { size_t& nmatches = *static_cast<size_t*>(ctx); nmatches++; return 0; } void checkHyperscan(PcreCheckDb& db, struct AuxInfo& aux) { int engineId = aux.str2EngineId.at("hyperscan"); int resMatchId = aux.resMatchId; int resNomatchId = aux.resNomatchId; int resErrorId = aux.resErrorId; const auto& rules = aux.rules; hs_database_t* hsDb = nullptr; hs_scratch_t* hsScratch = nullptr; //hs_platform_info_t hsPlatform; hs_compile_error_t* hsErr = nullptr; auto cur = select<Test>(db).orderBy(Test::Ruleid).cursor(); if (!cur.rowsLeft()) // nothing to do return; // map of Test-id to Result-id std::map<int, int> test2ResMap; // Entering into this loop, please make sure that // rules and cur are all sorted w.r.t rule id // (only, cur can have multiple occurrences of rule id's) // and also rules be super set of the iteration cur points to // in terms of containing rule id's. // Below outer and inner loop is assuming the above constraints // to prevent multiple rule compile for a same rule for (const auto& rule : rules) { if (!cur.rowsLeft()) break; if (rule.getID() != (*cur).ruleid.value()) continue; unsigned flag = HS_FLAG_ALLOWEMPTY; if (rule.isSet(regexbench::MOD_CASELESS)) flag |= HS_FLAG_CASELESS; if (rule.isSet(regexbench::MOD_MULTILINE)) flag |= HS_FLAG_MULTILINE; if (rule.isSet(regexbench::MOD_DOTALL)) flag |= HS_FLAG_DOTALL; hsDb = nullptr; hsScratch = nullptr; hsErr = nullptr; auto resCompile = hs_compile(rule.getRegexp().data(), flag, HS_MODE_BLOCK, nullptr, &hsDb, &hsErr); if (resCompile == HS_SUCCESS) { auto resAlloc = hs_alloc_scratch(hsDb, &hsScratch); if (resAlloc != HS_SUCCESS) { hs_free_database(hsDb); throw std::bad_alloc(); } } else hs_free_compile_error(hsErr); for (; cur.rowsLeft() && rule.getID() == (*cur).ruleid.value(); cur++) { if (resCompile != HS_SUCCESS) { test2ResMap[(*cur).id.value()] = resErrorId; continue; } const auto& pattern = select<Pattern>(db, Pattern::Id == (*cur).patternid).one(); auto blob = pattern.content.value(); size_t len = blob.length(); auto temp = std::make_unique<char[]>(len); blob.getData(reinterpret_cast<unsigned char*>(temp.get()), len, 0); size_t nmatches = 0; hs_scan(hsDb, temp.get(), static_cast<unsigned>(len), 0, hsScratch, hsOnMatch, &nmatches); if (nmatches) test2ResMap[(*cur).id.value()] = (nmatches > 0) ? resMatchId : resNomatchId; } hs_free_scratch(hsScratch); hs_free_database(hsDb); } //cout << "Hyper scan result" << endl << endl; for (const auto& p : test2ResMap) { try { auto curT = select<TestResult>(db, TestResult::Testid == p.first && TestResult::Engineid == engineId) .cursor(); (*curT).resultid = p.second; (*curT).update(); } catch (NotFound) { TestResult res(db); res.testid = p.first; res.engineid = engineId; res.resultid = p.second; res.update(); } // for debugging //const auto& test = select<Test>(db, Test::Id == p.first).one(); //cout << "test " << test.id.value() << " (rule id " << test.ruleid.value() // << ", pattern id " << test.patternid.value() // << ") => result : " << p.second << endl; } } <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "EC_DynamicComponent.h" #include "IModule.h" #include "ModuleManager.h" #include "Entity.h" #include "LoggingFunctions.h" #include <QScriptEngine> #include <QScriptValueIterator> DEFINE_POCO_LOGGING_FUNCTIONS("EC_DynamicComponent") #include <QDomDocument> namespace { struct DeserializeData { DeserializeData(const std::string name = std::string(""), const std::string type = std::string(""), const std::string value = std::string("")): name_(name), type_(type), value_(value) { } //! Checks if any of data structure's values are null. bool isNull() const { return name_ == "" || type_ == "" || value_ == ""; } std::string name_; std::string type_; std::string value_; }; //! Function that is used by std::sort algorithm to sort attributes by their name. bool CmpAttributeByName(const IAttribute *a, const IAttribute *b) { return a->GetNameString() < b->GetNameString(); } //! Function that is used by std::sort algorithm to sort DeserializeData by their name. bool CmpAttributeDataByName(const DeserializeData &a, const DeserializeData &b) { return a.name_ < b.name_; } } EC_DynamicComponent::EC_DynamicComponent(IModule *module): IComponent(module->GetFramework()) { } EC_DynamicComponent::~EC_DynamicComponent() { foreach(IAttribute *a, attributes_) SAFE_DELETE(a); } void EC_DynamicComponent::SerializeTo(QDomDocument& doc, QDomElement& base_element) const { QDomElement comp_element = BeginSerialization(doc, base_element); AttributeVector::const_iterator iter = attributes_.begin(); while(iter != attributes_.end()) { WriteAttribute(doc, comp_element, (*iter)->GetNameString().c_str(), (*iter)->ToString().c_str(), (*iter)->TypenameToString().c_str()); iter++; } } void EC_DynamicComponent::DeserializeFrom(QDomElement& element, AttributeChange::Type change) { if (!BeginDeserialization(element)) return; std::vector<DeserializeData> deserializedAttributes; QDomElement child = element.firstChildElement("attribute"); while(!child.isNull()) { QString name = child.attribute("name"); QString type = child.attribute("type"); QString value = child.attribute("value"); DeserializeData attributeData(name.toStdString(), type.toStdString(), value.toStdString()); deserializedAttributes.push_back(attributeData); child = child.nextSiblingElement("attribute"); } // Sort both lists in alphabetical order. AttributeVector oldAttributes = attributes_; std::stable_sort(oldAttributes.begin(), oldAttributes.end(), &CmpAttributeByName); std::stable_sort(deserializedAttributes.begin(), deserializedAttributes.end(), &CmpAttributeDataByName); std::vector<DeserializeData> addAttributes; std::vector<DeserializeData> remAttributes; AttributeVector::iterator iter1 = oldAttributes.begin(); std::vector<DeserializeData>::iterator iter2 = deserializedAttributes.begin(); // Check what attributes we need to add or remove from the dynamic component (done by comparing two list differences). while(iter1 != oldAttributes.end() || iter2 != deserializedAttributes.end()) { // No point to continue the iteration if other list is empty. We can just push all new attributes into the dynamic component. if(iter1 == oldAttributes.end()) { for(;iter2 != deserializedAttributes.end(); iter2++) { addAttributes.push_back(*iter2); } break; } // Only old attributes are left and they can be removed from the dynamic component. else if(iter2 == deserializedAttributes.end()) { for(;iter1 != oldAttributes.end(); iter1++) remAttributes.push_back(DeserializeData((*iter1)->GetNameString().c_str())); break; } // Attribute has already created and we only need to update it's value. if((*iter1)->GetNameString() == (*iter2).name_) { SetAttribute(QString::fromStdString(iter2->name_), QString::fromStdString(iter2->value_), change); iter2++; iter1++; } // Found a new attribute that need to be created and added to the component. else if((*iter1)->GetNameString() > (*iter2).name_) { addAttributes.push_back(*iter2); iter2++; } // Couldn't find the attribute in a new list so it need to be removed from the component. else { remAttributes.push_back(DeserializeData((*iter1)->GetNameString().c_str())); iter1++; } } while(!addAttributes.empty()) { DeserializeData attributeData = addAttributes.back(); IAttribute *attribute = CreateAttribute(attributeData.type_.c_str(), attributeData.name_.c_str()); if (attribute) attribute->FromString(attributeData.value_, change); addAttributes.pop_back(); } while(!remAttributes.empty()) { DeserializeData attributeData = remAttributes.back(); RemoveAttribute(QString::fromStdString(attributeData.name_)); remAttributes.pop_back(); } } IAttribute *EC_DynamicComponent::CreateAttribute(const QString &typeName, const QString &name, AttributeChange::Type change) { IAttribute *attribute = 0; if(ContainsAttribute(name)) return attribute; attribute = framework_->GetComponentManager()->CreateAttribute(this, typeName.toStdString(), name.toStdString()); if(attribute) emit AttributeAdded(name); AttributeChanged(attribute, change); return attribute; } void EC_DynamicComponent::RemoveAttribute(const QString &name, AttributeChange::Type change) { for(AttributeVector::iterator iter = attributes_.begin(); iter != attributes_.end(); iter++) { if((*iter)->GetNameString() == name.toStdString()) { //! /todo Make sure that component removal is replicated to the server if change type is Replicate. AttributeChanged(*iter, change); SAFE_DELETE(*iter); attributes_.erase(iter); emit AttributeRemoved(name); break; } } } void EC_DynamicComponent::AddQVariantAttribute(const QString &name, AttributeChange::Type change) { //Check if the attribute has already been created. if(!ContainsAttribute(name)) { Attribute<QVariant> *attribute = new Attribute<QVariant>(this, name.toStdString().c_str()); AttributeChanged(attribute, change); emit AttributeAdded(name); } LogWarning("Failed to add a new QVariant in name of " + name.toStdString() + ", cause there already is an attribute in that name."); } QVariant EC_DynamicComponent::GetAttribute(int index) const { if(index < attributes_.size() && index >= 0) { return attributes_[index]->ToQVariant(); } return QVariant(); } QVariant EC_DynamicComponent::GetAttribute(const QString &name) const { for(AttributeVector::const_iterator iter = attributes_.begin(); iter != attributes_.end(); ++iter) if ((*iter)->GetNameString() == name.toStdString()) return (*iter)->ToQVariant(); return QVariant(); } void EC_DynamicComponent::SetAttribute(int index, const QVariant &value, AttributeChange::Type change) { if(index < attributes_.size() && index >= 0) { attributes_[index]->FromQVariant(value, change); } LogWarning("Cannot get attribute name, cause index is out of range."); } void EC_DynamicComponent::SetAttributeQScript(const QString &name, const QScriptValue &value, AttributeChange::Type change) { for(AttributeVector::const_iterator iter = attributes_.begin(); iter != attributes_.end(); iter++) { if((*iter)->GetNameString() == name.toStdString()) { (*iter)->FromScriptValue(value, change); break; } } } void EC_DynamicComponent::SetAttribute(const QString &name, const QVariant &value, AttributeChange::Type change) { for(AttributeVector::const_iterator iter = attributes_.begin(); iter != attributes_.end(); iter++) { if((*iter)->GetNameString() == name.toStdString()) { (*iter)->FromQVariant(value, change); break; } } } QString EC_DynamicComponent::GetAttributeName(int index) const { if(index < attributes_.size() && index >= 0) { return attributes_[index]->GetName(); } LogWarning("Cannot get attribute name, cause index is out of range."); return QString(); } bool EC_DynamicComponent::ContainSameAttributes(const EC_DynamicComponent &comp) const { AttributeVector myAttributeVector = GetAttributes(); AttributeVector attributeVector = comp.GetAttributes(); if(attributeVector.size() != myAttributeVector.size()) return false; if(attributeVector.empty() && myAttributeVector.empty()) return true; std::sort(myAttributeVector.begin(), myAttributeVector.end(), &CmpAttributeByName); std::sort(attributeVector.begin(), attributeVector.end(), &CmpAttributeByName); AttributeVector::const_iterator iter1 = myAttributeVector.begin(); AttributeVector::const_iterator iter2 = attributeVector.begin(); while(iter1 != myAttributeVector.end() && iter2 != attributeVector.end()) { // Compare attribute names and type and if they mach continue iteration if not components aren't exatly the same. if((*iter1)->GetNameString() == (*iter2)->GetNameString() && (*iter1)->TypenameToString() == (*iter2)->TypenameToString()) { if(iter1 != myAttributeVector.end()) iter1++; if(iter2 != attributeVector.end()) iter2++; } else { return false; } } return true; /*// Get both attributes and check if they are holding exact number of attributes. AttributeVector myAttributeVector = GetAttributes(); AttributeVector attributeVector = comp.GetAttributes(); if(attributeVector.size() != myAttributeVector.size()) return false; // Compare that every attribute is same in both components. QSet<IAttribute*> myAttributeSet; QSet<IAttribute*> attributeSet; for(uint i = 0; i < myAttributeSet.size(); i++) { attributeSet.insert(myAttributeVector[i]); myAttributeSet.insert(attributeVector[i]); } if(attributeSet != myAttributeSet) return false; return true;*/ } bool EC_DynamicComponent::ContainsAttribute(const QString &name) const { AttributeVector::const_iterator iter = attributes_.begin(); while(iter != attributes_.end()) { if((*iter)->GetName() == name.toStdString()) { return true; } iter++; } return false; } <commit_msg>Fixed issue that caused deserialize code to fail in EC_DynamicComponent.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "EC_DynamicComponent.h" #include "IModule.h" #include "ModuleManager.h" #include "Entity.h" #include "LoggingFunctions.h" #include <QScriptEngine> #include <QScriptValueIterator> DEFINE_POCO_LOGGING_FUNCTIONS("EC_DynamicComponent") #include <QDomDocument> namespace { struct DeserializeData { DeserializeData(const std::string name = std::string(""), const std::string type = std::string(""), const std::string value = std::string("")): name_(name), type_(type), value_(value) { } //! Checks if any of data structure's values are null. bool isNull() const { return name_ == "" || type_ == "" || value_ == ""; } std::string name_; std::string type_; std::string value_; }; //! Function that is used by std::sort algorithm to sort attributes by their name. bool CmpAttributeByName(const IAttribute *a, const IAttribute *b) { return a->GetNameString() < b->GetNameString(); } //! Function that is used by std::sort algorithm to sort DeserializeData by their name. bool CmpAttributeDataByName(const DeserializeData &a, const DeserializeData &b) { return a.name_ < b.name_; } } EC_DynamicComponent::EC_DynamicComponent(IModule *module): IComponent(module->GetFramework()) { } EC_DynamicComponent::~EC_DynamicComponent() { foreach(IAttribute *a, attributes_) SAFE_DELETE(a); } void EC_DynamicComponent::SerializeTo(QDomDocument& doc, QDomElement& base_element) const { QDomElement comp_element = BeginSerialization(doc, base_element); AttributeVector::const_iterator iter = attributes_.begin(); while(iter != attributes_.end()) { WriteAttribute(doc, comp_element, (*iter)->GetNameString().c_str(), (*iter)->ToString().c_str(), (*iter)->TypenameToString().c_str()); iter++; } } void EC_DynamicComponent::DeserializeFrom(QDomElement& element, AttributeChange::Type change) { if (!BeginDeserialization(element)) return; std::vector<DeserializeData> deserializedAttributes; QDomElement child = element.firstChildElement("attribute"); while(!child.isNull()) { QString name = child.attribute("name"); QString type = child.attribute("type"); QString value = child.attribute("value"); DeserializeData attributeData(name.toStdString(), type.toStdString(), value.toStdString()); deserializedAttributes.push_back(attributeData); child = child.nextSiblingElement("attribute"); } // Sort both lists in alphabetical order. AttributeVector oldAttributes = attributes_; std::stable_sort(oldAttributes.begin(), oldAttributes.end(), &CmpAttributeByName); std::stable_sort(deserializedAttributes.begin(), deserializedAttributes.end(), &CmpAttributeDataByName); std::vector<DeserializeData> addAttributes; std::vector<DeserializeData> remAttributes; AttributeVector::iterator iter1 = oldAttributes.begin(); std::vector<DeserializeData>::iterator iter2 = deserializedAttributes.begin(); // Check what attributes we need to add or remove from the dynamic component (done by comparing two list differences). while(iter1 != oldAttributes.end() || iter2 != deserializedAttributes.end()) { // No point to continue the iteration if other list is empty. We can just push all new attributes into the dynamic component. if(iter1 == oldAttributes.end()) { for(;iter2 != deserializedAttributes.end(); iter2++) { addAttributes.push_back(*iter2); } break; } // Only old attributes are left and they can be removed from the dynamic component. else if(iter2 == deserializedAttributes.end()) { for(;iter1 != oldAttributes.end(); iter1++) remAttributes.push_back(DeserializeData((*iter1)->GetNameString().c_str())); break; } // Attribute has already created and we only need to update it's value. if((*iter1)->GetNameString() == (*iter2).name_) { //SetAttribute(QString::fromStdString(iter2->name_), QString::fromStdString(iter2->value_), change); for(AttributeVector::const_iterator attr_iter = attributes_.begin(); attr_iter != attributes_.end(); attr_iter++) { if((*attr_iter)->GetNameString() == iter2->name_) { (*attr_iter)->FromString(iter2->value_, change); } } iter2++; iter1++; } // Found a new attribute that need to be created and added to the component. else if((*iter1)->GetNameString() > (*iter2).name_) { addAttributes.push_back(*iter2); iter2++; } // Couldn't find the attribute in a new list so it need to be removed from the component. else { remAttributes.push_back(DeserializeData((*iter1)->GetNameString().c_str())); iter1++; } } while(!addAttributes.empty()) { DeserializeData attributeData = addAttributes.back(); IAttribute *attribute = CreateAttribute(attributeData.type_.c_str(), attributeData.name_.c_str()); if (attribute) attribute->FromString(attributeData.value_, change); addAttributes.pop_back(); } while(!remAttributes.empty()) { DeserializeData attributeData = remAttributes.back(); RemoveAttribute(QString::fromStdString(attributeData.name_)); remAttributes.pop_back(); } } IAttribute *EC_DynamicComponent::CreateAttribute(const QString &typeName, const QString &name, AttributeChange::Type change) { IAttribute *attribute = 0; if(ContainsAttribute(name)) return attribute; attribute = framework_->GetComponentManager()->CreateAttribute(this, typeName.toStdString(), name.toStdString()); if(attribute) emit AttributeAdded(name); AttributeChanged(attribute, change); return attribute; } void EC_DynamicComponent::RemoveAttribute(const QString &name, AttributeChange::Type change) { for(AttributeVector::iterator iter = attributes_.begin(); iter != attributes_.end(); iter++) { if((*iter)->GetNameString() == name.toStdString()) { //! /todo Make sure that component removal is replicated to the server if change type is Replicate. AttributeChanged(*iter, change); SAFE_DELETE(*iter); attributes_.erase(iter); emit AttributeRemoved(name); break; } } } void EC_DynamicComponent::AddQVariantAttribute(const QString &name, AttributeChange::Type change) { //Check if the attribute has already been created. if(!ContainsAttribute(name)) { Attribute<QVariant> *attribute = new Attribute<QVariant>(this, name.toStdString().c_str()); AttributeChanged(attribute, change); emit AttributeAdded(name); } LogWarning("Failed to add a new QVariant in name of " + name.toStdString() + ", cause there already is an attribute in that name."); } QVariant EC_DynamicComponent::GetAttribute(int index) const { if(index < attributes_.size() && index >= 0) { return attributes_[index]->ToQVariant(); } return QVariant(); } QVariant EC_DynamicComponent::GetAttribute(const QString &name) const { for(AttributeVector::const_iterator iter = attributes_.begin(); iter != attributes_.end(); ++iter) if ((*iter)->GetNameString() == name.toStdString()) return (*iter)->ToQVariant(); return QVariant(); } void EC_DynamicComponent::SetAttribute(int index, const QVariant &value, AttributeChange::Type change) { if(index < attributes_.size() && index >= 0) { attributes_[index]->FromQVariant(value, change); } LogWarning("Cannot get attribute name, cause index is out of range."); } void EC_DynamicComponent::SetAttributeQScript(const QString &name, const QScriptValue &value, AttributeChange::Type change) { for(AttributeVector::const_iterator iter = attributes_.begin(); iter != attributes_.end(); iter++) { if((*iter)->GetNameString() == name.toStdString()) { (*iter)->FromScriptValue(value, change); break; } } } void EC_DynamicComponent::SetAttribute(const QString &name, const QVariant &value, AttributeChange::Type change) { for(AttributeVector::const_iterator iter = attributes_.begin(); iter != attributes_.end(); iter++) { if((*iter)->GetNameString() == name.toStdString()) { (*iter)->FromQVariant(value, change); break; } } } QString EC_DynamicComponent::GetAttributeName(int index) const { if(index < attributes_.size() && index >= 0) { return attributes_[index]->GetName(); } LogWarning("Cannot get attribute name, cause index is out of range."); return QString(); } bool EC_DynamicComponent::ContainSameAttributes(const EC_DynamicComponent &comp) const { AttributeVector myAttributeVector = GetAttributes(); AttributeVector attributeVector = comp.GetAttributes(); if(attributeVector.size() != myAttributeVector.size()) return false; if(attributeVector.empty() && myAttributeVector.empty()) return true; std::sort(myAttributeVector.begin(), myAttributeVector.end(), &CmpAttributeByName); std::sort(attributeVector.begin(), attributeVector.end(), &CmpAttributeByName); AttributeVector::const_iterator iter1 = myAttributeVector.begin(); AttributeVector::const_iterator iter2 = attributeVector.begin(); while(iter1 != myAttributeVector.end() && iter2 != attributeVector.end()) { // Compare attribute names and type and if they mach continue iteration if not components aren't exatly the same. if((*iter1)->GetNameString() == (*iter2)->GetNameString() && (*iter1)->TypenameToString() == (*iter2)->TypenameToString()) { if(iter1 != myAttributeVector.end()) iter1++; if(iter2 != attributeVector.end()) iter2++; } else { return false; } } return true; /*// Get both attributes and check if they are holding exact number of attributes. AttributeVector myAttributeVector = GetAttributes(); AttributeVector attributeVector = comp.GetAttributes(); if(attributeVector.size() != myAttributeVector.size()) return false; // Compare that every attribute is same in both components. QSet<IAttribute*> myAttributeSet; QSet<IAttribute*> attributeSet; for(uint i = 0; i < myAttributeSet.size(); i++) { attributeSet.insert(myAttributeVector[i]); myAttributeSet.insert(attributeVector[i]); } if(attributeSet != myAttributeSet) return false; return true;*/ } bool EC_DynamicComponent::ContainsAttribute(const QString &name) const { AttributeVector::const_iterator iter = attributes_.begin(); while(iter != attributes_.end()) { if((*iter)->GetName() == name.toStdString()) { return true; } iter++; } return false; } <|endoftext|>
<commit_before>/* ttn_base_netjoin.cpp Tue Nov 1 2016 06:19:25 tmm */ /* Module: ttn_base_netjoin.cpp Function: Arduino_LoRaWAN_ttn_base::NetJoin() Version: V0.2.0 Tue Nov 1 2016 06:19:25 tmm Edit level 1 Copyright notice: This file copyright (C) 2016 by MCCI Corporation 3520 Krums Corners Road Ithaca, NY 14850 An unpublished work. All rights reserved. This file is proprietary information, and may not be disclosed or copied without the prior permission of MCCI Corporation. Author: Terry Moore, MCCI Corporation November 2016 Revision history: 0.2.0 Tue Nov 1 2016 06:19:25 tmm Module created. */ #include <Arduino_LoRaWAN_ttn.h> #include <Arduino_LoRaWAN_lmic.h> /****************************************************************************\ | | Manifest constants & typedefs. | \****************************************************************************/ /****************************************************************************\ | | Read-only data. | \****************************************************************************/ /****************************************************************************\ | | VARIABLES: | \****************************************************************************/ void Arduino_LoRaWAN_ttn_base::NetJoin() { LMIC_setLinkCheckMode(0); } <commit_msg>Fix #5: don't disable link-check-mode by default<commit_after>/* ttn_base_netjoin.cpp Tue Nov 1 2016 06:19:25 tmm */ /* Module: ttn_base_netjoin.cpp Function: Arduino_LoRaWAN_ttn_base::NetJoin() Version: V0.2.0 Tue Nov 1 2016 06:19:25 tmm Edit level 1 Copyright notice: This file copyright (C) 2016 by MCCI Corporation 3520 Krums Corners Road Ithaca, NY 14850 An unpublished work. All rights reserved. This file is proprietary information, and may not be disclosed or copied without the prior permission of MCCI Corporation. Author: Terry Moore, MCCI Corporation November 2016 Revision history: 0.2.0 Tue Nov 1 2016 06:19:25 tmm Module created. */ #include <Arduino_LoRaWAN_ttn.h> #include <Arduino_LoRaWAN_lmic.h> /****************************************************************************\ | | Manifest constants & typedefs. | \****************************************************************************/ /****************************************************************************\ | | Read-only data. | \****************************************************************************/ /****************************************************************************\ | | VARIABLES: | \****************************************************************************/ void Arduino_LoRaWAN_ttn_base::NetJoin() { // we don't want to disable link-check mode on // current TTN networks with the current LMIC. // LMIC_setLinkCheckMode(0); } <|endoftext|>